Skip to content

Commit 2d6102c

Browse files
fix(metadata-protocol): FORM_ADDRESS_TAKEN carries the holding form as details.holder; Setup reads it (#38712)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi989QTdPpQXDnsMXYfukg9Sp)_ Fixes #38626 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 管理员在设置的公开表单页打开一个表单、却因地址已被另一个表单占用而被拒时,提示里点名的占用表单改由服务器的拒绝直接给出;之前页面自己重算,列表过期时可能点错名或不点名。 - 属于公开表单(表单独立类型)那条工作线,替设置页去掉一份与服务器重复的占用规则。 - 出错时最坏是提示里说"另一个表单占用了地址"但不点名,保存本身仍被拒、不会写入;可直接撤回本 PR。 - 无 ## What changes - `@objectstack/metadata-protocol`: `formAddressClashRefusal` sets `holder: { name, packageId }` on the `409 FORM_ADDRESS_TAKEN` it throws (`packageId` is `null` for a form bound to no package). The message is unchanged. - `@objectstack/types`: one recogniser, `formAddressRefusalHolder(error)` (code `FORM_ADDRESS_TAKEN`, declared `409`, a well-shaped `holder`), read by `resolveThrownHttpError` into `details.holder`. That is the dispatcher door's answer (and every door that answers from the resolver). - `@objectstack/rest`: the declared-4xx arm of `resolveErrorResponse` (the door `RestServer`'s `PUT /meta/:type/:name` answers through) adds `details.holder` next to the existing `details.candidates` member, through the same recogniser. Measured before writing: neither door forwards a thrown `.details` (the resolver's list is closed on purpose), so the `details` thrown in `protocol-package-commits.ts` were no path to reuse. - Setup (`ui/packages/app-shell`): `refusedAddressHolderOf(err, rows)` reads the holder off the refusal in both door spellings (`body.details.holder` flat, `body.error.details.holder` nested). The page no longer re-reads the form list, and `heldSlug` and `publicAddressHolderOf` (the local copy of the server's rule) are deleted. The user-facing wording from #38678 is kept: the holder is named by its shown title, plus its package display name when the titles match. Only the data source changed. The title comes from the list the page shows, matched by name and package (stable, unlike the slug). A holder the list does not show (a form that is not anonymous) is named by its name without the object prefix. - `Clause-②: yes (widening)` (after L1-a REWORK 7271615422): `@objectstack/types` gains two exports from its `.` entry, `formAddressRefusalHolder` and `FormAddressRefusalHolder`, and both doors' `409 FORM_ADDRESS_TAKEN` bodies gain `details.holder`, inside the error envelope's declared open slot (`details`), the same shape as the `details.candidates` precedent. Nothing is narrowed; the level stays patch. ## Tests - `packages/rest/src/public-form-two-type-withdrawal.test.ts` (a new top-level describe in the shared harness): a real protocol on SQLite. RestServer's registered `PUT /api/v1/meta/:type/:name` answers `409` with `code: FORM_ADDRESS_TAKEN` and `details.holder`. The same refusal thrown by the real `saveMetaItem`, passed through `thrownAnswerOf` (the dispatcher's resolver), answers the same `status`, `code` and `details.holder`. - `packages/types/src/thrown-http-error.test.ts`: the holder is carried, a package-less holder included, and both status spellings are read. CONTROL: another code, another status, or a malformed holder carries nothing. - `ui/.../setup/publicForms.test.ts` and `PublicFormsSetupPage.test.tsx`: both door spellings are read. A **stale-list** case: the list was read while form A sat at the address, then A moved and form B took it. The refusal names B and the page says B, never A. No form-list read follows the refusal. With no holder, or a malformed one, the page says another form holds the address and names none. - Ablations (each mutated on disk, run red, restored with `git checkout HEAD`): dropping the REST member reds the PUT pin (`details.holder` undefined). Dropping the resolver member reds the types case. Dropping the flat-body read reds 5 UI cases, the stale-list case included. ## Acceptance notes - Measured: the `details` objects thrown in `packages/metadata-protocol/src/protocol-package-commits.ts` (`targetPackageId`, `owners`, `collisions`) are dropped by both HTTP doors. This was found by reading the code, with no reproduction through a public door, so it is noted here and not filed. - A holder the page does not list is now named by its name without the object prefix, where the old list re-read used its label. That form is never a public form, so the page never showed its title. - Changed lines are about 390 without the changeset, over the dispatch's estimate of about 200: 159 are deletions (the re-derivation and its tests), and the rest are both-door tests and docblocks. ## Verification Read first, by risk: 1. `packages/rest/src/error-response.ts` `declaredDetailsMember`: it now runs on every route's declared-4xx answer, gated on the recogniser. 2. `packages/types/src/thrown-http-error.ts` `formAddressRefusalHolder`: the shape gate. 3. `ui/packages/app-shell/src/views/setup/publicForms.ts` `refusedAddressHolderOf`: the two spellings. Two-minute check: `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/public-form-two-type-withdrawal.test.ts -t 38626` should show 1 passed. <details><summary>Local readings (head d57aac6)</summary> - types `thrown-http-error.test.ts`: 27/27 passed. rest `public-form-two-type-withdrawal.test.ts`: 64/64 passed. - ui `publicForms.test.ts`, `PublicFormsSetupPage.test.tsx`, `publicFormDesign.test.ts`: 3 files, 82/82 passed. - `typecheck` for types, metadata-protocol and rest: exit 0. UI `type-check`: NOT MEASURED, because the ui closure was not built locally; left to `Type Check UI`. - `dispatch-gates --ran`: 76 derived, 74 exit 0, 2 NOT MEASURED, both exit 3 PREREQUISITE NOT MET (`check-plugin-teardown-shape --self-test` needs an unshallow clone, `check:dual-build-cjs-loads` needs a full build). CI runs both. - `check-platform-checklist --changed-from origin/main`: 0 anchored files. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQu29PQequUrXXHYMn)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmQu29PQequUrXXHYMn <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmQu29PQequUrXXHYMn --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e130fd4 commit 2d6102c

10 files changed

Lines changed: 242 additions & 159 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/types': patch
3+
'@objectstack/metadata-protocol': patch
4+
'@objectstack/rest': patch
5+
---
6+
7+
fix: a `409 FORM_ADDRESS_TAKEN` refusal names the form that holds the address as data, in `details.holder`
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
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.

‎packages/metadata-protocol/src/protocol-form-writes.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -120,15 +120,16 @@ export function formHeldSlug(form: unknown): string | undefined {
120120
* refusal on the new type only: an old-shape `view` write keeps today's
121121
* first-match behaviour.
122122
*
123-
* `409`, code {@link FORM_ADDRESS_TAKEN}.
123+
* `409`, code {@link FORM_ADDRESS_TAKEN}, with the holding form as `holder`
124+
* (`{ name, packageId }`), answered as `details.holder`.
124125
*/
125126
export async function formAddressClashRefusal(
126127
host: FormReadHost,
127128
type: string,
128129
item: unknown,
129130
name: string,
130131
packageId: string | null | undefined,
131-
): Promise<(Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409 }) | undefined> {
132+
): Promise<(Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409; holder: { name: string; packageId: string | null } }) | undefined> {
132133
if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'form') return undefined;
133134
if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
134135
const slug = anonymousFormIntakeSlug((item as { sharing?: unknown }).sharing);
@@ -149,14 +150,18 @@ export async function formAddressClashRefusal(
149150
return true;
150151
}) as { name?: unknown; _packageId?: unknown } | undefined;
151152
if (holder === undefined) return undefined;
152-
const owner = typeof holder._packageId === 'string' && holder._packageId !== '' ? ` of the package '${holder._packageId}'` : '';
153+
const holderPkg = typeof holder._packageId === 'string' && holder._packageId !== '' ? holder._packageId : null;
154+
const owner = holderPkg !== null ? ` of the package '${holderPkg}'` : '';
153155
const err = new Error(
154156
`The form '${name}' cannot open the public address '/forms/${slug}': the form '${String(holder.name)}'${owner} `
155157
+ `holds it. Give '${name}' another public link, or clear the link of '${String(holder.name)}' first. A form `
156158
+ `holds an address while its public link names it, switched on or off.`,
157-
) as Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409 };
159+
) as Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409; holder: { name: string; packageId: string | null } };
158160
err.code = FORM_ADDRESS_TAKEN;
159161
err.status = 409;
162+
// [#38626] The holder as data, which every door answers in
163+
// `details.holder` (`formAddressRefusalHolder`, `@objectstack/types`).
164+
err.holder = { name: String(holder.name), packageId: holderPkg };
160165
return err;
161166
}
162167

‎packages/rest/src/error-response.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import {
6161
boundedDeclaredRefusalMessage,
6262
declaredHttpStatus,
6363
fiveXxArmDisplacesDeclared4xx,
64+
formAddressRefusalHolder,
6465
isSandboxCrash,
6566
isSandboxOrigin,
6667
isSandboxOwnFault,
@@ -641,17 +642,25 @@ function resolveErrorResponse(error: any, object?: string, options?: RouteErrorO
641642
: thrownCodeFields(error, error.status)),
642643
...(Array.isArray(error.issues) ? { issues: error.issues } : {}),
643644
...(object ? { object } : {}),
644-
...packageScopedCandidatesMember(error, options),
645+
...declaredDetailsMember(error, options),
645646
},
646647
});
647648
}
648649
return mapDataError(error, object);
649650
}
650651

651-
/** [#32201] The `details.candidates` member {@link RouteErrorOptions} asks for, or nothing. */
652-
function packageScopedCandidatesMember(error: unknown, options: RouteErrorOptions | undefined): { details?: { candidates: readonly PackageScopedHolder[] } } {
652+
/**
653+
* The `details` member of a declared-status refusal, or nothing: [#32201] the
654+
* `details.candidates` {@link RouteErrorOptions} asks for, and [#38626] the
655+
* form a `409 FORM_ADDRESS_TAKEN` names as holding the address
656+
* (`details.holder`, read by `@objectstack/types`' one recogniser, as the
657+
* dispatcher door's `resolveThrownHttpError` reads it), on every route.
658+
*/
659+
function declaredDetailsMember(error: unknown, options: RouteErrorOptions | undefined): { details?: Record<string, unknown> } {
653660
const candidates = options?.packageScopedCandidates ? packageScopedRefusalCandidates(error) : undefined;
654-
return candidates ? { details: { candidates } } : {};
661+
const holder = formAddressRefusalHolder(error);
662+
const details = { ...(candidates ? { candidates } : {}), ...(holder ? { holder } : {}) };
663+
return Object.keys(details).length > 0 ? { details } : {};
655664
}
656665

657666
/**

‎packages/rest/src/public-form-two-type-withdrawal.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
hashSpec,
3232
} from '@objectstack/metadata-core';
3333
import { readFileSync } from 'node:fs';
34+
import { thrownAnswerOf } from '@objectstack/types';
3435
import { RestServer } from './rest-server';
3536

3637
const BASE = 'com.example.forms37086';
@@ -1302,3 +1303,33 @@ describe('[ADR-0067 D2] a package publish refused part-way on an engine that can
13021303
});
13031304
}
13041305
});
1306+
1307+
describe('[#38626] `409 FORM_ADDRESS_TAKEN` carries the holding form as data on both doors', () => {
1308+
const engines: ObjectQL[] = [];
1309+
afterAll(async () => {
1310+
for (const engine of engines) await engine.destroy().catch(() => {});
1311+
});
1312+
const SECOND = `${OBJECT}.second`;
1313+
1314+
it('RestServer\'s PUT answers `details.holder`; the dispatcher\'s resolver answers the same thrown refusal with it', async () => {
1315+
const b = await boot({ forms: [formItem(true)] });
1316+
engines.push(b.engine);
1317+
await b.install(PAIR);
1318+
// RestServer's door: the registered `PUT /meta/:type/:name` handler, as an authoring caller.
1319+
(b.rest as any).resolveExecCtx = async () => ({ userId: 'u_author', isSystem: true });
1320+
const put = b.rest.getRoutes().find((r: any) => r.method === 'PUT' && r.path === '/api/v1/meta/:type/:name')!;
1321+
const res = makeRes();
1322+
await put.handler({
1323+
method: 'PUT', path: `/api/v1/meta/form/${SECOND}`, params: { type: 'form', name: SECOND },
1324+
query: { package: PAIR, mode: 'draft' }, body: { ...formItem(true), name: SECOND }, headers: {},
1325+
} as any, res);
1326+
expect([res._status, res._json?.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']);
1327+
expect(res._json?.details?.holder).toEqual({ name: NAME, packageId: BASE });
1328+
// The dispatcher's door: the same refusal, thrown by the real save, through the resolver it answers with.
1329+
const thrown = await b.protocol.saveMetaItem({ type: 'form', name: SECOND, packageId: PAIR, mode: 'draft', item: { ...formItem(true), name: SECOND } })
1330+
.then(() => undefined, (e: unknown) => e);
1331+
const answer = thrownAnswerOf(thrown, 500);
1332+
expect([answer.status, answer.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']);
1333+
expect(answer.details?.holder).toEqual({ name: NAME, packageId: BASE });
1334+
});
1335+
});

‎packages/types/src/thrown-http-error.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
// side-channel, because all three call this function.
1414

1515
import { describe, it, expect } from 'vitest';
16-
import { declaredRefusalLines, declaredUserMessage, packageScopedRefusalCandidates, resolveThrownHttpError } from './thrown-http-error.js';
16+
import { declaredRefusalLines, declaredUserMessage, formAddressRefusalHolder, packageScopedRefusalCandidates, resolveThrownHttpError } from './thrown-http-error.js';
1717
import { thrownAnswerOf } from './actions-door-answer.js';
1818
import { mapDataError } from './data-error-classification.js';
1919

@@ -250,3 +250,27 @@ describe('[#36877] declaredRefusalLines — a declared refusal thrown as a reaso
250250
expect(mapDataError(refusal({ refusals: undefined }), 'expense').body.details).toBeUndefined();
251251
});
252252
});
253+
254+
describe('[#38626] resolveThrownHttpError carries an address refusal\'s holder as `details.holder`', () => {
255+
const refusal = (extra: Record<string, unknown> = {}) => Object.assign(
256+
new Error("The form 'b' cannot open the public address '/forms/x': the form 'a' holds it."),
257+
{ code: 'FORM_ADDRESS_TAKEN', status: 409, holder: { name: 'crm_lead.a', packageId: 'crm' }, ...extra },
258+
);
259+
260+
it('resolves 409 FORM_ADDRESS_TAKEN with the holder, a package-less holder included', () => {
261+
const resolved = resolveThrownHttpError(refusal(), 500);
262+
expect([resolved.status, resolved.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']);
263+
expect(resolved.details).toEqual({ holder: { name: 'crm_lead.a', packageId: 'crm' } });
264+
expect(resolveThrownHttpError(refusal({ holder: { name: 'a', packageId: null } }), 500).details)
265+
.toEqual({ holder: { name: 'a', packageId: null } });
266+
expect(formAddressRefusalHolder(refusal({ status: undefined, statusCode: 409 }))).toEqual({ name: 'crm_lead.a', packageId: 'crm' });
267+
});
268+
269+
it('CONTROL: another code, another status, or a holder of another shape carries no holder', () => {
270+
expect(resolveThrownHttpError(refusal({ code: 'RESOURCE_CONFLICT' }), 500).details).toBeUndefined();
271+
expect(resolveThrownHttpError(refusal({ status: 400 }), 500).details).toBeUndefined();
272+
for (const holder of [undefined, null, 'a', { name: '' }, { name: 'a' }, { name: 'a', packageId: 3 }]) {
273+
expect(resolveThrownHttpError(refusal({ holder }), 500).details, JSON.stringify(holder)).toBeUndefined();
274+
}
275+
});
276+
});

‎packages/types/src/thrown-http-error.ts‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,8 @@ export interface ThrownHttpError {
197197
* Structured context: spec-validation `issues[]`, record-validation
198198
* `fields[]`, a package-scoped refusal's `candidates[]` (#32250,
199199
* {@link packageScopedRefusalCandidates}), a declared refusal list's
200-
* `refusals[]` (#36877, {@link declaredRefusalLines}). Absent rather than `{}` when the
200+
* `refusals[]` (#36877, {@link declaredRefusalLines}), an address refusal's
201+
* `holder` (#38626, {@link formAddressRefusalHolder}). Absent rather than `{}` when the
201202
* throw carried none, so an empty object never reads as "there is context
202203
* here".
203204
*/
@@ -276,6 +277,40 @@ function isPackageScopedRefusalHolder(candidate: unknown): candidate is PackageS
276277
}
277278
}
278279

280+
/** The form a `409 FORM_ADDRESS_TAKEN` refusal names as holding the address: its item name and its package (`null`: none). */
281+
export interface FormAddressRefusalHolder {
282+
readonly name: string;
283+
readonly packageId: string | null;
284+
}
285+
286+
/**
287+
* [#38626, ADR-0159 ruled question 3] The form that holds the public address a
288+
* `form` write was refused for, as every door answers it in `details.holder`
289+
* — or `undefined` for any other thrown value.
290+
*
291+
* `formAddressClashRefusal` (`@objectstack/metadata-protocol`) sets it on the
292+
* refusal it throws as `holder`, beside the message that names the same form,
293+
* so a client names the holder from the refusal instead of re-deriving the
294+
* write rule from a list it read earlier. Recognised by SHAPE (code
295+
* `FORM_ADDRESS_TAKEN`, a declared `409`, a `holder` with a non-empty string
296+
* `name` and a `packageId` that is a string or `null`), the
297+
* {@link packageScopedRefusalCandidates} precedent: this package cannot name
298+
* the producer. Read by {@link resolveThrownHttpError} and by the REST door's
299+
* declared-status arm, so no door carries a second recogniser.
300+
*/
301+
export function formAddressRefusalHolder(error: unknown): FormAddressRefusalHolder | undefined {
302+
if (typeof error !== 'object' || error === null) return undefined;
303+
const e = error as { code?: unknown; status?: unknown; statusCode?: unknown; holder?: unknown };
304+
if (e.code !== 'FORM_ADDRESS_TAKEN') return undefined;
305+
const declared = typeof e.status === 'number' ? e.status : typeof e.statusCode === 'number' ? e.statusCode : undefined;
306+
if (declared !== 409) return undefined;
307+
const holder = e.holder as { name?: unknown; packageId?: unknown } | null | undefined;
308+
if (typeof holder !== 'object' || holder === null) return undefined;
309+
if (typeof holder.name !== 'string' || holder.name === '') return undefined;
310+
if (holder.packageId !== null && typeof holder.packageId !== 'string') return undefined;
311+
return { name: holder.name, packageId: holder.packageId };
312+
}
313+
279314
/** [#36877] One sentence of a declared refusal thrown as a list: the reason and its rendered sentence. */
280315
export interface DeclaredRefusalLine {
281316
readonly reason: string;
@@ -330,7 +365,7 @@ export function declaredRefusalLines(error: unknown): readonly DeclaredRefusalLi
330365
* | declaredCode | `VALIDATION_FAILED` if it is one → any non-empty string `.code` → the derived code if it is an unevaluable hook condition → absent |
331366
* | message | `.message` when it is a string → `String(error)` |
332367
* | userMessage | a non-empty string `.userMessage` → absent (see {@link declaredUserMessage}) |
333-
* | 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 |
368+
* | 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 |
334369
*
335370
* Both status spellings are read because both are produced in this repo:
336371
* `plugin-approvals`' lifecycle hooks and `metadata-protocol` throw
@@ -394,6 +429,8 @@ export function resolveThrownHttpError(error: unknown, fallbackStatus = 500): Th
394429
const candidates = packageScopedRefusalCandidates(e);
395430
// [#36877] A declared refusal thrown as a list carries its sentences.
396431
const refusals = declaredRefusalLines(e);
432+
// [#38626] The form a `409 FORM_ADDRESS_TAKEN` names as holding the address.
433+
const holder = formAddressRefusalHolder(e);
397434
const details: Record<string, unknown> = {
398435
// A truthy NON-string `code` (a driver errno, say) is context and stays
399436
// 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
403440
...(validation ? { fields: validation.fields } : {}),
404441
...(candidates ? { candidates } : {}),
405442
...(refusals ? { refusals } : {}),
443+
...(holder ? { holder } : {}),
406444
};
407445

408446
const userMessage = declaredUserMessage(error);

0 commit comments

Comments
 (0)