@soda-gql/tools 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +72 -0
  2. package/codegen.d.ts +2 -0
  3. package/codegen.js +1 -0
  4. package/dist/bin.cjs +15509 -0
  5. package/dist/bin.cjs.map +1 -0
  6. package/dist/bin.d.cts +839 -0
  7. package/dist/bin.d.cts.map +1 -0
  8. package/dist/chunk-BrXtsOCC.cjs +41 -0
  9. package/dist/codegen.cjs +4704 -0
  10. package/dist/codegen.cjs.map +1 -0
  11. package/dist/codegen.d.cts +416 -0
  12. package/dist/codegen.d.cts.map +1 -0
  13. package/dist/codegen.d.mts +416 -0
  14. package/dist/codegen.d.mts.map +1 -0
  15. package/dist/codegen.mjs +4712 -0
  16. package/dist/codegen.mjs.map +1 -0
  17. package/dist/formatter-Glj5a663.cjs +510 -0
  18. package/dist/formatter-Glj5a663.cjs.map +1 -0
  19. package/dist/formatter.cjs +509 -0
  20. package/dist/formatter.cjs.map +1 -0
  21. package/dist/formatter.d.cts +33 -0
  22. package/dist/formatter.d.cts.map +1 -0
  23. package/dist/formatter.d.mts +33 -0
  24. package/dist/formatter.d.mts.map +1 -0
  25. package/dist/formatter.mjs +507 -0
  26. package/dist/formatter.mjs.map +1 -0
  27. package/dist/index.cjs +13 -0
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.cts +11 -0
  30. package/dist/index.d.cts.map +1 -0
  31. package/dist/index.d.mts +11 -0
  32. package/dist/index.d.mts.map +1 -0
  33. package/dist/index.mjs +12 -0
  34. package/dist/index.mjs.map +1 -0
  35. package/dist/typegen.cjs +864 -0
  36. package/dist/typegen.cjs.map +1 -0
  37. package/dist/typegen.d.cts +205 -0
  38. package/dist/typegen.d.cts.map +1 -0
  39. package/dist/typegen.d.mts +205 -0
  40. package/dist/typegen.d.mts.map +1 -0
  41. package/dist/typegen.mjs +859 -0
  42. package/dist/typegen.mjs.map +1 -0
  43. package/formatter.d.ts +2 -0
  44. package/formatter.js +1 -0
  45. package/index.d.ts +2 -0
  46. package/index.js +1 -0
  47. package/package.json +102 -0
  48. package/typegen.d.ts +2 -0
  49. package/typegen.js +1 -0
@@ -0,0 +1,509 @@
1
+ const require_chunk = require('./chunk-BrXtsOCC.cjs');
2
+ let neverthrow = require("neverthrow");
3
+ let node_crypto = require("node:crypto");
4
+ let node_module = require("node:module");
5
+ let __soda_gql_common_template_extraction = require("@soda-gql/common/template-extraction");
6
+ let __soda_gql_common_utils = require("@soda-gql/common/utils");
7
+ let __swc_core = require("@swc/core");
8
+
9
+ //#region packages/tools/src/formatter/detection.ts
10
+ /**
11
+ * Check if an expression is a reference to gql
12
+ * Handles: gql, namespace.gql
13
+ */
14
+ const isGqlReference = (node, gqlIdentifiers) => {
15
+ const unwrapped = node.type === "TsNonNullExpression" ? node.expression : node;
16
+ if (unwrapped.type === "Identifier") {
17
+ return gqlIdentifiers.has(unwrapped.value);
18
+ }
19
+ if (unwrapped.type === "MemberExpression" && unwrapped.property.type === "Identifier" && unwrapped.property.value === "gql") {
20
+ return true;
21
+ }
22
+ return false;
23
+ };
24
+ /**
25
+ * Check if a call expression is a gql definition call
26
+ * Handles: gql.default(...), gql.model(...), gql.schemaName(...) (multi-schema)
27
+ */
28
+ const isGqlDefinitionCall = (node, gqlIdentifiers) => {
29
+ if (node.callee.type !== "MemberExpression") return false;
30
+ const { object } = node.callee;
31
+ if (!isGqlReference(object, gqlIdentifiers)) return false;
32
+ const firstArg = node.arguments[0];
33
+ if (!firstArg || firstArg.expression.type !== "ArrowFunctionExpression" && firstArg.expression.type !== "FunctionExpression") return false;
34
+ return true;
35
+ };
36
+ /**
37
+ * Check if an object expression is a field selection object
38
+ * Field selection objects are returned from arrow functions with ({ f }) or ({ f, $ }) parameter
39
+ */
40
+ const isFieldSelectionObject = (object, parent) => {
41
+ let bodyObject = null;
42
+ if (parent.body.type === "ObjectExpression") {
43
+ bodyObject = parent.body;
44
+ } else if (parent.body.type === "ParenthesisExpression") {
45
+ const inner = parent.body.expression;
46
+ if (inner.type === "ObjectExpression") {
47
+ bodyObject = inner;
48
+ }
49
+ }
50
+ if (!bodyObject) return false;
51
+ if (bodyObject.span.start !== object.span.start) return false;
52
+ const param = parent.params[0];
53
+ if (!param || param.type !== "ObjectPattern") return false;
54
+ return param.properties.some((p) => {
55
+ if (p.type === "KeyValuePatternProperty" && p.key.type === "Identifier") {
56
+ return p.key.value === "f";
57
+ }
58
+ if (p.type === "AssignmentPatternProperty" && p.key.type === "Identifier") {
59
+ return p.key.value === "f";
60
+ }
61
+ return false;
62
+ });
63
+ };
64
+ /**
65
+ * Collect gql identifiers from import declarations
66
+ */
67
+ const collectGqlIdentifiers = (module$1) => {
68
+ const gqlIdentifiers = new Set();
69
+ for (const item of module$1.body) {
70
+ if (item.type !== "ImportDeclaration") continue;
71
+ for (const specifier of item.specifiers) {
72
+ if (specifier.type === "ImportSpecifier") {
73
+ const imported = specifier.imported?.value ?? specifier.local.value;
74
+ if (imported === "gql") {
75
+ gqlIdentifiers.add(specifier.local.value);
76
+ }
77
+ }
78
+ if (specifier.type === "ImportDefaultSpecifier") {
79
+ if (specifier.local.value === "gql") {
80
+ gqlIdentifiers.add(specifier.local.value);
81
+ }
82
+ }
83
+ if (specifier.type === "ImportNamespaceSpecifier") {}
84
+ }
85
+ }
86
+ return gqlIdentifiers;
87
+ };
88
+ /**
89
+ * Check if a call expression is a fragment definition call.
90
+ * Pattern: fragment.TypeName({ ... }) where `fragment` comes from gql factory destructuring.
91
+ */
92
+ const isFragmentDefinitionCall = (node, fragmentIdentifiers) => {
93
+ if (node.callee.type !== "MemberExpression") return false;
94
+ const { object } = node.callee;
95
+ if (object.type !== "Identifier") return false;
96
+ if (!fragmentIdentifiers.has(object.value)) return false;
97
+ const firstArg = node.arguments[0];
98
+ if (!firstArg || firstArg.expression.type !== "ObjectExpression") return false;
99
+ return true;
100
+ };
101
+ /**
102
+ * Check if an object expression already has a `key` property.
103
+ */
104
+ const hasKeyProperty = (obj) => {
105
+ return obj.properties.some((prop) => {
106
+ if (prop.type === "KeyValueProperty" && prop.key.type === "Identifier") {
107
+ return prop.key.value === "key";
108
+ }
109
+ return false;
110
+ });
111
+ };
112
+ /**
113
+ * Collect fragment identifiers from gql factory arrow function parameter.
114
+ * Looks for patterns like: ({ fragment }) => ... or ({ fragment: f }) => ...
115
+ */
116
+ const collectFragmentIdentifiers = (arrowFunction) => {
117
+ const fragmentIdentifiers = new Set();
118
+ const param = arrowFunction.params[0];
119
+ if (param?.type !== "ObjectPattern") return fragmentIdentifiers;
120
+ for (const p of param.properties) {
121
+ if (p.type === "KeyValuePatternProperty" && p.key.type === "Identifier" && p.key.value === "fragment") {
122
+ const localName = extractIdentifierName(p.value);
123
+ if (localName) fragmentIdentifiers.add(localName);
124
+ }
125
+ if (p.type === "AssignmentPatternProperty" && p.key.type === "Identifier" && p.key.value === "fragment") {
126
+ fragmentIdentifiers.add(p.key.value);
127
+ }
128
+ }
129
+ return fragmentIdentifiers;
130
+ };
131
+ /**
132
+ * Extract identifier name from a pattern node.
133
+ */
134
+ const extractIdentifierName = (pattern) => {
135
+ if (pattern.type === "Identifier") return pattern.value;
136
+ if (pattern.type === "BindingIdentifier") return pattern.value;
137
+ return null;
138
+ };
139
+
140
+ //#endregion
141
+ //#region packages/tools/src/formatter/insertion.ts
142
+ /**
143
+ * The newline string to insert after object opening brace
144
+ */
145
+ const NEWLINE_INSERTION = "\n";
146
+ /**
147
+ * Generate a random 8-character hex key for fragment identification.
148
+ * Uses Node.js crypto for cryptographically secure random bytes.
149
+ */
150
+ const generateFragmentKey = () => {
151
+ return (0, node_crypto.randomBytes)(4).toString("hex");
152
+ };
153
+ /**
154
+ * Create the key property insertion string.
155
+ *
156
+ * For single-line objects: returns ` key: "xxxxxxxx",\n`
157
+ * For multi-line objects (with indentation): returns `{indentation}key: "xxxxxxxx",\n`
158
+ * (the existing indentation before the next property is preserved)
159
+ *
160
+ * @param key - The hex key string
161
+ * @param indentation - Optional indentation string for multi-line objects
162
+ */
163
+ const createKeyInsertion = (key, indentation) => {
164
+ if (indentation !== undefined) {
165
+ return `${indentation}key: "${key}",\n`;
166
+ }
167
+ return ` key: "${key}",\n`;
168
+ };
169
+ /**
170
+ * Check if there's already a newline after the opening brace.
171
+ * Uses string inspection rather than AST.
172
+ *
173
+ * @param source - The source code string
174
+ * @param objectStartPos - The position of the `{` character in the source
175
+ */
176
+ const hasExistingNewline = (source, objectStartPos) => {
177
+ const pos = objectStartPos + 1;
178
+ const nextChar = source[pos];
179
+ return nextChar === "\n" || nextChar === "\r";
180
+ };
181
+ /**
182
+ * Detect the indentation used after an opening brace.
183
+ * Returns the whitespace string after the newline, or null if no newline.
184
+ *
185
+ * @param source - The source code string
186
+ * @param objectStartPos - The position of the `{` character
187
+ */
188
+ const detectIndentationAfterBrace = (source, objectStartPos) => {
189
+ const afterBrace = objectStartPos + 1;
190
+ const char = source[afterBrace];
191
+ if (char !== "\n" && char !== "\r") {
192
+ return null;
193
+ }
194
+ let pos = afterBrace + 1;
195
+ if (char === "\r" && source[pos] === "\n") {
196
+ pos++;
197
+ }
198
+ let indentation = "";
199
+ while (pos < source.length) {
200
+ const c = source[pos];
201
+ if (c === " " || c === " ") {
202
+ indentation += c;
203
+ pos++;
204
+ } else {
205
+ break;
206
+ }
207
+ }
208
+ return indentation;
209
+ };
210
+
211
+ //#endregion
212
+ //#region packages/tools/src/formatter/format.ts
213
+ const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
214
+ let _graphqlModule;
215
+ let _graphqlModuleError;
216
+ const getGraphqlModule = () => {
217
+ if (_graphqlModuleError) {
218
+ return (0, neverthrow.err)({
219
+ type: "FormatError",
220
+ code: "MISSING_DEPENDENCY",
221
+ message: "The \"graphql\" package is required for soda-gql formatter. Install it with: bun add graphql"
222
+ });
223
+ }
224
+ if (!_graphqlModule) {
225
+ try {
226
+ _graphqlModule = require$1("graphql");
227
+ } catch (cause) {
228
+ _graphqlModuleError = cause instanceof Error ? cause : new Error(String(cause));
229
+ return (0, neverthrow.err)({
230
+ type: "FormatError",
231
+ code: "MISSING_DEPENDENCY",
232
+ message: "The \"graphql\" package is required for soda-gql formatter. Install it with: bun add graphql",
233
+ cause
234
+ });
235
+ }
236
+ }
237
+ return (0, neverthrow.ok)(_graphqlModule);
238
+ };
239
+ /**
240
+ * Simple recursive AST traversal
241
+ */
242
+ const traverseNode = (node, context, gqlIdentifiers, onObjectExpression) => {
243
+ if (node.type === "CallExpression" && isGqlDefinitionCall(node, gqlIdentifiers)) {
244
+ const call = node;
245
+ const firstArg = call.arguments[0];
246
+ if (firstArg?.expression.type === "ArrowFunctionExpression") {
247
+ const arrow = firstArg.expression;
248
+ const fragmentIds = collectFragmentIdentifiers(arrow);
249
+ context = {
250
+ ...context,
251
+ insideGqlDefinition: true,
252
+ fragmentIdentifiers: new Set([...context.fragmentIdentifiers, ...fragmentIds])
253
+ };
254
+ } else {
255
+ context = {
256
+ ...context,
257
+ insideGqlDefinition: true
258
+ };
259
+ }
260
+ }
261
+ if (node.type === "CallExpression" && context.insideGqlDefinition && isFragmentDefinitionCall(node, context.fragmentIdentifiers)) {
262
+ const call = node;
263
+ const firstArg = call.arguments[0];
264
+ if (firstArg?.expression.type === "ObjectExpression" && context.currentArrowFunction) {
265
+ onObjectExpression(firstArg.expression, context.currentArrowFunction, { isFragmentConfig: true });
266
+ }
267
+ }
268
+ if (node.type === "ObjectExpression" && context.insideGqlDefinition && context.currentArrowFunction && isFieldSelectionObject(node, context.currentArrowFunction)) {
269
+ onObjectExpression(node, context.currentArrowFunction, { isFragmentConfig: false });
270
+ }
271
+ if (node.type === "CallExpression") {
272
+ const call = node;
273
+ traverseNode(call.callee, context, gqlIdentifiers, onObjectExpression);
274
+ for (const arg of call.arguments) {
275
+ traverseNode(arg.expression, context, gqlIdentifiers, onObjectExpression);
276
+ }
277
+ } else if (node.type === "ArrowFunctionExpression") {
278
+ const arrow = node;
279
+ const childContext = {
280
+ ...context,
281
+ currentArrowFunction: arrow
282
+ };
283
+ if (arrow.body.type !== "BlockStatement") {
284
+ traverseNode(arrow.body, childContext, gqlIdentifiers, onObjectExpression);
285
+ }
286
+ } else if (node.type === "ParenthesisExpression") {
287
+ const paren = node;
288
+ if (paren.expression) {
289
+ traverseNode(paren.expression, context, gqlIdentifiers, onObjectExpression);
290
+ }
291
+ } else if (node.type === "MemberExpression") {
292
+ const member = node;
293
+ traverseNode(member.object, context, gqlIdentifiers, onObjectExpression);
294
+ } else if (node.type === "ObjectExpression") {
295
+ const obj = node;
296
+ for (const prop of obj.properties) {
297
+ if (prop.type === "SpreadElement") {
298
+ traverseNode(prop.arguments, context, gqlIdentifiers, onObjectExpression);
299
+ } else if (prop.type === "KeyValueProperty") {
300
+ traverseNode(prop.value, context, gqlIdentifiers, onObjectExpression);
301
+ }
302
+ }
303
+ } else {
304
+ for (const value of Object.values(node)) {
305
+ if (Array.isArray(value)) {
306
+ for (const child of value) {
307
+ if (child && typeof child === "object" && "type" in child) {
308
+ traverseNode(child, context, gqlIdentifiers, onObjectExpression);
309
+ }
310
+ }
311
+ } else if (value && typeof value === "object" && "type" in value) {
312
+ traverseNode(value, context, gqlIdentifiers, onObjectExpression);
313
+ }
314
+ }
315
+ }
316
+ };
317
+ const traverse = (module$1, gqlIdentifiers, onObjectExpression) => {
318
+ const initialContext = {
319
+ insideGqlDefinition: false,
320
+ currentArrowFunction: null,
321
+ fragmentIdentifiers: new Set()
322
+ };
323
+ for (const statement of module$1.body) {
324
+ traverseNode(statement, initialContext, gqlIdentifiers, onObjectExpression);
325
+ }
326
+ };
327
+ /**
328
+ * Format soda-gql field selection objects by inserting newlines.
329
+ * Optionally injects fragment keys for anonymous fragments.
330
+ */
331
+ const format = (options) => {
332
+ const { sourceCode, filePath, injectFragmentKeys = false } = options;
333
+ let module$1;
334
+ try {
335
+ const program = (0, __swc_core.parseSync)(sourceCode, {
336
+ syntax: "typescript",
337
+ tsx: filePath?.endsWith(".tsx") ?? true,
338
+ target: "es2022",
339
+ decorators: false,
340
+ dynamicImport: true
341
+ });
342
+ if (program.type !== "Module") {
343
+ return (0, neverthrow.err)({
344
+ type: "FormatError",
345
+ code: "PARSE_ERROR",
346
+ message: `Not a module${filePath ? ` (${filePath})` : ""}`
347
+ });
348
+ }
349
+ module$1 = program;
350
+ } catch (cause) {
351
+ return (0, neverthrow.err)({
352
+ type: "FormatError",
353
+ code: "PARSE_ERROR",
354
+ message: `Failed to parse source code${filePath ? ` (${filePath})` : ""}`,
355
+ cause
356
+ });
357
+ }
358
+ const spanOffset = module$1.span.start;
359
+ const converter = (0, __soda_gql_common_utils.createSwcSpanConverter)(sourceCode);
360
+ const gqlIdentifiers = collectGqlIdentifiers(module$1);
361
+ if (gqlIdentifiers.size === 0) {
362
+ return (0, neverthrow.ok)({
363
+ modified: false,
364
+ sourceCode
365
+ });
366
+ }
367
+ const insertionPoints = [];
368
+ traverse(module$1, gqlIdentifiers, (object, _parent, callbackContext) => {
369
+ const objectStart = converter.byteOffsetToCharIndex(object.span.start - spanOffset);
370
+ if (callbackContext.isFragmentConfig && injectFragmentKeys && !hasKeyProperty(object)) {
371
+ const key = generateFragmentKey();
372
+ if (hasExistingNewline(sourceCode, objectStart)) {
373
+ const indentation = detectIndentationAfterBrace(sourceCode, objectStart) ?? "";
374
+ let insertPos = objectStart + 2;
375
+ if (sourceCode[objectStart + 1] === "\r") insertPos++;
376
+ insertionPoints.push({
377
+ position: insertPos,
378
+ content: createKeyInsertion(key, indentation)
379
+ });
380
+ } else {
381
+ insertionPoints.push({
382
+ position: objectStart + 1,
383
+ content: createKeyInsertion(key)
384
+ });
385
+ }
386
+ }
387
+ if (!callbackContext.isFragmentConfig && !hasExistingNewline(sourceCode, objectStart)) {
388
+ insertionPoints.push({
389
+ position: objectStart + 1,
390
+ content: NEWLINE_INSERTION
391
+ });
392
+ }
393
+ });
394
+ const graphqlResult = getGraphqlModule();
395
+ if (graphqlResult.isErr()) {
396
+ return (0, neverthrow.err)(graphqlResult.error);
397
+ }
398
+ const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;
399
+ const positionCtx = {
400
+ spanOffset,
401
+ converter
402
+ };
403
+ const templates = (0, __soda_gql_common_template_extraction.walkAndExtract)(module$1, gqlIdentifiers, positionCtx);
404
+ if (templates.length > 0) {
405
+ const defaultFormat = (source) => {
406
+ const ast = parseGraphql(source, { noLocation: false });
407
+ return printGraphql(ast);
408
+ };
409
+ const templateEdits = (0, __soda_gql_common_template_extraction.formatTemplatesInSource)(templates, sourceCode, defaultFormat);
410
+ for (const edit of templateEdits) {
411
+ insertionPoints.push({
412
+ position: edit.start,
413
+ content: edit.newText,
414
+ endPosition: edit.end
415
+ });
416
+ }
417
+ }
418
+ if (insertionPoints.length === 0) {
419
+ return (0, neverthrow.ok)({
420
+ modified: false,
421
+ sourceCode
422
+ });
423
+ }
424
+ const sortedPoints = [...insertionPoints].sort((a, b) => b.position - a.position);
425
+ let result = sourceCode;
426
+ for (const point of sortedPoints) {
427
+ const end = point.endPosition ?? point.position;
428
+ result = result.slice(0, point.position) + point.content + result.slice(end);
429
+ }
430
+ return (0, neverthrow.ok)({
431
+ modified: true,
432
+ sourceCode: result
433
+ });
434
+ };
435
+ /**
436
+ * Check if a file needs formatting (has unformatted field selections).
437
+ * Useful for pre-commit hooks or CI checks.
438
+ */
439
+ const needsFormat = (options) => {
440
+ const { sourceCode, filePath } = options;
441
+ let module$1;
442
+ try {
443
+ const program = (0, __swc_core.parseSync)(sourceCode, {
444
+ syntax: "typescript",
445
+ tsx: filePath?.endsWith(".tsx") ?? true,
446
+ target: "es2022",
447
+ decorators: false,
448
+ dynamicImport: true
449
+ });
450
+ if (program.type !== "Module") {
451
+ return (0, neverthrow.err)({
452
+ type: "FormatError",
453
+ code: "PARSE_ERROR",
454
+ message: `Not a module${filePath ? ` (${filePath})` : ""}`
455
+ });
456
+ }
457
+ module$1 = program;
458
+ } catch (cause) {
459
+ return (0, neverthrow.err)({
460
+ type: "FormatError",
461
+ code: "PARSE_ERROR",
462
+ message: `Failed to parse source code${filePath ? ` (${filePath})` : ""}`,
463
+ cause
464
+ });
465
+ }
466
+ const spanOffset = module$1.span.start;
467
+ const converter = (0, __soda_gql_common_utils.createSwcSpanConverter)(sourceCode);
468
+ const gqlIdentifiers = collectGqlIdentifiers(module$1);
469
+ if (gqlIdentifiers.size === 0) {
470
+ return (0, neverthrow.ok)(false);
471
+ }
472
+ let needsFormatting = false;
473
+ traverse(module$1, gqlIdentifiers, (object, _parent, callbackContext) => {
474
+ if (needsFormatting) return;
475
+ if (callbackContext.isFragmentConfig) return;
476
+ const objectStart = converter.byteOffsetToCharIndex(object.span.start - spanOffset);
477
+ if (!hasExistingNewline(sourceCode, objectStart)) {
478
+ needsFormatting = true;
479
+ }
480
+ });
481
+ if (!needsFormatting) {
482
+ const graphqlResult = getGraphqlModule();
483
+ if (graphqlResult.isErr()) {
484
+ return (0, neverthrow.err)(graphqlResult.error);
485
+ }
486
+ const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;
487
+ const positionCtx = {
488
+ spanOffset,
489
+ converter
490
+ };
491
+ const templates = (0, __soda_gql_common_template_extraction.walkAndExtract)(module$1, gqlIdentifiers, positionCtx);
492
+ if (templates.length > 0) {
493
+ const defaultFormat = (source) => {
494
+ const ast = parseGraphql(source, { noLocation: false });
495
+ return printGraphql(ast);
496
+ };
497
+ const templateEdits = (0, __soda_gql_common_template_extraction.formatTemplatesInSource)(templates, sourceCode, defaultFormat);
498
+ if (templateEdits.length > 0) {
499
+ needsFormatting = true;
500
+ }
501
+ }
502
+ }
503
+ return (0, neverthrow.ok)(needsFormatting);
504
+ };
505
+
506
+ //#endregion
507
+ exports.format = format;
508
+ exports.needsFormat = needsFormat;
509
+ //# sourceMappingURL=formatter.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter.cjs","names":["bodyObject: ObjectExpression | null","module","require","_graphqlModule: GraphqlModule | undefined","_graphqlModuleError: Error | undefined","initialContext: TraversalContext","module","module: Module","insertionPoints: InsertionPoint[]","positionCtx: PositionTrackingContext","defaultFormat: FormatGraphqlFn"],"sources":["../src/formatter/detection.ts","../src/formatter/insertion.ts","../src/formatter/format.ts"],"sourcesContent":["import type {\n ArrowFunctionExpression,\n CallExpression,\n Expression,\n Module,\n ObjectExpression,\n ObjectPatternProperty,\n Pattern,\n} from \"@swc/types\";\n\n/**\n * Check if an expression is a reference to gql\n * Handles: gql, namespace.gql\n */\nexport const isGqlReference = (node: Expression, gqlIdentifiers: ReadonlySet<string>): boolean => {\n // Unwrap TsNonNullExpression: gql! -> gql\n const unwrapped = node.type === \"TsNonNullExpression\" ? (node as { type: string; expression: Expression }).expression : node;\n if (unwrapped.type === \"Identifier\") {\n return gqlIdentifiers.has(unwrapped.value);\n }\n if (unwrapped.type === \"MemberExpression\" && unwrapped.property.type === \"Identifier\" && unwrapped.property.value === \"gql\") {\n return true;\n }\n return false;\n};\n\n/**\n * Check if a call expression is a gql definition call\n * Handles: gql.default(...), gql.model(...), gql.schemaName(...) (multi-schema)\n */\nexport const isGqlDefinitionCall = (node: CallExpression, gqlIdentifiers: ReadonlySet<string>): boolean => {\n if (node.callee.type !== \"MemberExpression\") return false;\n const { object } = node.callee;\n\n // Check object is a gql reference first\n if (!isGqlReference(object, gqlIdentifiers)) return false;\n\n // Verify first argument is an arrow function (factory pattern)\n // SWC's arguments are ExprOrSpread[], so access via .expression\n const firstArg = node.arguments[0];\n if (!firstArg || (firstArg.expression.type !== \"ArrowFunctionExpression\" && firstArg.expression.type !== \"FunctionExpression\"))\n return false;\n\n return true;\n};\n\n/**\n * Check if an object expression is a field selection object\n * Field selection objects are returned from arrow functions with ({ f }) or ({ f, $ }) parameter\n */\nexport const isFieldSelectionObject = (object: ObjectExpression, parent: ArrowFunctionExpression): boolean => {\n // The object must be the body of the arrow function\n // Handle both direct ObjectExpression and parenthesized ObjectExpression: `({ ... })`\n let bodyObject: ObjectExpression | null = null;\n\n if (parent.body.type === \"ObjectExpression\") {\n bodyObject = parent.body;\n } else if (parent.body.type === \"ParenthesisExpression\") {\n // Handle `({ f }) => ({ ...f.id() })` pattern where body is parenthesized\n const inner = parent.body.expression;\n if (inner.type === \"ObjectExpression\") {\n bodyObject = inner;\n }\n }\n\n if (!bodyObject) return false;\n if (bodyObject.span.start !== object.span.start) return false;\n\n // Check if first parameter has 'f' destructured\n const param = parent.params[0];\n if (!param || param.type !== \"ObjectPattern\") return false;\n\n return param.properties.some((p: ObjectPatternProperty) => {\n if (p.type === \"KeyValuePatternProperty\" && p.key.type === \"Identifier\") {\n return p.key.value === \"f\";\n }\n if (p.type === \"AssignmentPatternProperty\" && p.key.type === \"Identifier\") {\n return p.key.value === \"f\";\n }\n return false;\n });\n};\n\n/**\n * Collect gql identifiers from import declarations\n */\nexport const collectGqlIdentifiers = (module: Module): Set<string> => {\n const gqlIdentifiers = new Set<string>();\n\n for (const item of module.body) {\n if (item.type !== \"ImportDeclaration\") continue;\n\n for (const specifier of item.specifiers) {\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier.imported?.value ?? specifier.local.value;\n if (imported === \"gql\") {\n gqlIdentifiers.add(specifier.local.value);\n }\n }\n if (specifier.type === \"ImportDefaultSpecifier\") {\n // Check if default import might be gql\n if (specifier.local.value === \"gql\") {\n gqlIdentifiers.add(specifier.local.value);\n }\n }\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n // namespace import: import * as ns from \"...\"\n // Would need ns.gql pattern - handled by isGqlReference\n }\n }\n }\n\n return gqlIdentifiers;\n};\n\n/**\n * Check if a call expression is a fragment definition call.\n * Pattern: fragment.TypeName({ ... }) where `fragment` comes from gql factory destructuring.\n */\nexport const isFragmentDefinitionCall = (node: CallExpression, fragmentIdentifiers: ReadonlySet<string>): boolean => {\n if (node.callee.type !== \"MemberExpression\") return false;\n\n const { object } = node.callee;\n\n if (object.type !== \"Identifier\") return false;\n if (!fragmentIdentifiers.has(object.value)) return false;\n\n const firstArg = node.arguments[0];\n if (!firstArg || firstArg.expression.type !== \"ObjectExpression\") return false;\n\n return true;\n};\n\n/**\n * Check if an object expression already has a `key` property.\n */\nexport const hasKeyProperty = (obj: ObjectExpression): boolean => {\n return obj.properties.some((prop) => {\n if (prop.type === \"KeyValueProperty\" && prop.key.type === \"Identifier\") {\n return prop.key.value === \"key\";\n }\n return false;\n });\n};\n\n/**\n * Collect fragment identifiers from gql factory arrow function parameter.\n * Looks for patterns like: ({ fragment }) => ... or ({ fragment: f }) => ...\n */\nexport const collectFragmentIdentifiers = (arrowFunction: ArrowFunctionExpression): Set<string> => {\n const fragmentIdentifiers = new Set<string>();\n\n const param = arrowFunction.params[0];\n if (param?.type !== \"ObjectPattern\") return fragmentIdentifiers;\n\n for (const p of param.properties as ObjectPatternProperty[]) {\n if (p.type === \"KeyValuePatternProperty\" && p.key.type === \"Identifier\" && p.key.value === \"fragment\") {\n const localName = extractIdentifierName(p.value);\n if (localName) fragmentIdentifiers.add(localName);\n }\n if (p.type === \"AssignmentPatternProperty\" && p.key.type === \"Identifier\" && p.key.value === \"fragment\") {\n fragmentIdentifiers.add(p.key.value);\n }\n }\n\n return fragmentIdentifiers;\n};\n\n/**\n * Extract identifier name from a pattern node.\n */\nconst extractIdentifierName = (pattern: Pattern): string | null => {\n if (pattern.type === \"Identifier\") return pattern.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types\n if ((pattern as any).type === \"BindingIdentifier\") return (pattern as any).value;\n return null;\n};\n","import { randomBytes } from \"node:crypto\";\n\n/**\n * The newline string to insert after object opening brace\n */\nexport const NEWLINE_INSERTION = \"\\n\";\n\n/**\n * Generate a random 8-character hex key for fragment identification.\n * Uses Node.js crypto for cryptographically secure random bytes.\n */\nexport const generateFragmentKey = (): string => {\n return randomBytes(4).toString(\"hex\");\n};\n\n/**\n * Create the key property insertion string.\n *\n * For single-line objects: returns ` key: \"xxxxxxxx\",\\n`\n * For multi-line objects (with indentation): returns `{indentation}key: \"xxxxxxxx\",\\n`\n * (the existing indentation before the next property is preserved)\n *\n * @param key - The hex key string\n * @param indentation - Optional indentation string for multi-line objects\n */\nexport const createKeyInsertion = (key: string, indentation?: string): string => {\n if (indentation !== undefined) {\n // Multi-line: key goes on its own line with indentation\n // The next property's indentation is already in the source, so don't duplicate it\n return `${indentation}key: \"${key}\",\\n`;\n }\n // Single-line: space before key, newline after\n return ` key: \"${key}\",\\n`;\n};\n\n/**\n * Check if there's already a newline after the opening brace.\n * Uses string inspection rather than AST.\n *\n * @param source - The source code string\n * @param objectStartPos - The position of the `{` character in the source\n */\nexport const hasExistingNewline = (source: string, objectStartPos: number): boolean => {\n // Skip the `{` character\n const pos = objectStartPos + 1;\n\n // Check if next character is a newline\n const nextChar = source[pos];\n return nextChar === \"\\n\" || nextChar === \"\\r\";\n};\n\n/**\n * Detect the indentation used after an opening brace.\n * Returns the whitespace string after the newline, or null if no newline.\n *\n * @param source - The source code string\n * @param objectStartPos - The position of the `{` character\n */\nexport const detectIndentationAfterBrace = (source: string, objectStartPos: number): string | null => {\n const afterBrace = objectStartPos + 1;\n const char = source[afterBrace];\n\n // Check for newline (handles both \\n and \\r\\n)\n if (char !== \"\\n\" && char !== \"\\r\") {\n return null;\n }\n\n // Skip past the newline character(s)\n let pos = afterBrace + 1;\n if (char === \"\\r\" && source[pos] === \"\\n\") {\n pos++;\n }\n\n // Collect whitespace (indentation)\n let indentation = \"\";\n while (pos < source.length) {\n const c = source[pos];\n if (c === \" \" || c === \"\\t\") {\n indentation += c;\n pos++;\n } else {\n break;\n }\n }\n\n return indentation;\n};\n","import { createRequire } from \"node:module\";\nimport {\n type FormatGraphqlFn,\n formatTemplatesInSource,\n type PositionTrackingContext,\n walkAndExtract,\n} from \"@soda-gql/common/template-extraction\";\nimport { createSwcSpanConverter } from \"@soda-gql/common/utils\";\nimport { parseSync } from \"@swc/core\";\nimport type { ArrowFunctionExpression, CallExpression, Module, Node, ObjectExpression } from \"@swc/types\";\nimport { err, ok, type Result } from \"neverthrow\";\n\nconst require = createRequire(import.meta.url);\n\ntype GraphqlModule = {\n parse: (source: string, options?: { noLocation?: boolean }) => unknown;\n print: (ast: unknown) => string;\n};\n\nlet _graphqlModule: GraphqlModule | undefined;\nlet _graphqlModuleError: Error | undefined;\n\nconst getGraphqlModule = (): Result<GraphqlModule, FormatError> => {\n if (_graphqlModuleError) {\n return err({\n type: \"FormatError\",\n code: \"MISSING_DEPENDENCY\",\n message: 'The \"graphql\" package is required for soda-gql formatter. Install it with: bun add graphql',\n });\n }\n if (!_graphqlModule) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n _graphqlModule = require(\"graphql\") as GraphqlModule;\n } catch (cause) {\n _graphqlModuleError = cause instanceof Error ? cause : new Error(String(cause));\n return err({\n type: \"FormatError\",\n code: \"MISSING_DEPENDENCY\",\n message: 'The \"graphql\" package is required for soda-gql formatter. Install it with: bun add graphql',\n cause,\n });\n }\n }\n return ok(_graphqlModule);\n};\n\nimport {\n collectFragmentIdentifiers,\n collectGqlIdentifiers,\n hasKeyProperty,\n isFieldSelectionObject,\n isFragmentDefinitionCall,\n isGqlDefinitionCall,\n} from \"./detection\";\nimport {\n createKeyInsertion,\n detectIndentationAfterBrace,\n generateFragmentKey,\n hasExistingNewline,\n NEWLINE_INSERTION,\n} from \"./insertion\";\nimport type { FormatError, FormatOptions, FormatResult } from \"./types\";\n\ntype InsertionPoint = {\n readonly position: number;\n readonly content: string;\n readonly endPosition?: number;\n};\n\ntype TraversalContext = {\n insideGqlDefinition: boolean;\n currentArrowFunction: ArrowFunctionExpression | null;\n fragmentIdentifiers: ReadonlySet<string>;\n};\n\ntype TraversalCallbackContext = {\n readonly isFragmentConfig: boolean;\n};\n\ntype TraversalCallback = (\n object: ObjectExpression,\n parent: ArrowFunctionExpression,\n callbackContext: TraversalCallbackContext,\n) => void;\n\n/**\n * Simple recursive AST traversal\n */\nconst traverseNode = (\n node: Node,\n context: TraversalContext,\n gqlIdentifiers: ReadonlySet<string>,\n onObjectExpression: TraversalCallback,\n): void => {\n // Check for gql definition call entry and collect fragment identifiers\n if (node.type === \"CallExpression\" && isGqlDefinitionCall(node as CallExpression, gqlIdentifiers)) {\n const call = node as CallExpression;\n const firstArg = call.arguments[0];\n if (firstArg?.expression.type === \"ArrowFunctionExpression\") {\n const arrow = firstArg.expression as ArrowFunctionExpression;\n const fragmentIds = collectFragmentIdentifiers(arrow);\n context = {\n ...context,\n insideGqlDefinition: true,\n fragmentIdentifiers: new Set([...context.fragmentIdentifiers, ...fragmentIds]),\n };\n } else {\n context = { ...context, insideGqlDefinition: true };\n }\n }\n\n // Check for fragment definition call: fragment.TypeName({ ... })\n if (\n node.type === \"CallExpression\" &&\n context.insideGqlDefinition &&\n isFragmentDefinitionCall(node as CallExpression, context.fragmentIdentifiers)\n ) {\n const call = node as CallExpression;\n const firstArg = call.arguments[0];\n if (firstArg?.expression.type === \"ObjectExpression\" && context.currentArrowFunction) {\n onObjectExpression(firstArg.expression as ObjectExpression, context.currentArrowFunction, {\n isFragmentConfig: true,\n });\n }\n }\n\n // Handle object expressions - check if it's the body of the current arrow function\n if (\n node.type === \"ObjectExpression\" &&\n context.insideGqlDefinition &&\n context.currentArrowFunction &&\n isFieldSelectionObject(node as ObjectExpression, context.currentArrowFunction)\n ) {\n onObjectExpression(node as ObjectExpression, context.currentArrowFunction, { isFragmentConfig: false });\n }\n\n // Recursively visit children\n if (node.type === \"CallExpression\") {\n const call = node as CallExpression;\n traverseNode(call.callee as Node, context, gqlIdentifiers, onObjectExpression);\n for (const arg of call.arguments) {\n traverseNode(arg.expression as Node, context, gqlIdentifiers, onObjectExpression);\n }\n } else if (node.type === \"ArrowFunctionExpression\") {\n const arrow = node as ArrowFunctionExpression;\n // Update context with the new arrow function\n const childContext = { ...context, currentArrowFunction: arrow };\n if (arrow.body.type !== \"BlockStatement\") {\n traverseNode(arrow.body as Node, childContext, gqlIdentifiers, onObjectExpression);\n }\n } else if (node.type === \"ParenthesisExpression\") {\n // Handle parenthesized expressions like `({ ...f.id() })`\n // biome-ignore lint/suspicious/noExplicitAny: SWC types\n const paren = node as any;\n if (paren.expression) {\n traverseNode(paren.expression as Node, context, gqlIdentifiers, onObjectExpression);\n }\n } else if (node.type === \"MemberExpression\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC types\n const member = node as any;\n traverseNode(member.object as Node, context, gqlIdentifiers, onObjectExpression);\n } else if (node.type === \"ObjectExpression\") {\n const obj = node as ObjectExpression;\n for (const prop of obj.properties) {\n if (prop.type === \"SpreadElement\") {\n traverseNode(prop.arguments as Node, context, gqlIdentifiers, onObjectExpression);\n } else if (prop.type === \"KeyValueProperty\") {\n traverseNode(prop.value as Node, context, gqlIdentifiers, onObjectExpression);\n }\n }\n } else {\n // Generic traversal for other node types\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n if (child && typeof child === \"object\" && \"type\" in child) {\n traverseNode(child as Node, context, gqlIdentifiers, onObjectExpression);\n }\n }\n } else if (value && typeof value === \"object\" && \"type\" in value) {\n traverseNode(value as Node, context, gqlIdentifiers, onObjectExpression);\n }\n }\n }\n};\n\nconst traverse = (module: Module, gqlIdentifiers: ReadonlySet<string>, onObjectExpression: TraversalCallback): void => {\n const initialContext: TraversalContext = {\n insideGqlDefinition: false,\n currentArrowFunction: null,\n fragmentIdentifiers: new Set(),\n };\n for (const statement of module.body) {\n traverseNode(statement, initialContext, gqlIdentifiers, onObjectExpression);\n }\n};\n\n/**\n * Format soda-gql field selection objects by inserting newlines.\n * Optionally injects fragment keys for anonymous fragments.\n */\nexport const format = (options: FormatOptions): Result<FormatResult, FormatError> => {\n const { sourceCode, filePath, injectFragmentKeys = false } = options;\n\n // Parse source code with SWC\n let module: Module;\n try {\n const program = parseSync(sourceCode, {\n syntax: \"typescript\",\n tsx: filePath?.endsWith(\".tsx\") ?? true,\n target: \"es2022\",\n decorators: false,\n dynamicImport: true,\n });\n\n if (program.type !== \"Module\") {\n return err({\n type: \"FormatError\",\n code: \"PARSE_ERROR\",\n message: `Not a module${filePath ? ` (${filePath})` : \"\"}`,\n });\n }\n module = program;\n } catch (cause) {\n return err({\n type: \"FormatError\",\n code: \"PARSE_ERROR\",\n message: `Failed to parse source code${filePath ? ` (${filePath})` : \"\"}`,\n cause,\n });\n }\n\n // Calculate span offset for position normalization\n // SWC's BytePos counter accumulates across parseSync calls within the same process\n // Using module.span.start ensures correct position calculation regardless of accumulation\n const spanOffset = module.span.start;\n\n // SWC returns UTF-8 byte offsets; JS strings use UTF-16 code units.\n // The converter handles this mapping (fast path for ASCII-only sources).\n const converter = createSwcSpanConverter(sourceCode);\n\n // Collect gql identifiers from imports\n const gqlIdentifiers = collectGqlIdentifiers(module);\n if (gqlIdentifiers.size === 0) {\n return ok({ modified: false, sourceCode });\n }\n\n // Collect insertion points\n const insertionPoints: InsertionPoint[] = [];\n\n traverse(module, gqlIdentifiers, (object, _parent, callbackContext) => {\n // Calculate actual position in source (byte offset → char index)\n const objectStart = converter.byteOffsetToCharIndex(object.span.start - spanOffset);\n\n // For fragment config objects, inject key if enabled and not present\n if (callbackContext.isFragmentConfig && injectFragmentKeys && !hasKeyProperty(object)) {\n const key = generateFragmentKey();\n\n if (hasExistingNewline(sourceCode, objectStart)) {\n // Multi-line: insert after newline, preserving indentation\n const indentation = detectIndentationAfterBrace(sourceCode, objectStart) ?? \"\";\n let insertPos = objectStart + 2; // Skip { and \\n\n if (sourceCode[objectStart + 1] === \"\\r\") insertPos++;\n\n insertionPoints.push({\n position: insertPos,\n content: createKeyInsertion(key, indentation),\n });\n } else {\n // Single-line: insert right after {\n insertionPoints.push({\n position: objectStart + 1,\n content: createKeyInsertion(key),\n });\n }\n }\n\n // For field selection objects, insert newline if not present\n if (!callbackContext.isFragmentConfig && !hasExistingNewline(sourceCode, objectStart)) {\n insertionPoints.push({\n position: objectStart + 1,\n content: NEWLINE_INSERTION,\n });\n }\n });\n\n // Tagged template formatting\n const graphqlResult = getGraphqlModule();\n if (graphqlResult.isErr()) {\n return err(graphqlResult.error);\n }\n const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;\n\n const positionCtx: PositionTrackingContext = { spanOffset, converter };\n const templates = walkAndExtract(module as unknown as Node, gqlIdentifiers, positionCtx);\n\n if (templates.length > 0) {\n const defaultFormat: FormatGraphqlFn = (source) => {\n const ast = parseGraphql(source, { noLocation: false });\n return printGraphql(ast);\n };\n\n const templateEdits = formatTemplatesInSource(templates, sourceCode, defaultFormat);\n\n for (const edit of templateEdits) {\n insertionPoints.push({\n position: edit.start,\n content: edit.newText,\n endPosition: edit.end,\n });\n }\n }\n\n // Apply insertions\n if (insertionPoints.length === 0) {\n return ok({ modified: false, sourceCode });\n }\n\n // Sort in descending order to insert from end to beginning\n // This preserves earlier positions while modifying later parts\n const sortedPoints = [...insertionPoints].sort((a, b) => b.position - a.position);\n\n let result = sourceCode;\n for (const point of sortedPoints) {\n const end = point.endPosition ?? point.position;\n result = result.slice(0, point.position) + point.content + result.slice(end);\n }\n\n return ok({ modified: true, sourceCode: result });\n};\n\n/**\n * Check if a file needs formatting (has unformatted field selections).\n * Useful for pre-commit hooks or CI checks.\n */\nexport const needsFormat = (options: FormatOptions): Result<boolean, FormatError> => {\n const { sourceCode, filePath } = options;\n\n // Parse source code with SWC\n let module: Module;\n try {\n const program = parseSync(sourceCode, {\n syntax: \"typescript\",\n tsx: filePath?.endsWith(\".tsx\") ?? true,\n target: \"es2022\",\n decorators: false,\n dynamicImport: true,\n });\n\n if (program.type !== \"Module\") {\n return err({\n type: \"FormatError\",\n code: \"PARSE_ERROR\",\n message: `Not a module${filePath ? ` (${filePath})` : \"\"}`,\n });\n }\n module = program;\n } catch (cause) {\n return err({\n type: \"FormatError\",\n code: \"PARSE_ERROR\",\n message: `Failed to parse source code${filePath ? ` (${filePath})` : \"\"}`,\n cause,\n });\n }\n\n const spanOffset = module.span.start;\n const converter = createSwcSpanConverter(sourceCode);\n const gqlIdentifiers = collectGqlIdentifiers(module);\n\n if (gqlIdentifiers.size === 0) {\n return ok(false);\n }\n\n let needsFormatting = false;\n\n traverse(module, gqlIdentifiers, (object, _parent, callbackContext) => {\n if (needsFormatting) return; // Early exit\n\n // Skip fragment config objects for needsFormat check (key injection is optional)\n if (callbackContext.isFragmentConfig) return;\n\n const objectStart = converter.byteOffsetToCharIndex(object.span.start - spanOffset);\n if (!hasExistingNewline(sourceCode, objectStart)) {\n needsFormatting = true;\n }\n });\n\n // Check tagged templates\n if (!needsFormatting) {\n const graphqlResult = getGraphqlModule();\n if (graphqlResult.isErr()) {\n return err(graphqlResult.error);\n }\n const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;\n\n const positionCtx: PositionTrackingContext = { spanOffset, converter };\n const templates = walkAndExtract(module as unknown as Node, gqlIdentifiers, positionCtx);\n\n if (templates.length > 0) {\n const defaultFormat: FormatGraphqlFn = (source) => {\n const ast = parseGraphql(source, { noLocation: false });\n return printGraphql(ast);\n };\n\n const templateEdits = formatTemplatesInSource(templates, sourceCode, defaultFormat);\n if (templateEdits.length > 0) {\n needsFormatting = true;\n }\n }\n }\n\n return ok(needsFormatting);\n};\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAa,kBAAkB,MAAkB,mBAAiD;CAEhG,MAAM,YAAY,KAAK,SAAS,wBAAyB,KAAkD,aAAa;AACxH,KAAI,UAAU,SAAS,cAAc;AACnC,SAAO,eAAe,IAAI,UAAU,MAAM;;AAE5C,KAAI,UAAU,SAAS,sBAAsB,UAAU,SAAS,SAAS,gBAAgB,UAAU,SAAS,UAAU,OAAO;AAC3H,SAAO;;AAET,QAAO;;;;;;AAOT,MAAa,uBAAuB,MAAsB,mBAAiD;AACzG,KAAI,KAAK,OAAO,SAAS,mBAAoB,QAAO;CACpD,MAAM,EAAE,WAAW,KAAK;AAGxB,KAAI,CAAC,eAAe,QAAQ,eAAe,CAAE,QAAO;CAIpD,MAAM,WAAW,KAAK,UAAU;AAChC,KAAI,CAAC,YAAa,SAAS,WAAW,SAAS,6BAA6B,SAAS,WAAW,SAAS,qBACvG,QAAO;AAET,QAAO;;;;;;AAOT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AkB;AACxC,MAAI,cAAc,OAAO,EAAE;AACzB,8BAAW,cAAc,MAAM;;EAEjC,MAAM,EAAE,OAAO,cAAc,OAAO,iBAAiB,cAAc;EAEnE,MAAMG,cAAuC;GAAE;GAAY;GAAW;EACtE,MAAM,sEAA2BH,UAA2B,gBAAgB,YAAY;AAExF,MAAI,UAAU,SAAS,GAAG;GACxB,MAAMI,iBAAkC,WAAW;IACjD,MAAM,MAAM,aAAa,QAAQ,EAAE,YAAY,OAAO,CAAC;AACvD,WAAO,aAAa,IAAI;;GAG1B,MAAM,mFAAwC,WAAW,YAAY,cAAc;AACnF,OAAI,cAAc,SAAS,GAAG;AAC5B,sBAAkB;;;;AAKxB,2BAAU,gBAAgB"}
@@ -0,0 +1,33 @@
1
+ import { Result } from "neverthrow";
2
+
3
+ //#region packages/tools/src/formatter/types.d.ts
4
+ type FormatOptions = {
5
+ readonly sourceCode: string;
6
+ readonly filePath?: string;
7
+ readonly injectFragmentKeys?: boolean;
8
+ };
9
+ type FormatResult = {
10
+ readonly modified: boolean;
11
+ readonly sourceCode: string;
12
+ };
13
+ type FormatError = {
14
+ readonly type: "FormatError";
15
+ readonly code: "PARSE_ERROR" | "TRANSFORM_ERROR" | "MISSING_DEPENDENCY";
16
+ readonly message: string;
17
+ readonly cause?: unknown;
18
+ };
19
+ //#endregion
20
+ //#region packages/tools/src/formatter/format.d.ts
21
+ /**
22
+ * Format soda-gql field selection objects by inserting newlines.
23
+ * Optionally injects fragment keys for anonymous fragments.
24
+ */
25
+ declare const format: (options: FormatOptions) => Result<FormatResult, FormatError>;
26
+ /**
27
+ * Check if a file needs formatting (has unformatted field selections).
28
+ * Useful for pre-commit hooks or CI checks.
29
+ */
30
+ declare const needsFormat: (options: FormatOptions) => Result<boolean, FormatError>;
31
+ //#endregion
32
+ export { type FormatError, type FormatOptions, type FormatResult, format, needsFormat };
33
+ //# sourceMappingURL=formatter.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter.d.cts","names":[],"sources":["../src/formatter/types.ts","../src/formatter/format.ts"],"sourcesContent":[],"mappings":";;;KAAY,aAAA;;;EAAA,SAAA,kBAAa,CAAA,EAAA,OAAA;AAMzB,CAAA;AAKY,KALA,YAAA,GAKW;;;;AC+LV,KD/LD,WAAA,GC+TX;EAhI+B,SAAA,IAAA,EAAA,aAAA;EAAuB,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA,GAAA,oBAAA;EAAc,SAAA,OAAA,EAAA,MAAA;EAArB,SAAA,KAAA,CAAA,EAAA,OAAA;CAAM;;;;AD1MtD;AAMA;AAKA;cC+La,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cAsI1C,WAtI0C,EAAA,CAAA,OAAA,EAsIlB,aAtIkB,EAAA,GAsIF,MAtIE,CAAA,OAAA,EAsIc,WAtId,CAAA"}
@@ -0,0 +1,33 @@
1
+ import { Result } from "neverthrow";
2
+
3
+ //#region packages/tools/src/formatter/types.d.ts
4
+ type FormatOptions = {
5
+ readonly sourceCode: string;
6
+ readonly filePath?: string;
7
+ readonly injectFragmentKeys?: boolean;
8
+ };
9
+ type FormatResult = {
10
+ readonly modified: boolean;
11
+ readonly sourceCode: string;
12
+ };
13
+ type FormatError = {
14
+ readonly type: "FormatError";
15
+ readonly code: "PARSE_ERROR" | "TRANSFORM_ERROR" | "MISSING_DEPENDENCY";
16
+ readonly message: string;
17
+ readonly cause?: unknown;
18
+ };
19
+ //#endregion
20
+ //#region packages/tools/src/formatter/format.d.ts
21
+ /**
22
+ * Format soda-gql field selection objects by inserting newlines.
23
+ * Optionally injects fragment keys for anonymous fragments.
24
+ */
25
+ declare const format: (options: FormatOptions) => Result<FormatResult, FormatError>;
26
+ /**
27
+ * Check if a file needs formatting (has unformatted field selections).
28
+ * Useful for pre-commit hooks or CI checks.
29
+ */
30
+ declare const needsFormat: (options: FormatOptions) => Result<boolean, FormatError>;
31
+ //#endregion
32
+ export { type FormatError, type FormatOptions, type FormatResult, format, needsFormat };
33
+ //# sourceMappingURL=formatter.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter.d.mts","names":[],"sources":["../src/formatter/types.ts","../src/formatter/format.ts"],"sourcesContent":[],"mappings":";;;KAAY,aAAA;;;EAAA,SAAA,kBAAa,CAAA,EAAA,OAAA;AAMzB,CAAA;AAKY,KALA,YAAA,GAKW;;;;AC+LV,KD/LD,WAAA,GC+TX;EAhI+B,SAAA,IAAA,EAAA,aAAA;EAAuB,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA,GAAA,oBAAA;EAAc,SAAA,OAAA,EAAA,MAAA;EAArB,SAAA,KAAA,CAAA,EAAA,OAAA;CAAM;;;;AD1MtD;AAMA;AAKA;cC+La,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cAsI1C,WAtI0C,EAAA,CAAA,OAAA,EAsIlB,aAtIkB,EAAA,GAsIF,MAtIE,CAAA,OAAA,EAsIc,WAtId,CAAA"}