Skip to content

Commit 42eb126

Browse files
feat(spec): the published JSON Schema states the marketplace taxonomy facets' no-duplicates rule as uniqueItems (#31047)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoUxLbaBgDztWPQ9vNHLD3v5)_ Fixes #31036 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — no skill or doc teaches the facets' duplicate rule, and the reference renderer prints no `uniqueItems`, so nothing in `skills/**` or `content/docs/**` states the narrowed rule. ## 维护者速读 - 改了什么:spec 导出的 JSON Schema 现在把市场分类的「同一维度不能重复」写成 `uniqueItems: true`。`businessFunctions`、`industries` 两个维度本身,以及嵌着它们的 6 个 schema(Package、CreatePackageRequest、UpdatePackageRequest、MarketplaceListing、TemplateManifest、MarketplaceSearchResponse)都带上了这条规则。 - 为什么改:这条规则在 TypeScript/Zod 校验里一直生效(`['sales', 'sales']` 会被拒),但导出 JSON Schema 时丢了,编辑器提示和外部校验工具会放行重复值,作者要到发布时才被平台拒绝。 - 风险与回滚:运行时接受与拒绝的内容完全不变,只是发布的 schema 补上了运行时早已执行的规则;JSON Schema 新拒的文档运行时本来就拒。对只读发布 schema 的工具来说这是一次收窄(changeset 标了 BREAKING 与 ADR-0087 不需迁移),版本仍是 patch。回滚即 revert。 - 先看:`packages/spec/src/shared/refinement-projection.ts`(新的 `unique-items` 规则与「只对标量成立」的论证);`packages/spec/src/marketplace/taxonomy.zod.ts`(`distinct()` 改用已声明的谓词,表达式不变);`packages/spec/scripts/refinement-projection.test.ts`(等价性与 Zod 行为不变的钉子)。 - 两分钟验证:`pnpm --filter @objectstack/spec build && node -e "console.log(require('./packages/spec/json-schema/marketplace/MarketplaceBusinessFunctions.json').uniqueItems)"`,预期打印 `true`。 - 需要你做的:无,席位落地。 ## What changes - **A sixth arm in the closed refinement projection: `unique-items`.** `src/shared/refinement-projection.ts` adds the arm to `ProjectableRefinement` and `PROJECTABLE_REFINEMENT_PATTERNS`, plus a declared predicate `UNIQUE_SCALAR_ITEMS` (`new Set(values).size === values.length`) and the `JsonScalar` type it takes. The generator half (`scripts/lib/refinement-projection.ts`) emits it as JSON Schema's own `uniqueItems: true`, beside the node's `type` / `items` / `minItems` / `maxItems` (no `allOf`: `uniqueItems` is not a keyword the reference renderer reads as a type). - **Exact only on JSON scalars, and the type says so.** A `Set` compares with SameValueZero, `uniqueItems` with JSON equality. On strings, numbers, booleans and `null` those are one relation (`0` and `-0` are one value to both; `"1"` and `1` are two to both; `NaN` is not JSON). On objects they are not: a `Set` compares by identity, so two equal objects would be two members to the runtime and one value to the file. The predicate's parameter is `readonly JsonScalar[]`, so composing it on a list of objects is a compile error rather than a wider-than-runtime file. - **The taxonomy helper uses the declared predicate.** `distinct()` in `src/marketplace/taxonomy.zod.ts` passes `UNIQUE_SCALAR_ITEMS` instead of an inline copy of the same expression, and its item type is bounded to `z.ZodType<JsonScalar>` so the call type-checks. Same message, same `min` / `max`, same accept set. (Declared deviation below.) - **Ledger.** `packages/spec/dropped-refinements.baseline.json` deletes 8 entries (14 sites), and its `measured` block is re-read from this build: 252 published schemas / 1023 dropped sites / 728 projected / 0 undecidable (was 260 / 1037 / 369 / 0; see Acceptance notes on the 369). - **Changeset.** `@objectstack/spec` patch with both declaration lines (`Clause-②: no (narrowing)`, `Metadata-protocol: none`), the `**BREAKING (published artifact narrows)**` banner and one `adr-0087: not-required (no-migration-prescription)` marker, as the earlier arms of this list carried. - **The arm's limit, stated where a composer reads it.** The `unique-items` docblock and `UNIQUE_SCALAR_ITEMS` carry a ⛔ paragraph: the item parse must be the identity on scalars (`z.enum`, `z.literal`, `z.string()`, `z.number()`, `z.boolean()`, `z.null()`), never a coercing, trimming, case-folding or transforming item, because the predicate judges the parsed output and the keyword the document, so such an item would publish a file wider than the runtime while the ledger reads `projected`. ### Schemas that gain `uniqueItems` The `distinct()` helper is file-local to `taxonomy.zod.ts` and has exactly two callers. Every published schema that reaches them gains the keyword, and nothing else does (generator census: `14 unique-items`): | ledger entry (deleted) | sites now `projected` | |:---|:---| | `marketplace/MarketplaceBusinessFunctions` | root | | `marketplace/MarketplaceIndustries` | root | | `marketplace/Package` | `businessFunctions`, `industries` | | `marketplace/CreatePackageRequest` | `businessFunctions`, `industries` | | `marketplace/UpdatePackageRequest` | `businessFunctions`, `industries` | | `marketplace/MarketplaceListing` | `businessFunctions`, `industries` | | `marketplace/TemplateManifest` | `businessFunctions`, `industries` | | `marketplace/MarketplaceSearchResponse` | `items.element.businessFunctions`, `items.element.industries` | All are intended: each is the facet itself or a schema whose property is the facet. ## Tests `scripts/refinement-projection.test.ts` (the arm's shared harness, two new top-level `describe` blocks): - the closed roster pin gains `unique-items`; - the predicate declares itself; the emit is `uniqueItems: true` beside the node's own keywords; it is idempotent; - **equality pin**: over a scalar corpus (duplicates, case, `"1"` vs `1`, `0` vs `-0`, `1` vs `1.0` after `JSON.parse`, `true` vs `1`, `null`), a JSON-equality `uniqueItems` evaluator that is deliberately not a `Set` agrees with the predicate on every list; - a `@ts-expect-error` pin that an array of objects cannot compose the predicate (live: the scripts tsconfig compiles the file); - **live seam**: both facet schemas publish `uniqueItems: true` and keep their array shape; `Package` states it at both properties; runtime and keyword agree on a facet corpus; the census reads every one of the 14 sites `projected` naming `unique-items` with nothing dropped, for all 8 schemas; - **Zod unchanged** (seat's ask): the same accept/refuse verdicts as before on a corpus, including the duplicate refusal with its `custom` code and the helper's own message. Ablation (committed first, `scripts/ablation-replace.mjs`, mutation proven on disk 1 → 0 anchor hits): with the emit body replaced by `void jsonSchema;`, 7 of the new cases go red (`Tests 7 failed | 81 passed`), including the census case, which shows the detector measures the generator's projection; restored, `git diff HEAD` empty. ## Declared deviation The claim's file surface lists the Zod schemas as out of bounds ("stop on breach"). The arm cannot see an inline arrow: the projection recognises only predicates registered through a factory in `refinement-projection.ts` (a `WeakMap` keyed on the function, and the design refuses `fn.toString()` matching). So `distinct()` in `taxonomy.zod.ts` changes three lines: the import, the inline predicate swapped for `UNIQUE_SCALAR_ITEMS` (same expression), and a type-only bound `T extends z.ZodType<JsonScalar>`, because Set equality matches JSON `uniqueItems` only on scalars and the bound keeps that guarantee at compile time instead of behind a cast. The seat ruled this in (seat thread, 2026-11-06 20:12Z ruling A for the swap, 20:14Z for the bound). No schema shape, message or accept set moves; the Zod-unchanged test above pins it. ## Acceptance notes - **`measured.refinementSitesThatDidProject` was stale on `main`.** It read 369, while by arithmetic the generator on `main` reads 714 (the 728 measured here minus the 14 sites this PR projects; not re-run on `main`). The other three `measured` values matched by arithmetic. The block is hand-kept and no gate reads it; I re-read all four from this build rather than moving only the three this change touches. - **Other `Set`-uniqueness refinements left alone.** `src/security/tenant-layer0-verdict.ts` (`organizationIds`, a scalar list) is the same shape and could compose `UNIQUE_SCALAR_ITEMS`; `src/data/object.zod.ts` (`groups` unique by `key`) is uniqueness of a projection, not of items, so it is not this arm. Neither is in this card's surface. - **Clause-② reading (re-ruled by contract review 6695604767).** The published accept set narrows at 14 sites, so the declaration is `Clause-②: no (narrowing)`: nothing widens, and a narrowing of a published artifact is breaking. The level stays `patch` because, under ruling A, it follows `Metadata-protocol: none` alone; the sibling arm's `minor` (170fd83) predates that ruling. - **Not done from the review's ④:** the optional extra line inside `distinct()` restating the identity-parse rule. The seat's ruling capped `taxonomy.zod.ts` at three lines, so the rule lives in `refinement-projection.ts`, which `distinct()` imports from. - **Neighbours.** No open PR touches `refinement-projection.ts` (either half), `dropped-refinements.baseline.json` or `taxonomy.zod.ts` (read against the heads of the open code PRs around 20:30Z). - **Reference pages** under `content/docs/references/**` do not move: the reference renderer does not print `uniqueItems`. ## Verification <details><summary>Rework head `dd7ed18f` (contract review 6695604767)</summary> - Changeset gates: `check-adr-0087-registration --base origin/main` :: exit 0, reading `.changeset/31036-unique-items-projection.md [BREAKING+clause-②-narrowing] not-required (no-migration-prescription)`; `check-changeset-no-major` :: exit 0; `check-empty-changeset` :: exit 0; `pnpm check:changeset-gate-self-tests` :: exit 0. - Prose gates on the docblock edit: `check:doc-authoring`, `check:spec-docblock-symbol-anchors`, `check:nul-bytes`, `check:issue-citations`, `check-closing-keyword-parity` :: exit 0 each. - Spec: `tsc --noEmit` :: exit 0; `vitest run scripts/refinement-projection.test.ts scripts/dropped-refinements.test.ts src/marketplace` :: `Test Files 9 passed (9)`, `Tests 245 passed (245)`. - **Dogfood battery** (owed by the `(narrowing)` arm): `turbo run build --filter='./packages/**' --filter='@objectstack/dogfood^...'` then `pnpm --filter @objectstack/dogfood test`, under `os-verify-lock`, no shard, no path: VERDICT command-exit 0, `Test Files 428 passed | 3 skipped (431)`, `Tests 3562 passed | 41 skipped (3603)`, no failure. - CI on `dd7ed18f` at the time of this edit: 55 success, 9 skipped, 0 failure. The two reds on `da4e41dd` (`TypeScript Type Check`, `Test UI`) were aggregators over lanes cancelled at 21:11Z when this push superseded that head; no lane on `da4e41dd` concluded failure. </details> Earlier runs, on head `da4e41dd`, base `origin/main` `9d939c58` (the rework moved only the changeset and a docblock): <details><summary>Build, generated artifacts, typecheck, tests</summary> - `pnpm --filter @objectstack/spec build` (real `.d.ts`, under `os-verify-lock`) :: exit 0. The generator census prints `1023 refinement site(s) across 252 published schema(s)` and `728 ... DO reach the published JSON Schema`, of which `14 unique-items`. `json-schema/marketplace/MarketplaceBusinessFunctions.json` carries `"uniqueItems": true` beside `minItems: 1`, `maxItems: 3`. - `pnpm --filter @objectstack/spec check:generated` :: exit 0, `All 14 generated artifacts are up to date` (no reference page, api-surface or authorable-surface moves). - `pnpm --filter @objectstack/spec typecheck` :: exit 0 (build program, `tsconfig.scripts.json`, which compiles the new test and its `@ts-expect-error`, and the test layer). - `pnpm --filter @objectstack/spec test` :: VERDICT command-exit 0, `Test Files 820 passed (820)`, `Tests 25918 passed | 1 todo (25919)`. - Targeted: `vitest run scripts/refinement-projection.test.ts scripts/dropped-refinements.test.ts src/marketplace` :: `Test Files 9 passed (9)`, `Tests 245 passed (245)`. </details> <details><summary>Ablation</summary> - `node scripts/ablation-replace.mjs --file packages/spec/scripts/lib/refinement-projection.ts --anchor " jsonSchema.uniqueItems = true;" --replacement " void jsonSchema;" -- ... vitest run scripts/refinement-projection.test.ts`: `ok mutation landed: anchor 1 -> 0`, `Tests 7 failed | 81 passed (88)`. The 7: emit, idempotence, the scalar equality pin, both live-seam shape cases, the facet corpus agreement and the 8-schema census. Restored: `git diff HEAD` empty, anchor count 1. No build needed: the suite imports `src/` and `scripts/lib` directly. </details> <details><summary>Derived gates (82 families)</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 82 families on `da4e41dd`; all 82 exit 0. Record: `31036-gates-ran-da4e41dd.list` in the seat's out folder. - `--ran` reconciliation: `82 derived, 82 run, 0 NOT-MEASURED, 0 UNRUN`. - Four first runs exited 3 (PREREQUISITE NOT MET, not findings) and were re-run green after their prerequisites: `check-plugin-teardown-shape --self-test` (`git fetch --unshallow origin main`), lint `check:doc-formula-expressions`, `check:dual-build-cjs-loads`, `check:lean-entry-closure` (`turbo run build --filter='./packages/**' --filter='@objectstack/dogfood^...'`). - Local-only families: `check:skill-frame-freshness` exit 0; `check:dev-prereqs` exit 1 NOT MEASURED, reason: 34 `ui/` workspace packages have no `dist/` in this worktree (box state, the diff touches no `ui/` path). - Dogfood: run on the rework head, above. </details> <!-- signed: domain:spec#1 · os-tesla · session_01L9qibxH6kxj8gByoApv69p --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 81deb54 commit 42eb126

6 files changed

Lines changed: 321 additions & 52 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/spec': patch
3+
---
4+
5+
feat(spec): the published JSON Schema states the marketplace taxonomy facets' no-duplicates rule as `uniqueItems: true`
6+
7+
Clause-②: no (narrowing) — the published `json-schema/**` declarations of the two taxonomy facets, and of the six schemas that carry them, refuse a list that repeats a value, which they admitted before. The parse already refused it; nothing is widened and no key is added, removed or renamed.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped and no metadata type or stored shape moves: the set of documents the parse accepts is byte-for-byte what it was, and the lists the published files stop admitting are lists the parse already refused. An author lists each facet value once; there is nothing for `objectstack migrate meta` to rewrite and no tombstone. -->
11+
12+
**BREAKING (published artifact narrows)** — a validator reading `packages/spec/json-schema/**` (an editor, codegen, an external check) now refuses a duplicated `businessFunctions` or `industries` value at 14 sites in 8 published schemas.
13+
14+
`businessFunctions` and `industries` refuse a repeated value at parse time (`['sales', 'sales']` is refused with "`businessFunctions` lists a value more than once; list each value once."), but `packages/spec/json-schema/**` dropped that rule, so an editor or an external validator reading the published files accepted the duplicate. The files now say `uniqueItems: true` on both facets, wherever they appear: `marketplace/MarketplaceBusinessFunctions`, `marketplace/MarketplaceIndustries`, and the `businessFunctions` / `industries` properties of `marketplace/Package`, `marketplace/CreatePackageRequest`, `marketplace/UpdatePackageRequest`, `marketplace/MarketplaceListing`, `marketplace/TemplateManifest` and `marketplace/MarketplaceSearchResponse` (under `items`).
15+
16+
**Not a behaviour change.** The runtime accepts and refuses exactly what it did before; only the published file catches up. A document the published file now refuses was already refused by the parse.
17+
18+
**How.** The closed refinement projection (`src/shared/refinement-projection.ts`) gains one arm, `unique-items`, and a declared predicate for it, `UNIQUE_SCALAR_ITEMS`, which the taxonomy's list helper now uses in place of an inline copy of the same expression. The arm is exact only on lists of JSON scalars: a `Set` compares strings, numbers, booleans and `null` the way `uniqueItems` does (`0` and `-0` are one value to both, `"1"` and `1` are two), but compares objects by identity, so the predicate's parameter type is `readonly JsonScalar[]` and composing it on a list of objects does not compile.
19+
20+
**The ledger shrinks.** `packages/spec/dropped-refinements.baseline.json` loses the eight entries above (14 sites), from 1037 dropped sites in 260 published schemas to 1023 in 252.

‎packages/spec/dropped-refinements.baseline.json‎

Lines changed: 3 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
"description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.",
33
"measured": {
44
"zod": "4.4.3",
5-
"publishedSchemasWithDroppedRefinements": 260,
6-
"droppedRefinementSites": 1037,
7-
"refinementSitesThatDidProject": 369,
5+
"publishedSchemasWithDroppedRefinements": 252,
6+
"droppedRefinementSites": 1023,
7+
"refinementSitesThatDidProject": 728,
88
"refinementSitesWithNoJsonFormToCompare": 0
99
},
1010
"entries": {
@@ -1274,52 +1274,6 @@
12741274
""
12751275
]
12761276
},
1277-
"marketplace/CreatePackageRequest": {
1278-
"sites": [
1279-
"businessFunctions",
1280-
"industries"
1281-
]
1282-
},
1283-
"marketplace/MarketplaceBusinessFunctions": {
1284-
"sites": [
1285-
""
1286-
]
1287-
},
1288-
"marketplace/MarketplaceIndustries": {
1289-
"sites": [
1290-
""
1291-
]
1292-
},
1293-
"marketplace/MarketplaceListing": {
1294-
"sites": [
1295-
"businessFunctions",
1296-
"industries"
1297-
]
1298-
},
1299-
"marketplace/MarketplaceSearchResponse": {
1300-
"sites": [
1301-
"items.element.businessFunctions",
1302-
"items.element.industries"
1303-
]
1304-
},
1305-
"marketplace/Package": {
1306-
"sites": [
1307-
"businessFunctions",
1308-
"industries"
1309-
]
1310-
},
1311-
"marketplace/TemplateManifest": {
1312-
"sites": [
1313-
"businessFunctions",
1314-
"industries"
1315-
]
1316-
},
1317-
"marketplace/UpdatePackageRequest": {
1318-
"sites": [
1319-
"businessFunctions",
1320-
"industries"
1321-
]
1322-
},
13231277
"security/CriteriaSharingRule": {
13241278
"sites": [
13251279
"sharedWith"

‎packages/spec/scripts/lib/refinement-projection.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,22 @@ function conjoinPropertyNames(jsonSchema: JsonObject, rule: JsonObject): void {
225225
jsonSchema.allOf = [...allOf, { propertyNames: rule }];
226226
}
227227

228+
/**
229+
* JSON Schema's own `uniqueItems: true` — the keyword whose meaning IS this
230+
* arm's sentence, so nothing is encoded and nothing approximated.
231+
*
232+
* Nothing to conjoin and nothing to guard: `uniqueItems` is a boolean, zod
233+
* never emits it for an array, and `true` is the only value this arm writes,
234+
* so writing it twice — or onto a node that already says `true` — states one
235+
* rule. It sits beside the node's own `type`, `items`, `minItems` and
236+
* `maxItems` rather than in an `allOf`, because unlike `anyOf` it is no
237+
* keyword the reference renderer reads as the node's TYPE (`emitRequiredOneOf`
238+
* says why that one has to nest).
239+
*/
240+
function emitUniqueItems(jsonSchema: JsonObject): void {
241+
jsonSchema.uniqueItems = true;
242+
}
243+
228244
/** Write one declared arm's keywords onto one emitted node. */
229245
export function emitProjectableRefinement(jsonSchema: JsonObject, declared: ProjectableRefinement): void {
230246
switch (declared.pattern) {
@@ -243,6 +259,9 @@ export function emitProjectableRefinement(jsonSchema: JsonObject, declared: Proj
243259
case 'banned-key-pattern':
244260
emitBannedKeyPattern(jsonSchema, declared.keyPattern);
245261
return;
262+
case 'unique-items':
263+
emitUniqueItems(jsonSchema);
264+
return;
246265
}
247266
}
248267

‎packages/spec/scripts/refinement-projection.test.ts‎

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@
2929
* asserted rather than argued), and the predicate is shown STATELESS, which
3030
* is what a flagless `RegExp` buys and what a JSON Schema `pattern` — which
3131
* has no flags to carry — means.
32+
* - `unique-items` — over a corpus of JSON scalar lists, against a
33+
* `uniqueItems` evaluator that compares the JSON way (type, then value)
34+
* rather than through a `Set`, including `0` beside `-0` and `"1"` beside
35+
* `1`, the two places SameValueZero and JSON equality could have come
36+
* apart on scalars.
3237
*
3338
* ## Why an equality pin and not a comment
3439
*
@@ -59,7 +64,22 @@ import {
5964
dependentRequired,
6065
projectableRefinementOf,
6166
requiredOneOf,
67+
UNIQUE_SCALAR_ITEMS,
68+
type JsonScalar,
6269
} from '../src/shared/refinement-projection';
70+
import {
71+
MAX_BUSINESS_FUNCTIONS,
72+
MAX_INDUSTRIES,
73+
MarketplaceBusinessFunctionsSchema,
74+
MarketplaceIndustriesSchema,
75+
} from '../src/marketplace/taxonomy.zod';
76+
import {
77+
CreatePackageRequestSchema,
78+
PackageSchema,
79+
UpdatePackageRequestSchema,
80+
} from '../src/marketplace/package.zod';
81+
import { MarketplaceListingSchema, MarketplaceSearchResponseSchema } from '../src/marketplace/marketplace.zod';
82+
import { TemplateManifestSchema } from '../src/marketplace/template-manifest.zod';
6383
import { SSLConfigSchema } from '../src/data/driver-sql.zod';
6484
import { NormalizedFilterSchema } from '../src/data/filter.zod';
6585
import { TraceSamplingConfigSchema } from '../src/system/tracing.zod';
@@ -175,6 +195,7 @@ describe('the list of projectable patterns is CLOSED', () => {
175195
'dependent-required',
176196
'banned-keys',
177197
'banned-key-pattern',
198+
'unique-items',
178199
]);
179200
});
180201

@@ -1087,3 +1108,182 @@ describe('generator and detector project through ONE call, not two conventions',
10871108
expect(census.projected.map((s) => s.declaredPatterns)).toEqual([['dependent-required']]);
10881109
});
10891110
});
1111+
1112+
/**
1113+
* The node's `uniqueItems` rule, evaluated the way a validator would — JSON
1114+
* equality (same type, then same value), ⛔ deliberately NOT a `Set`, so the
1115+
* pin compares two spellings of the rule rather than one spelling with itself
1116+
* — and refusing to report anything when the node does not carry
1117+
* `uniqueItems: true`, so a projection that stopped emitting fails rather than
1118+
* passing vacuously.
1119+
*/
1120+
const uniqueItemsSatisfied = (node: Record<string, unknown>, doc: readonly unknown[]): boolean => {
1121+
if (node.uniqueItems !== true) {
1122+
throw new Error('the node carries no uniqueItems: true — nothing to evaluate');
1123+
}
1124+
const jsonTypeOf = (value: unknown): string => (value === null ? 'null' : typeof value);
1125+
// JSON Schema compares numbers by mathematical value, so `0` and `-0` are
1126+
// one number; `==` on two same-typed scalars says exactly that.
1127+
const jsonEqual = (a: unknown, b: unknown): boolean => jsonTypeOf(a) === jsonTypeOf(b) && a == b;
1128+
return doc.every((item, i) => doc.slice(i + 1).every((other) => !jsonEqual(item, other)));
1129+
};
1130+
1131+
describe('unique-items: a Set and `uniqueItems` are ONE relation on JSON scalars', () => {
1132+
it('declares itself, and has nothing per call site to declare', () => {
1133+
expect(projectableRefinementOf(UNIQUE_SCALAR_ITEMS)).toEqual({ pattern: 'unique-items' });
1134+
});
1135+
1136+
it('emits JSON Schema`s own `uniqueItems: true`, beside the node`s own keywords', () => {
1137+
const node = publish(z.array(z.string()).min(1).max(3).refine(UNIQUE_SCALAR_ITEMS, 'once'));
1138+
expect(node).toEqual({ ...publish(z.array(z.string()).min(1).max(3)), uniqueItems: true });
1139+
// ⛔ Not nested: `uniqueItems` is no keyword the reference renderer reads
1140+
// as the node's type, so there is no `allOf` to hide it in.
1141+
expect(node.allOf).toBeUndefined();
1142+
});
1143+
1144+
it('is idempotent — the same arm twice states one rule', () => {
1145+
const node: Record<string, unknown> = { type: 'array', items: { type: 'string' } };
1146+
emitProjectableRefinement(node, { pattern: 'unique-items' });
1147+
emitProjectableRefinement(node, { pattern: 'unique-items' });
1148+
expect(node).toEqual({ type: 'array', items: { type: 'string' }, uniqueItems: true });
1149+
});
1150+
1151+
it('the predicate and the keyword agree on every scalar list in the corpus', () => {
1152+
const node = publish(z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).refine(UNIQUE_SCALAR_ITEMS));
1153+
const corpus: JsonScalar[][] = [
1154+
[],
1155+
['sales'],
1156+
['sales', 'marketing'],
1157+
['sales', 'sales'],
1158+
['sales', 'marketing', 'sales'],
1159+
['Sales', 'sales'],
1160+
['1', 1],
1161+
[1, 1],
1162+
[0, -0],
1163+
[1, 1.0],
1164+
[true, 1],
1165+
[true, true],
1166+
[false, 0, '', null],
1167+
[null, null],
1168+
];
1169+
for (const list of corpus) {
1170+
// Through a JSON round trip on purpose: the domain is the document an
1171+
// author writes, and `JSON.parse` is what turns `1.0` into `1`.
1172+
const asJson = JSON.parse(JSON.stringify(list)) as JsonScalar[];
1173+
// Equality, not implication: the arm is exact, so a one-sided pin would
1174+
// pass a projection that had stopped narrowing at all.
1175+
expect(uniqueItemsSatisfied(node, asJson), `disagreement on ${JSON.stringify(asJson)}`)
1176+
.toBe(UNIQUE_SCALAR_ITEMS(asJson));
1177+
}
1178+
// `-0` survives `JSON.parse`, so the one SameValueZero-vs-`===` pair is
1179+
// asserted on the value itself rather than on its serialisation.
1180+
const negativeZero = JSON.parse('[0,-0]') as number[];
1181+
expect(Object.is(negativeZero[1], -0)).toBe(true);
1182+
expect(UNIQUE_SCALAR_ITEMS(negativeZero)).toBe(false);
1183+
expect(uniqueItemsSatisfied(node, negativeZero)).toBe(false);
1184+
});
1185+
1186+
it('⛔ an array of OBJECTS cannot compose it — the compile-time half of the exactness argument', () => {
1187+
// Two equal objects parsed from one document are two members to a `Set`
1188+
// and one value to `uniqueItems`; the scalar parameter type keeps that
1189+
// disagreement out of the published file.
1190+
// @ts-expect-error — `{ a: string }` is not a JSON scalar
1191+
z.array(z.object({ a: z.string() })).refine(UNIQUE_SCALAR_ITEMS);
1192+
const twins = JSON.parse('[{"a":"x"},{"a":"x"}]') as unknown[];
1193+
expect(new Set(twins).size).toBe(2);
1194+
});
1195+
});
1196+
1197+
describe('the LIVE seam: the marketplace taxonomy facets publish their no-duplicates rule', () => {
1198+
/** Every published schema the ledger named for the facets, with its own sites. */
1199+
const SEAMS: ReadonlyArray<readonly [string, z.ZodType, readonly string[]]> = [
1200+
['marketplace/MarketplaceBusinessFunctions', MarketplaceBusinessFunctionsSchema, ['']],
1201+
['marketplace/MarketplaceIndustries', MarketplaceIndustriesSchema, ['']],
1202+
['marketplace/Package', PackageSchema, ['businessFunctions', 'industries']],
1203+
['marketplace/CreatePackageRequest', CreatePackageRequestSchema, ['businessFunctions', 'industries']],
1204+
['marketplace/UpdatePackageRequest', UpdatePackageRequestSchema, ['businessFunctions', 'industries']],
1205+
['marketplace/MarketplaceListing', MarketplaceListingSchema, ['businessFunctions', 'industries']],
1206+
['marketplace/TemplateManifest', TemplateManifestSchema, ['businessFunctions', 'industries']],
1207+
[
1208+
'marketplace/MarketplaceSearchResponse',
1209+
MarketplaceSearchResponseSchema,
1210+
['items.element.businessFunctions', 'items.element.industries'],
1211+
],
1212+
];
1213+
1214+
it('both facet schemas state the rule, and keep the array shape they always stated', () => {
1215+
const facets: Array<readonly [z.ZodType, number]> = [
1216+
[MarketplaceBusinessFunctionsSchema, MAX_BUSINESS_FUNCTIONS],
1217+
[MarketplaceIndustriesSchema, MAX_INDUSTRIES],
1218+
];
1219+
for (const [schema, max] of facets) {
1220+
const node = publish(schema);
1221+
expect(node.type).toBe('array');
1222+
expect((node.items as Record<string, unknown>).enum).toBeInstanceOf(Array);
1223+
expect(node.maxItems).toBe(max);
1224+
expect(node.uniqueItems).toBe(true);
1225+
}
1226+
expect(publish(MarketplaceBusinessFunctionsSchema).minItems).toBe(1);
1227+
});
1228+
1229+
it('a schema that EMBEDS a facet states the rule at the facet`s own property', () => {
1230+
const props = publish(PackageSchema).properties as Record<string, Record<string, unknown>>;
1231+
expect(props.businessFunctions.uniqueItems).toBe(true);
1232+
expect(props.industries.uniqueItems).toBe(true);
1233+
});
1234+
1235+
it('⛔ the Zod parse is unchanged — it still refuses a duplicate and accepts the same lists', () => {
1236+
// The helper's predicate became a DECLARED one; the rule it enforces must
1237+
// not have moved. Same corpus, same verdicts, and the refusal still names
1238+
// the key with the helper's own message.
1239+
const verdicts: Array<readonly [unknown, boolean]> = [
1240+
[['sales'], true],
1241+
[['sales', 'marketing'], true],
1242+
[['sales', 'marketing', 'it'], true],
1243+
[['sales', 'sales'], false],
1244+
[['sales', 'marketing', 'sales'], false],
1245+
[[], false],
1246+
[['sales', 'marketing', 'it', 'hr'], false],
1247+
[['not-a-function'], false],
1248+
];
1249+
for (const [list, accepted] of verdicts) {
1250+
expect(MarketplaceBusinessFunctionsSchema.safeParse(list).success, JSON.stringify(list)).toBe(accepted);
1251+
}
1252+
expect(MarketplaceIndustriesSchema.safeParse([]).success).toBe(true);
1253+
expect(MarketplaceIndustriesSchema.safeParse(['retail', 'retail']).success).toBe(false);
1254+
const refused = MarketplaceBusinessFunctionsSchema.safeParse(['sales', 'sales']);
1255+
expect(refused.success).toBe(false);
1256+
expect(refused.error?.issues.map((issue) => [issue.code, issue.message])).toEqual([
1257+
['custom', '`businessFunctions` lists a value more than once; list each value once.'],
1258+
]);
1259+
});
1260+
1261+
it('⛔ the runtime and the emitted keywords agree on every facet list in the corpus', () => {
1262+
const node = publish(MarketplaceIndustriesSchema);
1263+
const corpus: string[][] = [
1264+
[],
1265+
['retail'],
1266+
['retail', 'logistics'],
1267+
['retail', 'retail'],
1268+
['retail', 'logistics', 'retail'],
1269+
['manufacturing', 'retail', 'logistics'],
1270+
];
1271+
for (const list of corpus) {
1272+
// Uniqueness only, deliberately: every list here is valid in every other
1273+
// respect, so the runtime's verdict is the duplicates rule's verdict.
1274+
expect(uniqueItemsSatisfied(node, list), `disagreement on ${JSON.stringify(list)}`)
1275+
.toBe(MarketplaceIndustriesSchema.safeParse(list).success);
1276+
}
1277+
});
1278+
1279+
it('their eight ledger rows are gone because every site now reads `projected`, naming the arm', () => {
1280+
for (const [defKey, schema, paths] of SEAMS) {
1281+
const census = collectDroppedRefinements(defKey, schema);
1282+
expect(census.dropped, defKey).toEqual([]);
1283+
for (const path of paths) {
1284+
const site = census.projected.find((s) => s.path === path);
1285+
expect(site?.declaredPatterns, `${defKey} @ ${JSON.stringify(path)}`).toEqual(['unique-items']);
1286+
}
1287+
}
1288+
});
1289+
});

‎packages/spec/src/marketplace/taxonomy.zod.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { z } from 'zod';
44
import { lazySchema } from '../shared/lazy-schema';
5+
import { UNIQUE_SCALAR_ITEMS, type JsonScalar } from '../shared/refinement-projection';
56
import type { InstallMode } from '../kernel/manifest.zod';
67

78
/**
@@ -153,9 +154,9 @@ export type PackageMaturity = z.input<typeof PackageMaturitySchema>;
153154
// ---------------------------------------------------------------------------
154155

155156
/** A list with no repeated value — a facet value counts once. */
156-
function distinct<T extends z.ZodType>(item: T, key: string) {
157+
function distinct<T extends z.ZodType<JsonScalar>>(item: T, key: string) {
157158
return z.array(item).refine(
158-
(values) => new Set(values).size === values.length,
159+
UNIQUE_SCALAR_ITEMS,
159160
{ message: `\`${key}\` lists a value more than once; list each value once.` },
160161
);
161162
}

0 commit comments

Comments
 (0)