Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/38626-form-address-holder-details.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@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-②: 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.
13 changes: 9 additions & 4 deletions packages/metadata-protocol/src/protocol-form-writes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,15 +120,16 @@ 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,
type: string,
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);
Expand All @@ -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;
}

Expand Down
17 changes: 13 additions & 4 deletions packages/rest/src/error-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import {
boundedDeclaredRefusalMessage,
declaredHttpStatus,
fiveXxArmDisplacesDeclared4xx,
formAddressRefusalHolder,
isSandboxCrash,
isSandboxOrigin,
isSandboxOwnFault,
Expand Down Expand Up @@ -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<string, unknown> } {
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 } : {};
}

/**
Expand Down
31 changes: 31 additions & 0 deletions packages/rest/src/public-form-two-type-withdrawal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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: { 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 });
// 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 });
});
});
26 changes: 25 additions & 1 deletion packages/types/src/thrown-http-error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<string, unknown> = {}) => 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();
}
});
});
42 changes: 40 additions & 2 deletions packages/types/src/thrown-http-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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".
*/
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<string, unknown> = {
// 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,
Expand All @@ -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);
Expand Down
Loading
Loading