Skip to content

Commit c23e556

Browse files
fix(metadata-protocol): a 422 INVALID_METADATA issue entry carries its zod issue's params (#37962)
repo:objectstack#3 · os-tesla · session_01L9qibyUSf2nKJWW6qBemSU <!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoCSEGDBy5L8NnTLNqGDmXLf)_ Fixes #36594 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:保存元数据被拒时,返回的每条问题除了原有的路径、说明和通用代码外,还会带上规则自己的具体原因码(例如主从对象的主字段不可写),调用方不必再靠英文句子猜是哪条规则。 - 为什么做:属于“搭建应用”专题,替通过接口保存元数据的客户端和智能体解决“只看到 custom、看不到具体原因码”的问题。 - 出错会怎样:只是在拒绝回复里多加一个字段,原有字段一个不动;若有问题,最坏是多出的字段内容不对,可直接撤回本次改动。 - 要你做什么:无。 ## What changes Revised after the contract review FAIL (record 7219293041, L1 REWORK 7219317393). Round 2 closes M1, S1, S2 and N1-N3. - `packages/metadata-protocol/src/protocol-metadata-issues.ts`: `MetadataIssueEntry` gains an optional `params?: Record<string, string | number | boolean>`. `zodIssuesToMetadataIssues` takes a new option, `{ refusalParams?: boolean }`, threaded through `collectMetadataIssues`. Only when it is set does an entry carry `params`. Three limits apply: - **Registered codes only:** an issue gets the member only when its `params.code` is a string `ErrorCode` accepts. Internal markers (`readAsWritten`, `refusalHead`, `retiredComponentType`) never reach the wire. - **JSON scalars only:** only string, finite-number and boolean members are copied. A BigInt, a cycle, a function or NaN is left out, so answering cannot throw, and the copy shares nothing with the issue (S1, S2, N3). - **Entry shape unchanged otherwise:** `code` is still `String(issue.code)`, `'custom'` for a refinement, and the de-duplication key is unchanged. - `packages/metadata-protocol/src/protocol-save.ts`: the save door's 422 (`saveMetaItem`, the spec-validation refusal) is the one caller that passes `{ refusalParams: true }`. Every other caller is unchanged, so `_diagnostics.errors[]` (`parseDiagnostics`, whose cached verdict `copyDiagnostics` copies one level deep), `seedApplied.issues[]` (`seedRequestValidationError`) and the unmanaged-install 400 keep exactly `path` / `message` / `code`. That is the shape `MetadataValidationResultSchema` and the publish response declare (M1). - `packages/spec/src/api/error-code-ledger.zod.ts` (the `CONTROLLED_BY_PARENT_MASTER_INVALID` comment) and `packages/spec/src/data/controlled-by-parent-master.ts` (the constant's docblock): both said the save door's 422 never carries `params`. Both now say the 422's `issues[]` entry carries the code on `params.code`, and that the read path's `_diagnostics.errors[]` does not. The ledger comment now spells out `door: 'none'` as "no door answers with this code as its `error.code`" (N1). Comment and TSDoc only. - `.changeset/36594-metadata-issue-params.md`: `patch` on both packages. AGENTS.md Post-Task Checklist step 3 sets the level by the `Metadata-protocol` kind, and "a non-protocol change, widening or breaking, ships `patch`". This change widens the 422 wire entry (`Clause-②: yes (widening)`) but changes nothing a metadata author can write (`Metadata-protocol: none`). `PLUGIN_UI_REQUIRED_KEY_MISSING` is named as a `PluginSchema` example, not a save-door one (N2). The REST error answer spreads `error.issues` unchanged (`packages/rest/src/error-response.ts`, the `issues` member), so the HTTP 422 body carries `params` with no REST change. ## Tests The new top-level `describe` in `packages/metadata-protocol/src/protocol.save-union-issues.test.ts` (the save door's issue-mapping harness: the real repository write path over a stub engine) has 7 cases: - `CONTROLLED_BY_PARENT_MASTER_INVALID` over `saveMetaItem`: an object save with a `readonly` master answers 422 `INVALID_METADATA` with exactly `[{ path: 'fields', code: 'custom', message, params: { code: 'CONTROLLED_BY_PARENT_MASTER_INVALID', shape: 'master-not-writable' } }]`, and nothing is stored. - Control over `saveMetaItem`: an issue zod raised without params (`label: 42`) gets no `params` own property. - Over `saveMetaItem`: a refusal whose params also hold a BigInt, a cycle, a function and NaN still answers 422 `INVALID_METADATA`. The entry keeps only `code`, `shape` and the scalar members, and `JSON.stringify` of the issues does not throw. The door is reached through a `registerMetadataTypeSchema('object', …)` override, restored in `finally` and checked restored. - `PLUGIN_UI_REQUIRED_KEY_MISSING`: the real `PluginSchema` refusal through the mapper with the door's option gives `{ path: 'staticPath', code: 'custom', params: { code: 'PLUGIN_UI_REQUIRED_KEY_MISSING', key: 'staticPath' } }`. It is not tested over `saveMetaItem` because no metadata type the save door accepts parses with `PluginSchema` on this tree. Measured: registering `PluginSchema` for a new type name and saving under it answers `INVALID_REQUEST` before any schema runs. - Params whose `code` is not a registered error code (`readAsWritten`, `retiredComponentType`, an unregistered string, a number, an array, null) give no `params`. - READ PATH: `decorateMetadataItem('object', …)` on the same refused object gives `_diagnostics.errors` of exactly `[{ path, message, code }]`. - SEED: `seedRequestValidationError` over an issue carrying CBP params gives `issues` with no `params`. ## Acceptance notes - No `ui/` consumer reads `params` from the 422 yet. Studio parses locally and already reads the code off the zod issue. The two `ui/` read-path mirrors the review named (`draftVerdict.ts`, `metadata-client.ts`) describe `_diagnostics`, which stays three keys, so they still match. - `packages/spec/CHANGELOG.md` still holds the released sentence "never `params`". It is release-owned and left alone. ## Verification Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 src/protocol.save-union-issues.test.ts -t 36594`. Expect 7 passed. Read first, by risk: 1. `packages/metadata-protocol/src/protocol-metadata-issues.ts`: `refusalParamsOf`, the option, and where `collectMetadataIssues` reads it. 2. `packages/metadata-protocol/src/protocol-save.ts`: the one call that passes `{ refusalParams: true }`. 3. The new `describe` at the foot of `protocol.save-union-issues.test.ts`. Local readings at head `ddbd5578`: <details><summary>Package tests and typecheck</summary> `pnpm --filter @objectstack/metadata-protocol typecheck && pnpm --filter @objectstack/metadata-protocol test` under the verify lock: `VERDICT command-exit 0`, Test Files 372 passed, 9 skipped (381); Tests 23605 passed, 45 skipped. </details> <details><summary>Ablation, four legs</summary> Each leg used `node scripts/ablation-replace.mjs` on `protocol-metadata-issues.ts` or `protocol-save.ts`, ran the new describe, and restored with blob == HEAD and an empty `git diff HEAD`. - A: the save door drops `{ refusalParams: true }`. The CBP and BigInt cases go red. - B: the option defaults on. The READ PATH and SEED cases go red. - C: the scalar filter is removed. The BigInt case goes red. - D: the registered-code gate is removed (anchor 1 -> 0, blob 49c9d69 -> 300da885). The markers case goes red: 1 failed, 6 passed. </details> <details><summary>Derived gate families</summary> `node scripts/pm/dispatch-gates.mjs --ran` on a record carrying each exit code: `98 derived famil(ies) accounted for — 97 run, 1 NOT-MEASURED`. The NOT-MEASURED one is `node scripts/check-plugin-teardown-shape.mjs --self-test` (checker health only, exit 3: its positive control is pinned to a commit this shallow clone cannot reach; CI's "Lint · scoped · tooling self-tests" is green). </details> CI on `ddbd5578`: every check green except `Test UI (13/16)`, one case in `StudioRoute.metadataArea-28561.test.tsx` that passes locally at this head and on this head merged with `origin/main` (3 runs, 33/33 each). See the PR comment. Changed lines: 255 (+238 / -17) across 6 files, under the 3000 threshold. Dogfood battery: not owed (no `!` in the title, no narrowing arm). --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibzQhDYnejPUPpyJvyc)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9a274e6 commit c23e556

6 files changed

Lines changed: 238 additions & 17 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
fix(metadata-protocol): a `422 INVALID_METADATA` issue entry carries the registered refusal on `params`, so a client of the save door can read the code
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
A spec rule that owns a registered error code stamps it on its zod issue as `params.code`, next to the fields that say which fix applies: `CONTROLLED_BY_PARENT_MASTER_INVALID` with `shape` (an object save), and `PLUGIN_UI_REQUIRED_KEY_MISSING` with `key` (`PluginSchema`, which no save-door type parses today). zod reports every such rule with its own issue code `'custom'`. The metadata save door's `422 INVALID_METADATA` built each `issues[]` entry from `path`, `message` and that `'custom'` only, so a client of the door (anything that does not parse locally the way Studio does) could not tell which rule refused the body except by its English message.
12+
13+
- **`@objectstack/metadata-protocol`.** The save door's 422 entry gains an optional `params` member: the registered refusal the issue carries, present only when the issue's `params.code` is a registered error code, and holding only its string, finite-number and boolean members. An object save refused for a `controlled_by_parent` master now answers `{ path: 'fields', code: 'custom', message, params: { code: 'CONTROLLED_BY_PARENT_MASTER_INVALID', shape: 'master-not-writable' } }`. Read the registered code from `params.code`. `zodIssuesToMetadataIssues` takes a new option, `refusalParams`, which only the save door sets. The read path's `_diagnostics.errors[]` and the seed refusal's `seedApplied.issues[]` keep exactly `path`, `message` and `code`, the shape their spec schemas publish.
14+
- **`@objectstack/spec`.** The `CONTROLLED_BY_PARENT_MASTER_INVALID` docblock and its ledger note now say the save door's 422 carries the code on `params.code`.
15+
16+
Nothing to migrate. The entry's `code` is unchanged (still zod's issue code, `'custom'` for these rules), and an entry that carries no registered refusal gets no `params` member, so a client that matches `code` or compares whole entries for other issues reads exactly what it read before.

‎packages/metadata-protocol/src/protocol-metadata-issues.ts‎

Lines changed: 80 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

3+
import { ErrorCode } from '@objectstack/spec/api';
4+
35
// [#25467 E0] Part of the module preamble of `protocol.ts`, moved here verbatim: the metadata
46
// issue entry and the Zod-issue walk that turns a parse failure into located metadata issues.
57
//
@@ -20,6 +22,36 @@ export interface MetadataIssueEntry {
2022
path: string;
2123
message: string;
2224
code: string | undefined;
25+
/**
26+
* The registered refusal a spec rule stamped on the issue, on the save
27+
* door's `422 INVALID_METADATA` only: `params.code` is the ADR-0112 code
28+
* (one {@link ErrorCode} accepts) and its siblings say which fix applies —
29+
* `CONTROLLED_BY_PARENT_MASTER_INVALID` with its `shape`. zod raises every
30+
* such rule with its own issue code `'custom'`, so without this member a
31+
* client of the door had only that `'custom'` and the English `message`,
32+
* while a local `safeParse` (Studio's path) saw the registered code.
33+
*
34+
* The contract, and why each limit is there:
35+
*
36+
* - **Only where asked for** ({@link ZodIssuesToMetadataIssuesOptions}).
37+
* The save door asks. The read path (`_diagnostics.errors[]`) and the
38+
* seed refusal (`seedApplied.issues[]`) do not: their published spec
39+
* schemas (`MetadataValidationResultSchema`, the publish response)
40+
* declare the entry as exactly `path` / `message` / `code`.
41+
* - **Only a registered refusal.** An issue whose `params.code` is not a
42+
* string {@link ErrorCode} accepts gets no member: `params` is also where
43+
* spec rules keep internal markers (`readAsWritten`, `refusalHead`,
44+
* `retiredComponentType`) that are not a wire vocabulary.
45+
* - **Only JSON scalars** (a string, a finite number, a boolean). Any other
46+
* value is left out, so answering never throws on a value
47+
* `JSON.stringify` cannot write, and the copy shares nothing with the
48+
* issue.
49+
*
50+
* Absent otherwise, never an empty placeholder. Additive: `code` above
51+
* stays zod's own issue code, so a client that matches `'custom'` today
52+
* still matches it. Read the registered code from `params.code`.
53+
*/
54+
params?: Record<string, string | number | boolean>;
2355
}
2456

2557
/**
@@ -121,6 +153,38 @@ interface ZodIssueLike {
121153
code?: unknown;
122154
errors?: unknown;
123155
issues?: unknown;
156+
params?: unknown;
157+
}
158+
159+
/**
160+
* The registered refusal an issue carries on `params`, as
161+
* {@link MetadataIssueEntry.params} states it: `undefined` unless `params` is
162+
* a plain object whose `code` is a string {@link ErrorCode} accepts, and then
163+
* only its JSON-scalar members.
164+
*/
165+
function refusalParamsOf(issue: ZodIssueLike): Record<string, string | number | boolean> | undefined {
166+
const params = issue?.params;
167+
if (params === null || typeof params !== 'object' || Array.isArray(params)) return undefined;
168+
const code = (params as { code?: unknown }).code;
169+
if (typeof code !== 'string' || !ErrorCode.safeParse(code).success) return undefined;
170+
const out: Record<string, string | number | boolean> = {};
171+
for (const [key, value] of Object.entries(params as Record<string, unknown>)) {
172+
if (typeof value === 'string' || typeof value === 'boolean'
173+
|| (typeof value === 'number' && Number.isFinite(value))) {
174+
out[key] = value;
175+
}
176+
}
177+
return out;
178+
}
179+
180+
/** How {@link zodIssuesToMetadataIssues} renders its entries. */
181+
export interface ZodIssuesToMetadataIssuesOptions {
182+
/**
183+
* Carry each issue's registered refusal on {@link MetadataIssueEntry.params}.
184+
* The save door's `422 INVALID_METADATA` sets it; a producer whose entry
185+
* shape a spec schema declares closed leaves it off.
186+
*/
187+
readonly refusalParams?: boolean;
124188
}
125189

126190
/** A zod issue path, normalised to the array zod always produces. */
@@ -281,6 +345,7 @@ function collectMetadataIssues(
281345
depth: number,
282346
seen: Set<string>,
283347
out: MetadataIssueEntry[],
348+
refusalParams: boolean,
284349
): void {
285350
const path = [...parentPath, ...issuePathOf(issue)];
286351
const branches: readonly (readonly ZodIssueLike[])[] =
@@ -302,6 +367,8 @@ function collectMetadataIssues(
302367
message: String(issue?.message ?? 'Invalid value'),
303368
code: issue?.code === undefined ? undefined : String(issue.code),
304369
};
370+
const params = refusalParams ? refusalParamsOf(issue) : undefined;
371+
if (params !== undefined) entry.params = params;
305372

306373
if (!expandable) {
307374
const key = JSON.stringify([entry.path, entry.code, entry.message]);
@@ -315,7 +382,7 @@ function collectMetadataIssues(
315382
const below: MetadataIssueEntry[] = [];
316383
for (const branch of selectUnionBranches(branches)) {
317384
for (const nested of branch) {
318-
collectMetadataIssues(nested, path, depth + 1, seen, below);
385+
collectMetadataIssues(nested, path, depth + 1, seen, below, refusalParams);
319386
}
320387
}
321388
// The head stays ahead of what it explains unless BOTH hold: something
@@ -328,7 +395,7 @@ function collectMetadataIssues(
328395
out.push(entry);
329396
// Unranked, and every one of them: see {@link CONTAINER_ISSUE_CODES}.
330397
for (const nested of contained) {
331-
collectMetadataIssues(nested, path, depth + 1, seen, out);
398+
collectMetadataIssues(nested, path, depth + 1, seen, out, refusalParams);
332399
}
333400
}
334401

@@ -367,14 +434,23 @@ function collectMetadataIssues(
367434
* entry below explains it (#35400, on {@link collectMetadataIssues}), so
368435
* `issues[0]` of a refused view save is the first located cause, not that
369436
* rootless line. Read entries by `path` and `code`, never by index.
437+
*
438+
* With `refusalParams` (the save door's 422), an entry also carries its
439+
* issue's registered refusal ({@link MetadataIssueEntry.params}): that is where
440+
* a spec rule with a registered code says which one it is, since `code` is
441+
* zod's `'custom'`. Without it every entry is exactly `path` / `message` /
442+
* `code`, the shape the read path and the seed refusal publish.
370443
*/
371-
export function zodIssuesToMetadataIssues(issues: unknown): MetadataIssueEntry[] {
444+
export function zodIssuesToMetadataIssues(
445+
issues: unknown,
446+
options: ZodIssuesToMetadataIssuesOptions = {},
447+
): MetadataIssueEntry[] {
372448
if (!Array.isArray(issues)) return [];
373449
const out: MetadataIssueEntry[] = [];
374450
for (const issue of issues) {
375451
// A fresh `seen` per top-level issue: de-duplication is about one
376452
// union's branches agreeing, never about two independent issues.
377-
collectMetadataIssues(issue as ZodIssueLike, [], 0, new Set<string>(), out);
453+
collectMetadataIssues(issue as ZodIssueLike, [], 0, new Set<string>(), out, options.refusalParams === true);
378454
}
379455
return out;
380456
}

‎packages/metadata-protocol/src/protocol-save.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1665,7 +1665,10 @@ export class ProtocolSaveFacet {
16651665
// every other body is judged as stored.
16661666
const parsed = schema.safeParse(flowGateVerdictBody ?? request.item);
16671667
if (!parsed.success) {
1668-
const issues = zodIssuesToMetadataIssues(parsed.error.issues);
1668+
// [#36594] The 422 alone carries each issue's registered
1669+
// refusal (`params.code` and its siblings); the read path
1670+
// and the seed refusal publish a closed entry shape.
1671+
const issues = zodIssuesToMetadataIssues(parsed.error.issues, { refusalParams: true });
16691672
// [#10524 → commit d806081dd] The findings clause is rendered PER
16701673
// FACE — see {@link specValidationFindings}. #10524's
16711674
// headline is applied on the faces that carry the same

‎packages/metadata-protocol/src/protocol.save-union-issues.test.ts‎

Lines changed: 121 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,10 @@ import { z } from 'zod';
3535
// #5619 sank the two predicates into a package both sides already depend on.
3636
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core';
3737
import { applyConversionsToStoredItem } from '@objectstack/spec';
38-
import { getMetadataTypeSchema } from '@objectstack/spec/kernel';
39-
import { ObjectStackProtocolImplementation, zodIssuesToMetadataIssues } from './protocol.js';
38+
import { CONTROLLED_BY_PARENT_MASTER_INVALID } from '@objectstack/spec/data';
39+
import { getMetadataTypeSchema, PLUGIN_UI_REQUIRED_KEY_MISSING, PluginSchema, registerMetadataTypeSchema } from '@objectstack/spec/kernel';
40+
import { ObjectStackProtocolImplementation, seedRequestValidationError, zodIssuesToMetadataIssues } from './protocol.js';
41+
import { decorateMetadataItem } from './metadata-diagnostics.js';
4042
import { ZOD_UNION_DEFAULT_MESSAGE } from './protocol-metadata-issues.js';
4143

4244
interface Row {
@@ -702,3 +704,120 @@ describe('#35500 a member that is itself a bare union of kinds explains nothing'
702704
expect(zodIssuesToMetadataIssues(issuesOf(schema, { u: { a: 1 } })).map((e) => [e.path, e.code])).toEqual([['u.a', 'invalid_type']]);
703705
});
704706
});
707+
708+
/**
709+
* #36594 — a spec refusal's registered code reaches the save door's 422.
710+
*
711+
* A spec rule that owns an ADR-0112 code stamps it on its zod issue as
712+
* `params.code`, beside the fields that say which fix applies; zod's own issue
713+
* code for every such rule is `'custom'`. The 422 entry kept `path`, `message`
714+
* and that `'custom'` and dropped `params`, so a client of the door could not
715+
* tell one refusal from another except by its English sentence. The 422 entry
716+
* now carries the registered refusal; `code` is unchanged.
717+
*
718+
* Only the 422: the read path's `_diagnostics.errors[]` and the seed refusal's
719+
* `seedApplied.issues[]` publish the entry as exactly `path` / `message` /
720+
* `code` (`MetadataValidationResultSchema`, the publish response), so they stay
721+
* that shape. `err.issues` is the 422 body's `issues` member as sent: the REST
722+
* error answer spreads it unchanged (`packages/rest/src/error-response.ts`).
723+
*/
724+
describe('#36594 the save door\'s 422 entry carries the registered refusal on `params`', () => {
725+
const detailWithReadonlyMaster = () => ({
726+
name: 'work_order_item',
727+
label: 'Work Order Item',
728+
sharingModel: 'controlled_by_parent',
729+
fields: {
730+
order: { name: 'order', type: 'master_detail', label: 'Order', reference: 'work_order', required: true, readonly: true },
731+
note: { name: 'note', type: 'text', label: 'Note' },
732+
},
733+
});
734+
const CBP_PARAMS = { code: CONTROLLED_BY_PARENT_MASTER_INVALID, shape: 'master-not-writable' };
735+
736+
it('CONTROLLED_BY_PARENT_MASTER_INVALID: an object save names the code and its shape; `code` stays \'custom\'', async () => {
737+
const { protocol, rows } = makeProtocol();
738+
739+
const err = await rejection(save(protocol, detailWithReadonlyMaster(), 'work_order_item', 'object'));
740+
741+
expect(err.code).toBe('INVALID_METADATA');
742+
expect(err.status).toBe(422);
743+
expect(err.issues).toEqual([{ path: 'fields', message: expect.any(String), code: 'custom', params: CBP_PARAMS }]);
744+
expect(rows.size).toBe(0);
745+
});
746+
747+
it('CONTROL — an issue zod raised without params gets no `params` member', async () => {
748+
const { protocol } = makeProtocol();
749+
const body = { ...detailWithReadonlyMaster(), label: 42 };
750+
751+
const err = await rejection(save(protocol, body, 'work_order_item', 'object'));
752+
753+
expect(err.status).toBe(422);
754+
const label = err.issues.find((i: any) => i.path === 'label');
755+
expect(label).toEqual({ path: 'label', message: expect.any(String), code: 'invalid_type' });
756+
expect(Object.prototype.hasOwnProperty.call(label, 'params')).toBe(false);
757+
});
758+
759+
it('a BigInt, a cycle, a function and NaN in a refusal\'s params are left out, and the door still answers 422', async () => {
760+
// The door judges a type by the schema `getMetadataTypeSchema` resolves, and a
761+
// registered override wins over the built-in one; restored below.
762+
const builtin = getMetadataTypeSchema('object')!;
763+
const cyclic: Record<string, unknown> = {};
764+
cyclic.self = cyclic;
765+
registerMetadataTypeSchema('object', z.any().superRefine((_v, ctx) => {
766+
ctx.addIssue({
767+
code: 'custom', path: ['fields'], message: 'refused',
768+
params: { ...CBP_PARAMS, big: BigInt(1), cyclic, fn: () => 1, nan: Number.NaN, count: 2, flag: true },
769+
});
770+
}));
771+
try {
772+
const { protocol } = makeProtocol();
773+
774+
const err = await rejection(save(protocol, detailWithReadonlyMaster(), 'work_order_item', 'object'));
775+
776+
expect(err.code).toBe('INVALID_METADATA');
777+
expect(err.status).toBe(422);
778+
expect(err.issues).toEqual([{ path: 'fields', message: 'refused', code: 'custom', params: { ...CBP_PARAMS, count: 2, flag: true } }]);
779+
expect(() => JSON.stringify({ issues: err.issues })).not.toThrow();
780+
} finally {
781+
registerMetadataTypeSchema('object', builtin);
782+
}
783+
expect(getMetadataTypeSchema('object')).toBe(builtin);
784+
});
785+
786+
it('PLUGIN_UI_REQUIRED_KEY_MISSING: the real `PluginSchema` refusal, through the mapper the door calls, names the code and the missing key', () => {
787+
// No metadata type the save door accepts parses with `PluginSchema` on
788+
// this tree (a type name it does not know is refused `INVALID_REQUEST`
789+
// before any schema runs), so this pins the mapper with the door's option.
790+
const parsed = PluginSchema.safeParse({ id: 'com.example.panel', name: 'Panel', version: '1.0.0', type: 'ui', slug: 'panel' });
791+
expect(parsed.success).toBe(false);
792+
793+
expect(zodIssuesToMetadataIssues(parsed.error!.issues, { refusalParams: true })).toEqual([{
794+
path: 'staticPath',
795+
message: expect.stringMatching(new RegExp(`^${PLUGIN_UI_REQUIRED_KEY_MISSING}: `)),
796+
code: 'custom',
797+
params: { code: PLUGIN_UI_REQUIRED_KEY_MISSING, key: 'staticPath' },
798+
}]);
799+
});
800+
801+
it('params whose `code` is not a registered error code are not a refusal: internal markers stay off the wire', () => {
802+
const issue = (params: unknown) => ({ code: 'custom', path: ['a'], message: 'm', params });
803+
804+
for (const params of [{ readAsWritten: true }, { retiredComponentType: 'x' }, { code: 'NOT_A_REGISTERED_CODE' }, { code: 7 }, ['code'], null]) {
805+
const [entry] = zodIssuesToMetadataIssues([issue(params)], { refusalParams: true });
806+
expect(entry).toEqual({ path: 'a', message: 'm', code: 'custom' });
807+
}
808+
});
809+
810+
it('READ PATH — `_diagnostics.errors[]` on a stored object with the same refusal carries no `params`', () => {
811+
const decorated: any = decorateMetadataItem('object', detailWithReadonlyMaster());
812+
813+
expect(decorated._diagnostics.valid).toBe(false);
814+
expect(decorated._diagnostics.errors).toEqual([{ path: 'fields', message: expect.any(String), code: 'custom' }]);
815+
});
816+
817+
it('SEED — the seed refusal behind `seedApplied.issues[]` carries no `params`', () => {
818+
const err: any = seedRequestValidationError([{ code: 'custom', path: ['seeds', 0], message: 'm', params: CBP_PARAMS }]);
819+
820+
expect(err.code).toBe('INVALID_METADATA');
821+
expect(err.issues).toEqual([{ path: 'seeds.0', message: 'm', code: 'custom' }]);
822+
});
823+
});

‎packages/spec/src/api/error-code-ledger.zod.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1953,16 +1953,20 @@ export const ERROR_CODE_LEDGER = {
19531953
// tree answers with it, the thrown value is the boundary.
19541954
'CONNECTOR_UPSTREAM_CHANGED',
19551955
'CONNECTOR_UPSTREAM_UNAVAILABLE',
1956-
// `door: 'none'` on the `PLUGIN_UI_REQUIRED_KEY_MISSING` reading below: the
1956+
// `door: 'none'` on the `PLUGIN_UI_REQUIRED_KEY_MISSING` reading below, read
1957+
// as: no door answers with this code as its `error.code`. The
19571958
// `controlled_by_parent` master refusal's code (`data/controlled-by-parent-master.ts`),
19581959
// stamped on the zod ISSUE as `params.code` beside `params.shape` by
19591960
// `ObjectSchema`'s refinement and `defineStack`'s extension-merge gate, never
19601961
// on a thrown error, and not in the `message`; no `status` of its own.
19611962
// Visible on the zod issue itself (any `safeParse`, the Studio settings
1962-
// tab's path, which keys its localized wording on it) and on `defineStack`'s
1963-
// `STACK_SCHEMA_INVALID` refusal, whose `issues` are the raw zod issues. NOT
1964-
// on the metadata save door's `422 INVALID_METADATA`: `zodIssuesToMetadataIssues`
1965-
// keeps `path`, `message` and zod's `code` ('custom'), never `params`.
1963+
// tab's path, which keys its localized wording on it), on `defineStack`'s
1964+
// `STACK_SCHEMA_INVALID` refusal, whose `issues` are the raw zod issues, and
1965+
// inside the metadata save door's `422 INVALID_METADATA` body, on an
1966+
// `issues[]` entry: `zodIssuesToMetadataIssues` carries the registered
1967+
// refusal there as `params.code` beside `params.shape`, while the body's
1968+
// `code` is `INVALID_METADATA` and the entry's own `code` stays zod's issue
1969+
// code ('custom'). The read path's `_diagnostics.errors[]` does not carry it.
19661970
'CONTROLLED_BY_PARENT_MASTER_INVALID',
19671971
'EXTERNAL_SCHEMA_MISMATCH',
19681972
'EXTERNAL_SCHEMA_MODE_VIOLATION',

0 commit comments

Comments
 (0)