@open-captable/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,835 @@
1
+ /**
2
+ * SchemaComposer
3
+ *
4
+ * Walks an OCF schema registry and produces a "composed" view of any schema
5
+ * by flattening its `allOf` ancestor chain into a single schema with merged
6
+ * `properties` and `required` arrays. The original `$id`, `allOf` array, and
7
+ * every other top-level field are preserved as-is so downstream consumers
8
+ * (e.g. the markdown doc generator) can still render "Composed From" links
9
+ * or detect backwards-compatibility wrappers.
10
+ *
11
+ * The module is intentionally framework-free: it operates on plain JSON
12
+ * objects and an `$id` -> raw-schema map, so it can be reused outside the
13
+ * doc generator (validation tooling, downstream codegen, etc.).
14
+ */
15
+ /**
16
+ * A schema is a backwards-compatibility wrapper if it declares a single
17
+ * `allOf` entry, a single `properties.object_type` field, and nothing else
18
+ * of substance. These wrappers must NOT be flattened: they intentionally
19
+ * stand alone as an alias for another, fully-defined object schema.
20
+ *
21
+ * This is the single source of truth for wrapper detection: the doc-generator
22
+ * factory (`utils/generate-docs/Schema/SchemaNode/Factory.ts`) imports and
23
+ * calls this function, so the composer, validator, and doc generator all agree
24
+ * on what counts as a wrapper.
25
+ */
26
+ export function isBackwardsCompatibleWrapper(json) {
27
+ if (!json || typeof json !== "object")
28
+ return false;
29
+ const properties = json.properties;
30
+ if (!properties || typeof properties !== "object")
31
+ return false;
32
+ const keys = Object.keys(properties);
33
+ if (keys.length !== 1)
34
+ return false;
35
+ const objectType = properties.object_type;
36
+ if (!objectType || typeof objectType !== "object")
37
+ return false;
38
+ const allOf = json.allOf;
39
+ if (!Array.isArray(allOf) || allOf.length !== 1)
40
+ return false;
41
+ const ref = allOf[0]?.$ref;
42
+ return typeof ref === "string";
43
+ }
44
+ // ---------------------------------------------------------------------------
45
+ // Version dispatcher (VersionWrapper) + stability flags
46
+ // ---------------------------------------------------------------------------
47
+ /**
48
+ * Structured stability flag used to mark a schema (or a single version shape)
49
+ * as pre-release or on its way out. This is a first-class JSON-Schema keyword
50
+ * — NOT a `$comment` convention — so tooling can read it reliably and consumers
51
+ * can opt in or out of pre-release shapes.
52
+ *
53
+ * - `stable` — supported; the current recommended shape (the default
54
+ * when the keyword is absent).
55
+ * - `beta` — feature-complete but still subject to change.
56
+ * - `alpha` — pre-release; shape is not final and may change or be
57
+ * withdrawn. Strict consumers should not treat it as final.
58
+ * - `planned_deprecation` — slated for removal in the shape OCF is moving
59
+ * toward, but NOT yet deprecated: still fully part of the
60
+ * current stable surface (kept under `none`/`compatibility`).
61
+ * It differs from `deprecated` in that it is dropped from the
62
+ * forward-looking `unstable` preview — both a version
63
+ * dispatcher whose only shape is `planned_deprecation` and a
64
+ * standalone schema (type / enum / primitive) carrying the
65
+ * flag disappear under `--experimental=unstable` (with
66
+ * references to them pruned), modeling "this has no place in
67
+ * the next major". Use it for the dependency closure of a
68
+ * superseded shape, so the whole subtree leaves together.
69
+ * - `deprecated` — on its way out; will be removed at a future major version.
70
+ * Unlike `planned_deprecation` it is retained in every mode.
71
+ */
72
+ export const STABILITY_KEYWORD = "x-ocf-stability";
73
+ export const STABILITY_LEVELS = [
74
+ "stable",
75
+ "beta",
76
+ "alpha",
77
+ "planned_deprecation",
78
+ "deprecated",
79
+ ];
80
+ export const DEFAULT_STABILITY = "stable";
81
+ /**
82
+ * Ordering rank for presentation: stable first, then beta, then alpha, then the
83
+ * on-the-way-out shapes (planned-deprecation, then deprecated). Lets the doc
84
+ * generator surface the current recommended shape at the top and push
85
+ * pre-release / on-the-way-out shapes below it.
86
+ */
87
+ export const STABILITY_RANK = {
88
+ stable: 0,
89
+ beta: 1,
90
+ alpha: 2,
91
+ planned_deprecation: 3,
92
+ deprecated: 4,
93
+ };
94
+ /**
95
+ * Short presentational badge + one-line note for each stability level — the
96
+ * single source of truth shared by every surface that renders stability: the
97
+ * doc generator (a pill under a schema's header and the per-version sections of
98
+ * a dispatcher page) and the TypeScript codegen (a JSDoc tag on the emitted
99
+ * type). Centralized here so the wording can't drift between them.
100
+ */
101
+ export const STABILITY_BADGE = {
102
+ stable: "✅ STABLE",
103
+ beta: "🧪 BETA",
104
+ alpha: "⚠️ ALPHA",
105
+ planned_deprecation: "🗓️ PLANNED DEPRECATION",
106
+ deprecated: "⛔ DEPRECATED",
107
+ };
108
+ export const STABILITY_NOTE = {
109
+ stable: "Supported — the current recommended shape.",
110
+ beta: "Feature-complete but still subject to change before it is marked stable.",
111
+ alpha: "Pre-release — this shape is **not final** and may change or be withdrawn. Do not treat it as stable.",
112
+ planned_deprecation: "Planned for deprecation — **not deprecated yet**: still fully supported in the current/stable surface, but slated for removal and therefore omitted from the forward-looking `unstable` preview.",
113
+ deprecated: "On its way out — retained for compatibility and scheduled for removal at a future major version.",
114
+ };
115
+ /**
116
+ * The authoritative, structural marker that a schema is a version dispatcher.
117
+ * Set `x-ocf-version-dispatcher: true` on the dispatcher and its identity no
118
+ * longer depends on how its version files happen to be named — a rename of a
119
+ * `.v#` file can't silently demote it back to a plain `anyOf` union (which
120
+ * would drop its `object_type` routing and scatter its doc page). When the flag
121
+ * is absent, detection falls back to the `.v#` filename convention on every
122
+ * referenced shape, so dispatchers that predate the flag still work.
123
+ */
124
+ export const VERSION_DISPATCHER_KEYWORD = "x-ocf-version-dispatcher";
125
+ /** Read the `x-ocf-stability` flag off a schema, defaulting to `stable`. */
126
+ export function stabilityOf(json) {
127
+ const raw = json && json[STABILITY_KEYWORD];
128
+ return STABILITY_LEVELS.includes(raw)
129
+ ? raw
130
+ : DEFAULT_STABILITY;
131
+ }
132
+ /**
133
+ * The single source of truth for the versioned-shape filename convention: a
134
+ * schema `$id` (or `$ref`) whose basename carries a `.v#` suffix, e.g.
135
+ * `EquityCompensationIssuance.v1.schema.json`. Centralized here (rather than
136
+ * re-implemented in the factory and the doc nodes) so every consumer agrees
137
+ * on what counts as a version shape.
138
+ */
139
+ const VERSION_SUFFIX_RE = /\.(v\d+)$/;
140
+ /** The trailing path segment of a schema `$id`/`$ref`, with the
141
+ * `.schema.json` extension stripped (so `.v#` becomes the basename suffix). */
142
+ function versionShapeBasename(idOrRef) {
143
+ const last = idOrRef.split("/").pop() ?? "";
144
+ return last.replace(/\.schema\.json$/, "");
145
+ }
146
+ /** Whether a schema `$id`/`$ref` (or a schema object carrying one) follows the
147
+ * `.v#` versioned-shape filename convention. */
148
+ export function hasVersionSuffix(idOrJson) {
149
+ const id = typeof idOrJson === "string"
150
+ ? idOrJson
151
+ : idOrJson?.["$id"];
152
+ if (typeof id !== "string")
153
+ return false;
154
+ return VERSION_SUFFIX_RE.test(versionShapeBasename(id));
155
+ }
156
+ /** The `v#` label extracted from a versioned-shape `$id`/`$ref`/basename
157
+ * (e.g. `v1`), or `null` when there is no `.v#` suffix. */
158
+ export function versionLabelOf(idOrRef) {
159
+ const match = versionShapeBasename(idOrRef).match(VERSION_SUFFIX_RE);
160
+ return match ? match[1] : null;
161
+ }
162
+ /** The numeric version pulled from a versioned-shape `$id`/`$ref`/basename
163
+ * (e.g. `2` for `…EquityCompensationIssuance.v2.schema.json`), or `null` when
164
+ * there is no `.v#` suffix. This is the ordering key for "which version is the
165
+ * latest" when `--experimental` collapses a dispatcher to a single shape. */
166
+ export function versionNumberOf(idOrRef) {
167
+ const label = versionLabelOf(idOrRef);
168
+ if (!label)
169
+ return null;
170
+ const n = Number.parseInt(label.slice(1), 10);
171
+ return Number.isNaN(n) ? null : n;
172
+ }
173
+ /**
174
+ * A "version dispatcher" (VersionWrapper) is the versioned analogue of the
175
+ * backwards-compatibility wrapper. The stable, public `$id` lives on a thin
176
+ * schema whose body is an `anyOf` of `$ref`s to concrete, self-contained
177
+ * versioned shapes. Consumers that reference the public `$id` transparently
178
+ * accept every listed shape during a transition window; cutover at a major
179
+ * version is a one-line edit (drop a `$ref`).
180
+ *
181
+ * Detection mirrors `isBackwardsCompatibleWrapper`: a dispatcher carries no
182
+ * `properties` of its own and an `anyOf` whose every entry is a bare `$ref`
183
+ * (exactly one key, `$ref`). The "no own properties" guard excludes ordinary
184
+ * object schemas that use a top-level `anyOf` for conditional constraints.
185
+ *
186
+ * Which `anyOf`-of-`$ref`s is a dispatcher (vs. a generic "one of these object
187
+ * types" union) is decided by an affirmative signal, never inferred from a
188
+ * union alone:
189
+ * - the explicit `x-ocf-version-dispatcher: true` marker (authoritative,
190
+ * rename-proof), or
191
+ * - failing that, the `.v#` versioned-shape filename convention on every
192
+ * referenced shape (the legacy heuristic).
193
+ */
194
+ export function isVersionWrapper(json) {
195
+ if (!json || typeof json !== "object")
196
+ return false;
197
+ const properties = json.properties;
198
+ if (properties && Object.keys(properties).length > 0)
199
+ return false;
200
+ const anyOf = json.anyOf;
201
+ if (!Array.isArray(anyOf) || anyOf.length === 0)
202
+ return false;
203
+ const allBareRefs = anyOf.every((entry) => entry &&
204
+ typeof entry === "object" &&
205
+ typeof entry.$ref === "string" &&
206
+ Object.keys(entry).length === 1);
207
+ if (!allBareRefs)
208
+ return false;
209
+ // The explicit marker is authoritative: it identifies a dispatcher
210
+ // structurally, so the convention can't be defeated by renaming a version
211
+ // file out of the `.v#` pattern.
212
+ if (json[VERSION_DISPATCHER_KEYWORD] === true) {
213
+ return true;
214
+ }
215
+ // Legacy fallback: every referenced shape must follow the `.v#`
216
+ // versioned-shape convention, so a generic union of bare `$ref`s is not
217
+ // mistaken for a dispatcher.
218
+ return versionRefsOf(json).every((ref) => hasVersionSuffix(ref));
219
+ }
220
+ /** The ordered list of versioned-shape `$ref`s declared by a dispatcher. */
221
+ export function versionRefsOf(json) {
222
+ const anyOf = json && json.anyOf;
223
+ if (!Array.isArray(anyOf))
224
+ return [];
225
+ return anyOf
226
+ .map((entry) => entry.$ref)
227
+ .filter((ref) => typeof ref === "string");
228
+ }
229
+ /**
230
+ * Map each versioned-shape `$ref` to the `$id` of the version dispatcher whose
231
+ * `anyOf` references it. Ownership — not the `.v#` filename — is the single
232
+ * source of truth for "this shape belongs to that dispatcher", shared by the
233
+ * validator's `object_type` routing, the doc generator's page folding, and the
234
+ * TypeScript codegen's aggregate types so none of them can disagree on what
235
+ * counts as a versioned shape.
236
+ */
237
+ export function versionShapeOwnerMap(schemas) {
238
+ const owners = new Map();
239
+ for (const schema of schemas) {
240
+ if (schema && isVersionWrapper(schema)) {
241
+ for (const ref of versionRefsOf(schema))
242
+ owners.set(ref, schema.$id);
243
+ }
244
+ }
245
+ return owners;
246
+ }
247
+ /**
248
+ * The literal `object_type` values a schema's `object_type` property declares,
249
+ * via either a `const` string or an `enum` array. Returns `[]` for anything
250
+ * else (missing, a `$ref`, a non-string const, etc.) so callers never
251
+ * dereference an absent `const`. The single reader of this shape, shared by the
252
+ * validator's object-type map, the object doc node, and the version dispatcher.
253
+ */
254
+ export function objectTypeValues(objectType) {
255
+ if (!objectType ||
256
+ typeof objectType !== "object" ||
257
+ Array.isArray(objectType)) {
258
+ return [];
259
+ }
260
+ const ot = objectType;
261
+ if (typeof ot.const === "string")
262
+ return [ot.const];
263
+ if (Array.isArray(ot.enum)) {
264
+ return ot.enum.filter((v) => typeof v === "string");
265
+ }
266
+ return [];
267
+ }
268
+ // ---------------------------------------------------------------------------
269
+ // Experimental mode (version-dispatcher resolution policy)
270
+ // ---------------------------------------------------------------------------
271
+ /**
272
+ * How the toolchain (composer, TypeScript codegen, doc generator) treats a
273
+ * version dispatcher. Selected by the `--experimental` CLI flag.
274
+ *
275
+ * - `compatibility` (the default): keep the dispatcher as-is — the public
276
+ * `$id` accepts the union of every listed shape (codegen emits
277
+ * `V1 | V2 | …`; the docs fold all versions into one page). This is the
278
+ * historical behavior, so the default output is unchanged.
279
+ * - `none`: drop the dispatcher entirely and expose only the latest **stable**
280
+ * versioned shape under the dispatcher's public `$id`. The pre-release /
281
+ * older shapes never reach the public surface.
282
+ * - `unstable`: expose the latest **pre-release** (alpha or beta) versioned
283
+ * shape, falling back to the latest stable shape when none is pre-release.
284
+ * Use this to preview the shape OCF is moving toward. A dispatcher whose
285
+ * only shapes are `planned_deprecation` has no shape in this forward-looking
286
+ * surface: it is dropped entirely (not collapsed), and every `$ref` to it —
287
+ * plus its `object_type`(s) in any enum — is pruned so the remaining schemas
288
+ * still compose / codegen / document cleanly.
289
+ *
290
+ * `none` and `unstable` both *collapse* a dispatcher to a single chosen shape
291
+ * (re-homed onto the public `$id`, with every other version shape removed from
292
+ * the output). They differ only in which shape they pick — and `unstable` may
293
+ * instead drop a dispatcher outright when it is entirely planned-for-deprecation.
294
+ */
295
+ export const EXPERIMENTAL_MODES = [
296
+ "none",
297
+ "compatibility",
298
+ "unstable",
299
+ ];
300
+ /** The default the `--experimental` flag carries when omitted: `compatibility`,
301
+ * so the toolchain's default output is unchanged from before the flag existed
302
+ * (dispatchers stay unions / folded pages). Opt into `none` / `unstable`
303
+ * explicitly to collapse dispatchers to a single shape. */
304
+ export const DEFAULT_EXPERIMENTAL_MODE = "compatibility";
305
+ /** Narrow an arbitrary string to an `ExperimentalMode` (for CLI arg parsing). */
306
+ export function isExperimentalMode(value) {
307
+ return EXPERIMENTAL_MODES.includes(value);
308
+ }
309
+ /** Coerce a parsed CLI value to an `ExperimentalMode`, falling back to the
310
+ * default when it is absent or unrecognized. The yargs CLIs validate the flag
311
+ * via `choices` first, so this just narrows the parsed string to the union
312
+ * type; entrypoints without yargs use `experimentalFromArgv` instead. */
313
+ export function coerceExperimentalMode(value) {
314
+ return isExperimentalMode(value) ? value : DEFAULT_EXPERIMENTAL_MODE;
315
+ }
316
+ /** Parse `--experimental <mode>` / `--experimental=<mode>` from a raw argv
317
+ * slice, falling back to the default when the flag is absent and throwing on an
318
+ * unrecognized value. A dependency-light parser for entrypoints that don't wire
319
+ * up yargs (the doc generator); the yargs CLIs use `coerceExperimentalMode`. */
320
+ export function experimentalFromArgv(argv) {
321
+ const flag = "--experimental";
322
+ for (let i = 0; i < argv.length; i++) {
323
+ const arg = argv[i];
324
+ let value;
325
+ if (arg === flag)
326
+ value = argv[i + 1];
327
+ else if (arg.startsWith(`${flag}=`))
328
+ value = arg.slice(flag.length + 1);
329
+ else
330
+ continue;
331
+ if (!isExperimentalMode(value)) {
332
+ throw new Error(`--experimental must be one of: ${EXPERIMENTAL_MODES.join(", ")}`);
333
+ }
334
+ return value;
335
+ }
336
+ return DEFAULT_EXPERIMENTAL_MODE;
337
+ }
338
+ /**
339
+ * Pick the single versioned shape a collapsing mode (`none` / `unstable`)
340
+ * exposes, from a dispatcher's resolved version shapes (in `anyOf` declaration
341
+ * order). "Latest" is the highest `.v#` number, falling back to declaration
342
+ * order for any shape without a numeric suffix.
343
+ *
344
+ * - `none`: the latest shape whose stability is exactly `stable`; failing
345
+ * that, the latest `planned_deprecation` shape — those are still part of the
346
+ * current stable surface (they only leave under `unstable`), so a dispatcher
347
+ * of only planned-deprecation shapes still resolves here without a warning.
348
+ * - `unstable`: the latest `alpha`/`beta` shape; failing that, the latest
349
+ * `stable` shape. (Callers strip `planned_deprecation` shapes before calling
350
+ * in `unstable` mode — see `applyExperimentalMode` — so they are never
351
+ * selected here.)
352
+ *
353
+ * When neither pool yields a shape (e.g. a dispatcher of only `deprecated`
354
+ * shapes), it falls back to the latest shape overall and flags `fallback: true`
355
+ * so the caller can warn. Returns `null` only for an empty input.
356
+ */
357
+ export function selectVersionForMode(versions, mode) {
358
+ if (versions.length === 0)
359
+ return null;
360
+ const ranked = versions.map((json, index) => ({
361
+ json,
362
+ stability: stabilityOf(json),
363
+ rank: versionNumberOf(json.$id) ?? index,
364
+ }));
365
+ const latest = (pool) => pool.length
366
+ ? pool.reduce((best, c) => (c.rank > best.rank ? c : best))
367
+ : null;
368
+ if (mode === "none") {
369
+ const stable = latest(ranked.filter((c) => c.stability === "stable"));
370
+ if (stable)
371
+ return { selected: stable.json, fallback: false };
372
+ // `planned_deprecation` is still current (it only departs under `unstable`),
373
+ // so it is a valid — and non-fallback — `none` selection when no strictly
374
+ // `stable` shape exists.
375
+ const planned = latest(ranked.filter((c) => c.stability === "planned_deprecation"));
376
+ if (planned)
377
+ return { selected: planned.json, fallback: false };
378
+ }
379
+ else {
380
+ const preRelease = latest(ranked.filter((c) => c.stability === "alpha" || c.stability === "beta"));
381
+ if (preRelease)
382
+ return { selected: preRelease.json, fallback: false };
383
+ const stable = latest(ranked.filter((c) => c.stability === "stable"));
384
+ if (stable)
385
+ return { selected: stable.json, fallback: false };
386
+ }
387
+ // Nothing in the preferred pool(s): expose the latest shape regardless of
388
+ // stability rather than emit an empty dispatcher, and let the caller warn.
389
+ return { selected: latest(ranked).json, fallback: true };
390
+ }
391
+ /**
392
+ * Re-home a selected versioned shape onto its dispatcher's stable public `$id`,
393
+ * producing a normal standalone schema. The dispatcher's public NAME (`title`)
394
+ * wins when non-empty — it carries no `(v#)` suffix — but the `description`
395
+ * stays the selected shape's own: a dispatcher's description narrates the
396
+ * union ("accepts v1 or v2"), which is false for a collapsed single shape.
397
+ * The dispatcher's description is only a fallback for a shape without one.
398
+ * The union body and the `x-ocf-version-dispatcher` marker are dropped (they
399
+ * belong to the dispatcher, not the shape). The selected shape's own `allOf`,
400
+ * `properties`, `required`, `additionalProperties`, and `x-ocf-stability`
401
+ * carry through untouched so downstream composition/codegen/docs treat it
402
+ * like any other schema.
403
+ */
404
+ function collapseDispatcherToVersion(dispatcher, version) {
405
+ const collapsed = { ...version, $id: dispatcher.$id };
406
+ if (dispatcher.title)
407
+ collapsed.title = dispatcher.title;
408
+ if (!collapsed.description && dispatcher.description) {
409
+ collapsed.description = dispatcher.description;
410
+ }
411
+ delete collapsed[VERSION_DISPATCHER_KEYWORD];
412
+ delete collapsed.anyOf;
413
+ return collapsed;
414
+ }
415
+ /**
416
+ * Apply the `--experimental` policy to a flat list of raw schemas BEFORE any
417
+ * composition, codegen, or doc rendering. This is the single shared entry point
418
+ * all three tools call, so they resolve dispatchers identically.
419
+ *
420
+ * - `compatibility`: a no-op — the dispatchers are left intact and the
421
+ * existing dispatcher-aware code paths handle the union / folded page.
422
+ * - `none` / `unstable`: every version dispatcher is replaced by its selected
423
+ * shape (see `selectVersionForMode`) re-homed onto the public `$id`, and
424
+ * every versioned shape it owned is removed from the set. After this pass
425
+ * there are no dispatchers left, so downstream tooling sees only ordinary
426
+ * schemas and needs no per-mode special-casing.
427
+ * - `none` / `unstable` additionally drop every **standalone** schema (a
428
+ * type / enum / primitive that is neither a dispatcher nor a versioned
429
+ * shape) whose stability has no place in that surface: `unstable` drops
430
+ * `planned_deprecation` schemas (the dependency closure of the shapes
431
+ * being superseded), and `none` symmetrically drops pre-release
432
+ * `alpha`/`beta` schemas (the dependency closure of shapes the stable
433
+ * surface doesn't select). `compatibility` keeps everything.
434
+ *
435
+ * Schemas that reference a dispatcher's public `$id` keep working: that `$id`
436
+ * now resolves to the collapsed shape. (Per the VersionWrapper convention,
437
+ * properties reference the public `$id`, never a `.v#` shape directly, so the
438
+ * removed version shapes leave no dangling references.) Any `anyOf`/`oneOf`
439
+ * `$ref` to a wholesale-dropped `$id` — and any dropped `object_type` value in
440
+ * an enum — is pruned from the survivors so the result still resolves cleanly.
441
+ */
442
+ export function applyExperimentalMode(rawSchemas, mode) {
443
+ if (mode === "compatibility")
444
+ return rawSchemas;
445
+ const registry = buildSchemaRegistry(rawSchemas);
446
+ const droppedVersionIds = new Set();
447
+ const collapsedByDispatcherId = new Map();
448
+ // Public `$id`s removed wholesale (not collapsed). Two sources, both only
449
+ // under `unstable`: a dispatcher whose only shapes are `planned_deprecation`,
450
+ // and a standalone planned-for-deprecation schema (see below). Both are
451
+ // treated identically afterward — dropped, then their `$ref`s and
452
+ // `object_type`s pruned from the survivors — so they share one set.
453
+ const droppedPublicIds = new Set();
454
+ const prunedObjectTypes = new Set();
455
+ // Every `$id` that is a versioned shape behind some dispatcher — excluded
456
+ // from the standalone-drop pass below, since the dispatcher loop owns them.
457
+ // Reuses `versionShapeOwnerMap`, the single source of truth for what counts as
458
+ // a versioned shape, so this pass can't disagree with the rest of the tooling.
459
+ const versionShapeIds = new Set(versionShapeOwnerMap(rawSchemas).keys());
460
+ for (const schema of rawSchemas) {
461
+ if (!isVersionWrapper(schema))
462
+ continue;
463
+ const resolved = [];
464
+ for (const ref of versionRefsOf(schema)) {
465
+ const target = registry[ref];
466
+ if (!target) {
467
+ console.warn(`--experimental=${mode}: version dispatcher ${schema.$id} references ` +
468
+ `${ref}, which is not in the schema set; ignoring it.`);
469
+ continue;
470
+ }
471
+ resolved.push(target);
472
+ }
473
+ if (resolved.length === 0) {
474
+ console.warn(`--experimental=${mode}: version dispatcher ${schema.$id} has no ` +
475
+ `resolvable versioned shapes; leaving it unchanged.`);
476
+ continue;
477
+ }
478
+ // Under `unstable`, planned-for-deprecation shapes have no place in the
479
+ // forward-looking surface. Strip them; if nothing is left, the whole
480
+ // dispatcher is dropped (and its refs / enum values pruned below).
481
+ const selectable = mode === "unstable"
482
+ ? resolved.filter((v) => stabilityOf(v) !== "planned_deprecation")
483
+ : resolved;
484
+ if (selectable.length === 0) {
485
+ for (const version of resolved) {
486
+ droppedVersionIds.add(version.$id);
487
+ for (const ot of objectTypeValues(version.properties?.object_type)) {
488
+ prunedObjectTypes.add(ot);
489
+ }
490
+ }
491
+ droppedPublicIds.add(schema.$id);
492
+ continue;
493
+ }
494
+ const selection = selectVersionForMode(selectable, mode);
495
+ if (selection.fallback) {
496
+ const wanted = mode === "none" ? "stable" : "alpha/beta or stable";
497
+ console.warn(`--experimental=${mode}: version dispatcher ${schema.$id} has no ` +
498
+ `${wanted} versioned shape; falling back to ${selection.selected.$id} ` +
499
+ `(${stabilityOf(selection.selected)}).`);
500
+ }
501
+ for (const version of resolved)
502
+ droppedVersionIds.add(version.$id);
503
+ collapsedByDispatcherId.set(schema.$id, collapseDispatcherToVersion(schema, selection.selected));
504
+ }
505
+ // Each collapsed surface also drops standalone schemas — a type / enum /
506
+ // primitive that is neither a dispatcher nor a versioned shape — whose
507
+ // stability has no place in it, mirroring which versioned shapes the mode
508
+ // refuses to select: `unstable` (the forward-looking surface) omits
509
+ // planned-for-deprecation schemas, and `none` (the current stable surface)
510
+ // omits pre-release alpha/beta schemas. Both directions cover the dependency
511
+ // closure of shapes the mode's dispatchers don't expose. (`compatibility`
512
+ // keeps everything.)
513
+ const droppedStandaloneStabilities = mode === "unstable"
514
+ ? new Set(["planned_deprecation"])
515
+ : new Set(["alpha", "beta"]);
516
+ for (const schema of rawSchemas) {
517
+ if (isVersionWrapper(schema))
518
+ continue;
519
+ if (versionShapeIds.has(schema.$id))
520
+ continue;
521
+ if (!droppedStandaloneStabilities.has(stabilityOf(schema)))
522
+ continue;
523
+ droppedPublicIds.add(schema.$id);
524
+ for (const ot of objectTypeValues(schema.properties?.object_type)) {
525
+ prunedObjectTypes.add(ot);
526
+ }
527
+ }
528
+ if (collapsedByDispatcherId.size === 0 && droppedPublicIds.size === 0) {
529
+ return rawSchemas;
530
+ }
531
+ const result = [];
532
+ for (const schema of rawSchemas) {
533
+ if (droppedPublicIds.has(schema.$id))
534
+ continue;
535
+ const collapsed = collapsedByDispatcherId.get(schema.$id);
536
+ if (collapsed) {
537
+ result.push(collapsed);
538
+ continue;
539
+ }
540
+ if (droppedVersionIds.has(schema.$id))
541
+ continue;
542
+ result.push(schema);
543
+ }
544
+ // A wholesale drop leaves the rest of the set pointing at a `$id` (and listing
545
+ // an `object_type`) that no longer exists. Prune both so every surviving
546
+ // schema still resolves, composes, codegens, and documents cleanly. With no
547
+ // wholesale drop there is nothing to prune (`prunedObjectTypes` is only ever
548
+ // populated alongside `droppedPublicIds`), so the survivors pass through.
549
+ const survivors = droppedPublicIds.size === 0
550
+ ? result
551
+ : result.map((schema) => pruneDroppedReferences(schema, droppedPublicIds, prunedObjectTypes));
552
+ // Anything still pointing at a dropped `$id` after pruning (e.g. a property's
553
+ // direct `$ref`) cannot be silently repaired — fail fast with the referencer
554
+ // and target named rather than let it resurface as an opaque missing-$ref
555
+ // error downstream.
556
+ assertNoDanglingDroppedRefs(survivors, new Set([...droppedPublicIds, ...droppedVersionIds]), mode);
557
+ return survivors;
558
+ }
559
+ /**
560
+ * Fail fast when a surviving schema still references an `$id` that was removed
561
+ * from the set. Refs inside `anyOf`/`oneOf`/`allOf` are pruned automatically
562
+ * (see `pruneDroppedReferences`); anything left — e.g. a property's direct
563
+ * `$ref` to a dropped standalone schema, or any ref to a removed `.v#` version
564
+ * shape (which nothing may reference, per the VersionWrapper convention) —
565
+ * would otherwise resurface downstream as an opaque missing-`$ref` failure in
566
+ * composition, codegen, or docs. The error names each referencer and dropped
567
+ * target so the fix is obvious: keep the dropped schema in this surface
568
+ * (adjust its `x-ocf-stability`) or update the referencing schema.
569
+ */
570
+ function assertNoDanglingDroppedRefs(survivors, droppedIds, mode) {
571
+ if (droppedIds.size === 0)
572
+ return;
573
+ const violations = [];
574
+ const scan = (node, ownerId) => {
575
+ if (Array.isArray(node)) {
576
+ for (const item of node)
577
+ scan(item, ownerId);
578
+ return;
579
+ }
580
+ if (!node || typeof node !== "object")
581
+ return;
582
+ const ref = node.$ref;
583
+ if (typeof ref === "string" && droppedIds.has(ref)) {
584
+ violations.push(`${ownerId} -> ${ref}`);
585
+ }
586
+ for (const value of Object.values(node)) {
587
+ scan(value, ownerId);
588
+ }
589
+ };
590
+ for (const schema of survivors)
591
+ scan(schema, schema.$id);
592
+ if (violations.length === 0)
593
+ return;
594
+ throw new Error(`--experimental=${mode}: ${violations.length} reference(s) to schemas ` +
595
+ `dropped from this surface remain after pruning:\n ` +
596
+ `${violations.join("\n ")}\n` +
597
+ `Refs inside anyOf/oneOf/allOf are pruned automatically; a direct $ref ` +
598
+ `cannot be. Either keep the dropped schema in this surface (adjust its ` +
599
+ `x-ocf-stability) or update the referencing schema.`);
600
+ }
601
+ /**
602
+ * Strip every trace of a dropped dispatcher from a surviving schema:
603
+ * - any `anyOf`/`oneOf`/`allOf` entry that is a `$ref` to a dropped `$id`
604
+ * (recursively, so a combinator nested under `properties.items` is handled);
605
+ * - any top-level `enum` value that is a dropped `object_type` (the
606
+ * `ObjectType` enum).
607
+ * Returns the input unchanged (same reference) when nothing matches, so the pass
608
+ * only clones schemas it actually rewrites.
609
+ */
610
+ export function pruneDroppedReferences(schema, droppedRefIds, droppedObjectTypes) {
611
+ const pruned = deepPruneRefs(schema, droppedRefIds);
612
+ let next = pruned.changed ? pruned.value : schema;
613
+ if (droppedObjectTypes.size > 0 &&
614
+ Array.isArray(next.enum)) {
615
+ const original = next.enum;
616
+ const filtered = original.filter((v) => !(typeof v === "string" && droppedObjectTypes.has(v)));
617
+ if (filtered.length !== original.length) {
618
+ next = { ...next, enum: filtered };
619
+ }
620
+ }
621
+ return next;
622
+ }
623
+ /** Composition keywords whose array entries are subschemas we can prune one at
624
+ * a time (a dropped branch just leaves the union/intersection). */
625
+ const COMBINATOR_KEYWORDS = new Set([
626
+ "anyOf",
627
+ "oneOf",
628
+ "allOf",
629
+ ]);
630
+ /** True when a subschema references a dropped `$id`. draft-07 ignores keywords
631
+ * that sit beside a `$ref`, so an entry like `{ $ref, description }` is
632
+ * effectively just the ref and counts as dropped too. */
633
+ function refsDroppedId(entry, droppedRefIds) {
634
+ return (!!entry &&
635
+ typeof entry === "object" &&
636
+ typeof entry.$ref === "string" &&
637
+ droppedRefIds.has(entry.$ref));
638
+ }
639
+ /** Recursively drop `anyOf`/`oneOf`/`allOf` entries that reference a dropped
640
+ * `$id`. If pruning empties a combinator, the keyword is removed rather than
641
+ * left as an unsatisfiable `oneOf: []`/`anyOf: []` (an empty `allOf` is
642
+ * likewise redundant). Returns `{ changed }` so callers avoid cloning
643
+ * untouched subtrees. */
644
+ function deepPruneRefs(node, droppedRefIds) {
645
+ if (Array.isArray(node)) {
646
+ let changed = false;
647
+ const out = node.map((item) => {
648
+ const r = deepPruneRefs(item, droppedRefIds);
649
+ if (r.changed)
650
+ changed = true;
651
+ return r.value;
652
+ });
653
+ return { value: changed ? out : node, changed };
654
+ }
655
+ if (node && typeof node === "object") {
656
+ let changed = false;
657
+ const out = {};
658
+ for (const [key, val] of Object.entries(node)) {
659
+ if (COMBINATOR_KEYWORDS.has(key) && Array.isArray(val)) {
660
+ const kept = val.filter((entry) => !refsDroppedId(entry, droppedRefIds));
661
+ if (kept.length !== val.length)
662
+ changed = true;
663
+ const r = deepPruneRefs(kept, droppedRefIds);
664
+ if (r.changed)
665
+ changed = true;
666
+ // An emptied combinator is dropped, not emitted: an empty `oneOf`/
667
+ // `anyOf` matches nothing (unsatisfiable) and an empty `allOf` is inert.
668
+ if (r.value.length === 0) {
669
+ changed = true;
670
+ continue;
671
+ }
672
+ out[key] = r.value;
673
+ continue;
674
+ }
675
+ const r = deepPruneRefs(val, droppedRefIds);
676
+ if (r.changed)
677
+ changed = true;
678
+ out[key] = r.value;
679
+ }
680
+ return { value: changed ? out : node, changed };
681
+ }
682
+ return { value: node, changed: false };
683
+ }
684
+ /**
685
+ * Build an $id -> raw-schema map from a flat list of raw schema JSONs.
686
+ * Throws if two schemas share an `$id`, because that would make composition
687
+ * ambiguous.
688
+ */
689
+ export function buildSchemaRegistry(rawSchemas) {
690
+ const registry = {};
691
+ for (const json of rawSchemas) {
692
+ if (!json || typeof json !== "object" || typeof json.$id !== "string") {
693
+ continue;
694
+ }
695
+ if (registry[json.$id]) {
696
+ throw new Error(`Duplicate schema $id in registry: ${json.$id}`);
697
+ }
698
+ registry[json.$id] = json;
699
+ }
700
+ return registry;
701
+ }
702
+ /**
703
+ * Raised when a schema's `allOf` `$ref` cannot be resolved in the registry.
704
+ * A typed error (rather than a string-matched message) so callers can decide
705
+ * whether a dangling ref is fatal without coupling to the message text.
706
+ */
707
+ export class MissingRefError extends Error {
708
+ schemaId;
709
+ ref;
710
+ constructor(schemaId, ref) {
711
+ super(`Cannot compose ${schemaId}: unknown allOf $ref '${ref}'`);
712
+ this.schemaId = schemaId;
713
+ this.ref = ref;
714
+ this.name = "MissingRefError";
715
+ }
716
+ }
717
+ /**
718
+ * Compose a single schema by flattening its `allOf` chain.
719
+ *
720
+ * Merge semantics (chosen to be a behavior-preserving extraction of the
721
+ * doc-generator's previous in-class logic):
722
+ *
723
+ * - Wrapper schemas are returned unchanged (only `properties` and
724
+ * `required` are defaulted to {} / []).
725
+ * - For non-wrappers, each entry in `allOf` is composed first (recursively,
726
+ * memoized via `cache`). The composed parents' `properties` are spread
727
+ * in declaration order; then the schema's own `properties` are applied
728
+ * on top, with entries whose value is an empty object (placeholders that
729
+ * opt into inheriting from the parent) skipped so they do not overwrite
730
+ * a parent's definition. Key ORDER is preserved: parents' keys keep
731
+ * their original positions even when the child overrides their values.
732
+ * - `required` is the concatenation of the schema's own `required` and
733
+ * every composed parent's `required` (recursive). Duplicates are
734
+ * intentionally kept to match the pre-extraction behavior.
735
+ *
736
+ * `onMissingRef` controls a single unresolved `allOf` `$ref`:
737
+ * - `"throw"` (default): raise `MissingRefError`.
738
+ * - `"skip"`: warn and drop only that one parent, still merging every parent
739
+ * that DOES resolve. This is per-parent — a missing ancestor never causes
740
+ * a whole subtree to fall back to its raw, un-merged form, so a schema's
741
+ * resolvable inheritance is always reflected regardless of which sibling
742
+ * ref is missing or what order schemas are composed in.
743
+ */
744
+ export function composeSchema(rawJson, registry, cache = new Map(), onMissingRef = "throw") {
745
+ const cached = cache.get(rawJson.$id);
746
+ if (cached)
747
+ return cached;
748
+ if (isBackwardsCompatibleWrapper(rawJson) || isVersionWrapper(rawJson)) {
749
+ // Wrappers (backwards-compat aliases and version dispatchers alike) stand
750
+ // alone: there is no `allOf` chain to flatten, and their `anyOf`/`allOf`
751
+ // body must be preserved verbatim so downstream tooling can resolve the
752
+ // referenced shapes. Only default `properties`/`required` for the type.
753
+ const wrapper = {
754
+ ...rawJson,
755
+ properties: rawJson.properties ?? {},
756
+ required: rawJson.required ? [...rawJson.required] : [],
757
+ };
758
+ cache.set(rawJson.$id, wrapper);
759
+ return wrapper;
760
+ }
761
+ const allOf = rawJson.allOf ?? [];
762
+ const parents = [];
763
+ for (const ref of allOf) {
764
+ const parentRaw = registry[ref.$ref];
765
+ if (!parentRaw) {
766
+ if (onMissingRef === "skip") {
767
+ console.warn(`Composing ${rawJson.$id}: skipping unknown allOf $ref '${ref.$ref}' (its inherited properties will be absent).`);
768
+ continue;
769
+ }
770
+ throw new MissingRefError(rawJson.$id, ref.$ref);
771
+ }
772
+ parents.push(composeSchema(parentRaw, registry, cache, onMissingRef));
773
+ }
774
+ const mergedProperties = {};
775
+ for (const parent of parents) {
776
+ Object.assign(mergedProperties, parent.properties ?? {});
777
+ }
778
+ for (const [name, value] of Object.entries(rawJson.properties ?? {})) {
779
+ const isPlaceholder = value && typeof value === "object" && Object.keys(value).length === 0;
780
+ if (!isPlaceholder) {
781
+ mergedProperties[name] = value;
782
+ }
783
+ }
784
+ const required = [
785
+ ...(rawJson.required ?? []),
786
+ ...parents.flatMap((parent) => parent.required ?? []),
787
+ ];
788
+ const composed = {
789
+ ...rawJson,
790
+ properties: mergedProperties,
791
+ required,
792
+ };
793
+ cache.set(rawJson.$id, composed);
794
+ return composed;
795
+ }
796
+ /**
797
+ * Compose every schema in `rawSchemas` and return both the registry of raw
798
+ * schemas and the parallel registry of composed schemas (keyed by `$id`),
799
+ * plus the composed list in the same order as the input. Useful for callers
800
+ * (the doc generator, external utilities) that want one pass over the full
801
+ * schema tree.
802
+ */
803
+ export function composeAll(rawSchemas, options = {}) {
804
+ const { onMissingRef = "throw" } = options;
805
+ const registry = buildSchemaRegistry(rawSchemas);
806
+ const cache = new Map();
807
+ const composed = rawSchemas.map((raw) => composeSchema(raw, registry, cache, onMissingRef));
808
+ const composedById = {};
809
+ for (const c of composed)
810
+ composedById[c.$id] = c;
811
+ return { registry, composed, composedById };
812
+ }
813
+ /**
814
+ * Drop a vacuous `properties: {}` / `required: []` from a composed (or
815
+ * dereferenced) schema before it is serialized to a file. The composer defaults
816
+ * both fields on every schema so the in-memory shape is uniform, but a written
817
+ * enum or scalar-type schema has no properties and no required list — emitting
818
+ * the empty containers just adds noise to the output. Non-empty values and
819
+ * object schemas are left untouched. Returns a shallow clone; the input is not
820
+ * mutated.
821
+ */
822
+ export function omitEmptyComposedContainers(schema) {
823
+ const clone = { ...schema };
824
+ const properties = clone.properties;
825
+ if (properties &&
826
+ typeof properties === "object" &&
827
+ !Array.isArray(properties) &&
828
+ Object.keys(properties).length === 0) {
829
+ delete clone.properties;
830
+ }
831
+ if (Array.isArray(clone.required) && clone.required.length === 0) {
832
+ delete clone.required;
833
+ }
834
+ return clone;
835
+ }