@ptdgrp/typedgql 1.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,911 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ //#region src/runtime/types.ts
4
+ const __runtime = Symbol("__selection_runtime");
5
+ function runtimeOf(selection) {
6
+ return selection[__runtime];
7
+ }
8
+ var StringValue = class {
9
+ constructor(value, quotationMarks = true) {
10
+ this.value = value;
11
+ this.quotationMarks = quotationMarks;
12
+ }
13
+ };
14
+ const __fragment_spread = Symbol("__fragment_spread");
15
+ var FragmentSpread = class {
16
+ [__fragment_spread] = true;
17
+ constructor(name, selection) {
18
+ this.name = name;
19
+ this.selection = selection;
20
+ }
21
+ };
22
+ var FragmentRef = class extends FragmentSpread {
23
+ constructor(name, selection) {
24
+ super(name, selection);
25
+ }
26
+ };
27
+
28
+ //#endregion
29
+ //#region src/runtime/schema.ts
30
+ const SCHEMA_TYPE_REGISTRY = /* @__PURE__ */ new Map();
31
+ const SCHEMA_TYPE_FACTORY_REGISTRY = /* @__PURE__ */ new Map();
32
+ const SCHEMA_TYPE_RESOLVING = /* @__PURE__ */ new Set();
33
+ const resolveRegisteredSchemaType = (typeName) => {
34
+ const registered = SCHEMA_TYPE_REGISTRY.get(typeName);
35
+ if (registered) return registered;
36
+ const factory = SCHEMA_TYPE_FACTORY_REGISTRY.get(typeName);
37
+ if (!factory) return;
38
+ if (SCHEMA_TYPE_RESOLVING.has(typeName)) throw new Error(`Circular schema factory resolution detected for "${typeName}"`);
39
+ SCHEMA_TYPE_RESOLVING.add(typeName);
40
+ try {
41
+ registerSchemaType(factory());
42
+ } finally {
43
+ SCHEMA_TYPE_RESOLVING.delete(typeName);
44
+ }
45
+ return SCHEMA_TYPE_REGISTRY.get(typeName);
46
+ };
47
+ const registerSchemaTypeFactory = (typeName, factory) => {
48
+ if (!SCHEMA_TYPE_FACTORY_REGISTRY.has(typeName)) SCHEMA_TYPE_FACTORY_REGISTRY.set(typeName, factory);
49
+ };
50
+ const createSchemaType = (name, category, superTypes, declaredFields) => {
51
+ const declaredFieldMap = /* @__PURE__ */ new Map();
52
+ for (const desc of declaredFields) if (typeof desc === "string") declaredFieldMap.set(desc, buildField(desc, "SCALAR", /* @__PURE__ */ new Map()));
53
+ else {
54
+ const argMap = /* @__PURE__ */ new Map();
55
+ if (desc.argGraphQLTypeMap) for (const k in desc.argGraphQLTypeMap) argMap.set(k, desc.argGraphQLTypeMap[k]);
56
+ declaredFieldMap.set(desc.name, buildField(desc.name, desc.category, argMap, desc.targetTypeName, desc.undefinable));
57
+ }
58
+ let _fields;
59
+ const result = {
60
+ name,
61
+ category,
62
+ interfaces: superTypes,
63
+ ownFields: declaredFieldMap,
64
+ get fields() {
65
+ if (!_fields) _fields = superTypes.length === 0 ? declaredFieldMap : collectFields(result);
66
+ return _fields;
67
+ }
68
+ };
69
+ registerSchemaType(result);
70
+ return result;
71
+ };
72
+ const buildField = (name, category, argGraphQLTypeMap, targetTypeName, undefinable) => {
73
+ const isPlural = category === "LIST";
74
+ const isAssociation = category === "REFERENCE" || isPlural;
75
+ return {
76
+ name,
77
+ category,
78
+ argGraphQLTypeMap,
79
+ targetTypeName,
80
+ isPlural,
81
+ isAssociation,
82
+ isFunction: argGraphQLTypeMap.size !== 0 || isAssociation || targetTypeName !== void 0,
83
+ isUndefinable: undefinable ?? false
84
+ };
85
+ };
86
+ const collectFields = (type) => {
87
+ const result = /* @__PURE__ */ new Map();
88
+ _collect(type, result);
89
+ return result;
90
+ };
91
+ const _collect = (type, out) => {
92
+ for (const [name, field] of type.ownFields) out.set(name, field);
93
+ for (const superType of type.interfaces) _collect(superType, out);
94
+ };
95
+ const registerSchemaType = (type) => {
96
+ const existing = SCHEMA_TYPE_REGISTRY.get(type.name);
97
+ if (!existing) {
98
+ SCHEMA_TYPE_REGISTRY.set(type.name, type);
99
+ return;
100
+ }
101
+ if (existing.ownFields.size < type.ownFields.size) SCHEMA_TYPE_REGISTRY.set(type.name, type);
102
+ };
103
+
104
+ //#endregion
105
+ //#region src/runtime/parameter.ts
106
+ /**
107
+ * @author ChenTao
108
+ *
109
+ * 1. If object is used by field arguments, don't specify the graphqlTypeName
110
+ * 2. If object is used by directive arguments, graphqlTypeName is required
111
+ */
112
+ const __marker = Symbol("__parameter_ref_marker");
113
+ var ParameterRef = class ParameterRef {
114
+ [__marker] = true;
115
+ constructor(name, graphqlTypeName) {
116
+ this.name = name;
117
+ this.graphqlTypeName = graphqlTypeName;
118
+ if (name.startsWith("$")) throw new Error("parameter name cannot start with '$'");
119
+ }
120
+ static of(name, graphqlTypeName) {
121
+ return new ParameterRef(name, graphqlTypeName);
122
+ }
123
+ };
124
+
125
+ //#endregion
126
+ //#region src/runtime/text-builder.ts
127
+ const SCOPE_BRACKETS = {
128
+ block: ["{", "}"],
129
+ arguments: ["(", ")"],
130
+ array: ["[", "]"]
131
+ };
132
+ const DEFAULT_SEPARATORS = {
133
+ arguments: ", ",
134
+ array: ", "
135
+ };
136
+ var TextBuilder = class {
137
+ result = "";
138
+ atNewLine = false;
139
+ scopes = [];
140
+ constructor(indent = " ") {
141
+ this.indent = indent;
142
+ }
143
+ text(value) {
144
+ const scope = this.scopes.at(-1);
145
+ if (value && scope && !scope.dirty) {
146
+ if (scope.multiLines) this.lineBreak();
147
+ scope.dirty = true;
148
+ }
149
+ let remaining = value;
150
+ while (remaining) {
151
+ this.flushIndent();
152
+ const newlineIdx = remaining.indexOf("\n");
153
+ if (newlineIdx !== -1) {
154
+ this.result += remaining.substring(0, newlineIdx);
155
+ this.lineBreak();
156
+ remaining = remaining.substring(newlineIdx + 1);
157
+ } else {
158
+ this.result += remaining;
159
+ remaining = "";
160
+ }
161
+ }
162
+ return this;
163
+ }
164
+ scope(options, action) {
165
+ const { type, multiLines = false, separator, prefix, suffix } = options;
166
+ const [open, close] = SCOPE_BRACKETS[type];
167
+ if (prefix) this.text(prefix);
168
+ this.text(open);
169
+ this.scopes.push({
170
+ type,
171
+ multiLines,
172
+ separator: separator ?? DEFAULT_SEPARATORS[type],
173
+ dirty: false
174
+ });
175
+ try {
176
+ action();
177
+ } finally {
178
+ this.scopes.pop();
179
+ if (multiLines && !this.atNewLine) this.lineBreak();
180
+ this.text(close);
181
+ if (suffix) this.text(suffix);
182
+ }
183
+ return this;
184
+ }
185
+ separator(value) {
186
+ const scope = this.scopes.at(-1);
187
+ if (!scope) throw new Error("No existing scope");
188
+ if (scope.dirty) {
189
+ const sep = value || scope.separator;
190
+ if (sep) this.text(sep);
191
+ if (scope.multiLines) this.lineBreak();
192
+ }
193
+ return this;
194
+ }
195
+ toString() {
196
+ return this.result;
197
+ }
198
+ flushIndent() {
199
+ if (this.atNewLine) {
200
+ this.result += this.indent.repeat(this.scopes.length);
201
+ this.atNewLine = false;
202
+ }
203
+ }
204
+ lineBreak() {
205
+ this.result += "\n";
206
+ this.atNewLine = true;
207
+ }
208
+ };
209
+
210
+ //#endregion
211
+ //#region src/runtime/selection.ts
212
+ var SelectionImpl = class SelectionImpl {
213
+ [__runtime] = this;
214
+ _fieldMap;
215
+ _directiveMap;
216
+ _result;
217
+ constructor(_ctx, _negative, _field, _args, _child, _fieldOptionsValue, _directive, _directiveArgs, _operationName) {
218
+ this._ctx = _ctx;
219
+ this._negative = _negative;
220
+ this._field = _field;
221
+ this._args = _args;
222
+ this._child = _child;
223
+ this._fieldOptionsValue = _fieldOptionsValue;
224
+ this._directive = _directive;
225
+ this._directiveArgs = _directiveArgs;
226
+ this._operationName = _operationName;
227
+ }
228
+ get lastField() {
229
+ return this._field;
230
+ }
231
+ get _schemaType() {
232
+ return Array.isArray(this._ctx) ? this._ctx[0] : this._ctx._schemaType;
233
+ }
234
+ get _enumInputMetadata() {
235
+ return Array.isArray(this._ctx) ? this._ctx[1] : this._ctx._enumInputMetadata;
236
+ }
237
+ get _unionItemTypes() {
238
+ return Array.isArray(this._ctx) ? this._ctx.length > 2 && this._ctx[2]?.length ? this._ctx[2] : void 0 : this._ctx._unionItemTypes;
239
+ }
240
+ get _prev() {
241
+ return Array.isArray(this._ctx) ? void 0 : this._ctx;
242
+ }
243
+ get schemaType() {
244
+ return this._schemaType;
245
+ }
246
+ get operationName() {
247
+ if (this._operationName !== void 0) return this._operationName;
248
+ return this._prev?.operationName;
249
+ }
250
+ addField(field, args, child, optionsValue) {
251
+ return new SelectionImpl(this, false, field, args, child, optionsValue);
252
+ }
253
+ removeField(field) {
254
+ if (field === "__typename") throw new Error("__typename cannot be removed");
255
+ return new SelectionImpl(this, true, field);
256
+ }
257
+ addEmbeddable(child, fragmentName) {
258
+ let fieldName;
259
+ if (fragmentName !== void 0) {
260
+ if (fragmentName.length === 0) throw new Error("fragmentName cannot be ''");
261
+ if (fragmentName.startsWith("on ")) throw new Error("fragmentName cannot start with 'on '");
262
+ fieldName = `... ${fragmentName}`;
263
+ } else if (child._schemaType.name === this._schemaType.name || child._unionItemTypes !== void 0) fieldName = "...";
264
+ else fieldName = `... on ${child._schemaType.name}`;
265
+ return new SelectionImpl(this, false, fieldName, void 0, child);
266
+ }
267
+ addDirective(directive, directiveArgs) {
268
+ return new SelectionImpl(this, false, "", void 0, void 0, void 0, directive, directiveArgs);
269
+ }
270
+ withOperationName(operationName) {
271
+ if (operationName === void 0) return this;
272
+ if (operationName.trim().length === 0) throw new Error("operationName cannot be empty");
273
+ return new SelectionImpl(this, false, "", void 0, void 0, void 0, void 0, void 0, operationName);
274
+ }
275
+ get fieldMap() {
276
+ return this._fieldMap ??= this._buildFieldMap();
277
+ }
278
+ get directiveMap() {
279
+ return this._directiveMap ??= this._buildDirectiveMap();
280
+ }
281
+ get variableTypeMap() {
282
+ return this._serialize().variableTypeMap;
283
+ }
284
+ findField(fieldKey) {
285
+ const field = this.fieldMap.get(fieldKey);
286
+ if (field) return field;
287
+ for (const [, f] of this.fieldMap) if (f.name.startsWith("...") && f.childSelections) for (const child of f.childSelections) {
288
+ const deeper = runtimeOf(child).findField(fieldKey);
289
+ if (deeper) return deeper;
290
+ }
291
+ }
292
+ findFieldsByName(fieldName) {
293
+ const out = [];
294
+ this._collectFieldsByName(fieldName, out);
295
+ return out;
296
+ }
297
+ findFieldByName(fieldName) {
298
+ const fields = this.findFieldsByName(fieldName);
299
+ if (fields.length > 1) throw new Error(`Too many fields named "${fieldName}" in selection of type "${this._schemaType.name}"`);
300
+ return fields[0];
301
+ }
302
+ toString() {
303
+ return this._serialize().text;
304
+ }
305
+ toFragmentString() {
306
+ return this._serialize().fragmentText;
307
+ }
308
+ toJSON() {
309
+ return JSON.stringify(this._serialize());
310
+ }
311
+ _buildFieldMap() {
312
+ const nodes = [];
313
+ for (let n = this; n; n = n._prev) if (n._field !== "") nodes.push(n);
314
+ const map = /* @__PURE__ */ new Map();
315
+ for (let i = nodes.length - 1; i >= 0; --i) {
316
+ const n = nodes[i];
317
+ const key = n._fieldOptionsValue?.alias ?? n._field;
318
+ if (n._field.startsWith("...")) {
319
+ let children = map.get(key)?.childSelections;
320
+ if (!children) {
321
+ children = [];
322
+ map.set(key, {
323
+ name: n._field,
324
+ plural: false,
325
+ childSelections: children
326
+ });
327
+ }
328
+ children.push(n._child);
329
+ } else if (n._negative) map.delete(key);
330
+ else map.set(key, {
331
+ name: n._field,
332
+ argGraphQLTypes: n._schemaType.fields.get(n._field)?.argGraphQLTypeMap,
333
+ args: n._args,
334
+ fieldOptionsValue: n._fieldOptionsValue,
335
+ plural: n._schemaType.fields.get(n._field)?.isPlural ?? false,
336
+ childSelections: n._child ? [n._child] : void 0
337
+ });
338
+ }
339
+ return map;
340
+ }
341
+ _buildDirectiveMap() {
342
+ const map = /* @__PURE__ */ new Map();
343
+ for (let n = this; n; n = n._prev) if (n._directive !== void 0 && !map.has(n._directive)) map.set(n._directive, n._directiveArgs);
344
+ return map;
345
+ }
346
+ _collectFieldsByName(fieldName, out) {
347
+ for (const field of this.fieldMap.values()) if (field.name === fieldName) out.push(field);
348
+ else if (field.name.startsWith("...") && field.childSelections) for (const child of field.childSelections) out.push(...runtimeOf(child).findFieldsByName(fieldName));
349
+ }
350
+ _serialize() {
351
+ return this._result ??= serialize(this);
352
+ }
353
+ };
354
+ const withOperationName = (selection, operationName) => selection.withOperationName(operationName);
355
+ const serialize = (root) => {
356
+ const writer = new TextBuilder();
357
+ const fragmentWriter = new TextBuilder();
358
+ let ctx = new SerializeContext(writer);
359
+ ctx.acceptDirectives(root.directiveMap);
360
+ writer.scope({
361
+ type: "block",
362
+ multiLines: true,
363
+ suffix: "\n"
364
+ }, () => {
365
+ ctx.acceptSelection(root);
366
+ });
367
+ const renderedFragments = /* @__PURE__ */ new Set();
368
+ while (true) {
369
+ const fragmentMap = ctx.namedFragmentMap;
370
+ if (fragmentMap.size === 0) break;
371
+ ctx = new SerializeContext(fragmentWriter, ctx);
372
+ for (const [name, fragment] of fragmentMap) if (renderedFragments.add(name)) {
373
+ const runtime = runtimeOf(fragment);
374
+ fragmentWriter.text(`fragment ${name} on ${runtime.schemaType.name} `);
375
+ ctx.acceptDirectives(runtime.directiveMap);
376
+ fragmentWriter.scope({
377
+ type: "block",
378
+ multiLines: true,
379
+ suffix: "\n"
380
+ }, () => {
381
+ ctx.acceptSelection(fragment);
382
+ });
383
+ }
384
+ }
385
+ return {
386
+ text: writer.toString(),
387
+ fragmentText: fragmentWriter.toString(),
388
+ variableTypeMap: ctx.variableTypeMap
389
+ };
390
+ };
391
+ var SerializeContext = class SerializeContext {
392
+ namedFragmentMap = /* @__PURE__ */ new Map();
393
+ fragmentNameCounter = /* @__PURE__ */ new Map();
394
+ fragmentRuntimeNameMap = /* @__PURE__ */ new WeakMap();
395
+ variableTypeMap;
396
+ constructor(writer, prev) {
397
+ this.writer = writer;
398
+ this.variableTypeMap = prev?.variableTypeMap ?? /* @__PURE__ */ new Map();
399
+ }
400
+ acceptSelection(sel) {
401
+ const t = this.writer.text.bind(this.writer);
402
+ const runtime = runtimeOf(sel);
403
+ for (const field of runtime.fieldMap.values()) {
404
+ const name = field.name;
405
+ const children = field.childSelections;
406
+ if (name.startsWith("... ") && !name.startsWith("... on ") && children?.length) {
407
+ const baseName = name.substring(3).trim();
408
+ for (const c of children) t(`... ${this.resolveFragmentRuntimeName(baseName, c)}\n`);
409
+ continue;
410
+ }
411
+ if (name !== "...") {
412
+ const alias = field.fieldOptionsValue?.alias;
413
+ if (alias && alias !== name) t(`${alias}: `);
414
+ t(name);
415
+ if (field.argGraphQLTypes) {
416
+ const meta = sel._enumInputMetadata;
417
+ this.acceptArgs(field.args, field.argGraphQLTypes, meta);
418
+ }
419
+ this.acceptDirectives(field.fieldOptionsValue?.directives);
420
+ }
421
+ if (children?.length) if (name === "...") for (const c of children) this.acceptSelection(c);
422
+ else {
423
+ t(" ");
424
+ this.writer.scope({
425
+ type: "block",
426
+ multiLines: true
427
+ }, () => {
428
+ for (const c of children) this.acceptSelection(c);
429
+ });
430
+ }
431
+ t("\n");
432
+ }
433
+ }
434
+ resolveFragmentRuntimeName(baseName, selection) {
435
+ if (this.namedFragmentMap.get(baseName) === selection) return baseName;
436
+ let byBaseName = this.fragmentRuntimeNameMap.get(selection);
437
+ if (!byBaseName) {
438
+ byBaseName = /* @__PURE__ */ new Map();
439
+ this.fragmentRuntimeNameMap.set(selection, byBaseName);
440
+ }
441
+ const existing = byBaseName.get(baseName);
442
+ if (existing) return existing;
443
+ let runtimeName = baseName;
444
+ const occupied = this.namedFragmentMap.get(runtimeName);
445
+ if (occupied && occupied !== selection) {
446
+ let idx = this.fragmentNameCounter.get(baseName) ?? 1;
447
+ while (this.namedFragmentMap.has(`${baseName}_${idx}`)) idx += 1;
448
+ this.fragmentNameCounter.set(baseName, idx + 1);
449
+ runtimeName = `${baseName}_${idx}`;
450
+ }
451
+ this.namedFragmentMap.set(runtimeName, selection);
452
+ byBaseName.set(baseName, runtimeName);
453
+ return runtimeName;
454
+ }
455
+ acceptDirectives(directives) {
456
+ if (!directives) return;
457
+ for (const [directive, args] of directives) {
458
+ this.writer.text(`\n@${directive}`);
459
+ this.acceptArgs(args);
460
+ }
461
+ }
462
+ acceptArgs(args, argGraphQLTypeMap, enumInputMetadata) {
463
+ if (!args) return;
464
+ const t = this.writer.text.bind(this.writer);
465
+ let hasField;
466
+ if (argGraphQLTypeMap) {
467
+ hasField = false;
468
+ for (const argName in args) if (argGraphQLTypeMap.get(argName) !== void 0) {
469
+ hasField = true;
470
+ break;
471
+ } else console.warn(`Unexpected argument: ${argName}`);
472
+ } else hasField = Object.keys(args).length !== 0;
473
+ if (hasField) this.writer.scope({
474
+ type: "arguments",
475
+ multiLines: isMultilineJSON(args)
476
+ }, () => {
477
+ for (const argName in args) {
478
+ this.writer.separator();
479
+ const arg = args[argName];
480
+ if (argGraphQLTypeMap) {
481
+ const typeName = argGraphQLTypeMap.get(argName);
482
+ if (typeName !== void 0) if (arg?.[__marker]) {
483
+ const ref = arg;
484
+ this.registerVariableType(ref, typeName, false, "field argument");
485
+ t(`${argName}: $${ref.name}`);
486
+ } else {
487
+ t(`${argName}: `);
488
+ this.acceptLiteral(arg, SerializeContext.enumMetaType(enumInputMetadata, typeName), typeName);
489
+ }
490
+ else throw new Error(`Unknown argument '${argName}'`);
491
+ } else if (arg?.[__marker]) {
492
+ const ref = arg;
493
+ if (!ref.graphqlTypeName) throw new Error(`Directive argument '${ref.name}' requires graphqlTypeName`);
494
+ this.registerVariableType(ref, ref.graphqlTypeName, false, "directive argument");
495
+ t(`${argName}: $${ref.name}`);
496
+ } else {
497
+ t(`${argName}: `);
498
+ this.acceptLiteral(arg, void 0, void 0);
499
+ }
500
+ }
501
+ });
502
+ }
503
+ acceptLiteral(value, metaType, graphqlTypeName) {
504
+ const t = this.writer.text.bind(this.writer);
505
+ if (value == null) {
506
+ t("null");
507
+ return;
508
+ }
509
+ if (typeof value === "number") {
510
+ t(value.toString());
511
+ return;
512
+ }
513
+ if (typeof value === "string") {
514
+ t(metaType ? value : JSON.stringify(value));
515
+ return;
516
+ }
517
+ if (typeof value === "boolean") {
518
+ t(value ? "true" : "false");
519
+ return;
520
+ }
521
+ if (value?.[__marker]) {
522
+ const ref = value;
523
+ if (!graphqlTypeName && !ref.graphqlTypeName) throw new Error(`Argument '${ref.name}' nested type cannot be inferred; provide graphqlTypeName`);
524
+ this.registerVariableType(ref, graphqlTypeName, true, "nested argument");
525
+ t(`$${ref.name}`);
526
+ return;
527
+ }
528
+ if (value instanceof StringValue) {
529
+ t(value.quotationMarks ? JSON.stringify(value.value) : value.value);
530
+ return;
531
+ }
532
+ if (Array.isArray(value) || value instanceof Set) {
533
+ const elementGraphQLTypeName = SerializeContext.elementTypeName(graphqlTypeName);
534
+ this.writer.scope({ type: "array" }, () => {
535
+ for (const e of value) {
536
+ this.writer.separator(", ");
537
+ this.acceptLiteral(e, metaType, elementGraphQLTypeName);
538
+ }
539
+ });
540
+ } else if (value instanceof Map) this.writer.scope({ type: "block" }, () => {
541
+ for (const [k, v] of value) {
542
+ this.writer.separator(", ");
543
+ this.writer.text(k);
544
+ t(": ");
545
+ this.acceptLiteral(v, metaType?.fields?.get(k), metaType?.fieldGraphQLTypeMap?.get(k));
546
+ }
547
+ });
548
+ else if (typeof value === "object") this.writer.scope({ type: "block" }, () => {
549
+ for (const k in value) {
550
+ this.writer.separator(", ");
551
+ this.writer.text(k);
552
+ t(": ");
553
+ this.acceptLiteral(value[k], metaType?.fields?.get(k), metaType?.fieldGraphQLTypeMap?.get(k));
554
+ }
555
+ });
556
+ }
557
+ registerVariableType(ref, expectedTypeName, allowImplicitFromRef = false, context = "argument") {
558
+ const typeName = expectedTypeName ?? (allowImplicitFromRef ? ref.graphqlTypeName : void 0);
559
+ if (!typeName) throw new Error(`Directive argument '${ref.name}' requires graphqlTypeName`);
560
+ if (ref.graphqlTypeName && ref.graphqlTypeName !== typeName) throw new Error(`Argument '${ref.name}' type conflict: '${typeName}' vs ParameterRef '${ref.graphqlTypeName}' (${context})`);
561
+ const existing = this.variableTypeMap.get(ref.name);
562
+ if (existing && existing !== typeName) throw new Error(`Argument '${ref.name}' type conflict: '${existing}' vs '${typeName}' (${context})`);
563
+ this.variableTypeMap.set(ref.name, typeName);
564
+ }
565
+ static enumMetaType(meta, typeName) {
566
+ if (!meta || !typeName) return void 0;
567
+ return meta.get(typeName.split(/\[|\]|!/).join(""));
568
+ }
569
+ static elementTypeName(typeName) {
570
+ if (!typeName) return void 0;
571
+ let normalized = typeName.trim();
572
+ if (normalized.endsWith("!")) normalized = normalized.slice(0, -1).trim();
573
+ if (normalized.startsWith("[") && normalized.endsWith("]")) return normalized.slice(1, -1).trim();
574
+ return normalized;
575
+ }
576
+ };
577
+ const isMultilineJSON = (obj) => {
578
+ let size = 0;
579
+ if (Array.isArray(obj)) for (const v of obj) {
580
+ if (typeof v === "object" && !v?.[__marker]) return true;
581
+ if (++size > 2) return true;
582
+ }
583
+ else if (typeof obj === "object" && obj !== null) for (const k of Reflect.ownKeys(obj)) {
584
+ const v = obj[k];
585
+ if (typeof v === "object" && !v?.[__marker]) return true;
586
+ if (++size > 2) return true;
587
+ }
588
+ return false;
589
+ };
590
+
591
+ //#endregion
592
+ //#region src/runtime/field-options.ts
593
+ var FieldOptions = class FieldOptions {
594
+ _value;
595
+ constructor(_prev, _alias, _directive, _directiveArgs) {
596
+ this._prev = _prev;
597
+ this._alias = _alias;
598
+ this._directive = _directive;
599
+ this._directiveArgs = _directiveArgs;
600
+ }
601
+ alias(alias) {
602
+ return new FieldOptions(this, alias);
603
+ }
604
+ directive(directive, args) {
605
+ if (directive.startsWith("@")) throw new Error("directive name should not start with '@', it will be prepended automatically");
606
+ return new FieldOptions(this, void 0, directive, args);
607
+ }
608
+ get value() {
609
+ return this._value ??= this._buildValue();
610
+ }
611
+ _buildValue() {
612
+ let alias;
613
+ const directives = /* @__PURE__ */ new Map();
614
+ for (let node = this; node; node = node._prev) {
615
+ if (node._alias !== void 0 && alias === void 0) alias = node._alias;
616
+ if (node._directive !== void 0 && !directives.has(node._directive)) {
617
+ const args = node._directiveArgs;
618
+ directives.set(node._directive, args && Object.keys(args).length !== 0 ? args : void 0);
619
+ }
620
+ }
621
+ return {
622
+ alias,
623
+ directives
624
+ };
625
+ }
626
+ };
627
+ const createFieldOptions = () => {
628
+ return new FieldOptions();
629
+ };
630
+
631
+ //#endregion
632
+ //#region src/runtime/enum-metadata.ts
633
+ /**
634
+ * 元数据构建器
635
+ *
636
+ * codegen 生成的代码会调用此构建器来注册 schema 中的 enum/input 类型:
637
+ * ```ts
638
+ * const builder = new EnumInputMetadataBuilder();
639
+ * builder.add("Status"); // enum
640
+ * builder.add("CreateInput", [{name: "status", typeName: "Status"}]); // input
641
+ * export const ENUM_INPUT_METADATA = builder.build();
642
+ * ```
643
+ */
644
+ var EnumInputMetadataBuilder = class EnumInputMetadataBuilder {
645
+ typeMap = /* @__PURE__ */ new Map();
646
+ static BUILTIN_SCALARS = new Set([
647
+ "ID",
648
+ "String",
649
+ "Int",
650
+ "Float",
651
+ "Boolean"
652
+ ]);
653
+ /** 注册一个枚举/输入类型。无 fields 参数表示 ENUM,有则表示 INPUT */
654
+ add(name, fields) {
655
+ this.typeMap.set(name, fields);
656
+ return this;
657
+ }
658
+ /** 构建不可变的元数据表 */
659
+ build() {
660
+ const result = /* @__PURE__ */ new Map();
661
+ const resolve = (name) => {
662
+ const existing = result.get(name);
663
+ if (existing) return existing;
664
+ if (!this.typeMap.has(name)) throw new Error(`Unknown enum/input type: '${name}'`);
665
+ const rawFields = this.typeMap.get(name);
666
+ let fields;
667
+ let fieldGraphQLTypeMap;
668
+ if (rawFields) {
669
+ fields = /* @__PURE__ */ new Map();
670
+ fieldGraphQLTypeMap = /* @__PURE__ */ new Map();
671
+ for (const { name: fieldName, typeName, graphqlTypeName, isLeaf } of rawFields) {
672
+ let resolved;
673
+ if (!(isLeaf || EnumInputMetadataBuilder.BUILTIN_SCALARS.has(typeName))) {
674
+ if (!this.typeMap.has(typeName)) throw new Error(`Unknown enum/input type: '${typeName}'`);
675
+ resolved = resolve(typeName);
676
+ }
677
+ fields.set(fieldName, resolved);
678
+ if (graphqlTypeName) fieldGraphQLTypeMap.set(fieldName, graphqlTypeName);
679
+ }
680
+ }
681
+ const metaType = {
682
+ type: rawFields === void 0 ? "ENUM" : "INPUT",
683
+ name,
684
+ fields,
685
+ fieldGraphQLTypeMap
686
+ };
687
+ result.set(name, metaType);
688
+ return metaType;
689
+ };
690
+ for (const name of this.typeMap.keys()) resolve(name);
691
+ return result;
692
+ }
693
+ };
694
+
695
+ //#endregion
696
+ //#region src/runtime/proxy.ts
697
+ const createSelection = (schemaType, enumInputMetadata, unionEntityTypes) => {
698
+ return new Proxy(new SelectionImpl([
699
+ schemaType,
700
+ enumInputMetadata,
701
+ unionEntityTypes
702
+ ], false, ""), proxyHandler(schemaType));
703
+ };
704
+ const BUILT_DIRECTIVES = new Set([
705
+ "$omit",
706
+ "$alias",
707
+ "$directive",
708
+ "$include",
709
+ "$skip",
710
+ "$on",
711
+ "$use"
712
+ ]);
713
+ const resolveValueOrThunk = (value) => {
714
+ return typeof value === "function" ? value() : value;
715
+ };
716
+ const createChildSelectionProxy = (schemaType, enumInputMetadata) => {
717
+ return new Proxy(new SelectionImpl([
718
+ schemaType,
719
+ enumInputMetadata,
720
+ void 0
721
+ ], false, ""), proxyHandler(schemaType));
722
+ };
723
+ const buildRequiredArgs = (argTypeMap) => {
724
+ if (!argTypeMap.size) return void 0;
725
+ const requiredArgNames = Array.from(argTypeMap.entries()).filter(([, type]) => type.endsWith("!")).map(([name]) => name);
726
+ if (!requiredArgNames.length) return void 0;
727
+ const args = {};
728
+ for (const name of requiredArgNames) args[name] = ParameterRef.of(name);
729
+ return args;
730
+ };
731
+ const resolveAssociationTarget = (fieldName, fieldTargetTypeName, ownerTypeName) => {
732
+ if (!fieldTargetTypeName) throw new Error(`Field "${fieldName}" has no target type`);
733
+ const targetSchemaType = resolveRegisteredSchemaType(fieldTargetTypeName);
734
+ if (!targetSchemaType) throw new Error(`Cannot resolve schema type "${fieldTargetTypeName}" for field "${fieldName}" on "${ownerTypeName}"`);
735
+ return targetSchemaType;
736
+ };
737
+ const parseAssociationArgs = (argArray) => {
738
+ let args;
739
+ let childSelectionFactory;
740
+ let childSelection;
741
+ for (const arg of argArray) if (arg instanceof SelectionImpl) childSelection = arg;
742
+ else if (typeof arg === "function") childSelectionFactory = arg;
743
+ else args = arg;
744
+ return {
745
+ args,
746
+ childSelectionFactory,
747
+ childSelection
748
+ };
749
+ };
750
+ const parseMethodArgs = (argArray) => {
751
+ let args;
752
+ let child;
753
+ let optionsValue;
754
+ for (const arg of argArray) if (arg instanceof SelectionImpl) child = arg;
755
+ else if (typeof arg === "function") optionsValue = arg(createFieldOptions()).value;
756
+ else args = arg;
757
+ return {
758
+ args,
759
+ child,
760
+ optionsValue
761
+ };
762
+ };
763
+ const findLastFieldSelection = (selection, lastField) => {
764
+ const byKey = selection.fieldMap.get(lastField);
765
+ if (byKey) return byKey;
766
+ const byName = selection.findFieldsByName(lastField);
767
+ return byName.length ? byName[0] : void 0;
768
+ };
769
+ const rewriteLastFieldWithOptions = (selection, lastField, optionsValue) => {
770
+ const existing = findLastFieldSelection(selection, lastField);
771
+ let current = selection.removeField(lastField);
772
+ current = current.addField(lastField, existing?.args, existing?.childSelections?.[0], optionsValue);
773
+ return current;
774
+ };
775
+ const mergeLastFieldDirective = (selection, lastField, directiveName, directiveArgs) => {
776
+ const existing = findLastFieldSelection(selection, lastField);
777
+ const directives = new Map(existing?.fieldOptionsValue?.directives ?? []);
778
+ directives.set(directiveName, directiveArgs);
779
+ return rewriteLastFieldWithOptions(selection, lastField, {
780
+ alias: existing?.fieldOptionsValue?.alias,
781
+ directives
782
+ });
783
+ };
784
+ const proxyHandler = (schemaType) => {
785
+ const handler = { get: (target, p, _receiver) => {
786
+ if (p === "schemaType") return schemaType;
787
+ if (typeof p === "string") {
788
+ if (BUILT_DIRECTIVES.has(p)) return new Proxy(DUMMY, methodHandler(target, handler, p));
789
+ else if (schemaType.fields.has(p)) {
790
+ const field = schemaType.fields.get(p);
791
+ if (field.isAssociation || field.targetTypeName !== void 0) return (...argArray) => {
792
+ const targetSchemaType = resolveAssociationTarget(p, field.targetTypeName, schemaType.name);
793
+ let { args, childSelectionFactory, childSelection } = parseAssociationArgs(argArray);
794
+ if (childSelectionFactory) childSelection = childSelectionFactory(createChildSelectionProxy(targetSchemaType, target._enumInputMetadata));
795
+ if (!childSelection) throw new Error(`Field "${p}" requires a child selection`);
796
+ if (!args) args = buildRequiredArgs(field.argGraphQLTypeMap);
797
+ return new Proxy(target.addField(p, args, childSelection), handler);
798
+ };
799
+ if (field.isFunction) return new Proxy(DUMMY, methodHandler(target, handler, p));
800
+ return new Proxy(target.addField(p), handler);
801
+ }
802
+ }
803
+ return Reflect.get(target, p, target);
804
+ } };
805
+ return handler;
806
+ };
807
+ const methodHandler = (targetSelection, handler, field) => {
808
+ return { apply: (_1, _2, argArray) => {
809
+ if (field === "$on") {
810
+ let childSelection;
811
+ if (typeof argArray[0] === "string" && typeof argArray[1] === "function") {
812
+ const targetTypeName = argArray[0];
813
+ const builder = argArray[1];
814
+ const targetSchemaType = resolveRegisteredSchemaType(targetTypeName);
815
+ if (!targetSchemaType) throw new Error(`Cannot resolve schema type "${targetTypeName}" for $on`);
816
+ childSelection = builder(createChildSelectionProxy(targetSchemaType, targetSelection._enumInputMetadata));
817
+ } else if (typeof argArray[0] === "function") {
818
+ const builder = argArray[0];
819
+ const targetSchemaType = targetSelection.schemaType;
820
+ childSelection = builder(createChildSelectionProxy(targetSchemaType, targetSelection._enumInputMetadata));
821
+ } else throw new Error("$on requires a builder or (typeName, builder) arguments");
822
+ let parent = targetSelection;
823
+ if (targetSelection.schemaType.name !== runtimeOf(childSelection).schemaType.name) parent = targetSelection.addField("__typename");
824
+ return new Proxy(parent.addEmbeddable(childSelection, void 0), handler);
825
+ }
826
+ if (field === "$use") {
827
+ const fragment = resolveValueOrThunk(argArray[0]);
828
+ if (!fragment || !fragment[__fragment_spread]) throw new Error("$use requires a fragment created by fragment$");
829
+ const childSelection = fragment.selection;
830
+ let parent = targetSelection;
831
+ if (targetSelection.schemaType.name !== runtimeOf(childSelection).schemaType.name) parent = targetSelection.addField("__typename");
832
+ return new Proxy(parent.addEmbeddable(childSelection, fragment.name), handler);
833
+ }
834
+ if (field === "$omit") {
835
+ let current = targetSelection;
836
+ for (const fieldName of argArray) if (typeof fieldName === "string") current = current.removeField(fieldName);
837
+ return new Proxy(current, handler);
838
+ }
839
+ if (field === "$alias") {
840
+ const alias = argArray[0];
841
+ const lastField = targetSelection.lastField;
842
+ if (!lastField) throw new Error("$alias requires a preceding field selection");
843
+ const existing = findLastFieldSelection(targetSelection, lastField);
844
+ const current = rewriteLastFieldWithOptions(targetSelection, lastField, {
845
+ alias,
846
+ directives: new Map(existing?.fieldOptionsValue?.directives ?? [])
847
+ });
848
+ return new Proxy(current, handler);
849
+ }
850
+ if (field === "$directive") {
851
+ const lastField = targetSelection.lastField;
852
+ if (!lastField) return new Proxy(targetSelection.addDirective(argArray[0], argArray[1]), handler);
853
+ const current = mergeLastFieldDirective(targetSelection, lastField, argArray[0], argArray[1]);
854
+ return new Proxy(current, handler);
855
+ }
856
+ if (field === "$include" || field === "$skip") {
857
+ const directiveName = field === "$include" ? "include" : "skip";
858
+ const directiveArgs = { if: argArray[0] };
859
+ const lastField = targetSelection.lastField;
860
+ if (!lastField) return new Proxy(targetSelection.addDirective(directiveName, directiveArgs), handler);
861
+ const current = mergeLastFieldDirective(targetSelection, lastField, directiveName, directiveArgs);
862
+ return new Proxy(current, handler);
863
+ }
864
+ let { args, child, optionsValue } = parseMethodArgs(argArray);
865
+ if (!args) {
866
+ const argMap = targetSelection.schemaType.ownFields.get(field)?.argGraphQLTypeMap;
867
+ args = argMap ? buildRequiredArgs(argMap) : void 0;
868
+ }
869
+ return new Proxy(targetSelection.addField(field, args, child, optionsValue), handler);
870
+ } };
871
+ };
872
+ const DUMMY = () => {};
873
+ const SELECTION_TARGET = new SelectionImpl([
874
+ createSchemaType("Any", "OBJECT", [], []),
875
+ new EnumInputMetadataBuilder().build(),
876
+ void 0
877
+ ], false, "");
878
+
879
+ //#endregion
880
+ //#region src/runtime/cyrb53.ts
881
+ const cyrb53 = (str, seed = 0) => {
882
+ let h1 = 3735928559 ^ seed;
883
+ let h2 = 1103547991 ^ seed;
884
+ for (let i = 0; i < str.length; i++) {
885
+ const ch = str.charCodeAt(i);
886
+ h1 = Math.imul(h1 ^ ch, 2654435761);
887
+ h2 = Math.imul(h2 ^ ch, 1597334677);
888
+ }
889
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
890
+ h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
891
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
892
+ h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
893
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
894
+ };
895
+
896
+ //#endregion
897
+ exports.EnumInputMetadataBuilder = EnumInputMetadataBuilder;
898
+ exports.FragmentRef = FragmentRef;
899
+ exports.FragmentSpread = FragmentSpread;
900
+ exports.ParameterRef = ParameterRef;
901
+ exports.SelectionNode = SelectionImpl;
902
+ exports.StringValue = StringValue;
903
+ exports.TextBuilder = TextBuilder;
904
+ exports.__parameterRefMarker = __marker;
905
+ exports.createSchemaType = createSchemaType;
906
+ exports.createSelection = createSelection;
907
+ exports.cyrb53 = cyrb53;
908
+ exports.registerSchemaTypeFactory = registerSchemaTypeFactory;
909
+ exports.resolveRegisteredSchemaType = resolveRegisteredSchemaType;
910
+ exports.runtimeOf = runtimeOf;
911
+ exports.withOperationName = withOperationName;