From b01f2790ea43e8c225f5f628eac6aa392dd474a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:06:49 +0000 Subject: [PATCH 1/4] fix(metadata-protocol): FORM_ADDRESS_TAKEN carries the holding form as details.holder; Setup reads it Claude-Session: https://claude.ai/code/session_01ADHkmQu29PQequUrXXHYMn Co-authored-by: Claude --- .../src/protocol-form-writes.ts | 13 ++- packages/rest/src/error-response.ts | 17 +++- .../public-form-two-type-withdrawal.test.ts | 31 +++++++ packages/types/src/thrown-http-error.test.ts | 26 +++++- packages/types/src/thrown-http-error.ts | 42 ++++++++- .../views/setup/PublicFormsSetupPage.test.tsx | 59 ++++++++---- .../src/views/setup/PublicFormsSetupPage.tsx | 25 ++---- .../src/views/setup/publicForms.test.ts | 89 +++++++------------ .../app-shell/src/views/setup/publicForms.ts | 85 ++++++------------ 9 files changed, 228 insertions(+), 159 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-form-writes.ts b/packages/metadata-protocol/src/protocol-form-writes.ts index efa21564701..298825293d1 100644 --- a/packages/metadata-protocol/src/protocol-form-writes.ts +++ b/packages/metadata-protocol/src/protocol-form-writes.ts @@ -120,7 +120,8 @@ export function formHeldSlug(form: unknown): string | undefined { * refusal on the new type only: an old-shape `view` write keeps today's * first-match behaviour. * - * `409`, code {@link FORM_ADDRESS_TAKEN}. + * `409`, code {@link FORM_ADDRESS_TAKEN}, with the holding form as `holder` + * (`{ name, packageId }`), answered as `details.holder`. */ export async function formAddressClashRefusal( host: FormReadHost, @@ -128,7 +129,7 @@ export async function formAddressClashRefusal( item: unknown, name: string, packageId: string | null | undefined, -): Promise<(Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409 }) | undefined> { +): Promise<(Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409; holder: { name: string; packageId: string | null } }) | undefined> { if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'form') return undefined; if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined; const slug = anonymousFormIntakeSlug((item as { sharing?: unknown }).sharing); @@ -149,14 +150,18 @@ export async function formAddressClashRefusal( return true; }) as { name?: unknown; _packageId?: unknown } | undefined; if (holder === undefined) return undefined; - const owner = typeof holder._packageId === 'string' && holder._packageId !== '' ? ` of the package '${holder._packageId}'` : ''; + const holderPkg = typeof holder._packageId === 'string' && holder._packageId !== '' ? holder._packageId : null; + const owner = holderPkg !== null ? ` of the package '${holderPkg}'` : ''; const err = new Error( `The form '${name}' cannot open the public address '/forms/${slug}': the form '${String(holder.name)}'${owner} ` + `holds it. Give '${name}' another public link, or clear the link of '${String(holder.name)}' first. A form ` + `holds an address while its public link names it, switched on or off.`, - ) as Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409 }; + ) as Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409; holder: { name: string; packageId: string | null } }; err.code = FORM_ADDRESS_TAKEN; err.status = 409; + // [#38626] The holder as data, which every door answers in + // `details.holder` (`formAddressRefusalHolder`, `@objectstack/types`). + err.holder = { name: String(holder.name), packageId: holderPkg }; return err; } diff --git a/packages/rest/src/error-response.ts b/packages/rest/src/error-response.ts index a71c99077c8..e1fb30ac78e 100644 --- a/packages/rest/src/error-response.ts +++ b/packages/rest/src/error-response.ts @@ -61,6 +61,7 @@ import { boundedDeclaredRefusalMessage, declaredHttpStatus, fiveXxArmDisplacesDeclared4xx, + formAddressRefusalHolder, isSandboxCrash, isSandboxOrigin, isSandboxOwnFault, @@ -641,17 +642,25 @@ function resolveErrorResponse(error: any, object?: string, options?: RouteErrorO : thrownCodeFields(error, error.status)), ...(Array.isArray(error.issues) ? { issues: error.issues } : {}), ...(object ? { object } : {}), - ...packageScopedCandidatesMember(error, options), + ...declaredDetailsMember(error, options), }, }); } return mapDataError(error, object); } -/** [#32201] The `details.candidates` member {@link RouteErrorOptions} asks for, or nothing. */ -function packageScopedCandidatesMember(error: unknown, options: RouteErrorOptions | undefined): { details?: { candidates: readonly PackageScopedHolder[] } } { +/** + * The `details` member of a declared-status refusal, or nothing: [#32201] the + * `details.candidates` {@link RouteErrorOptions} asks for, and [#38626] the + * form a `409 FORM_ADDRESS_TAKEN` names as holding the address + * (`details.holder`, read by `@objectstack/types`' one recogniser, as the + * dispatcher door's `resolveThrownHttpError` reads it), on every route. + */ +function declaredDetailsMember(error: unknown, options: RouteErrorOptions | undefined): { details?: Record } { const candidates = options?.packageScopedCandidates ? packageScopedRefusalCandidates(error) : undefined; - return candidates ? { details: { candidates } } : {}; + const holder = formAddressRefusalHolder(error); + const details = { ...(candidates ? { candidates } : {}), ...(holder ? { holder } : {}) }; + return Object.keys(details).length > 0 ? { details } : {}; } /** diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 190e1d1e12d..8497ac7aacc 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -31,6 +31,7 @@ import { hashSpec, } from '@objectstack/metadata-core'; import { readFileSync } from 'node:fs'; +import { thrownAnswerOf } from '@objectstack/types'; import { RestServer } from './rest-server'; const BASE = 'com.example.forms37086'; @@ -1300,3 +1301,33 @@ describe('[ADR-0067 D2] a package publish refused part-way on an engine that can }); } }); + +describe('[#38626] `409 FORM_ADDRESS_TAKEN` carries the holding form as data on both doors', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const SECOND = `${OBJECT}.second`; + + it('RestServer\'s PUT answers `details.holder`; the dispatcher\'s resolver answers the same thrown refusal with it', async () => { + const b = await boot({ forms: [formItem(true)] }); + engines.push(b.engine); + await b.install(PAIR); + // RestServer's door: the registered `PUT /meta/:type/:name` handler, as an authoring caller. + (b.rest as any).resolveExecCtx = async () => ({ userId: 'u_author', isSystem: true }); + const put = b.rest.getRoutes().find((r: any) => r.method === 'PUT' && r.path === '/api/v1/meta/:type/:name')!; + const res = makeRes(); + await put.handler({ + method: 'PUT', path: `/api/v1/meta/form/${SECOND}`, params: { type: 'form', name: SECOND }, + query: { packageId: PAIR, mode: 'draft' }, body: { ...formItem(true), name: SECOND }, headers: {}, + } as any, res); + expect([res._status, res._json?.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']); + expect(res._json?.details?.holder).toEqual({ name: NAME, packageId: BASE }); + // The dispatcher's door: the same refusal, thrown by the real save, through the resolver it answers with. + const thrown = await b.protocol.saveMetaItem({ type: 'form', name: SECOND, packageId: PAIR, mode: 'draft', item: { ...formItem(true), name: SECOND } }) + .then(() => undefined, (e: unknown) => e); + const answer = thrownAnswerOf(thrown, 500); + expect([answer.status, answer.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']); + expect(answer.details?.holder).toEqual({ name: NAME, packageId: BASE }); + }); +}); diff --git a/packages/types/src/thrown-http-error.test.ts b/packages/types/src/thrown-http-error.test.ts index 706bc56765e..fa3a49ceb89 100644 --- a/packages/types/src/thrown-http-error.test.ts +++ b/packages/types/src/thrown-http-error.test.ts @@ -13,7 +13,7 @@ // side-channel, because all three call this function. import { describe, it, expect } from 'vitest'; -import { declaredRefusalLines, declaredUserMessage, packageScopedRefusalCandidates, resolveThrownHttpError } from './thrown-http-error.js'; +import { declaredRefusalLines, declaredUserMessage, formAddressRefusalHolder, packageScopedRefusalCandidates, resolveThrownHttpError } from './thrown-http-error.js'; import { thrownAnswerOf } from './actions-door-answer.js'; import { mapDataError } from './data-error-classification.js'; @@ -250,3 +250,27 @@ describe('[#36877] declaredRefusalLines — a declared refusal thrown as a reaso expect(mapDataError(refusal({ refusals: undefined }), 'expense').body.details).toBeUndefined(); }); }); + +describe('[#38626] resolveThrownHttpError carries an address refusal\'s holder as `details.holder`', () => { + const refusal = (extra: Record = {}) => Object.assign( + new Error("The form 'b' cannot open the public address '/forms/x': the form 'a' holds it."), + { code: 'FORM_ADDRESS_TAKEN', status: 409, holder: { name: 'crm_lead.a', packageId: 'crm' }, ...extra }, + ); + + it('resolves 409 FORM_ADDRESS_TAKEN with the holder, a package-less holder included', () => { + const resolved = resolveThrownHttpError(refusal(), 500); + expect([resolved.status, resolved.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']); + expect(resolved.details).toEqual({ holder: { name: 'crm_lead.a', packageId: 'crm' } }); + expect(resolveThrownHttpError(refusal({ holder: { name: 'a', packageId: null } }), 500).details) + .toEqual({ holder: { name: 'a', packageId: null } }); + expect(formAddressRefusalHolder(refusal({ status: undefined, statusCode: 409 }))).toEqual({ name: 'crm_lead.a', packageId: 'crm' }); + }); + + it('CONTROL: another code, another status, or a holder of another shape carries no holder', () => { + expect(resolveThrownHttpError(refusal({ code: 'RESOURCE_CONFLICT' }), 500).details).toBeUndefined(); + expect(resolveThrownHttpError(refusal({ status: 400 }), 500).details).toBeUndefined(); + for (const holder of [undefined, null, 'a', { name: '' }, { name: 'a' }, { name: 'a', packageId: 3 }]) { + expect(resolveThrownHttpError(refusal({ holder }), 500).details, JSON.stringify(holder)).toBeUndefined(); + } + }); +}); diff --git a/packages/types/src/thrown-http-error.ts b/packages/types/src/thrown-http-error.ts index fe6ac1912ea..7d2c23961e7 100644 --- a/packages/types/src/thrown-http-error.ts +++ b/packages/types/src/thrown-http-error.ts @@ -197,7 +197,8 @@ export interface ThrownHttpError { * Structured context: spec-validation `issues[]`, record-validation * `fields[]`, a package-scoped refusal's `candidates[]` (#32250, * {@link packageScopedRefusalCandidates}), a declared refusal list's - * `refusals[]` (#36877, {@link declaredRefusalLines}). Absent rather than `{}` when the + * `refusals[]` (#36877, {@link declaredRefusalLines}), an address refusal's + * `holder` (#38626, {@link formAddressRefusalHolder}). Absent rather than `{}` when the * throw carried none, so an empty object never reads as "there is context * here". */ @@ -276,6 +277,40 @@ function isPackageScopedRefusalHolder(candidate: unknown): candidate is PackageS } } +/** The form a `409 FORM_ADDRESS_TAKEN` refusal names as holding the address: its item name and its package (`null`: none). */ +export interface FormAddressRefusalHolder { + readonly name: string; + readonly packageId: string | null; +} + +/** + * [#38626, ADR-0159 ruled question 3] The form that holds the public address a + * `form` write was refused for, as every door answers it in `details.holder` + * — or `undefined` for any other thrown value. + * + * `formAddressClashRefusal` (`@objectstack/metadata-protocol`) sets it on the + * refusal it throws as `holder`, beside the message that names the same form, + * so a client names the holder from the refusal instead of re-deriving the + * write rule from a list it read earlier. Recognised by SHAPE (code + * `FORM_ADDRESS_TAKEN`, a declared `409`, a `holder` with a non-empty string + * `name` and a `packageId` that is a string or `null`), the + * {@link packageScopedRefusalCandidates} precedent: this package cannot name + * the producer. Read by {@link resolveThrownHttpError} and by the REST door's + * declared-status arm, so no door carries a second recogniser. + */ +export function formAddressRefusalHolder(error: unknown): FormAddressRefusalHolder | undefined { + if (typeof error !== 'object' || error === null) return undefined; + const e = error as { code?: unknown; status?: unknown; statusCode?: unknown; holder?: unknown }; + if (e.code !== 'FORM_ADDRESS_TAKEN') return undefined; + const declared = typeof e.status === 'number' ? e.status : typeof e.statusCode === 'number' ? e.statusCode : undefined; + if (declared !== 409) return undefined; + const holder = e.holder as { name?: unknown; packageId?: unknown } | null | undefined; + if (typeof holder !== 'object' || holder === null) return undefined; + if (typeof holder.name !== 'string' || holder.name === '') return undefined; + if (holder.packageId !== null && typeof holder.packageId !== 'string') return undefined; + return { name: holder.name, packageId: holder.packageId }; +} + /** [#36877] One sentence of a declared refusal thrown as a list: the reason and its rendered sentence. */ export interface DeclaredRefusalLine { readonly reason: string; @@ -330,7 +365,7 @@ export function declaredRefusalLines(error: unknown): readonly DeclaredRefusalLi * | declaredCode | `VALIDATION_FAILED` if it is one → any non-empty string `.code` → the derived code if it is an unevaluable hook condition → absent | * | message | `.message` when it is a string → `String(error)` | * | userMessage | a non-empty string `.userMessage` → absent (see {@link declaredUserMessage}) | - * | details | a non-string `.code`, `.issues`, a validation failure's `fields`, a package-scoped refusal's `candidates`, a declared refusal list's `refusals` ({@link declaredRefusalLines}) → absent | + * | details | a non-string `.code`, `.issues`, a validation failure's `fields`, a package-scoped refusal's `candidates`, a declared refusal list's `refusals` ({@link declaredRefusalLines}), an address refusal's `holder` ({@link formAddressRefusalHolder}) → absent | * * Both status spellings are read because both are produced in this repo: * `plugin-approvals`' lifecycle hooks and `metadata-protocol` throw @@ -394,6 +429,8 @@ export function resolveThrownHttpError(error: unknown, fallbackStatus = 500): Th const candidates = packageScopedRefusalCandidates(e); // [#36877] A declared refusal thrown as a list carries its sentences. const refusals = declaredRefusalLines(e); + // [#38626] The form a `409 FORM_ADDRESS_TAKEN` names as holding the address. + const holder = formAddressRefusalHolder(e); const details: Record = { // A truthy NON-string `code` (a driver errno, say) is context and stays // context — promoting it would put a number in the field callers branch on, @@ -403,6 +440,7 @@ export function resolveThrownHttpError(error: unknown, fallbackStatus = 500): Th ...(validation ? { fields: validation.fields } : {}), ...(candidates ? { candidates } : {}), ...(refusals ? { refusals } : {}), + ...(holder ? { holder } : {}), }; const userMessage = declaredUserMessage(error); diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx index 1c91bd7b454..ff1ebcbba15 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx @@ -227,14 +227,19 @@ describe('PublicFormsSetupPage', () => { }); describe('[#37087] a switch-on refused because another form holds the address (409 FORM_ADDRESS_TAKEN)', () => { - /** The server's refusal, as the metadata client throws it. */ - const addressTaken = () => - Object.assign( - new Error( - "The form 'web_to_lead' cannot open the public address '/forms/contact-us': the form 'crm_lead.newsletter' of the package 'crm' holds it.", - ), - { status: 409, code: 'FORM_ADDRESS_TAKEN' }, - ); + /** + * The server's refusal, as the metadata client throws it: the raw body on + * `body`, the holder in its `details` (#38626), in RestServer's flat + * spelling or, `nested`, the dispatcher's. + */ + const addressTaken = (holderOf: { name: string; packageId: string | null } | null = { name: 'crm_lead.newsletter', packageId: 'crm' }, nested = false) => { + const message = "The form 'web_to_lead' cannot open the public address '/forms/contact-us': the form 'crm_lead.newsletter' of the package 'crm' holds it."; + const details = holderOf ? { details: { holder: holderOf } } : {}; + const body = nested + ? { success: false, error: { code: 'FORM_ADDRESS_TAKEN', message, ...details } } + : { error: message, code: 'FORM_ADDRESS_TAKEN', ...details }; + return Object.assign(new Error(message), { status: 409, code: 'FORM_ADDRESS_TAKEN', body }); + }; /** The form that holds the address: on, at the same slug. */ const holder = (extra: Record = {}) => form(true, { name: 'crm_lead.newsletter', label: 'Newsletter signup', title: 'Newsletter signup', ...extra }); @@ -264,8 +269,8 @@ describe('PublicFormsSetupPage', () => { expect(said()).not.toContain('cannot open the public address'); expect(said()).not.toContain('refusalServer'); expect(warn).toHaveBeenCalled(); - // The holder is read from the environment's forms, again, after the refusal. - expect(fake.listed).toEqual(['form']); + // The holder is read from the refusal: the environment's forms are not read again. + expect(fake.listed).toEqual([]); // Nothing was switched: the row stays off and no success is said. expect(fake.toast.success).not.toHaveBeenCalled(); expect(screen.getByTestId('public-form-row-web_to_lead')).toHaveAttribute('data-on', 'false'); @@ -279,29 +284,48 @@ describe('PublicFormsSetupPage', () => { fake.layered = () => ({ code: form(false), effective: form(false) }); fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); fake.save = async () => { - throw addressTaken(); + throw addressTaken({ name: 'crm_lead.newsletter', packageId: 'support' }, true); }; const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); render(, { wrapper: host(ADMIN) }); fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + // The dispatcher's nested envelope names the holder the same way. expect(said()).toContain('«publicFormsSetup.refusalAddressTaken» {\\"holder\\":\\"Contact us (Support desk)\\"}'); expect(said()).not.toContain('crm_lead.newsletter'); expect(said()).not.toContain('(support)'); warn.mockRestore(); }); - it('with no holder read, says another form holds the address and names none, never the generic server sentence', async () => { + it('[#38626] a stale list: the holder is the one the refusal names, not the form the list last saw at the address', async () => { + // The list was read while `crm_lead.newsletter` sat at `contact-us`; since then it moved to `newsletter` + // and `crm_lead.signup` took `contact-us`. The refusal names `crm_lead.signup`. + const moved = holder({ sharing: { enabled: true, allowAnonymous: true, publicLink: 'contact-us' } }); + const signup = form(true, { name: 'crm_lead.signup', label: 'Event signup', title: 'Event signup', sharing: { enabled: false, allowAnonymous: true, publicLink: 'events' } }); + fake.items = [form(false), moved, signup]; + fake.layered = () => ({ code: form(false), effective: form(false) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + fake.save = async () => { + throw addressTaken({ name: 'crm_lead.signup', packageId: 'crm' }); + }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + render(, { wrapper: host(ADMIN) }); + fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + expect(said()).toContain('«publicFormsSetup.refusalAddressTaken» {\\"holder\\":\\"Event signup\\"}'); + expect(said()).not.toContain('Newsletter signup'); + warn.mockRestore(); + }); + + it('with no holder in the refusal, says another form holds the address and names none, never the generic server sentence', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - for (const how of ['the forms read again hold no other form at the address', 'the second read fails'] as const) { + for (const how of ['the refusal carries no holder', 'the holder is not a holder'] as const) { (fake.toast.error as ReturnType).mockClear(); - fake.listFails = null; - fake.items = [form(false)]; + fake.items = [form(false), holder()]; fake.layered = () => ({ code: form(false), effective: form(false) }); fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); fake.save = async () => { - if (how === 'the second read fails') fake.listFails = 'ECONNRESET'; - throw addressTaken(); + throw how === 'the refusal carries no holder' ? addressTaken(null) : addressTaken({ name: '', packageId: 'crm' }); }; const { unmount } = render(, { wrapper: host(ADMIN) }); fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); @@ -310,7 +334,6 @@ describe('PublicFormsSetupPage', () => { '«publicFormsSetup.switchFailed» ' + JSON.stringify({ name: 'Contact us', message: '«publicFormsSetup.refusalAddressTakenUnknown»' }), ); - expect(said(), how).not.toContain('ECONNRESET'); unmount(); } warn.mockRestore(); diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx index fa74e8030d7..4aad49452c0 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx @@ -56,7 +56,7 @@ import { PublicFormSwitchRefusal, isAddressTakenRefusal, markShippedOff, - publicAddressHolderOf, + refusedAddressHolderOf, publicFormRowsOf, switchPublicForm, type PublicAddressHolder, @@ -193,20 +193,13 @@ function PublicFormsSetupBody() { } }; - /** The other form that holds `row`'s address, read from the environment's forms, with the package list; `null` when none is read. */ - const readAddressHolder = async (row: PublicFormRow): Promise => { - try { - const client: any = (adapter as any)?.getClient?.(); - if (!client?.meta?.getItems) return null; - const holder = publicAddressHolderOf(await client.meta.getItems('form'), row); - if (!holder) return null; - // Only a holder sharing the row's title is named with its package. - const packageNames = holder.title === row.title ? await fetchListedPackageManifests().catch(() => null) : null; - return { holder, packageNames }; - } catch (err) { - console.warn('[public forms] address holder read failed:', formatMetadataError(err)); - return null; - } + /** The form the refusal names as holding `row`'s address, with the package list; `null` when the refusal names none. */ + const readAddressHolder = async (row: PublicFormRow, err: unknown): Promise => { + const holder = refusedAddressHolderOf(err, read.kind === 'ready' ? read.rows : []); + if (!holder) return null; + // Only a holder sharing the row's title is named with its package. + const packageNames = holder.title === row.title ? await fetchListedPackageManifests().catch(() => null) : null; + return { holder, packageNames }; }; const flip = async (row: PublicFormRow, on: boolean) => { @@ -233,7 +226,7 @@ function PublicFormsSetupBody() { if (isAddressTakenRefusal(err)) { // The server's own words (they name both forms and their packages) go to the console log. console.warn('[public forms] switch refused:', formatMetadataError(err)); - const message = addressTakenText(t, row, await readAddressHolder(row)); + const message = addressTakenText(t, row, await readAddressHolder(row, err)); toast.error(t('publicFormsSetup.switchFailed', { name: row.title, message })); return; } diff --git a/ui/packages/app-shell/src/views/setup/publicForms.test.ts b/ui/packages/app-shell/src/views/setup/publicForms.test.ts index c6c8c5150fa..6c91b1927de 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.test.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.test.ts @@ -7,9 +7,9 @@ import { isAddressTakenRefusal, markShippedOff, overrideHoldsOnlySwitch, - publicAddressHolderOf, publicFormRowOf, publicFormRowsOf, + refusedAddressHolderOf, switchPublicForm, } from './publicForms'; @@ -98,70 +98,43 @@ describe('publicFormRowsOf', () => { }); }); -describe('[#37087] publicAddressHolderOf: the other form that holds an address', () => { - /** The form being switched on: `web_to_lead` of `crm`, at `contact-us`, switched off. */ - const row = publicFormRowOf(formItem({}, false))!; - /** Another form whose public link names the same address. */ - const other = (overrides: Record = {}, enabled = true) => - formItem({ name: 'crm_lead.newsletter', label: 'Newsletter signup', title: 'Newsletter signup', ...overrides }, enabled); +describe('[#38626] refusedAddressHolderOf: the holder the refusal names', () => { + const refusal = (body: unknown) => Object.assign(new Error('taken'), { status: 409, code: 'FORM_ADDRESS_TAKEN', body }); + const holder = { name: 'crm_lead.newsletter', packageId: 'crm' }; + /** The list the page shows: the holder under its shown name. */ + const rows = [publicFormRowOf(formItem({ name: 'crm_lead.newsletter', label: 'Newsletter signup' }))!]; - it('names the other form whose public link names the address, by the name the list shows it under', () => { - expect(publicAddressHolderOf({ items: [formItem({}, false), other()] }, row)).toEqual({ - name: 'crm_lead.newsletter', - title: 'Newsletter signup', - packageId: 'crm', - }); - // A bare array answer reads the same. - expect(publicAddressHolderOf([other(), formItem({}, false)], row)?.name).toBe('crm_lead.newsletter'); + it('reads both doors\' spellings: RestServer\'s flat body and the dispatcher\'s nested envelope', () => { + const named = { name: 'crm_lead.newsletter', title: 'Newsletter signup', packageId: 'crm' }; + expect(refusedAddressHolderOf(refusal({ error: 'x', code: 'FORM_ADDRESS_TAKEN', details: { holder } }), rows)).toEqual(named); + expect(refusedAddressHolderOf(refusal({ success: false, error: { code: 'FORM_ADDRESS_TAKEN', message: 'x', details: { holder } } }), rows)).toEqual(named); }); - it('a form holds its address switched off, and when it was never anonymous: the server counts both', () => { - expect(publicAddressHolderOf([formItem({}, false), other({}, false)], row)?.name).toBe('crm_lead.newsletter'); - const internal = other({ sharing: { enabled: true, allowAnonymous: false, publicLink: '/forms/contact-us' } }); - // Not a public form, so Setup does not list it; it holds the address all the same. - expect(publicFormRowOf(internal)).toBeNull(); - expect(publicAddressHolderOf([formItem({}, false), internal], row)?.name).toBe('crm_lead.newsletter'); - }); - - it('reads a public link as the routes do: `/forms/x`, `forms/x` and `x` are one address', () => { - for (const publicLink of ['/forms/contact-us', 'forms/contact-us', 'contact-us']) { - const holder = other({ sharing: { enabled: true, allowAnonymous: true, publicLink } }); - expect(publicAddressHolderOf([holder], row)?.name, publicLink).toBe('crm_lead.newsletter'); - } - }); - - it('the form itself is not another form: its own item, the app\'s document it overrides, and an override of it', () => { - // Its own item alone: nobody else holds the address. - expect(publicAddressHolderOf([formItem({}, false)], row)).toBeNull(); - // The row is the override an environment saved over the app's form: the app's own document is the same form. - const override = formItem({ _packageId: 'crm.custom', overrides: { package: 'crm', basedOn: '3.0.0' } }, false); - const overrideRow = publicFormRowOf(override)!; - expect(overrideRow.packageId).toBe('crm.custom'); - expect(publicAddressHolderOf([override, formItem()], overrideRow)).toBeNull(); - // The row is the app's form: an override of it is the same form. - expect(publicAddressHolderOf([formItem({}, false), override], row)).toBeNull(); - // CONTROL: beside those, a third form at the address is still named. - expect(publicAddressHolderOf([override, formItem(), other()], overrideRow)?.name).toBe('crm_lead.newsletter'); - }); - - it('a form of the same name in an unrelated package is another form', () => { - const twin = formItem({ _packageId: 'hr', label: 'HR contact' }); - expect(publicAddressHolderOf([formItem({}, false), twin], row)).toEqual({ name: 'web_to_lead', title: 'HR contact', packageId: 'hr' }); + it('a stale list: the list row\'s address does not matter, the refusal\'s holder is named by name and package', () => { + const stale = [{ ...rows[0], slug: 'newsletter' }, publicFormRowOf(formItem({}, false))!]; + expect(refusedAddressHolderOf(refusal({ details: { holder } }), stale)?.title).toBe('Newsletter signup'); + // The same name in another package is another form. + expect(refusedAddressHolderOf(refusal({ details: { holder: { ...holder, packageId: 'hr' } } }), stale)).toEqual({ + name: 'crm_lead.newsletter', + title: 'newsletter', + packageId: 'hr', + }); }); - it('a row bound to no package stands for every item of its name, as the server judges a package-less write', () => { - const loose = publicFormRowOf(formItem({ _packageId: undefined }, false))!; - expect(loose.packageId).toBeNull(); - expect(publicAddressHolderOf([formItem({ _packageId: undefined }, false), formItem()], loose)).toBeNull(); - expect(publicAddressHolderOf([formItem({ _packageId: undefined }, false), other()], loose)?.name).toBe('crm_lead.newsletter'); + it('a holder the list does not show is named by its name without the object prefix; a package-less holder reads as null', () => { + expect(refusedAddressHolderOf(refusal({ details: { holder: { name: 'crm_lead.internal', packageId: null } } }), rows)).toEqual({ + name: 'crm_lead.internal', + title: 'internal', + packageId: null, + }); }); - it('answers null when no other form holds the address, and for an answer that is not a list', () => { - const elsewhere = other({ sharing: { enabled: true, allowAnonymous: true, publicLink: 'newsletter' } }); - expect(publicAddressHolderOf([formItem({}, false), elsewhere], row)).toBeNull(); - expect(publicAddressHolderOf(undefined, row)).toBeNull(); - expect(publicAddressHolderOf({ items: 'nope' }, row)).toBeNull(); - expect(publicAddressHolderOf([null, 'x', { name: '' }, { sharing: { publicLink: 'contact-us' } }], row)).toBeNull(); + it('answers null when the refusal carries no holder, or not one', () => { + expect(refusedAddressHolderOf(refusal({ error: 'x' }), rows)).toBeNull(); + expect(refusedAddressHolderOf(refusal({ details: { holder: { name: '' } } }), rows)).toBeNull(); + expect(refusedAddressHolderOf(refusal({ details: { holder: { name: 'a', packageId: 3 } } }), rows)).toBeNull(); + expect(refusedAddressHolderOf(new Error('no body'), rows)).toBeNull(); + expect(refusedAddressHolderOf(undefined, rows)).toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/setup/publicForms.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts index a754aae869e..1c6dba76dcb 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -68,18 +68,18 @@ * ## An address another form holds * * The server refuses a switch-on that would leave two forms open on one - * address (`409 FORM_ADDRESS_TAKEN`, ADR-0159 ruled question 3). Its envelope - * names the other form in its message prose alone, so the page reads the - * environment's forms again and finds the holder by the server's own rule - * ({@link publicAddressHolderOf}): it then names both forms, the one being - * switched on and the one that holds the address (objectstack#37087). + * address (`409 FORM_ADDRESS_TAKEN`, ADR-0159 ruled question 3). The refusal + * carries the form that holds the address as data (`details.holder`), so the + * page names both forms, the one being switched on and the one that holds the + * address, from the server's answer ({@link refusedAddressHolderOf}), never + * from a second copy of the server's rule (objectstack#37087, #38626). * * Not listed here: when a form last took a submission. A submission is an * ordinary record of the form's object and records no form, so there is * nothing to read. */ -import { anonymousFormIntakeSlug, formExplicitlyWithdraws, publicFormSlug } from '@objectstack/spec/ui'; +import { anonymousFormIntakeSlug, formExplicitlyWithdraws } from '@objectstack/spec/ui'; import { errorCodeIs } from '@object-ui/types'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { @@ -202,61 +202,34 @@ export interface PublicAddressHolder { packageId: string | null; } -/** - * The slug a form's public link names, switched on or off: the address the - * server's write rule reads the form to hold (`formHeldSlug`, - * `@objectstack/metadata-protocol`). - */ -function heldSlug(form: FormDoc): string | undefined { - const link = isDoc(form.sharing) ? form.sharing.publicLink : undefined; - return typeof link === 'string' && link !== '' ? publicFormSlug(link) : undefined; +/** A `{ name, packageId }` holder, or `null` when `v` is not one. */ +function holderOf(v: unknown): Pick | null { + if (!isDoc(v) || typeof v.name !== 'string' || !v.name) return null; + if (v.packageId !== null && typeof v.packageId !== 'string') return null; + return { name: v.name, packageId: v.packageId || null }; } -const packageOf = (item: FormDoc): string | null => - typeof item._packageId === 'string' && item._packageId ? item._packageId : null; - -const overriddenPackageOf = (item: FormDoc): string | null => - isDoc(item.overrides) && typeof item.overrides.package === 'string' && item.overrides.package - ? item.overrides.package - : null; - /** - * The OTHER form that holds `row`'s address in a `GET /meta/form` answer - * (`{ items }`, or a bare array), or `null` when the answer holds none. + * The form a `409 FORM_ADDRESS_TAKEN` names as holding the address, read from + * the refusal itself (`details.holder`, `{ name, packageId }`), or `null` when + * it carries none. The two doors that serve a metadata save spell the + * envelope apart, so both are read: `RestServer`'s flat body + * (`body.details.holder`) and the runtime dispatcher's nested one + * (`body.error.details.holder`). * - * Judged as the server judges the write it refuses (module header): a form - * holds an address while its public link names it, switched on or off, so a - * switched-off holder and a form that was never anonymous both count. `row` - * itself is not "another form": the item of its name in its own package, the - * app's document that item overrides and an override of it, and, for a row - * bound to no package, every item of its name. + * Its name on the page comes from `rows` (the list the page shows), matched by + * name and package, which stay put while a form's address moves; a holder the + * list does not show is named by its name without the object prefix, as + * {@link shownName} names a form with no label. */ -export function publicAddressHolderOf( - answer: unknown, - row: Pick, -): PublicAddressHolder | null { - const items: FormDoc[] = ( - Array.isArray(answer) ? answer : isDoc(answer) && Array.isArray(answer.items) ? answer.items : [] - ).filter((item: unknown): item is FormDoc => isDoc(item) && typeof item.name === 'string' && !!item.name); - // The packages `row` stands in: its own, and the app's it overrides. - const own = new Set(); - if (row.packageId) { - own.add(row.packageId); - for (const item of items) { - if (item.name !== row.name || packageOf(item) !== row.packageId) continue; - const base = overriddenPackageOf(item); - if (base) own.add(base); - } - } - const isRow = (item: FormDoc): boolean => { - if (item.name !== row.name) return false; - if (!row.packageId) return true; - const pkg = packageOf(item); - const base = overriddenPackageOf(item); - return (pkg !== null && own.has(pkg)) || (base !== null && own.has(base)); - }; - const holder = items.find((item) => heldSlug(item) === row.slug && !isRow(item)); - return holder ? { name: holder.name, title: shownName(holder), packageId: packageOf(holder) } : null; +export function refusedAddressHolderOf(err: unknown, rows: readonly PublicFormRow[]): PublicAddressHolder | null { + const body = (err as { body?: unknown } | null | undefined)?.body; + if (!isDoc(body)) return null; + const nested = isDoc(body.error) && isDoc(body.error.details) ? body.error.details.holder : undefined; + const holder = holderOf(isDoc(body.details) ? body.details.holder : undefined) ?? holderOf(nested); + if (!holder) return null; + const listed = rows.find((r) => r.name === holder.name && r.packageId === holder.packageId); + return { ...holder, title: listed ? listed.title : shownName({ name: holder.name }) }; } /** The metadata client calls {@link switchPublicForm} makes. */ From c0a85cf0cfc5689426a0f635dd2e926ca15bfda8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:18:54 +0000 Subject: [PATCH 2/4] test(rest): PUT /meta pin reads the package query key Claude-Session: https://claude.ai/code/session_01ADHkmQu29PQequUrXXHYMn Co-authored-by: Claude --- packages/rest/src/public-form-two-type-withdrawal.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 8497ac7aacc..654e461ce90 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -1319,7 +1319,7 @@ describe('[#38626] `409 FORM_ADDRESS_TAKEN` carries the holding form as data on const res = makeRes(); await put.handler({ method: 'PUT', path: `/api/v1/meta/form/${SECOND}`, params: { type: 'form', name: SECOND }, - query: { packageId: PAIR, mode: 'draft' }, body: { ...formItem(true), name: SECOND }, headers: {}, + query: { package: PAIR, mode: 'draft' }, body: { ...formItem(true), name: SECOND }, headers: {}, } as any, res); expect([res._status, res._json?.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']); expect(res._json?.details?.holder).toEqual({ name: NAME, packageId: BASE }); From d57aac66a108a3854e425358acc49d9bfba2f78e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:22:26 +0000 Subject: [PATCH 3/4] chore: changeset for the address refusal's holder Claude-Session: https://claude.ai/code/session_01ADHkmQu29PQequUrXXHYMn Co-authored-by: Claude --- .changeset/38626-form-address-holder-details.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .changeset/38626-form-address-holder-details.md diff --git a/.changeset/38626-form-address-holder-details.md b/.changeset/38626-form-address-holder-details.md new file mode 100644 index 00000000000..23016ea391a --- /dev/null +++ b/.changeset/38626-form-address-holder-details.md @@ -0,0 +1,12 @@ +--- +'@objectstack/types': patch +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +--- + +fix: a `409 FORM_ADDRESS_TAKEN` refusal names the form that holds the address as data, in `details.holder` + +Clause-②: no +Metadata-protocol: none + +A `form` write left open on a public address another form holds is refused `409 FORM_ADDRESS_TAKEN`, as before, and the refusal now carries the holding form beside its message: `details.holder` is `{ name, packageId }` (`packageId` is `null` for a form bound to no package). Both doors that answer a metadata save carry it: `RestServer`'s `PUT /meta/:type/:name` in its flat body (`details.holder`) and the runtime dispatcher's `/meta` door in the nested envelope (`error.details.holder`). `@objectstack/types` exports the one recogniser, `formAddressRefusalHolder(error)`, and `resolveThrownHttpError` answers it in `details`. Setup's Public forms page names the holder from the refusal, so a list read before another form took the address no longer names the wrong form. From e19ef2c925757c6833d1738bda5841cf827da881 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:20:30 +0000 Subject: [PATCH 4/4] chore: changeset declares the widening of the address refusal's holder Claude-Session: https://claude.ai/code/session_01ADHkmQu29PQequUrXXHYMn Co-authored-by: Claude --- .changeset/38626-form-address-holder-details.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.changeset/38626-form-address-holder-details.md b/.changeset/38626-form-address-holder-details.md index 23016ea391a..5c894fbf59d 100644 --- a/.changeset/38626-form-address-holder-details.md +++ b/.changeset/38626-form-address-holder-details.md @@ -6,7 +6,9 @@ fix: a `409 FORM_ADDRESS_TAKEN` refusal names the form that holds the address as data, in `details.holder` -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none A `form` write left open on a public address another form holds is refused `409 FORM_ADDRESS_TAKEN`, as before, and the refusal now carries the holding form beside its message: `details.holder` is `{ name, packageId }` (`packageId` is `null` for a form bound to no package). Both doors that answer a metadata save carry it: `RestServer`'s `PUT /meta/:type/:name` in its flat body (`details.holder`) and the runtime dispatcher's `/meta` door in the nested envelope (`error.details.holder`). `@objectstack/types` exports the one recogniser, `formAddressRefusalHolder(error)`, and `resolveThrownHttpError` answers it in `details`. Setup's Public forms page names the holder from the refusal, so a list read before another form took the address no longer names the wrong form. + +Widening: `@objectstack/types` gains two exports, `formAddressRefusalHolder` and the `FormAddressRefusalHolder` type, and the `409 FORM_ADDRESS_TAKEN` body of both doors gains the `details.holder` member.