document-model 6.2.3-dev.90 → 6.2.3-dev.92

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.
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
- import { actions, assertIsDocumentModelDocument, assertIsDocumentModelState, baseCreateDocument, createState, defaultBaseState, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelReducer, documentModelSaveToFileHandle, isDocumentModelDocument, isDocumentModelState } from "@powerhousedao/shared/document-model";
1
+ import { n as getCatalogScalar, o as isScalarDefinition, r as scalarCatalog, s as scalarDefinitionVersion, t as documentModelScalars } from "./catalog-6zzASEUv.js";
2
+ import { BaseDocumentHeaderSchema, BaseDocumentStateSchema, actions, assertIsDocumentModelDocument, assertIsDocumentModelState, baseActions, baseCreateDocument, baseLoadFromInputVersioned, baseSaveToFileHandle, createAction, createBaseState, createReducer, createState, defaultBaseState, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelReducer, documentModelSaveToFileHandle, isDocumentAction, isDocumentModelDocument, isDocumentModelState, normalizeDocumentModelVersion } from "@powerhousedao/shared/document-model";
3
+ import { z } from "zod";
4
+ import { camelCase, constantCase, pascalCase } from "change-case";
2
5
  export * from "@powerhousedao/shared/document-model";
3
6
  //#region src/state.ts
4
7
  const isStateOfType = (state) => {
@@ -219,7 +222,4431 @@ const setErrorHandler = (handler) => {
219
222
  const childLogger = (tags) => {
220
223
  return logger.child(tags);
221
224
  };
225
+ new Uint32Array([
226
+ 1116352408,
227
+ 1899447441,
228
+ 3049323471,
229
+ 3921009573,
230
+ 961987163,
231
+ 1508970993,
232
+ 2453635748,
233
+ 2870763221,
234
+ 3624381080,
235
+ 310598401,
236
+ 607225278,
237
+ 1426881987,
238
+ 1925078388,
239
+ 2162078206,
240
+ 2614888103,
241
+ 3248222580,
242
+ 3835390401,
243
+ 4022224774,
244
+ 264347078,
245
+ 604807628,
246
+ 770255983,
247
+ 1249150122,
248
+ 1555081692,
249
+ 1996064986,
250
+ 2554220882,
251
+ 2821834349,
252
+ 2952996808,
253
+ 3210313671,
254
+ 3336571891,
255
+ 3584528711,
256
+ 113926993,
257
+ 338241895,
258
+ 666307205,
259
+ 773529912,
260
+ 1294757372,
261
+ 1396182291,
262
+ 1695183700,
263
+ 1986661051,
264
+ 2177026350,
265
+ 2456956037,
266
+ 2730485921,
267
+ 2820302411,
268
+ 3259730800,
269
+ 3345764771,
270
+ 3516065817,
271
+ 3600352804,
272
+ 4094571909,
273
+ 275423344,
274
+ 430227734,
275
+ 506948616,
276
+ 659060556,
277
+ 883997877,
278
+ 958139571,
279
+ 1322822218,
280
+ 1537002063,
281
+ 1747873779,
282
+ 1955562222,
283
+ 2024104815,
284
+ 2227730452,
285
+ 2361852424,
286
+ 2428436474,
287
+ 2756734187,
288
+ 3204031479,
289
+ 3329325298
290
+ ]);
291
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
292
+ function uuidBytes(uuid) {
293
+ if (!UUID_PATTERN.test(uuid)) throw new TypeError(`UUID namespace ${JSON.stringify(uuid)} is not canonical.`);
294
+ const hex = uuid.replaceAll("-", "");
295
+ return Uint8Array.from({ length: 16 }, (_, index) => Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16));
296
+ }
297
+ function formatUuid(bytes) {
298
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
299
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
300
+ }
301
+ function uuidV5(namespace, name) {
302
+ const namespaceBytes = uuidBytes(namespace);
303
+ const nameBytes = new TextEncoder().encode(name);
304
+ const input = new Uint8Array(namespaceBytes.length + nameBytes.length);
305
+ input.set(namespaceBytes);
306
+ input.set(nameBytes, namespaceBytes.length);
307
+ const digest = sha1(input).slice(0, 16);
308
+ digest[6] = digest[6] & 15 | 80;
309
+ digest[8] = digest[8] & 63 | 128;
310
+ return formatUuid(digest);
311
+ }
312
+ function rotateLeft(value, shift) {
313
+ return (value << shift | value >>> 32 - shift) >>> 0;
314
+ }
315
+ function sha1(bytes) {
316
+ const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;
317
+ const input = new Uint8Array(paddedLength);
318
+ input.set(bytes);
319
+ input[bytes.length] = 128;
320
+ const view = new DataView(input.buffer);
321
+ const bitLength = BigInt(bytes.length) * 8n;
322
+ view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);
323
+ view.setUint32(paddedLength - 4, Number(bitLength & 4294967295n), false);
324
+ const state = new Uint32Array([
325
+ 1732584193,
326
+ 4023233417,
327
+ 2562383102,
328
+ 271733878,
329
+ 3285377520
330
+ ]);
331
+ const words = /* @__PURE__ */ new Uint32Array(80);
332
+ for (let offset = 0; offset < paddedLength; offset += 64) {
333
+ for (let index = 0; index < 16; index += 1) words[index] = view.getUint32(offset + index * 4, false);
334
+ for (let index = 16; index < 80; index += 1) words[index] = rotateLeft(words[index - 3] ^ words[index - 8] ^ words[index - 14] ^ words[index - 16], 1);
335
+ let a = state[0];
336
+ let b = state[1];
337
+ let c = state[2];
338
+ let d = state[3];
339
+ let e = state[4];
340
+ for (let index = 0; index < 80; index += 1) {
341
+ let f;
342
+ let k;
343
+ if (index < 20) {
344
+ f = b & c | ~b & d;
345
+ k = 1518500249;
346
+ } else if (index < 40) {
347
+ f = b ^ c ^ d;
348
+ k = 1859775393;
349
+ } else if (index < 60) {
350
+ f = b & c | b & d | c & d;
351
+ k = 2400959708;
352
+ } else {
353
+ f = b ^ c ^ d;
354
+ k = 3395469782;
355
+ }
356
+ const next = rotateLeft(a, 5) + f + e + k + words[index] >>> 0;
357
+ e = d;
358
+ d = c;
359
+ c = rotateLeft(b, 30);
360
+ b = a;
361
+ a = next;
362
+ }
363
+ state[0] = state[0] + a >>> 0;
364
+ state[1] = state[1] + b >>> 0;
365
+ state[2] = state[2] + c >>> 0;
366
+ state[3] = state[3] + d >>> 0;
367
+ state[4] = state[4] + e >>> 0;
368
+ }
369
+ const digest = /* @__PURE__ */ new Uint8Array(20);
370
+ const digestView = new DataView(digest.buffer);
371
+ state.forEach((word, index) => {
372
+ digestView.setUint32(index * 4, word, false);
373
+ });
374
+ return digest;
375
+ }
376
+ //#endregion
377
+ //#region src/definition/kernel/primitives.ts
378
+ function memberPath(parent, key) {
379
+ if (typeof key === "number") return `${parent}[${key}]`;
380
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
381
+ }
382
+ function encodeProperty(descriptor, path, ancestors) {
383
+ if (!("value" in descriptor)) throw new TypeError(`${path} must be a data property, not an accessor.`);
384
+ if (descriptor.enumerable !== true) throw new TypeError(`${path} must be enumerable.`);
385
+ return encode(descriptor.value, path, ancestors);
386
+ }
387
+ function encodeArray(value, path, ancestors) {
388
+ if (Object.getPrototypeOf(value) !== Array.prototype) throw new TypeError(`${path} must be a plain array.`);
389
+ for (const key of Reflect.ownKeys(value)) {
390
+ if (key === "length") continue;
391
+ if (typeof key === "symbol") throw new TypeError(`${path} must not have symbol keys.`);
392
+ if (!/^(?:0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length) throw new TypeError(`${path} must not have a non-index property ${JSON.stringify(key)}.`);
393
+ }
394
+ const members = [];
395
+ for (let index = 0; index < value.length; index += 1) {
396
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
397
+ if (descriptor === void 0) throw new TypeError(`${memberPath(path, index)} must not be an array hole.`);
398
+ members.push(encodeProperty(descriptor, memberPath(path, index), ancestors));
399
+ }
400
+ return `[${members.join(",")}]`;
401
+ }
402
+ function encodeObject(value, path, ancestors) {
403
+ const prototype = Object.getPrototypeOf(value);
404
+ if (prototype !== Object.prototype && prototype !== null) throw new TypeError(`${path} must be a plain object.`);
405
+ const keys = [];
406
+ for (const key of Reflect.ownKeys(value)) {
407
+ if (typeof key === "symbol") throw new TypeError(`${path} must not have symbol keys.`);
408
+ keys.push(key);
409
+ }
410
+ keys.sort(compareCodeUnits);
411
+ const members = [];
412
+ for (const key of keys) {
413
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
414
+ if (descriptor === void 0) throw new TypeError(`${memberPath(path, key)} must be an own property.`);
415
+ members.push(`${JSON.stringify(key)}:${encodeProperty(descriptor, memberPath(path, key), ancestors)}`);
416
+ }
417
+ return `{${members.join(",")}}`;
418
+ }
419
+ function encode(value, path, ancestors) {
420
+ switch (typeof value) {
421
+ case "string":
422
+ case "boolean": return JSON.stringify(value);
423
+ case "number":
424
+ if (Number.isFinite(value)) return JSON.stringify(value);
425
+ throw new TypeError(`${path} must be a finite number.`);
426
+ case "object": {
427
+ if (value === null) return "null";
428
+ if (ancestors.has(value)) throw new TypeError(`${path} must not contain a cycle.`);
429
+ ancestors.add(value);
430
+ const encoded = Array.isArray(value) ? encodeArray(value, path, ancestors) : encodeObject(value, path, ancestors);
431
+ ancestors.delete(value);
432
+ return encoded;
433
+ }
434
+ default: throw new TypeError(`${path} must be a JSON value, received ${typeof value}.`);
435
+ }
436
+ }
437
+ function canonicalJson(value) {
438
+ return encode(value, "$", /* @__PURE__ */ new Set());
439
+ }
440
+ function compareCodeUnits(a, b) {
441
+ return a < b ? -1 : a > b ? 1 : 0;
442
+ }
443
+ const DIGIT_0 = 48;
444
+ const DIGIT_9 = 57;
445
+ function isDigit(code) {
446
+ return DIGIT_0 <= code && code <= DIGIT_9;
447
+ }
448
+ /**
449
+ * graphql-js's `naturalCompare`, which `lexicographicSortSchema` sorts a
450
+ * generated schema with: runs of digits compare as numbers, so `item2`
451
+ * precedes `item10`. Copied, not imported, so a model never loads `graphql`.
452
+ */
453
+ function compareGeneratedOrder(a, b) {
454
+ let aIndex = 0;
455
+ let bIndex = 0;
456
+ while (aIndex < a.length && bIndex < b.length) {
457
+ let aChar = a.charCodeAt(aIndex);
458
+ let bChar = b.charCodeAt(bIndex);
459
+ if (isDigit(aChar) && isDigit(bChar)) {
460
+ let aNumber = 0;
461
+ do {
462
+ ++aIndex;
463
+ aNumber = aNumber * 10 + aChar - DIGIT_0;
464
+ aChar = a.charCodeAt(aIndex);
465
+ } while (isDigit(aChar) && aNumber > 0);
466
+ let bNumber = 0;
467
+ do {
468
+ ++bIndex;
469
+ bNumber = bNumber * 10 + bChar - DIGIT_0;
470
+ bChar = b.charCodeAt(bIndex);
471
+ } while (isDigit(bChar) && bNumber > 0);
472
+ if (aNumber !== bNumber) return aNumber < bNumber ? -1 : 1;
473
+ } else {
474
+ if (aChar !== bChar) return aChar < bChar ? -1 : 1;
475
+ ++aIndex;
476
+ ++bIndex;
477
+ }
478
+ }
479
+ return a.length - b.length;
480
+ }
481
+ const EMPTY_INPUT_FIELD_NAME = "_empty";
482
+ function isGraphQLName(value) {
483
+ return typeof value === "string" && /^[_A-Za-z][_0-9A-Za-z]*$/.test(value);
484
+ }
485
+ function isAuthoredSchemaName(value) {
486
+ return isGraphQLName(value) && !value.startsWith("__");
487
+ }
488
+ function isEnumValueName(value) {
489
+ return isAuthoredSchemaName(value) && value !== "true" && value !== "false" && value !== "null";
490
+ }
491
+ function isNFC(value) {
492
+ return value.normalize("NFC") === value;
493
+ }
494
+ //#endregion
495
+ //#region src/definition/kernel/diagnostics.ts
496
+ const MAX_SUMMARY_CODE_POINTS = 512;
497
+ function capCodePoints(value, max = MAX_SUMMARY_CODE_POINTS) {
498
+ const points = [...value];
499
+ const limit = Math.max(0, max);
500
+ return points.length <= limit ? value : points.slice(0, limit).join("");
501
+ }
502
+ function copySource(source) {
503
+ return {
504
+ specifier: source.specifier,
505
+ ...source.exportPath !== void 0 && { exportPath: [...source.exportPath] }
506
+ };
507
+ }
508
+ function copyDefinitionRef(definition) {
509
+ return {
510
+ kind: definition.kind,
511
+ key: definition.key,
512
+ ...definition.version !== void 0 && { version: definition.version }
513
+ };
514
+ }
515
+ function createDiagnostic(input, { severity, phase }) {
516
+ return {
517
+ code: input.code,
518
+ severity,
519
+ phase,
520
+ ...input.source !== void 0 && { source: copySource(input.source) },
521
+ ...input.definition !== void 0 && { definition: copyDefinitionRef(input.definition) },
522
+ path: [...input.path],
523
+ message: input.message,
524
+ ...input.expected !== void 0 && { expected: capCodePoints(input.expected) },
525
+ ...input.received !== void 0 && { received: capCodePoints(input.received) },
526
+ repair: input.repair,
527
+ ...input.related !== void 0 && { related: input.related.map((location) => ({
528
+ ...location.source !== void 0 && { source: copySource(location.source) },
529
+ path: [...location.path],
530
+ message: location.message
531
+ })) }
532
+ };
533
+ }
534
+ function describeReceived(value) {
535
+ if (value === null) return "null";
536
+ try {
537
+ return Array.isArray(value) ? "array" : typeof value;
538
+ } catch {
539
+ return "inspection-failed";
540
+ }
541
+ }
542
+ /**
543
+ * A layer's catalog: its own codes plus the codes of the catalog below it,
544
+ * which already holds every lower layer's codes. A code keeps the meaning its
545
+ * owning layer gave it, so an own code the lower catalog declares is refused.
546
+ */
547
+ function defineDiagnosticCatalog(own, lower) {
548
+ const lowerCodes = lower?.codes ?? {};
549
+ const ownEntries = Object.entries(own).map(([code, entry]) => [code, Object.freeze({ ...entry })]);
550
+ const redefined = ownEntries.map(([code]) => code).filter((code) => Object.hasOwn(lowerCodes, code));
551
+ if (redefined.length > 0) throw new TypeError(`Diagnostic code ${redefined.join(", ")} is already declared by a lower layer.`);
552
+ const codes = Object.freeze({
553
+ ...lowerCodes,
554
+ ...Object.fromEntries(ownEntries)
555
+ });
556
+ const create = (input) => createDiagnostic(input, codes[input.code]);
557
+ return Object.freeze({
558
+ codes,
559
+ create,
560
+ fail(input) {
561
+ throw new DefinitionError([create(input)]);
562
+ }
563
+ });
564
+ }
565
+ function compareNumbers(a, b) {
566
+ return a < b ? -1 : a > b ? 1 : 0;
567
+ }
568
+ function compareOptional(a, b, compare) {
569
+ if (a === void 0) return b === void 0 ? 0 : -1;
570
+ if (b === void 0) return 1;
571
+ return compare(a, b);
572
+ }
573
+ function compareLists(a, b, compare) {
574
+ const shared = Math.min(a.length, b.length);
575
+ for (let index = 0; index < shared; index += 1) {
576
+ const result = compare(a[index], b[index]);
577
+ if (result !== 0) return result;
578
+ }
579
+ return compareNumbers(a.length, b.length);
580
+ }
581
+ function comparePathSegments(a, b) {
582
+ if (typeof a === "number") return typeof b === "number" ? compareNumbers(a, b) : -1;
583
+ if (typeof b === "number") return 1;
584
+ return compareCodeUnits(a, b);
585
+ }
586
+ function compareDefinitionPaths(a, b) {
587
+ return compareLists(a, b, comparePathSegments);
588
+ }
589
+ function compareSources(a, b) {
590
+ const specifier = compareCodeUnits(a.specifier, b.specifier);
591
+ if (specifier !== 0) return specifier;
592
+ return compareOptional(a.exportPath, b.exportPath, (x, y) => compareLists(x, y, compareCodeUnits));
593
+ }
594
+ function compareDefinitionRefs(a, b) {
595
+ const kind = compareCodeUnits(a.kind, b.kind);
596
+ if (kind !== 0) return kind;
597
+ const key = compareCodeUnits(a.key, b.key);
598
+ if (key !== 0) return key;
599
+ return compareOptional(a.version, b.version, compareNumbers);
600
+ }
601
+ function compareDefinitionDiagnostics(a, b) {
602
+ const source = compareOptional(a.source, b.source, compareSources);
603
+ if (source !== 0) return source;
604
+ const definition = compareOptional(a.definition, b.definition, compareDefinitionRefs);
605
+ if (definition !== 0) return definition;
606
+ const path = compareDefinitionPaths(a.path, b.path);
607
+ if (path !== 0) return path;
608
+ return compareCodeUnits(a.code, b.code);
609
+ }
610
+ function sortDefinitionDiagnostics(diagnostics) {
611
+ return [...diagnostics].sort(compareDefinitionDiagnostics);
612
+ }
613
+ function formatPointer(path) {
614
+ if (path.length === 0) return "(root)";
615
+ return path.map((segment) => `/${String(segment).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
616
+ }
617
+ function formatSource(source) {
618
+ if (source === void 0) return "(no source)";
619
+ const exportPath = source.exportPath ?? [];
620
+ return exportPath.length === 0 ? source.specifier : `${source.specifier}#${formatPointer(exportPath)}`;
621
+ }
622
+ function formatDefinitionRef(definition) {
623
+ if (definition === void 0) return "";
624
+ const version = definition.version === void 0 ? "" : `@${definition.version}`;
625
+ return ` ${definition.kind} ${definition.key}${version}`;
626
+ }
627
+ function oneLine(value) {
628
+ return value.replace(/\s+/g, " ");
629
+ }
630
+ /** @experimental One line: code, severity and phase, location, message, expected, received, related and repair. */
631
+ function formatDefinitionDiagnostic(diagnostic) {
632
+ const where = `${formatSource(diagnostic.source)}${formatDefinitionRef(diagnostic.definition)} ${formatPointer(diagnostic.path)}`;
633
+ const expected = diagnostic.expected === void 0 ? "" : ` Expected: ${oneLine(diagnostic.expected)}`;
634
+ const received = diagnostic.received === void 0 ? "" : ` Received: ${oneLine(diagnostic.received)}`;
635
+ const related = (diagnostic.related ?? []).map((location) => ` Related: ${formatSource(location.source)} ${formatPointer(location.path)}: ${oneLine(location.message)}`).join("");
636
+ return `${diagnostic.code} [${diagnostic.severity}/${diagnostic.phase}] ${where}: ${oneLine(diagnostic.message)}${expected}${received}${related} Repair: ${oneLine(diagnostic.repair)}`;
637
+ }
638
+ /**
639
+ * @experimental Thrown when a code-first declaration is refused. `diagnostics`
640
+ * holds every problem found, sorted, each with its code, path and repair.
641
+ */
642
+ var DefinitionError = class extends Error {
643
+ diagnostics;
644
+ constructor(diagnostics) {
645
+ if (diagnostics.length === 0) throw new TypeError("DefinitionError requires at least one diagnostic.");
646
+ const sorted = sortDefinitionDiagnostics(diagnostics);
647
+ const noun = sorted.length === 1 ? "diagnostic" : "diagnostics";
648
+ super([`Definition failed with ${sorted.length} ${noun}:`, ...sorted.map(formatDefinitionDiagnostic)].join("\n"));
649
+ this.name = "DefinitionError";
650
+ this.diagnostics = sorted;
651
+ }
652
+ };
653
+ //#endregion
654
+ //#region src/definition/dsl/diagnostic-codes.ts
655
+ const dslDiagnostics = defineDiagnosticCatalog({
656
+ "PH-DEF-FIELD-OPTION-UNSUPPORTED": {
657
+ severity: "error",
658
+ phase: "definition",
659
+ meaning: "A field use contains an option its builder or its position does not support"
660
+ },
661
+ "PH-DEF-TYPE-AS-FIELD": {
662
+ severity: "error",
663
+ phase: "definition",
664
+ meaning: "A named type is used as a field without ph.ref"
665
+ },
666
+ "PH-DEF-NAME-INVALID": {
667
+ severity: "error",
668
+ phase: "definition",
669
+ meaning: "An authored GraphQL type, field, or enum value name is lexically invalid or reserved"
670
+ },
671
+ "PH-DEF-FIELD-INVALID": {
672
+ severity: "error",
673
+ phase: "definition",
674
+ meaning: "A field position holds a value that is neither a field use nor a named type"
675
+ },
676
+ "PH-DEF-REFERENCE-TARGET-INVALID": {
677
+ severity: "error",
678
+ phase: "definition",
679
+ meaning: "A ph.ref target is not a named type: a field use, another reference, undefined, or an anonymous input"
680
+ },
681
+ "PH-DEF-ENUM-VALUES-INVALID": {
682
+ severity: "error",
683
+ phase: "definition",
684
+ meaning: "An enum declares no values, a duplicate value, or a reserved value"
685
+ },
686
+ "PH-DEF-UNION-MEMBERS-INVALID": {
687
+ severity: "error",
688
+ phase: "definition",
689
+ meaning: "A union declares no members, a duplicate member, or a member that is not a ph.object"
690
+ },
691
+ "PH-DEF-IMPLEMENTS-INVALID": {
692
+ severity: "error",
693
+ phase: "definition",
694
+ meaning: "An object or an interface implements something that is not a ph.interface, or the same interface twice"
695
+ },
696
+ "PH-SCALAR-FACTORY-AS-FIELD": {
697
+ severity: "error",
698
+ phase: "definition",
699
+ meaning: "A scalar field-use factory is used as a field without being called"
700
+ },
701
+ "PH-SCALAR-INTERNAL": {
702
+ severity: "error",
703
+ phase: "definition",
704
+ meaning: "A field uses a catalog scalar that only the reactor host declares, such as JSONObject"
705
+ },
706
+ "PH-SCALAR-DEFINITION-INVALID": {
707
+ severity: "error",
708
+ phase: "definition",
709
+ meaning: "ph.scalar received a value that is not a scalar definition of this release's format"
710
+ }
711
+ }, defineDiagnosticCatalog({
712
+ "PH-DEF-OPTION-INVALID": {
713
+ severity: "error",
714
+ phase: "definition",
715
+ meaning: "An option is malformed: wrong type, accessor, symbol key, non-plain object, an explicit undefined or non-JSON default, or an @equals pattern the generator cannot write"
716
+ },
717
+ "PH-DEF-COMPATIBILITY-INVALID": {
718
+ severity: "error",
719
+ phase: "definition",
720
+ meaning: "A location-free GraphQL compatibility AST is malformed or disagrees with the stored definitions it accompanies"
721
+ }
722
+ }));
723
+ //#endregion
724
+ //#region src/definition/kernel/global-registry.ts
725
+ function getGlobalRegistry(key, create) {
726
+ const registries = globalThis;
727
+ return registries[Symbol.for(key)] ??= create();
728
+ }
729
+ //#endregion
730
+ //#region src/definition/dsl/descriptor-registry.ts
731
+ const registry = getGlobalRegistry("powerhouse.document-model.descriptors.v1", () => ({
732
+ fieldDescriptors: /* @__PURE__ */ new WeakSet(),
733
+ typeDescriptors: /* @__PURE__ */ new WeakSet(),
734
+ scalarFactories: /* @__PURE__ */ new WeakSet(),
735
+ referenceResolvers: /* @__PURE__ */ new WeakMap()
736
+ }));
737
+ function registerFieldDescriptor(descriptor) {
738
+ registry.fieldDescriptors.add(descriptor);
739
+ return descriptor;
740
+ }
741
+ function registerTypeDescriptor(descriptor) {
742
+ registry.typeDescriptors.add(descriptor);
743
+ return descriptor;
744
+ }
745
+ function registerScalarFactory(factory) {
746
+ registry.scalarFactories.add(factory);
747
+ return factory;
748
+ }
749
+ function isFieldDescriptor(value) {
750
+ return value !== null && typeof value === "object" && registry.fieldDescriptors.has(value);
751
+ }
752
+ function isTypeDescriptor(value) {
753
+ return value !== null && typeof value === "object" && registry.typeDescriptors.has(value);
754
+ }
755
+ function isScalarFactory(value) {
756
+ return typeof value === "function" && registry.scalarFactories.has(value);
757
+ }
758
+ function registerReference(descriptor, resolve) {
759
+ registry.referenceResolvers.set(descriptor, resolve);
760
+ return descriptor;
761
+ }
762
+ function referenceResolver(descriptor) {
763
+ return registry.referenceResolvers.get(descriptor);
764
+ }
765
+ //#endregion
766
+ //#region src/definition/kernel/data-properties.ts
767
+ function rejectionReceived(rejection) {
768
+ return "received" in rejection ? rejection.received : rejection.reason;
769
+ }
770
+ const CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;
771
+ function snapshotDataRecord(value, allowedKeys, path) {
772
+ return snapshotPlainObject(value, allowedKeys, path, snapshotDataValue, /* @__PURE__ */ new Set());
773
+ }
774
+ function snapshotArray(value, path) {
775
+ return snapshotArrayValue(value, path, (member) => ({
776
+ ok: true,
777
+ value: member
778
+ }), /* @__PURE__ */ new Set());
779
+ }
780
+ function snapshotArrayValue(value, path, member, ancestors) {
781
+ try {
782
+ if (!Array.isArray(value)) return {
783
+ ok: false,
784
+ reason: "not-array",
785
+ path,
786
+ received: describeReceived(value)
787
+ };
788
+ } catch {
789
+ return {
790
+ ok: false,
791
+ reason: "inspection-failed",
792
+ path
793
+ };
794
+ }
795
+ if (ancestors.has(value)) return {
796
+ ok: false,
797
+ reason: "cycle",
798
+ path
799
+ };
800
+ ancestors.add(value);
801
+ try {
802
+ return snapshotArrayMembers(value, path, member, ancestors);
803
+ } finally {
804
+ ancestors.delete(value);
805
+ }
806
+ }
807
+ function snapshotArrayMembers(value, path, member, ancestors) {
808
+ let prototype;
809
+ let keys;
810
+ let lengthDescriptor;
811
+ try {
812
+ prototype = Object.getPrototypeOf(value);
813
+ keys = Reflect.ownKeys(value);
814
+ lengthDescriptor = Object.getOwnPropertyDescriptor(value, "length");
815
+ } catch {
816
+ return {
817
+ ok: false,
818
+ reason: "inspection-failed",
819
+ path
820
+ };
821
+ }
822
+ if (prototype !== Array.prototype) return {
823
+ ok: false,
824
+ reason: "custom-prototype",
825
+ path,
826
+ expected: "array",
827
+ received: "array of another prototype or realm"
828
+ };
829
+ const length = lengthDescriptor?.value;
830
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0) return {
831
+ ok: false,
832
+ reason: "inspection-failed",
833
+ path
834
+ };
835
+ for (const key of keys) {
836
+ if (key === "length") continue;
837
+ if (typeof key === "symbol") return {
838
+ ok: false,
839
+ reason: "symbol-key",
840
+ path,
841
+ key
842
+ };
843
+ if (!CANONICAL_INDEX.test(key) || Number(key) >= length) return {
844
+ ok: false,
845
+ reason: "array-property",
846
+ path: [...path, key],
847
+ key
848
+ };
849
+ }
850
+ const elements = [];
851
+ for (let index = 0; index < length; index += 1) {
852
+ const elementPath = [...path, index];
853
+ let descriptor;
854
+ try {
855
+ descriptor = Object.getOwnPropertyDescriptor(value, index);
856
+ } catch {
857
+ return {
858
+ ok: false,
859
+ reason: "inspection-failed",
860
+ path: elementPath
861
+ };
862
+ }
863
+ if (descriptor === void 0) return {
864
+ ok: false,
865
+ reason: "sparse",
866
+ path: elementPath,
867
+ key: index
868
+ };
869
+ const propertyValue = dataPropertyValue(descriptor, index, elementPath);
870
+ if (!propertyValue.ok) return propertyValue;
871
+ const element = member(propertyValue.value, elementPath, ancestors);
872
+ if (!element.ok) return element;
873
+ elements.push(element.value);
874
+ }
875
+ return {
876
+ ok: true,
877
+ value: Object.freeze(elements)
878
+ };
879
+ }
880
+ function snapshotRecord(value, allowedKeys, path, ignoredKeys = []) {
881
+ return snapshotPlainObject(value, allowedKeys, path, (member) => ({
882
+ ok: true,
883
+ value: member
884
+ }), /* @__PURE__ */ new Set(), ignoredKeys);
885
+ }
886
+ function snapshotPlainObject(value, allowedKeys, path, member, ancestors, ignoredKeys = []) {
887
+ if (value === null || typeof value !== "object") return {
888
+ ok: false,
889
+ reason: "not-record",
890
+ path,
891
+ received: describeReceived(value)
892
+ };
893
+ if (ancestors.has(value)) return {
894
+ ok: false,
895
+ reason: "cycle",
896
+ path
897
+ };
898
+ ancestors.add(value);
899
+ try {
900
+ return snapshotPlainObjectMembers(value, allowedKeys, path, member, ancestors, ignoredKeys);
901
+ } finally {
902
+ ancestors.delete(value);
903
+ }
904
+ }
905
+ function snapshotPlainObjectMembers(value, allowedKeys, path, member, ancestors, ignoredKeys) {
906
+ let isArray;
907
+ let prototype;
908
+ let keys;
909
+ try {
910
+ isArray = Array.isArray(value);
911
+ prototype = Object.getPrototypeOf(value);
912
+ keys = Reflect.ownKeys(value);
913
+ } catch {
914
+ return {
915
+ ok: false,
916
+ reason: "inspection-failed",
917
+ path
918
+ };
919
+ }
920
+ if (isArray) return {
921
+ ok: false,
922
+ reason: "not-record",
923
+ path,
924
+ received: "array"
925
+ };
926
+ if (prototype !== Object.prototype && prototype !== null) return {
927
+ ok: false,
928
+ reason: "custom-prototype",
929
+ path,
930
+ expected: "record",
931
+ received: "object"
932
+ };
933
+ const entries = [];
934
+ for (const key of keys) {
935
+ if (typeof key === "symbol") return {
936
+ ok: false,
937
+ reason: "symbol-key",
938
+ path,
939
+ key
940
+ };
941
+ if (ignoredKeys.includes(key)) continue;
942
+ const memberPath = [...path, key];
943
+ if (allowedKeys !== void 0 && !allowedKeys.includes(key)) return {
944
+ ok: false,
945
+ reason: "unknown-key",
946
+ path: memberPath,
947
+ key,
948
+ allowedKeys
949
+ };
950
+ let descriptor;
951
+ try {
952
+ descriptor = Object.getOwnPropertyDescriptor(value, key);
953
+ } catch {
954
+ return {
955
+ ok: false,
956
+ reason: "inspection-failed",
957
+ path: memberPath
958
+ };
959
+ }
960
+ if (descriptor === void 0) return {
961
+ ok: false,
962
+ reason: "inspection-failed",
963
+ path: memberPath
964
+ };
965
+ const propertyValue = dataPropertyValue(descriptor, key, memberPath);
966
+ if (!propertyValue.ok) return propertyValue;
967
+ const snapshot = member(propertyValue.value, memberPath, ancestors);
968
+ if (!snapshot.ok) return snapshot;
969
+ entries.push([key, snapshot.value]);
970
+ }
971
+ return {
972
+ ok: true,
973
+ value: Object.freeze(Object.fromEntries(entries))
974
+ };
975
+ }
976
+ function dataPropertyValue(descriptor, key, path) {
977
+ if (!("value" in descriptor)) return {
978
+ ok: false,
979
+ reason: "accessor",
980
+ path,
981
+ key
982
+ };
983
+ if (!descriptor.enumerable) return {
984
+ ok: false,
985
+ reason: "non-enumerable",
986
+ path,
987
+ key
988
+ };
989
+ return {
990
+ ok: true,
991
+ value: descriptor.value
992
+ };
993
+ }
994
+ function snapshotDataValue(value, path, ancestors) {
995
+ switch (typeof value) {
996
+ case "string":
997
+ case "number":
998
+ case "boolean":
999
+ case "bigint":
1000
+ case "undefined": return {
1001
+ ok: true,
1002
+ value
1003
+ };
1004
+ case "function": return {
1005
+ ok: false,
1006
+ reason: "not-data",
1007
+ path,
1008
+ received: "function"
1009
+ };
1010
+ case "symbol": return {
1011
+ ok: false,
1012
+ reason: "not-data",
1013
+ path,
1014
+ received: "symbol"
1015
+ };
1016
+ case "object": {
1017
+ if (value === null) return {
1018
+ ok: true,
1019
+ value
1020
+ };
1021
+ let isArray;
1022
+ try {
1023
+ isArray = Array.isArray(value);
1024
+ } catch {
1025
+ return {
1026
+ ok: false,
1027
+ reason: "inspection-failed",
1028
+ path
1029
+ };
1030
+ }
1031
+ return isArray ? snapshotArrayValue(value, path, snapshotDataValue, ancestors) : snapshotPlainObject(value, void 0, path, snapshotDataValue, ancestors);
1032
+ }
1033
+ }
1034
+ }
1035
+ //#endregion
1036
+ //#region src/definition/kernel/equals-pattern.ts
1037
+ /**
1038
+ * The regular expression source the generator writes for `@equals(value: v)`.
1039
+ * The plugin fills its template `/^$1$/` with `String.prototype.replace`, so
1040
+ * `v` is inserted unescaped and its replacement tokens (`$&`, `` $` ``, `$'`,
1041
+ * `$$`) are expanded first.
1042
+ */
1043
+ function equalsPattern(value) {
1044
+ return "/^$1$/".replace("$1", value).slice(1, -1);
1045
+ }
1046
+ const LINE_TERMINATORS = /* @__PURE__ */ new Set([
1047
+ "\n",
1048
+ "\r",
1049
+ "\u2028",
1050
+ "\u2029"
1051
+ ]);
1052
+ /**
1053
+ * Why an `@equals` pattern cannot be validated the way the generator does,
1054
+ * if it cannot. The generator writes the pattern, as `equalsPattern`
1055
+ * expands it, into a regex literal: a `/` outside a character class ends
1056
+ * that literal, and a line terminator cannot appear in one, so either leaves
1057
+ * generated code that does not compile or does not validate.
1058
+ */
1059
+ function equalsPatternProblem(pattern) {
1060
+ const expected = "a regular expression pattern the generator can write as /^pattern$/";
1061
+ const source = equalsPattern(pattern);
1062
+ let inClass = false;
1063
+ for (let index = 0; index < source.length; index++) {
1064
+ const character = source[index];
1065
+ const escaped = character === "\\";
1066
+ if (escaped) index++;
1067
+ if (LINE_TERMINATORS.has(source[index])) return {
1068
+ message: "The @equals pattern contains a line terminator, which a regular expression literal cannot hold.",
1069
+ expected,
1070
+ repair: "Write the line terminator as an escape such as \\n, which the regular expression reads the same way."
1071
+ };
1072
+ if (escaped) continue;
1073
+ if (character === "[") inClass = true;
1074
+ else if (character === "]") inClass = false;
1075
+ else if (character === "/" && !inClass) return {
1076
+ message: "The @equals pattern contains a / outside a character class, which ends the generated regular expression literal.",
1077
+ expected,
1078
+ repair: "Escape the slash as \\/ (written \"\\\\/\" in a JavaScript string), or put it in a character class such as [/]."
1079
+ };
1080
+ }
1081
+ try {
1082
+ new RegExp(source);
1083
+ } catch (error) {
1084
+ return {
1085
+ message: `The @equals pattern is not a valid regular expression: ${error instanceof Error ? error.message : String(error)}`,
1086
+ expected,
1087
+ repair: "Fix the pattern, or escape the characters that have a meaning in a regular expression."
1088
+ };
1089
+ }
1090
+ }
1091
+ //#endregion
1092
+ //#region src/definition/dsl/types.ts
1093
+ const FIELD_USE_ROLE = "field use";
1094
+ const NAMED_TYPE_ROLE = "named type; wrap it with ph.ref(Type) to use it as a field";
1095
+ //#endregion
1096
+ //#region src/definition/dsl/zod.ts
1097
+ /**
1098
+ * The generator wraps a nullable field of an object or an input with
1099
+ * `.nullish()`, a nullable list item that is itself a list with `.nullish()`,
1100
+ * and any other nullable list item with `.nullable()`. So the slot a field use
1101
+ * fills decides, and a descriptor's own validator is its field-slot validator.
1102
+ */
1103
+ function itemValidator(item) {
1104
+ const base = fieldBase(item);
1105
+ if (item.required) return base;
1106
+ return item.kind === "list" ? base.nullish() : base.nullable();
1107
+ }
1108
+ function fieldBase(field) {
1109
+ switch (field.kind) {
1110
+ case "scalar": return field.baseValidator;
1111
+ case "list": return z.array(itemValidator(field.item));
1112
+ case "ref": {
1113
+ const reference = field;
1114
+ return z.lazy(() => resolveReference(reference).validator);
1115
+ }
1116
+ }
1117
+ }
1118
+ /**
1119
+ * The generator maps `@equals(value: v)` to `.regex(/^v$/)` and ignores every
1120
+ * other directive.
1121
+ */
1122
+ function applyDirective(base, directive) {
1123
+ const value = directive.arguments.find((argument) => argument.name === "value")?.value;
1124
+ if (directive.name !== "equals" || typeof value !== "string") return base;
1125
+ return base.check(z.regex(new RegExp(equalsPattern(value))));
1126
+ }
1127
+ function constrainedBase(field) {
1128
+ return field.presentation.directives.reduce(applyDirective, fieldBase(field));
1129
+ }
1130
+ /**
1131
+ * The generator emits `.default(v)` only on a field that is not a list and
1132
+ * whose default is a string, number, boolean, or enum literal. A list, input
1133
+ * object, or `null` default leaves the field as required as it was, although
1134
+ * the generated types make every defaulted field an optional key.
1135
+ */
1136
+ function withDefault(field, base) {
1137
+ const fallback = field.presentation.default;
1138
+ if (!fallback.present || field.kind === "list") return base;
1139
+ const { value } = fallback;
1140
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? base.default(value) : base;
1141
+ }
1142
+ /**
1143
+ * Generated schemas list their members in `lexicographicSortSchema` order,
1144
+ * after an optional `__typename` literal. Shape order carries no validation meaning, but Zod
1145
+ * reports issues in shape order and a failed operation persists that message,
1146
+ * so the compiled schemas keep the generated order.
1147
+ */
1148
+ function objectShape(fields) {
1149
+ return Object.fromEntries(Object.entries(fields).sort(([left], [right]) => compareGeneratedOrder(left, right)).map(([key, field]) => [key, field.validator]));
1150
+ }
1151
+ function resolveReference(descriptor) {
1152
+ const resolve = referenceResolver(descriptor);
1153
+ if (resolve === void 0) throw new TypeError("The reference descriptor was not created by ph.ref.");
1154
+ return resolve();
1155
+ }
1156
+ function buildValidator(descriptor) {
1157
+ switch (descriptor.kind) {
1158
+ case "scalar":
1159
+ case "list":
1160
+ case "ref": {
1161
+ const field = descriptor;
1162
+ const base = withDefault(field, constrainedBase(field));
1163
+ return field.required ? base : base.nullish();
1164
+ }
1165
+ case "enum": {
1166
+ const names = descriptor.values.map((value) => value.name).sort(compareGeneratedOrder);
1167
+ return z.enum(names);
1168
+ }
1169
+ case "input": {
1170
+ const shape = objectShape(descriptor.fields);
1171
+ return z.object(Object.keys(shape).length === 0 ? { [EMPTY_INPUT_FIELD_NAME]: z.boolean().nullish() } : shape);
1172
+ }
1173
+ case "object": {
1174
+ const object = descriptor;
1175
+ return z.object({
1176
+ __typename: z.literal(object.name).optional(),
1177
+ ...objectShape(object.fields)
1178
+ });
1179
+ }
1180
+ case "interface": return z.object(objectShape(descriptor.fields));
1181
+ case "union": {
1182
+ const members = [...descriptor.members].sort((left, right) => compareGeneratedOrder(left.name, right.name)).map((member) => member.validator);
1183
+ return z.union(members);
1184
+ }
1185
+ }
1186
+ }
1187
+ //#endregion
1188
+ //#region src/definition/dsl/field-options.ts
1189
+ const FIELD_OPTION_KEYS = Object.freeze([
1190
+ "required",
1191
+ "description",
1192
+ "deprecated",
1193
+ "defaultValue"
1194
+ ]);
1195
+ const SCALAR_FIELD_OPTION_KEYS = Object.freeze([...FIELD_OPTION_KEYS, "equals"]);
1196
+ const LIST_ITEM_METADATA_KEYS = [
1197
+ "description",
1198
+ "deprecated",
1199
+ "defaultValue"
1200
+ ];
1201
+ function rejectionPath(rejection) {
1202
+ return rejection.path.map((segment) => typeof segment === "number" ? segment : String(segment));
1203
+ }
1204
+ const FOREIGN_ARRAY = "Expected a plain array, not an Array subclass or an array from another realm.";
1205
+ function optionRejection(rejection, unsupportedKeyCode, allowedKeys) {
1206
+ if (rejection.reason === "unknown-key") return dslDiagnostics.fail({
1207
+ code: unsupportedKeyCode,
1208
+ path: rejectionPath(rejection),
1209
+ message: `Option ${JSON.stringify(rejection.key)} is not supported here.`,
1210
+ expected: allowedKeys.join(", "),
1211
+ received: rejection.key,
1212
+ repair: `Remove ${JSON.stringify(rejection.key)}; the supported options are ${allowedKeys.join(", ")}.`
1213
+ });
1214
+ if (rejection.reason === "custom-prototype" && rejection.expected === "array") return dslDiagnostics.fail({
1215
+ code: "PH-DEF-OPTION-INVALID",
1216
+ path: rejectionPath(rejection),
1217
+ message: FOREIGN_ARRAY,
1218
+ received: rejection.received,
1219
+ repair: "Pass an array literal, or copy the array with Array.from(...)."
1220
+ });
1221
+ return dslDiagnostics.fail({
1222
+ code: "PH-DEF-OPTION-INVALID",
1223
+ path: rejectionPath(rejection),
1224
+ message: `The option value could not be snapshotted (${rejection.reason}).`,
1225
+ received: rejectionReceived(rejection),
1226
+ repair: "Pass a plain object literal with enumerable string-keyed data properties and no accessors, symbols, or class instances."
1227
+ });
1228
+ }
1229
+ function snapshotDataOptions(value, allowedKeys, path, unsupportedKeyCode = "PH-DEF-OPTION-INVALID") {
1230
+ const snapshot = snapshotDataRecord(value, allowedKeys, path);
1231
+ if (!snapshot.ok) return optionRejection(snapshot, unsupportedKeyCode, allowedKeys);
1232
+ return snapshot.value;
1233
+ }
1234
+ function snapshotDescriptorOptions(value, allowedKeys, path) {
1235
+ const snapshot = snapshotRecord(value, allowedKeys, path);
1236
+ if (!snapshot.ok) return optionRejection(snapshot, "PH-DEF-OPTION-INVALID", allowedKeys);
1237
+ return snapshot.value;
1238
+ }
1239
+ function snapshotDescriptorArray(value, path, code, repair) {
1240
+ const snapshot = snapshotArray(value, path);
1241
+ if (snapshot.ok) return snapshot.value;
1242
+ if (snapshot.reason === "not-array") return dslDiagnostics.fail({
1243
+ code,
1244
+ path,
1245
+ message: "Expected an array.",
1246
+ received: snapshot.received,
1247
+ repair
1248
+ });
1249
+ if (snapshot.reason === "custom-prototype" && snapshot.expected === "array") return dslDiagnostics.fail({
1250
+ code,
1251
+ path,
1252
+ message: FOREIGN_ARRAY,
1253
+ received: snapshot.received,
1254
+ repair: `${repair} Copy an Array subclass or an array from another realm with Array.from(...).`
1255
+ });
1256
+ return optionRejection(snapshot, code, []);
1257
+ }
1258
+ function snapshotFieldMap(value, path) {
1259
+ const snapshot = snapshotRecord(value, void 0, path);
1260
+ if (!snapshot.ok) return optionRejection(snapshot, "PH-DEF-OPTION-INVALID", []);
1261
+ return snapshot.value;
1262
+ }
1263
+ function assertAuthoredName(value, path) {
1264
+ if (!isAuthoredSchemaName(value)) return dslDiagnostics.fail({
1265
+ code: "PH-DEF-NAME-INVALID",
1266
+ path,
1267
+ message: "A GraphQL name must match /^[_A-Za-z][_0-9A-Za-z]*$/ and must not start with two underscores.",
1268
+ expected: "a GraphQL name such as InvoiceLineItem",
1269
+ received: typeof value === "string" ? value : describeReceived(value),
1270
+ repair: "Use letters, digits, and underscores, start with a letter or one underscore, and avoid the reserved __ prefix."
1271
+ });
1272
+ return value;
1273
+ }
1274
+ function assertFieldUse(value, path) {
1275
+ if (isFieldDescriptor(value)) return;
1276
+ if (isScalarFactory(value)) {
1277
+ const role = value.role;
1278
+ dslDiagnostics.fail({
1279
+ code: "PH-SCALAR-FACTORY-AS-FIELD",
1280
+ path,
1281
+ message: "A scalar factory was used as a field without being called.",
1282
+ expected: FIELD_USE_ROLE,
1283
+ received: role,
1284
+ repair: role.slice(role.indexOf("call it, as ") + 12)
1285
+ });
1286
+ }
1287
+ if (isTypeDescriptor(value)) dslDiagnostics.fail({
1288
+ code: "PH-DEF-TYPE-AS-FIELD",
1289
+ path,
1290
+ message: `Named type ${JSON.stringify(value.name)} was used directly as a field.`,
1291
+ expected: FIELD_USE_ROLE,
1292
+ received: value.role,
1293
+ repair: `Wrap the type with ph.ref(${value.name ?? "Type"}).`
1294
+ });
1295
+ dslDiagnostics.fail({
1296
+ code: "PH-DEF-FIELD-INVALID",
1297
+ path,
1298
+ message: "A field position must hold a field use created by ph.",
1299
+ received: describeReceived(value),
1300
+ repair: "Use a called scalar factory such as ph.String(), ph.list(...), or ph.ref(Type)."
1301
+ });
1302
+ }
1303
+ function assertNamedType(value, path, code, repair) {
1304
+ if (isTypeDescriptor(value)) return;
1305
+ const received = isFieldDescriptor(value) ? `field use (${value.kind})` : isScalarFactory(value) ? "scalar factory" : describeReceived(value);
1306
+ dslDiagnostics.fail({
1307
+ code,
1308
+ path,
1309
+ message: "Expected a named type created by ph.enum, ph.object, ph.input, ph.interface, or ph.union.",
1310
+ expected: "a named type descriptor",
1311
+ received,
1312
+ repair
1313
+ });
1314
+ }
1315
+ function stringOption(options, key, path) {
1316
+ const value = options[key];
1317
+ if (value === void 0) return null;
1318
+ if (typeof value !== "string") return dslDiagnostics.fail({
1319
+ code: "PH-DEF-OPTION-INVALID",
1320
+ path: [...path, key],
1321
+ message: `Option ${key} must be a string.`,
1322
+ expected: "string",
1323
+ received: describeReceived(value),
1324
+ repair: `Pass a string ${key} or omit it.`
1325
+ });
1326
+ return value;
1327
+ }
1328
+ function defaultOption(options, path) {
1329
+ if (!Object.hasOwn(options, "defaultValue")) return { present: false };
1330
+ const value = options.defaultValue;
1331
+ if (value === void 0) return dslDiagnostics.fail({
1332
+ code: "PH-DEF-OPTION-INVALID",
1333
+ path: [...path, "defaultValue"],
1334
+ message: "defaultValue is present but undefined.",
1335
+ expected: "a JSON value, or no defaultValue property at all",
1336
+ received: "undefined",
1337
+ repair: "Delete the defaultValue property to omit the default, or give it a JSON value such as null."
1338
+ });
1339
+ try {
1340
+ canonicalJson(value);
1341
+ } catch (error) {
1342
+ return dslDiagnostics.fail({
1343
+ code: "PH-DEF-OPTION-INVALID",
1344
+ path: [...path, "defaultValue"],
1345
+ message: `defaultValue is not JSON: ${error instanceof Error ? error.message : String(error)}`,
1346
+ repair: "Use a JSON value for defaultValue."
1347
+ });
1348
+ }
1349
+ return {
1350
+ present: true,
1351
+ value
1352
+ };
1353
+ }
1354
+ const NO_DIRECTIVES = Object.freeze([]);
1355
+ function equalsDirectives(options, path) {
1356
+ const value = stringOption(options, "equals", path);
1357
+ if (value === null) return NO_DIRECTIVES;
1358
+ const problem = equalsPatternProblem(value);
1359
+ if (problem !== void 0) return dslDiagnostics.fail({
1360
+ code: "PH-DEF-OPTION-INVALID",
1361
+ path: [...path, "equals"],
1362
+ received: value,
1363
+ ...problem
1364
+ });
1365
+ return Object.freeze([Object.freeze({
1366
+ name: "equals",
1367
+ arguments: Object.freeze([Object.freeze({
1368
+ name: "value",
1369
+ value
1370
+ })])
1371
+ })]);
1372
+ }
1373
+ function resolveFieldOptions(options, path, allowedKeys = FIELD_OPTION_KEYS) {
1374
+ const config = options === void 0 ? {} : snapshotDataOptions(options, allowedKeys, path, "PH-DEF-FIELD-OPTION-UNSUPPORTED");
1375
+ const required = config.required === void 0 ? false : config.required;
1376
+ if (typeof required !== "boolean") return dslDiagnostics.fail({
1377
+ code: "PH-DEF-OPTION-INVALID",
1378
+ path: [...path, "required"],
1379
+ message: "Option required must be a boolean.",
1380
+ expected: "boolean",
1381
+ received: describeReceived(required),
1382
+ repair: "Use required: true, required: false, or omit the option."
1383
+ });
1384
+ return {
1385
+ required,
1386
+ presentation: Object.freeze({
1387
+ description: stringOption(config, "description", path),
1388
+ deprecated: stringOption(config, "deprecated", path),
1389
+ default: Object.freeze(defaultOption(config, path)),
1390
+ directives: equalsDirectives(config, path)
1391
+ })
1392
+ };
1393
+ }
1394
+ function assertBareListItem(item, path) {
1395
+ const authored = LIST_ITEM_METADATA_KEYS.filter((key) => key === "defaultValue" ? item.presentation.default.present : item.presentation[key] !== null);
1396
+ if (authored.length > 0) dslDiagnostics.fail({
1397
+ code: "PH-DEF-OPTION-INVALID",
1398
+ path: [
1399
+ ...path,
1400
+ "options",
1401
+ authored[0]
1402
+ ],
1403
+ message: `A list item carries ${authored.join(", ")}, but GraphQL has no field or argument definition for a list item.`,
1404
+ received: authored.join(", "),
1405
+ repair: `Move ${authored.join(", ")} to the ph.list(...) options of the outer field use.`
1406
+ });
1407
+ if (item.presentation.directives.length > 0) dslDiagnostics.fail({
1408
+ code: "PH-DEF-OPTION-INVALID",
1409
+ path: [
1410
+ ...path,
1411
+ "options",
1412
+ "equals"
1413
+ ],
1414
+ message: "A list item carries equals, but GraphQL has no field or argument definition for a list item to carry @equals on.",
1415
+ received: "equals",
1416
+ repair: "Remove equals from the list item; a list cannot constrain its items with @equals."
1417
+ });
1418
+ }
1419
+ function createScalarField(scalarName, baseValidator, options, definition) {
1420
+ const { required, presentation } = resolveFieldOptions(options, ["options"], SCALAR_FIELD_OPTION_KEYS);
1421
+ const carriesPattern = typeof baseValidator.regex === "function";
1422
+ if (presentation.directives.length > 0 && !carriesPattern) dslDiagnostics.fail({
1423
+ code: "PH-DEF-FIELD-OPTION-UNSUPPORTED",
1424
+ path: ["options", "equals"],
1425
+ message: `Option equals adds a pattern check, and the validator of ${scalarName} is not a Zod string schema that can carry one.`,
1426
+ received: scalarName,
1427
+ repair: "Remove equals, or use it on a scalar whose validator is a Zod string schema, such as ph.String() or ph.PHID()."
1428
+ });
1429
+ const descriptor = {
1430
+ kind: "scalar",
1431
+ role: FIELD_USE_ROLE,
1432
+ identity: Object.freeze({
1433
+ kind: "scalar",
1434
+ name: scalarName,
1435
+ required
1436
+ }),
1437
+ scalarName,
1438
+ baseValidator,
1439
+ ...definition !== void 0 && { definition },
1440
+ required,
1441
+ presentation,
1442
+ validator: void 0
1443
+ };
1444
+ descriptor.validator = buildValidator(descriptor);
1445
+ return registerFieldDescriptor(Object.freeze(descriptor));
1446
+ }
1447
+ //#endregion
1448
+ //#region src/definition/dsl/scalar-fields.ts
1449
+ const BUILDER_NAMES = {
1450
+ Amount_Money: "Money",
1451
+ Amount_Percentage: "Percentage",
1452
+ Amount_Tokens: "Tokens",
1453
+ Amount_Fiat: "AmountFiat",
1454
+ Amount_Crypto: "AmountCrypto",
1455
+ Amount_Currency: "AmountCurrency"
1456
+ };
1457
+ function builderName(name) {
1458
+ return Object.hasOwn(BUILDER_NAMES, name) ? BUILDER_NAMES[name] : name;
1459
+ }
1460
+ function scalarFactory(call, name, validator, definition) {
1461
+ const factory = (options) => createScalarField(name, validator, options, definition);
1462
+ return registerScalarFactory(Object.freeze(Object.assign(factory, {
1463
+ role: `field-use factory; call it, as ${call}({ required: true })`,
1464
+ kind: "scalar-factory"
1465
+ })));
1466
+ }
1467
+ const builtInScalarFactories = {
1468
+ ID: scalarFactory("ph.ID", "ID", z.string()),
1469
+ String: scalarFactory("ph.String", "String", z.string()),
1470
+ Boolean: scalarFactory("ph.Boolean", "Boolean", z.boolean()),
1471
+ Int: scalarFactory("ph.Int", "Int", z.number()),
1472
+ Float: scalarFactory("ph.Float", "Float", z.number())
1473
+ };
1474
+ const catalogScalarFactories = Object.fromEntries(documentModelScalars.map((definition) => {
1475
+ const builder = builderName(definition.name);
1476
+ return [builder, scalarFactory(`ph.${builder}`, definition.name, definition.schema, definition)];
1477
+ }));
1478
+ const modelScalarNames = new Set(documentModelScalars.map((definition) => definition.name));
1479
+ const hostOnlyScalars = new Set(scalarCatalog.map((definition) => definition.name).filter((name) => !modelScalarNames.has(name)));
1480
+ function scalarField(definition, options) {
1481
+ if (!isScalarDefinition(definition)) refuseScalarDefinition(definition);
1482
+ if (hostOnlyScalars.has(definition.name)) dslDiagnostics.fail({
1483
+ code: "PH-SCALAR-INTERNAL",
1484
+ definition: {
1485
+ kind: "scalar",
1486
+ key: definition.name
1487
+ },
1488
+ path: ["definition"],
1489
+ message: `${definition.name} is internal to the reactor host. A document model cannot use it.`,
1490
+ received: definition.name,
1491
+ repair: "Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one."
1492
+ });
1493
+ return createScalarField(definition.name, definition.schema, options, definition);
1494
+ }
1495
+ const EXPECTED_DEFINITION = "a ScalarDefinition from defineScalar in document-model/scalars";
1496
+ function refuseScalarDefinition(value) {
1497
+ const version = scalarDefinitionVersion(value);
1498
+ if (version === void 0) return dslDiagnostics.fail({
1499
+ code: "PH-SCALAR-DEFINITION-INVALID",
1500
+ path: ["definition"],
1501
+ message: "ph.scalar takes a scalar definition returned by defineScalar.",
1502
+ expected: EXPECTED_DEFINITION,
1503
+ received: describeReceived(value),
1504
+ repair: "Pass the value defineScalar returned, or use a ph.<Scalar>() factory for a catalog scalar."
1505
+ });
1506
+ const received = typeof version === "number" ? String(version) : describeReceived(version);
1507
+ return dslDiagnostics.fail({
1508
+ code: "PH-SCALAR-DEFINITION-INVALID",
1509
+ path: ["definition"],
1510
+ message: `The scalar definition has format version ${received}; this release reads version 1.`,
1511
+ expected: EXPECTED_DEFINITION,
1512
+ received,
1513
+ repair: "Install the same document-model release in the package that defines the scalar and the package that uses it."
1514
+ });
1515
+ }
1516
+ //#endregion
1517
+ //#region src/definition/dsl/field.ts
1518
+ const KIND_NOUNS = {
1519
+ enum: "an enum",
1520
+ object: "an object",
1521
+ input: "an input",
1522
+ interface: "an interface",
1523
+ union: "a union"
1524
+ };
1525
+ function fieldMap(value, path) {
1526
+ const members = snapshotFieldMap(value, path);
1527
+ for (const [key, member] of Object.entries(members)) {
1528
+ assertAuthoredName(key, [...path, key]);
1529
+ assertFieldUse(member, [...path, key]);
1530
+ }
1531
+ return Object.freeze({ ...members });
1532
+ }
1533
+ function enumValues(input) {
1534
+ const entries = snapshotDescriptorArray(input, ["options", "values"], "PH-DEF-ENUM-VALUES-INVALID", "Pass values as a nonempty array of strings or { name, description?, deprecated? } entries.");
1535
+ if (entries.length === 0) dslDiagnostics.fail({
1536
+ code: "PH-DEF-ENUM-VALUES-INVALID",
1537
+ path: ["options", "values"],
1538
+ message: "An enum must declare at least one value.",
1539
+ repair: "Add at least one enum value."
1540
+ });
1541
+ const seen = /* @__PURE__ */ new Set();
1542
+ return Object.freeze(entries.map((entry, index) => {
1543
+ const path = [
1544
+ "options",
1545
+ "values",
1546
+ index
1547
+ ];
1548
+ const normalized = typeof entry === "string" ? { name: entry } : snapshotDataOptions(entry, [
1549
+ "name",
1550
+ "description",
1551
+ "deprecated"
1552
+ ], path);
1553
+ const name = assertAuthoredName(normalized.name, [...path, "name"]);
1554
+ if (!isEnumValueName(name)) dslDiagnostics.fail({
1555
+ code: "PH-DEF-ENUM-VALUES-INVALID",
1556
+ path: [...path, "name"],
1557
+ message: `${JSON.stringify(name)} is a reserved GraphQL literal and cannot be an enum value.`,
1558
+ received: name,
1559
+ repair: `Rename the value; true, false, and null are GraphQL literals.`
1560
+ });
1561
+ if (seen.has(name)) dslDiagnostics.fail({
1562
+ code: "PH-DEF-ENUM-VALUES-INVALID",
1563
+ path: [...path, "name"],
1564
+ message: `Enum value ${JSON.stringify(name)} is declared twice.`,
1565
+ received: name,
1566
+ repair: "Keep one declaration per enum value."
1567
+ });
1568
+ seen.add(name);
1569
+ return Object.freeze({
1570
+ name,
1571
+ description: stringOption(normalized, "description", path),
1572
+ deprecated: stringOption(normalized, "deprecated", path)
1573
+ });
1574
+ }));
1575
+ }
1576
+ function namedType(node) {
1577
+ const descriptor = {
1578
+ ...node,
1579
+ role: NAMED_TYPE_ROLE,
1580
+ identity: Object.freeze({
1581
+ kind: node.kind,
1582
+ name: node.name,
1583
+ description: node.description
1584
+ }),
1585
+ validator: void 0
1586
+ };
1587
+ descriptor.validator = buildValidator(descriptor);
1588
+ return registerTypeDescriptor(Object.freeze(descriptor));
1589
+ }
1590
+ function refTarget(candidate, path) {
1591
+ assertNamedType(candidate, path, "PH-DEF-REFERENCE-TARGET-INVALID", "Pass a named type returned by ph.enum, ph.object, ph.input, ph.interface, or ph.union, or a thunk returning one.");
1592
+ if (candidate.name === null) dslDiagnostics.fail({
1593
+ code: "PH-DEF-REFERENCE-TARGET-INVALID",
1594
+ path,
1595
+ message: "An anonymous input cannot be a reference target.",
1596
+ repair: "Give the input a name: ph.input(\"NameInput\", { fields })."
1597
+ });
1598
+ return candidate;
1599
+ }
1600
+ function implementedInterfaces(config) {
1601
+ const implemented = config.implements !== void 0 ? snapshotDescriptorArray(config.implements, ["options", "implements"], "PH-DEF-IMPLEMENTS-INVALID", "Pass implements as an array of descriptors returned by ph.interface.") : [];
1602
+ const seen = /* @__PURE__ */ new Set();
1603
+ implemented.forEach((candidate, index) => {
1604
+ const path = [
1605
+ "options",
1606
+ "implements",
1607
+ index
1608
+ ];
1609
+ assertNamedType(candidate, path, "PH-DEF-IMPLEMENTS-INVALID", "Pass a descriptor returned by ph.interface.");
1610
+ if (candidate.kind !== "interface") dslDiagnostics.fail({
1611
+ code: "PH-DEF-IMPLEMENTS-INVALID",
1612
+ path,
1613
+ message: `${JSON.stringify(candidate.name)} is ${KIND_NOUNS[candidate.kind]}, not an interface.`,
1614
+ received: candidate.kind,
1615
+ repair: "Only descriptors returned by ph.interface can be implemented."
1616
+ });
1617
+ const interfaceName = candidate.name;
1618
+ if (seen.has(interfaceName)) dslDiagnostics.fail({
1619
+ code: "PH-DEF-IMPLEMENTS-INVALID",
1620
+ path,
1621
+ message: `Interface ${JSON.stringify(interfaceName)} is implemented twice.`,
1622
+ received: interfaceName,
1623
+ repair: "List each implemented interface once."
1624
+ });
1625
+ seen.add(interfaceName);
1626
+ });
1627
+ return Object.freeze([...implemented]);
1628
+ }
1629
+ function objectType(name, options) {
1630
+ return namedType({
1631
+ kind: "object",
1632
+ ...implementingMembers(name, options)
1633
+ });
1634
+ }
1635
+ function interfaceType(name, options) {
1636
+ return namedType({
1637
+ kind: "interface",
1638
+ ...implementingMembers(name, options)
1639
+ });
1640
+ }
1641
+ function implementingMembers(name, options) {
1642
+ const validName = assertAuthoredName(name, ["name"]);
1643
+ const config = snapshotDescriptorOptions(options, [
1644
+ "fields",
1645
+ "description",
1646
+ "implements"
1647
+ ], ["options"]);
1648
+ return {
1649
+ name: validName,
1650
+ description: stringOption(config, "description", ["options"]),
1651
+ fields: fieldMap(config.fields, ["options", "fields"]),
1652
+ implements: implementedInterfaces(config)
1653
+ };
1654
+ }
1655
+ /**
1656
+ * @experimental The field and type builders of a code-first document model:
1657
+ * scalar factories such as `ph.String()` and `ph.PHID()`, `ph.scalar` for a
1658
+ * project scalar, and `list`, `ref`, `enum`, `object`, `interface`, `input`,
1659
+ * and `union`.
1660
+ */
1661
+ const ph = Object.freeze({
1662
+ ...builtInScalarFactories,
1663
+ ...catalogScalarFactories,
1664
+ scalar: scalarField,
1665
+ list(item, options) {
1666
+ assertFieldUse(item, ["item"]);
1667
+ assertBareListItem(item, ["item"]);
1668
+ const { required, presentation } = resolveFieldOptions(options, ["options"]);
1669
+ const descriptor = {
1670
+ kind: "list",
1671
+ role: FIELD_USE_ROLE,
1672
+ identity: Object.freeze({
1673
+ kind: "list",
1674
+ required,
1675
+ item: item.identity
1676
+ }),
1677
+ item,
1678
+ required,
1679
+ presentation,
1680
+ validator: void 0
1681
+ };
1682
+ descriptor.validator = buildValidator(descriptor);
1683
+ return registerFieldDescriptor(Object.freeze(descriptor));
1684
+ },
1685
+ ref(target, options) {
1686
+ let resolved;
1687
+ const resolve = () => {
1688
+ if (resolved === void 0) resolved = refTarget(typeof target === "function" && !isTypeDescriptor(target) ? target() : target, ["target"]);
1689
+ return resolved;
1690
+ };
1691
+ if (typeof target !== "function") resolve();
1692
+ const { required, presentation } = resolveFieldOptions(options, ["options"]);
1693
+ const descriptor = {
1694
+ kind: "ref",
1695
+ role: FIELD_USE_ROLE,
1696
+ identity: Object.freeze({
1697
+ kind: "ref",
1698
+ required
1699
+ }),
1700
+ target,
1701
+ required,
1702
+ presentation,
1703
+ validator: void 0
1704
+ };
1705
+ const reference = descriptor;
1706
+ registerReference(reference, resolve);
1707
+ descriptor.validator = buildValidator(reference);
1708
+ return registerFieldDescriptor(Object.freeze(reference));
1709
+ },
1710
+ enum(name, options) {
1711
+ const validName = assertAuthoredName(name, ["name"]);
1712
+ const config = snapshotDescriptorOptions(options, ["values", "description"], ["options"]);
1713
+ return namedType({
1714
+ kind: "enum",
1715
+ name: validName,
1716
+ description: stringOption(config, "description", ["options"]),
1717
+ values: enumValues(config.values)
1718
+ });
1719
+ },
1720
+ object: objectType,
1721
+ interface: interfaceType,
1722
+ input(...args) {
1723
+ const [nameOrOptions, maybeOptions] = args;
1724
+ const name = typeof nameOrOptions === "string" ? assertAuthoredName(nameOrOptions, ["name"]) : null;
1725
+ const config = snapshotDescriptorOptions(typeof nameOrOptions === "string" ? maybeOptions : nameOrOptions, ["fields", "description"], ["options"]);
1726
+ return namedType({
1727
+ kind: "input",
1728
+ name,
1729
+ description: stringOption(config, "description", ["options"]),
1730
+ fields: fieldMap(config.fields, ["options", "fields"])
1731
+ });
1732
+ },
1733
+ union(name, options) {
1734
+ const validName = assertAuthoredName(name, ["name"]);
1735
+ const config = snapshotDescriptorOptions(options, ["members", "description"], ["options"]);
1736
+ const members = snapshotDescriptorArray(config.members, ["options", "members"], "PH-DEF-UNION-MEMBERS-INVALID", "Pass members as a nonempty array of descriptors returned by ph.object.");
1737
+ if (members.length === 0) dslDiagnostics.fail({
1738
+ code: "PH-DEF-UNION-MEMBERS-INVALID",
1739
+ path: ["options", "members"],
1740
+ message: "A union must declare at least one object member.",
1741
+ repair: "Add at least one ph.object descriptor to members."
1742
+ });
1743
+ const seen = /* @__PURE__ */ new Set();
1744
+ members.forEach((member, index) => {
1745
+ const path = [
1746
+ "options",
1747
+ "members",
1748
+ index
1749
+ ];
1750
+ assertNamedType(member, path, "PH-DEF-UNION-MEMBERS-INVALID", "Replace the member with a descriptor returned by ph.object.");
1751
+ if (member.kind !== "object") dslDiagnostics.fail({
1752
+ code: "PH-DEF-UNION-MEMBERS-INVALID",
1753
+ path,
1754
+ message: `Union member ${JSON.stringify(member.name)} is ${KIND_NOUNS[member.kind]}; GraphQL unions hold object types only.`,
1755
+ received: member.kind,
1756
+ repair: "Replace the member with a descriptor returned by ph.object."
1757
+ });
1758
+ const memberName = member.name;
1759
+ if (seen.has(memberName)) dslDiagnostics.fail({
1760
+ code: "PH-DEF-UNION-MEMBERS-INVALID",
1761
+ path,
1762
+ message: `Union member ${JSON.stringify(memberName)} is declared twice.`,
1763
+ received: memberName,
1764
+ repair: "List each member object once."
1765
+ });
1766
+ seen.add(memberName);
1767
+ });
1768
+ return namedType({
1769
+ kind: "union",
1770
+ name: validName,
1771
+ description: stringOption(config, "description", ["options"]),
1772
+ members: Object.freeze([...members])
1773
+ });
1774
+ }
1775
+ });
1776
+ //#endregion
1777
+ //#region src/definition/kernel/diagnostic-collector.ts
1778
+ var DefinitionDiagnosticCollector = class {
1779
+ #catalog;
1780
+ #definition;
1781
+ #diagnostics = [];
1782
+ constructor(catalog, definition) {
1783
+ this.#catalog = catalog;
1784
+ this.#definition = definition;
1785
+ }
1786
+ get diagnostics() {
1787
+ return sortDefinitionDiagnostics(this.#diagnostics);
1788
+ }
1789
+ add(input) {
1790
+ this.#diagnostics.push(this.#catalog.create({
1791
+ ...this.#definition !== void 0 && { definition: this.#definition },
1792
+ ...input
1793
+ }));
1794
+ }
1795
+ merge(diagnostics) {
1796
+ for (const diagnostic of diagnostics) this.#diagnostics.push(this.#definition === void 0 || diagnostic.definition !== void 0 ? diagnostic : {
1797
+ ...diagnostic,
1798
+ definition: { ...this.#definition }
1799
+ });
1800
+ }
1801
+ capture(attempt) {
1802
+ try {
1803
+ return attempt();
1804
+ } catch (error) {
1805
+ if (!(error instanceof DefinitionError)) throw error;
1806
+ this.merge(error.diagnostics);
1807
+ return;
1808
+ }
1809
+ }
1810
+ throwIfFailed() {
1811
+ if (!this.#diagnostics.some((entry) => entry.severity === "error")) return;
1812
+ throw new DefinitionError(this.#diagnostics);
1813
+ }
1814
+ };
1815
+ //#endregion
1816
+ //#region src/definition/kernel/printer.ts
1817
+ const INDENT = " ";
1818
+ const LINE = "\n";
1819
+ function namedTypeInventory(definitions) {
1820
+ const inventory = /* @__PURE__ */ new Map();
1821
+ for (const definition of definitions) inventory.set(definition.name, definition);
1822
+ return inventory;
1823
+ }
1824
+ const ESCAPES = {
1825
+ "\"": "\\\"",
1826
+ "\\": "\\\\",
1827
+ "\b": "\\b",
1828
+ "\f": "\\f",
1829
+ "\n": "\\n",
1830
+ "\r": "\\r",
1831
+ " ": "\\t"
1832
+ };
1833
+ function isControlCodePoint(code) {
1834
+ return code < 32 || code === 127;
1835
+ }
1836
+ function stringLiteral(value) {
1837
+ let printed = "\"";
1838
+ for (const point of value) {
1839
+ const escape = ESCAPES[point];
1840
+ if (escape !== void 0) {
1841
+ printed += escape;
1842
+ continue;
1843
+ }
1844
+ const code = point.codePointAt(0) ?? 0;
1845
+ printed += isControlCodePoint(code) ? `\\u${code.toString(16).toUpperCase().padStart(4, "0")}` : point;
1846
+ }
1847
+ return `${printed}"`;
1848
+ }
1849
+ function hasControlCodePoint(value) {
1850
+ for (const point of value) if (isControlCodePoint(point.codePointAt(0) ?? 0)) return true;
1851
+ return false;
1852
+ }
1853
+ /**
1854
+ * A block string survives the lexer's dedent only when every line is nonempty
1855
+ * and carries no leading or trailing whitespace of its own, and the value ends
1856
+ * in neither a quote nor a backslash. Every other description prints as an
1857
+ * escaped single-line string, which always round-trips.
1858
+ */
1859
+ function blockStringable(value) {
1860
+ if (!value.includes(LINE)) return false;
1861
+ if (value.includes("\"\"\"")) return false;
1862
+ if (value.endsWith("\"") || value.endsWith("\\")) return false;
1863
+ return value.split(LINE).every((line) => line.length > 0 && line.trim() === line && !hasControlCodePoint(line) && !line.includes("\r"));
1864
+ }
1865
+ function descriptionLiteral(value, indent) {
1866
+ if (!blockStringable(value)) return stringLiteral(value);
1867
+ return [
1868
+ "\"\"\"",
1869
+ ...value.split(LINE).map((line) => `${indent}${line}`),
1870
+ `${indent}"""`
1871
+ ].join(LINE);
1872
+ }
1873
+ function descriptionLine(description, indent = "") {
1874
+ if (description === null) return "";
1875
+ return `${indent}${descriptionLiteral(description, indent)}${LINE}`;
1876
+ }
1877
+ function inlineDescription(description) {
1878
+ return description === null ? "" : `${stringLiteral(description)} `;
1879
+ }
1880
+ function printNumber(value) {
1881
+ if (!Number.isFinite(value)) throw new TypeError(`A GraphQL value must be finite, received ${String(value)}.`);
1882
+ return JSON.stringify(value);
1883
+ }
1884
+ function printGraphQLLiteral(value) {
1885
+ if (value === null) return "null";
1886
+ if (typeof value === "boolean") return String(value);
1887
+ if (typeof value === "number") return printNumber(value);
1888
+ if (typeof value === "string") return stringLiteral(value);
1889
+ if (Array.isArray(value)) return `[${value.map(printGraphQLLiteral).join(", ")}]`;
1890
+ return `{${Object.entries(value).map(([key, member]) => `${key}: ${printGraphQLLiteral(member)}`).join(", ")}}`;
1891
+ }
1892
+ function enumValueNames(definition) {
1893
+ return new Set(definition.values.map((value) => value.name));
1894
+ }
1895
+ function printTypedValue(value, type, inventory) {
1896
+ if (value === null) return "null";
1897
+ if (type.kind === "list") {
1898
+ if (!Array.isArray(value)) return printTypedValue(value, type.item, inventory);
1899
+ return `[${value.map((item) => printTypedValue(item, type.item, inventory)).join(", ")}]`;
1900
+ }
1901
+ if (type.kind === "scalar") return printGraphQLLiteral(value);
1902
+ const definition = inventory.get(type.name);
1903
+ if (definition === void 0) return printGraphQLLiteral(value);
1904
+ if (definition.kind === "enum") return typeof value === "string" && enumValueNames(definition).has(value) ? value : printGraphQLLiteral(value);
1905
+ if (definition.kind !== "input" || typeof value !== "object" || Array.isArray(value)) return printGraphQLLiteral(value);
1906
+ const fields = new Map(definition.fields.map((field) => [field.name, field]));
1907
+ return `{${Object.entries(value).map(([key, member]) => {
1908
+ const field = fields.get(key);
1909
+ return `${key}: ${field === void 0 ? printGraphQLLiteral(member) : printTypedValue(member, field.type, inventory)}`;
1910
+ }).join(", ")}}`;
1911
+ }
1912
+ function printTypeReference(type) {
1913
+ const base = type.kind === "list" ? `[${printTypeReference(type.item)}]` : type.name;
1914
+ return type.required ? `${base}!` : base;
1915
+ }
1916
+ function printDeprecated(deprecated) {
1917
+ return deprecated === null ? "" : ` @deprecated(reason: ${stringLiteral(deprecated)})`;
1918
+ }
1919
+ function printDirectives(directives) {
1920
+ if (directives === void 0 || directives.length === 0) return "";
1921
+ return directives.map((directive) => {
1922
+ if (directive.arguments.length === 0) return ` @${directive.name}`;
1923
+ const args = directive.arguments.map((argument) => `${argument.name}: ${printGraphQLLiteral(argument.value)}`).join(", ");
1924
+ return ` @${directive.name}(${args})`;
1925
+ }).join("");
1926
+ }
1927
+ function printInputValue(field, inventory) {
1928
+ const defaultValue = Object.hasOwn(field, "defaultValue") ? ` = ${printTypedValue(field.defaultValue, field.type, inventory)}` : "";
1929
+ return `${field.name}: ${printTypeReference(field.type)}${defaultValue}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;
1930
+ }
1931
+ function printInputField(field, inventory) {
1932
+ return `${descriptionLine(field.description, INDENT)}${INDENT}${printInputValue(field, inventory)}`;
1933
+ }
1934
+ function printArguments(args, inventory) {
1935
+ if (args === void 0 || args.length === 0) return "";
1936
+ return `(${args.map((argument) => `${inlineDescription(argument.description)}${printInputValue(argument, inventory)}`).join(", ")})`;
1937
+ }
1938
+ function printField(field, inventory) {
1939
+ return `${descriptionLine(field.description, INDENT)}${INDENT}${field.name}${printArguments(field.args, inventory)}: ${printTypeReference(field.type)}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;
1940
+ }
1941
+ function printImplements(implemented) {
1942
+ return implemented === void 0 || implemented.length === 0 ? "" : ` implements ${implemented.join(" & ")}`;
1943
+ }
1944
+ function printBlock(members) {
1945
+ return members.length === 0 ? "" : ` {${LINE}${members.join(LINE)}${LINE}}`;
1946
+ }
1947
+ function printNamedDefinition(definition, inventory = namedTypeInventory([definition])) {
1948
+ const description = descriptionLine(definition.description);
1949
+ switch (definition.kind) {
1950
+ case "enum": {
1951
+ const values = definition.values.map((value) => `${descriptionLine(value.description, INDENT)}${INDENT}${value.name}${printDeprecated(value.deprecated)}${printDirectives(value.directives)}`);
1952
+ return `${description}enum ${definition.name}${printBlock(values)}`;
1953
+ }
1954
+ case "object": {
1955
+ const fields = definition.fields.map((field) => printField(field, inventory));
1956
+ return `${description}type ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;
1957
+ }
1958
+ case "interface": {
1959
+ const fields = definition.fields.map((field) => printField(field, inventory));
1960
+ return `${description}interface ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;
1961
+ }
1962
+ case "input": {
1963
+ const fields = definition.fields.length === 0 ? [`${INDENT}${EMPTY_INPUT_FIELD_NAME}: Boolean`] : definition.fields.map((field) => printInputField(field, inventory));
1964
+ return `${description}input ${definition.name}${printBlock(fields)}`;
1965
+ }
1966
+ case "union": return `${description}union ${definition.name} = ${definition.members.join(" | ")}`;
1967
+ }
1968
+ }
1969
+ function printSchemaSegment(definitions, known = definitions) {
1970
+ if (definitions.length === 0) return "";
1971
+ const inventory = namedTypeInventory(known);
1972
+ return `${definitions.map((definition) => printNamedDefinition(definition, inventory)).join(`${LINE}${LINE}`)}${LINE}`;
1973
+ }
1974
+ //#endregion
1975
+ //#region src/definition/compiler/anonymous-input.ts
1976
+ function nameAnonymousInput(descriptor, name) {
1977
+ assertNamedType(descriptor, ["descriptor"], "PH-DEF-REFERENCE-TARGET-INVALID", "Pass a descriptor returned by ph.input.");
1978
+ if (descriptor.name !== null) return descriptor;
1979
+ const validName = assertAuthoredName(name, ["name"]);
1980
+ return registerTypeDescriptor(Object.freeze({
1981
+ ...descriptor,
1982
+ name: validName,
1983
+ identity: Object.freeze({
1984
+ kind: "input",
1985
+ name: validName,
1986
+ description: descriptor.description
1987
+ })
1988
+ }));
1989
+ }
1990
+ //#endregion
1991
+ //#region src/definition/compiler/input-default.ts
1992
+ const INT_MIN = -(2 ** 31);
1993
+ const INT_MAX = 2 ** 31 - 1;
1994
+ const GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
1995
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
1996
+ function fieldDefault(field) {
1997
+ return field.presentation.default.present ? field.presentation.default.value : void 0;
1998
+ }
1999
+ function isIntLiteral(value) {
2000
+ return typeof value === "number" && /^-?\d+$/.test(JSON.stringify(value));
2001
+ }
2002
+ /** `Array.isArray` narrows a readonly JSON array to `any[]`. */
2003
+ function isList(value) {
2004
+ return Array.isArray(value);
2005
+ }
2006
+ function isInputObject(value) {
2007
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2008
+ }
2009
+ function builtInLiteral(name, value) {
2010
+ const shown = canonicalJson(value);
2011
+ switch (name) {
2012
+ case "Int": return isIntLiteral(value) && value >= INT_MIN && value <= INT_MAX ? { accepted: value } : { rejected: `${shown} is not a signed 32-bit integer` };
2013
+ case "Float": return typeof value === "number" ? { accepted: value } : { rejected: `${shown} is not a number` };
2014
+ case "String": return typeof value === "string" ? { accepted: value } : { rejected: `${shown} is not a string` };
2015
+ case "Boolean": return typeof value === "boolean" ? { accepted: value } : { rejected: `${shown} is not a boolean` };
2016
+ case "ID":
2017
+ if (typeof value === "string") return { accepted: value };
2018
+ return isIntLiteral(value) ? { accepted: String(value) } : { rejected: `${shown} is not a string or an integer` };
2019
+ default: return;
2020
+ }
2021
+ }
2022
+ function printableProblem(value) {
2023
+ if (typeof value === "string") return LONE_SURROGATE.test(value) ? `${canonicalJson(value)} is not well-formed Unicode` : null;
2024
+ if (isList(value)) {
2025
+ for (const member of value) {
2026
+ const problem = printableProblem(member);
2027
+ if (problem !== null) return problem;
2028
+ }
2029
+ return null;
2030
+ }
2031
+ if (!isInputObject(value)) return null;
2032
+ for (const [key, member] of Object.entries(value)) {
2033
+ const problem = GRAPHQL_NAME.test(key) ? printableProblem(member) : `key ${JSON.stringify(key)} is not a GraphQL name`;
2034
+ if (problem !== null) return problem;
2035
+ }
2036
+ return null;
2037
+ }
2038
+ function scalarProblem(scalar, value) {
2039
+ const builtIn = builtInLiteral(scalar.scalarName, value);
2040
+ if (builtIn !== void 0 && "rejected" in builtIn) return builtIn.rejected;
2041
+ const unprintable = printableProblem(value);
2042
+ if (unprintable !== null) return unprintable;
2043
+ const invalid = `${canonicalJson(value)} is not a valid ${scalar.scalarName}`;
2044
+ let result;
2045
+ try {
2046
+ result = constrainedBase(scalar).safeParse(builtIn === void 0 ? value : builtIn.accepted);
2047
+ } catch (error) {
2048
+ return `${invalid}: its validator threw (${thrownReason(error)})`;
2049
+ }
2050
+ if (result.success) return null;
2051
+ return `${invalid}: ${issueReason(result.error.issues)}`;
2052
+ }
2053
+ function issueReason(issues) {
2054
+ return issues.map((issue) => issue.message.replace(/\.$/, "")).join("; ");
2055
+ }
2056
+ function thrownReason(error) {
2057
+ const issues = error?.issues;
2058
+ return (Array.isArray(issues) ? issueReason(issues) : error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim().replace(/\.$/, "");
2059
+ }
2060
+ function resolvedTarget(reference) {
2061
+ try {
2062
+ return resolveReference(reference);
2063
+ } catch {
2064
+ return;
2065
+ }
2066
+ }
2067
+ function enumProblem(target, value) {
2068
+ if (typeof value === "string" && target.values.some((member) => member.name === value)) return null;
2069
+ const members = target.values.map((member) => member.name).join(", ");
2070
+ return `${canonicalJson(value)} is not a value of enum ${target.name} (${members})`;
2071
+ }
2072
+ function inputObjectProblem(target, value) {
2073
+ const name = target.name ?? "the input";
2074
+ if (!isInputObject(value)) return `${canonicalJson(value)} is not an object for input ${name}`;
2075
+ const declaresNoFields = Object.keys(target.fields).length === 0;
2076
+ for (const [key, member] of Object.entries(value)) {
2077
+ if (declaresNoFields && key === "_empty") {
2078
+ if (member === null || typeof member === "boolean") continue;
2079
+ return `field ${JSON.stringify(key)}: ${canonicalJson(member)} is not a boolean`;
2080
+ }
2081
+ if (!Object.hasOwn(target.fields, key)) return `field ${JSON.stringify(key)} is not declared on ${name}`;
2082
+ }
2083
+ for (const [key, field] of Object.entries(target.fields)) {
2084
+ if (!Object.hasOwn(value, key)) {
2085
+ if (field.required && !field.presentation.default.present) return `required field ${JSON.stringify(key)} of ${name} is missing`;
2086
+ continue;
2087
+ }
2088
+ const problem = inputDefaultProblem(field, value[key]);
2089
+ if (problem !== null) return `field ${JSON.stringify(key)}: ${problem}`;
2090
+ }
2091
+ return null;
2092
+ }
2093
+ function inputDefaultProblem(field, value) {
2094
+ if (value === null) return field.required ? "null is not accepted by a required field" : null;
2095
+ switch (field.kind) {
2096
+ case "scalar": return scalarProblem(field, value);
2097
+ case "list": {
2098
+ const { item } = field;
2099
+ if (!isList(value)) return inputDefaultProblem(item, value);
2100
+ for (const [index, member] of value.entries()) {
2101
+ const problem = inputDefaultProblem(item, member);
2102
+ if (problem !== null) return `item ${index}: ${problem}`;
2103
+ }
2104
+ return null;
2105
+ }
2106
+ case "ref": {
2107
+ const target = resolvedTarget(field);
2108
+ switch (target?.kind) {
2109
+ case "enum": return enumProblem(target, value);
2110
+ case "input": return inputObjectProblem(target, value);
2111
+ default: return null;
2112
+ }
2113
+ }
2114
+ }
2115
+ }
2116
+ function objectTargets(field, value) {
2117
+ if (value === void 0 || value === null) return [];
2118
+ if (field.kind === "list") {
2119
+ const { item } = field;
2120
+ return (isList(value) ? value : [value]).flatMap((member) => objectTargets(item, member));
2121
+ }
2122
+ if (field.kind !== "ref" || !isInputObject(value)) return [];
2123
+ const target = resolvedTarget(field);
2124
+ if (target?.kind !== "input") return [];
2125
+ const input = target;
2126
+ return [input, ...Object.entries(input.fields).flatMap(([key, nested]) => Object.hasOwn(value, key) ? objectTargets(nested, value[key]) : [])];
2127
+ }
2128
+ /**
2129
+ * graphql-js coerces an input field's default while it builds the fields of
2130
+ * the declaring type, and reads the fields of every input type the default
2131
+ * holds an object of. When those reads lead back to `owner`, the build never
2132
+ * ends. Returns the fields whose defaults close that loop, starting with
2133
+ * `owner.key`, or null when there is no loop.
2134
+ */
2135
+ function inputDefaultCycle(owner, key) {
2136
+ const seen = /* @__PURE__ */ new Set([owner]);
2137
+ const pending = [];
2138
+ const follow = (type, name, trail) => {
2139
+ const field = type.fields[name];
2140
+ const step = [...trail, `${type.name}.${name}`];
2141
+ for (const target of objectTargets(field, fieldDefault(field))) {
2142
+ if (target === owner) return step;
2143
+ if (seen.has(target)) continue;
2144
+ seen.add(target);
2145
+ pending.push({
2146
+ type: target,
2147
+ trail: step
2148
+ });
2149
+ }
2150
+ return null;
2151
+ };
2152
+ const direct = follow(owner, key, []);
2153
+ if (direct !== null) return direct;
2154
+ for (let next = pending.shift(); next !== void 0; next = pending.shift()) for (const name of Object.keys(next.type.fields)) {
2155
+ const cycle = follow(next.type, name, next.trail);
2156
+ if (cycle !== null) return cycle;
2157
+ }
2158
+ return null;
2159
+ }
2160
+ //#endregion
2161
+ //#region src/definition/compiler/input-cycle.ts
2162
+ function nonNullInputCycles(definitions) {
2163
+ const inputs = new Map(definitions.filter((definition) => definition.kind === "input").map((input) => [input.name, input]));
2164
+ const visited = /* @__PURE__ */ new Set();
2165
+ const path = [];
2166
+ const pathIndex = /* @__PURE__ */ new Map();
2167
+ const cycles = [];
2168
+ const visit = (input) => {
2169
+ if (visited.has(input.name)) return;
2170
+ visited.add(input.name);
2171
+ pathIndex.set(input.name, path.length);
2172
+ for (const field of input.fields) {
2173
+ if (field.type.kind !== "named" || !field.type.required) continue;
2174
+ const target = inputs.get(field.type.name);
2175
+ if (target === void 0) continue;
2176
+ const cycleStart = pathIndex.get(target.name);
2177
+ path.push({
2178
+ owner: input.name,
2179
+ key: field.key
2180
+ });
2181
+ if (cycleStart === void 0) visit(target);
2182
+ else cycles.push({
2183
+ input: target.name,
2184
+ fields: path.slice(cycleStart)
2185
+ });
2186
+ path.pop();
2187
+ }
2188
+ pathIndex.delete(input.name);
2189
+ };
2190
+ for (const input of inputs.values()) visit(input);
2191
+ return cycles;
2192
+ }
2193
+ //#endregion
2194
+ //#region src/definition/compiler/interface-conformance.ts
2195
+ function interfaceConformanceProblems(definitions) {
2196
+ const byName = new Map(definitions.map((definition) => [definition.name, definition]));
2197
+ const problems = [];
2198
+ for (const owner of definitions) {
2199
+ if (owner.kind !== "object" && owner.kind !== "interface") continue;
2200
+ const implemented = owner.implements ?? [];
2201
+ for (const name of implemented) {
2202
+ const iface = byName.get(name);
2203
+ if (iface?.kind !== "interface") continue;
2204
+ for (const ancestor of iface.implements ?? []) {
2205
+ if (implemented.includes(ancestor)) continue;
2206
+ problems.push({
2207
+ owner: owner.name,
2208
+ message: `Type ${owner.name} must implement ${ancestor} because it is implemented by ${iface.name}.`,
2209
+ expected: `explicit implementation of ${ancestor}`,
2210
+ received: `implements ${iface.name}`,
2211
+ repair: `Add ${ancestor} to ${owner.name}'s implemented interfaces.`
2212
+ });
2213
+ }
2214
+ for (const ifaceField of iface.fields) {
2215
+ const expected = `${iface.name}.${ifaceField.name}`;
2216
+ const received = `${owner.name}.${ifaceField.name}`;
2217
+ const field = owner.fields.find(({ name }) => name === ifaceField.name);
2218
+ if (field === void 0) problems.push({
2219
+ owner: owner.name,
2220
+ message: `Interface field ${expected} expected but ${owner.name} does not provide it.`,
2221
+ expected: `${expected}: ${printTypeReference(ifaceField.type)}`,
2222
+ received: "missing field",
2223
+ repair: `Add ${ifaceField.name} with a type compatible with ${expected}, or remove ${iface.name} from ${owner.name}'s implemented interfaces.`
2224
+ });
2225
+ else if (!isSubType(byName, field.type, ifaceField.type)) problems.push({
2226
+ owner: owner.name,
2227
+ message: `Interface field ${expected} expects type ${printTypeReference(ifaceField.type)} but ${received} is type ${printTypeReference(field.type)}.`,
2228
+ expected: printTypeReference(ifaceField.type),
2229
+ received: printTypeReference(field.type),
2230
+ repair: `Give ${received} a type compatible with ${expected}.`
2231
+ });
2232
+ }
2233
+ }
2234
+ }
2235
+ return problems;
2236
+ }
2237
+ function isSubType(byName, candidate, target) {
2238
+ if (target.required && !candidate.required) return false;
2239
+ if (candidate.kind === "list" || target.kind === "list") return candidate.kind === "list" && target.kind === "list" && isSubType(byName, candidate.item, target.item);
2240
+ if (candidate.name === target.name) return true;
2241
+ const abstract = byName.get(target.name);
2242
+ if (abstract?.kind === "union") return abstract.members.includes(candidate.name);
2243
+ const member = byName.get(candidate.name);
2244
+ return abstract?.kind === "interface" && (member?.kind === "object" || member?.kind === "interface") && member.implements?.includes(abstract.name) === true;
2245
+ }
2246
+ //#endregion
2247
+ //#region src/definition/compiler/descriptor-walk.ts
2248
+ var WalkAbort = class extends Error {};
2249
+ function directivesOf(field) {
2250
+ const { directives } = field.presentation;
2251
+ return directives.length > 0 ? { directives } : {};
2252
+ }
2253
+ var DescriptorWalk = class {
2254
+ definitions = [];
2255
+ catalogScalars = /* @__PURE__ */ new Set();
2256
+ packageScalars = /* @__PURE__ */ new Map();
2257
+ #collector;
2258
+ #built = /* @__PURE__ */ new Map();
2259
+ #visited = /* @__PURE__ */ new Set();
2260
+ #claims = /* @__PURE__ */ new Map();
2261
+ constructor(collector) {
2262
+ this.#collector = collector;
2263
+ }
2264
+ visitType(candidate, position, path, options = {}) {
2265
+ if (!isTypeDescriptor(candidate)) {
2266
+ this.#collector.add({
2267
+ code: "PH-DM-DECLARATION-INVALID",
2268
+ path,
2269
+ message: "A type position must hold a named type created by a ph builder.",
2270
+ expected: "a named type descriptor",
2271
+ received: describeReceived(candidate),
2272
+ repair: "Use a descriptor returned by ph.enum, ph.object, ph.input, ph.interface, or ph.union."
2273
+ });
2274
+ return;
2275
+ }
2276
+ if (this.#visited.has(candidate)) return this.#built.get(candidate);
2277
+ if (!this.#claimName(candidate, path)) return void 0;
2278
+ this.#visited.add(candidate);
2279
+ const definition = this.#attempt(() => this.#namedDefinition(candidate, path));
2280
+ if (definition === void 0) return void 0;
2281
+ this.#built.set(candidate, definition);
2282
+ if (options.emit !== false) this.definitions.push(definition);
2283
+ this.#visitChildren(candidate, position, path);
2284
+ return definition;
2285
+ }
2286
+ checkInputCycles() {
2287
+ const fieldPath = ({ owner, key }) => [
2288
+ ...this.#claims.get(owner)?.path ?? [],
2289
+ "fields",
2290
+ key
2291
+ ];
2292
+ for (const cycle of nonNullInputCycles(this.definitions)) {
2293
+ const [first, ...rest] = cycle.fields;
2294
+ const keys = cycle.fields.map(({ key }) => key).join(".");
2295
+ this.#collector.add({
2296
+ code: "PH-DM-INPUT-CYCLE",
2297
+ path: fieldPath(first),
2298
+ message: `Input ${cycle.input} contains itself through the non-null fields ${JSON.stringify(keys)}, so no finite value satisfies it.`,
2299
+ expected: "a nullable field or a list in every input cycle",
2300
+ received: cycle.fields.map(({ owner, key }) => `${owner}.${key}`).join(" -> "),
2301
+ repair: "Make one field of the cycle nullable, or wrap it in ph.list.",
2302
+ ...rest.length > 0 && { related: rest.map((field) => ({
2303
+ path: fieldPath(field),
2304
+ message: "The cycle continues through this field."
2305
+ })) }
2306
+ });
2307
+ }
2308
+ }
2309
+ checkInterfaceImplementations() {
2310
+ for (const { owner, ...problem } of interfaceConformanceProblems(this.definitions)) this.#collector.add({
2311
+ code: "PH-DM-INTERFACE-INVALID",
2312
+ path: this.#claims.get(owner)?.path ?? [],
2313
+ ...problem
2314
+ });
2315
+ }
2316
+ #namedDefinition(descriptor, path) {
2317
+ const name = this.#requireName(descriptor, path);
2318
+ switch (descriptor.kind) {
2319
+ case "enum": return {
2320
+ kind: "enum",
2321
+ name,
2322
+ description: descriptor.description,
2323
+ values: descriptor.values.map((value) => ({
2324
+ name: value.name,
2325
+ description: value.description,
2326
+ deprecated: value.deprecated
2327
+ }))
2328
+ };
2329
+ case "object":
2330
+ case "interface": {
2331
+ const implementing = descriptor;
2332
+ const implemented = implementing.implements.map((entry, index) => this.#requireName(entry, [
2333
+ ...path,
2334
+ "implements",
2335
+ index
2336
+ ]));
2337
+ return {
2338
+ kind: descriptor.kind,
2339
+ name,
2340
+ description: descriptor.description,
2341
+ ...implemented.length > 0 && { implements: implemented },
2342
+ fields: this.#requireFields(implementing.fields, descriptor.kind, name, path)
2343
+ };
2344
+ }
2345
+ case "input": return {
2346
+ kind: "input",
2347
+ name,
2348
+ description: descriptor.description,
2349
+ unknownKeys: "preserve",
2350
+ fields: this.#inputFields(descriptor, path)
2351
+ };
2352
+ case "union": return {
2353
+ kind: "union",
2354
+ name,
2355
+ description: descriptor.description,
2356
+ members: descriptor.members.map((member, index) => this.#requireName(member, [
2357
+ ...path,
2358
+ "members",
2359
+ index
2360
+ ]))
2361
+ };
2362
+ }
2363
+ }
2364
+ #attempt(build) {
2365
+ try {
2366
+ return this.#collector.capture(build);
2367
+ } catch (error) {
2368
+ if (error instanceof WalkAbort) return void 0;
2369
+ throw error;
2370
+ }
2371
+ }
2372
+ #typeReference(field, path) {
2373
+ switch (field.kind) {
2374
+ case "scalar": {
2375
+ const scalar = field;
2376
+ return {
2377
+ kind: "scalar",
2378
+ name: this.#scalarName(scalar, path),
2379
+ required: scalar.required
2380
+ };
2381
+ }
2382
+ case "list": {
2383
+ const list = field;
2384
+ return {
2385
+ kind: "list",
2386
+ required: list.required,
2387
+ item: this.#typeReference(list.item, [...path, "item"])
2388
+ };
2389
+ }
2390
+ case "ref": {
2391
+ const reference = field;
2392
+ const target = this.#resolve(reference, path);
2393
+ if (target === void 0) throw new WalkAbort();
2394
+ return {
2395
+ kind: "named",
2396
+ name: this.#requireName(target, path),
2397
+ required: reference.required
2398
+ };
2399
+ }
2400
+ }
2401
+ }
2402
+ #requireFields(fields, kind, name, path) {
2403
+ if (Object.keys(fields).length === 0) {
2404
+ this.#collector.add({
2405
+ code: "PH-DM-DECLARATION-INVALID",
2406
+ path: [...path, "fields"],
2407
+ message: `The ${kind} type ${JSON.stringify(name)} declares no fields, and GraphQL cannot build a schema that contains it.`,
2408
+ expected: "at least one field",
2409
+ received: "no fields",
2410
+ repair: `Give ${JSON.stringify(name)} a field, or remove it from the model. Only ph.input({ fields: {} }) may be member-less, because it projects _empty: Boolean.`
2411
+ });
2412
+ throw new WalkAbort();
2413
+ }
2414
+ return Object.entries(fields).map(([key, field]) => ({
2415
+ key,
2416
+ name: key,
2417
+ description: field.presentation.description,
2418
+ deprecated: field.presentation.deprecated,
2419
+ type: this.#typeReference(field, [
2420
+ ...path,
2421
+ "fields",
2422
+ key
2423
+ ]),
2424
+ ...directivesOf(field)
2425
+ }));
2426
+ }
2427
+ #inputFields(owner, path) {
2428
+ return Object.entries(owner.fields).map(([key, field]) => {
2429
+ const defaultValue = fieldDefault(field);
2430
+ const fieldPath = [
2431
+ ...path,
2432
+ "fields",
2433
+ key
2434
+ ];
2435
+ const type = this.#typeReference(field, fieldPath);
2436
+ if (!this.#checkInputDefault(field, type, fieldPath)) this.#checkDefaultCycle(owner, key, fieldPath);
2437
+ this.#checkInputDeprecation(field, type, fieldPath);
2438
+ return {
2439
+ key,
2440
+ name: key,
2441
+ description: field.presentation.description,
2442
+ deprecated: field.presentation.deprecated,
2443
+ type,
2444
+ ...defaultValue !== void 0 && { defaultValue },
2445
+ ...directivesOf(field)
2446
+ };
2447
+ });
2448
+ }
2449
+ #visitChildren(descriptor, position, path) {
2450
+ switch (descriptor.kind) {
2451
+ case "enum": return;
2452
+ case "input":
2453
+ this.#visitFields(descriptor.fields, "input", path);
2454
+ return;
2455
+ case "union":
2456
+ descriptor.members.forEach((member, index) => this.visitType(member, "output", [
2457
+ ...path,
2458
+ "members",
2459
+ index
2460
+ ]));
2461
+ return;
2462
+ case "object":
2463
+ case "interface": {
2464
+ const implementing = descriptor;
2465
+ implementing.implements.forEach((entry, index) => this.visitType(entry, "output", [
2466
+ ...path,
2467
+ "implements",
2468
+ index
2469
+ ]));
2470
+ this.#visitFields(implementing.fields, position, path);
2471
+ return;
2472
+ }
2473
+ }
2474
+ }
2475
+ #visitFields(fields, position, path) {
2476
+ for (const [key, field] of Object.entries(fields)) this.#visitField(field, position, [
2477
+ ...path,
2478
+ "fields",
2479
+ key
2480
+ ]);
2481
+ }
2482
+ #visitField(field, position, path) {
2483
+ if (position === "output" && fieldDefault(field) !== void 0) this.#collector.add({
2484
+ code: "PH-DM-DEFAULT-UNSUPPORTED",
2485
+ path,
2486
+ message: "A document state field cannot declare a GraphQL default value.",
2487
+ expected: "no defaultValue on a document state field use",
2488
+ received: "defaultValue",
2489
+ repair: "Remove defaultValue and set the value in the scope initial value or in the reducer. To default an operation input, declare defaultValue on the field of its ph.input."
2490
+ });
2491
+ switch (field.kind) {
2492
+ case "scalar": return;
2493
+ case "list":
2494
+ this.#visitField(field.item, position, [...path, "item"]);
2495
+ return;
2496
+ case "ref": {
2497
+ const target = this.#resolve(field, path);
2498
+ if (target === void 0 || !this.#checkPosition(target, position, path)) return;
2499
+ this.visitType(target, position, path);
2500
+ return;
2501
+ }
2502
+ }
2503
+ }
2504
+ #checkInputDefault(field, type, path) {
2505
+ const value = fieldDefault(field);
2506
+ if (value === void 0) return false;
2507
+ const problem = inputDefaultProblem(field, value);
2508
+ if (problem === null) return false;
2509
+ const typeText = printTypeReference(type);
2510
+ this.#collector.add({
2511
+ code: "PH-DEF-OPTION-INVALID",
2512
+ path: [...path, "defaultValue"],
2513
+ message: `defaultValue is not a valid value of type ${typeText}: ${problem}.`,
2514
+ expected: `a value of type ${typeText}`,
2515
+ received: canonicalJson(value),
2516
+ repair: "Use a default the field's type accepts, or remove defaultValue."
2517
+ });
2518
+ return true;
2519
+ }
2520
+ #checkInputDeprecation(field, type, path) {
2521
+ if (field.presentation.deprecated === null || !type.required || fieldDefault(field) !== void 0) return;
2522
+ this.#collector.add({
2523
+ code: "PH-DEF-FIELD-OPTION-UNSUPPORTED",
2524
+ path: [...path, "deprecated"],
2525
+ message: `Required input field ${String(path.at(-1))} cannot be deprecated: a caller has to supply it, so GraphQL refuses the schema.`,
2526
+ expected: "no deprecated on a required input field without a defaultValue",
2527
+ received: "deprecated",
2528
+ repair: "Remove required, give the field a defaultValue, or remove deprecated."
2529
+ });
2530
+ }
2531
+ #checkDefaultCycle(owner, key, path) {
2532
+ const cycle = inputDefaultCycle(owner, key);
2533
+ if (cycle === null) return;
2534
+ this.#collector.add({
2535
+ code: "PH-DEF-OPTION-INVALID",
2536
+ path: [...path, "defaultValue"],
2537
+ message: `defaultValue builds input ${owner.name} from itself through the object defaults on ${cycle.join(", ")}, which GraphQL cannot resolve.`,
2538
+ expected: "no cycle of object defaults between input types",
2539
+ received: canonicalJson(fieldDefault(owner.fields[key]) ?? null),
2540
+ repair: "Remove any one object default in the cycle, or default a nullable field in it to null. Either change clears every diagnostic this cycle reports."
2541
+ });
2542
+ }
2543
+ #resolve(reference, path) {
2544
+ try {
2545
+ return resolveReference(reference);
2546
+ } catch (error) {
2547
+ if (error instanceof DefinitionError) {
2548
+ for (const diagnostic of error.diagnostics) this.#collector.add({
2549
+ code: "PH-DEF-REFERENCE-TARGET-INVALID",
2550
+ path,
2551
+ message: diagnostic.message,
2552
+ ...diagnostic.received !== void 0 && { received: diagnostic.received },
2553
+ repair: diagnostic.repair
2554
+ });
2555
+ return;
2556
+ }
2557
+ this.#collector.add({
2558
+ code: "PH-DEF-REFERENCE-TARGET-INVALID",
2559
+ path,
2560
+ message: `A ph.ref target could not be resolved: ${error instanceof Error ? error.message : String(error)}`,
2561
+ repair: "Return an initialized named type from the thunk passed to ph.ref."
2562
+ });
2563
+ return;
2564
+ }
2565
+ }
2566
+ #checkPosition(target, position, path) {
2567
+ if (position === "input" ? target.kind === "input" || target.kind === "enum" : target.kind !== "input") return true;
2568
+ this.#collector.add({
2569
+ code: "PH-DM-TYPE-POSITION-INVALID",
2570
+ path,
2571
+ message: `The ${target.kind} type ${JSON.stringify(target.name)} cannot be referenced from an ${position} position.`,
2572
+ expected: position === "input" ? "a ph.input or ph.enum type" : "an object, interface, enum, or union type",
2573
+ received: `${target.kind} ${JSON.stringify(target.name)}`,
2574
+ repair: position === "input" ? "Reference a ph.input or ph.enum type from an operation input." : "Reference an output type from document state; an input type cannot be part of stored state."
2575
+ });
2576
+ return false;
2577
+ }
2578
+ #claimName(descriptor, path) {
2579
+ if (descriptor.name === null) return true;
2580
+ const reserved = reservedScalar(descriptor.name);
2581
+ if (reserved !== void 0) {
2582
+ this.#collector.add({
2583
+ code: "PH-DEF-NAME-INVALID",
2584
+ path,
2585
+ message: `GraphQL name ${JSON.stringify(descriptor.name)} is ${reserved}, so a named type cannot take it.`,
2586
+ expected: "a name no scalar of the catalog or of GraphQL uses",
2587
+ received: descriptor.name,
2588
+ repair: `Rename the ${descriptor.kind} type.`
2589
+ });
2590
+ return false;
2591
+ }
2592
+ if (this.packageScalars.has(descriptor.name)) {
2593
+ this.#scalarTypeCollision(descriptor.name, path);
2594
+ return false;
2595
+ }
2596
+ const claim = this.#claims.get(descriptor.name);
2597
+ if (claim === void 0) {
2598
+ this.#claims.set(descriptor.name, {
2599
+ token: descriptor,
2600
+ path
2601
+ });
2602
+ return true;
2603
+ }
2604
+ if (claim.token === descriptor) return true;
2605
+ this.#collector.add({
2606
+ code: "PH-DM-DUPLICATE-NAME",
2607
+ path,
2608
+ message: `GraphQL type name ${JSON.stringify(descriptor.name)} is claimed by two different descriptors.`,
2609
+ expected: "one descriptor per GraphQL type name",
2610
+ received: descriptor.name,
2611
+ repair: "Rename one of the two types, or reuse the same descriptor token in both places.",
2612
+ related: [{
2613
+ path: claim.path,
2614
+ message: `The other descriptor named ${JSON.stringify(descriptor.name)} was declared here.`
2615
+ }]
2616
+ });
2617
+ return false;
2618
+ }
2619
+ #scalarName(scalar, path) {
2620
+ const name = scalar.scalarName;
2621
+ const definition = scalar.definition;
2622
+ if (definition === void 0) return name;
2623
+ if (getCatalogScalar(name) !== void 0) {
2624
+ this.catalogScalars.add(name);
2625
+ return name;
2626
+ }
2627
+ const known = this.packageScalars.get(name);
2628
+ if (known !== void 0 && known !== definition) {
2629
+ this.#collector.add({
2630
+ code: "PH-SCALAR-DUPLICATE-NAME",
2631
+ definition: {
2632
+ kind: "scalar",
2633
+ key: name
2634
+ },
2635
+ path,
2636
+ message: `Two different project scalars are named ${name}.`,
2637
+ received: name,
2638
+ repair: `Declare ${name} once with defineScalar and import that definition everywhere it is used.`
2639
+ });
2640
+ throw new WalkAbort();
2641
+ }
2642
+ if (known === void 0 && this.#claims.has(name)) {
2643
+ this.#scalarTypeCollision(name, path);
2644
+ throw new WalkAbort();
2645
+ }
2646
+ this.packageScalars.set(name, definition);
2647
+ return name;
2648
+ }
2649
+ #scalarTypeCollision(name, path) {
2650
+ this.#collector.add({
2651
+ code: "PH-DM-DUPLICATE-NAME",
2652
+ path,
2653
+ message: `GraphQL name ${JSON.stringify(name)} is claimed by a project scalar and a named type.`,
2654
+ expected: "one GraphQL definition per name",
2655
+ received: name,
2656
+ repair: "Rename the scalar or the type."
2657
+ });
2658
+ }
2659
+ #requireName(descriptor, path) {
2660
+ if (descriptor.name !== null) return descriptor.name;
2661
+ this.#collector.add({
2662
+ code: "PH-DEF-REFERENCE-TARGET-INVALID",
2663
+ path,
2664
+ message: "An anonymous input has no GraphQL name in this position.",
2665
+ repair: "Name the input as ph.input(\"PagingInput\", { fields }), or use it as one operation input."
2666
+ });
2667
+ throw new WalkAbort();
2668
+ }
2669
+ };
2670
+ function reservedScalar(name) {
2671
+ if (Object.hasOwn(builtInScalarFactories, name)) return "a built-in GraphQL scalar";
2672
+ if (getCatalogScalar(name) !== void 0) return `the catalog scalar ${name}, which every host declares`;
2673
+ }
2674
+ //#endregion
2675
+ //#region src/definition/compiler/diagnostic-codes.ts
2676
+ const compilerDiagnostics = defineDiagnosticCatalog({
2677
+ "PH-DM-DUPLICATE-ACTION": {
2678
+ severity: "error",
2679
+ phase: "definition",
2680
+ meaning: "Two operations derive the same persisted action type, or an operation derives one the document runtime owns"
2681
+ },
2682
+ "PH-DM-DUPLICATE-NAME": {
2683
+ severity: "error",
2684
+ phase: "definition",
2685
+ meaning: "Two declarations derive the same module, GraphQL type, or creator name"
2686
+ },
2687
+ "PH-DM-IDENTITY-INVALID": {
2688
+ severity: "error",
2689
+ phase: "definition",
2690
+ meaning: "An identity segment, compatibility ID, or derived UUID violates the V1 contract"
2691
+ },
2692
+ "PH-DM-DECLARATION-INVALID": {
2693
+ severity: "error",
2694
+ phase: "definition",
2695
+ meaning: "A model, module, operation, error, example, version, or family declaration member is absent, malformed, unsupported, or forged"
2696
+ },
2697
+ "PH-DM-DEFAULT-UNSUPPORTED": {
2698
+ severity: "error",
2699
+ phase: "definition",
2700
+ meaning: "A document state field declares a GraphQL default value"
2701
+ },
2702
+ "PH-DM-INTERFACE-INVALID": {
2703
+ severity: "error",
2704
+ phase: "definition",
2705
+ meaning: "An object or interface does not satisfy an implemented interface's fields or ancestor requirements"
2706
+ },
2707
+ "PH-DM-INPUT-CYCLE": {
2708
+ severity: "error",
2709
+ phase: "definition",
2710
+ meaning: "An input type contains itself through singular non-null input fields, so no finite value satisfies it"
2711
+ },
2712
+ "PH-DM-TYPE-POSITION-INVALID": {
2713
+ severity: "error",
2714
+ phase: "definition",
2715
+ meaning: "An input type is referenced from an output position, or an output type from an input position"
2716
+ },
2717
+ "PH-DM-INITIAL-VALUE-INVALID": {
2718
+ severity: "error",
2719
+ phase: "definition",
2720
+ meaning: "A scope initial value cannot produce a stored JSON string, or its own state validator rejects it"
2721
+ },
2722
+ "PH-SCALAR-DUPLICATE-NAME": {
2723
+ severity: "error",
2724
+ phase: "definition",
2725
+ meaning: "Two different project scalars of one model claim one name"
2726
+ }
2727
+ }, dslDiagnostics);
2728
+ //#endregion
2729
+ //#region src/definition/compiler/identity.ts
2730
+ const DOCUMENT_MODEL_IDENTITY_NAMESPACE = "f80a5a40-200a-5996-b2af-2c0996a4135e";
2731
+ function segments(request) {
2732
+ switch (request.kind) {
2733
+ case "module": return [["moduleKey", request.moduleKey]];
2734
+ case "operation": return [["moduleKey", request.moduleKey], ["operationKey", request.operationKey]];
2735
+ case "error": return [
2736
+ ["moduleKey", request.moduleKey],
2737
+ ["operationKey", request.operationKey],
2738
+ ["errorKey", request.errorKey]
2739
+ ];
2740
+ case "state-example": return [["scope", request.scope], ["exampleKey", request.exampleKey]];
2741
+ case "operation-example": return [
2742
+ ["moduleKey", request.moduleKey],
2743
+ ["operationKey", request.operationKey],
2744
+ ["exampleKey", request.exampleKey]
2745
+ ];
2746
+ }
2747
+ }
2748
+ function escapeNonAscii(value) {
2749
+ return [...value].map((point) => {
2750
+ const code = point.codePointAt(0) ?? 0;
2751
+ return code >= 32 && code <= 126 ? point : `\\u{${code.toString(16)}}`;
2752
+ }).join("");
2753
+ }
2754
+ const IDENTITY_KEY_SEPARATOR = "/";
2755
+ function deriveDefinitionId(request, path = []) {
2756
+ const fields = [["documentType", request.documentType], ...segments(request)];
2757
+ for (const [field, value] of fields) {
2758
+ if (!isNFC(value)) return {
2759
+ ok: false,
2760
+ diagnostic: compilerDiagnostics.create({
2761
+ code: "PH-DM-IDENTITY-INVALID",
2762
+ path: [...path, field],
2763
+ message: `${field} "${escapeNonAscii(value)}" is not in Unicode NFC, so its derived ID would depend on how the source was encoded.`,
2764
+ expected: "an identity segment already in Unicode NFC",
2765
+ received: `"${escapeNonAscii(value)}"`,
2766
+ repair: `Rewrite ${field} in the source as "${escapeNonAscii(value.normalize("NFC"))}".`
2767
+ })
2768
+ };
2769
+ if (field !== "documentType" && value.includes(IDENTITY_KEY_SEPARATOR)) return {
2770
+ ok: false,
2771
+ diagnostic: compilerDiagnostics.create({
2772
+ code: "PH-DM-IDENTITY-INVALID",
2773
+ path: [...path, field],
2774
+ message: `${field} ${JSON.stringify(value)} contains ${JSON.stringify(IDENTITY_KEY_SEPARATOR)}, which separates the segments of an identity key.`,
2775
+ expected: `a ${field} without ${JSON.stringify(IDENTITY_KEY_SEPARATOR)}`,
2776
+ received: value,
2777
+ repair: `Rename it without ${JSON.stringify(IDENTITY_KEY_SEPARATOR)}; a compatibility map is keyed by the joined identity path.`
2778
+ })
2779
+ };
2780
+ }
2781
+ const tuple = [
2782
+ "powerhouse.document-model.identity",
2783
+ 1,
2784
+ request.documentType,
2785
+ request.kind,
2786
+ ...fields.slice(1).map(([, value]) => value)
2787
+ ];
2788
+ return {
2789
+ ok: true,
2790
+ id: uuidV5(DOCUMENT_MODEL_IDENTITY_NAMESPACE, canonicalJson(tuple))
2791
+ };
2792
+ }
2793
+ //#endregion
2794
+ //#region src/definition/compiler/initial-value.ts
2795
+ function serializeAndValidateInitialValue(root, value) {
2796
+ let serialized;
2797
+ try {
2798
+ serialized = JSON.stringify(value);
2799
+ } catch (error) {
2800
+ return {
2801
+ ok: false,
2802
+ reason: "not-serializable",
2803
+ message: error instanceof Error ? error.message : String(error)
2804
+ };
2805
+ }
2806
+ if (serialized === void 0) return {
2807
+ ok: false,
2808
+ reason: "not-serializable",
2809
+ message: `JSON.stringify returned undefined for a value of type ${typeof value}`
2810
+ };
2811
+ const parsed = JSON.parse(serialized);
2812
+ try {
2813
+ root.validator.parse(parsed);
2814
+ } catch (error) {
2815
+ return {
2816
+ ok: false,
2817
+ reason: "rejected",
2818
+ message: error instanceof Error ? error.message : String(error)
2819
+ };
2820
+ }
2821
+ return {
2822
+ ok: true,
2823
+ value: parsed,
2824
+ serialized
2825
+ };
2826
+ }
2827
+ //#endregion
2828
+ //#region src/definition/compiler/naming.ts
2829
+ function deriveDocumentModelNames(model, overrides = {}) {
2830
+ const graphQLName = overrides.graphQLName ?? pascalCase(model.name);
2831
+ return {
2832
+ documentType: overrides.documentType ?? model.id,
2833
+ graphQLName,
2834
+ globalStateRootName: overrides.globalStateRootName ?? `${graphQLName}State`,
2835
+ localStateRootName: overrides.localStateRootName ?? `${graphQLName}LocalState`
2836
+ };
2837
+ }
2838
+ function deriveDocumentModelModuleNames(modelName, moduleKey, overrides = {}) {
2839
+ const modulePascal = pascalCase(moduleKey);
2840
+ return {
2841
+ storedName: overrides.storedName ?? modulePascal,
2842
+ operationsInterfaceName: overrides.operationsInterfaceName ?? `${pascalCase(modelName)}${modulePascal}Operations`,
2843
+ actionNamespaceName: overrides.actionNamespaceName ?? `${camelCase(modelName)}${modulePascal}Actions`
2844
+ };
2845
+ }
2846
+ function deriveDocumentModelOperationNames(operationKey, overrides = {}) {
2847
+ const operationPascal = pascalCase(operationKey);
2848
+ const actionType = overrides.actionType ?? constantCase(operationKey);
2849
+ return {
2850
+ storedName: overrides.storedName ?? operationPascal,
2851
+ actionType,
2852
+ inputTypeName: overrides.inputTypeName ?? `${operationPascal}Input`,
2853
+ creatorKey: overrides.creatorKey ?? camelCase(constantCase(operationKey)),
2854
+ reducerMethod: overrides.reducerMethod ?? `${camelCase(operationKey)}Operation`
2855
+ };
2856
+ }
2857
+ const PLATFORM_ACTION_TYPES = /* @__PURE__ */ new Set([
2858
+ "SET_NAME",
2859
+ "SET_PREFERRED_EDITOR",
2860
+ "UNDO",
2861
+ "REDO",
2862
+ "RETRACT",
2863
+ "CREATE_DOCUMENT",
2864
+ "DELETE_DOCUMENT",
2865
+ "UPGRADE_DOCUMENT",
2866
+ "ADD_RELATIONSHIP",
2867
+ "REMOVE_RELATIONSHIP",
2868
+ "UPDATE_RELATIONSHIP",
2869
+ "PURGE_DOCUMENT"
2870
+ ]);
2871
+ function deriveOperationErrorClassName(errorKey) {
2872
+ return pascalCase(errorKey);
2873
+ }
2874
+ function deriveDocumentModelErrorNames(errorKey, authored = {}) {
2875
+ return {
2876
+ key: errorKey,
2877
+ storedName: authored.name ?? errorKey,
2878
+ storedCode: authored.code ?? errorKey
2879
+ };
2880
+ }
2881
+ const MODULE_NAME_KINDS = [
2882
+ "storedName",
2883
+ "operationsInterfaceName",
2884
+ "actionNamespaceName"
2885
+ ];
2886
+ const OPERATION_NAME_KINDS = [
2887
+ "actionType",
2888
+ "storedName",
2889
+ "inputTypeName",
2890
+ "creatorKey",
2891
+ "reducerMethod"
2892
+ ];
2893
+ function nameSlot(owner, scope, kind, value) {
2894
+ return JSON.stringify([
2895
+ owner,
2896
+ scope,
2897
+ kind,
2898
+ value
2899
+ ]);
2900
+ }
2901
+ function moduleNameClaims(names) {
2902
+ return MODULE_NAME_KINDS.map((kind) => ({
2903
+ kind,
2904
+ slot: nameSlot("module", "model", kind, names[kind]),
2905
+ value: names[kind]
2906
+ }));
2907
+ }
2908
+ function operationNameClaims(moduleKey, names) {
2909
+ return OPERATION_NAME_KINDS.map((kind) => {
2910
+ return {
2911
+ kind,
2912
+ slot: nameSlot("operation", kind === "storedName" || kind === "reducerMethod" ? moduleKey : "model", kind, names[kind]),
2913
+ value: names[kind]
2914
+ };
2915
+ });
2916
+ }
2917
+ function claim(claims, claimant, nameClaims) {
2918
+ const collisions = /* @__PURE__ */ new Map();
2919
+ for (const { kind, slot, value } of nameClaims) {
2920
+ const first = claims.get(slot);
2921
+ if (first === void 0) {
2922
+ claims.set(slot, claimant);
2923
+ continue;
2924
+ }
2925
+ const collision = collisions.get(first) ?? {
2926
+ first,
2927
+ names: [],
2928
+ actionType: false
2929
+ };
2930
+ collision.names.push(`${kind} ${JSON.stringify(value)}`);
2931
+ if (kind === "actionType") collision.actionType = true;
2932
+ collisions.set(first, collision);
2933
+ }
2934
+ return [...collisions.values()];
2935
+ }
2936
+ function collisionDiagnostic(claimant, collision) {
2937
+ const list = collision.names.join(", ");
2938
+ return compilerDiagnostics.create({
2939
+ code: collision.actionType ? "PH-DM-DUPLICATE-ACTION" : "PH-DM-DUPLICATE-NAME",
2940
+ path: claimant.path,
2941
+ message: `${claimant.label} derives ${list}, already derived by ${collision.first.label}.`,
2942
+ expected: `distinct derived names for ${claimant.label} and ${collision.first.label}`,
2943
+ received: list,
2944
+ repair: `Rename ${claimant.label} or ${collision.first.label} so their derived names differ.`,
2945
+ related: [{
2946
+ path: collision.first.path,
2947
+ message: `${collision.first.label} derives the same ${collision.names.length === 1 ? "name" : "names"}.`
2948
+ }]
2949
+ });
2950
+ }
2951
+ function checkDerivedNameCollisions(modules) {
2952
+ const claims = /* @__PURE__ */ new Map();
2953
+ const diagnostics = [];
2954
+ for (const module of modules) {
2955
+ const moduleClaim = {
2956
+ path: ["modules", module.key],
2957
+ label: `module ${JSON.stringify(module.key)}`
2958
+ };
2959
+ for (const collision of claim(claims, moduleClaim, moduleNameClaims(module.names))) diagnostics.push(collisionDiagnostic(moduleClaim, collision));
2960
+ for (const operation of module.operations) {
2961
+ const operationClaim = {
2962
+ path: [
2963
+ "modules",
2964
+ module.key,
2965
+ "operations",
2966
+ operation.key
2967
+ ],
2968
+ label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`
2969
+ };
2970
+ for (const collision of claim(claims, operationClaim, operationNameClaims(module.key, operation.names))) diagnostics.push(collisionDiagnostic(operationClaim, collision));
2971
+ }
2972
+ }
2973
+ return diagnostics;
2974
+ }
2975
+ //#endregion
2976
+ //#region src/definition/compiler/segments.ts
2977
+ function referencedNames(definition) {
2978
+ const names = [];
2979
+ const visit = (reference) => {
2980
+ if (reference.kind === "list") {
2981
+ visit(reference.item);
2982
+ return;
2983
+ }
2984
+ if (reference.kind === "named") names.push(reference.name);
2985
+ };
2986
+ switch (definition.kind) {
2987
+ case "enum": return names;
2988
+ case "union": return definition.members;
2989
+ case "input":
2990
+ definition.fields.forEach((field) => visit(field.type));
2991
+ return names;
2992
+ case "object":
2993
+ case "interface":
2994
+ names.push(...definition.implements ?? []);
2995
+ for (const field of definition.fields) {
2996
+ field.args?.forEach((argument) => visit(argument.type));
2997
+ visit(field.type);
2998
+ }
2999
+ return names;
3000
+ }
3001
+ }
3002
+ function reachableFrom(rootName, index) {
3003
+ const reached = /* @__PURE__ */ new Set();
3004
+ if (rootName === null) return reached;
3005
+ const queue = [rootName];
3006
+ while (queue.length > 0) {
3007
+ const name = queue.pop();
3008
+ if (reached.has(name)) continue;
3009
+ const definition = index.get(name);
3010
+ if (definition === void 0) continue;
3011
+ reached.add(name);
3012
+ queue.push(...referencedNames(definition));
3013
+ }
3014
+ return reached;
3015
+ }
3016
+ function assignStoredSegments(input) {
3017
+ const stateIndex = new Map(input.types.map((definition) => [definition.name, definition]));
3018
+ const globalReach = reachableFrom(input.globalRoot, stateIndex);
3019
+ const localReach = reachableFrom(input.localRoot, stateIndex);
3020
+ const operationIndex = new Map(stateIndex);
3021
+ for (const operation of input.operations) if (operation.input !== null) operationIndex.set(operation.input.name, operation.input);
3022
+ const claimed = /* @__PURE__ */ new Set();
3023
+ const operations = /* @__PURE__ */ new Map();
3024
+ for (const operation of input.operations) {
3025
+ if (operation.input === null) continue;
3026
+ claimed.add(operation.input.name);
3027
+ const reached = reachableFrom(operation.input.name, operationIndex);
3028
+ const supporting = input.types.filter((definition) => definition.kind === "input" && reached.has(definition.name) && !claimed.has(definition.name));
3029
+ for (const definition of supporting) claimed.add(definition.name);
3030
+ operations.set(operation.key, [operation.input, ...supporting]);
3031
+ }
3032
+ const local = input.types.filter((definition) => definition.kind !== "input" && localReach.has(definition.name) && !globalReach.has(definition.name));
3033
+ const localDeclared = new Set(local.map((definition) => definition.name));
3034
+ return {
3035
+ global: input.types.filter((definition) => !localDeclared.has(definition.name) && !claimed.has(definition.name)),
3036
+ local,
3037
+ operations
3038
+ };
3039
+ }
3040
+ //#endregion
3041
+ //#region src/definition/compiler/stored-scalar.ts
3042
+ function storedScalarDefinition(definition) {
3043
+ return {
3044
+ kind: "powerhouse.scalar",
3045
+ formatVersion: 1,
3046
+ name: definition.name,
3047
+ representation: definition.representation ?? "json",
3048
+ description: definition.description ?? "",
3049
+ coercion: { source: definition.coercion === void 0 ? "derived" : "explicit" },
3050
+ coercionProfile: "catalog-v1"
3051
+ };
3052
+ }
3053
+ function scalarReferences(catalogScalars, packageScalars) {
3054
+ const catalog = documentModelScalars.map(({ name }) => name).filter((name) => catalogScalars.has(name)).map((name) => ({
3055
+ name,
3056
+ implementation: `powerhouse.catalog#${name}`,
3057
+ coercionProfile: "catalog-v1"
3058
+ }));
3059
+ const declared = [...packageScalars].sort(([left], [right]) => compareCodeUnits(left, right)).map(([name, definition]) => ({
3060
+ name,
3061
+ implementation: `package#${name}`,
3062
+ coercionProfile: "catalog-v1",
3063
+ definition: storedScalarDefinition(definition)
3064
+ }));
3065
+ return [...catalog, ...declared];
3066
+ }
3067
+ function declareProjectScalars(segment, packageScalars) {
3068
+ return [...[...packageScalars.keys()].sort(compareCodeUnits).map((name) => `scalar ${name}`), segment].join("\n\n");
3069
+ }
3070
+ function namedTypeOf(type) {
3071
+ return type.kind === "list" ? namedTypeOf(type.item) : type.name;
3072
+ }
3073
+ function inputReachesProjectScalar(input, types, packageScalars) {
3074
+ const visited = /* @__PURE__ */ new Set();
3075
+ const reaches = (candidate) => {
3076
+ if (visited.has(candidate.name)) return false;
3077
+ visited.add(candidate.name);
3078
+ return candidate.fields.some((field) => {
3079
+ const name = namedTypeOf(field.type);
3080
+ if (packageScalars.has(name)) return true;
3081
+ const target = types.find((type) => type.name === name);
3082
+ return target?.kind === "input" && reaches(target);
3083
+ });
3084
+ };
3085
+ return reaches(input);
3086
+ }
3087
+ //#endregion
3088
+ //#region src/definition/compiler/compile.ts
3089
+ function deriveId(collector, request, path) {
3090
+ const derived = deriveDefinitionId(request, path);
3091
+ if (derived.ok) return derived.id;
3092
+ collector.merge([derived.diagnostic]);
3093
+ }
3094
+ function exampleDefinitions(collector, examples, path, identity) {
3095
+ const keys = /* @__PURE__ */ new Map();
3096
+ const definitions = [];
3097
+ examples.forEach((example, index) => {
3098
+ const keyPath = [
3099
+ ...path,
3100
+ index,
3101
+ "key"
3102
+ ];
3103
+ const first = keys.get(example.key);
3104
+ if (first !== void 0) {
3105
+ collector.add({
3106
+ code: "PH-DM-IDENTITY-INVALID",
3107
+ path: keyPath,
3108
+ message: `Example key ${JSON.stringify(example.key)} is declared twice, so both examples would derive one ID.`,
3109
+ expected: "a unique stable key for every example in this declaration",
3110
+ received: example.key,
3111
+ repair: "Give each example its own stable key.",
3112
+ related: [{
3113
+ path: [
3114
+ ...path,
3115
+ first,
3116
+ "key"
3117
+ ],
3118
+ message: "The first example with this key was declared here."
3119
+ }]
3120
+ });
3121
+ return;
3122
+ }
3123
+ keys.set(example.key, index);
3124
+ const id = identity(example.key, keyPath);
3125
+ if (id === void 0) return;
3126
+ definitions.push({
3127
+ id,
3128
+ key: example.key,
3129
+ value: example.value
3130
+ });
3131
+ });
3132
+ return definitions;
3133
+ }
3134
+ function errorDefinitions(collector, documentType, moduleKey, operation, path) {
3135
+ return Object.entries(operation.errors).flatMap(([key, declaration]) => {
3136
+ const id = deriveId(collector, {
3137
+ kind: "error",
3138
+ documentType,
3139
+ moduleKey,
3140
+ operationKey: operation.key,
3141
+ errorKey: key
3142
+ }, [
3143
+ ...path,
3144
+ "errors",
3145
+ key
3146
+ ]);
3147
+ if (id === void 0) return [];
3148
+ const names = deriveDocumentModelErrorNames(key, declaration);
3149
+ return [{
3150
+ id,
3151
+ key,
3152
+ code: names.storedCode,
3153
+ name: names.storedName,
3154
+ description: declaration.description ?? null,
3155
+ template: declaration.template ?? null
3156
+ }];
3157
+ });
3158
+ }
3159
+ function errorClasses(collector, errors, path, moduleClasses) {
3160
+ return errors.flatMap((error) => {
3161
+ const errorPath = [
3162
+ ...path,
3163
+ "errors",
3164
+ error.key
3165
+ ];
3166
+ const name = error.name ?? "";
3167
+ const className = deriveOperationErrorClassName(name);
3168
+ if (!isAuthoredSchemaName(className)) {
3169
+ collector.add({
3170
+ code: "PH-DM-DECLARATION-INVALID",
3171
+ path: [...errorPath, "name"],
3172
+ message: `Error name ${JSON.stringify(name)} derives the class name ${JSON.stringify(className)}, so codegen could not generate its class.`,
3173
+ expected: "a name whose PascalCase spelling is a GraphQL name",
3174
+ received: name,
3175
+ repair: "Give the error a name such as LimitReached, or remove name so the key names the class."
3176
+ });
3177
+ return [];
3178
+ }
3179
+ const codePath = [...errorPath, "code"];
3180
+ if (error.code !== null && error.code !== error.code.trim()) {
3181
+ collector.add({
3182
+ code: "PH-DM-DECLARATION-INVALID",
3183
+ path: codePath,
3184
+ message: `Error code ${JSON.stringify(error.code)} has whitespace around it.`,
3185
+ expected: "a code without leading or trailing whitespace",
3186
+ received: error.code,
3187
+ repair: "Remove the whitespace around the code, or leave the code empty so the class name is the code."
3188
+ });
3189
+ return [];
3190
+ }
3191
+ const code = error.code || className;
3192
+ const first = moduleClasses.get(className);
3193
+ if (first === void 0) moduleClasses.set(className, {
3194
+ code,
3195
+ path: codePath
3196
+ });
3197
+ else if (first.code !== code) {
3198
+ collector.add({
3199
+ code: "PH-DM-DECLARATION-INVALID",
3200
+ path: codePath,
3201
+ message: `The error class ${className} has the code ${JSON.stringify(first.code)} elsewhere in this module, and a module has one ${className} class.`,
3202
+ expected: first.code,
3203
+ received: code,
3204
+ repair: `Give both ${className} errors the same code, or give one another name.`,
3205
+ related: [{
3206
+ path: first.path,
3207
+ message: "The first code was declared here."
3208
+ }]
3209
+ });
3210
+ return [];
3211
+ }
3212
+ return [{
3213
+ key: error.key,
3214
+ className,
3215
+ code
3216
+ }];
3217
+ });
3218
+ }
3219
+ function nonEmptyState(name, initialValue, examples, schema) {
3220
+ return {
3221
+ root: {
3222
+ kind: "named",
3223
+ name,
3224
+ required: true
3225
+ },
3226
+ initialValue: initialValue.value,
3227
+ examples,
3228
+ unknownKeys: "preserve",
3229
+ materialized: {
3230
+ schema,
3231
+ initialValue: initialValue.serialized,
3232
+ examples: examples.map(({ id, value }) => ({
3233
+ id,
3234
+ value
3235
+ }))
3236
+ }
3237
+ };
3238
+ }
3239
+ function materializeInitialValue(collector, root, scope, value) {
3240
+ const materialized = serializeAndValidateInitialValue(root, value);
3241
+ if (materialized.ok) return materialized;
3242
+ const notSerializable = materialized.reason === "not-serializable";
3243
+ collector.add({
3244
+ code: "PH-DM-INITIAL-VALUE-INVALID",
3245
+ path: [
3246
+ "scopes",
3247
+ scope,
3248
+ "initialValue"
3249
+ ],
3250
+ message: notSerializable ? "This initial value cannot produce a stored JSON string." : `The ${root.name} schema rejects this initial value.`,
3251
+ expected: `a value ${root.name} accepts and JSON.stringify can serialize`,
3252
+ received: materialized.message,
3253
+ repair: notSerializable ? "Replace the value with JSON data; a stored initial value must serialize." : "Correct the initial value so the declared state schema accepts it."
3254
+ });
3255
+ }
3256
+ function compileDocumentModelVersion(config, modules) {
3257
+ const collector = new DefinitionDiagnosticCollector(compilerDiagnostics, {
3258
+ kind: "document-model",
3259
+ key: config.id,
3260
+ version: config.version
3261
+ });
3262
+ const walk = new DescriptorWalk(collector);
3263
+ const documentType = config.names.documentType;
3264
+ const identities = /* @__PURE__ */ new Map();
3265
+ const claimIdentity = (id, path) => {
3266
+ const first = identities.get(id);
3267
+ if (first === void 0) {
3268
+ identities.set(id, path);
3269
+ return;
3270
+ }
3271
+ collector.add({
3272
+ code: "PH-DM-IDENTITY-INVALID",
3273
+ path,
3274
+ message: `Specification ID ${id} is already claimed by another declaration.`,
3275
+ expected: "one ID per module, operation, error, and example",
3276
+ received: id,
3277
+ repair: "Give the two declarations distinct keys.",
3278
+ related: [{
3279
+ path: first,
3280
+ message: "First claimed here."
3281
+ }]
3282
+ });
3283
+ };
3284
+ const { global, local, auxiliaryTypes } = config.scopes;
3285
+ walk.visitType(global.root, "output", [
3286
+ "scopes",
3287
+ "global",
3288
+ "schema"
3289
+ ]);
3290
+ if (local.root !== null) walk.visitType(local.root, "output", [
3291
+ "scopes",
3292
+ "local",
3293
+ "schema"
3294
+ ]);
3295
+ auxiliaryTypes.forEach((descriptor, index) => walk.visitType(descriptor, "output", [
3296
+ "scopes",
3297
+ "auxiliaryTypes",
3298
+ index
3299
+ ]));
3300
+ const moduleKeys = /* @__PURE__ */ new Map();
3301
+ const derivedNames = [];
3302
+ const draftModules = [];
3303
+ modules.forEach((module, moduleIndex) => {
3304
+ const modulePath = ["modules", moduleIndex];
3305
+ const firstModule = moduleKeys.get(module.key);
3306
+ if (firstModule !== void 0) {
3307
+ collector.add({
3308
+ code: "PH-DM-DUPLICATE-NAME",
3309
+ path: [...modulePath, "key"],
3310
+ message: `Module key ${JSON.stringify(module.key)} is declared twice.`,
3311
+ expected: "a unique key for every module in a version",
3312
+ received: module.key,
3313
+ repair: "Rename one of the two modules.",
3314
+ related: [{
3315
+ path: [
3316
+ "modules",
3317
+ firstModule,
3318
+ "key"
3319
+ ],
3320
+ message: "The first module with this key was declared here."
3321
+ }]
3322
+ });
3323
+ return;
3324
+ }
3325
+ moduleKeys.set(module.key, moduleIndex);
3326
+ const moduleNames = deriveDocumentModelModuleNames(config.name, module.key);
3327
+ const moduleId = deriveId(collector, {
3328
+ kind: "module",
3329
+ documentType,
3330
+ moduleKey: module.key
3331
+ }, [...modulePath, "key"]);
3332
+ if (moduleId !== void 0) claimIdentity(moduleId, [...modulePath, "id"]);
3333
+ const operations = [];
3334
+ const derivedOperations = [];
3335
+ const moduleErrorClasses = /* @__PURE__ */ new Map();
3336
+ module.operations.forEach((operation, operationIndex) => {
3337
+ const operationPath = [
3338
+ ...modulePath,
3339
+ "operations",
3340
+ operationIndex
3341
+ ];
3342
+ const names = deriveDocumentModelOperationNames(operation.key);
3343
+ derivedOperations.push({
3344
+ key: operation.key,
3345
+ names
3346
+ });
3347
+ if (names.creatorKey !== operation.key) collector.add({
3348
+ code: "PH-DM-DECLARATION-INVALID",
3349
+ path: [...operationPath, "key"],
3350
+ message: `Operation key ${JSON.stringify(operation.key)} derives creator key ${JSON.stringify(names.creatorKey)}, so the typed and the runtime action creator keys would differ.`,
3351
+ expected: names.creatorKey,
3352
+ received: operation.key,
3353
+ repair: `Rename the operation to ${JSON.stringify(names.creatorKey)}.`
3354
+ });
3355
+ if (PLATFORM_ACTION_TYPES.has(names.actionType)) collector.add({
3356
+ code: "PH-DM-DUPLICATE-ACTION",
3357
+ path: [...operationPath, "key"],
3358
+ message: `Operation key ${JSON.stringify(operation.key)} derives action type ${names.actionType}, which the document runtime reduces itself, so this operation's reducer would never run.`,
3359
+ expected: "an action type the document runtime does not own",
3360
+ received: names.actionType,
3361
+ repair: "Rename the operation."
3362
+ });
3363
+ const operationId = deriveId(collector, {
3364
+ kind: "operation",
3365
+ documentType,
3366
+ moduleKey: module.key,
3367
+ operationKey: operation.key
3368
+ }, [...operationPath, "key"]);
3369
+ if (operationId !== void 0) claimIdentity(operationId, [...operationPath, "id"]);
3370
+ const inputPath = [...operationPath, "input"];
3371
+ if (operation.input.name !== null && operation.input.name !== names.inputTypeName) {
3372
+ collector.add({
3373
+ code: "PH-DM-DECLARATION-INVALID",
3374
+ path: inputPath,
3375
+ message: `Operation ${JSON.stringify(operation.key)} declares the input type ${JSON.stringify(operation.input.name)}, but the stored format binds an operation's input type name to the operation.`,
3376
+ expected: names.inputTypeName,
3377
+ received: operation.input.name,
3378
+ repair: `Declare the input inline as ph.input({ fields: { ... } }), referencing a shared named input from a field when several operations need the same fields, or name it ${JSON.stringify(names.inputTypeName)}.`
3379
+ });
3380
+ return;
3381
+ }
3382
+ const namedInput = collector.capture(() => nameAnonymousInput(operation.input, names.inputTypeName));
3383
+ if (namedInput === void 0) return;
3384
+ const input = walk.visitType(namedInput, "input", inputPath, { emit: operation.input.name !== null });
3385
+ if (input === void 0 || input.kind !== "input") return;
3386
+ const errors = errorDefinitions(collector, documentType, module.key, operation, operationPath);
3387
+ errors.forEach((error) => claimIdentity(error.id, [
3388
+ ...operationPath,
3389
+ "errors",
3390
+ error.key,
3391
+ "id"
3392
+ ]));
3393
+ const examples = exampleDefinitions(collector, operation.examples, [...operationPath, "examples"], (key, path) => deriveId(collector, {
3394
+ kind: "operation-example",
3395
+ documentType,
3396
+ moduleKey: module.key,
3397
+ operationKey: operation.key,
3398
+ exampleKey: key
3399
+ }, path));
3400
+ examples.forEach((example) => claimIdentity(example.id, [
3401
+ ...operationPath,
3402
+ "examples",
3403
+ example.key,
3404
+ "id"
3405
+ ]));
3406
+ if (operationId === void 0) return;
3407
+ operations.push({
3408
+ declaration: operation,
3409
+ actionType: names.actionType,
3410
+ creatorKey: names.creatorKey,
3411
+ scope: operation.scope,
3412
+ input,
3413
+ inputValidator: namedInput.validator,
3414
+ errorClasses: errorClasses(collector, errors, operationPath, moduleErrorClasses),
3415
+ definition: {
3416
+ id: operationId,
3417
+ key: operation.key,
3418
+ name: names.storedName,
3419
+ description: operation.description,
3420
+ actionType: names.actionType,
3421
+ creatorKey: names.creatorKey,
3422
+ scope: operation.scope,
3423
+ input,
3424
+ errors,
3425
+ examples,
3426
+ template: operation.template,
3427
+ reducer: operation.reducerTemplate
3428
+ }
3429
+ });
3430
+ });
3431
+ derivedNames.push({
3432
+ key: module.key,
3433
+ names: moduleNames,
3434
+ operations: derivedOperations
3435
+ });
3436
+ if (moduleId === void 0) return;
3437
+ draftModules.push({
3438
+ operations,
3439
+ definition: {
3440
+ id: moduleId,
3441
+ key: module.key,
3442
+ name: moduleNames.storedName,
3443
+ description: module.description,
3444
+ operations: operations.map((operation) => operation.definition)
3445
+ }
3446
+ });
3447
+ });
3448
+ collector.merge(checkDerivedNameCollisions(derivedNames));
3449
+ const stateExamples = (scope) => {
3450
+ const examples = exampleDefinitions(collector, config.scopes[scope].examples, [
3451
+ "scopes",
3452
+ scope,
3453
+ "examples"
3454
+ ], (key, path) => deriveId(collector, {
3455
+ kind: "state-example",
3456
+ documentType,
3457
+ scope,
3458
+ exampleKey: key
3459
+ }, path));
3460
+ examples.forEach((example) => claimIdentity(example.id, [
3461
+ "scopes",
3462
+ scope,
3463
+ "examples",
3464
+ example.key,
3465
+ "id"
3466
+ ]));
3467
+ return examples;
3468
+ };
3469
+ const globalExamples = stateExamples("global");
3470
+ const localExamples = stateExamples("local");
3471
+ walk.checkInterfaceImplementations();
3472
+ walk.checkInputCycles();
3473
+ collector.throwIfFailed();
3474
+ const types = walk.definitions;
3475
+ const printSegment = (definitions) => printSchemaSegment(definitions, types);
3476
+ const globalName = config.names.globalStateRootName;
3477
+ const localName = local.root === null ? null : config.names.localStateRootName;
3478
+ const segments = assignStoredSegments({
3479
+ types,
3480
+ globalRoot: globalName,
3481
+ localRoot: localName,
3482
+ operations: draftModules.flatMap((module) => module.operations.map((operation) => ({
3483
+ key: `${module.definition.key}/${operation.definition.key}`,
3484
+ input: operation.input
3485
+ })))
3486
+ });
3487
+ const globalInitialValue = materializeInitialValue(collector, global.root, "global", global.initialValue);
3488
+ const localInitialValue = local.root === null ? {
3489
+ value: {},
3490
+ serialized: "{}"
3491
+ } : materializeInitialValue(collector, local.root, "local", local.initialValue);
3492
+ collector.throwIfFailed();
3493
+ if (globalInitialValue === void 0 || localInitialValue === void 0) throw new TypeError("A state initial value could not be materialized.");
3494
+ const localState = localName === null ? {
3495
+ root: null,
3496
+ initialValue: {},
3497
+ examples: localExamples,
3498
+ unknownKeys: "preserve",
3499
+ materialized: {
3500
+ schema: "",
3501
+ initialValue: "{}",
3502
+ examples: localExamples.map(({ id, value }) => ({
3503
+ id,
3504
+ value
3505
+ }))
3506
+ }
3507
+ } : nonEmptyState(localName, localInitialValue, localExamples, printSegment(segments.local));
3508
+ const compiledModules = draftModules.map((module) => ({
3509
+ ...module,
3510
+ operations: module.operations.map((operation) => {
3511
+ const key = `${module.definition.key}/${operation.definition.key}`;
3512
+ return {
3513
+ ...operation,
3514
+ inputSchema: printSegment(segments.operations.get(key) ?? [operation.input]),
3515
+ parsesInput: inputReachesProjectScalar(operation.input, types, walk.packageScalars)
3516
+ };
3517
+ })
3518
+ }));
3519
+ const specification = {
3520
+ version: config.version,
3521
+ scalars: scalarReferences(walk.catalogScalars, walk.packageScalars),
3522
+ graphQLCompatibility: null,
3523
+ types,
3524
+ state: {
3525
+ global: nonEmptyState(globalName, globalInitialValue, globalExamples, declareProjectScalars(printSegment(segments.global), walk.packageScalars)),
3526
+ local: localState
3527
+ },
3528
+ modules: compiledModules.map((module) => module.definition),
3529
+ changeLog: [...config.changeLog]
3530
+ };
3531
+ return {
3532
+ config,
3533
+ specification,
3534
+ definition: {
3535
+ kind: "powerhouse.document-model",
3536
+ formatVersion: 1,
3537
+ compatibility: {
3538
+ identity: "derived-v1",
3539
+ scalarCoercion: "catalog-v1",
3540
+ serialization: "canonical-v1"
3541
+ },
3542
+ model: {
3543
+ documentType,
3544
+ graphQLName: config.names.graphQLName,
3545
+ name: config.name,
3546
+ description: config.description,
3547
+ extension: config.extension,
3548
+ author: {
3549
+ name: config.author.name,
3550
+ website: config.author.website
3551
+ }
3552
+ },
3553
+ specifications: [specification]
3554
+ },
3555
+ initialGlobalState: globalInitialValue.value,
3556
+ initialLocalState: localInitialValue.value,
3557
+ modules: compiledModules
3558
+ };
3559
+ }
3560
+ //#endregion
3561
+ //#region src/definition/model/diagnostic-codes.ts
3562
+ const modelDiagnostics = defineDiagnosticCatalog({
3563
+ "PH-DM-STATE-ROOT-INVALID": {
3564
+ severity: "error",
3565
+ phase: "definition",
3566
+ meaning: "A required state root is absent, is not an object, or has the wrong canonical name"
3567
+ },
3568
+ "PH-DM-SCOPE-UNSUPPORTED": {
3569
+ severity: "error",
3570
+ phase: "definition",
3571
+ meaning: "A definition requests a scope outside global or local"
3572
+ },
3573
+ "PH-AUTH-UNSUPPORTED": {
3574
+ severity: "error",
3575
+ phase: "authorization",
3576
+ meaning: "A document model declares authorization, which core v1 rejects"
3577
+ }
3578
+ }, compilerDiagnostics);
3579
+ //#endregion
3580
+ //#region src/definition/model/normalize.ts
3581
+ function modelCollector(definition) {
3582
+ return new DefinitionDiagnosticCollector(modelDiagnostics, definition);
3583
+ }
3584
+ function take(collector, snapshot, allowedKeys, unknownKeyCode = "PH-DM-DECLARATION-INVALID", repair = "Pass a plain object literal with enumerable string-keyed data properties and no accessors, symbols, or class instances.") {
3585
+ if (snapshot.ok) return snapshot.value;
3586
+ const path = snapshot.path.map((segment) => typeof segment === "number" ? segment : String(segment));
3587
+ if (snapshot.reason === "unknown-key") collector.add({
3588
+ code: unknownKeyCode,
3589
+ path,
3590
+ message: `Option ${JSON.stringify(snapshot.key)} is not supported here.`,
3591
+ expected: allowedKeys.join(", "),
3592
+ received: snapshot.key,
3593
+ repair: `Remove ${JSON.stringify(snapshot.key)}; the supported options are ${allowedKeys.join(", ")}.`
3594
+ });
3595
+ else if (snapshot.reason === "custom-prototype" && snapshot.expected === "array") collector.add({
3596
+ code: "PH-DM-DECLARATION-INVALID",
3597
+ path,
3598
+ message: "Expected a plain array, not an Array subclass or an array from another realm.",
3599
+ received: snapshot.received,
3600
+ repair: "Pass an array literal, or copy the array with Array.from(...)."
3601
+ });
3602
+ else collector.add({
3603
+ code: "PH-DM-DECLARATION-INVALID",
3604
+ path,
3605
+ message: `The option value could not be snapshotted (${snapshot.reason}).`,
3606
+ received: rejectionReceived(snapshot),
3607
+ repair
3608
+ });
3609
+ }
3610
+ function takeArray(collector, value, path) {
3611
+ return take(collector, snapshotArray(value, path), [], void 0, "Pass an array literal of data values with no holes, extra properties, accessors, or proxies.");
3612
+ }
3613
+ function requiredString(collector, value, path) {
3614
+ if (typeof value === "string" && value.length > 0) return value;
3615
+ collector.add({
3616
+ code: "PH-DM-DECLARATION-INVALID",
3617
+ path,
3618
+ message: "This declaration member must be a nonempty string.",
3619
+ expected: "a nonempty string",
3620
+ received: value === void 0 ? "absent" : describeReceived(value),
3621
+ repair: `Give ${String(path.at(-1) ?? "the member")} a nonempty string value.`
3622
+ });
3623
+ }
3624
+ function requiredText(collector, value, path) {
3625
+ if (typeof value === "string") return value;
3626
+ collector.add({
3627
+ code: "PH-DM-DECLARATION-INVALID",
3628
+ path,
3629
+ message: "This declaration member must be a string.",
3630
+ expected: "a string",
3631
+ received: value === void 0 ? "absent" : describeReceived(value),
3632
+ repair: `Give ${String(path.at(-1))} a string value.`
3633
+ });
3634
+ }
3635
+ function optionalString(collector, value, path) {
3636
+ if (value === void 0 || value === null) return null;
3637
+ if (typeof value === "string") return value;
3638
+ collector.add({
3639
+ code: "PH-DM-DECLARATION-INVALID",
3640
+ path,
3641
+ message: "This declaration member must be a string, null, or absent.",
3642
+ expected: "a string, null, or absent",
3643
+ received: describeReceived(value),
3644
+ repair: `Pass a string, pass null, or omit ${String(path.at(-1))}.`
3645
+ });
3646
+ }
3647
+ function normalizeExamples(collector, value, path) {
3648
+ if (value === void 0) return [];
3649
+ const entries = takeArray(collector, value, path);
3650
+ if (entries === void 0) return [];
3651
+ return entries.flatMap((entry, index) => {
3652
+ const examplePath = [...path, index];
3653
+ const example = take(collector, snapshotDataRecord(entry, ["key", "value"], examplePath), ["key", "value"]);
3654
+ if (example === void 0) return [];
3655
+ const key = requiredString(collector, example.key, [...examplePath, "key"]);
3656
+ if (typeof example.value !== "string") {
3657
+ collector.add({
3658
+ code: "PH-DM-DECLARATION-INVALID",
3659
+ path: [...examplePath, "value"],
3660
+ message: "An example value must be the stored JSON string.",
3661
+ expected: "string",
3662
+ received: describeReceived(example.value),
3663
+ repair: "Pass the serialized example, such as '{\"id\":\"item-1\"}'."
3664
+ });
3665
+ return [];
3666
+ }
3667
+ return key === void 0 ? [] : [{
3668
+ key,
3669
+ value: example.value
3670
+ }];
3671
+ });
3672
+ }
3673
+ //#endregion
3674
+ //#region src/definition/model/define-document-model.ts
3675
+ const moduleDeclarations = /* @__PURE__ */ new WeakMap();
3676
+ const compiledVersions$1 = /* @__PURE__ */ new WeakMap();
3677
+ function compiledVersionOf(value) {
3678
+ return value !== null && typeof value === "object" ? compiledVersions$1.get(value) : void 0;
3679
+ }
3680
+ function notExactEmptyObject(value) {
3681
+ const otherPrototype = "an object whose prototype is not Object.prototype";
3682
+ const snapshot = snapshotRecord(value, [], []);
3683
+ if (!snapshot.ok) {
3684
+ if (snapshot.reason === "unknown-key") return "a nonempty object";
3685
+ if (snapshot.reason === "custom-prototype") return otherPrototype;
3686
+ return rejectionReceived(snapshot);
3687
+ }
3688
+ try {
3689
+ return Object.getPrototypeOf(value) === Object.prototype ? void 0 : otherPrototype;
3690
+ } catch {
3691
+ return "inspection-failed";
3692
+ }
3693
+ }
3694
+ function stateRoot(collector, candidate, expectedName, path) {
3695
+ if (isTypeDescriptor(candidate) && candidate.kind === "object" && candidate.name === expectedName) return candidate;
3696
+ collector.add({
3697
+ code: "PH-DM-STATE-ROOT-INVALID",
3698
+ path,
3699
+ message: `A state root must be a ph.object named ${expectedName}.`,
3700
+ expected: `ph.object(${JSON.stringify(expectedName)}, { fields: { ... } })`,
3701
+ received: isTypeDescriptor(candidate) ? `${candidate.kind} ${JSON.stringify(candidate.name)}` : candidate === void 0 ? "absent" : describeReceived(candidate),
3702
+ repair: `Declare this scope as ph.object(${JSON.stringify(expectedName)}, { fields: { ... } }); the root name is derived from the model name.`
3703
+ });
3704
+ }
3705
+ const SCOPE_DECLARATION_KEYS = [
3706
+ "schema",
3707
+ "initialValue",
3708
+ "examples"
3709
+ ];
3710
+ function normalizeScope(collector, value, scope, expectedName) {
3711
+ const path = ["scopes", scope];
3712
+ const declaration = take(collector, snapshotRecord(value, SCOPE_DECLARATION_KEYS, path), SCOPE_DECLARATION_KEYS);
3713
+ if (declaration === void 0) return void 0;
3714
+ const examples = normalizeExamples(collector, declaration.examples, [...path, "examples"]);
3715
+ const initialValuePath = [...path, "initialValue"];
3716
+ if (scope === "local" && declaration.schema === null) {
3717
+ const refused = notExactEmptyObject(declaration.initialValue);
3718
+ if (refused === void 0) return {
3719
+ root: null,
3720
+ initialValue: {},
3721
+ examples
3722
+ };
3723
+ collector.add({
3724
+ code: "PH-DM-INITIAL-VALUE-INVALID",
3725
+ path: initialValuePath,
3726
+ message: "An empty local scope requires an exact empty plain JSON object as its initial value.",
3727
+ expected: "{}",
3728
+ received: refused,
3729
+ repair: "Use local: { schema: null, initialValue: {} }."
3730
+ });
3731
+ return;
3732
+ }
3733
+ const root = stateRoot(collector, declaration.schema, expectedName, [...path, "schema"]);
3734
+ if (root === void 0) return void 0;
3735
+ const initialValue = snapshotDataRecord(declaration.initialValue, void 0, initialValuePath);
3736
+ if (!initialValue.ok) {
3737
+ collector.add({
3738
+ code: "PH-DM-INITIAL-VALUE-INVALID",
3739
+ path: initialValue.path.map((segment) => typeof segment === "number" ? segment : String(segment)),
3740
+ message: "An initial value must contain only plain data properties.",
3741
+ expected: "a plain data object",
3742
+ received: rejectionReceived(initialValue),
3743
+ repair: "Use a plain object with enumerable string-keyed data properties."
3744
+ });
3745
+ return;
3746
+ }
3747
+ return {
3748
+ root,
3749
+ initialValue: initialValue.value,
3750
+ examples
3751
+ };
3752
+ }
3753
+ const CONFIG_KEYS = [
3754
+ "id",
3755
+ "name",
3756
+ "description",
3757
+ "extension",
3758
+ "version",
3759
+ "author",
3760
+ "changeLog",
3761
+ "scopes"
3762
+ ];
3763
+ const SCOPE_MAP_KEYS = [
3764
+ "auxiliaryTypes",
3765
+ "global",
3766
+ "local"
3767
+ ];
3768
+ function rejectAuthorization(collector, container, path) {
3769
+ let keys = [];
3770
+ try {
3771
+ if (container !== null && typeof container === "object") keys = Object.getOwnPropertyNames(container);
3772
+ } catch {}
3773
+ if (!keys.includes("auth")) return false;
3774
+ collector.add({
3775
+ code: "PH-AUTH-UNSUPPORTED",
3776
+ path: [...path, "auth"],
3777
+ message: "A document model cannot declare authorization; core V1 rejects a model auth declaration.",
3778
+ expected: "no auth declaration",
3779
+ received: "auth",
3780
+ repair: "Remove the auth declaration. Platform authorization state and its runtime behavior are unchanged and stay outside the model declaration."
3781
+ });
3782
+ return true;
3783
+ }
3784
+ function normalizeScopes(collector, value, names) {
3785
+ const path = ["scopes"];
3786
+ const declaresAuth = rejectAuthorization(collector, value, path);
3787
+ const snapshot = snapshotRecord(value, SCOPE_MAP_KEYS, path, ["auth"]);
3788
+ if (!snapshot.ok && snapshot.reason === "unknown-key") {
3789
+ collector.add({
3790
+ code: "PH-DM-SCOPE-UNSUPPORTED",
3791
+ path: [...path, snapshot.key],
3792
+ message: `Scope ${JSON.stringify(snapshot.key)} cannot be declared; DocumentSpecification.state describes global and local only.`,
3793
+ expected: "global or local",
3794
+ received: snapshot.key,
3795
+ repair: "Remove the scope. auth, document, and header stay platform concerns, and runtime action scopes keep their current handling."
3796
+ });
3797
+ return;
3798
+ }
3799
+ const scopes = take(collector, snapshot, SCOPE_MAP_KEYS);
3800
+ if (scopes === void 0 || declaresAuth) return void 0;
3801
+ const auxiliaryTypes = (scopes.auxiliaryTypes === void 0 ? [] : takeArray(collector, scopes.auxiliaryTypes, [...path, "auxiliaryTypes"]) ?? []).flatMap((candidate, index) => {
3802
+ if (isTypeDescriptor(candidate)) return [candidate];
3803
+ collector.add({
3804
+ code: "PH-DM-DECLARATION-INVALID",
3805
+ path: [
3806
+ ...path,
3807
+ "auxiliaryTypes",
3808
+ index
3809
+ ],
3810
+ message: "An auxiliary type must be a named type created by a ph builder.",
3811
+ expected: "a named type descriptor",
3812
+ received: describeReceived(candidate),
3813
+ repair: "List descriptors returned by ph.enum, ph.object, ph.input, ph.interface, or ph.union."
3814
+ });
3815
+ return [];
3816
+ });
3817
+ const global = normalizeScope(collector, scopes.global, "global", names.global);
3818
+ const local = normalizeScope(collector, scopes.local, "local", names.local);
3819
+ if (global === void 0 || global.root === null || local === void 0) return;
3820
+ return {
3821
+ auxiliaryTypes,
3822
+ global: {
3823
+ ...global,
3824
+ root: global.root
3825
+ },
3826
+ local
3827
+ };
3828
+ }
3829
+ function normalizeConfig(collector, input) {
3830
+ const declaresAuth = rejectAuthorization(collector, input, []);
3831
+ const config = take(collector, snapshotRecord(input, CONFIG_KEYS, [], ["auth"]), CONFIG_KEYS);
3832
+ if (config === void 0 || declaresAuth) return void 0;
3833
+ const id = requiredString(collector, config.id, ["id"]);
3834
+ const name = requiredString(collector, config.name, ["name"]);
3835
+ const description = requiredText(collector, config.description, ["description"]);
3836
+ const extension = requiredString(collector, config.extension, ["extension"]);
3837
+ const version = config.version;
3838
+ const validVersion = typeof version === "number" && Number.isSafeInteger(version) && version > 0;
3839
+ if (!validVersion) collector.add({
3840
+ code: "PH-DM-DECLARATION-INVALID",
3841
+ path: ["version"],
3842
+ message: "A code-first model version must be a positive safe integer.",
3843
+ expected: "a positive safe integer",
3844
+ received: typeof version === "number" ? String(version) : describeReceived(version),
3845
+ repair: "Use version: 1, or the next integer for a later version."
3846
+ });
3847
+ const author = take(collector, snapshotRecord(config.author, ["name", "website"], ["author"]), ["name", "website"]);
3848
+ const authorName = author === void 0 ? void 0 : requiredString(collector, author.name, ["author", "name"]);
3849
+ const website = author === void 0 ? null : optionalString(collector, author.website, ["author", "website"]);
3850
+ const changeLog = (config.changeLog === void 0 ? [] : takeArray(collector, config.changeLog, ["changeLog"]) ?? []).flatMap((entry, index) => {
3851
+ const line = requiredString(collector, entry, ["changeLog", index]);
3852
+ return line === void 0 ? [] : [line];
3853
+ });
3854
+ if (id === void 0 || name === void 0) return void 0;
3855
+ const names = deriveDocumentModelNames({
3856
+ id,
3857
+ name
3858
+ });
3859
+ const scopes = normalizeScopes(collector, config.scopes, {
3860
+ global: names.globalStateRootName,
3861
+ local: names.localStateRootName
3862
+ });
3863
+ if (scopes === void 0 || description === void 0 || extension === void 0 || authorName === void 0 || website === void 0 || !validVersion) return;
3864
+ return {
3865
+ id,
3866
+ name,
3867
+ description,
3868
+ extension,
3869
+ version,
3870
+ author: {
3871
+ name: authorName,
3872
+ website
3873
+ },
3874
+ changeLog,
3875
+ names,
3876
+ scopes
3877
+ };
3878
+ }
3879
+ const OPERATION_KEYS = [
3880
+ "description",
3881
+ "input",
3882
+ "errors",
3883
+ "examples",
3884
+ "template",
3885
+ "reducerTemplate",
3886
+ "reduce"
3887
+ ];
3888
+ const ERROR_KEYS = [
3889
+ "code",
3890
+ "name",
3891
+ "description",
3892
+ "template"
3893
+ ];
3894
+ function normalizeErrors(collector, value, path) {
3895
+ if (value === void 0) return {};
3896
+ const errors = take(collector, snapshotRecord(value, void 0, path), []);
3897
+ if (errors === void 0) return {};
3898
+ const normalized = {};
3899
+ for (const [key, declaration] of Object.entries(errors)) {
3900
+ const errorPath = [...path, key];
3901
+ if (key.length === 0 || !isNFC(key)) {
3902
+ collector.add({
3903
+ code: "PH-DM-IDENTITY-INVALID",
3904
+ path: errorPath,
3905
+ message: "An error key is an identity segment, so it must be a nonempty string already in Unicode NFC.",
3906
+ expected: "a nonempty NFC error key",
3907
+ received: key,
3908
+ repair: "Rewrite the error key in Unicode NFC."
3909
+ });
3910
+ continue;
3911
+ }
3912
+ const className = deriveOperationErrorClassName(key);
3913
+ if (className !== key) {
3914
+ collector.add({
3915
+ code: "PH-DM-DECLARATION-INVALID",
3916
+ path: errorPath,
3917
+ message: `Error key ${JSON.stringify(key)} derives the class name ${JSON.stringify(className)}, so the message a failed operation persists would differ from the schema-first equivalent.`,
3918
+ expected: className,
3919
+ received: key,
3920
+ repair: `Rename the error to ${JSON.stringify(className)}.`
3921
+ });
3922
+ continue;
3923
+ }
3924
+ const metadata = take(collector, snapshotDataRecord(declaration, ERROR_KEYS, errorPath), ERROR_KEYS);
3925
+ if (metadata === void 0) continue;
3926
+ const entry = {};
3927
+ let valid = true;
3928
+ for (const member of ERROR_KEYS) {
3929
+ if (!Object.hasOwn(metadata, member)) continue;
3930
+ const text = optionalString(collector, metadata[member], [...errorPath, member]);
3931
+ if (text === void 0) valid = false;
3932
+ else entry[member] = text;
3933
+ }
3934
+ if (valid) normalized[key] = entry;
3935
+ }
3936
+ return normalized;
3937
+ }
3938
+ const builtTokens = /* @__PURE__ */ new WeakSet();
3939
+ function operationBuilder(collector, stage, scope) {
3940
+ return ((input) => {
3941
+ const token = { kind: "powerhouse.document-model-operation" };
3942
+ builtTokens.add(token);
3943
+ const reject = () => {
3944
+ stage.rejected.add(token);
3945
+ return token;
3946
+ };
3947
+ const path = ["operations"];
3948
+ const config = take(collector, snapshotRecord(input, OPERATION_KEYS, path), OPERATION_KEYS);
3949
+ if (config === void 0) return reject();
3950
+ const descriptor = config.input;
3951
+ if (!isTypeDescriptor(descriptor) || descriptor.kind !== "input") {
3952
+ collector.add({
3953
+ code: "PH-DM-DECLARATION-INVALID",
3954
+ path: [...path, "input"],
3955
+ message: "An operation must declare a ph.input descriptor.",
3956
+ expected: "a ph.input descriptor",
3957
+ received: isTypeDescriptor(descriptor) ? descriptor.kind : descriptor === void 0 ? "absent" : describeReceived(descriptor),
3958
+ repair: "Declare input: ph.input({ fields: { ... } }); an operation with no fields uses ph.input({ fields: {} })."
3959
+ });
3960
+ return reject();
3961
+ }
3962
+ if (typeof config.reduce !== "function") {
3963
+ collector.add({
3964
+ code: "PH-DM-DECLARATION-INVALID",
3965
+ path: [...path, "reduce"],
3966
+ message: "An operation must declare one reducer.",
3967
+ expected: "reduce(state, input, ctx)",
3968
+ received: config.reduce === void 0 ? "absent" : describeReceived(config.reduce),
3969
+ repair: "Add reduce(state, input, ctx) to the operation declaration."
3970
+ });
3971
+ return reject();
3972
+ }
3973
+ const text = (key) => optionalString(collector, config[key], [...path, key]) ?? null;
3974
+ stage.declarations.set(token, {
3975
+ scope,
3976
+ input: descriptor,
3977
+ description: text("description"),
3978
+ errors: normalizeErrors(collector, config.errors, [...path, "errors"]),
3979
+ examples: normalizeExamples(collector, config.examples, [...path, "examples"]),
3980
+ template: text("template"),
3981
+ reducerTemplate: text("reducerTemplate"),
3982
+ reduce: config.reduce
3983
+ });
3984
+ return token;
3985
+ });
3986
+ }
3987
+ function normalizeModuleKey(collector, key) {
3988
+ const path = ["modules", "key"];
3989
+ const moduleKey = requiredString(collector, key, path);
3990
+ if (moduleKey === void 0) return void 0;
3991
+ if (!isNFC(moduleKey)) {
3992
+ collector.add({
3993
+ code: "PH-DM-IDENTITY-INVALID",
3994
+ path,
3995
+ message: "A module key is an identity segment, so it must already be in Unicode NFC.",
3996
+ expected: "a module key in Unicode NFC",
3997
+ received: moduleKey,
3998
+ repair: "Rewrite the module key in Unicode NFC."
3999
+ });
4000
+ return;
4001
+ }
4002
+ const storedName = deriveDocumentModelModuleNames("", moduleKey).storedName;
4003
+ if (!isAuthoredSchemaName(storedName)) {
4004
+ collector.add({
4005
+ code: "PH-DM-DECLARATION-INVALID",
4006
+ path,
4007
+ message: `Module key ${JSON.stringify(moduleKey)} derives the invalid stored name ${JSON.stringify(storedName)}.`,
4008
+ expected: "a key whose derived stored name is a GraphQL name",
4009
+ received: moduleKey,
4010
+ repair: "Use a module key such as lineItems or line-items."
4011
+ });
4012
+ return;
4013
+ }
4014
+ return moduleKey;
4015
+ }
4016
+ function normalizeModule(collector, key, config) {
4017
+ const moduleKey = normalizeModuleKey(collector, key);
4018
+ const declaration = take(collector, snapshotRecord(config, ["description", "operations"], ["module"]), ["description", "operations"]);
4019
+ if (declaration === void 0 || moduleKey === void 0) return void 0;
4020
+ const description = optionalString(collector, declaration.description, ["module", "description"]);
4021
+ if (typeof declaration.operations !== "function") {
4022
+ collector.add({
4023
+ code: "PH-DM-DECLARATION-INVALID",
4024
+ path: ["module", "operations"],
4025
+ message: "Module operations must be declared by a callback.",
4026
+ expected: "operations: ({ global, local }) => ({ ... })",
4027
+ received: declaration.operations === void 0 ? "absent" : describeReceived(declaration.operations),
4028
+ repair: "Use operations: ({ global, local }) => ({ ... })."
4029
+ });
4030
+ return;
4031
+ }
4032
+ const stage = {
4033
+ declarations: /* @__PURE__ */ new Map(),
4034
+ rejected: /* @__PURE__ */ new Set()
4035
+ };
4036
+ const operationMap = take(collector, snapshotRecord(declaration.operations({
4037
+ global: operationBuilder(collector, stage, "global"),
4038
+ local: operationBuilder(collector, stage, "local")
4039
+ }), void 0, ["module", "operations"]), []);
4040
+ if (operationMap === void 0) return void 0;
4041
+ const operations = [];
4042
+ const seen = /* @__PURE__ */ new Map();
4043
+ for (const [operationKey, candidate] of Object.entries(operationMap)) {
4044
+ const path = [
4045
+ "module",
4046
+ "operations",
4047
+ operationKey
4048
+ ];
4049
+ if (!isAuthoredSchemaName(operationKey) || !isNFC(operationKey)) {
4050
+ collector.add({
4051
+ code: "PH-DM-DECLARATION-INVALID",
4052
+ path,
4053
+ message: `Operation key ${JSON.stringify(operationKey)} must be a GraphQL name in Unicode NFC, because the action type, input type, and creator key derive from it.`,
4054
+ expected: "a GraphQL name such as addLineItem",
4055
+ received: operationKey,
4056
+ repair: "Rename the operation key."
4057
+ });
4058
+ continue;
4059
+ }
4060
+ const token = candidate !== null && typeof candidate === "object" ? candidate : void 0;
4061
+ const operation = token === void 0 ? void 0 : stage.declarations.get(token);
4062
+ if (token === void 0 || operation === void 0) {
4063
+ if (token !== void 0 && stage.rejected.has(token)) continue;
4064
+ collector.add({
4065
+ code: "PH-DM-DECLARATION-INVALID",
4066
+ path,
4067
+ message: "An operation entry must be the value this operations callback's global(...) or local(...) builder returned.",
4068
+ expected: "an operation token of this operations callback",
4069
+ received: token !== void 0 && builtTokens.has(token) ? "an operation token this operations callback did not build" : describeReceived(candidate),
4070
+ repair: "Wrap the operation declaration with the scope builder the operations callback receives."
4071
+ });
4072
+ continue;
4073
+ }
4074
+ const firstKey = seen.get(token);
4075
+ if (firstKey !== void 0) {
4076
+ collector.add({
4077
+ code: "PH-DM-DECLARATION-INVALID",
4078
+ path,
4079
+ message: `This operation token is already assigned to ${JSON.stringify(firstKey)}.`,
4080
+ expected: "one scope-builder call per operation",
4081
+ received: operationKey,
4082
+ repair: "Call the scope builder separately for each operation.",
4083
+ related: [{
4084
+ path: [
4085
+ "module",
4086
+ "operations",
4087
+ firstKey
4088
+ ],
4089
+ message: "The token was first assigned here."
4090
+ }]
4091
+ });
4092
+ continue;
4093
+ }
4094
+ seen.set(token, operationKey);
4095
+ operations.push({
4096
+ ...operation,
4097
+ key: operationKey
4098
+ });
4099
+ }
4100
+ return {
4101
+ key: moduleKey,
4102
+ description: description ?? null,
4103
+ operations
4104
+ };
4105
+ }
4106
+ function versionModules(collector, contextId, documentType, versionConfig) {
4107
+ const declaration = take(collector, snapshotRecord(versionConfig, ["modules"], ["version"]), ["modules"]);
4108
+ const modules = declaration === void 0 ? void 0 : takeArray(collector, declaration.modules, ["modules"]);
4109
+ if (modules === void 0) {
4110
+ collector.add({
4111
+ code: "PH-DM-DECLARATION-INVALID",
4112
+ path: ["modules"],
4113
+ message: "A model version requires an array of module tokens.",
4114
+ expected: "modules: [oneModule, anotherModule]",
4115
+ received: "absent",
4116
+ repair: "Pass every module token of this version in one array."
4117
+ });
4118
+ return [];
4119
+ }
4120
+ return modules.flatMap((module, index) => {
4121
+ const entry = module !== null && typeof module === "object" ? moduleDeclarations.get(module) : void 0;
4122
+ if (entry?.contextId === contextId) return [entry.declaration];
4123
+ if (entry !== void 0) {
4124
+ collector.add({
4125
+ code: "PH-DM-DECLARATION-INVALID",
4126
+ path: ["modules", index],
4127
+ message: "This module was created by a different document-model context.",
4128
+ expected: `a module of ${JSON.stringify(documentType)}`,
4129
+ received: "a module of another document-model context",
4130
+ repair: "Pass only the modules returned by this context's module() call; a same-shaped state type does not make another model's module this one's."
4131
+ });
4132
+ return [];
4133
+ }
4134
+ collector.add({
4135
+ code: "PH-DM-DECLARATION-INVALID",
4136
+ path: ["modules", index],
4137
+ message: "A version member is not a document-model module token.",
4138
+ expected: "a module token returned by context.module",
4139
+ received: describeReceived(module),
4140
+ repair: "Pass only the values returned by this context's module()."
4141
+ });
4142
+ return [];
4143
+ });
4144
+ }
4145
+ /**
4146
+ * @experimental Declares a document model version from `ph` descriptors.
4147
+ * The context's `module()` declares operations and `version()` compiles them
4148
+ * into a token for `materialize` or `defineDocumentModelFamily`.
4149
+ */
4150
+ function defineDocumentModel(config) {
4151
+ const contextId = Symbol("powerhouse.document-model-context");
4152
+ const configCollector = modelCollector();
4153
+ const normalized = normalizeConfig(configCollector, config);
4154
+ configCollector.throwIfFailed();
4155
+ if (normalized === void 0) throw new TypeError("The document-model declaration could not be normalized.");
4156
+ const definitionRef = {
4157
+ kind: "document-model",
4158
+ key: normalized.id,
4159
+ version: normalized.version
4160
+ };
4161
+ return {
4162
+ module(key, moduleConfig) {
4163
+ const collector = modelCollector(definitionRef);
4164
+ const declaration = normalizeModule(collector, key, moduleConfig);
4165
+ collector.throwIfFailed();
4166
+ if (declaration === void 0) throw new TypeError("The module declaration could not be normalized.");
4167
+ const token = { kind: "powerhouse.document-model-module" };
4168
+ moduleDeclarations.set(token, {
4169
+ contextId,
4170
+ declaration
4171
+ });
4172
+ return token;
4173
+ },
4174
+ version(versionConfig) {
4175
+ const collector = modelCollector(definitionRef);
4176
+ const modules = versionModules(collector, contextId, normalized.id, versionConfig);
4177
+ collector.throwIfFailed();
4178
+ const compiled = collector.capture(() => compileDocumentModelVersion(normalized, modules));
4179
+ collector.throwIfFailed();
4180
+ if (compiled === void 0) throw new TypeError("The model version could not be compiled.");
4181
+ const token = {
4182
+ kind: "powerhouse.document-model-version",
4183
+ version: normalized.version,
4184
+ documentType: normalized.id
4185
+ };
4186
+ compiledVersions$1.set(token, compiled);
4187
+ return token;
4188
+ }
4189
+ };
4190
+ }
4191
+ //#endregion
4192
+ //#region src/definition/model/family.ts
4193
+ const familyDeclarations = /* @__PURE__ */ new WeakMap();
4194
+ function familyDeclarationOf(value) {
4195
+ return value !== null && typeof value === "object" ? familyDeclarations.get(value) : void 0;
4196
+ }
4197
+ function compiledVersions(collector, value) {
4198
+ const versions = takeArray(collector, value, ["versions"]) ?? [];
4199
+ if (versions.length === 0) collector.add({
4200
+ code: "PH-DM-DECLARATION-INVALID",
4201
+ path: ["versions"],
4202
+ message: "A document-model family requires at least one version.",
4203
+ expected: "a nonempty version tuple",
4204
+ received: String(versions.length),
4205
+ repair: "List every version returned by context.version({ modules })."
4206
+ });
4207
+ return versions.flatMap((version, index) => {
4208
+ const compiled = compiledVersionOf(version);
4209
+ if (compiled !== void 0) return [compiled];
4210
+ collector.add({
4211
+ code: "PH-DM-DECLARATION-INVALID",
4212
+ path: ["versions", index],
4213
+ message: "A family version must be a token returned by context.version.",
4214
+ expected: "an opaque version token",
4215
+ received: describeReceived(version),
4216
+ repair: "Pass context.version({ modules }) results; a version token is not registrable on its own."
4217
+ });
4218
+ return [];
4219
+ });
4220
+ }
4221
+ function checkFamilyVersions(collector, versions) {
4222
+ const first = versions.at(0);
4223
+ if (first === void 0) return;
4224
+ const firstModel = canonicalJson(first.definition.model);
4225
+ versions.forEach((version, index) => {
4226
+ const path = ["versions", index];
4227
+ if (version.config.id !== first.config.id) {
4228
+ collector.add({
4229
+ code: "PH-DM-DECLARATION-INVALID",
4230
+ path: [...path, "documentType"],
4231
+ message: "Every version of a family must use one document type.",
4232
+ expected: first.config.id,
4233
+ received: version.config.id,
4234
+ repair: "Compose only the versions declared with the same model id."
4235
+ });
4236
+ return;
4237
+ }
4238
+ const model = canonicalJson(version.definition.model);
4239
+ if (model !== firstModel) collector.add({
4240
+ code: "PH-DM-DECLARATION-INVALID",
4241
+ path: [...path, "model"],
4242
+ message: "Family model metadata must be identical across versions, because the stored document model carries one copy of it.",
4243
+ expected: firstModel,
4244
+ received: model,
4245
+ repair: "Use the same name, description, extension, and author in every version of the family."
4246
+ });
4247
+ const previous = versions[index - 1];
4248
+ if (index === 0 || version.config.version === previous.config.version + 1) return;
4249
+ collector.add({
4250
+ code: "PH-DM-DECLARATION-INVALID",
4251
+ path: [...path, "version"],
4252
+ message: "Family versions must be unique, contiguous, and in ascending order, so the last entry is the latest.",
4253
+ expected: String(previous.config.version + 1),
4254
+ received: String(version.config.version),
4255
+ repair: "List every consecutive version once, in ascending order."
4256
+ });
4257
+ });
4258
+ }
4259
+ const MANIFEST_KEYS = [
4260
+ "documentType",
4261
+ "latestVersion",
4262
+ "supportedVersions",
4263
+ "upgrades"
4264
+ ];
4265
+ const TRANSITION_KEYS = [
4266
+ "toVersion",
4267
+ "upgradeReducer",
4268
+ "description"
4269
+ ];
4270
+ function numberText(value) {
4271
+ return typeof value === "number" ? String(value) : describeReceived(value);
4272
+ }
4273
+ function checkUpgradeManifest(collector, value, versions) {
4274
+ const path = ["upgradeManifest"];
4275
+ if (value === void 0) {
4276
+ collector.add({
4277
+ code: "PH-DM-DECLARATION-INVALID",
4278
+ path,
4279
+ message: "A document-model family requires its upgrade manifest.",
4280
+ expected: "the manifest exported by upgrades/upgrade-manifest.ts",
4281
+ received: "absent",
4282
+ repair: "Pass the manifest that lists every version and the upgrade into each one after the first."
4283
+ });
4284
+ return;
4285
+ }
4286
+ const manifest = take(collector, snapshotRecord(value, MANIFEST_KEYS, path), MANIFEST_KEYS);
4287
+ const first = versions.at(0);
4288
+ if (manifest === void 0 || first === void 0) return void 0;
4289
+ const numbers = versions.map((version) => version.config.version);
4290
+ if (manifest.documentType !== first.config.id) collector.add({
4291
+ code: "PH-DM-DECLARATION-INVALID",
4292
+ path: [...path, "documentType"],
4293
+ message: "The upgrade manifest names a different document type.",
4294
+ expected: first.config.id,
4295
+ received: typeof manifest.documentType === "string" ? manifest.documentType : describeReceived(manifest.documentType),
4296
+ repair: "Use the id every version of the family declares."
4297
+ });
4298
+ const supported = snapshotArray(manifest.supportedVersions, [...path, "supportedVersions"]);
4299
+ if (!(supported.ok && supported.value.length === numbers.length && supported.value.every((version, index) => version === numbers[index]))) collector.add({
4300
+ code: "PH-DM-DECLARATION-INVALID",
4301
+ path: [...path, "supportedVersions"],
4302
+ message: "The upgrade manifest and the family list different versions.",
4303
+ expected: JSON.stringify(numbers),
4304
+ received: supported.ok ? JSON.stringify(supported.value) : rejectionReceived(supported),
4305
+ repair: "List every version the family composes, in ascending order."
4306
+ });
4307
+ if (manifest.latestVersion !== numbers.at(-1)) collector.add({
4308
+ code: "PH-DM-DECLARATION-INVALID",
4309
+ path: [...path, "latestVersion"],
4310
+ message: "The upgrade manifest's latest version is not the family's last.",
4311
+ expected: String(numbers.at(-1)),
4312
+ received: numberText(manifest.latestVersion),
4313
+ repair: "Set latestVersion to the last entry of supportedVersions."
4314
+ });
4315
+ const upgradesPath = [...path, "upgrades"];
4316
+ const upgrades = take(collector, snapshotRecord(manifest.upgrades, void 0, upgradesPath), []);
4317
+ if (upgrades === void 0) return void 0;
4318
+ const expected = numbers.slice(1).map((version) => `v${version}`);
4319
+ const actual = Object.keys(upgrades).sort(compareCodeUnits);
4320
+ if (expected.length !== actual.length || expected.some((key) => !actual.includes(key))) collector.add({
4321
+ code: "PH-DM-DECLARATION-INVALID",
4322
+ path: upgradesPath,
4323
+ message: "A family needs exactly one upgrade transition for every version after the first.",
4324
+ expected: expected.join(", ") || "no transitions",
4325
+ received: actual.join(", ") || "no transitions",
4326
+ repair: "Key each transition by the version it upgrades to, as upgrades: { v2 }."
4327
+ });
4328
+ const checked = {};
4329
+ for (const version of numbers.slice(1)) {
4330
+ const key = `v${version}`;
4331
+ if (!Object.hasOwn(upgrades, key)) continue;
4332
+ const transitionPath = [...upgradesPath, key];
4333
+ const transition = take(collector, snapshotRecord(upgrades[key], TRANSITION_KEYS, transitionPath), TRANSITION_KEYS);
4334
+ if (transition === void 0) continue;
4335
+ if (transition.toVersion !== version) collector.add({
4336
+ code: "PH-DM-DECLARATION-INVALID",
4337
+ path: [...transitionPath, "toVersion"],
4338
+ message: `The transition under ${key} must target version ${version}.`,
4339
+ expected: String(version),
4340
+ received: numberText(transition.toVersion),
4341
+ repair: "Set toVersion to the version the transition is keyed by."
4342
+ });
4343
+ if (typeof transition.upgradeReducer !== "function") collector.add({
4344
+ code: "PH-DM-DECLARATION-INVALID",
4345
+ path: [...transitionPath, "upgradeReducer"],
4346
+ message: "An upgrade transition must carry a callable upgradeReducer.",
4347
+ expected: "a function",
4348
+ received: transition.upgradeReducer === void 0 ? "absent" : describeReceived(transition.upgradeReducer),
4349
+ repair: "Write the upgrade by hand: it rewrites both state and initialState."
4350
+ });
4351
+ const description = optionalString(collector, transition.description, [...transitionPath, "description"]);
4352
+ checked[key] = {
4353
+ toVersion: version,
4354
+ upgradeReducer: transition.upgradeReducer,
4355
+ ...typeof description === "string" ? { description } : {}
4356
+ };
4357
+ }
4358
+ return {
4359
+ documentType: first.config.id,
4360
+ latestVersion: numbers[numbers.length - 1],
4361
+ supportedVersions: numbers,
4362
+ upgrades: checked
4363
+ };
4364
+ }
4365
+ function copyUpgradeManifest(manifest) {
4366
+ const upgrades = {};
4367
+ for (const [key, transition] of Object.entries(manifest.upgrades)) upgrades[key] = { ...transition };
4368
+ return {
4369
+ documentType: manifest.documentType,
4370
+ latestVersion: manifest.latestVersion,
4371
+ supportedVersions: [...manifest.supportedVersions],
4372
+ upgrades
4373
+ };
4374
+ }
4375
+ /**
4376
+ * @experimental Composes the versions of one document type with the upgrade
4377
+ * manifest that moves a document between them. `materialize` turns the
4378
+ * result into one module per version.
4379
+ */
4380
+ function defineDocumentModelFamily(config) {
4381
+ const collector = modelCollector();
4382
+ const declaration = take(collector, snapshotRecord(config, ["versions", "upgradeManifest"], []), ["versions", "upgradeManifest"]);
4383
+ collector.throwIfFailed();
4384
+ const versions = compiledVersions(collector, declaration?.versions);
4385
+ collector.throwIfFailed();
4386
+ checkFamilyVersions(collector, versions);
4387
+ const upgradeManifest = checkUpgradeManifest(collector, declaration?.upgradeManifest, versions);
4388
+ collector.throwIfFailed();
4389
+ const first = versions.at(0);
4390
+ if (first === void 0 || upgradeManifest === void 0) throw new TypeError("A document-model family requires at least one version.");
4391
+ const token = {
4392
+ kind: "powerhouse.document-model-family",
4393
+ documentType: first.config.id
4394
+ };
4395
+ familyDeclarations.set(token, {
4396
+ versions,
4397
+ upgradeManifest
4398
+ });
4399
+ return token;
4400
+ }
4401
+ //#endregion
4402
+ //#region src/definition/runtime/materialize.ts
4403
+ function cloneJson(value) {
4404
+ return JSON.parse(JSON.stringify(value));
4405
+ }
4406
+ function createOperationErrorClass({ className, code }) {
4407
+ return { [className]: class extends Error {
4408
+ errorCode = code;
4409
+ constructor(message = className) {
4410
+ super(message);
4411
+ }
4412
+ } }[className];
4413
+ }
4414
+ function operationErrorClasses(module) {
4415
+ const classes = /* @__PURE__ */ new Map();
4416
+ return new Map(module.operations.map((operation) => [operation, Object.freeze(Object.fromEntries(operation.errorClasses.map((errorClass) => {
4417
+ const ErrorClass = classes.get(errorClass.className) ?? createOperationErrorClass(errorClass);
4418
+ classes.set(errorClass.className, ErrorClass);
4419
+ return [errorClass.key, ErrorClass];
4420
+ })))]));
4421
+ }
4422
+ function createActionCreator(operation) {
4423
+ const validator = () => operation.inputValidator;
4424
+ const create = (input) => createAction(operation.actionType, { ...input }, void 0, validator, operation.scope);
4425
+ return operation.input.fields.length === 0 ? (input = {}) => create(input) : create;
4426
+ }
4427
+ function createRuntimeBehavior(version) {
4428
+ const dispatchTable = /* @__PURE__ */ new Map();
4429
+ const modelActions = {};
4430
+ for (const module of version.modules) {
4431
+ const errors = operationErrorClasses(module);
4432
+ for (const operation of module.operations) {
4433
+ dispatchTable.set(operation.actionType, {
4434
+ operation,
4435
+ errors: errors.get(operation) ?? {}
4436
+ });
4437
+ modelActions[operation.creatorKey] = createActionCreator(operation);
4438
+ }
4439
+ }
4440
+ const stateReducer = (state, action, dispatch) => {
4441
+ if (isDocumentAction(action)) return state;
4442
+ const entry = dispatchTable.get(action.type);
4443
+ if (entry === void 0) return state;
4444
+ const { operation } = entry;
4445
+ const parsed = operation.inputValidator.parse(action.input);
4446
+ const reduced = operation.parsesInput ? {
4447
+ ...action,
4448
+ input: parsed
4449
+ } : action;
4450
+ const reduce = operation.declaration.reduce;
4451
+ reduce(state[operation.scope], reduced.input, {
4452
+ errors: entry.errors,
4453
+ action: reduced,
4454
+ dispatch
4455
+ });
4456
+ };
4457
+ return {
4458
+ reducer: createReducer(stateReducer),
4459
+ actions: {
4460
+ ...baseActions,
4461
+ ...modelActions
4462
+ }
4463
+ };
4464
+ }
4465
+ function storedState(state) {
4466
+ return {
4467
+ schema: state.materialized.schema,
4468
+ initialValue: state.materialized.initialValue,
4469
+ examples: state.materialized.examples.map(({ id, value }) => ({
4470
+ id,
4471
+ value
4472
+ }))
4473
+ };
4474
+ }
4475
+ function storedSpecification(version) {
4476
+ const { specification } = version;
4477
+ return {
4478
+ version: specification.version,
4479
+ state: {
4480
+ global: storedState(specification.state.global),
4481
+ local: storedState(specification.state.local)
4482
+ },
4483
+ modules: version.modules.map(({ definition, operations }) => ({
4484
+ id: definition.id,
4485
+ name: definition.name,
4486
+ description: definition.description,
4487
+ operations: operations.map((operation) => ({
4488
+ id: operation.definition.id,
4489
+ name: operation.definition.name,
4490
+ description: operation.definition.description,
4491
+ schema: operation.inputSchema,
4492
+ template: operation.definition.template,
4493
+ reducer: operation.definition.reducer,
4494
+ errors: operation.definition.errors.map((error) => ({
4495
+ id: error.id,
4496
+ code: error.code,
4497
+ name: error.name,
4498
+ description: error.description,
4499
+ template: error.template
4500
+ })),
4501
+ examples: operation.definition.examples.map(({ id, value }) => ({
4502
+ id,
4503
+ value
4504
+ })),
4505
+ scope: operation.definition.scope
4506
+ }))
4507
+ })),
4508
+ changeLog: [...specification.changeLog]
4509
+ };
4510
+ }
4511
+ function storedGlobalState(version, versions) {
4512
+ const { model } = version.definition;
4513
+ return {
4514
+ id: model.documentType,
4515
+ name: model.name,
4516
+ author: { ...model.author },
4517
+ extension: model.extension,
4518
+ description: model.description,
4519
+ specifications: versions.map(storedSpecification)
4520
+ };
4521
+ }
4522
+ function stampedVersion(state) {
4523
+ const documentScope = typeof state === "object" && state !== null ? state.document : void 0;
4524
+ const version = typeof documentScope === "object" && documentScope !== null ? documentScope.version : void 0;
4525
+ return normalizeDocumentModelVersion(typeof version === "number" ? version : void 0);
4526
+ }
4527
+ function createRuntimeSchemas(version, known) {
4528
+ const header = BaseDocumentHeaderSchema.extend({ documentType: z.literal(version.config.id) });
4529
+ const states = /* @__PURE__ */ new Map();
4530
+ const documents = /* @__PURE__ */ new Map();
4531
+ for (const candidate of known) {
4532
+ const state = BaseDocumentStateSchema.extend({ global: candidate.config.scopes.global.root.validator });
4533
+ states.set(candidate.config.version, state);
4534
+ documents.set(candidate.config.version, z.object({
4535
+ header,
4536
+ state,
4537
+ initialState: state
4538
+ }));
4539
+ }
4540
+ const ownState = states.get(version.config.version);
4541
+ const ownDocument = documents.get(version.config.version);
4542
+ return {
4543
+ state: (state) => states.get(stampedVersion(state)) ?? ownState,
4544
+ document: (document) => documents.get(stampedVersion(typeof document === "object" && document !== null ? document.state : void 0)) ?? ownDocument
4545
+ };
4546
+ }
4547
+ function materializeVersion(version, versions, behaviors, upgradeManifest) {
4548
+ const known = versions.filter((candidate) => candidate.config.version <= version.config.version);
4549
+ const schemas = createRuntimeSchemas(version, known);
4550
+ const behavior = behaviors.get(version);
4551
+ const initialGlobalState = version.initialGlobalState;
4552
+ const initialLocalState = version.initialLocalState;
4553
+ const reducers = Object.fromEntries(known.map((candidate) => [candidate.config.version, behaviors.get(candidate).reducer]));
4554
+ const utils = {
4555
+ fileExtension: version.config.extension,
4556
+ createState(state) {
4557
+ const scoped = state;
4558
+ return {
4559
+ ...createBaseState(scoped?.auth, {
4560
+ version: version.config.version,
4561
+ ...scoped?.document
4562
+ }),
4563
+ global: {
4564
+ ...cloneJson(initialGlobalState),
4565
+ ...scoped?.global
4566
+ },
4567
+ local: {
4568
+ ...cloneJson(initialLocalState),
4569
+ ...scoped?.local
4570
+ }
4571
+ };
4572
+ },
4573
+ createDocument(state) {
4574
+ return baseCreateDocument(utils.createState, state, version.config.id);
4575
+ },
4576
+ saveToFileHandle(document, input) {
4577
+ return baseSaveToFileHandle(document, input);
4578
+ },
4579
+ loadFromInput(input) {
4580
+ return baseLoadFromInputVersioned(input, {
4581
+ reducers,
4582
+ upgradeManifest
4583
+ });
4584
+ },
4585
+ isStateOfType(state) {
4586
+ return schemas.state(state).safeParse(state).success;
4587
+ },
4588
+ assertIsStateOfType(state) {
4589
+ schemas.state(state).parse(state);
4590
+ },
4591
+ isDocumentOfType(document) {
4592
+ return schemas.document(document).safeParse(document).success;
4593
+ },
4594
+ assertIsDocumentOfType(document) {
4595
+ schemas.document(document).parse(document);
4596
+ }
4597
+ };
4598
+ const definition = cloneJson({
4599
+ ...version.definition,
4600
+ specifications: versions.map((candidate) => candidate.specification)
4601
+ });
4602
+ return {
4603
+ version: version.config.version,
4604
+ reducer: behavior.reducer,
4605
+ actions: behavior.actions,
4606
+ utils,
4607
+ documentModel: createState(defaultBaseState(), cloneJson(storedGlobalState(version, versions))),
4608
+ definition
4609
+ };
4610
+ }
4611
+ function materializeFamily(versions, upgradeManifest) {
4612
+ const behaviors = new Map(versions.map((version) => [version, createRuntimeBehavior(version)]));
4613
+ const modules = versions.map((version) => materializeVersion(version, versions, behaviors, upgradeManifest));
4614
+ return {
4615
+ modules,
4616
+ upgradeManifest,
4617
+ at(number) {
4618
+ const module = modules.find((candidate) => candidate.version === number);
4619
+ if (module === void 0) throw new RangeError(`Document model ${upgradeManifest.documentType} has no version ${String(number)}; it publishes ${versions.map((version) => version.config.version).join(", ")}.`);
4620
+ return module;
4621
+ }
4622
+ };
4623
+ }
4624
+ function refuseDefinition(value) {
4625
+ return modelDiagnostics.fail({
4626
+ code: "PH-DM-DECLARATION-INVALID",
4627
+ path: [],
4628
+ message: "materialize takes a definition returned by context.version or defineDocumentModelFamily.",
4629
+ expected: "a version or family definition",
4630
+ received: describeReceived(value),
4631
+ repair: "Pass the value context.version({ modules }) or defineDocumentModelFamily(...) returned."
4632
+ });
4633
+ }
4634
+ function materialize(definition) {
4635
+ const version = compiledVersionOf(definition);
4636
+ if (version !== void 0) {
4637
+ const { id, version: number } = version.config;
4638
+ return materializeFamily([version], {
4639
+ documentType: id,
4640
+ latestVersion: number,
4641
+ supportedVersions: [number],
4642
+ upgrades: {}
4643
+ }).modules[0];
4644
+ }
4645
+ const family = familyDeclarationOf(definition);
4646
+ if (family === void 0) return refuseDefinition(definition);
4647
+ return materializeFamily(family.versions, copyUpgradeManifest(family.upgradeManifest));
4648
+ }
222
4649
  //#endregion
223
- export { ConsoleLogger, DocumentModelController, PHDocumentController, assertIsDocumentOfType, assertIsStateOfType, childLogger, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, isDocumentOfType, isStateOfType, logger, setErrorHandler, setLogLevel };
4650
+ export { ConsoleLogger, DefinitionError, DocumentModelController, PHDocumentController, assertIsDocumentOfType, assertIsStateOfType, childLogger, defineDocumentModel, defineDocumentModelFamily, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, isDocumentOfType, isStateOfType, logger, materialize, ph, setErrorHandler, setLogLevel };
224
4651
 
225
4652
  //# sourceMappingURL=index.js.map