@ptdgrp/typedgql 1.0.0-beta.15 → 1.0.0-beta.20

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