@soda-gql/formatter 0.10.2 → 0.11.1

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 CHANGED
@@ -1,5 +1,6 @@
1
1
  let __swc_core = require("@swc/core");
2
2
  let neverthrow = require("neverthrow");
3
+ let node_crypto = require("node:crypto");
3
4
 
4
5
  //#region packages/formatter/src/detection.ts
5
6
  /**
@@ -63,6 +64,53 @@ const collectGqlIdentifiers = (module$1) => {
63
64
  }
64
65
  return gqlIdentifiers;
65
66
  };
67
+ /**
68
+ * Check if a call expression is a fragment definition call.
69
+ * Pattern: fragment.TypeName({ ... }) where `fragment` comes from gql factory destructuring.
70
+ */
71
+ const isFragmentDefinitionCall = (node, fragmentIdentifiers) => {
72
+ if (node.callee.type !== "MemberExpression") return false;
73
+ const { object } = node.callee;
74
+ if (object.type !== "Identifier") return false;
75
+ if (!fragmentIdentifiers.has(object.value)) return false;
76
+ const firstArg = node.arguments[0];
77
+ if (!firstArg || firstArg.expression.type !== "ObjectExpression") return false;
78
+ return true;
79
+ };
80
+ /**
81
+ * Check if an object expression already has a `key` property.
82
+ */
83
+ const hasKeyProperty = (obj) => {
84
+ return obj.properties.some((prop) => {
85
+ if (prop.type === "KeyValueProperty" && prop.key.type === "Identifier") return prop.key.value === "key";
86
+ return false;
87
+ });
88
+ };
89
+ /**
90
+ * Collect fragment identifiers from gql factory arrow function parameter.
91
+ * Looks for patterns like: ({ fragment }) => ... or ({ fragment: f }) => ...
92
+ */
93
+ const collectFragmentIdentifiers = (arrowFunction) => {
94
+ const fragmentIdentifiers = /* @__PURE__ */ new Set();
95
+ const param = arrowFunction.params[0];
96
+ if (param?.type !== "ObjectPattern") return fragmentIdentifiers;
97
+ for (const p of param.properties) {
98
+ if (p.type === "KeyValuePatternProperty" && p.key.type === "Identifier" && p.key.value === "fragment") {
99
+ const localName = extractIdentifierName(p.value);
100
+ if (localName) fragmentIdentifiers.add(localName);
101
+ }
102
+ if (p.type === "AssignmentPatternProperty" && p.key.type === "Identifier" && p.key.value === "fragment") fragmentIdentifiers.add(p.key.value);
103
+ }
104
+ return fragmentIdentifiers;
105
+ };
106
+ /**
107
+ * Extract identifier name from a pattern node.
108
+ */
109
+ const extractIdentifierName = (pattern) => {
110
+ if (pattern.type === "Identifier") return pattern.value;
111
+ if (pattern.type === "BindingIdentifier") return pattern.value;
112
+ return null;
113
+ };
66
114
 
67
115
  //#endregion
68
116
  //#region packages/formatter/src/insertion.ts
@@ -71,6 +119,27 @@ const collectGqlIdentifiers = (module$1) => {
71
119
  */
72
120
  const NEWLINE_INSERTION = "\n";
73
121
  /**
122
+ * Generate a random 8-character hex key for fragment identification.
123
+ * Uses Node.js crypto for cryptographically secure random bytes.
124
+ */
125
+ const generateFragmentKey = () => {
126
+ return (0, node_crypto.randomBytes)(4).toString("hex");
127
+ };
128
+ /**
129
+ * Create the key property insertion string.
130
+ *
131
+ * For single-line objects: returns ` key: "xxxxxxxx",\n`
132
+ * For multi-line objects (with indentation): returns `{indentation}key: "xxxxxxxx",\n`
133
+ * (the existing indentation before the next property is preserved)
134
+ *
135
+ * @param key - The hex key string
136
+ * @param indentation - Optional indentation string for multi-line objects
137
+ */
138
+ const createKeyInsertion = (key, indentation) => {
139
+ if (indentation !== void 0) return `${indentation}key: "${key}",\n`;
140
+ return ` key: "${key}",\n`;
141
+ };
142
+ /**
74
143
  * Check if there's already a newline after the opening brace.
75
144
  * Uses string inspection rather than AST.
76
145
  *
@@ -81,6 +150,29 @@ const hasExistingNewline = (source, objectStartPos) => {
81
150
  const nextChar = source[objectStartPos + 1];
82
151
  return nextChar === "\n" || nextChar === "\r";
83
152
  };
153
+ /**
154
+ * Detect the indentation used after an opening brace.
155
+ * Returns the whitespace string after the newline, or null if no newline.
156
+ *
157
+ * @param source - The source code string
158
+ * @param objectStartPos - The position of the `{` character
159
+ */
160
+ const detectIndentationAfterBrace = (source, objectStartPos) => {
161
+ const afterBrace = objectStartPos + 1;
162
+ const char = source[afterBrace];
163
+ if (char !== "\n" && char !== "\r") return null;
164
+ let pos = afterBrace + 1;
165
+ if (char === "\r" && source[pos] === "\n") pos++;
166
+ let indentation = "";
167
+ while (pos < source.length) {
168
+ const c = source[pos];
169
+ if (c === " " || c === " ") {
170
+ indentation += c;
171
+ pos++;
172
+ } else break;
173
+ }
174
+ return indentation;
175
+ };
84
176
 
85
177
  //#endregion
86
178
  //#region packages/formatter/src/format.ts
@@ -88,11 +180,26 @@ const hasExistingNewline = (source, objectStartPos) => {
88
180
  * Simple recursive AST traversal
89
181
  */
90
182
  const traverseNode = (node, context, gqlIdentifiers, onObjectExpression) => {
91
- if (node.type === "CallExpression" && isGqlDefinitionCall(node, gqlIdentifiers)) context = {
92
- ...context,
93
- insideGqlDefinition: true
94
- };
95
- if (node.type === "ObjectExpression" && context.insideGqlDefinition && context.currentArrowFunction && isFieldSelectionObject(node, context.currentArrowFunction)) onObjectExpression(node, context.currentArrowFunction);
183
+ if (node.type === "CallExpression" && isGqlDefinitionCall(node, gqlIdentifiers)) {
184
+ const firstArg = node.arguments[0];
185
+ if (firstArg?.expression.type === "ArrowFunctionExpression") {
186
+ const arrow = firstArg.expression;
187
+ const fragmentIds = collectFragmentIdentifiers(arrow);
188
+ context = {
189
+ ...context,
190
+ insideGqlDefinition: true,
191
+ fragmentIdentifiers: new Set([...context.fragmentIdentifiers, ...fragmentIds])
192
+ };
193
+ } else context = {
194
+ ...context,
195
+ insideGqlDefinition: true
196
+ };
197
+ }
198
+ if (node.type === "CallExpression" && context.insideGqlDefinition && isFragmentDefinitionCall(node, context.fragmentIdentifiers)) {
199
+ const firstArg = node.arguments[0];
200
+ if (firstArg?.expression.type === "ObjectExpression" && context.currentArrowFunction) onObjectExpression(firstArg.expression, context.currentArrowFunction, { isFragmentConfig: true });
201
+ }
202
+ if (node.type === "ObjectExpression" && context.insideGqlDefinition && context.currentArrowFunction && isFieldSelectionObject(node, context.currentArrowFunction)) onObjectExpression(node, context.currentArrowFunction, { isFragmentConfig: false });
96
203
  if (node.type === "CallExpression") {
97
204
  const call = node;
98
205
  traverseNode(call.callee, context, gqlIdentifiers, onObjectExpression);
@@ -117,17 +224,19 @@ const traverseNode = (node, context, gqlIdentifiers, onObjectExpression) => {
117
224
  } else if (value && typeof value === "object" && "type" in value) traverseNode(value, context, gqlIdentifiers, onObjectExpression);
118
225
  };
119
226
  const traverse = (module$1, gqlIdentifiers, onObjectExpression) => {
120
- for (const statement of module$1.body) traverseNode(statement, {
227
+ const initialContext = {
121
228
  insideGqlDefinition: false,
122
- currentArrowFunction: null
123
- }, gqlIdentifiers, onObjectExpression);
229
+ currentArrowFunction: null,
230
+ fragmentIdentifiers: /* @__PURE__ */ new Set()
231
+ };
232
+ for (const statement of module$1.body) traverseNode(statement, initialContext, gqlIdentifiers, onObjectExpression);
124
233
  };
125
234
  /**
126
235
  * Format soda-gql field selection objects by inserting newlines.
127
- * This preserves multi-line formatting when using Biome/Prettier.
236
+ * Optionally injects fragment keys for anonymous fragments.
128
237
  */
129
238
  const format = (options) => {
130
- const { sourceCode, filePath } = options;
239
+ const { sourceCode, filePath, injectFragmentKeys = false } = options;
131
240
  let module$1;
132
241
  try {
133
242
  const program = (0, __swc_core.parseSync)(sourceCode, {
@@ -151,25 +260,42 @@ const format = (options) => {
151
260
  cause
152
261
  });
153
262
  }
154
- const spanOffset = module$1.span.end - sourceCode.length + 1;
263
+ const spanOffset = module$1.span.start;
155
264
  const gqlIdentifiers = collectGqlIdentifiers(module$1);
156
265
  if (gqlIdentifiers.size === 0) return (0, neverthrow.ok)({
157
266
  modified: false,
158
267
  sourceCode
159
268
  });
160
269
  const insertionPoints = [];
161
- traverse(module$1, gqlIdentifiers, (object, _parent) => {
270
+ traverse(module$1, gqlIdentifiers, (object, _parent, callbackContext) => {
162
271
  const objectStart = object.span.start - spanOffset;
163
- if (hasExistingNewline(sourceCode, objectStart)) return;
164
- insertionPoints.push(objectStart + 1);
272
+ if (callbackContext.isFragmentConfig && injectFragmentKeys && !hasKeyProperty(object)) {
273
+ const key = generateFragmentKey();
274
+ if (hasExistingNewline(sourceCode, objectStart)) {
275
+ const indentation = detectIndentationAfterBrace(sourceCode, objectStart) ?? "";
276
+ let insertPos = objectStart + 2;
277
+ if (sourceCode[objectStart + 1] === "\r") insertPos++;
278
+ insertionPoints.push({
279
+ position: insertPos,
280
+ content: createKeyInsertion(key, indentation)
281
+ });
282
+ } else insertionPoints.push({
283
+ position: objectStart + 1,
284
+ content: createKeyInsertion(key)
285
+ });
286
+ }
287
+ if (!callbackContext.isFragmentConfig && !hasExistingNewline(sourceCode, objectStart)) insertionPoints.push({
288
+ position: objectStart + 1,
289
+ content: NEWLINE_INSERTION
290
+ });
165
291
  });
166
292
  if (insertionPoints.length === 0) return (0, neverthrow.ok)({
167
293
  modified: false,
168
294
  sourceCode
169
295
  });
170
- const sortedPoints = [...insertionPoints].sort((a, b) => b - a);
296
+ const sortedPoints = [...insertionPoints].sort((a, b) => b.position - a.position);
171
297
  let result = sourceCode;
172
- for (const pos of sortedPoints) result = result.slice(0, pos) + NEWLINE_INSERTION + result.slice(pos);
298
+ for (const point of sortedPoints) result = result.slice(0, point.position) + point.content + result.slice(point.position);
173
299
  return (0, neverthrow.ok)({
174
300
  modified: true,
175
301
  sourceCode: result
@@ -204,12 +330,13 @@ const needsFormat = (options) => {
204
330
  cause
205
331
  });
206
332
  }
207
- const spanOffset = module$1.span.end - sourceCode.length + 1;
333
+ const spanOffset = module$1.span.start;
208
334
  const gqlIdentifiers = collectGqlIdentifiers(module$1);
209
335
  if (gqlIdentifiers.size === 0) return (0, neverthrow.ok)(false);
210
336
  let needsFormatting = false;
211
- traverse(module$1, gqlIdentifiers, (object, _parent) => {
337
+ traverse(module$1, gqlIdentifiers, (object, _parent, callbackContext) => {
212
338
  if (needsFormatting) return;
339
+ if (callbackContext.isFragmentConfig) return;
213
340
  if (!hasExistingNewline(sourceCode, object.span.start - spanOffset)) needsFormatting = true;
214
341
  });
215
342
  return (0, neverthrow.ok)(needsFormatting);
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["bodyObject: ObjectExpression | null","module","module","module: Module","insertionPoints: number[]"],"sources":["../src/detection.ts","../src/insertion.ts","../src/format.ts"],"sourcesContent":["import type {\n ArrowFunctionExpression,\n CallExpression,\n Expression,\n Module,\n ObjectExpression,\n ObjectPatternProperty,\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 if (node.type === \"Identifier\") {\n return gqlIdentifiers.has(node.value);\n }\n if (node.type === \"MemberExpression\" && node.property.type === \"Identifier\" && node.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\") 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 * The newline string to insert after object opening brace\n */\nexport const NEWLINE_INSERTION = \"\\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","import { parseSync } from \"@swc/core\";\nimport type { ArrowFunctionExpression, CallExpression, Module, Node, ObjectExpression } from \"@swc/types\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport { collectGqlIdentifiers, isFieldSelectionObject, isGqlDefinitionCall } from \"./detection\";\nimport { hasExistingNewline, NEWLINE_INSERTION } from \"./insertion\";\nimport type { FormatError, FormatOptions, FormatResult } from \"./types\";\n\ntype TraversalContext = {\n insideGqlDefinition: boolean;\n currentArrowFunction: ArrowFunctionExpression | null;\n};\n\n/**\n * Simple recursive AST traversal\n */\nconst traverseNode = (\n node: Node,\n context: TraversalContext,\n gqlIdentifiers: ReadonlySet<string>,\n onObjectExpression: (object: ObjectExpression, parent: ArrowFunctionExpression) => void,\n): void => {\n // Check for gql definition call entry\n if (node.type === \"CallExpression\" && isGqlDefinitionCall(node as CallExpression, gqlIdentifiers)) {\n context = { ...context, insideGqlDefinition: true };\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);\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 = (\n module: Module,\n gqlIdentifiers: ReadonlySet<string>,\n onObjectExpression: (object: ObjectExpression, parent: ArrowFunctionExpression) => void,\n): void => {\n for (const statement of module.body) {\n traverseNode(statement, { insideGqlDefinition: false, currentArrowFunction: null }, gqlIdentifiers, onObjectExpression);\n }\n};\n\n/**\n * Format soda-gql field selection objects by inserting newlines.\n * This preserves multi-line formatting when using Biome/Prettier.\n */\nexport const format = (options: FormatOptions): Result<FormatResult, 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 // Calculate span offset for position normalization\n // SWC's BytePos counter accumulates across parseSync calls within the same process\n const spanOffset = module.span.end - sourceCode.length + 1;\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: number[] = [];\n\n traverse(module, gqlIdentifiers, (object, _parent) => {\n // Calculate actual position in source\n const objectStart = object.span.start - spanOffset;\n\n // Check if already has newline\n if (hasExistingNewline(sourceCode, objectStart)) return;\n\n // Record insertion point (position after `{`)\n insertionPoints.push(objectStart + 1);\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 - a);\n\n let result = sourceCode;\n for (const pos of sortedPoints) {\n result = result.slice(0, pos) + NEWLINE_INSERTION + result.slice(pos);\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.end - sourceCode.length + 1;\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) => {\n if (needsFormatting) return; // Early exit\n\n const objectStart = object.span.start - spanOffset;\n if (!hasExistingNewline(sourceCode, objectStart)) {\n needsFormatting = true;\n }\n });\n\n return ok(needsFormatting);\n};\n"],"mappings":";;;;;;;;AAaA,MAAa,kBAAkB,MAAkB,mBAAiD;AAChG,KAAI,KAAK,SAAS,aAChB,QAAO,eAAe,IAAI,KAAK,MAAM;AAEvC,KAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,SAAS,gBAAgB,KAAK,SAAS,UAAU,MACrG,QAAO;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,YAAY,SAAS,WAAW,SAAS,0BAA2B,QAAO;AAEhF,QAAO;;;;;;AAOT,MAAa,0BAA0B,QAA0B,WAA6C;CAG5G,IAAIA,aAAsC;AAE1C,KAAI,OAAO,KAAK,SAAS,mBACvB,cAAa,OAAO;UACX,OAAO,KAAK,SAAS,yBAAyB;EAEvD,MAAM,QAAQ,OAAO,KAAK;AAC1B,MAAI,MAAM,SAAS,mBACjB,cAAa;;AAIjB,KAAI,CAAC,WAAY,QAAO;AACxB,KAAI,WAAW,KAAK,UAAU,OAAO,KAAK,MAAO,QAAO;CAGxD,MAAM,QAAQ,OAAO,OAAO;AAC5B,KAAI,CAAC,SAAS,MAAM,SAAS,gBAAiB,QAAO;AAErD,QAAO,MAAM,WAAW,MAAM,MAA6B;AACzD,MAAI,EAAE,SAAS,6BAA6B,EAAE,IAAI,SAAS,aACzD,QAAO,EAAE,IAAI,UAAU;AAEzB,MAAI,EAAE,SAAS,+BAA+B,EAAE,IAAI,SAAS,aAC3D,QAAO,EAAE,IAAI,UAAU;AAEzB,SAAO;GACP;;;;;AAMJ,MAAa,yBAAyB,aAAgC;CACpE,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Y;AACpD,MAAI,gBAAiB;AAGrB,MAAI,CAAC,mBAAmB,YADJ,OAAO,KAAK,QAAQ,WACQ,CAC9C,mBAAkB;GAEpB;AAEF,2BAAU,gBAAgB"}
1
+ {"version":3,"file":"index.cjs","names":["bodyObject: ObjectExpression | null","module","initialContext: TraversalContext","module","module: Module","insertionPoints: InsertionPoint[]"],"sources":["../src/detection.ts","../src/insertion.ts","../src/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 if (node.type === \"Identifier\") {\n return gqlIdentifiers.has(node.value);\n }\n if (node.type === \"MemberExpression\" && node.property.type === \"Identifier\" && node.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\") 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 { parseSync } from \"@swc/core\";\nimport type { ArrowFunctionExpression, CallExpression, Module, Node, ObjectExpression } from \"@swc/types\";\nimport { err, ok, type Result } from \"neverthrow\";\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};\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 // 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\n const objectStart = 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 // 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 result = result.slice(0, point.position) + point.content + result.slice(point.position);\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 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 = object.span.start - spanOffset;\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C;;CAGJ,MAAM,aAAaD,SAAO,KAAK;CAC/B,MAAM,iBAAiB,sBAAsBA,SAAO;AAEpD,KAAI,eAAe,SAAS,EAC1B,2BAAU,MAAM;CAGlB,IAAI,kBAAkB;AAEtB,UAASA,UAAQ,iBAAiB,QAAQ,SAAS,oBAAoB;AACrE,MAAI,gBAAiB;AAGrB,MAAI,gBAAgB,iBAAkB;AAGtC,MAAI,CAAC,mBAAmB,YADJ,OAAO,KAAK,QAAQ,WACQ,CAC9C,mBAAkB;GAEpB;AAEF,2BAAU,gBAAgB"}
package/dist/index.d.cts CHANGED
@@ -4,6 +4,7 @@ import { Result } from "neverthrow";
4
4
  type FormatOptions = {
5
5
  readonly sourceCode: string;
6
6
  readonly filePath?: string;
7
+ readonly injectFragmentKeys?: boolean;
7
8
  };
8
9
  type FormatResult = {
9
10
  readonly modified: boolean;
@@ -19,7 +20,7 @@ type FormatError = {
19
20
  //#region packages/formatter/src/format.d.ts
20
21
  /**
21
22
  * Format soda-gql field selection objects by inserting newlines.
22
- * This preserves multi-line formatting when using Biome/Prettier.
23
+ * Optionally injects fragment keys for anonymous fragments.
23
24
  */
24
25
  declare const format: (options: FormatOptions) => Result<FormatResult, FormatError>;
25
26
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/format.ts"],"sourcesContent":[],"mappings":";;;KAAY,aAAA;;;AAAZ,CAAA;AAKY,KAAA,YAAA,GAAY;EAKZ,SAAA,QAAW,EAAA,OAAA;;;KAAX,WAAA;EC0FC,SAsEZ,IAAA,EAAA,aAAA;EAtE+B,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA;EAAuB,SAAA,OAAA,EAAA,MAAA;EAAc,SAAA,KAAA,CAAA,EAAA,OAAA;CAArB;;;;ADpGhD;AAKA;AAKA;cC0Fa,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cA4E1C,WA5E0C,EAAA,CAAA,OAAA,EA4ElB,aA5EkB,EAAA,GA4EF,MA5EE,CAAA,OAAA,EA4Ec,WA5Ed,CAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/format.ts"],"sourcesContent":[],"mappings":";;;KAAY,aAAA;;;EAAA,SAAA,kBAAa,CAAA,EAAA,OAAA;AAMzB,CAAA;AAKY,KALA,YAAA,GAKW;;;;ACkJV,KDlJD,WAAA,GCkPX;EAhG+B,SAAA,IAAA,EAAA,aAAA;EAAuB,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA;EAAc,SAAA,OAAA,EAAA,MAAA;EAArB,SAAA,KAAA,CAAA,EAAA,OAAA;CAAM;;;;AD7JtD;AAMA;AAKA;cCkJa,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cAsG1C,WAtG0C,EAAA,CAAA,OAAA,EAsGlB,aAtGkB,EAAA,GAsGF,MAtGE,CAAA,OAAA,EAsGc,WAtGd,CAAA"}
package/dist/index.d.mts CHANGED
@@ -4,6 +4,7 @@ import { Result } from "neverthrow";
4
4
  type FormatOptions = {
5
5
  readonly sourceCode: string;
6
6
  readonly filePath?: string;
7
+ readonly injectFragmentKeys?: boolean;
7
8
  };
8
9
  type FormatResult = {
9
10
  readonly modified: boolean;
@@ -19,7 +20,7 @@ type FormatError = {
19
20
  //#region packages/formatter/src/format.d.ts
20
21
  /**
21
22
  * Format soda-gql field selection objects by inserting newlines.
22
- * This preserves multi-line formatting when using Biome/Prettier.
23
+ * Optionally injects fragment keys for anonymous fragments.
23
24
  */
24
25
  declare const format: (options: FormatOptions) => Result<FormatResult, FormatError>;
25
26
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/format.ts"],"sourcesContent":[],"mappings":";;;KAAY,aAAA;;;AAAZ,CAAA;AAKY,KAAA,YAAA,GAAY;EAKZ,SAAA,QAAW,EAAA,OAAA;;;KAAX,WAAA;EC0FC,SAsEZ,IAAA,EAAA,aAAA;EAtE+B,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA;EAAuB,SAAA,OAAA,EAAA,MAAA;EAAc,SAAA,KAAA,CAAA,EAAA,OAAA;CAArB;;;;ADpGhD;AAKA;AAKA;cC0Fa,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cA4E1C,WA5E0C,EAAA,CAAA,OAAA,EA4ElB,aA5EkB,EAAA,GA4EF,MA5EE,CAAA,OAAA,EA4Ec,WA5Ed,CAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/format.ts"],"sourcesContent":[],"mappings":";;;KAAY,aAAA;;;EAAA,SAAA,kBAAa,CAAA,EAAA,OAAA;AAMzB,CAAA;AAKY,KALA,YAAA,GAKW;;;;ACkJV,KDlJD,WAAA,GCkPX;EAhG+B,SAAA,IAAA,EAAA,aAAA;EAAuB,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA;EAAc,SAAA,OAAA,EAAA,MAAA;EAArB,SAAA,KAAA,CAAA,EAAA,OAAA;CAAM;;;;AD7JtD;AAMA;AAKA;cCkJa,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cAsG1C,WAtG0C,EAAA,CAAA,OAAA,EAsGlB,aAtGkB,EAAA,GAsGF,MAtGE,CAAA,OAAA,EAsGc,WAtGd,CAAA"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { parseSync } from "@swc/core";
2
2
  import { err, ok } from "neverthrow";
3
+ import { randomBytes } from "node:crypto";
3
4
 
4
5
  //#region packages/formatter/src/detection.ts
5
6
  /**
@@ -63,6 +64,53 @@ const collectGqlIdentifiers = (module) => {
63
64
  }
64
65
  return gqlIdentifiers;
65
66
  };
67
+ /**
68
+ * Check if a call expression is a fragment definition call.
69
+ * Pattern: fragment.TypeName({ ... }) where `fragment` comes from gql factory destructuring.
70
+ */
71
+ const isFragmentDefinitionCall = (node, fragmentIdentifiers) => {
72
+ if (node.callee.type !== "MemberExpression") return false;
73
+ const { object } = node.callee;
74
+ if (object.type !== "Identifier") return false;
75
+ if (!fragmentIdentifiers.has(object.value)) return false;
76
+ const firstArg = node.arguments[0];
77
+ if (!firstArg || firstArg.expression.type !== "ObjectExpression") return false;
78
+ return true;
79
+ };
80
+ /**
81
+ * Check if an object expression already has a `key` property.
82
+ */
83
+ const hasKeyProperty = (obj) => {
84
+ return obj.properties.some((prop) => {
85
+ if (prop.type === "KeyValueProperty" && prop.key.type === "Identifier") return prop.key.value === "key";
86
+ return false;
87
+ });
88
+ };
89
+ /**
90
+ * Collect fragment identifiers from gql factory arrow function parameter.
91
+ * Looks for patterns like: ({ fragment }) => ... or ({ fragment: f }) => ...
92
+ */
93
+ const collectFragmentIdentifiers = (arrowFunction) => {
94
+ const fragmentIdentifiers = /* @__PURE__ */ new Set();
95
+ const param = arrowFunction.params[0];
96
+ if (param?.type !== "ObjectPattern") return fragmentIdentifiers;
97
+ for (const p of param.properties) {
98
+ if (p.type === "KeyValuePatternProperty" && p.key.type === "Identifier" && p.key.value === "fragment") {
99
+ const localName = extractIdentifierName(p.value);
100
+ if (localName) fragmentIdentifiers.add(localName);
101
+ }
102
+ if (p.type === "AssignmentPatternProperty" && p.key.type === "Identifier" && p.key.value === "fragment") fragmentIdentifiers.add(p.key.value);
103
+ }
104
+ return fragmentIdentifiers;
105
+ };
106
+ /**
107
+ * Extract identifier name from a pattern node.
108
+ */
109
+ const extractIdentifierName = (pattern) => {
110
+ if (pattern.type === "Identifier") return pattern.value;
111
+ if (pattern.type === "BindingIdentifier") return pattern.value;
112
+ return null;
113
+ };
66
114
 
67
115
  //#endregion
68
116
  //#region packages/formatter/src/insertion.ts
@@ -71,6 +119,27 @@ const collectGqlIdentifiers = (module) => {
71
119
  */
72
120
  const NEWLINE_INSERTION = "\n";
73
121
  /**
122
+ * Generate a random 8-character hex key for fragment identification.
123
+ * Uses Node.js crypto for cryptographically secure random bytes.
124
+ */
125
+ const generateFragmentKey = () => {
126
+ return randomBytes(4).toString("hex");
127
+ };
128
+ /**
129
+ * Create the key property insertion string.
130
+ *
131
+ * For single-line objects: returns ` key: "xxxxxxxx",\n`
132
+ * For multi-line objects (with indentation): returns `{indentation}key: "xxxxxxxx",\n`
133
+ * (the existing indentation before the next property is preserved)
134
+ *
135
+ * @param key - The hex key string
136
+ * @param indentation - Optional indentation string for multi-line objects
137
+ */
138
+ const createKeyInsertion = (key, indentation) => {
139
+ if (indentation !== void 0) return `${indentation}key: "${key}",\n`;
140
+ return ` key: "${key}",\n`;
141
+ };
142
+ /**
74
143
  * Check if there's already a newline after the opening brace.
75
144
  * Uses string inspection rather than AST.
76
145
  *
@@ -81,6 +150,29 @@ const hasExistingNewline = (source, objectStartPos) => {
81
150
  const nextChar = source[objectStartPos + 1];
82
151
  return nextChar === "\n" || nextChar === "\r";
83
152
  };
153
+ /**
154
+ * Detect the indentation used after an opening brace.
155
+ * Returns the whitespace string after the newline, or null if no newline.
156
+ *
157
+ * @param source - The source code string
158
+ * @param objectStartPos - The position of the `{` character
159
+ */
160
+ const detectIndentationAfterBrace = (source, objectStartPos) => {
161
+ const afterBrace = objectStartPos + 1;
162
+ const char = source[afterBrace];
163
+ if (char !== "\n" && char !== "\r") return null;
164
+ let pos = afterBrace + 1;
165
+ if (char === "\r" && source[pos] === "\n") pos++;
166
+ let indentation = "";
167
+ while (pos < source.length) {
168
+ const c = source[pos];
169
+ if (c === " " || c === " ") {
170
+ indentation += c;
171
+ pos++;
172
+ } else break;
173
+ }
174
+ return indentation;
175
+ };
84
176
 
85
177
  //#endregion
86
178
  //#region packages/formatter/src/format.ts
@@ -88,11 +180,26 @@ const hasExistingNewline = (source, objectStartPos) => {
88
180
  * Simple recursive AST traversal
89
181
  */
90
182
  const traverseNode = (node, context, gqlIdentifiers, onObjectExpression) => {
91
- if (node.type === "CallExpression" && isGqlDefinitionCall(node, gqlIdentifiers)) context = {
92
- ...context,
93
- insideGqlDefinition: true
94
- };
95
- if (node.type === "ObjectExpression" && context.insideGqlDefinition && context.currentArrowFunction && isFieldSelectionObject(node, context.currentArrowFunction)) onObjectExpression(node, context.currentArrowFunction);
183
+ if (node.type === "CallExpression" && isGqlDefinitionCall(node, gqlIdentifiers)) {
184
+ const firstArg = node.arguments[0];
185
+ if (firstArg?.expression.type === "ArrowFunctionExpression") {
186
+ const arrow = firstArg.expression;
187
+ const fragmentIds = collectFragmentIdentifiers(arrow);
188
+ context = {
189
+ ...context,
190
+ insideGqlDefinition: true,
191
+ fragmentIdentifiers: new Set([...context.fragmentIdentifiers, ...fragmentIds])
192
+ };
193
+ } else context = {
194
+ ...context,
195
+ insideGqlDefinition: true
196
+ };
197
+ }
198
+ if (node.type === "CallExpression" && context.insideGqlDefinition && isFragmentDefinitionCall(node, context.fragmentIdentifiers)) {
199
+ const firstArg = node.arguments[0];
200
+ if (firstArg?.expression.type === "ObjectExpression" && context.currentArrowFunction) onObjectExpression(firstArg.expression, context.currentArrowFunction, { isFragmentConfig: true });
201
+ }
202
+ if (node.type === "ObjectExpression" && context.insideGqlDefinition && context.currentArrowFunction && isFieldSelectionObject(node, context.currentArrowFunction)) onObjectExpression(node, context.currentArrowFunction, { isFragmentConfig: false });
96
203
  if (node.type === "CallExpression") {
97
204
  const call = node;
98
205
  traverseNode(call.callee, context, gqlIdentifiers, onObjectExpression);
@@ -117,17 +224,19 @@ const traverseNode = (node, context, gqlIdentifiers, onObjectExpression) => {
117
224
  } else if (value && typeof value === "object" && "type" in value) traverseNode(value, context, gqlIdentifiers, onObjectExpression);
118
225
  };
119
226
  const traverse = (module, gqlIdentifiers, onObjectExpression) => {
120
- for (const statement of module.body) traverseNode(statement, {
227
+ const initialContext = {
121
228
  insideGqlDefinition: false,
122
- currentArrowFunction: null
123
- }, gqlIdentifiers, onObjectExpression);
229
+ currentArrowFunction: null,
230
+ fragmentIdentifiers: /* @__PURE__ */ new Set()
231
+ };
232
+ for (const statement of module.body) traverseNode(statement, initialContext, gqlIdentifiers, onObjectExpression);
124
233
  };
125
234
  /**
126
235
  * Format soda-gql field selection objects by inserting newlines.
127
- * This preserves multi-line formatting when using Biome/Prettier.
236
+ * Optionally injects fragment keys for anonymous fragments.
128
237
  */
129
238
  const format = (options) => {
130
- const { sourceCode, filePath } = options;
239
+ const { sourceCode, filePath, injectFragmentKeys = false } = options;
131
240
  let module;
132
241
  try {
133
242
  const program = parseSync(sourceCode, {
@@ -151,25 +260,42 @@ const format = (options) => {
151
260
  cause
152
261
  });
153
262
  }
154
- const spanOffset = module.span.end - sourceCode.length + 1;
263
+ const spanOffset = module.span.start;
155
264
  const gqlIdentifiers = collectGqlIdentifiers(module);
156
265
  if (gqlIdentifiers.size === 0) return ok({
157
266
  modified: false,
158
267
  sourceCode
159
268
  });
160
269
  const insertionPoints = [];
161
- traverse(module, gqlIdentifiers, (object, _parent) => {
270
+ traverse(module, gqlIdentifiers, (object, _parent, callbackContext) => {
162
271
  const objectStart = object.span.start - spanOffset;
163
- if (hasExistingNewline(sourceCode, objectStart)) return;
164
- insertionPoints.push(objectStart + 1);
272
+ if (callbackContext.isFragmentConfig && injectFragmentKeys && !hasKeyProperty(object)) {
273
+ const key = generateFragmentKey();
274
+ if (hasExistingNewline(sourceCode, objectStart)) {
275
+ const indentation = detectIndentationAfterBrace(sourceCode, objectStart) ?? "";
276
+ let insertPos = objectStart + 2;
277
+ if (sourceCode[objectStart + 1] === "\r") insertPos++;
278
+ insertionPoints.push({
279
+ position: insertPos,
280
+ content: createKeyInsertion(key, indentation)
281
+ });
282
+ } else insertionPoints.push({
283
+ position: objectStart + 1,
284
+ content: createKeyInsertion(key)
285
+ });
286
+ }
287
+ if (!callbackContext.isFragmentConfig && !hasExistingNewline(sourceCode, objectStart)) insertionPoints.push({
288
+ position: objectStart + 1,
289
+ content: NEWLINE_INSERTION
290
+ });
165
291
  });
166
292
  if (insertionPoints.length === 0) return ok({
167
293
  modified: false,
168
294
  sourceCode
169
295
  });
170
- const sortedPoints = [...insertionPoints].sort((a, b) => b - a);
296
+ const sortedPoints = [...insertionPoints].sort((a, b) => b.position - a.position);
171
297
  let result = sourceCode;
172
- for (const pos of sortedPoints) result = result.slice(0, pos) + NEWLINE_INSERTION + result.slice(pos);
298
+ for (const point of sortedPoints) result = result.slice(0, point.position) + point.content + result.slice(point.position);
173
299
  return ok({
174
300
  modified: true,
175
301
  sourceCode: result
@@ -204,12 +330,13 @@ const needsFormat = (options) => {
204
330
  cause
205
331
  });
206
332
  }
207
- const spanOffset = module.span.end - sourceCode.length + 1;
333
+ const spanOffset = module.span.start;
208
334
  const gqlIdentifiers = collectGqlIdentifiers(module);
209
335
  if (gqlIdentifiers.size === 0) return ok(false);
210
336
  let needsFormatting = false;
211
- traverse(module, gqlIdentifiers, (object, _parent) => {
337
+ traverse(module, gqlIdentifiers, (object, _parent, callbackContext) => {
212
338
  if (needsFormatting) return;
339
+ if (callbackContext.isFragmentConfig) return;
213
340
  if (!hasExistingNewline(sourceCode, object.span.start - spanOffset)) needsFormatting = true;
214
341
  });
215
342
  return ok(needsFormatting);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["bodyObject: ObjectExpression | null","module: Module","insertionPoints: number[]"],"sources":["../src/detection.ts","../src/insertion.ts","../src/format.ts"],"sourcesContent":["import type {\n ArrowFunctionExpression,\n CallExpression,\n Expression,\n Module,\n ObjectExpression,\n ObjectPatternProperty,\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 if (node.type === \"Identifier\") {\n return gqlIdentifiers.has(node.value);\n }\n if (node.type === \"MemberExpression\" && node.property.type === \"Identifier\" && node.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\") 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 * The newline string to insert after object opening brace\n */\nexport const NEWLINE_INSERTION = \"\\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","import { parseSync } from \"@swc/core\";\nimport type { ArrowFunctionExpression, CallExpression, Module, Node, ObjectExpression } from \"@swc/types\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport { collectGqlIdentifiers, isFieldSelectionObject, isGqlDefinitionCall } from \"./detection\";\nimport { hasExistingNewline, NEWLINE_INSERTION } from \"./insertion\";\nimport type { FormatError, FormatOptions, FormatResult } from \"./types\";\n\ntype TraversalContext = {\n insideGqlDefinition: boolean;\n currentArrowFunction: ArrowFunctionExpression | null;\n};\n\n/**\n * Simple recursive AST traversal\n */\nconst traverseNode = (\n node: Node,\n context: TraversalContext,\n gqlIdentifiers: ReadonlySet<string>,\n onObjectExpression: (object: ObjectExpression, parent: ArrowFunctionExpression) => void,\n): void => {\n // Check for gql definition call entry\n if (node.type === \"CallExpression\" && isGqlDefinitionCall(node as CallExpression, gqlIdentifiers)) {\n context = { ...context, insideGqlDefinition: true };\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);\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 = (\n module: Module,\n gqlIdentifiers: ReadonlySet<string>,\n onObjectExpression: (object: ObjectExpression, parent: ArrowFunctionExpression) => void,\n): void => {\n for (const statement of module.body) {\n traverseNode(statement, { insideGqlDefinition: false, currentArrowFunction: null }, gqlIdentifiers, onObjectExpression);\n }\n};\n\n/**\n * Format soda-gql field selection objects by inserting newlines.\n * This preserves multi-line formatting when using Biome/Prettier.\n */\nexport const format = (options: FormatOptions): Result<FormatResult, 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 // Calculate span offset for position normalization\n // SWC's BytePos counter accumulates across parseSync calls within the same process\n const spanOffset = module.span.end - sourceCode.length + 1;\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: number[] = [];\n\n traverse(module, gqlIdentifiers, (object, _parent) => {\n // Calculate actual position in source\n const objectStart = object.span.start - spanOffset;\n\n // Check if already has newline\n if (hasExistingNewline(sourceCode, objectStart)) return;\n\n // Record insertion point (position after `{`)\n insertionPoints.push(objectStart + 1);\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 - a);\n\n let result = sourceCode;\n for (const pos of sortedPoints) {\n result = result.slice(0, pos) + NEWLINE_INSERTION + result.slice(pos);\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.end - sourceCode.length + 1;\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) => {\n if (needsFormatting) return; // Early exit\n\n const objectStart = object.span.start - spanOffset;\n if (!hasExistingNewline(sourceCode, objectStart)) {\n needsFormatting = true;\n }\n });\n\n return ok(needsFormatting);\n};\n"],"mappings":";;;;;;;;AAaA,MAAa,kBAAkB,MAAkB,mBAAiD;AAChG,KAAI,KAAK,SAAS,aAChB,QAAO,eAAe,IAAI,KAAK,MAAM;AAEvC,KAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,SAAS,gBAAgB,KAAK,SAAS,UAAU,MACrG,QAAO;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,YAAY,SAAS,WAAW,SAAS,0BAA2B,QAAO;AAEhF,QAAO;;;;;;AAOT,MAAa,0BAA0B,QAA0B,WAA6C;CAG5G,IAAIA,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Ae,YAAyD;CACnF,MAAM,EAAE,YAAY,aAAa;CAGjC,IAAID;AACJ,KAAI;EACF,MAAM,UAAU,UAAU,YAAY;GACpC,QAAQ;GACR,KAAK,UAAU,SAAS,OAAO,IAAI;GACnC,QAAQ;GACR,YAAY;GACZ,eAAe;GAChB,CAAC;AAEF,MAAI,QAAQ,SAAS,SACnB,QAAO,IAAI;GACT,MAAM;GACN,MAAM;GACN,SAAS,eAAe,WAAW,KAAK,SAAS,KAAK;GACvD,CAAC;AAEJ,WAAS;UACF,OAAO;AACd,SAAO,IAAI;GACT,MAAM;GACN,MAAM;GACN,SAAS,8BAA8B,WAAW,KAAK,SAAS,KAAK;GACrE;GACD,CAAC;;CAGJ,MAAM,aAAa,OAAO,KAAK,MAAM,WAAW,SAAS;CACzD,MAAM,iBAAiB,sBAAsB,OAAO;AAEpD,KAAI,eAAe,SAAS,EAC1B,QAAO,GAAG,MAAM;CAGlB,IAAI,kBAAkB;AAEtB,UAAS,QAAQ,iBAAiB,QAAQ,YAAY;AACpD,MAAI,gBAAiB;AAGrB,MAAI,CAAC,mBAAmB,YADJ,OAAO,KAAK,QAAQ,WACQ,CAC9C,mBAAkB;GAEpB;AAEF,QAAO,GAAG,gBAAgB"}
1
+ {"version":3,"file":"index.mjs","names":["bodyObject: ObjectExpression | null","initialContext: TraversalContext","module: Module","insertionPoints: InsertionPoint[]"],"sources":["../src/detection.ts","../src/insertion.ts","../src/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 if (node.type === \"Identifier\") {\n return gqlIdentifiers.has(node.value);\n }\n if (node.type === \"MemberExpression\" && node.property.type === \"Identifier\" && node.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\") 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 { parseSync } from \"@swc/core\";\nimport type { ArrowFunctionExpression, CallExpression, Module, Node, ObjectExpression } from \"@swc/types\";\nimport { err, ok, type Result } from \"neverthrow\";\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};\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 // 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\n const objectStart = 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 // 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 result = result.slice(0, point.position) + point.content + result.slice(point.position);\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 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 = object.span.start - spanOffset;\n if (!hasExistingNewline(sourceCode, objectStart)) {\n needsFormatting = true;\n }\n });\n\n return ok(needsFormatting);\n};\n"],"mappings":";;;;;;;;;AAcA,MAAa,kBAAkB,MAAkB,mBAAiD;AAChG,KAAI,KAAK,SAAS,aAChB,QAAO,eAAe,IAAI,KAAK,MAAM;AAEvC,KAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,SAAS,gBAAgB,KAAK,SAAS,UAAU,MACrG,QAAO;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,YAAY,SAAS,WAAW,SAAS,0BAA2B,QAAO;AAEhF,QAAO;;;;;;AAOT,MAAa,0BAA0B,QAA0B,WAA6C;C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GAAG,MAAM,EAAE,WAAW,EAAE,SAAS;CAEjF,IAAI,SAAS;AACb,MAAK,MAAM,SAAS,aAClB,UAAS,OAAO,MAAM,GAAG,MAAM,SAAS,GAAG,MAAM,UAAU,OAAO,MAAM,MAAM,SAAS;AAGzF,QAAO,GAAG;EAAE,UAAU;EAAM,YAAY;EAAQ,CAAC;;;;;;AAOnD,MAAa,eAAe,YAAyD;CACnF,MAAM,EAAE,YAAY,aAAa;CAGjC,IAAID;AACJ,KAAI;EACF,MAAM,UAAU,UAAU,YAAY;GACpC,QAAQ;GACR,KAAK,UAAU,SAAS,OAAO,IAAI;GACnC,QAAQ;GACR,YAAY;GACZ,eAAe;GAChB,CAAC;AAEF,MAAI,QAAQ,SAAS,SACnB,QAAO,IAAI;GACT,MAAM;GACN,MAAM;GACN,SAAS,eAAe,WAAW,KAAK,SAAS,KAAK;GACvD,CAAC;AAEJ,WAAS;UACF,OAAO;AACd,SAAO,IAAI;GACT,MAAM;GACN,MAAM;GACN,SAAS,8BAA8B,WAAW,KAAK,SAAS,KAAK;GACrE;GACD,CAAC;;CAGJ,MAAM,aAAa,OAAO,KAAK;CAC/B,MAAM,iBAAiB,sBAAsB,OAAO;AAEpD,KAAI,eAAe,SAAS,EAC1B,QAAO,GAAG,MAAM;CAGlB,IAAI,kBAAkB;AAEtB,UAAS,QAAQ,iBAAiB,QAAQ,SAAS,oBAAoB;AACrE,MAAI,gBAAiB;AAGrB,MAAI,gBAAgB,iBAAkB;AAGtC,MAAI,CAAC,mBAAmB,YADJ,OAAO,KAAK,QAAQ,WACQ,CAC9C,mBAAkB;GAEpB;AAEF,QAAO,GAAG,gBAAgB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soda-gql/formatter",
3
- "version": "0.10.2",
3
+ "version": "0.11.1",
4
4
  "description": "GraphQL document formatter for soda-gql",
5
5
  "type": "module",
6
6
  "private": false,