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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2655 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
3
+ import { z } from "zod";
4
+ import { fileURLToPath } from "node:url";
5
+ import { DEFAULT_AUTHORING_MODE, parseDefinitionSourcesConfig } from "@powerhousedao/shared/clis/definition-sources";
6
+ //#region src/definition/kernel/hashes.ts
7
+ function rotateRight(value, shift) {
8
+ return (value >>> shift | value << 32 - shift) >>> 0;
9
+ }
10
+ const SHA256_CONSTANTS = new Uint32Array([
11
+ 1116352408,
12
+ 1899447441,
13
+ 3049323471,
14
+ 3921009573,
15
+ 961987163,
16
+ 1508970993,
17
+ 2453635748,
18
+ 2870763221,
19
+ 3624381080,
20
+ 310598401,
21
+ 607225278,
22
+ 1426881987,
23
+ 1925078388,
24
+ 2162078206,
25
+ 2614888103,
26
+ 3248222580,
27
+ 3835390401,
28
+ 4022224774,
29
+ 264347078,
30
+ 604807628,
31
+ 770255983,
32
+ 1249150122,
33
+ 1555081692,
34
+ 1996064986,
35
+ 2554220882,
36
+ 2821834349,
37
+ 2952996808,
38
+ 3210313671,
39
+ 3336571891,
40
+ 3584528711,
41
+ 113926993,
42
+ 338241895,
43
+ 666307205,
44
+ 773529912,
45
+ 1294757372,
46
+ 1396182291,
47
+ 1695183700,
48
+ 1986661051,
49
+ 2177026350,
50
+ 2456956037,
51
+ 2730485921,
52
+ 2820302411,
53
+ 3259730800,
54
+ 3345764771,
55
+ 3516065817,
56
+ 3600352804,
57
+ 4094571909,
58
+ 275423344,
59
+ 430227734,
60
+ 506948616,
61
+ 659060556,
62
+ 883997877,
63
+ 958139571,
64
+ 1322822218,
65
+ 1537002063,
66
+ 1747873779,
67
+ 1955562222,
68
+ 2024104815,
69
+ 2227730452,
70
+ 2361852424,
71
+ 2428436474,
72
+ 2756734187,
73
+ 3204031479,
74
+ 3329325298
75
+ ]);
76
+ function sha256(value) {
77
+ const bytes = new TextEncoder().encode(value);
78
+ const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;
79
+ const input = new Uint8Array(paddedLength);
80
+ input.set(bytes);
81
+ input[bytes.length] = 128;
82
+ const view = new DataView(input.buffer);
83
+ const bitLength = BigInt(bytes.length) * 8n;
84
+ view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);
85
+ view.setUint32(paddedLength - 4, Number(bitLength & 4294967295n), false);
86
+ const state = new Uint32Array([
87
+ 1779033703,
88
+ 3144134277,
89
+ 1013904242,
90
+ 2773480762,
91
+ 1359893119,
92
+ 2600822924,
93
+ 528734635,
94
+ 1541459225
95
+ ]);
96
+ const words = /* @__PURE__ */ new Uint32Array(64);
97
+ for (let offset = 0; offset < paddedLength; offset += 64) {
98
+ for (let index = 0; index < 16; index += 1) words[index] = view.getUint32(offset + index * 4, false);
99
+ for (let index = 16; index < 64; index += 1) {
100
+ const previous15 = words[index - 15];
101
+ const previous2 = words[index - 2];
102
+ const sigma0 = rotateRight(previous15, 7) ^ rotateRight(previous15, 18) ^ previous15 >>> 3;
103
+ const sigma1 = rotateRight(previous2, 17) ^ rotateRight(previous2, 19) ^ previous2 >>> 10;
104
+ words[index] = words[index - 16] + sigma0 + words[index - 7] + sigma1 >>> 0;
105
+ }
106
+ let a = state[0];
107
+ let b = state[1];
108
+ let c = state[2];
109
+ let d = state[3];
110
+ let e = state[4];
111
+ let f = state[5];
112
+ let g = state[6];
113
+ let h = state[7];
114
+ for (let index = 0; index < 64; index += 1) {
115
+ const sigma1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
116
+ const choice = e & f ^ ~e & g;
117
+ const temporary1 = h + sigma1 + choice + SHA256_CONSTANTS[index] + words[index] >>> 0;
118
+ const temporary2 = (rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
119
+ h = g;
120
+ g = f;
121
+ f = e;
122
+ e = d + temporary1 >>> 0;
123
+ d = c;
124
+ c = b;
125
+ b = a;
126
+ a = temporary1 + temporary2 >>> 0;
127
+ }
128
+ state[0] = state[0] + a >>> 0;
129
+ state[1] = state[1] + b >>> 0;
130
+ state[2] = state[2] + c >>> 0;
131
+ state[3] = state[3] + d >>> 0;
132
+ state[4] = state[4] + e >>> 0;
133
+ state[5] = state[5] + f >>> 0;
134
+ state[6] = state[6] + g >>> 0;
135
+ state[7] = state[7] + h >>> 0;
136
+ }
137
+ return `sha256:${[...state].map((word) => word.toString(16).padStart(8, "0")).join("")}`;
138
+ }
139
+ //#endregion
140
+ //#region src/definition/kernel/primitives.ts
141
+ function memberPath(parent, key) {
142
+ if (typeof key === "number") return `${parent}[${key}]`;
143
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
144
+ }
145
+ function encodeProperty(descriptor, path, ancestors) {
146
+ if (!("value" in descriptor)) throw new TypeError(`${path} must be a data property, not an accessor.`);
147
+ if (descriptor.enumerable !== true) throw new TypeError(`${path} must be enumerable.`);
148
+ return encode(descriptor.value, path, ancestors);
149
+ }
150
+ function encodeArray(value, path, ancestors) {
151
+ if (Object.getPrototypeOf(value) !== Array.prototype) throw new TypeError(`${path} must be a plain array.`);
152
+ for (const key of Reflect.ownKeys(value)) {
153
+ if (key === "length") continue;
154
+ if (typeof key === "symbol") throw new TypeError(`${path} must not have symbol keys.`);
155
+ 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)}.`);
156
+ }
157
+ const members = [];
158
+ for (let index = 0; index < value.length; index += 1) {
159
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
160
+ if (descriptor === void 0) throw new TypeError(`${memberPath(path, index)} must not be an array hole.`);
161
+ members.push(encodeProperty(descriptor, memberPath(path, index), ancestors));
162
+ }
163
+ return `[${members.join(",")}]`;
164
+ }
165
+ function encodeObject(value, path, ancestors) {
166
+ const prototype = Object.getPrototypeOf(value);
167
+ if (prototype !== Object.prototype && prototype !== null) throw new TypeError(`${path} must be a plain object.`);
168
+ const keys = [];
169
+ for (const key of Reflect.ownKeys(value)) {
170
+ if (typeof key === "symbol") throw new TypeError(`${path} must not have symbol keys.`);
171
+ keys.push(key);
172
+ }
173
+ keys.sort(compareCodeUnits);
174
+ const members = [];
175
+ for (const key of keys) {
176
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
177
+ if (descriptor === void 0) throw new TypeError(`${memberPath(path, key)} must be an own property.`);
178
+ members.push(`${JSON.stringify(key)}:${encodeProperty(descriptor, memberPath(path, key), ancestors)}`);
179
+ }
180
+ return `{${members.join(",")}}`;
181
+ }
182
+ function encode(value, path, ancestors) {
183
+ switch (typeof value) {
184
+ case "string":
185
+ case "boolean": return JSON.stringify(value);
186
+ case "number":
187
+ if (Number.isFinite(value)) return JSON.stringify(value);
188
+ throw new TypeError(`${path} must be a finite number.`);
189
+ case "object": {
190
+ if (value === null) return "null";
191
+ if (ancestors.has(value)) throw new TypeError(`${path} must not contain a cycle.`);
192
+ ancestors.add(value);
193
+ const encoded = Array.isArray(value) ? encodeArray(value, path, ancestors) : encodeObject(value, path, ancestors);
194
+ ancestors.delete(value);
195
+ return encoded;
196
+ }
197
+ default: throw new TypeError(`${path} must be a JSON value, received ${typeof value}.`);
198
+ }
199
+ }
200
+ function canonicalJson(value) {
201
+ return encode(value, "$", /* @__PURE__ */ new Set());
202
+ }
203
+ function canonicalDigest(value) {
204
+ return sha256(canonicalJson(value));
205
+ }
206
+ function compareCodeUnits(a, b) {
207
+ return a < b ? -1 : a > b ? 1 : 0;
208
+ }
209
+ function isGraphQLName(value) {
210
+ return typeof value === "string" && /^[_A-Za-z][_0-9A-Za-z]*$/.test(value);
211
+ }
212
+ function isNFC(value) {
213
+ return value.normalize("NFC") === value;
214
+ }
215
+ //#endregion
216
+ //#region src/definition/kernel/diagnostics.ts
217
+ const MAX_SUMMARY_CODE_POINTS = 512;
218
+ function capCodePoints(value, max = MAX_SUMMARY_CODE_POINTS) {
219
+ const points = [...value];
220
+ const limit = Math.max(0, max);
221
+ return points.length <= limit ? value : points.slice(0, limit).join("");
222
+ }
223
+ function copySource(source) {
224
+ return {
225
+ specifier: source.specifier,
226
+ ...source.exportPath !== void 0 && { exportPath: [...source.exportPath] }
227
+ };
228
+ }
229
+ function copyDefinitionRef(definition) {
230
+ return {
231
+ kind: definition.kind,
232
+ key: definition.key,
233
+ ...definition.version !== void 0 && { version: definition.version }
234
+ };
235
+ }
236
+ function createDiagnostic(input, { severity, phase }) {
237
+ return {
238
+ code: input.code,
239
+ severity,
240
+ phase,
241
+ ...input.source !== void 0 && { source: copySource(input.source) },
242
+ ...input.definition !== void 0 && { definition: copyDefinitionRef(input.definition) },
243
+ path: [...input.path],
244
+ message: input.message,
245
+ ...input.expected !== void 0 && { expected: capCodePoints(input.expected) },
246
+ ...input.received !== void 0 && { received: capCodePoints(input.received) },
247
+ repair: input.repair,
248
+ ...input.related !== void 0 && { related: input.related.map((location) => ({
249
+ ...location.source !== void 0 && { source: copySource(location.source) },
250
+ path: [...location.path],
251
+ message: location.message
252
+ })) }
253
+ };
254
+ }
255
+ function describeReceived(value) {
256
+ if (value === null) return "null";
257
+ try {
258
+ return Array.isArray(value) ? "array" : typeof value;
259
+ } catch {
260
+ return "inspection-failed";
261
+ }
262
+ }
263
+ /**
264
+ * A layer's catalog: its own codes plus the codes of the catalog below it,
265
+ * which already holds every lower layer's codes. A code keeps the meaning its
266
+ * owning layer gave it, so an own code the lower catalog declares is refused.
267
+ */
268
+ function defineDiagnosticCatalog(own, lower) {
269
+ const lowerCodes = lower?.codes ?? {};
270
+ const ownEntries = Object.entries(own).map(([code, entry]) => [code, Object.freeze({ ...entry })]);
271
+ const redefined = ownEntries.map(([code]) => code).filter((code) => Object.hasOwn(lowerCodes, code));
272
+ if (redefined.length > 0) throw new TypeError(`Diagnostic code ${redefined.join(", ")} is already declared by a lower layer.`);
273
+ const codes = Object.freeze({
274
+ ...lowerCodes,
275
+ ...Object.fromEntries(ownEntries)
276
+ });
277
+ const create = (input) => createDiagnostic(input, codes[input.code]);
278
+ return Object.freeze({
279
+ codes,
280
+ create,
281
+ fail(input) {
282
+ throw new DefinitionError([create(input)]);
283
+ }
284
+ });
285
+ }
286
+ function compareNumbers(a, b) {
287
+ return a < b ? -1 : a > b ? 1 : 0;
288
+ }
289
+ function compareOptional(a, b, compare) {
290
+ if (a === void 0) return b === void 0 ? 0 : -1;
291
+ if (b === void 0) return 1;
292
+ return compare(a, b);
293
+ }
294
+ function compareLists(a, b, compare) {
295
+ const shared = Math.min(a.length, b.length);
296
+ for (let index = 0; index < shared; index += 1) {
297
+ const result = compare(a[index], b[index]);
298
+ if (result !== 0) return result;
299
+ }
300
+ return compareNumbers(a.length, b.length);
301
+ }
302
+ function comparePathSegments(a, b) {
303
+ if (typeof a === "number") return typeof b === "number" ? compareNumbers(a, b) : -1;
304
+ if (typeof b === "number") return 1;
305
+ return compareCodeUnits(a, b);
306
+ }
307
+ function compareDefinitionPaths(a, b) {
308
+ return compareLists(a, b, comparePathSegments);
309
+ }
310
+ function compareSources(a, b) {
311
+ const specifier = compareCodeUnits(a.specifier, b.specifier);
312
+ if (specifier !== 0) return specifier;
313
+ return compareOptional(a.exportPath, b.exportPath, (x, y) => compareLists(x, y, compareCodeUnits));
314
+ }
315
+ function compareDefinitionRefs(a, b) {
316
+ const kind = compareCodeUnits(a.kind, b.kind);
317
+ if (kind !== 0) return kind;
318
+ const key = compareCodeUnits(a.key, b.key);
319
+ if (key !== 0) return key;
320
+ return compareOptional(a.version, b.version, compareNumbers);
321
+ }
322
+ function compareDefinitionDiagnostics(a, b) {
323
+ const source = compareOptional(a.source, b.source, compareSources);
324
+ if (source !== 0) return source;
325
+ const definition = compareOptional(a.definition, b.definition, compareDefinitionRefs);
326
+ if (definition !== 0) return definition;
327
+ const path = compareDefinitionPaths(a.path, b.path);
328
+ if (path !== 0) return path;
329
+ return compareCodeUnits(a.code, b.code);
330
+ }
331
+ function sortDefinitionDiagnostics(diagnostics) {
332
+ return [...diagnostics].sort(compareDefinitionDiagnostics);
333
+ }
334
+ function formatPointer(path) {
335
+ if (path.length === 0) return "(root)";
336
+ return path.map((segment) => `/${String(segment).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
337
+ }
338
+ function formatSource(source) {
339
+ if (source === void 0) return "(no source)";
340
+ const exportPath = source.exportPath ?? [];
341
+ return exportPath.length === 0 ? source.specifier : `${source.specifier}#${formatPointer(exportPath)}`;
342
+ }
343
+ function formatDefinitionRef(definition) {
344
+ if (definition === void 0) return "";
345
+ const version = definition.version === void 0 ? "" : `@${definition.version}`;
346
+ return ` ${definition.kind} ${definition.key}${version}`;
347
+ }
348
+ function oneLine(value) {
349
+ return value.replace(/\s+/g, " ");
350
+ }
351
+ /** @experimental One line: code, severity and phase, location, message, expected, received, related and repair. */
352
+ function formatDefinitionDiagnostic(diagnostic) {
353
+ const where = `${formatSource(diagnostic.source)}${formatDefinitionRef(diagnostic.definition)} ${formatPointer(diagnostic.path)}`;
354
+ const expected = diagnostic.expected === void 0 ? "" : ` Expected: ${oneLine(diagnostic.expected)}`;
355
+ const received = diagnostic.received === void 0 ? "" : ` Received: ${oneLine(diagnostic.received)}`;
356
+ const related = (diagnostic.related ?? []).map((location) => ` Related: ${formatSource(location.source)} ${formatPointer(location.path)}: ${oneLine(location.message)}`).join("");
357
+ return `${diagnostic.code} [${diagnostic.severity}/${diagnostic.phase}] ${where}: ${oneLine(diagnostic.message)}${expected}${received}${related} Repair: ${oneLine(diagnostic.repair)}`;
358
+ }
359
+ /**
360
+ * @experimental Thrown when a code-first declaration is refused. `diagnostics`
361
+ * holds every problem found, sorted, each with its code, path and repair.
362
+ */
363
+ var DefinitionError = class extends Error {
364
+ diagnostics;
365
+ constructor(diagnostics) {
366
+ if (diagnostics.length === 0) throw new TypeError("DefinitionError requires at least one diagnostic.");
367
+ const sorted = sortDefinitionDiagnostics(diagnostics);
368
+ const noun = sorted.length === 1 ? "diagnostic" : "diagnostics";
369
+ super([`Definition failed with ${sorted.length} ${noun}:`, ...sorted.map(formatDefinitionDiagnostic)].join("\n"));
370
+ this.name = "DefinitionError";
371
+ this.diagnostics = sorted;
372
+ }
373
+ };
374
+ //#endregion
375
+ //#region src/scalars/types.ts
376
+ const SCALAR_DEFINITION = Symbol.for("powerhouse.scalar-definition");
377
+ //#endregion
378
+ //#region src/scalars/define-catalog-scalar.ts
379
+ function defineCatalogScalar(input) {
380
+ return Object.freeze({
381
+ ...input,
382
+ [SCALAR_DEFINITION]: 1
383
+ });
384
+ }
385
+ //#endregion
386
+ //#region src/scalars/scalar-literal.ts
387
+ var ScalarLiteralVariableError = class extends TypeError {
388
+ constructor(name) {
389
+ super(`Variable $${name} cannot appear inside a scalar literal; GraphQL resolves variables before literal coercion.`);
390
+ this.name = "ScalarLiteralVariableError";
391
+ }
392
+ };
393
+ /** Converts a literal node to its runtime value. A variable anywhere throws. */
394
+ function scalarLiteralValue(node) {
395
+ switch (node.kind) {
396
+ case "string":
397
+ case "enum": return node.value;
398
+ case "int":
399
+ case "float": return Number(node.value);
400
+ case "boolean": return node.value;
401
+ case "null": return null;
402
+ case "list": return node.values.map(scalarLiteralValue);
403
+ case "object": return Object.fromEntries(node.fields.map((field) => [field.name, scalarLiteralValue(field.value)]));
404
+ case "variable": throw new ScalarLiteralVariableError(node.name);
405
+ }
406
+ }
407
+ function objectFields(node) {
408
+ if (node.kind !== "object") throw new TypeError("Value must be an object literal.");
409
+ return new Map(node.fields.map((field) => [field.name, field.value]));
410
+ }
411
+ function literalString(node, field) {
412
+ if (node?.kind !== "string") throw new TypeError(`${field} must be a string literal.`);
413
+ return node.value;
414
+ }
415
+ function floatOnlyNumber(node, field) {
416
+ if (node?.kind !== "float") throw new TypeError(`${field} must be a float literal.`);
417
+ return Number.parseFloat(node.value);
418
+ }
419
+ //#endregion
420
+ //#region src/scalars/declarations/unknown.ts
421
+ const unknownScalar = defineCatalogScalar({
422
+ name: "Unknown",
423
+ typescriptType: "unknown",
424
+ zodSource: "z.unknown()",
425
+ schema: z.unknown(),
426
+ representation: "opaque",
427
+ coercion: {
428
+ parseValue: (value) => value,
429
+ parseLiteral: scalarLiteralValue,
430
+ serialize: (value) => value
431
+ }
432
+ });
433
+ //#endregion
434
+ //#region src/scalars/declarations/date-time.ts
435
+ const dateTimeScalar = defineCatalogScalar({
436
+ example: "2024-01-01T00:00:00.000Z",
437
+ name: "DateTime",
438
+ typescriptType: "string",
439
+ zodSource: "z.iso.datetime()",
440
+ schema: z.iso.datetime(),
441
+ representation: "string"
442
+ });
443
+ //#endregion
444
+ //#region src/scalars/pattern.ts
445
+ function matchesScalarPattern(pattern, value) {
446
+ return Reflect.apply(pattern.test.bind(pattern), void 0, [value]) === true;
447
+ }
448
+ //#endregion
449
+ //#region src/scalars/declarations/address.ts
450
+ const addressScalar = defineCatalogScalar({
451
+ example: "eip155:0x0000000000000000000000000000000000000000",
452
+ name: "Address",
453
+ typescriptType: "`${string}:0x${string}`",
454
+ zodSource: "z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))",
455
+ schema: z.custom((val) => matchesScalarPattern(/^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/, val)),
456
+ representation: "string"
457
+ });
458
+ //#endregion
459
+ //#region src/scalars/declarations/attachment-ref.ts
460
+ const attachmentRefScalar = defineCatalogScalar({
461
+ example: "attachment://v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
462
+ name: "AttachmentRef",
463
+ typescriptType: "`attachment://v${number}:${string}`",
464
+ zodSource: "z.custom<`attachment://v${number}:${string}`>((val) => /^attachment:\\/\\/v\\d+:.+$/.test(val as string))",
465
+ schema: z.custom((val) => matchesScalarPattern(/^attachment:\/\/v\d+:.+$/, val)),
466
+ representation: "string"
467
+ });
468
+ //#endregion
469
+ //#region src/scalars/coercion.ts
470
+ /** Runs `schema` on every path; `readLiteral` turns an inline literal into its value first. */
471
+ function validatingCoercion(schema, readLiteral) {
472
+ const parse = (value) => schema.parse(value);
473
+ return {
474
+ parseValue: parse,
475
+ parseLiteral: (node) => parse(readLiteral(node)),
476
+ serialize: parse
477
+ };
478
+ }
479
+ //#endregion
480
+ //#region src/scalars/declarations/amounts.ts
481
+ function floatAmountCoercion(schema) {
482
+ return validatingCoercion(schema, (node) => floatOnlyNumber(node, "value"));
483
+ }
484
+ function stringAmountCoercion(schema) {
485
+ return validatingCoercion(schema, (node) => {
486
+ const fields = objectFields(node);
487
+ const value = literalString(fields.get("value"), "value");
488
+ if (!/^\d+(\.\d+)?$/.test(value)) throw new TypeError("value must be a numeric string.");
489
+ return {
490
+ unit: literalString(fields.get("unit"), "unit"),
491
+ value
492
+ };
493
+ });
494
+ }
495
+ //#endregion
496
+ //#region src/scalars/declarations/amount-tokens.ts
497
+ const schema$6 = z.number();
498
+ const amountTokensScalar = defineCatalogScalar({
499
+ name: "Amount_Tokens",
500
+ typescriptType: "number",
501
+ zodSource: "z.number()",
502
+ schema: schema$6,
503
+ representation: "number",
504
+ coercion: floatAmountCoercion(schema$6)
505
+ });
506
+ //#endregion
507
+ //#region src/scalars/declarations/ethereum-address.ts
508
+ const ethereumAddressScalar = defineCatalogScalar({
509
+ name: "EthereumAddress",
510
+ typescriptType: "string",
511
+ zodSource: "z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: 'Invalid Ethereum address format' })",
512
+ schema: z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: "Invalid Ethereum address format" }),
513
+ representation: "string"
514
+ });
515
+ //#endregion
516
+ //#region src/scalars/declarations/email-address.ts
517
+ const emailAddressScalar = defineCatalogScalar({
518
+ name: "EmailAddress",
519
+ typescriptType: "string",
520
+ zodSource: "z.email()",
521
+ schema: z.email(),
522
+ representation: "string"
523
+ });
524
+ //#endregion
525
+ //#region src/scalars/declarations/amount-percentage.ts
526
+ const schema$5 = z.number();
527
+ const amountPercentageScalar = defineCatalogScalar({
528
+ name: "Amount_Percentage",
529
+ typescriptType: "number",
530
+ zodSource: "z.number()",
531
+ schema: schema$5,
532
+ representation: "number",
533
+ coercion: floatAmountCoercion(schema$5)
534
+ });
535
+ //#endregion
536
+ //#region src/scalars/declarations/date.ts
537
+ const dateScalar = defineCatalogScalar({
538
+ example: "2024-01-01T00:00:00.000Z",
539
+ name: "Date",
540
+ typescriptType: "string",
541
+ zodSource: "z.iso.datetime()",
542
+ schema: z.iso.datetime(),
543
+ representation: "string"
544
+ });
545
+ //#endregion
546
+ //#region src/scalars/declarations/url.ts
547
+ const urlScalar = defineCatalogScalar({
548
+ example: "https://example.com",
549
+ name: "URL",
550
+ typescriptType: "string",
551
+ zodSource: "z.url()",
552
+ schema: z.url(),
553
+ representation: "string"
554
+ });
555
+ //#endregion
556
+ //#region src/scalars/declarations/amount-money.ts
557
+ const schema$4 = z.number();
558
+ const amountMoneyScalar = defineCatalogScalar({
559
+ name: "Amount_Money",
560
+ typescriptType: "number",
561
+ zodSource: "z.number()",
562
+ schema: schema$4,
563
+ representation: "number",
564
+ coercion: floatAmountCoercion(schema$4)
565
+ });
566
+ //#endregion
567
+ //#region src/scalars/declarations/olabel.ts
568
+ const olabelScalar = defineCatalogScalar({
569
+ name: "OLabel",
570
+ typescriptType: "string",
571
+ zodSource: "z.string()",
572
+ schema: z.string(),
573
+ representation: "string"
574
+ });
575
+ //#endregion
576
+ //#region src/scalars/declarations/currency.ts
577
+ const currencyScalar = defineCatalogScalar({
578
+ name: "Currency",
579
+ typescriptType: "string",
580
+ zodSource: "z.string()",
581
+ schema: z.string(),
582
+ representation: "string"
583
+ });
584
+ //#endregion
585
+ //#region src/scalars/declarations/phid.ts
586
+ const phidScalar = defineCatalogScalar({
587
+ name: "PHID",
588
+ typescriptType: "string",
589
+ zodSource: "z.string()",
590
+ schema: z.string(),
591
+ representation: "string"
592
+ });
593
+ //#endregion
594
+ //#region src/scalars/declarations/oid.ts
595
+ const oidScalar = defineCatalogScalar({
596
+ name: "OID",
597
+ typescriptType: "string",
598
+ zodSource: "z.string()",
599
+ schema: z.string(),
600
+ representation: "string"
601
+ });
602
+ //#endregion
603
+ //#region src/scalars/declarations/amount-fiat.ts
604
+ const schema$3 = z.object({
605
+ unit: z.string(),
606
+ value: z.number()
607
+ });
608
+ const amountFiatScalar = defineCatalogScalar({
609
+ name: "Amount_Fiat",
610
+ typescriptType: "{ unit: string, value: number }",
611
+ zodSource: "z.object({ unit: z.string(), value: z.number() })",
612
+ schema: schema$3,
613
+ representation: "json-object",
614
+ coercion: validatingCoercion(schema$3, (node) => {
615
+ const fields = objectFields(node);
616
+ return {
617
+ unit: literalString(fields.get("unit"), "unit"),
618
+ value: floatOnlyNumber(fields.get("value"), "value")
619
+ };
620
+ })
621
+ });
622
+ //#endregion
623
+ //#region src/scalars/declarations/amount-currency.ts
624
+ const schema$2 = z.object({
625
+ unit: z.string(),
626
+ value: z.string()
627
+ });
628
+ const amountCurrencyScalar = defineCatalogScalar({
629
+ name: "Amount_Currency",
630
+ typescriptType: "{ unit: string, value: string }",
631
+ zodSource: "z.object({ unit: z.string(), value: z.string()})",
632
+ schema: schema$2,
633
+ representation: "json-object",
634
+ coercion: stringAmountCoercion(schema$2)
635
+ });
636
+ //#endregion
637
+ //#region src/scalars/declarations/amount-crypto.ts
638
+ const schema$1 = z.object({
639
+ unit: z.string(),
640
+ value: z.string()
641
+ });
642
+ const amountCryptoScalar = defineCatalogScalar({
643
+ name: "Amount_Crypto",
644
+ typescriptType: "{ unit: string, value: string }",
645
+ zodSource: "z.object({ unit: z.string(), value: z.string() })",
646
+ schema: schema$1,
647
+ representation: "json-object",
648
+ coercion: stringAmountCoercion(schema$1)
649
+ });
650
+ //#endregion
651
+ //#region src/scalars/declarations/amount.ts
652
+ const schema = z.object({
653
+ unit: z.string().optional(),
654
+ value: z.number()
655
+ });
656
+ //#endregion
657
+ //#region src/scalars/catalog.ts
658
+ const declarations = [
659
+ unknownScalar,
660
+ dateTimeScalar,
661
+ addressScalar,
662
+ attachmentRefScalar,
663
+ amountTokensScalar,
664
+ ethereumAddressScalar,
665
+ emailAddressScalar,
666
+ amountPercentageScalar,
667
+ dateScalar,
668
+ urlScalar,
669
+ amountMoneyScalar,
670
+ olabelScalar,
671
+ currencyScalar,
672
+ phidScalar,
673
+ oidScalar,
674
+ amountFiatScalar,
675
+ amountCurrencyScalar,
676
+ amountCryptoScalar,
677
+ defineCatalogScalar({
678
+ name: "Amount",
679
+ typescriptType: "{ unit?: string, value?: number }",
680
+ zodSource: "z.object({ unit: z.string().optional(), value: z.number() })",
681
+ schema,
682
+ representation: "json-object",
683
+ coercion: validatingCoercion(schema, (node) => {
684
+ const fields = objectFields(node);
685
+ const unit = fields.get("unit");
686
+ return {
687
+ unit: unit === void 0 ? void 0 : literalString(unit, "unit"),
688
+ value: floatOnlyNumber(fields.get("value"), "value")
689
+ };
690
+ })
691
+ }),
692
+ defineCatalogScalar({
693
+ name: "Upload",
694
+ typescriptType: "File",
695
+ zodSource: "z.any()",
696
+ schema: z.any(),
697
+ representation: "opaque",
698
+ coercion: {
699
+ parseValue: (value) => value,
700
+ parseLiteral: () => {
701
+ throw new TypeError("Upload literals are not supported.");
702
+ },
703
+ serialize: (value) => value
704
+ }
705
+ }),
706
+ defineCatalogScalar({
707
+ name: "JSONObject",
708
+ typescriptType: null,
709
+ zodSource: null,
710
+ schema: z.record(z.string(), z.unknown()),
711
+ representation: "json-object"
712
+ })
713
+ ];
714
+ const scalarCatalog = Object.freeze([...declarations]);
715
+ new Map(scalarCatalog.map((definition) => [definition.name, definition]));
716
+ const documentModelScalars = Object.freeze(scalarCatalog.filter((definition) => definition.typescriptType !== null && definition.zodSource !== null));
717
+ //#endregion
718
+ //#region src/definition/kernel/diagnostic-collector.ts
719
+ var DefinitionDiagnosticCollector = class {
720
+ #catalog;
721
+ #definition;
722
+ #diagnostics = [];
723
+ constructor(catalog, definition) {
724
+ this.#catalog = catalog;
725
+ this.#definition = definition;
726
+ }
727
+ get diagnostics() {
728
+ return sortDefinitionDiagnostics(this.#diagnostics);
729
+ }
730
+ add(input) {
731
+ this.#diagnostics.push(this.#catalog.create({
732
+ ...this.#definition !== void 0 && { definition: this.#definition },
733
+ ...input
734
+ }));
735
+ }
736
+ merge(diagnostics) {
737
+ for (const diagnostic of diagnostics) this.#diagnostics.push(this.#definition === void 0 || diagnostic.definition !== void 0 ? diagnostic : {
738
+ ...diagnostic,
739
+ definition: { ...this.#definition }
740
+ });
741
+ }
742
+ capture(attempt) {
743
+ try {
744
+ return attempt();
745
+ } catch (error) {
746
+ if (!(error instanceof DefinitionError)) throw error;
747
+ this.merge(error.diagnostics);
748
+ return;
749
+ }
750
+ }
751
+ throwIfFailed() {
752
+ if (!this.#diagnostics.some((entry) => entry.severity === "error")) return;
753
+ throw new DefinitionError(this.#diagnostics);
754
+ }
755
+ };
756
+ //#endregion
757
+ //#region src/definition/kernel/data-properties.ts
758
+ function rejectionReceived(rejection) {
759
+ return "received" in rejection ? rejection.received : rejection.reason;
760
+ }
761
+ const CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;
762
+ function snapshotArray(value, path) {
763
+ return snapshotArrayValue(value, path, (member) => ({
764
+ ok: true,
765
+ value: member
766
+ }), /* @__PURE__ */ new Set());
767
+ }
768
+ function snapshotArrayValue(value, path, member, ancestors) {
769
+ try {
770
+ if (!Array.isArray(value)) return {
771
+ ok: false,
772
+ reason: "not-array",
773
+ path,
774
+ received: describeReceived(value)
775
+ };
776
+ } catch {
777
+ return {
778
+ ok: false,
779
+ reason: "inspection-failed",
780
+ path
781
+ };
782
+ }
783
+ if (ancestors.has(value)) return {
784
+ ok: false,
785
+ reason: "cycle",
786
+ path
787
+ };
788
+ ancestors.add(value);
789
+ try {
790
+ return snapshotArrayMembers(value, path, member, ancestors);
791
+ } finally {
792
+ ancestors.delete(value);
793
+ }
794
+ }
795
+ function snapshotArrayMembers(value, path, member, ancestors) {
796
+ let prototype;
797
+ let keys;
798
+ let lengthDescriptor;
799
+ try {
800
+ prototype = Object.getPrototypeOf(value);
801
+ keys = Reflect.ownKeys(value);
802
+ lengthDescriptor = Object.getOwnPropertyDescriptor(value, "length");
803
+ } catch {
804
+ return {
805
+ ok: false,
806
+ reason: "inspection-failed",
807
+ path
808
+ };
809
+ }
810
+ if (prototype !== Array.prototype) return {
811
+ ok: false,
812
+ reason: "custom-prototype",
813
+ path,
814
+ expected: "array",
815
+ received: "array of another prototype or realm"
816
+ };
817
+ const length = lengthDescriptor?.value;
818
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0) return {
819
+ ok: false,
820
+ reason: "inspection-failed",
821
+ path
822
+ };
823
+ for (const key of keys) {
824
+ if (key === "length") continue;
825
+ if (typeof key === "symbol") return {
826
+ ok: false,
827
+ reason: "symbol-key",
828
+ path,
829
+ key
830
+ };
831
+ if (!CANONICAL_INDEX.test(key) || Number(key) >= length) return {
832
+ ok: false,
833
+ reason: "array-property",
834
+ path: [...path, key],
835
+ key
836
+ };
837
+ }
838
+ const elements = [];
839
+ for (let index = 0; index < length; index += 1) {
840
+ const elementPath = [...path, index];
841
+ let descriptor;
842
+ try {
843
+ descriptor = Object.getOwnPropertyDescriptor(value, index);
844
+ } catch {
845
+ return {
846
+ ok: false,
847
+ reason: "inspection-failed",
848
+ path: elementPath
849
+ };
850
+ }
851
+ if (descriptor === void 0) return {
852
+ ok: false,
853
+ reason: "sparse",
854
+ path: elementPath,
855
+ key: index
856
+ };
857
+ const propertyValue = dataPropertyValue(descriptor, index, elementPath);
858
+ if (!propertyValue.ok) return propertyValue;
859
+ const element = member(propertyValue.value, elementPath, ancestors);
860
+ if (!element.ok) return element;
861
+ elements.push(element.value);
862
+ }
863
+ return {
864
+ ok: true,
865
+ value: Object.freeze(elements)
866
+ };
867
+ }
868
+ function snapshotRecord(value, allowedKeys, path, ignoredKeys = []) {
869
+ return snapshotPlainObject(value, allowedKeys, path, (member) => ({
870
+ ok: true,
871
+ value: member
872
+ }), /* @__PURE__ */ new Set(), ignoredKeys);
873
+ }
874
+ function snapshotPlainObject(value, allowedKeys, path, member, ancestors, ignoredKeys = []) {
875
+ if (value === null || typeof value !== "object") return {
876
+ ok: false,
877
+ reason: "not-record",
878
+ path,
879
+ received: describeReceived(value)
880
+ };
881
+ if (ancestors.has(value)) return {
882
+ ok: false,
883
+ reason: "cycle",
884
+ path
885
+ };
886
+ ancestors.add(value);
887
+ try {
888
+ return snapshotPlainObjectMembers(value, allowedKeys, path, member, ancestors, ignoredKeys);
889
+ } finally {
890
+ ancestors.delete(value);
891
+ }
892
+ }
893
+ function snapshotPlainObjectMembers(value, allowedKeys, path, member, ancestors, ignoredKeys) {
894
+ let isArray;
895
+ let prototype;
896
+ let keys;
897
+ try {
898
+ isArray = Array.isArray(value);
899
+ prototype = Object.getPrototypeOf(value);
900
+ keys = Reflect.ownKeys(value);
901
+ } catch {
902
+ return {
903
+ ok: false,
904
+ reason: "inspection-failed",
905
+ path
906
+ };
907
+ }
908
+ if (isArray) return {
909
+ ok: false,
910
+ reason: "not-record",
911
+ path,
912
+ received: "array"
913
+ };
914
+ if (prototype !== Object.prototype && prototype !== null) return {
915
+ ok: false,
916
+ reason: "custom-prototype",
917
+ path,
918
+ expected: "record",
919
+ received: "object"
920
+ };
921
+ const entries = [];
922
+ for (const key of keys) {
923
+ if (typeof key === "symbol") return {
924
+ ok: false,
925
+ reason: "symbol-key",
926
+ path,
927
+ key
928
+ };
929
+ if (ignoredKeys.includes(key)) continue;
930
+ const memberPath = [...path, key];
931
+ if (allowedKeys !== void 0 && !allowedKeys.includes(key)) return {
932
+ ok: false,
933
+ reason: "unknown-key",
934
+ path: memberPath,
935
+ key,
936
+ allowedKeys
937
+ };
938
+ let descriptor;
939
+ try {
940
+ descriptor = Object.getOwnPropertyDescriptor(value, key);
941
+ } catch {
942
+ return {
943
+ ok: false,
944
+ reason: "inspection-failed",
945
+ path: memberPath
946
+ };
947
+ }
948
+ if (descriptor === void 0) return {
949
+ ok: false,
950
+ reason: "inspection-failed",
951
+ path: memberPath
952
+ };
953
+ const propertyValue = dataPropertyValue(descriptor, key, memberPath);
954
+ if (!propertyValue.ok) return propertyValue;
955
+ const snapshot = member(propertyValue.value, memberPath, ancestors);
956
+ if (!snapshot.ok) return snapshot;
957
+ entries.push([key, snapshot.value]);
958
+ }
959
+ return {
960
+ ok: true,
961
+ value: Object.freeze(Object.fromEntries(entries))
962
+ };
963
+ }
964
+ function dataPropertyValue(descriptor, key, path) {
965
+ if (!("value" in descriptor)) return {
966
+ ok: false,
967
+ reason: "accessor",
968
+ path,
969
+ key
970
+ };
971
+ if (!descriptor.enumerable) return {
972
+ ok: false,
973
+ reason: "non-enumerable",
974
+ path,
975
+ key
976
+ };
977
+ return {
978
+ ok: true,
979
+ value: descriptor.value
980
+ };
981
+ }
982
+ //#endregion
983
+ //#region src/definition/kernel/diagnostic-codes.ts
984
+ const kernelDiagnostics = defineDiagnosticCatalog({
985
+ "PH-DEF-OPTION-INVALID": {
986
+ severity: "error",
987
+ phase: "definition",
988
+ 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"
989
+ },
990
+ "PH-DEF-COMPATIBILITY-INVALID": {
991
+ severity: "error",
992
+ phase: "definition",
993
+ meaning: "A location-free GraphQL compatibility AST is malformed or disagrees with the stored definitions it accompanies"
994
+ }
995
+ });
996
+ //#endregion
997
+ //#region src/definition/kernel/graphql-ast.ts
998
+ function compatibilityDiagnostic(path, message, detail = {}) {
999
+ return kernelDiagnostics.create({
1000
+ code: "PH-DEF-COMPATIBILITY-INVALID",
1001
+ path,
1002
+ message,
1003
+ ...detail.expected !== void 0 && { expected: detail.expected },
1004
+ ...detail.received !== void 0 && { received: detail.received },
1005
+ ...detail.related !== void 0 && { related: detail.related },
1006
+ repair: detail.repair ?? "Regenerate the compatibility AST from the schema this declaration replaces, or change the descriptors to agree with it."
1007
+ });
1008
+ }
1009
+ const ARRAY_INDEX = /^(?:0|[1-9][0-9]*)$/;
1010
+ function validateLocationFreeDocument(value, path) {
1011
+ const diagnostics = [];
1012
+ const refuse = (at, message, received) => diagnostics.push(compatibilityDiagnostic(at, message, {
1013
+ expected: "JSON data",
1014
+ received,
1015
+ repair: "Keep only JSON data in the AST: strings, finite numbers, booleans, null, plain arrays and plain objects with data properties."
1016
+ }));
1017
+ const ancestors = /* @__PURE__ */ new Set();
1018
+ const visitProperty = (owner, key, at) => {
1019
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
1020
+ if (descriptor === void 0) refuse(at, "A compatibility AST array must not have holes.", "hole");
1021
+ else if (!("value" in descriptor)) refuse(at, "A compatibility AST must hold data properties, not accessors.", "accessor");
1022
+ else visit(descriptor.value, at);
1023
+ };
1024
+ const visit = (node, at) => {
1025
+ if (node === null || typeof node === "string" || typeof node === "boolean") return;
1026
+ if (typeof node === "number") {
1027
+ if (!Number.isFinite(node)) refuse(at, "A compatibility AST number must be finite.", String(node));
1028
+ return;
1029
+ }
1030
+ if (typeof node !== "object") {
1031
+ refuse(at, `A compatibility AST must contain JSON data only, received ${typeof node}.`, typeof node);
1032
+ return;
1033
+ }
1034
+ if (ancestors.has(node)) {
1035
+ refuse(at, "A compatibility AST must not contain a cycle.", "cycle");
1036
+ return;
1037
+ }
1038
+ const prototype = Object.getPrototypeOf(node);
1039
+ const isArray = Array.isArray(node);
1040
+ if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
1041
+ refuse(at, "A compatibility AST must hold plain arrays and plain objects only.", describeReceived(node));
1042
+ return;
1043
+ }
1044
+ ancestors.add(node);
1045
+ for (const key of Reflect.ownKeys(node)) if (typeof key === "symbol") refuse(at, "A compatibility AST must not have symbol keys.", "symbol");
1046
+ else if (isArray) {
1047
+ if (key !== "length" && !ARRAY_INDEX.test(key)) refuse([...at, key], "A compatibility AST array must hold only its items.", key);
1048
+ } else if (key === "loc") diagnostics.push(compatibilityDiagnostic([...at, key], "A compatibility AST must be location free.", {
1049
+ expected: "no loc property",
1050
+ received: "loc",
1051
+ repair: "Strip every loc property from the AST."
1052
+ }));
1053
+ else visitProperty(node, key, [...at, key]);
1054
+ if (isArray) for (let index = 0; index < node.length; index += 1) visitProperty(node, index, [...at, index]);
1055
+ ancestors.delete(node);
1056
+ };
1057
+ visit(value, path);
1058
+ return diagnostics;
1059
+ }
1060
+ //#endregion
1061
+ //#region src/definition/compiler/diagnostic-codes.ts
1062
+ const compilerDiagnostics = defineDiagnosticCatalog({
1063
+ "PH-DM-DUPLICATE-ACTION": {
1064
+ severity: "error",
1065
+ phase: "definition",
1066
+ meaning: "Two operations derive the same persisted action type, or an operation derives one the document runtime owns"
1067
+ },
1068
+ "PH-DM-DUPLICATE-NAME": {
1069
+ severity: "error",
1070
+ phase: "definition",
1071
+ meaning: "Two declarations derive the same module, GraphQL type, or creator name"
1072
+ },
1073
+ "PH-DM-IDENTITY-INVALID": {
1074
+ severity: "error",
1075
+ phase: "definition",
1076
+ meaning: "An identity segment, compatibility ID, or derived UUID violates the V1 contract"
1077
+ },
1078
+ "PH-DM-DECLARATION-INVALID": {
1079
+ severity: "error",
1080
+ phase: "definition",
1081
+ meaning: "A model, module, operation, error, example, version, or family declaration member is absent, malformed, unsupported, or forged"
1082
+ },
1083
+ "PH-DM-DEFAULT-UNSUPPORTED": {
1084
+ severity: "error",
1085
+ phase: "definition",
1086
+ meaning: "A document state field declares a GraphQL default value"
1087
+ },
1088
+ "PH-DM-INTERFACE-INVALID": {
1089
+ severity: "error",
1090
+ phase: "definition",
1091
+ meaning: "An object or interface does not satisfy an implemented interface's fields or ancestor requirements"
1092
+ },
1093
+ "PH-DM-INPUT-CYCLE": {
1094
+ severity: "error",
1095
+ phase: "definition",
1096
+ meaning: "An input type contains itself through singular non-null input fields, so no finite value satisfies it"
1097
+ },
1098
+ "PH-DM-TYPE-POSITION-INVALID": {
1099
+ severity: "error",
1100
+ phase: "definition",
1101
+ meaning: "An input type is referenced from an output position, or an output type from an input position"
1102
+ },
1103
+ "PH-DM-INITIAL-VALUE-INVALID": {
1104
+ severity: "error",
1105
+ phase: "definition",
1106
+ meaning: "A scope initial value cannot produce a stored JSON string, or its own state validator rejects it"
1107
+ },
1108
+ "PH-SCALAR-DUPLICATE-NAME": {
1109
+ severity: "error",
1110
+ phase: "definition",
1111
+ meaning: "Two different project scalars of one model claim one name"
1112
+ }
1113
+ }, defineDiagnosticCatalog({
1114
+ "PH-DEF-FIELD-OPTION-UNSUPPORTED": {
1115
+ severity: "error",
1116
+ phase: "definition",
1117
+ meaning: "A field use contains an option its builder or its position does not support"
1118
+ },
1119
+ "PH-DEF-TYPE-AS-FIELD": {
1120
+ severity: "error",
1121
+ phase: "definition",
1122
+ meaning: "A named type is used as a field without ph.ref"
1123
+ },
1124
+ "PH-DEF-NAME-INVALID": {
1125
+ severity: "error",
1126
+ phase: "definition",
1127
+ meaning: "An authored GraphQL type, field, or enum value name is lexically invalid or reserved"
1128
+ },
1129
+ "PH-DEF-FIELD-INVALID": {
1130
+ severity: "error",
1131
+ phase: "definition",
1132
+ meaning: "A field position holds a value that is neither a field use nor a named type"
1133
+ },
1134
+ "PH-DEF-REFERENCE-TARGET-INVALID": {
1135
+ severity: "error",
1136
+ phase: "definition",
1137
+ meaning: "A ph.ref target is not a named type: a field use, another reference, undefined, or an anonymous input"
1138
+ },
1139
+ "PH-DEF-ENUM-VALUES-INVALID": {
1140
+ severity: "error",
1141
+ phase: "definition",
1142
+ meaning: "An enum declares no values, a duplicate value, or a reserved value"
1143
+ },
1144
+ "PH-DEF-UNION-MEMBERS-INVALID": {
1145
+ severity: "error",
1146
+ phase: "definition",
1147
+ meaning: "A union declares no members, a duplicate member, or a member that is not a ph.object"
1148
+ },
1149
+ "PH-DEF-IMPLEMENTS-INVALID": {
1150
+ severity: "error",
1151
+ phase: "definition",
1152
+ meaning: "An object or an interface implements something that is not a ph.interface, or the same interface twice"
1153
+ },
1154
+ "PH-SCALAR-FACTORY-AS-FIELD": {
1155
+ severity: "error",
1156
+ phase: "definition",
1157
+ meaning: "A scalar field-use factory is used as a field without being called"
1158
+ },
1159
+ "PH-SCALAR-INTERNAL": {
1160
+ severity: "error",
1161
+ phase: "definition",
1162
+ meaning: "A field uses a catalog scalar that only the reactor host declares, such as JSONObject"
1163
+ },
1164
+ "PH-SCALAR-DEFINITION-INVALID": {
1165
+ severity: "error",
1166
+ phase: "definition",
1167
+ meaning: "ph.scalar received a value that is not a scalar definition of this release's format"
1168
+ }
1169
+ }, kernelDiagnostics));
1170
+ //#endregion
1171
+ //#region src/definition/compiler/wire-shape.ts
1172
+ const BUILT_IN_SCALARS = [
1173
+ "ID",
1174
+ "String",
1175
+ "Boolean",
1176
+ "Int",
1177
+ "Float"
1178
+ ];
1179
+ const CATALOG_SCALARS = documentModelScalars.map(({ name }) => name);
1180
+ const MODEL_SCALARS = /* @__PURE__ */ new Set([...BUILT_IN_SCALARS, ...CATALOG_SCALARS]);
1181
+ const HOST_ONLY_SCALARS = new Set(scalarCatalog.map(({ name }) => name).filter((name) => !MODEL_SCALARS.has(name)));
1182
+ const SCALAR_REPRESENTATIONS = [
1183
+ "string",
1184
+ "number",
1185
+ "boolean",
1186
+ "json-object",
1187
+ "json",
1188
+ "opaque"
1189
+ ];
1190
+ var ShapeChecker = class {
1191
+ collector = new DefinitionDiagnosticCollector(compilerDiagnostics);
1192
+ packageScalars = /* @__PURE__ */ new Set();
1193
+ fail(path, message, expected, received) {
1194
+ this.collector.add({
1195
+ code: "PH-DM-DECLARATION-INVALID",
1196
+ path,
1197
+ message,
1198
+ expected,
1199
+ received: typeof received === "string" ? received : typeof received === "number" || typeof received === "boolean" ? String(received) : describeReceived(received),
1200
+ repair: "Produce the definition with materialize or a document-model/tooling adapter; a hand-edited wire definition is not accepted."
1201
+ });
1202
+ }
1203
+ record(value, keys, path) {
1204
+ const snapshot = snapshotRecord(value, keys, path);
1205
+ if (snapshot.ok) return snapshot.value;
1206
+ return this.fail(snapshot.path, `This node is not a plain object with the V1 members (${snapshot.reason}).`, keys.join(", "), rejectionReceived(snapshot));
1207
+ }
1208
+ array(value, path) {
1209
+ const snapshot = snapshotArray(value, path);
1210
+ if (snapshot.ok) return snapshot.value;
1211
+ return this.fail(snapshot.path, "This node must be an array.", "an array", rejectionReceived(snapshot));
1212
+ }
1213
+ string(value, path) {
1214
+ if (typeof value === "string") return value;
1215
+ return this.fail(path, "This member must be a string.", "string", value);
1216
+ }
1217
+ nullableString(value, path) {
1218
+ if (value === null || typeof value === "string") return;
1219
+ this.fail(path, "This member must be a string or null.", "string | null", value);
1220
+ }
1221
+ literal(value, expected, path) {
1222
+ if (value === expected) return;
1223
+ this.fail(path, "This member has a fixed value.", String(expected), value);
1224
+ }
1225
+ oneOf(value, allowed, path) {
1226
+ if (allowed.includes(value)) return value;
1227
+ return this.fail(path, "This member is outside its closed set.", allowed.join(" | "), value);
1228
+ }
1229
+ json(value, path) {
1230
+ try {
1231
+ canonicalJson(value);
1232
+ } catch (error) {
1233
+ return this.fail(path, `This member must be a JSON value: ${error instanceof Error ? error.message : String(error)}`, "a JSON value", value);
1234
+ }
1235
+ return value;
1236
+ }
1237
+ graphQLName(value, path) {
1238
+ if (isGraphQLName(value)) return value;
1239
+ return this.fail(path, "This member must be a GraphQL name.", "a GraphQL name", value);
1240
+ }
1241
+ rejectHostOnlyScalar(value, path) {
1242
+ if (typeof value !== "string" || !HOST_ONLY_SCALARS.has(value)) return false;
1243
+ this.collector.add({
1244
+ code: "PH-SCALAR-INTERNAL",
1245
+ definition: {
1246
+ kind: "scalar",
1247
+ key: value
1248
+ },
1249
+ path,
1250
+ message: `${value} is internal to the reactor host. A document model cannot use it.`,
1251
+ received: value,
1252
+ repair: "Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one."
1253
+ });
1254
+ return true;
1255
+ }
1256
+ };
1257
+ function typeReference(check, value, path) {
1258
+ const kind = value?.kind;
1259
+ const node = kind === "list" ? check.record(value, [
1260
+ "kind",
1261
+ "required",
1262
+ "item"
1263
+ ], path) : check.record(value, [
1264
+ "kind",
1265
+ "name",
1266
+ "required"
1267
+ ], path);
1268
+ if (node === void 0) return;
1269
+ if (typeof node.required !== "boolean") check.fail([...path, "required"], "A type reference records nullability.", "boolean", node.required);
1270
+ if (kind === "list") typeReference(check, node.item, [...path, "item"]);
1271
+ else if (kind === "scalar") {
1272
+ if (check.rejectHostOnlyScalar(node.name, [...path, "name"])) return;
1273
+ if (typeof node.name !== "string" || !(MODEL_SCALARS.has(node.name) || check.packageScalars.has(node.name))) check.fail([...path, "name"], "A scalar reference names a catalog scalar, a GraphQL built-in, or a package scalar the specification declares.", [...MODEL_SCALARS, ...check.packageScalars].join(" | "), node.name);
1274
+ } else if (kind === "named") check.graphQLName(node.name, [...path, "name"]);
1275
+ else check.fail([...path, "kind"], "A type reference has three kinds.", "scalar | named | list", kind);
1276
+ }
1277
+ function directiveUses(check, value, path) {
1278
+ check.array(value, path)?.forEach((use, index) => {
1279
+ const node = check.record(use, ["name", "arguments"], [...path, index]);
1280
+ if (node === void 0) return;
1281
+ check.graphQLName(node.name, [
1282
+ ...path,
1283
+ index,
1284
+ "name"
1285
+ ]);
1286
+ check.array(node.arguments, [
1287
+ ...path,
1288
+ index,
1289
+ "arguments"
1290
+ ])?.forEach((argument, argumentIndex) => {
1291
+ const at = [
1292
+ ...path,
1293
+ index,
1294
+ "arguments",
1295
+ argumentIndex
1296
+ ];
1297
+ const entry = check.record(argument, ["name", "value"], at);
1298
+ if (entry === void 0) return;
1299
+ check.graphQLName(entry.name, [...at, "name"]);
1300
+ check.json(entry.value, [...at, "value"]);
1301
+ });
1302
+ });
1303
+ }
1304
+ const FIELD_KEYS = [
1305
+ "key",
1306
+ "name",
1307
+ "description",
1308
+ "deprecated",
1309
+ "type"
1310
+ ];
1311
+ function field(check, value, path, input) {
1312
+ const node = check.record(value, [
1313
+ ...FIELD_KEYS,
1314
+ "directives",
1315
+ input ? "defaultValue" : "args"
1316
+ ], path);
1317
+ if (node === void 0) return;
1318
+ check.string(node.key, [...path, "key"]);
1319
+ check.graphQLName(node.name, [...path, "name"]);
1320
+ check.nullableString(node.description, [...path, "description"]);
1321
+ check.nullableString(node.deprecated, [...path, "deprecated"]);
1322
+ typeReference(check, node.type, [...path, "type"]);
1323
+ if (node.directives !== void 0) directiveUses(check, node.directives, [...path, "directives"]);
1324
+ if (input) {
1325
+ if (Object.hasOwn(node, "defaultValue")) check.json(node.defaultValue, [...path, "defaultValue"]);
1326
+ } else if (node.args !== void 0) check.array(node.args, [...path, "args"])?.forEach((argument, index) => field(check, argument, [
1327
+ ...path,
1328
+ "args",
1329
+ index
1330
+ ], true));
1331
+ }
1332
+ function fields(check, value, path, input) {
1333
+ check.array(value, path)?.forEach((entry, index) => field(check, entry, [...path, index], input));
1334
+ }
1335
+ function enumValue(check, value, path) {
1336
+ const node = check.record(value, [
1337
+ "name",
1338
+ "description",
1339
+ "deprecated",
1340
+ "directives"
1341
+ ], path);
1342
+ if (node === void 0) return;
1343
+ check.graphQLName(node.name, [...path, "name"]);
1344
+ check.nullableString(node.description, [...path, "description"]);
1345
+ check.nullableString(node.deprecated, [...path, "deprecated"]);
1346
+ if (node.directives !== void 0) directiveUses(check, node.directives, [...path, "directives"]);
1347
+ }
1348
+ const NAMED_TYPE_MEMBERS = {
1349
+ enum: "values",
1350
+ object: "fields",
1351
+ interface: "fields",
1352
+ input: "fields",
1353
+ union: "members"
1354
+ };
1355
+ function namedType(check, value, path) {
1356
+ const kind = value?.kind;
1357
+ if (typeof kind !== "string" || !Object.hasOwn(NAMED_TYPE_MEMBERS, kind)) return check.fail([...path, "kind"], "A named type has five kinds.", Object.keys(NAMED_TYPE_MEMBERS).join(" | "), kind);
1358
+ const typed = kind;
1359
+ const member = NAMED_TYPE_MEMBERS[typed];
1360
+ const extra = typed === "object" || typed === "interface" ? ["implements"] : typed === "input" ? ["unknownKeys"] : [];
1361
+ const node = check.record(value, [
1362
+ "kind",
1363
+ "name",
1364
+ "description",
1365
+ ...extra,
1366
+ member
1367
+ ], path);
1368
+ if (node === void 0) return void 0;
1369
+ check.nullableString(node.description, [...path, "description"]);
1370
+ const members = check.array(node[member], [...path, member]);
1371
+ switch (typed) {
1372
+ case "enum":
1373
+ members?.forEach((entry, index) => enumValue(check, entry, [
1374
+ ...path,
1375
+ "values",
1376
+ index
1377
+ ]));
1378
+ break;
1379
+ case "union":
1380
+ members?.forEach((entry, index) => check.graphQLName(entry, [
1381
+ ...path,
1382
+ "members",
1383
+ index
1384
+ ]));
1385
+ break;
1386
+ case "input":
1387
+ check.oneOf(node.unknownKeys, ["preserve", "reject"], [...path, "unknownKeys"]);
1388
+ fields(check, node.fields, [...path, "fields"], true);
1389
+ break;
1390
+ default:
1391
+ if (node.implements !== void 0) check.array(node.implements, [...path, "implements"])?.forEach((entry, index) => check.graphQLName(entry, [
1392
+ ...path,
1393
+ "implements",
1394
+ index
1395
+ ]));
1396
+ fields(check, node.fields, [...path, "fields"], false);
1397
+ }
1398
+ return check.graphQLName(node.name, [...path, "name"]);
1399
+ }
1400
+ function examples(check, value, path, keys) {
1401
+ check.array(value, path)?.forEach((entry, index) => {
1402
+ const node = check.record(entry, keys, [...path, index]);
1403
+ if (node === void 0) return;
1404
+ for (const key of keys) check.string(node[key], [
1405
+ ...path,
1406
+ index,
1407
+ key
1408
+ ]);
1409
+ });
1410
+ }
1411
+ function state(check, value, path, scope) {
1412
+ const node = check.record(value, [
1413
+ "root",
1414
+ "initialValue",
1415
+ "examples",
1416
+ "unknownKeys",
1417
+ "materialized"
1418
+ ], path);
1419
+ if (node === void 0) return;
1420
+ if (node.root === null) {
1421
+ if (scope === "global") check.fail([...path, "root"], "A global state always has a root.", "a named type reference", null);
1422
+ if (check.json(node.initialValue, [...path, "initialValue"]) !== void 0) {
1423
+ if (canonicalJson(node.initialValue) !== "{}") check.fail([...path, "initialValue"], "An empty local state carries an exact empty object.", "{}", node.initialValue);
1424
+ }
1425
+ } else {
1426
+ typeReference(check, node.root, [...path, "root"]);
1427
+ check.json(node.initialValue, [...path, "initialValue"]);
1428
+ }
1429
+ check.literal(node.unknownKeys, "preserve", [...path, "unknownKeys"]);
1430
+ examples(check, node.examples, [...path, "examples"], [
1431
+ "id",
1432
+ "key",
1433
+ "value"
1434
+ ]);
1435
+ const materializedPath = [...path, "materialized"];
1436
+ const materialized = check.record(node.materialized, [
1437
+ "schema",
1438
+ "initialValue",
1439
+ "examples"
1440
+ ], materializedPath);
1441
+ if (materialized === void 0) return;
1442
+ const schema = check.string(materialized.schema, [...materializedPath, "schema"]);
1443
+ if (node.root === null && schema !== void 0 && schema !== "") check.fail([...materializedPath, "schema"], "An empty local state materializes an empty schema.", "\"\"", schema);
1444
+ check.string(materialized.initialValue, [...materializedPath, "initialValue"]);
1445
+ examples(check, materialized.examples, [...materializedPath, "examples"], ["id", "value"]);
1446
+ }
1447
+ const OPERATION_KEYS = [
1448
+ "id",
1449
+ "key",
1450
+ "name",
1451
+ "description",
1452
+ "actionType",
1453
+ "creatorKey",
1454
+ "scope",
1455
+ "input",
1456
+ "errors",
1457
+ "examples",
1458
+ "template",
1459
+ "reducer"
1460
+ ];
1461
+ const ERROR_KEYS = [
1462
+ "id",
1463
+ "key",
1464
+ "code",
1465
+ "name",
1466
+ "description",
1467
+ "template"
1468
+ ];
1469
+ function operation(check, value, path) {
1470
+ const node = check.record(value, OPERATION_KEYS, path);
1471
+ if (node === void 0) return;
1472
+ for (const key of [
1473
+ "id",
1474
+ "key",
1475
+ "actionType",
1476
+ "creatorKey"
1477
+ ]) check.string(node[key], [...path, key]);
1478
+ for (const key of [
1479
+ "name",
1480
+ "description",
1481
+ "template",
1482
+ "reducer"
1483
+ ]) check.nullableString(node[key], [...path, key]);
1484
+ check.oneOf(node.scope, ["global", "local"], [...path, "scope"]);
1485
+ if (node.input !== null) {
1486
+ const kind = node.input?.kind;
1487
+ if (kind !== "input") check.fail([
1488
+ ...path,
1489
+ "input",
1490
+ "kind"
1491
+ ], "An operation input is an input type.", "input", kind);
1492
+ else namedType(check, node.input, [...path, "input"]);
1493
+ }
1494
+ check.array(node.errors, [...path, "errors"])?.forEach((entry, index) => {
1495
+ const at = [
1496
+ ...path,
1497
+ "errors",
1498
+ index
1499
+ ];
1500
+ const error = check.record(entry, ERROR_KEYS, at);
1501
+ if (error === void 0) return;
1502
+ check.string(error.id, [...at, "id"]);
1503
+ check.string(error.key, [...at, "key"]);
1504
+ for (const key of [
1505
+ "code",
1506
+ "name",
1507
+ "description",
1508
+ "template"
1509
+ ]) check.nullableString(error[key], [...at, key]);
1510
+ });
1511
+ examples(check, node.examples, [...path, "examples"], [
1512
+ "id",
1513
+ "key",
1514
+ "value"
1515
+ ]);
1516
+ }
1517
+ function storedScalar(check, value, name, path) {
1518
+ const node = check.record(value, [
1519
+ "kind",
1520
+ "formatVersion",
1521
+ "name",
1522
+ "representation",
1523
+ "description",
1524
+ "coercion",
1525
+ "coercionProfile"
1526
+ ], path);
1527
+ if (node === void 0) return;
1528
+ check.literal(node.kind, "powerhouse.scalar", [...path, "kind"]);
1529
+ check.literal(node.formatVersion, 1, [...path, "formatVersion"]);
1530
+ check.literal(node.name, name, [...path, "name"]);
1531
+ check.oneOf(node.representation, SCALAR_REPRESENTATIONS, [...path, "representation"]);
1532
+ check.string(node.description, [...path, "description"]);
1533
+ check.literal(node.coercionProfile, "catalog-v1", [...path, "coercionProfile"]);
1534
+ const coercion = check.record(node.coercion, ["source"], [...path, "coercion"]);
1535
+ if (coercion !== void 0) check.oneOf(coercion.source, ["derived", "explicit"], [
1536
+ ...path,
1537
+ "coercion",
1538
+ "source"
1539
+ ]);
1540
+ }
1541
+ function scalars(check, value, path) {
1542
+ const declared = /* @__PURE__ */ new Set();
1543
+ check.array(value, path)?.forEach((entry, index) => {
1544
+ const at = [...path, index];
1545
+ const isPackage = typeof entry === "object" && entry !== null && Object.hasOwn(entry, "definition");
1546
+ const scalar = check.record(entry, [
1547
+ "name",
1548
+ "implementation",
1549
+ "coercionProfile",
1550
+ "definition"
1551
+ ], at);
1552
+ if (scalar === void 0) return;
1553
+ check.literal(scalar.coercionProfile, "catalog-v1", [...at, "coercionProfile"]);
1554
+ if (check.rejectHostOnlyScalar(scalar.name, [...at, "name"])) return;
1555
+ if (!isPackage) {
1556
+ const name = check.oneOf(scalar.name, CATALOG_SCALARS, [...at, "name"]);
1557
+ if (name !== void 0) check.literal(scalar.implementation, `powerhouse.catalog#${name}`, [...at, "implementation"]);
1558
+ return;
1559
+ }
1560
+ const name = check.graphQLName(scalar.name, [...at, "name"]);
1561
+ if (name === void 0) return;
1562
+ if (MODEL_SCALARS.has(name) || declared.has(name)) {
1563
+ check.fail([...at, "name"], "A package scalar has a name no catalog scalar, GraphQL built-in, or other package scalar uses.", "an unused GraphQL name", name);
1564
+ return;
1565
+ }
1566
+ check.literal(scalar.implementation, `package#${name}`, [...at, "implementation"]);
1567
+ storedScalar(check, scalar.definition, name, [...at, "definition"]);
1568
+ declared.add(name);
1569
+ });
1570
+ return declared;
1571
+ }
1572
+ function specification(check, value, path) {
1573
+ const node = check.record(value, [
1574
+ "version",
1575
+ "scalars",
1576
+ "graphQLCompatibility",
1577
+ "types",
1578
+ "state",
1579
+ "modules",
1580
+ "changeLog"
1581
+ ], path);
1582
+ if (node === void 0) return;
1583
+ if (typeof node.version !== "number" || !Number.isSafeInteger(node.version) || node.version <= 0) check.fail([...path, "version"], "A specification version is a positive safe integer.", "a positive safe integer", node.version);
1584
+ check.packageScalars = scalars(check, node.scalars, [...path, "scalars"]);
1585
+ if (node.graphQLCompatibility !== null) {
1586
+ const at = [...path, "graphQLCompatibility"];
1587
+ const compatibility = check.record(node.graphQLCompatibility, [
1588
+ "kind",
1589
+ "document",
1590
+ "preserveDefinitionOrder"
1591
+ ], at);
1592
+ if (compatibility !== void 0) {
1593
+ check.literal(compatibility.kind, "graphql-ast-v1", [...at, "kind"]);
1594
+ check.literal(compatibility.preserveDefinitionOrder, true, [...at, "preserveDefinitionOrder"]);
1595
+ check.collector.merge(validateLocationFreeDocument(compatibility.document, [...at, "document"]));
1596
+ }
1597
+ }
1598
+ const declared = /* @__PURE__ */ new Set();
1599
+ check.array(node.types, [...path, "types"])?.forEach((entry, index) => {
1600
+ const name = namedType(check, entry, [
1601
+ ...path,
1602
+ "types",
1603
+ index
1604
+ ]);
1605
+ if (name === void 0) return;
1606
+ if (declared.has(name) || check.packageScalars.has(name)) check.fail([
1607
+ ...path,
1608
+ "types",
1609
+ index,
1610
+ "name"
1611
+ ], "A named type is declared once per specification, and never under a package scalar's name.", "one definition per name", name);
1612
+ declared.add(name);
1613
+ });
1614
+ const stateNode = check.record(node.state, ["global", "local"], [...path, "state"]);
1615
+ if (stateNode !== void 0) for (const scope of ["global", "local"]) {
1616
+ state(check, stateNode[scope], [
1617
+ ...path,
1618
+ "state",
1619
+ scope
1620
+ ], scope);
1621
+ const root = stateNode[scope]?.root;
1622
+ if (typeof root?.name === "string" && !declared.has(root.name)) check.fail([
1623
+ ...path,
1624
+ "state",
1625
+ scope,
1626
+ "root",
1627
+ "name"
1628
+ ], "A state root is declared in this specification's types.", [...declared].join(" | "), root.name);
1629
+ }
1630
+ check.array(node.modules, [...path, "modules"])?.forEach((entry, index) => {
1631
+ const at = [
1632
+ ...path,
1633
+ "modules",
1634
+ index
1635
+ ];
1636
+ const module = check.record(entry, [
1637
+ "id",
1638
+ "key",
1639
+ "name",
1640
+ "description",
1641
+ "operations"
1642
+ ], at);
1643
+ if (module === void 0) return;
1644
+ check.string(module.id, [...at, "id"]);
1645
+ check.string(module.key, [...at, "key"]);
1646
+ check.string(module.name, [...at, "name"]);
1647
+ check.nullableString(module.description, [...at, "description"]);
1648
+ check.array(module.operations, [...at, "operations"])?.forEach((candidate, operationIndex) => operation(check, candidate, [
1649
+ ...at,
1650
+ "operations",
1651
+ operationIndex
1652
+ ]));
1653
+ });
1654
+ check.array(node.changeLog, [...path, "changeLog"])?.forEach((entry, index) => check.string(entry, [
1655
+ ...path,
1656
+ "changeLog",
1657
+ index
1658
+ ]));
1659
+ }
1660
+ function checkDocumentModelDefinitionShape(value, path = []) {
1661
+ const check = new ShapeChecker();
1662
+ const node = check.record(value, [
1663
+ "kind",
1664
+ "formatVersion",
1665
+ "compatibility",
1666
+ "model",
1667
+ "specifications"
1668
+ ], path);
1669
+ if (node === void 0) return check.collector.diagnostics;
1670
+ check.literal(node.kind, "powerhouse.document-model", [...path, "kind"]);
1671
+ check.literal(node.formatVersion, 1, [...path, "formatVersion"]);
1672
+ const compatibilityPath = [...path, "compatibility"];
1673
+ const compatibility = check.record(node.compatibility, [
1674
+ "identity",
1675
+ "scalarCoercion",
1676
+ "serialization"
1677
+ ], compatibilityPath);
1678
+ if (compatibility !== void 0) {
1679
+ check.oneOf(compatibility.identity, ["derived-v1", "explicit-schema-first"], [...compatibilityPath, "identity"]);
1680
+ check.literal(compatibility.scalarCoercion, "catalog-v1", [...compatibilityPath, "scalarCoercion"]);
1681
+ check.oneOf(compatibility.serialization, ["canonical-v1", "explicit-schema-first"], [...compatibilityPath, "serialization"]);
1682
+ }
1683
+ const modelPath = [...path, "model"];
1684
+ const model = check.record(node.model, [
1685
+ "documentType",
1686
+ "graphQLName",
1687
+ "name",
1688
+ "description",
1689
+ "extension",
1690
+ "author"
1691
+ ], modelPath);
1692
+ if (model !== void 0) {
1693
+ if (check.string(model.documentType, [...modelPath, "documentType"]) === "") check.fail([...modelPath, "documentType"], "A document type is not empty.", "a document type", "\"\"");
1694
+ check.graphQLName(model.graphQLName, [...modelPath, "graphQLName"]);
1695
+ for (const key of [
1696
+ "name",
1697
+ "description",
1698
+ "extension"
1699
+ ]) check.string(model[key], [...modelPath, key]);
1700
+ const author = check.record(model.author, ["name", "website"], [...modelPath, "author"]);
1701
+ if (author !== void 0) {
1702
+ check.string(author.name, [
1703
+ ...modelPath,
1704
+ "author",
1705
+ "name"
1706
+ ]);
1707
+ check.nullableString(author.website, [
1708
+ ...modelPath,
1709
+ "author",
1710
+ "website"
1711
+ ]);
1712
+ }
1713
+ }
1714
+ const specifications = check.array(node.specifications, [...path, "specifications"]);
1715
+ if (specifications?.length === 0) check.fail([...path, "specifications"], "A definition carries at least one specification.", "a nonempty specification history", "an empty array");
1716
+ specifications?.forEach((entry, index) => specification(check, entry, [
1717
+ ...path,
1718
+ "specifications",
1719
+ index
1720
+ ]));
1721
+ return check.collector.diagnostics;
1722
+ }
1723
+ //#endregion
1724
+ //#region src/definition/tooling/diagnostic-codes.ts
1725
+ const toolingDiagnostics = defineDiagnosticCatalog({
1726
+ "PH-CONFIG-SOURCE-INVALID": {
1727
+ severity: "error",
1728
+ phase: "configuration",
1729
+ meaning: "The config file, a definition source entry, or an export pointer cannot select a module export"
1730
+ },
1731
+ "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE": {
1732
+ severity: "error",
1733
+ phase: "configuration",
1734
+ meaning: "A definition source path, or the real path behind its symlinks, leaves the package root"
1735
+ },
1736
+ "PH-CONFIG-DUPLICATE-SOURCE": {
1737
+ severity: "error",
1738
+ phase: "configuration",
1739
+ meaning: "Two entries select the same module and export path"
1740
+ },
1741
+ "PH-CONFIG-VERSION-UNSUPPORTED": {
1742
+ severity: "error",
1743
+ phase: "configuration",
1744
+ meaning: "definitionSources declares a format version this release does not read"
1745
+ },
1746
+ "PH-IMPORT-FAILED": {
1747
+ severity: "error",
1748
+ phase: "import",
1749
+ meaning: "A selected module is missing, throws while it is evaluated, or the import adapter returned no namespace"
1750
+ },
1751
+ "PH-PKG-DEFINITION-UNRECOGNIZED": {
1752
+ severity: "error",
1753
+ phase: "package",
1754
+ meaning: "A selected export holds no materialized document model, family, or upgrade manifest"
1755
+ },
1756
+ "PH-PKG-DEFINITION-UNINSPECTABLE": {
1757
+ severity: "error",
1758
+ phase: "package",
1759
+ meaning: "A selected export hides its members behind an accessor or a Proxy"
1760
+ },
1761
+ "PH-PKG-LOGICAL-COLLISION": {
1762
+ severity: "error",
1763
+ phase: "package",
1764
+ meaning: "Two distinct values claim one document type and version, or one upgrade manifest document type"
1765
+ }
1766
+ }, defineDiagnosticCatalog({
1767
+ "PH-DM-STATE-ROOT-INVALID": {
1768
+ severity: "error",
1769
+ phase: "definition",
1770
+ meaning: "A required state root is absent, is not an object, or has the wrong canonical name"
1771
+ },
1772
+ "PH-DM-SCOPE-UNSUPPORTED": {
1773
+ severity: "error",
1774
+ phase: "definition",
1775
+ meaning: "A definition requests a scope outside global or local"
1776
+ },
1777
+ "PH-AUTH-UNSUPPORTED": {
1778
+ severity: "error",
1779
+ phase: "authorization",
1780
+ meaning: "A document model declares authorization, which core v1 rejects"
1781
+ }
1782
+ }, compilerDiagnostics));
1783
+ //#endregion
1784
+ //#region src/definition/tooling/adapters/code-first-document-model-source-adapter.ts
1785
+ const MODULE_KEYS = "version, reducer, actions, utils, documentModel, definition";
1786
+ const REPAIR = "Export the module materialize returned, or family.at(version), without replacing its members.";
1787
+ function sourceOf(source, exportPath) {
1788
+ const path = [...source.exportPath ?? [], ...exportPath];
1789
+ return {
1790
+ specifier: source.specifier,
1791
+ ...path.length > 0 && { exportPath: path }
1792
+ };
1793
+ }
1794
+ function invalid(collector, path, message, expected, received, repair = REPAIR) {
1795
+ collector.add({
1796
+ code: "PH-DM-DECLARATION-INVALID",
1797
+ path,
1798
+ message,
1799
+ expected,
1800
+ received,
1801
+ repair
1802
+ });
1803
+ }
1804
+ function storedDocumentType(collector, value, path) {
1805
+ const documentModel = snapshotRecord(value, void 0, path);
1806
+ const global = documentModel.ok ? snapshotRecord(documentModel.value.global, void 0, [...path, "global"]) : documentModel;
1807
+ if (!global.ok) return invalid(collector, global.path, `A module keeps its stored model in documentModel.global as plain data, and it cannot be read (${global.reason}).`, "documentModel.global as a plain record of data properties", rejectionReceived(global));
1808
+ const id = global.value.id;
1809
+ if (typeof id !== "string" || id === "") return invalid(collector, [
1810
+ ...path,
1811
+ "global",
1812
+ "id"
1813
+ ], "A module has a stored model ID.", "a nonempty document type", typeof id === "string" ? "\"\"" : describeReceived(id), "Declare id in defineDocumentModel; the stored model ID is the document type every consumer registers.");
1814
+ return id;
1815
+ }
1816
+ function artifact(collector, value, source, path) {
1817
+ const snapshot = snapshotRecord(value, void 0, path);
1818
+ if (!snapshot.ok) return invalid(collector, snapshot.path, `This export is not a document-model module (${snapshot.reason}).`, MODULE_KEYS, rejectionReceived(snapshot));
1819
+ const module = snapshot.value;
1820
+ let usable = true;
1821
+ if (typeof module.reducer !== "function") {
1822
+ usable = false;
1823
+ invalid(collector, [...path, "reducer"], "A module has a callable reducer.", "a reducer function", describeReceived(module.reducer));
1824
+ }
1825
+ const version = module.version;
1826
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version <= 0) {
1827
+ usable = false;
1828
+ invalid(collector, [...path, "version"], "A code-first module declares its registry version as a positive safe integer.", "a positive safe integer", typeof version === "number" ? String(version) : describeReceived(version));
1829
+ }
1830
+ const documentType = storedDocumentType(collector, module.documentModel, [...path, "documentModel"]);
1831
+ if (module.definition === void 0) return invalid(collector, [...path, "definition"], "This module carries no structured definition, so it was not made by materialize.", "the definition materialize attaches", "undefined", "Export the module materialize returned.");
1832
+ const shape = checkDocumentModelDefinitionShape(module.definition, [...path, "definition"]);
1833
+ collector.merge(shape);
1834
+ if (!usable || documentType === void 0 || shape.length > 0 || typeof version !== "number") return;
1835
+ const definition = module.definition;
1836
+ if (definition.model.documentType !== documentType) return invalid(collector, [
1837
+ ...path,
1838
+ "definition",
1839
+ "model",
1840
+ "documentType"
1841
+ ], "The structured definition and the stored model describe different document types.", documentType, definition.model.documentType, "Materialize the module and its definition from the same declaration.");
1842
+ if (!definition.specifications.some((entry) => entry.version === version)) return invalid(collector, [
1843
+ ...path,
1844
+ "definition",
1845
+ "specifications"
1846
+ ], `The specification history carries no version ${version}, which is the version this module serves.`, `a specification for version ${version}`, definition.specifications.map((entry) => String(entry.version)).join(", "), "Compose the versions with defineDocumentModelFamily so every module carries the complete history.");
1847
+ return {
1848
+ kind: "powerhouse.document-model-artifact",
1849
+ source,
1850
+ documentType,
1851
+ version,
1852
+ definition,
1853
+ digest: canonicalDigest(definition),
1854
+ documentModel: module.documentModel
1855
+ };
1856
+ }
1857
+ function familyManifest(collector, value, artifacts, path) {
1858
+ const snapshot = snapshotRecord(value, void 0, path);
1859
+ const manifest = snapshot.ok ? snapshot.value : void 0;
1860
+ const versions = artifacts.map((entry) => entry.version);
1861
+ const supported = manifest?.supportedVersions;
1862
+ const declared = Array.isArray(supported) && supported.every(Number.isSafeInteger) ? canonicalJson(supported) : describeReceived(supported);
1863
+ if (manifest === void 0 || declared !== canonicalJson(versions) || manifest.latestVersion !== versions.at(-1)) {
1864
+ invalid(collector, snapshot.ok ? path : snapshot.path, "A family's upgrade manifest covers exactly the versions its modules serve.", canonicalJson(versions), snapshot.ok ? declared : rejectionReceived(snapshot), "Export the family materialize returned, so its manifest and modules stay one declaration.");
1865
+ return null;
1866
+ }
1867
+ const documentTypes = new Set(artifacts.map((entry) => entry.documentType));
1868
+ if (documentTypes.size !== 1 || !documentTypes.has(manifest.documentType)) {
1869
+ invalid(collector, [...path, "documentType"], "A family's upgrade manifest and its modules name one document type.", [...documentTypes].join(", "), String(manifest.documentType), "Compose one family per document type.");
1870
+ return null;
1871
+ }
1872
+ return value;
1873
+ }
1874
+ /**
1875
+ * @experimental Normalizes one materialized code-first module, or a family
1876
+ * and its versions in order. A family reports every malformed member: a
1877
+ * valid sibling never makes a broken one pass.
1878
+ */
1879
+ function adaptCodeFirstDocumentModelSource(value, source) {
1880
+ const collector = new DefinitionDiagnosticCollector(toolingDiagnostics);
1881
+ const family = snapshotRecord(value, void 0, []);
1882
+ const modules = family.ok && typeof family.value.at === "function" ? snapshotArray(family.value.modules, ["modules"]) : void 0;
1883
+ if (family.ok && modules?.ok === true) {
1884
+ const artifacts = modules.value.flatMap((module, index) => {
1885
+ const entry = artifact(collector, module, sourceOf(source, ["modules", String(index)]), ["modules", index]);
1886
+ return entry === void 0 ? [] : [entry];
1887
+ });
1888
+ return {
1889
+ artifacts,
1890
+ upgradeManifest: artifacts.length === modules.value.length ? familyManifest(collector, family.value.upgradeManifest, artifacts, ["upgradeManifest"]) : null,
1891
+ diagnostics: collector.diagnostics
1892
+ };
1893
+ }
1894
+ const single = artifact(collector, value, source, []);
1895
+ return {
1896
+ artifacts: single === void 0 ? [] : [single],
1897
+ upgradeManifest: null,
1898
+ diagnostics: collector.diagnostics
1899
+ };
1900
+ }
1901
+ //#endregion
1902
+ //#region src/definition/tooling/definition-source-resolution.ts
1903
+ const CONFIG_FILE_NAME = "./powerhouse.config.json";
1904
+ const IDENTITY_SEPARATOR = String.fromCharCode(0);
1905
+ function render(value) {
1906
+ if (typeof value === "string") return value;
1907
+ if (value === void 0) return "undefined";
1908
+ try {
1909
+ return JSON.stringify(value) ?? typeof value;
1910
+ } catch {
1911
+ return typeof value;
1912
+ }
1913
+ }
1914
+ function sourceSet(mode, origin, sources) {
1915
+ const value = {
1916
+ mode,
1917
+ origin,
1918
+ sources
1919
+ };
1920
+ return {
1921
+ ...value,
1922
+ digest: canonicalDigest(value)
1923
+ };
1924
+ }
1925
+ function compareDefinitionSources(left, right) {
1926
+ const specifier = compareCodeUnits(left.specifier, right.specifier);
1927
+ if (specifier !== 0) return specifier;
1928
+ const leftPath = left.exportPath ?? [];
1929
+ const rightPath = right.exportPath ?? [];
1930
+ for (let index = 0; index < Math.min(leftPath.length, rightPath.length); index += 1) {
1931
+ const segment = compareCodeUnits(leftPath[index], rightPath[index]);
1932
+ if (segment !== 0) return segment;
1933
+ }
1934
+ return leftPath.length - rightPath.length;
1935
+ }
1936
+ function isCanonicalText(value) {
1937
+ for (const character of value) {
1938
+ const codePoint = character.codePointAt(0) ?? 0;
1939
+ if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) return false;
1940
+ }
1941
+ return isNFC(value);
1942
+ }
1943
+ function isWithin(root, path) {
1944
+ const child = relative(root, path);
1945
+ return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute(child);
1946
+ }
1947
+ function normalizeSpecifier(value) {
1948
+ if (!value.startsWith("./") || /[\\#?]/.test(value) || !isCanonicalText(value)) return {
1949
+ ok: false,
1950
+ code: "PH-CONFIG-SOURCE-INVALID",
1951
+ message: "A definition source is a POSIX package-relative path beginning with './'."
1952
+ };
1953
+ const normalized = posix.normalize(value.slice(2));
1954
+ if (normalized === "." || normalized === "./") return {
1955
+ ok: false,
1956
+ code: "PH-CONFIG-SOURCE-INVALID",
1957
+ message: "A definition source names a module file, not the package root."
1958
+ };
1959
+ if (normalized === ".." || normalized.startsWith("../")) return {
1960
+ ok: false,
1961
+ code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
1962
+ message: "The normalized definition source path leaves the package root."
1963
+ };
1964
+ if (!/\.(?:[cm]?[jt]s|[jt]sx)$/.test(value)) return {
1965
+ ok: false,
1966
+ code: "PH-CONFIG-SOURCE-INVALID",
1967
+ message: "A definition source names a JavaScript or TypeScript module file with its extension."
1968
+ };
1969
+ return {
1970
+ ok: true,
1971
+ specifier: `./${normalized}`
1972
+ };
1973
+ }
1974
+ /**
1975
+ * Resolves symlinks as far as the path exists, so a source that is not
1976
+ * written yet is still judged against the real package root.
1977
+ */
1978
+ function realPathThroughExistingParent(path) {
1979
+ let current = path;
1980
+ const suffix = [];
1981
+ while (!existsSync(current)) {
1982
+ const parent = dirname(current);
1983
+ if (parent === current) return path;
1984
+ suffix.unshift(relative(parent, current));
1985
+ current = parent;
1986
+ }
1987
+ return resolve(realpathSync.native(current), ...suffix);
1988
+ }
1989
+ function invalidEntry(path, message, expected, received, repair, source) {
1990
+ return { diagnostic: toolingDiagnostics.create({
1991
+ code: "PH-CONFIG-SOURCE-INVALID",
1992
+ ...source !== void 0 && { source },
1993
+ path,
1994
+ message,
1995
+ expected,
1996
+ received,
1997
+ repair
1998
+ }) };
1999
+ }
2000
+ function normalizeEntry(value, position, packageRoot, packageRootIdentity) {
2001
+ if (value === null || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) return invalidEntry(position, "A definition source entry must be a plain object.", "{ specifier, exportPath? }", render(value), "Replace this entry with { \"specifier\": \"./src/<module>.ts\" }.");
2002
+ const entry = value;
2003
+ const extra = Object.keys(entry).filter((key) => key !== "specifier" && key !== "exportPath").sort(compareCodeUnits);
2004
+ if (extra.length > 0) return invalidEntry(position, "A definition source entry carries unsupported properties.", "specifier and optional exportPath", extra.join(", "), `Remove ${extra.join(", ")} from this entry.`);
2005
+ const specifierPath = [...position, "specifier"];
2006
+ if (typeof entry.specifier !== "string") return invalidEntry(specifierPath, "A definition source specifier must be a string.", "a './' POSIX package-relative path", render(entry.specifier), "Set specifier to the package-relative TypeScript module path.");
2007
+ const normalized = normalizeSpecifier(entry.specifier);
2008
+ if (!normalized.ok) return { diagnostic: toolingDiagnostics.create({
2009
+ code: normalized.code,
2010
+ path: specifierPath,
2011
+ message: normalized.message,
2012
+ expected: "a './' path contained by the selected package root",
2013
+ received: entry.specifier,
2014
+ repair: "Move the module inside the package and spell its path relative to the config file."
2015
+ }) };
2016
+ const { specifier } = normalized;
2017
+ let exportPath;
2018
+ if (entry.exportPath !== void 0) {
2019
+ if (!(Array.isArray(entry.exportPath) && entry.exportPath.every((segment) => typeof segment === "string" && isCanonicalText(segment)))) return invalidEntry([...position, "exportPath"], "An exportPath is an array of exact property keys in NFC, without control characters.", "an array of property-key strings", render(entry.exportPath), "Replace exportPath with the exported property keys, outermost first.", { specifier });
2020
+ const segments = entry.exportPath;
2021
+ if (segments.length > 0) exportPath = [...segments];
2022
+ }
2023
+ const source = exportPath === void 0 ? { specifier } : {
2024
+ specifier,
2025
+ exportPath
2026
+ };
2027
+ const declaredPath = resolve(packageRoot, ...specifier.slice(2).split("/"));
2028
+ let moduleIdentity;
2029
+ try {
2030
+ moduleIdentity = realPathThroughExistingParent(declaredPath);
2031
+ } catch {
2032
+ return invalidEntry(specifierPath, "The definition source path could not be resolved.", "a resolvable path inside the package root", specifier, "Fix the path, or the permissions of a directory on the way to it.", source);
2033
+ }
2034
+ if (!isWithin(packageRootIdentity, moduleIdentity)) return { diagnostic: toolingDiagnostics.create({
2035
+ code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
2036
+ source,
2037
+ path: specifierPath,
2038
+ message: "The definition source resolves through a symlink that leaves the package root.",
2039
+ expected: "a real path contained by the package root",
2040
+ received: specifier,
2041
+ repair: "Replace the symlink with a module that really lives in this package."
2042
+ }) };
2043
+ return { source: {
2044
+ source,
2045
+ position,
2046
+ moduleIdentity
2047
+ } };
2048
+ }
2049
+ function duplicateDiagnostics(sources) {
2050
+ const groups = /* @__PURE__ */ new Map();
2051
+ for (const entry of sources) {
2052
+ const key = [entry.moduleIdentity, JSON.stringify(entry.source.exportPath ?? [])].join(IDENTITY_SEPARATOR);
2053
+ groups.set(key, [...groups.get(key) ?? [], entry]);
2054
+ }
2055
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
2056
+ const [first, ...rest] = [...group].sort((left, right) => compareDefinitionSources(left.source, right.source) || compareDefinitionPaths(left.position, right.position));
2057
+ return toolingDiagnostics.create({
2058
+ code: "PH-CONFIG-DUPLICATE-SOURCE",
2059
+ source: first.source,
2060
+ path: first.position,
2061
+ message: "Several entries select the same module and export path, so one of them can only repeat the other's definitions.",
2062
+ expected: "one entry per module and export path",
2063
+ received: `${group.length} entries`,
2064
+ repair: "Remove every duplicate entry except one.",
2065
+ related: rest.map((entry) => ({
2066
+ source: entry.source,
2067
+ path: entry.position,
2068
+ message: "This entry resolves to the same module and export path."
2069
+ }))
2070
+ });
2071
+ });
2072
+ }
2073
+ function failed(roots, diagnostics, origin = "config", sources = []) {
2074
+ return {
2075
+ ...roots,
2076
+ status: "failed",
2077
+ sourceSet: sourceSet("code-first", origin, sources),
2078
+ diagnostics: sortDefinitionDiagnostics(diagnostics),
2079
+ resolved: []
2080
+ };
2081
+ }
2082
+ function skipped(roots, skipReason, mode) {
2083
+ return {
2084
+ ...roots,
2085
+ status: "skipped",
2086
+ skipReason,
2087
+ sourceSet: sourceSet(mode, "config", []),
2088
+ diagnostics: [],
2089
+ resolved: []
2090
+ };
2091
+ }
2092
+ const CONFIG_FAILURE_REPAIR = {
2093
+ missing: "Create the config file, or point --config-file at the package's existing one.",
2094
+ "read-failed": "Fix the permissions of the selected config file.",
2095
+ "parse-failed": "Repair the JSON in the selected config file.",
2096
+ "not-an-object": "Make the config file a single JSON object."
2097
+ };
2098
+ function readConfigObject(configFile) {
2099
+ let text;
2100
+ try {
2101
+ text = readFileSync(configFile, "utf8");
2102
+ } catch (error) {
2103
+ const code = error?.code;
2104
+ return {
2105
+ ok: false,
2106
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-failed"
2107
+ };
2108
+ }
2109
+ let parsed;
2110
+ try {
2111
+ parsed = JSON.parse(text);
2112
+ } catch {
2113
+ return {
2114
+ ok: false,
2115
+ reason: "parse-failed"
2116
+ };
2117
+ }
2118
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
2119
+ ok: false,
2120
+ reason: "not-an-object"
2121
+ };
2122
+ return {
2123
+ ok: true,
2124
+ value: parsed
2125
+ };
2126
+ }
2127
+ function selectionDiagnostic(narrowed) {
2128
+ if (narrowed.reason === "unsupported-version") return toolingDiagnostics.create({
2129
+ code: "PH-CONFIG-VERSION-UNSUPPORTED",
2130
+ path: narrowed.path,
2131
+ message: "The definitionSources format version is not one this release reads.",
2132
+ expected: "1",
2133
+ received: render(narrowed.received),
2134
+ repair: "Set definitionSources.formatVersion to 1, or upgrade ph."
2135
+ });
2136
+ return toolingDiagnostics.create({
2137
+ code: "PH-CONFIG-SOURCE-INVALID",
2138
+ path: narrowed.path,
2139
+ message: "The definitionSources selection is malformed.",
2140
+ expected: narrowed.expected,
2141
+ received: render(narrowed.received),
2142
+ repair: `Set this member to ${narrowed.expected}.`
2143
+ });
2144
+ }
2145
+ function resolveDefinitionSources(request) {
2146
+ const configFile = resolve(request.configFile ?? CONFIG_FILE_NAME);
2147
+ const packageRoot = dirname(configFile);
2148
+ let packageRootIdentity = packageRoot;
2149
+ try {
2150
+ packageRootIdentity = realpathSync.native(packageRoot);
2151
+ } catch {}
2152
+ const roots = {
2153
+ packageRoot,
2154
+ packageRootIdentity
2155
+ };
2156
+ if (request.allowMissingConfig === true && !existsSync(configFile)) return skipped(roots, "definition-sources-absent", DEFAULT_AUTHORING_MODE);
2157
+ const config = readConfigObject(configFile);
2158
+ if (!config.ok) return failed(roots, [toolingDiagnostics.create({
2159
+ code: "PH-CONFIG-SOURCE-INVALID",
2160
+ path: ["configFile"],
2161
+ message: "The selected Powerhouse config file could not be read; its directory is the package root.",
2162
+ expected: "an existing config file holding one JSON object",
2163
+ received: config.reason,
2164
+ repair: CONFIG_FAILURE_REPAIR[config.reason]
2165
+ })]);
2166
+ const origin = "config";
2167
+ const narrowed = parseDefinitionSourcesConfig(config.value.definitionSources);
2168
+ if (!narrowed.ok) return narrowed.reason === "missing" ? skipped(roots, "definition-sources-absent", DEFAULT_AUTHORING_MODE) : failed(roots, [selectionDiagnostic(narrowed)], origin);
2169
+ if (narrowed.mode === "schema-first") return skipped(roots, "explicit-schema-first-mode", "schema-first");
2170
+ if (narrowed.entries.length === 0) return skipped(roots, "definition-sources-empty", "code-first");
2171
+ const normalized = narrowed.entries.map((value, index) => normalizeEntry(value, [
2172
+ "definitionSources",
2173
+ "entries",
2174
+ index
2175
+ ], packageRoot, packageRootIdentity));
2176
+ const resolved = normalized.flatMap((result) => "source" in result ? [result.source] : []).sort((left, right) => compareDefinitionSources(left.source, right.source));
2177
+ const sources = resolved.map((entry) => entry.source);
2178
+ const entryDiagnostics = normalized.flatMap((result) => "diagnostic" in result ? [result.diagnostic] : []);
2179
+ if (entryDiagnostics.length > 0) return failed(roots, entryDiagnostics, origin, sources);
2180
+ const duplicates = duplicateDiagnostics(resolved);
2181
+ if (duplicates.length > 0) return failed(roots, duplicates, origin, sources);
2182
+ return {
2183
+ ...roots,
2184
+ status: "ready",
2185
+ sourceSet: sourceSet("code-first", origin, sources),
2186
+ diagnostics: [],
2187
+ resolved
2188
+ };
2189
+ }
2190
+ function publicResolution(value) {
2191
+ const common = {
2192
+ packageRoot: value.packageRoot,
2193
+ sourceSet: value.sourceSet,
2194
+ diagnostics: value.diagnostics
2195
+ };
2196
+ return value.status === "skipped" ? {
2197
+ ...common,
2198
+ status: "skipped",
2199
+ skipReason: value.skipReason
2200
+ } : {
2201
+ ...common,
2202
+ status: value.status
2203
+ };
2204
+ }
2205
+ /**
2206
+ * @experimental The selection a command would load, resolved without
2207
+ * importing anything and without any machine-specific path but the root.
2208
+ */
2209
+ function resolveDefinitionSelection(request) {
2210
+ return publicResolution(resolveDefinitionSources(request));
2211
+ }
2212
+ //#endregion
2213
+ //#region src/definition/tooling/structured-diagnostics.ts
2214
+ function describeThrown(error) {
2215
+ if (error === null) return "null";
2216
+ try {
2217
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
2218
+ } catch {}
2219
+ return typeof error;
2220
+ }
2221
+ /** Reads an own data property without running a getter or a Proxy trap twice. */
2222
+ function readProperty(value, key) {
2223
+ try {
2224
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
2225
+ if (descriptor === void 0 || !("value" in descriptor)) return { ok: false };
2226
+ return {
2227
+ ok: true,
2228
+ value: descriptor.value
2229
+ };
2230
+ } catch {
2231
+ return { ok: false };
2232
+ }
2233
+ }
2234
+ const DEFINITION_KINDS = [
2235
+ "document-model",
2236
+ "subgraph",
2237
+ "scalar",
2238
+ "package"
2239
+ ];
2240
+ function definitionRef(value) {
2241
+ const snapshot = snapshotRecord(value, void 0, []);
2242
+ if (!snapshot.ok) return void 0;
2243
+ const { kind, key, version } = snapshot.value;
2244
+ if (typeof key !== "string" || key === "" || !DEFINITION_KINDS.includes(kind)) return;
2245
+ return {
2246
+ kind,
2247
+ key,
2248
+ ...typeof version === "number" && { version }
2249
+ };
2250
+ }
2251
+ function isPathSegment(segment) {
2252
+ return typeof segment === "string" || typeof segment === "number" && Number.isSafeInteger(segment);
2253
+ }
2254
+ function structuredDiagnostics(value, source) {
2255
+ if (value === null || typeof value !== "object" && typeof value !== "function") return;
2256
+ const list = readProperty(value, "diagnostics");
2257
+ if (!list.ok) return void 0;
2258
+ const snapshot = snapshotArray(list.value, []);
2259
+ if (!snapshot.ok || snapshot.value.length === 0) return void 0;
2260
+ const rebuilt = [];
2261
+ for (const candidate of snapshot.value) {
2262
+ const entry = snapshotRecord(candidate, void 0, []);
2263
+ if (!entry.ok) return void 0;
2264
+ const { code, message, repair, expected, received } = entry.value;
2265
+ const path = snapshotArray(entry.value.path, []);
2266
+ if (typeof code !== "string" || !Object.hasOwn(toolingDiagnostics.codes, code) || typeof message !== "string" || typeof repair !== "string" || !path.ok || !path.value.every(isPathSegment) || expected !== void 0 && typeof expected !== "string" || received !== void 0 && typeof received !== "string") return;
2267
+ const definition = definitionRef(entry.value.definition);
2268
+ rebuilt.push(toolingDiagnostics.create({
2269
+ code,
2270
+ source,
2271
+ ...definition !== void 0 && { definition },
2272
+ path: path.value,
2273
+ message,
2274
+ ...expected !== void 0 && { expected },
2275
+ ...received !== void 0 && { received },
2276
+ repair
2277
+ }));
2278
+ }
2279
+ return rebuilt;
2280
+ }
2281
+ //#endregion
2282
+ //#region src/definition/tooling/definition-source-loader.ts
2283
+ const KEY_SEPARATOR = String.fromCharCode(0);
2284
+ function isSha256Digest(value) {
2285
+ return typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value);
2286
+ }
2287
+ function isVersionList(value) {
2288
+ return Array.isArray(value) && value.every((version) => Number.isSafeInteger(version) && version > 0);
2289
+ }
2290
+ function isDocumentModelModule(record) {
2291
+ return typeof record.reducer === "function" && snapshotRecord(record.documentModel, void 0, []).ok;
2292
+ }
2293
+ function isUpgradeManifest(record) {
2294
+ return typeof record.documentType === "string" && Number.isSafeInteger(record.latestVersion) && isVersionList(record.supportedVersions) && snapshotRecord(record.upgrades, void 0, []).ok;
2295
+ }
2296
+ function familyMembers(record) {
2297
+ if (typeof record.at !== "function" || record.upgradeManifest === void 0) return;
2298
+ const modules = snapshotArray(record.modules, []);
2299
+ return modules.ok ? modules.value : void 0;
2300
+ }
2301
+ function documentTypeOf(module) {
2302
+ const stored = snapshotRecord(module.documentModel, void 0, []);
2303
+ const global = stored.ok ? snapshotRecord(stored.value.global, void 0, []) : void 0;
2304
+ return global?.ok === true && typeof global.value.id === "string" ? global.value.id : "";
2305
+ }
2306
+ function extendSource(source, path) {
2307
+ const exportPath = [...source.exportPath ?? [], ...path.map(String)];
2308
+ return {
2309
+ specifier: source.specifier,
2310
+ ...exportPath.length > 0 && { exportPath }
2311
+ };
2312
+ }
2313
+ function claim(collected, logicalKey, describe, source, path) {
2314
+ const existing = collected.claimed.get(logicalKey);
2315
+ if (existing === void 0) {
2316
+ collected.claimed.set(logicalKey, {
2317
+ source,
2318
+ path
2319
+ });
2320
+ return;
2321
+ }
2322
+ collected.diagnostics.push(toolingDiagnostics.create({
2323
+ code: "PH-PKG-LOGICAL-COLLISION",
2324
+ source,
2325
+ path,
2326
+ message: `Two different values both declare ${describe}, so a host registering this package would keep only one of them.`,
2327
+ expected: "one value per logical definition",
2328
+ received: describe,
2329
+ repair: "Export one canonical value for this definition and remove the other source entry.",
2330
+ related: [{
2331
+ source: existing.source,
2332
+ path: existing.path,
2333
+ message: "The first value claiming it is here."
2334
+ }]
2335
+ }));
2336
+ }
2337
+ function collectDocumentModel(collected, value, source, path) {
2338
+ const module = value;
2339
+ collected.documentModels.push({
2340
+ source,
2341
+ path,
2342
+ value: module
2343
+ });
2344
+ const documentType = documentTypeOf(module);
2345
+ const version = module.version;
2346
+ if (documentType === "" || typeof version !== "number") return;
2347
+ claim(collected, [
2348
+ "document-model",
2349
+ documentType,
2350
+ String(version)
2351
+ ].join(KEY_SEPARATOR), `document model ${documentType} version ${String(version)}`, source, path);
2352
+ }
2353
+ function collectUpgradeManifest(collected, value, source, path) {
2354
+ const manifest = value;
2355
+ collected.upgradeManifests.push({
2356
+ source,
2357
+ path,
2358
+ value: manifest
2359
+ });
2360
+ claim(collected, ["upgrade-manifest", manifest.documentType].join(KEY_SEPARATOR), `the upgrade manifest of ${manifest.documentType}`, source, path);
2361
+ }
2362
+ function visit(collected, value, source, path) {
2363
+ if (value === null || typeof value !== "object") return 0;
2364
+ const alias = collected.visited.get(value);
2365
+ if (alias !== void 0) return alias;
2366
+ collected.visited.set(value, 0);
2367
+ const found = walk(collected, value, source, path);
2368
+ collected.visited.set(value, found);
2369
+ return found;
2370
+ }
2371
+ function walk(collected, value, source, path) {
2372
+ const array = snapshotArray(value, path);
2373
+ if (array.ok) return array.value.reduce((count, member, index) => count + visit(collected, member, source, [...path, index]), 0);
2374
+ const plain = snapshotRecord(value, void 0, path);
2375
+ if (!plain.ok) {
2376
+ if (plain.reason !== "accessor" && plain.reason !== "inspection-failed") return 0;
2377
+ collected.diagnostics.push(toolingDiagnostics.create({
2378
+ code: "PH-PKG-DEFINITION-UNINSPECTABLE",
2379
+ source: extendSource(source, path),
2380
+ path,
2381
+ message: `This export could not be read safely (${plain.reason}).`,
2382
+ expected: "a plain object, an array, or a materialized definition",
2383
+ received: rejectionReceived(plain),
2384
+ repair: "Export plain values: a getter or a Proxy hides what the loader reads."
2385
+ }));
2386
+ return 0;
2387
+ }
2388
+ const record = plain.value;
2389
+ const members = familyMembers(record);
2390
+ if (members !== void 0) return members.reduce((total, member, index) => total + visit(collected, member, source, [
2391
+ ...path,
2392
+ "modules",
2393
+ index
2394
+ ]), 0) + visit(collected, record.upgradeManifest, source, [...path, "upgradeManifest"]);
2395
+ if (isDocumentModelModule(record)) {
2396
+ collectDocumentModel(collected, value, extendSource(source, path), path);
2397
+ return 1;
2398
+ }
2399
+ if (isUpgradeManifest(record)) {
2400
+ collectUpgradeManifest(collected, value, extendSource(source, path), path);
2401
+ return 1;
2402
+ }
2403
+ return Object.keys(record).sort(compareCodeUnits).reduce((count, key) => count + visit(collected, record[key], source, [...path, key]), 0);
2404
+ }
2405
+ function checkManifestCoverage(collected) {
2406
+ const versionsByType = /* @__PURE__ */ new Map();
2407
+ for (const entry of collected.documentModels) {
2408
+ const documentType = documentTypeOf(entry.value);
2409
+ const version = entry.value.version;
2410
+ if (documentType === "" || typeof version !== "number") continue;
2411
+ versionsByType.set(documentType, [...versionsByType.get(documentType) ?? [], version]);
2412
+ }
2413
+ const ascending = (left, right) => left - right;
2414
+ for (const manifest of collected.upgradeManifests) {
2415
+ const { documentType, supportedVersions, latestVersion, upgrades } = manifest.value;
2416
+ const definition = {
2417
+ kind: "document-model",
2418
+ key: documentType
2419
+ };
2420
+ const loaded = [...versionsByType.get(documentType) ?? []].sort(ascending);
2421
+ const declared = [...supportedVersions].sort(ascending);
2422
+ if (JSON.stringify(loaded) !== JSON.stringify(declared) || latestVersion !== declared.at(-1)) {
2423
+ collected.diagnostics.push(toolingDiagnostics.create({
2424
+ code: "PH-DM-DECLARATION-INVALID",
2425
+ source: manifest.source,
2426
+ definition,
2427
+ path: manifest.path,
2428
+ message: "The upgrade manifest and the selected modules of this document type describe different version sets.",
2429
+ expected: `supportedVersions ${JSON.stringify(loaded)} with latestVersion ${String(loaded.at(-1))}`,
2430
+ received: `supportedVersions ${JSON.stringify(declared)} with latestVersion ${String(latestVersion)}`,
2431
+ repair: "Select the whole family that materialize returned, so its modules and its manifest stay one declaration."
2432
+ }));
2433
+ continue;
2434
+ }
2435
+ const expected = declared.slice(1).map((version) => `v${version}`);
2436
+ const actual = Object.keys(upgrades).sort(compareCodeUnits);
2437
+ if (JSON.stringify(actual) !== JSON.stringify([...expected].sort(compareCodeUnits))) collected.diagnostics.push(toolingDiagnostics.create({
2438
+ code: "PH-DM-DECLARATION-INVALID",
2439
+ source: manifest.source,
2440
+ definition,
2441
+ path: [...manifest.path, "upgrades"],
2442
+ message: "The upgrade manifest does not carry exactly one transition for each version after the first.",
2443
+ expected: expected.join(", ") || "no transitions",
2444
+ received: actual.join(", ") || "no transitions",
2445
+ repair: "Publish the manifest materialize returned, unmodified."
2446
+ }));
2447
+ }
2448
+ }
2449
+ /**
2450
+ * A native namespace carries a `Symbol.toStringTag` key and Vite's SSR
2451
+ * namespace exposes exports through getters; the data-property rules would
2452
+ * reject both without this flattening.
2453
+ */
2454
+ function namespaceSnapshot(value) {
2455
+ if (value === null || typeof value !== "object" && typeof value !== "function") throw new TypeError(`The import adapter returned ${describeReceived(value)} instead of a module namespace.`);
2456
+ return Object.freeze({ ...value });
2457
+ }
2458
+ function unresolvedBareImportOf(error) {
2459
+ if (!(error instanceof Error)) return void 0;
2460
+ const match = /^Cannot find (?:package|module) '([^']+)' imported from '?(.+?)'?$/m.exec(error.message);
2461
+ if (match === null) return void 0;
2462
+ const [, specifier, importer] = match;
2463
+ if (/^(?:[./\\]|[a-zA-Z][\w+.-]*:)/.test(specifier)) return void 0;
2464
+ const name = specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
2465
+ const from = importer.startsWith("file:") ? fileURLToPath(importer) : importer;
2466
+ if (!isAbsolute(from)) return void 0;
2467
+ for (let directory = dirname(from);; directory = dirname(directory)) {
2468
+ if (existsSync(join(directory, "node_modules", name))) return void 0;
2469
+ if (dirname(directory) === directory) return name;
2470
+ }
2471
+ }
2472
+ function importDiagnostics(error, source, missing) {
2473
+ if (missing) return [toolingDiagnostics.create({
2474
+ code: "PH-IMPORT-FAILED",
2475
+ source,
2476
+ path: [],
2477
+ message: "definitionSources lists a module that does not exist.",
2478
+ expected: "an existing module inside the package",
2479
+ received: source.specifier,
2480
+ repair: "Fix the specifier, or remove the entry from definitionSources.entries in powerhouse.config.json."
2481
+ })];
2482
+ const structured = structuredDiagnostics(error, source);
2483
+ if (structured !== void 0) return structured;
2484
+ const unresolved = unresolvedBareImportOf(error);
2485
+ return [toolingDiagnostics.create({
2486
+ code: "PH-IMPORT-FAILED",
2487
+ source,
2488
+ path: [],
2489
+ message: unresolved === void 0 ? "This definition source could not be imported." : `This definition source could not resolve the import ${unresolved}.`,
2490
+ expected: unresolved === void 0 ? "an importable TypeScript module" : `a project alias or installed dependency resolving ${unresolved}`,
2491
+ received: describeThrown(error),
2492
+ repair: unresolved === void 0 ? "Fix this module or one of its imports, then load it again." : `Check the project tsconfig paths and package dependencies for ${unresolved}. If it is an npm package, list it in package.json and install dependencies.`
2493
+ })];
2494
+ }
2495
+ function selectExport(source, namespace) {
2496
+ let current = namespace;
2497
+ const exportPath = source.exportPath ?? [];
2498
+ for (const [index, key] of exportPath.entries()) {
2499
+ const read = current !== null && (typeof current === "object" || typeof current === "function") ? readProperty(current, key) : void 0;
2500
+ if (read?.ok !== true) return {
2501
+ ok: false,
2502
+ diagnostic: toolingDiagnostics.create({
2503
+ code: "PH-CONFIG-SOURCE-INVALID",
2504
+ source,
2505
+ path: ["exportPath", index],
2506
+ message: read === void 0 ? `The export pointer reads "${key}" from a value that has no properties.` : `The configured export "${key}" is absent, or is not a plain readable property.`,
2507
+ expected: read === void 0 ? "an object or a namespace" : key,
2508
+ received: read === void 0 ? describeReceived(current) : "missing",
2509
+ repair: "Point the export pointer at an exact exported property, spelled as it is exported."
2510
+ })
2511
+ };
2512
+ current = read.value;
2513
+ }
2514
+ return {
2515
+ ok: true,
2516
+ value: current
2517
+ };
2518
+ }
2519
+ function sortBySource(entries) {
2520
+ return [...entries].sort((left, right) => compareDefinitionSources(left.source, right.source) || compareDefinitionPaths(left.path, right.path));
2521
+ }
2522
+ function empty(resolution) {
2523
+ return {
2524
+ ...resolution,
2525
+ documentModels: [],
2526
+ upgradeManifests: []
2527
+ };
2528
+ }
2529
+ /**
2530
+ * @experimental Imports the selected definition sources and finds the
2531
+ * materialized document models, families and upgrade manifests they export.
2532
+ * It folds aliases, reports two values that claim one `documentType@version`,
2533
+ * and returns everything sorted by source, so neither config order nor
2534
+ * import completion order changes a result. Validity belongs to the
2535
+ * adapters; registration belongs to the host.
2536
+ */
2537
+ var DefinitionSourceLoader = class {
2538
+ #importer;
2539
+ #imports = /* @__PURE__ */ new Map();
2540
+ #revision;
2541
+ constructor(importer) {
2542
+ this.#importer = importer;
2543
+ }
2544
+ resolve(request) {
2545
+ return publicResolution(resolveDefinitionSources(request));
2546
+ }
2547
+ async normalizeDefinitionSources(request) {
2548
+ request.signal?.throwIfAborted();
2549
+ const resolution = resolveDefinitionSources(request);
2550
+ if (resolution.status !== "ready") return empty(publicResolution(resolution));
2551
+ if (!isSha256Digest(request.packageRevision)) return empty({
2552
+ packageRoot: resolution.packageRoot,
2553
+ sourceSet: resolution.sourceSet,
2554
+ status: "failed",
2555
+ diagnostics: [toolingDiagnostics.create({
2556
+ code: "PH-CONFIG-SOURCE-INVALID",
2557
+ path: ["packageRevision"],
2558
+ message: "The package revision is not a SHA-256 identifier, so no import can be bound to it.",
2559
+ expected: "sha256: followed by 64 lowercase hexadecimal digits",
2560
+ received: typeof request.packageRevision === "string" ? request.packageRevision : describeReceived(request.packageRevision),
2561
+ repair: "Pass a revision digest of the package's current files."
2562
+ })]
2563
+ });
2564
+ await this.#retainRevision(request.packageRevision);
2565
+ const namespaces = await this.#importModules(resolution, request);
2566
+ request.signal?.throwIfAborted();
2567
+ const collected = {
2568
+ documentModels: [],
2569
+ upgradeManifests: [],
2570
+ diagnostics: [],
2571
+ visited: /* @__PURE__ */ new Map(),
2572
+ claimed: /* @__PURE__ */ new Map()
2573
+ };
2574
+ for (const entry of resolution.resolved) {
2575
+ const namespace = namespaces.get(entry.moduleIdentity);
2576
+ if (namespace === void 0) continue;
2577
+ if (!namespace.ok) {
2578
+ collected.diagnostics.push(...namespace.diagnostics(entry.source));
2579
+ continue;
2580
+ }
2581
+ const selected = selectExport(entry.source, namespace.value);
2582
+ if (!selected.ok) {
2583
+ collected.diagnostics.push(selected.diagnostic);
2584
+ continue;
2585
+ }
2586
+ if (visit(collected, selected.value, entry.source, []) === 0) collected.diagnostics.push(toolingDiagnostics.create({
2587
+ code: "PH-PKG-DEFINITION-UNRECOGNIZED",
2588
+ source: entry.source,
2589
+ path: [],
2590
+ message: "This source exports no materialized document model, so selecting it loads nothing.",
2591
+ expected: "a module or family materialize returned, or a collection holding them",
2592
+ received: "no recognized definition",
2593
+ repair: "Point this entry at the export that materialize(...) returned."
2594
+ }));
2595
+ }
2596
+ checkManifestCoverage(collected);
2597
+ const diagnostics = sortDefinitionDiagnostics(collected.diagnostics);
2598
+ return {
2599
+ packageRoot: resolution.packageRoot,
2600
+ sourceSet: resolution.sourceSet,
2601
+ status: diagnostics.some(({ severity }) => severity === "error") ? "failed" : "ready",
2602
+ diagnostics,
2603
+ documentModels: sortBySource(collected.documentModels),
2604
+ upgradeManifests: sortBySource(collected.upgradeManifests)
2605
+ };
2606
+ }
2607
+ async dispose() {
2608
+ const revision = this.#revision;
2609
+ this.#imports.clear();
2610
+ this.#revision = void 0;
2611
+ if (revision !== void 0) await this.#importer.disposeRevision?.(revision);
2612
+ }
2613
+ async #retainRevision(revision) {
2614
+ if (this.#revision === revision) return;
2615
+ const superseded = this.#revision;
2616
+ this.#imports.clear();
2617
+ this.#revision = revision;
2618
+ if (superseded !== void 0) await this.#importer.disposeRevision?.(superseded);
2619
+ }
2620
+ async #importModules(resolution, request) {
2621
+ const results = /* @__PURE__ */ new Map();
2622
+ for (const entry of resolution.resolved) {
2623
+ const { moduleIdentity, source } = entry;
2624
+ if (results.has(moduleIdentity)) continue;
2625
+ let namespace = this.#imports.get(moduleIdentity);
2626
+ if (namespace === void 0) {
2627
+ namespace = this.#importer.importModule({
2628
+ packageRoot: resolution.packageRootIdentity,
2629
+ specifier: source.specifier,
2630
+ packageRevision: request.packageRevision,
2631
+ ...request.signal !== void 0 && { signal: request.signal }
2632
+ });
2633
+ this.#imports.set(moduleIdentity, namespace);
2634
+ namespace.catch(() => this.#imports.delete(moduleIdentity));
2635
+ }
2636
+ try {
2637
+ results.set(moduleIdentity, {
2638
+ ok: true,
2639
+ value: namespaceSnapshot(await namespace)
2640
+ });
2641
+ } catch (error) {
2642
+ const missing = !existsSync(moduleIdentity);
2643
+ results.set(moduleIdentity, {
2644
+ ok: false,
2645
+ diagnostics: (failedSource) => importDiagnostics(error, failedSource, missing)
2646
+ });
2647
+ }
2648
+ }
2649
+ return results;
2650
+ }
2651
+ };
2652
+ //#endregion
2653
+ export { DefinitionSourceLoader, adaptCodeFirstDocumentModelSource, formatDefinitionDiagnostic, resolveDefinitionSelection };
2654
+
2655
+ //# sourceMappingURL=tooling.mjs.map