diff --git a/.changeset/37444-first-screen-studio-catalogue.md b/.changeset/37444-first-screen-studio-catalogue.md new file mode 100644 index 00000000000..95278d219ae --- /dev/null +++ b/.changeset/37444-first-screen-studio-catalogue.md @@ -0,0 +1,14 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@objectstack/console': patch +--- + +perf(console): an object list and a record page no longer load the Studio designer's string table on first paint + +Clause-②: no +Metadata-protocol: none + +Opening an object list or a record page downloaded the Studio designer's English string table (about 69 KB gzipped) and the designer's header and Customize controls with it, before the page could paint, for every user, designer or not. The running app's save paths that load with those pages (a list's view save, the record page's tabs and arrangement saves, the header-pin save) read small pure helpers that lived inside the designer's component modules, and importing a helper loaded the whole module. + +Those helpers now live in modules of their own, so each page's first load is about 94 KB gzipped lighter on the Console build this was measured on. Nothing changes in what the pages show or save: every name is still exported from where it was, and the designer loads its string table when it opens, as before. diff --git a/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts b/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts index 8c148c27ddd..76cca8c1fa3 100644 --- a/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts +++ b/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts @@ -49,7 +49,7 @@ import type { ObjectActionLayout } from '@objectstack/spec/data'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; -import { isDraftVersionConflict } from '../views/metadata-admin/DraftConflictDialog.js'; +import { isDraftVersionConflict } from '../views/metadata-admin/draftVersionGuard.js'; import { authoredPublished, type AuthoredLayers } from '../views/metadata-admin/authoredObjectBuffer.js'; import { saveObjectExtensionArrangement } from '../views/objectExtensionArrangementSave.js'; import { diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts index df6cbd13ae4..e91b084eb7b 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -75,8 +75,8 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; -import { isDraftVersionConflict, publishedPinOf, type DraftPin } from '../views/metadata-admin/DraftConflictDialog.js'; -import { overrideDraftBody } from '../views/studio-design/StudioCustomizeControls.js'; +import { isDraftVersionConflict, publishedPinOf, type DraftPin } from '../views/metadata-admin/draftVersionGuard.js'; +import { overrideDraftBody } from '../views/studio-design/customizeOverride.js'; import { ensureCustomizationPackage, fetchListedPackageManifests, diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx index b759367524d..b4bfb78a4f8 100644 --- a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx @@ -79,7 +79,7 @@ vi.mock('./studio-design/packages-io', async (importOriginal) => ({ return packages.ensure!(base); }, })); -vi.mock('./studio-design/StudioCustomizeControls', async (importOriginal) => ({ +vi.mock('./studio-design/customizeOverride', async (importOriginal) => ({ ...(await importOriginal>()), useCustomizeDoorWalled: () => gate.walled, })); diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx index dc6abc492d8..bded558ac23 100644 --- a/ui/packages/app-shell/src/views/DashboardView.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.tsx @@ -52,7 +52,7 @@ import { } from './DashboardInPageEditor.js'; import { StudioReturnButton, useStudioReturnPath } from './StudioReturnButton.js'; import { useInSetupApp } from '../console/setupApp.js'; -import { useCustomizeDoorWalled } from './studio-design/StudioCustomizeControls.js'; +import { useCustomizeDoorWalled } from './studio-design/customizeOverride.js'; import { readDashboardEditArrival, withoutDashboardEditArrival } from '../layout/designModeArrival.js'; /** diff --git a/ui/packages/app-shell/src/views/RecordTabsConfig.tsx b/ui/packages/app-shell/src/views/RecordTabsConfig.tsx index 88ad2bd06ac..445800fb858 100644 --- a/ui/packages/app-shell/src/views/RecordTabsConfig.tsx +++ b/ui/packages/app-shell/src/views/RecordTabsConfig.tsx @@ -65,7 +65,7 @@ import { useObjectTranslation } from '@object-ui/i18n'; import { isRecordPageBuiltinTab, readRelatedListsArrangement, relatedListEntryName } from '@objectstack/spec/data'; import { useDesignMode, useDesignModeActive, useDesignModeChange } from '../layout/designMode.js'; import { useStudioDesignGate, useStudioEntryGate } from '../hooks/useStudioDesignGate.js'; -import { useCustomizeDoorWalled } from './studio-design/StudioCustomizeControls.js'; +import { useCustomizeDoorWalled } from './studio-design/customizeOverride.js'; import { relatedListEntryNames, type DerivedRelatedList } from '../utils/deriveRelatedLists.js'; import { studioItemPath } from './studio-design/studioAddress.js'; import { entryDetails } from './studio-design/relatedListVocabulary.js'; diff --git a/ui/packages/app-shell/src/views/ReportView.shippedReportSave-36716.test.tsx b/ui/packages/app-shell/src/views/ReportView.shippedReportSave-36716.test.tsx index 6ca02405a62..dbb0967a1dd 100644 --- a/ui/packages/app-shell/src/views/ReportView.shippedReportSave-36716.test.tsx +++ b/ui/packages/app-shell/src/views/ReportView.shippedReportSave-36716.test.tsx @@ -73,7 +73,7 @@ vi.mock('./studio-design/packages-io', async (importOriginal) => ({ ensureCustomizationPackage: vi.fn((base: string) => doors.ensure(base)), })); const walled = vi.hoisted(() => ({ value: false })); -vi.mock('./studio-design/StudioCustomizeControls', async (importOriginal) => ({ +vi.mock('./studio-design/customizeOverride', async (importOriginal) => ({ ...(await importOriginal>()), useCustomizeDoorWalled: () => walled.value, })); diff --git a/ui/packages/app-shell/src/views/ReportView.tsx b/ui/packages/app-shell/src/views/ReportView.tsx index 007deccc127..46bddc5a46f 100644 --- a/ui/packages/app-shell/src/views/ReportView.tsx +++ b/ui/packages/app-shell/src/views/ReportView.tsx @@ -30,7 +30,7 @@ import { saveInPlace, type InPlaceEditTarget, } from './runtime-metadata-persistence.js'; -import { useCustomizeDoorWalled } from './studio-design/StudioCustomizeControls.js'; +import { useCustomizeDoorWalled } from './studio-design/customizeOverride.js'; import { authoredBuffer, extractDraftBody, formatMetadataError, type AuthoredLayers } from '@object-ui/data-objectstack'; import { t as tStudio, tFormat, useMetadataLocale } from './metadata-admin/i18n.js'; import { servedPackageId } from '@object-ui/core'; diff --git a/ui/packages/app-shell/src/views/__tests__/RecordTabsConfigInstalled-36499.test.tsx b/ui/packages/app-shell/src/views/__tests__/RecordTabsConfigInstalled-36499.test.tsx index a8b7e66d0b9..a2073cd210e 100644 --- a/ui/packages/app-shell/src/views/__tests__/RecordTabsConfigInstalled-36499.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/RecordTabsConfigInstalled-36499.test.tsx @@ -57,7 +57,7 @@ vi.mock('../../hooks/useStudioDesignGate', async (importOriginal) => ({ useStudioEntryGate: (path: string | null) => (session.view && path ? { path, posture: 'view' } : null), })); -vi.mock('../studio-design/StudioCustomizeControls', async (importOriginal) => ({ +vi.mock('../studio-design/customizeOverride', async (importOriginal) => ({ ...(await importOriginal>()), useCustomizeDoorWalled: () => session.walled, })); diff --git a/ui/packages/app-shell/src/views/__tests__/firstScreenStudioCatalogue-37444.test.ts b/ui/packages/app-shell/src/views/__tests__/firstScreenStudioCatalogue-37444.test.ts new file mode 100644 index 00000000000..9990e5e8a4e --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/firstScreenStudioCatalogue-37444.test.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37444 — a list or record page's first load does not carry the + * Studio designer's string table. + * + * The running app's save paths (a list's view save, the record page's tabs and + * arrangement saves, the header-pin save) load with a list or record page. They read pure helpers — the override draft body, the + * object-extension body, the draft-version guard — which used to live in + * component modules (`StudioCustomizeControls.tsx`, `DraftConflictDialog.tsx`) + * that import the designer's `t()` (`metadata-admin/i18n.ts`) and through it + * the `studio` namespace's English catalogue, statically. Measured on the + * Console build of `021524cd`, that put about 94 KB gzipped on both pages' + * first load. The helpers now live in `customizeOverride.ts` and + * `draftVersionGuard.ts`. + * + * This walks each save path's STATIC relative imports in source (type-only + * imports and `import()` excluded, as the browser loads them) and asserts the + * walk never reaches the designer's string table. The walk is checked to see + * the edge it guards: `DraftConflictDialog.tsx` itself must reach it. + */ +import { readFileSync, existsSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const SRC = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); + +/** The designer string table, by file and by package specifier. */ +const DESIGNER_I18N_FILE = resolve(SRC, 'views/metadata-admin/i18n.ts'); +const DESIGNER_I18N_SPECIFIER = /^@object-ui\/i18n\/namespaces\/studio$/; + +/** + * The save paths a list or record page loads with (read off the Console + * build's static closure of `ObjectView` and `RecordDetailView`). The + * design-mode menu save is not one: it loads with design mode, and it still + * reads the app-nav canvas, which translates. + */ +const SAVE_PATHS = [ + 'views/runtime-metadata-persistence.ts', + 'views/recordTabsConfigSave.ts', + 'views/objectExtensionArrangementSave.ts', + 'layout/designModeHeaderPinsSave.ts', +]; + +/** Static value imports of one module: `import … from '…'` and `export … from '…'`, never `import type`. */ +function staticSpecifiers(code: string): string[] { + const out: string[] = []; + const re = /^\s*(import|export)\s+(?!type\s)([^;]*?\bfrom\s+)?['"]([^'"]+)['"]/gm; + for (const m of code.matchAll(re)) { + if (m[1] === 'export' && !m[2]) continue; + out.push(m[3]); + } + return out; +} + +function resolveRelative(from: string, specifier: string): string | null { + const base = resolve(dirname(from), specifier.replace(/\.js$/, '')); + for (const candidate of [`${base}.ts`, `${base}.tsx`, resolve(base, 'index.ts'), resolve(base, 'index.tsx')]) { + if (existsSync(candidate)) return candidate; + } + return null; +} + +/** The first chain from `entry` to the designer string table, or `null`. */ +function chainToDesignerI18n(entry: string): string[] | null { + const start = resolve(SRC, entry); + const prev = new Map([[start, null]]); + const queue = [start]; + while (queue.length) { + const file = queue.shift() as string; + for (const specifier of staticSpecifiers(readFileSync(file, 'utf8'))) { + if (DESIGNER_I18N_SPECIFIER.test(specifier)) { + const chain = [specifier]; + for (let at: string | null = file; at; at = prev.get(at) ?? null) chain.unshift(at.slice(SRC.length + 1)); + return chain; + } + if (!specifier.startsWith('.')) continue; + const next = resolveRelative(file, specifier); + if (!next || prev.has(next)) continue; + prev.set(next, file); + if (next === DESIGNER_I18N_FILE) { + const chain: string[] = []; + for (let at: string | null = next; at; at = prev.get(at) ?? null) chain.unshift(at.slice(SRC.length + 1)); + return chain; + } + queue.push(next); + } + } + return null; +} + +describe('a list or record page first load carries no Studio designer string table (objectstack#37444)', () => { + it('the walk sees the edge it guards: the conflict dialog reaches the designer table', () => { + expect(chainToDesignerI18n('views/metadata-admin/DraftConflictDialog.tsx')).not.toBeNull(); + expect(chainToDesignerI18n('views/studio-design/StudioCustomizeControls.tsx')).not.toBeNull(); + }); + + it.each(SAVE_PATHS)('%s reaches no designer string table through static imports', (entry) => { + expect(chainToDesignerI18n(entry)).toBeNull(); + }); + + it('the pure halves import no component module and no string table', () => { + for (const entry of ['views/studio-design/customizeOverride.ts', 'views/metadata-admin/draftVersionGuard.ts']) { + expect(chainToDesignerI18n(entry)).toBeNull(); + expect(staticSpecifiers(readFileSync(resolve(SRC, entry), 'utf8'))).not.toContain('@object-ui/components'); + } + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx index 224040edb9f..84c84bb4356 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx @@ -116,466 +116,28 @@ import { buttonVariants, cn, } from '@object-ui/components'; -import type { MetadataClient, MetadataClientSaveOptions } from '@object-ui/data-objectstack'; -import { GetMetaItemLayeredResponseSchema, GetMetaItemResponseSchema, MetadataConflictErrorSchema } from '@objectstack/spec/api'; -import { errorCodeIs } from '@object-ui/types'; +import type { MetadataClient } from '@object-ui/data-objectstack'; import { t, tFormat, translateMetadataType, useMetadataLocale } from './i18n.js'; -/** - * objectstack#36726 — what a publish conflict's `beforeReload` left at the - * item: `'discarded'`, the draft the Save wrote was taken back, so the reload - * re-reads the live row; `'kept'`, a draft pending before the Save stays (it - * carries the page's edits), so the reload re-reads that draft (rule 9). - */ -export type BeforeReloadOutcome = 'discarded' | 'kept'; - -/** What a guarded save ended in, when it did not throw. */ -export type DraftSaveOutcome = 'saved' | 'reloaded'; - -/** The author's answer to a conflict. */ -export type DraftConflictChoice = 'reload' | 'overwrite' | 'cancel'; - -/** The item a refused save addressed. */ -export interface DraftConflict { - type: string; - name: string; - /** - * objectstack#36601 — which layer moved: the draft (the draft save was - * refused, the default) or the published row (the Save's publish was). - */ - layer?: 'draft' | 'published'; -} - -const KEPT_EDITING = new WeakSet(); - -/** - * objectstack#36601 — `err` is the "not saved" error the guarded publish - * throws when the author, asked about a published row that moved, chose to - * keep editing: no request failed, so the caller shows it as the draft - * conflict's own "not saved" line, never as a refused publish. - */ -export function isPublishConflictKeptEditing(err: unknown): boolean { - return typeof err === 'object' && err !== null && KEPT_EDITING.has(err); -} - -/** - * The version-conflict refusal of the `/meta` draft door, told apart from the - * door's OTHER 409 (`DESTRUCTIVE_CHANGE`) by its code, never by its prose. - */ -export function isDraftVersionConflict(err: unknown): boolean { - return (err as { status?: unknown } | null | undefined)?.status === 409 && errorCodeIs(err, 'METADATA_CONFLICT'); -} - -/** - * The precondition a guarded draft save is sent with: exactly one of the two - * headers, by construction never both. - */ -export type DraftPin = { readonly ifMatch: string } | { readonly ifNoneMatch: '*' }; - -/** - * A served `version` — a token, or `null` for "no row at this address" — as the - * pin a save to that address sends. An empty token pins nothing: the client - * sends no `If-Match` for it. - */ -function pinOfVersion(version: string | null): DraftPin | null { - if (version === null) return { ifNoneMatch: '*' }; - return version.length > 0 ? { ifMatch: version } : null; -} - -/** - * What a load's DRAFT read (`MetadataClient.getDraft`, at the address the - * buffer's saves write) says the next draft save is pinned with: - * - * - `null` — no pending draft (the drafts ledger lists none, or the read - * answered 404 `NO_DRAFT`): `If-None-Match: *`; - * - the envelope's `version`, read through `GetMetaItemResponseSchema`'s own - * member: a token pins `If-Match`, a served `null` pins `If-None-Match: *`; - * - an envelope that carries no `version` (a server from before the read - * served one) pins nothing, and the save goes unpinned as it always did. - */ -export function draftPinOf(answer: unknown): DraftPin | null { - if (answer === null) return { ifNoneMatch: '*' }; - if (!answer || typeof answer !== 'object' || !('version' in answer)) return null; - const version = GetMetaItemResponseSchema.shape.version.safeParse((answer as { version: unknown }).version); - return version.success && version.data !== undefined ? pinOfVersion(version.data) : null; -} - -/** - * objectstack#36601 — what a load's `/layers` read (`MetadataClient.layered`, - * at the address the buffer's publish writes) says the Save's publish is - * pinned with: its `overlayVersion`, read through - * `GetMetaItemLayeredResponseSchema`'s own member — a token pins `If-Match`, a - * served `null` (no published row there) pins `If-None-Match: *`. An answer - * that carries no `overlayVersion` (a server from before it was served) pins - * nothing, and the publish goes unpinned as it always did. - */ -export function publishedPinOf(layered: unknown): DraftPin | null { - if (!layered || typeof layered !== 'object' || !('overlayVersion' in layered)) return null; - const version = GetMetaItemLayeredResponseSchema.shape.overlayVersion.safeParse( - (layered as { overlayVersion: unknown }).overlayVersion, - ); - return version.success && version.data !== undefined ? pinOfVersion(version.data) : null; -} - -/** - * The pin an "overwrite" re-sends with: the refused save's `currentVersion`, - * parsed by the spec's `MetadataConflictErrorSchema` off the body the client - * kept. A body that does not carry one (a server from before the field) - * pins nothing, and the overwrite is sent unpinned, as it was before. - */ -function pinOfConflict(err: unknown): DraftPin | null { - const body = MetadataConflictErrorSchema.safeParse((err as { body?: unknown } | null | undefined)?.body); - return body.success ? pinOfVersion(body.data.currentVersion) : null; -} - -/** - * Whether a draft read was REFUSED for this session (`403`): the read reached - * a draft row and the server withheld it, so the row exists and its body is - * not this session's to hold. Told apart by status, never by prose. - */ -export function isDraftReadRefused(err: unknown): boolean { - return (err as { status?: unknown } | null | undefined)?.status === 403; -} - -/** What {@link readDraftForSave} answers. */ -export interface DraftReadForSave { - /** The served draft envelope, or `null`: no pending draft, or a read that failed. */ - answer: T | null; - /** The pin the next draft save at the read's address is sent with. */ - pin: DraftPin | null; - /** - * The server's refusal, present only when the read was refused `403` - * ({@link isDraftReadRefused}). `answer` is then `null` although a draft is - * pending: a load that sees `refused` installs no buffer, because one seeded - * from the published layer would be saved over the draft it never read. - */ - refused?: unknown; -} - -/** - * A load's draft read at `packageId` — the address the buffer's draft saves - * write — with the pin it serves for that address. Read and pin come from one - * call so a load cannot pin a save to a read of another address (see the - * module header). A read that fails resolves `answer: null`, as the loads' - * `.catch(() => null)` always did, and pins nothing: a failure says nothing - * about the row. A read refused `403` says the row is there and withheld, and - * carries the refusal as `refused`. Record the pin with `recordRead` where the - * buffer is installed, not here: a load that is cancelled installs nothing. - */ -export async function readDraftForSave( - client: Pick, - type: string, - name: string, - packageId: string | null | undefined, - // objectstack#26649 — the bundle member whose draft this is; omitted, the - // canonical member's. The save it pins is addressed by its body's member. - member?: string, -): Promise> { - try { - const answer = await client.getDraft(type, name, { - ...(packageId ? { packageId } : {}), - ...(member ? { member } : {}), - }); - return { answer, pin: draftPinOf(answer) }; - } catch (err) { - return isDraftReadRefused(err) ? { answer: null, pin: null, refused: err } : { answer: null, pin: null }; - } -} - -function itemKey(type: string, name: string, packageId: string | null | undefined): string { - return JSON.stringify([type, name, packageId ?? null]); -} - -function receiptVersion(receipt: unknown): string | null { - const version = (receipt as { version?: unknown } | null | undefined)?.version; - return typeof version === 'string' && version.length > 0 ? version : null; -} - -/** `options` sent with `pin` in place of whatever precondition they carried. */ -function pinned(options: MetadataClientSaveOptions, pin: DraftPin | null): MetadataClientSaveOptions { - if (!pin) return options; - const { ifMatch: _ifMatch, ifNoneMatch: _ifNoneMatch, ...rest } = options; - return { ...rest, ...pin }; -} - -export interface DraftVersionGuardDeps { - /** The client to save through, read at the moment of the save. */ - client: () => Pick; - /** Ask the author how to resolve a conflict. */ - ask: (conflict: DraftConflict) => Promise; - /** Replace the buffer with the saved version (the caller's load). */ - reload: () => void; - /** The error a save the author chose not to send ends in. */ - notSaved: (conflict: DraftConflict) => Error; -} - -/** - * The React-free half of the guard: the pins held for one buffer, the - * one-at-a-time queue, and the conflict branch. {@link useDraftSaveGuard} binds - * it to a client, a dialog and the caller's reload. - */ -export class DraftVersionGuard { - /** - * The pin held per item (type, name, package) this buffer saves. One entry in - * the usual case; a surface whose one buffer switches between items (the - * hook panel) keeps each item's own. - */ - private readonly held = new Map(); - /** objectstack#36601 — the published layer's pin per item, for the Save's publish (rules 6–8). */ - private readonly published = new Map(); - /** - * objectstack#36726 — rule 9: per item, the published pin a conflict was - * raised on, held over a reload that re-read a pending draft until the - * author re-confirms; `fresh` is what the reload's load recorded meanwhile - * (absent until it has), taken once the item is confirmed. - */ - private readonly unconfirmed = new Map(); - private tail: Promise | null = null; - /** Bumped by a reload: a save queued before it carries the replaced buffer. */ - private epoch = 0; - - constructor(private deps: DraftVersionGuardDeps) {} - - /** Re-bind inputs that change between renders (the client, the reload, the locale's text). */ - bind(deps: Pick): void { - this.deps = { ...this.deps, ...deps }; - } - - /** The pin held, for the item `save` would address (tests read it). */ - heldFor(type: string, name: string, packageId?: string | null): DraftPin | null { - return this.held.get(itemKey(type, name, packageId)) ?? null; - } - - /** The published pin held, for the item `publish` would address (tests read it). */ - publishedFor(type: string, name: string, packageId?: string | null): DraftPin | null { - const key = itemKey(type, name, packageId); - return this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null; - } - - /** The buffer was installed with no draft read behind it: nothing describes it. */ - forget = (): void => { - this.held.clear(); - this.published.clear(); - this.unconfirmed.clear(); - }; - - /** - * objectstack#36726 — rule 9 ends for the item: its publish takes the pin - * the last load recorded, if one has since the reload. - */ - private confirm(key: string): void { - const entry = this.unconfirmed.get(key); - if (!entry) return; - this.unconfirmed.delete(key); - if (entry.fresh) this.published.set(key, entry.fresh); - else if (entry.fresh === null) this.published.delete(key); - } - - /** - * objectstack#36601 — the buffer was installed from a load whose `/layers` - * read, at the address the buffer's publish writes, served `pin` - * ({@link publishedPinOf}). `null` pins nothing. - */ - recordPublished = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => { - const key = itemKey(type, name, packageId); - // objectstack#36726 — a reload that re-read a pending draft is not the - // author's answer to the conflict: the pin it was raised on stays (rule 9). - const entry = this.unconfirmed.get(key); - if (entry) { - entry.fresh = pin; - return; - } - if (pin) this.published.set(key, pin); - else this.published.delete(key); - }; - - /** - * objectstack#36601 — the Save's publish of the draft it just wrote, pinned - * to the published version this buffer holds (rules 6–9 above). Resolves - * `'published'`, or `'reloaded'` when the author chose to reload after a - * conflict (`beforeReload` has run, then the caller's reload); throws the - * client's error otherwise, and the guard's "not saved" error when the - * author kept editing. `beforeReload` answers what it left at the item - * ({@link BeforeReloadOutcome}); one that answers nothing is `'discarded'`. - */ - publish = async ( - client: Pick, - type: string, - name: string, - options: { packageId?: string; member?: string } = {}, - beforeReload?: () => Promise, - ): Promise<'published' | 'reloaded'> => { - const key = itemKey(type, name, options.packageId); - let pin = this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null; - for (;;) { - try { - const receipt = await client.publish(type, name, { ...options, ...(pin ?? {}) }); - // The publish the author's buffer was built for landed: rule 9 is over for it. - this.unconfirmed.delete(key); - const version = receiptVersion(receipt); - if (version) this.published.set(key, { ifMatch: version }); - else this.published.delete(key); - return 'published'; - } catch (err) { - if (!isDraftVersionConflict(err)) throw err; - const conflict: DraftConflict = { type, name, layer: 'published' }; - const choice = await this.deps.ask(conflict); - if (choice === 'reload') { - // A `beforeReload` that throws (its draft could not be taken back) - // stops the reload here: nothing is re-read and the pins stay, so - // the next Save is asked about again (contract review S2). - const left = await beforeReload?.(); - this.held.clear(); - this.published.clear(); - this.epoch += 1; - // objectstack#36726 — the reload re-reads the pending draft it kept, - // which carries the page's edits: never pinned to the fresh read's - // version, so its next Save is refused and asked again (rule 9). - if (left === 'kept' && pin) this.unconfirmed.set(key, { pin }); - this.deps.reload(); - return 'reloaded'; - } - if (choice !== 'overwrite') { - const kept = this.deps.notSaved(conflict); - KEPT_EDITING.add(kept); - throw kept; - } - // As for a draft: the re-send is pinned to the version the refusal - // names, so a publish landing in between is asked about again. The - // author has seen the live row move and chose this buffer over it: - // that is the re-confirmation rule 9 waits for. - this.unconfirmed.delete(key); - pin = pinOfConflict(err); - if (pin) this.published.set(key, pin); - else this.published.delete(key); - } - } - }; - - /** - * The buffer was installed from a load whose draft read, at the address the - * buffer's saves write (`type`, `name`, `packageId`), served `pin` — what - * {@link readDraftForSave} returned. `null` pins nothing, as `forget()`. - */ - recordRead = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => { - const key = itemKey(type, name, packageId); - this.pin(key, pin); - // objectstack#36726 — no draft is pending at the address: the buffer is - // the live row, which the load's published read describes (rule 9 ends). - if (pin && 'ifNoneMatch' in pin) this.confirm(key); - }; - - /** - * Save `item` through the client. A non-draft save (no `mode: 'draft'`) is - * passed straight through: the guard pins drafts only. - */ - save = ( - type: string, - name: string, - item: unknown, - options: MetadataClientSaveOptions = {}, - ): Promise => { - if (options.mode !== 'draft') { - return this.deps.client().save(type, name, item, options).then(() => 'saved' as const); - } - const epoch = this.epoch; - const run = (): Promise => this.run(epoch, type, name, item, options); - // Started at once when nothing is in flight, so the request leaves in the - // same tick as before; queued behind the save in flight otherwise. - const result = this.tail ? this.tail.then(run) : run(); - const settled = result.then( - () => undefined, - () => undefined, - ); - this.tail = settled; - void settled.then(() => { - if (this.tail === settled) this.tail = null; - }); - return result; - }; - - private async run( - epoch: number, - type: string, - name: string, - item: unknown, - options: MetadataClientSaveOptions, - ): Promise { - // The author chose to reload while this save waited: its buffer is gone. - if (epoch !== this.epoch) return 'reloaded'; - const key = itemKey(type, name, options.packageId); - let pin = this.held.get(key) ?? null; - const client = this.deps.client(); - for (;;) { - try { - const receipt = await client.save(type, name, item, pinned(options, pin)); - this.hold(key, receipt); - return 'saved'; - } catch (err) { - if (!isDraftVersionConflict(err)) throw err; - const conflict: DraftConflict = { type, name }; - const choice = await this.deps.ask(conflict); - if (choice === 'reload') { - this.held.clear(); - this.published.clear(); - this.epoch += 1; - this.deps.reload(); - return 'reloaded'; - } - if (choice !== 'overwrite') throw this.deps.notSaved(conflict); - // The author has seen that the draft moved and chose this buffer over - // the version the refusal names, so the re-send is pinned to THAT - // version: a save landing between the refusal and the confirmation is - // refused again and asked about, never overwritten. Held, too, so a - // refusal of the re-send for another reason (a destructive change the - // caller confirms) retries over the same version. - pin = pinOfConflict(err); - this.pin(key, pin); - } - } - } - - private hold(key: string, receipt: unknown): void { - const version = receiptVersion(receipt); - this.pin(key, version ? { ifMatch: version } : null); - } - - private pin(key: string, pin: DraftPin | null): void { - if (pin) this.held.set(key, pin); - else this.held.delete(key); - } -} - -/** {@link DraftSaveGuard.heldDraftVersion} over a guard: the token of the `If-Match` it holds. */ -export function heldDraftVersionOf(guard: Pick): DraftSaveGuard['heldDraftVersion'] { - return (type, name, packageId) => { - const pin = guard.heldFor(type, name, packageId); - return pin && 'ifMatch' in pin ? pin.ifMatch : undefined; - }; -} - -export interface DraftSaveGuard { - /** A guarded `client.save` — same arguments, resolves what it ended in. */ - save: DraftVersionGuard['save']; - /** Call where the buffer is installed from a load's draft read (rule 3 above). */ - recordRead: DraftVersionGuard['recordRead']; - /** Call where the buffer is installed with no draft read behind it (rule 3 above). */ - forget: () => void; - /** Call where the buffer is installed from a load's `/layers` read (rule 6 above). */ - recordPublished: DraftVersionGuard['recordPublished']; - /** The Save's pinned publish (rules 7–8 above). */ - publish: DraftVersionGuard['publish']; - /** - * objectstack#36350 — the version of the draft this buffer last wrote or read - * at the item (the `If-Match` it holds: a save's receipt version, or the - * load's draft read), for a publish pinned to that draft (`draftVersion`). - * `undefined` when it holds no token (no draft, or a server that serves no - * version): such a publish goes unpinned. - */ - heldDraftVersion: (type: string, name: string, packageId?: string | null) => string | undefined; - /** The conflict dialog; render it once, anywhere in the caller's tree. */ - dialog: React.ReactElement; -} +export { + isPublishConflictKeptEditing, + isDraftVersionConflict, + draftPinOf, + publishedPinOf, + isDraftReadRefused, + readDraftForSave, + DraftVersionGuard, + heldDraftVersionOf, + type BeforeReloadOutcome, + type DraftSaveOutcome, + type DraftConflictChoice, + type DraftConflict, + type DraftPin, + type DraftReadForSave, + type DraftVersionGuardDeps, + type DraftSaveGuard, +} from './draftVersionGuard.js'; +import { DraftVersionGuard, heldDraftVersionOf, type DraftConflict, type DraftConflictChoice, type DraftSaveGuard } from './draftVersionGuard.js'; /** * One guard for one editing buffer. `onReload` replaces the buffer with the diff --git a/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx b/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx index 153da831eaa..c03faf66fb5 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx @@ -24,7 +24,7 @@ import type { RichMetadataTypeEntry } from './useMetadata.js'; import { useMetadataLocale, t, translateMetadataType, translateMetadataDomain } from './i18n.js'; import { environmentScopeSuffix } from './catalog-scope.js'; import { useMetadataAreaHost } from './metadataAreaHost.js'; -import { isStudioCustomizeType } from '../studio-design/StudioCustomizeControls.js'; +import { isStudioCustomizeType } from '../studio-design/customizeOverride.js'; import { AREA_CUSTOMIZE_EDITOR_TYPES, AREA_FORM_EDITOR_TYPES } from '../studio-design/metadataArea.js'; import { StudioTitleRowEnd } from '../studio-design/studioTitleRow.js'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts index 3719b8b4ad6..ff799e26d45 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts @@ -30,7 +30,7 @@ import type { DraftChange, MetadataClient } from '@object-ui/data-objectstack'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { isAgentDraftSurface } from '../studio-design/StudioDraftMark.js'; -import type { DraftSaveGuard } from './DraftConflictDialog.js'; +import type { DraftSaveGuard } from './draftVersionGuard.js'; /** The item a Save wrote, at the address its draft save wrote it. */ export interface DetailPublishTarget { diff --git a/ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts b/ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts new file mode 100644 index 00000000000..5f682e8b393 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts @@ -0,0 +1,478 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The draft-version guard's pure half: the conflict predicates, the pins a + * load reads, the guarded read and the {@link DraftVersionGuard} itself. The + * behaviour is specified in `./DraftConflictDialog.tsx`'s header, which + * re-exports every name here. + * + * ⛔ No component and no designer string table here. The running app's save + * paths that load with a list or record page (a list's view save, the record + * page's tabs and arrangement saves, the header-pin save) import these; + * reading them through + * `DraftConflictDialog.tsx` statically pulled the designer's English + * catalogue (`@object-ui/i18n/namespaces/studio`, through `./i18n.ts`) into + * those pages' first load (objectstack#37444). The dialog and + * `useDraftSaveGuard`, which render and translate, stay there. + */ + +import type * as React from 'react'; +import type { MetadataClient, MetadataClientSaveOptions } from '@object-ui/data-objectstack'; +import { GetMetaItemLayeredResponseSchema, GetMetaItemResponseSchema, MetadataConflictErrorSchema } from '@objectstack/spec/api'; +import { errorCodeIs } from '@object-ui/types'; + +/** + * objectstack#36726 — what a publish conflict's `beforeReload` left at the + * item: `'discarded'`, the draft the Save wrote was taken back, so the reload + * re-reads the live row; `'kept'`, a draft pending before the Save stays (it + * carries the page's edits), so the reload re-reads that draft (rule 9). + */ +export type BeforeReloadOutcome = 'discarded' | 'kept'; + +/** What a guarded save ended in, when it did not throw. */ +export type DraftSaveOutcome = 'saved' | 'reloaded'; + +/** The author's answer to a conflict. */ +export type DraftConflictChoice = 'reload' | 'overwrite' | 'cancel'; + +/** The item a refused save addressed. */ +export interface DraftConflict { + type: string; + name: string; + /** + * objectstack#36601 — which layer moved: the draft (the draft save was + * refused, the default) or the published row (the Save's publish was). + */ + layer?: 'draft' | 'published'; +} + +const KEPT_EDITING = new WeakSet(); + +/** + * objectstack#36601 — `err` is the "not saved" error the guarded publish + * throws when the author, asked about a published row that moved, chose to + * keep editing: no request failed, so the caller shows it as the draft + * conflict's own "not saved" line, never as a refused publish. + */ +export function isPublishConflictKeptEditing(err: unknown): boolean { + return typeof err === 'object' && err !== null && KEPT_EDITING.has(err); +} + +/** + * The version-conflict refusal of the `/meta` draft door, told apart from the + * door's OTHER 409 (`DESTRUCTIVE_CHANGE`) by its code, never by its prose. + */ +export function isDraftVersionConflict(err: unknown): boolean { + return (err as { status?: unknown } | null | undefined)?.status === 409 && errorCodeIs(err, 'METADATA_CONFLICT'); +} + +/** + * The precondition a guarded draft save is sent with: exactly one of the two + * headers, by construction never both. + */ +export type DraftPin = { readonly ifMatch: string } | { readonly ifNoneMatch: '*' }; + +/** + * A served `version` — a token, or `null` for "no row at this address" — as the + * pin a save to that address sends. An empty token pins nothing: the client + * sends no `If-Match` for it. + */ +function pinOfVersion(version: string | null): DraftPin | null { + if (version === null) return { ifNoneMatch: '*' }; + return version.length > 0 ? { ifMatch: version } : null; +} + +/** + * What a load's DRAFT read (`MetadataClient.getDraft`, at the address the + * buffer's saves write) says the next draft save is pinned with: + * + * - `null` — no pending draft (the drafts ledger lists none, or the read + * answered 404 `NO_DRAFT`): `If-None-Match: *`; + * - the envelope's `version`, read through `GetMetaItemResponseSchema`'s own + * member: a token pins `If-Match`, a served `null` pins `If-None-Match: *`; + * - an envelope that carries no `version` (a server from before the read + * served one) pins nothing, and the save goes unpinned as it always did. + */ +export function draftPinOf(answer: unknown): DraftPin | null { + if (answer === null) return { ifNoneMatch: '*' }; + if (!answer || typeof answer !== 'object' || !('version' in answer)) return null; + const version = GetMetaItemResponseSchema.shape.version.safeParse((answer as { version: unknown }).version); + return version.success && version.data !== undefined ? pinOfVersion(version.data) : null; +} + +/** + * objectstack#36601 — what a load's `/layers` read (`MetadataClient.layered`, + * at the address the buffer's publish writes) says the Save's publish is + * pinned with: its `overlayVersion`, read through + * `GetMetaItemLayeredResponseSchema`'s own member — a token pins `If-Match`, a + * served `null` (no published row there) pins `If-None-Match: *`. An answer + * that carries no `overlayVersion` (a server from before it was served) pins + * nothing, and the publish goes unpinned as it always did. + */ +export function publishedPinOf(layered: unknown): DraftPin | null { + if (!layered || typeof layered !== 'object' || !('overlayVersion' in layered)) return null; + const version = GetMetaItemLayeredResponseSchema.shape.overlayVersion.safeParse( + (layered as { overlayVersion: unknown }).overlayVersion, + ); + return version.success && version.data !== undefined ? pinOfVersion(version.data) : null; +} + +/** + * The pin an "overwrite" re-sends with: the refused save's `currentVersion`, + * parsed by the spec's `MetadataConflictErrorSchema` off the body the client + * kept. A body that does not carry one (a server from before the field) + * pins nothing, and the overwrite is sent unpinned, as it was before. + */ +function pinOfConflict(err: unknown): DraftPin | null { + const body = MetadataConflictErrorSchema.safeParse((err as { body?: unknown } | null | undefined)?.body); + return body.success ? pinOfVersion(body.data.currentVersion) : null; +} + +/** + * Whether a draft read was REFUSED for this session (`403`): the read reached + * a draft row and the server withheld it, so the row exists and its body is + * not this session's to hold. Told apart by status, never by prose. + */ +export function isDraftReadRefused(err: unknown): boolean { + return (err as { status?: unknown } | null | undefined)?.status === 403; +} + +/** What {@link readDraftForSave} answers. */ +export interface DraftReadForSave { + /** The served draft envelope, or `null`: no pending draft, or a read that failed. */ + answer: T | null; + /** The pin the next draft save at the read's address is sent with. */ + pin: DraftPin | null; + /** + * The server's refusal, present only when the read was refused `403` + * ({@link isDraftReadRefused}). `answer` is then `null` although a draft is + * pending: a load that sees `refused` installs no buffer, because one seeded + * from the published layer would be saved over the draft it never read. + */ + refused?: unknown; +} + +/** + * A load's draft read at `packageId` — the address the buffer's draft saves + * write — with the pin it serves for that address. Read and pin come from one + * call so a load cannot pin a save to a read of another address (see the + * module header). A read that fails resolves `answer: null`, as the loads' + * `.catch(() => null)` always did, and pins nothing: a failure says nothing + * about the row. A read refused `403` says the row is there and withheld, and + * carries the refusal as `refused`. Record the pin with `recordRead` where the + * buffer is installed, not here: a load that is cancelled installs nothing. + */ +export async function readDraftForSave( + client: Pick, + type: string, + name: string, + packageId: string | null | undefined, + // objectstack#26649 — the bundle member whose draft this is; omitted, the + // canonical member's. The save it pins is addressed by its body's member. + member?: string, +): Promise> { + try { + const answer = await client.getDraft(type, name, { + ...(packageId ? { packageId } : {}), + ...(member ? { member } : {}), + }); + return { answer, pin: draftPinOf(answer) }; + } catch (err) { + return isDraftReadRefused(err) ? { answer: null, pin: null, refused: err } : { answer: null, pin: null }; + } +} + +function itemKey(type: string, name: string, packageId: string | null | undefined): string { + return JSON.stringify([type, name, packageId ?? null]); +} + +function receiptVersion(receipt: unknown): string | null { + const version = (receipt as { version?: unknown } | null | undefined)?.version; + return typeof version === 'string' && version.length > 0 ? version : null; +} + +/** `options` sent with `pin` in place of whatever precondition they carried. */ +function pinned(options: MetadataClientSaveOptions, pin: DraftPin | null): MetadataClientSaveOptions { + if (!pin) return options; + const { ifMatch: _ifMatch, ifNoneMatch: _ifNoneMatch, ...rest } = options; + return { ...rest, ...pin }; +} + +export interface DraftVersionGuardDeps { + /** The client to save through, read at the moment of the save. */ + client: () => Pick; + /** Ask the author how to resolve a conflict. */ + ask: (conflict: DraftConflict) => Promise; + /** Replace the buffer with the saved version (the caller's load). */ + reload: () => void; + /** The error a save the author chose not to send ends in. */ + notSaved: (conflict: DraftConflict) => Error; +} + +/** + * The React-free half of the guard: the pins held for one buffer, the + * one-at-a-time queue, and the conflict branch. {@link useDraftSaveGuard} binds + * it to a client, a dialog and the caller's reload. + */ +export class DraftVersionGuard { + /** + * The pin held per item (type, name, package) this buffer saves. One entry in + * the usual case; a surface whose one buffer switches between items (the + * hook panel) keeps each item's own. + */ + private readonly held = new Map(); + /** objectstack#36601 — the published layer's pin per item, for the Save's publish (rules 6–8). */ + private readonly published = new Map(); + /** + * objectstack#36726 — rule 9: per item, the published pin a conflict was + * raised on, held over a reload that re-read a pending draft until the + * author re-confirms; `fresh` is what the reload's load recorded meanwhile + * (absent until it has), taken once the item is confirmed. + */ + private readonly unconfirmed = new Map(); + private tail: Promise | null = null; + /** Bumped by a reload: a save queued before it carries the replaced buffer. */ + private epoch = 0; + + constructor(private deps: DraftVersionGuardDeps) {} + + /** Re-bind inputs that change between renders (the client, the reload, the locale's text). */ + bind(deps: Pick): void { + this.deps = { ...this.deps, ...deps }; + } + + /** The pin held, for the item `save` would address (tests read it). */ + heldFor(type: string, name: string, packageId?: string | null): DraftPin | null { + return this.held.get(itemKey(type, name, packageId)) ?? null; + } + + /** The published pin held, for the item `publish` would address (tests read it). */ + publishedFor(type: string, name: string, packageId?: string | null): DraftPin | null { + const key = itemKey(type, name, packageId); + return this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null; + } + + /** The buffer was installed with no draft read behind it: nothing describes it. */ + forget = (): void => { + this.held.clear(); + this.published.clear(); + this.unconfirmed.clear(); + }; + + /** + * objectstack#36726 — rule 9 ends for the item: its publish takes the pin + * the last load recorded, if one has since the reload. + */ + private confirm(key: string): void { + const entry = this.unconfirmed.get(key); + if (!entry) return; + this.unconfirmed.delete(key); + if (entry.fresh) this.published.set(key, entry.fresh); + else if (entry.fresh === null) this.published.delete(key); + } + + /** + * objectstack#36601 — the buffer was installed from a load whose `/layers` + * read, at the address the buffer's publish writes, served `pin` + * ({@link publishedPinOf}). `null` pins nothing. + */ + recordPublished = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => { + const key = itemKey(type, name, packageId); + // objectstack#36726 — a reload that re-read a pending draft is not the + // author's answer to the conflict: the pin it was raised on stays (rule 9). + const entry = this.unconfirmed.get(key); + if (entry) { + entry.fresh = pin; + return; + } + if (pin) this.published.set(key, pin); + else this.published.delete(key); + }; + + /** + * objectstack#36601 — the Save's publish of the draft it just wrote, pinned + * to the published version this buffer holds (rules 6–9 above). Resolves + * `'published'`, or `'reloaded'` when the author chose to reload after a + * conflict (`beforeReload` has run, then the caller's reload); throws the + * client's error otherwise, and the guard's "not saved" error when the + * author kept editing. `beforeReload` answers what it left at the item + * ({@link BeforeReloadOutcome}); one that answers nothing is `'discarded'`. + */ + publish = async ( + client: Pick, + type: string, + name: string, + options: { packageId?: string; member?: string } = {}, + beforeReload?: () => Promise, + ): Promise<'published' | 'reloaded'> => { + const key = itemKey(type, name, options.packageId); + let pin = this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null; + for (;;) { + try { + const receipt = await client.publish(type, name, { ...options, ...(pin ?? {}) }); + // The publish the author's buffer was built for landed: rule 9 is over for it. + this.unconfirmed.delete(key); + const version = receiptVersion(receipt); + if (version) this.published.set(key, { ifMatch: version }); + else this.published.delete(key); + return 'published'; + } catch (err) { + if (!isDraftVersionConflict(err)) throw err; + const conflict: DraftConflict = { type, name, layer: 'published' }; + const choice = await this.deps.ask(conflict); + if (choice === 'reload') { + // A `beforeReload` that throws (its draft could not be taken back) + // stops the reload here: nothing is re-read and the pins stay, so + // the next Save is asked about again (contract review S2). + const left = await beforeReload?.(); + this.held.clear(); + this.published.clear(); + this.epoch += 1; + // objectstack#36726 — the reload re-reads the pending draft it kept, + // which carries the page's edits: never pinned to the fresh read's + // version, so its next Save is refused and asked again (rule 9). + if (left === 'kept' && pin) this.unconfirmed.set(key, { pin }); + this.deps.reload(); + return 'reloaded'; + } + if (choice !== 'overwrite') { + const kept = this.deps.notSaved(conflict); + KEPT_EDITING.add(kept); + throw kept; + } + // As for a draft: the re-send is pinned to the version the refusal + // names, so a publish landing in between is asked about again. The + // author has seen the live row move and chose this buffer over it: + // that is the re-confirmation rule 9 waits for. + this.unconfirmed.delete(key); + pin = pinOfConflict(err); + if (pin) this.published.set(key, pin); + else this.published.delete(key); + } + } + }; + + /** + * The buffer was installed from a load whose draft read, at the address the + * buffer's saves write (`type`, `name`, `packageId`), served `pin` — what + * {@link readDraftForSave} returned. `null` pins nothing, as `forget()`. + */ + recordRead = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => { + const key = itemKey(type, name, packageId); + this.pin(key, pin); + // objectstack#36726 — no draft is pending at the address: the buffer is + // the live row, which the load's published read describes (rule 9 ends). + if (pin && 'ifNoneMatch' in pin) this.confirm(key); + }; + + /** + * Save `item` through the client. A non-draft save (no `mode: 'draft'`) is + * passed straight through: the guard pins drafts only. + */ + save = ( + type: string, + name: string, + item: unknown, + options: MetadataClientSaveOptions = {}, + ): Promise => { + if (options.mode !== 'draft') { + return this.deps.client().save(type, name, item, options).then(() => 'saved' as const); + } + const epoch = this.epoch; + const run = (): Promise => this.run(epoch, type, name, item, options); + // Started at once when nothing is in flight, so the request leaves in the + // same tick as before; queued behind the save in flight otherwise. + const result = this.tail ? this.tail.then(run) : run(); + const settled = result.then( + () => undefined, + () => undefined, + ); + this.tail = settled; + void settled.then(() => { + if (this.tail === settled) this.tail = null; + }); + return result; + }; + + private async run( + epoch: number, + type: string, + name: string, + item: unknown, + options: MetadataClientSaveOptions, + ): Promise { + // The author chose to reload while this save waited: its buffer is gone. + if (epoch !== this.epoch) return 'reloaded'; + const key = itemKey(type, name, options.packageId); + let pin = this.held.get(key) ?? null; + const client = this.deps.client(); + for (;;) { + try { + const receipt = await client.save(type, name, item, pinned(options, pin)); + this.hold(key, receipt); + return 'saved'; + } catch (err) { + if (!isDraftVersionConflict(err)) throw err; + const conflict: DraftConflict = { type, name }; + const choice = await this.deps.ask(conflict); + if (choice === 'reload') { + this.held.clear(); + this.published.clear(); + this.epoch += 1; + this.deps.reload(); + return 'reloaded'; + } + if (choice !== 'overwrite') throw this.deps.notSaved(conflict); + // The author has seen that the draft moved and chose this buffer over + // the version the refusal names, so the re-send is pinned to THAT + // version: a save landing between the refusal and the confirmation is + // refused again and asked about, never overwritten. Held, too, so a + // refusal of the re-send for another reason (a destructive change the + // caller confirms) retries over the same version. + pin = pinOfConflict(err); + this.pin(key, pin); + } + } + } + + private hold(key: string, receipt: unknown): void { + const version = receiptVersion(receipt); + this.pin(key, version ? { ifMatch: version } : null); + } + + private pin(key: string, pin: DraftPin | null): void { + if (pin) this.held.set(key, pin); + else this.held.delete(key); + } +} + +/** {@link DraftSaveGuard.heldDraftVersion} over a guard: the token of the `If-Match` it holds. */ +export function heldDraftVersionOf(guard: Pick): DraftSaveGuard['heldDraftVersion'] { + return (type, name, packageId) => { + const pin = guard.heldFor(type, name, packageId); + return pin && 'ifMatch' in pin ? pin.ifMatch : undefined; + }; +} + +export interface DraftSaveGuard { + /** A guarded `client.save` — same arguments, resolves what it ended in. */ + save: DraftVersionGuard['save']; + /** Call where the buffer is installed from a load's draft read (rule 3 above). */ + recordRead: DraftVersionGuard['recordRead']; + /** Call where the buffer is installed with no draft read behind it (rule 3 above). */ + forget: () => void; + /** Call where the buffer is installed from a load's `/layers` read (rule 6 above). */ + recordPublished: DraftVersionGuard['recordPublished']; + /** The Save's pinned publish (rules 7–8 above). */ + publish: DraftVersionGuard['publish']; + /** + * objectstack#36350 — the version of the draft this buffer last wrote or read + * at the item (the `If-Match` it holds: a save's receipt version, or the + * load's draft read), for a publish pinned to that draft (`draftVersion`). + * `undefined` when it holds no token (no draft, or a server that serves no + * version): such a publish goes unpinned. + */ + heldDraftVersion: (type: string, name: string, packageId?: string | null) => string | undefined; + /** The conflict dialog; render it once, anywhere in the caller's tree. */ + dialog: React.ReactElement; +} diff --git a/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts index 791a31f86db..5256e87b9cd 100644 --- a/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts +++ b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts @@ -45,8 +45,8 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import type { CustomArrangementKey, ObjectActionLayout } from '@objectstack/spec/data'; -import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js'; -import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf, type ObjectExtensionBody } from './studio-design/StudioCustomizeControls.js'; +import { isDraftVersionConflict } from './metadata-admin/draftVersionGuard.js'; +import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf, type ObjectExtensionBody } from './studio-design/customizeOverride.js'; import type { EnsuredCustomizationPackage, ListedPackageManifest } from './studio-design/packages-io.js'; /** The doors the write goes through; the defaults are the console's own (`consoleExtensionArrangementDoors`). */ diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index d70c539692a..6fb1a46fe7d 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -22,7 +22,7 @@ import type { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.j import type { useMetadataClient } from './metadata-admin/useMetadata.js'; import { persistRuntimeMetadata, createRuntimeMetadata, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; import type { RuntimeCreateApp, SaveAndPublishOutcome } from './runtime-metadata-persistence.js'; -import type { DraftVersionGuard } from './metadata-admin/DraftConflictDialog.js'; +import type { DraftVersionGuard } from './metadata-admin/draftVersionGuard.js'; import { draftBarPackageOf } from '../preview/DraftPreviewBar.js'; import { useMetadata } from '../providers/MetadataProvider.js'; import { buildAddViewSpec, setDefaultViewPatches, buildViewConfigSaveBody } from './objectViewTabs.js'; diff --git a/ui/packages/app-shell/src/views/recordTabsConfigSave.ts b/ui/packages/app-shell/src/views/recordTabsConfigSave.ts index a93a073cab3..9b101db38fb 100644 --- a/ui/packages/app-shell/src/views/recordTabsConfigSave.ts +++ b/ui/packages/app-shell/src/views/recordTabsConfigSave.ts @@ -33,7 +33,7 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; -import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js'; +import { isDraftVersionConflict } from './metadata-admin/draftVersionGuard.js'; import { ensureCustomizationPackage, fetchListedPackageManifests, @@ -42,7 +42,7 @@ import { import { recordTabsEntries, type RecordTabsCatalog, type RecordTabsDraft } from './recordTabsConfigModel.js'; import { saveObjectExtensionArrangement, type ExtensionArrangementDoors } from './objectExtensionArrangementSave.js'; import { installedTabsEntries } from './recordTabsInstalled.js'; -import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf } from './studio-design/StudioCustomizeControls.js'; +import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf } from './studio-design/customizeOverride.js'; /** The doors the save goes through; the defaults are the console's own. */ export interface RecordTabsSaveDoors { diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 5544720aa89..59c453d731c 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -46,10 +46,10 @@ import { isDraftVersionConflict, type DraftSaveOutcome, type DraftVersionGuard, -} from './metadata-admin/DraftConflictDialog.js'; +} from './metadata-admin/draftVersionGuard.js'; import { ensureCustomizationPackage, fetchListedPackageManifests } from './studio-design/packages-io.js'; import { listedCustomizationPairOf, listedPackageVersion, type ListedPackageManifest } from './studio-design/packages-io.js'; -import { overrideDraftBody } from './studio-design/StudioCustomizeControls.js'; +import { overrideDraftBody } from './studio-design/customizeOverride.js'; /** The runtime-editable artifact types ADR-0034 unifies. `page` (a record * `PageSchema`) joins the original three (#1541): a record page is edited in diff --git a/ui/packages/app-shell/src/views/setup/publicForms.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts index a2052ff28f7..44496fc6d31 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -75,7 +75,7 @@ import { type RuntimePersistCtx, type SaveAndPublishOutcome, } from '../runtime-metadata-persistence.js'; -import { declaredOverrideOf, overrideDraftBody } from '../studio-design/StudioCustomizeControls.js'; +import { declaredOverrideOf, overrideDraftBody } from '../studio-design/customizeOverride.js'; import { fetchListedPackageManifests } from '../studio-design/packages-io.js'; type FormDoc = Record; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx b/ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx index 5e397b80cd6..8c0a3af2fcf 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx @@ -26,6 +26,11 @@ * * The pair's id for a write is the ensure door's answer * (`packages-io.ts#ensureCustomizationPackage`); the editor asks it. + * + * The pure half (the types, the declaration, the draft body, the walled + * verdict, the extension body) lives in `./customizeOverride.ts` and is + * re-exported here: the running app's save paths import it from there, so a + * list or record page does not load this module (objectstack#37444). */ import * as React from 'react'; @@ -43,110 +48,28 @@ import { PopoverTrigger, cn, } from '@object-ui/components'; -import { useAuth } from '@object-ui/auth'; -import type { TenancyPosture } from '@object-ui/auth'; import { extractDraftBody, type MetadataClient } from '@object-ui/data-objectstack'; -import { - OverrideDeclarationSchema, - isOverridableMetadataType, - type OverrideDeclarationParsed, -} from '@objectstack/spec/kernel'; -import { - BASE_FIELD_DISPLAY_WHITELIST, - EXTENSION_FIELD_SUFFIX, - isExtensionFieldName, - isPlainRecord, -} from '@objectstack/spec/data'; +import type { OverrideDeclarationParsed } from '@objectstack/spec/kernel'; +import { BASE_FIELD_DISPLAY_WHITELIST, isPlainRecord } from '@objectstack/spec/data'; import { Layers, Pencil, RotateCcw } from 'lucide-react'; -import { postureHasOrgWall, useTenancyPosture } from '../../hooks/useTenancyPosture.js'; import { t, tFormat } from '../metadata-admin/i18n.js'; import { STUDIO_FOLD_LABEL } from './studio-tokens.js'; import { useStudioFoldedMenuClose } from './StudioItemHeader.js'; import { readFields, writeFields, type FieldEntry } from '../metadata-admin/previews/object-fields-io.js'; -/** - * The types Studio's Customize door covers: a view, dashboard, report and page - * (objectstack#30063: a page, block or source, is edited in its designer as a - * dashboard is), and an app (objectstack#30059: the whole app is copied into - * the pair on the first saved navigation edit). Each is an `overridable` type - * of the spec's classification. Their door was the Interfaces pillar's header; - * since objectstack#36502 retired that pillar, a read-only base's view, - * dashboard, report or page is customized in the All metadata area's editor - * (`StudioBundleItemEditor`, `metadataArea.ts#AREA_CUSTOMIZE_EDITOR_TYPES`), - * and an app's navigation in the running app's design mode - * (`layout/designModeMenuSave.ts`). Translations and email templates are - * customized in that editor too (objectstack#28569), and so is a read-only - * package's dataset, with its own designer (objectstack#30064). - */ -export const STUDIO_CUSTOMIZE_TYPES: readonly string[] = ['view', 'dashboard', 'report', 'page', 'app']; - -/** Whether Studio customizes an item of `type` into a read-only base's pair. */ -export function isStudioCustomizeType(type: string | undefined | null): boolean { - return !!type && STUDIO_CUSTOMIZE_TYPES.includes(type) && isOverridableMetadataType(type); -} - -/** - * The override declaration of `base` that `doc` carries (`doc.overrides`, - * parsed by the spec's `OverrideDeclarationSchema`), or `null`: a document - * that declares nothing, declares another base, or carries a malformed - * declaration declares no override of `base`. - */ -export function declaredOverrideOf(doc: unknown, base: string): OverrideDeclarationParsed | null { - if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return null; - const parsed = OverrideDeclarationSchema.safeParse((doc as { overrides?: unknown }).overrides); - return parsed.success && parsed.data.package === base ? parsed.data : null; -} - -/** - * The body a customization's draft is written into the pair with: `doc` - * without its top-level `_` keys (the read's decorations and the base's - * protection envelope, `_packageId` included, belong to the base's item, not - * to the pair's), declaring the override of `base`. A declaration of `base` - * the document already carries (an item customized before) is kept as it is, - * its `basedOn` included: re-basing is a person's call, never a save's. - * `null` when there is no declaration to keep and no version to declare - * (`basedOn: null`, a base whose listed manifest states none): nothing is - * guessed, and the caller says so. - */ -export function overrideDraftBody( - doc: Record, - base: string, - basedOn: string | null, -): Record | null { - const declaration = declaredOverrideOf(doc, base) ?? (basedOn ? { package: base, basedOn } : null); - if (declaration === null) return null; - const body: Record = {}; - for (const [key, value] of Object.entries(doc)) { - if (!key.startsWith('_')) body[key] = value; - } - body.overrides = declaration; - return body; -} - -/** - * Whether the ensure door refuses this caller on this deployment. The door - * (`POST /packages/:id/ensure-customization`) judges the caller as the - * package install door does: under the walled `group` / `isolated` postures - * only the platform operator may call it, and under `single` (or with no - * posture served) the `manage_metadata` holder Studio already requires. Read - * from the two facts the server publishes for that verdict, the posture - * (`features.tenancyPosture`) and the session's `user.isPlatformAdmin`, the - * ones `setup/packagedFlowLedger.ts#useFlowLedgerWalledReadOnly` reads. The - * server stays the judge: a refusal after an attempt is shown as it is sent. - */ -export function customizeDoorWalled(input: { - posture: TenancyPosture | undefined; - isPlatformOperator: boolean; -}): boolean { - return postureHasOrgWall(input.posture) && !input.isPlatformOperator; -} - -/** {@link customizeDoorWalled} for this session and this deployment. */ -export function useCustomizeDoorWalled(): boolean { - const posture = useTenancyPosture(); - const { user } = useAuth(); - return customizeDoorWalled({ posture, isPlatformOperator: user?.isPlatformAdmin === true }); -} +export { + STUDIO_CUSTOMIZE_TYPES, + isStudioCustomizeType, + declaredOverrideOf, + overrideDraftBody, + customizeDoorWalled, + useCustomizeDoorWalled, + OBJECT_EXTENSION_TYPE, + extensionFieldName, + objectExtensionBodyOf, + type ObjectExtensionBody, +} from './customizeOverride.js'; +import { declaredOverrideOf, type ObjectExtensionBody } from './customizeOverride.js'; /** The override the server serves for one item, and where it is served from. */ export interface ServedOverride { @@ -463,38 +386,6 @@ export function StudioRestoreOriginalDialog({ */ export const BaseFieldDisplayPatchContext = React.createContext(false); -/** - * The metadata type a base object's extension is written as: one row per - * package per target object, filed under the target's name, its body - * `ObjectExtensionSchema` (`extend`, `fields`, `fieldPatches`, …). - */ -export const OBJECT_EXTENSION_TYPE = 'object_extension'; - -/** The pair's extension of one base object: `extend` names the object. */ -export type ObjectExtensionBody = Record & { extend: string }; - -/** - * `name` spelled as a customer extension field: the spec's suffix appended - * once (`region` → `region__c`, `region__c` unchanged). Empty stays empty. - */ -export function extensionFieldName(name: string): string { - if (!name) return name; - return isExtensionFieldName(name) ? name : `${name}${EXTENSION_FIELD_SUFFIX}`; -} - -/** - * The extension body a read served for `objectName`: the document without - * its `_` keys (the envelope a read stamps, which the strict schema refuses), - * `extend` set to the object. `null` when the read served no document. - */ -export function objectExtensionBodyOf(doc: unknown, objectName: string): ObjectExtensionBody | null { - if (!isPlainRecord(doc)) return null; - const body: Record = {}; - for (const [key, value] of Object.entries(doc)) { - if (!key.startsWith('_')) body[key] = value; - } - return { ...body, extend: objectName }; -} /** The names `ext.fields` declares. */ export function extensionFieldNames(ext: Record | null | undefined): string[] { diff --git a/ui/packages/app-shell/src/views/studio-design/customizeOverride.ts b/ui/packages/app-shell/src/views/studio-design/customizeOverride.ts new file mode 100644 index 00000000000..4347317bbed --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/customizeOverride.ts @@ -0,0 +1,144 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Customize door's pure half: which types Studio customizes, the override + * declaration a document carries, the body a pair's draft is written with, the + * door's walled verdict, and a base object's extension body. + * + * ⛔ No component, no designer string table and no Studio chrome here. The + * running app's save paths that load with a list or record page (a list's + * view save, the record page's tabs and arrangement saves) read these; + * importing the names from + * `StudioCustomizeControls.tsx` statically pulled that component module, the + * Studio header and the designer's English catalogue + * (`@object-ui/i18n/namespaces/studio`) into those pages' first load + * (objectstack#37444). `StudioCustomizeControls.tsx` re-exports every name, + * so the designer's own imports are unchanged. + */ + +import { useAuth } from '@object-ui/auth'; +import type { TenancyPosture } from '@object-ui/auth'; +import { + OverrideDeclarationSchema, + isOverridableMetadataType, + type OverrideDeclarationParsed, +} from '@objectstack/spec/kernel'; +import { EXTENSION_FIELD_SUFFIX, isExtensionFieldName, isPlainRecord } from '@objectstack/spec/data'; +import { postureHasOrgWall, useTenancyPosture } from '../../hooks/useTenancyPosture.js'; + +/** + * The types Studio's Customize door covers: a view, dashboard, report and page + * (objectstack#30063: a page, block or source, is edited in its designer as a + * dashboard is), and an app (objectstack#30059: the whole app is copied into + * the pair on the first saved navigation edit). Each is an `overridable` type + * of the spec's classification. Their door was the Interfaces pillar's header; + * since objectstack#36502 retired that pillar, a read-only base's view, + * dashboard, report or page is customized in the All metadata area's editor + * (`StudioBundleItemEditor`, `metadataArea.ts#AREA_CUSTOMIZE_EDITOR_TYPES`), + * and an app's navigation in the running app's design mode + * (`layout/designModeMenuSave.ts`). Translations and email templates are + * customized in that editor too (objectstack#28569), and so is a read-only + * package's dataset, with its own designer (objectstack#30064). + */ +export const STUDIO_CUSTOMIZE_TYPES: readonly string[] = ['view', 'dashboard', 'report', 'page', 'app']; + +/** Whether Studio customizes an item of `type` into a read-only base's pair. */ +export function isStudioCustomizeType(type: string | undefined | null): boolean { + return !!type && STUDIO_CUSTOMIZE_TYPES.includes(type) && isOverridableMetadataType(type); +} + +/** + * The override declaration of `base` that `doc` carries (`doc.overrides`, + * parsed by the spec's `OverrideDeclarationSchema`), or `null`: a document + * that declares nothing, declares another base, or carries a malformed + * declaration declares no override of `base`. + */ +export function declaredOverrideOf(doc: unknown, base: string): OverrideDeclarationParsed | null { + if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return null; + const parsed = OverrideDeclarationSchema.safeParse((doc as { overrides?: unknown }).overrides); + return parsed.success && parsed.data.package === base ? parsed.data : null; +} + +/** + * The body a customization's draft is written into the pair with: `doc` + * without its top-level `_` keys (the read's decorations and the base's + * protection envelope, `_packageId` included, belong to the base's item, not + * to the pair's), declaring the override of `base`. A declaration of `base` + * the document already carries (an item customized before) is kept as it is, + * its `basedOn` included: re-basing is a person's call, never a save's. + * `null` when there is no declaration to keep and no version to declare + * (`basedOn: null`, a base whose listed manifest states none): nothing is + * guessed, and the caller says so. + */ +export function overrideDraftBody( + doc: Record, + base: string, + basedOn: string | null, +): Record | null { + const declaration = declaredOverrideOf(doc, base) ?? (basedOn ? { package: base, basedOn } : null); + if (declaration === null) return null; + const body: Record = {}; + for (const [key, value] of Object.entries(doc)) { + if (!key.startsWith('_')) body[key] = value; + } + body.overrides = declaration; + return body; +} + +/** + * Whether the ensure door refuses this caller on this deployment. The door + * (`POST /packages/:id/ensure-customization`) judges the caller as the + * package install door does: under the walled `group` / `isolated` postures + * only the platform operator may call it, and under `single` (or with no + * posture served) the `manage_metadata` holder Studio already requires. Read + * from the two facts the server publishes for that verdict, the posture + * (`features.tenancyPosture`) and the session's `user.isPlatformAdmin`, the + * ones `setup/packagedFlowLedger.ts#useFlowLedgerWalledReadOnly` reads. The + * server stays the judge: a refusal after an attempt is shown as it is sent. + */ +export function customizeDoorWalled(input: { + posture: TenancyPosture | undefined; + isPlatformOperator: boolean; +}): boolean { + return postureHasOrgWall(input.posture) && !input.isPlatformOperator; +} + +/** {@link customizeDoorWalled} for this session and this deployment. */ +export function useCustomizeDoorWalled(): boolean { + const posture = useTenancyPosture(); + const { user } = useAuth(); + return customizeDoorWalled({ posture, isPlatformOperator: user?.isPlatformAdmin === true }); +} + +/** + * The metadata type a base object's extension is written as: one row per + * package per target object, filed under the target's name, its body + * `ObjectExtensionSchema` (`extend`, `fields`, `fieldPatches`, …). + */ +export const OBJECT_EXTENSION_TYPE = 'object_extension'; + +/** The pair's extension of one base object: `extend` names the object. */ +export type ObjectExtensionBody = Record & { extend: string }; + +/** + * `name` spelled as a customer extension field: the spec's suffix appended + * once (`region` → `region__c`, `region__c` unchanged). Empty stays empty. + */ +export function extensionFieldName(name: string): string { + if (!name) return name; + return isExtensionFieldName(name) ? name : `${name}${EXTENSION_FIELD_SUFFIX}`; +} + +/** + * The extension body a read served for `objectName`: the document without + * its `_` keys (the envelope a read stamps, which the strict schema refuses), + * `extend` set to the object. `null` when the read served no document. + */ +export function objectExtensionBodyOf(doc: unknown, objectName: string): ObjectExtensionBody | null { + if (!isPlainRecord(doc)) return null; + const body: Record = {}; + for (const [key, value] of Object.entries(doc)) { + if (!key.startsWith('_')) body[key] = value; + } + return { ...body, extend: objectName }; +}