@soda-gql/formatter 0.12.2 → 0.12.4
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 +72 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +72 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +12 -4
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
let node_module = require("node:module");
|
|
2
|
+
let __soda_gql_common_template_extraction = require("@soda-gql/common/template-extraction");
|
|
3
|
+
let __soda_gql_common_utils = require("@soda-gql/common/utils");
|
|
1
4
|
let __swc_core = require("@swc/core");
|
|
2
5
|
let neverthrow = require("neverthrow");
|
|
3
6
|
let node_crypto = require("node:crypto");
|
|
@@ -8,8 +11,9 @@ let node_crypto = require("node:crypto");
|
|
|
8
11
|
* Handles: gql, namespace.gql
|
|
9
12
|
*/
|
|
10
13
|
const isGqlReference = (node, gqlIdentifiers) => {
|
|
11
|
-
|
|
12
|
-
if (
|
|
14
|
+
const unwrapped = node.type === "TsNonNullExpression" ? node.expression : node;
|
|
15
|
+
if (unwrapped.type === "Identifier") return gqlIdentifiers.has(unwrapped.value);
|
|
16
|
+
if (unwrapped.type === "MemberExpression" && unwrapped.property.type === "Identifier" && unwrapped.property.value === "gql") return true;
|
|
13
17
|
return false;
|
|
14
18
|
};
|
|
15
19
|
/**
|
|
@@ -21,7 +25,7 @@ const isGqlDefinitionCall = (node, gqlIdentifiers) => {
|
|
|
21
25
|
const { object } = node.callee;
|
|
22
26
|
if (!isGqlReference(object, gqlIdentifiers)) return false;
|
|
23
27
|
const firstArg = node.arguments[0];
|
|
24
|
-
if (!firstArg || firstArg.expression.type !== "ArrowFunctionExpression") return false;
|
|
28
|
+
if (!firstArg || firstArg.expression.type !== "ArrowFunctionExpression" && firstArg.expression.type !== "FunctionExpression") return false;
|
|
25
29
|
return true;
|
|
26
30
|
};
|
|
27
31
|
/**
|
|
@@ -176,6 +180,28 @@ const detectIndentationAfterBrace = (source, objectStartPos) => {
|
|
|
176
180
|
|
|
177
181
|
//#endregion
|
|
178
182
|
//#region packages/formatter/src/format.ts
|
|
183
|
+
const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
184
|
+
let _graphqlModule;
|
|
185
|
+
let _graphqlModuleError;
|
|
186
|
+
const getGraphqlModule = () => {
|
|
187
|
+
if (_graphqlModuleError) return (0, neverthrow.err)({
|
|
188
|
+
type: "FormatError",
|
|
189
|
+
code: "MISSING_DEPENDENCY",
|
|
190
|
+
message: "The \"graphql\" package is required for --format-tagged-templates. Install it with: bun add graphql"
|
|
191
|
+
});
|
|
192
|
+
if (!_graphqlModule) try {
|
|
193
|
+
_graphqlModule = require$1("graphql");
|
|
194
|
+
} catch (cause) {
|
|
195
|
+
_graphqlModuleError = cause instanceof Error ? cause : new Error(String(cause));
|
|
196
|
+
return (0, neverthrow.err)({
|
|
197
|
+
type: "FormatError",
|
|
198
|
+
code: "MISSING_DEPENDENCY",
|
|
199
|
+
message: "The \"graphql\" package is required for --format-tagged-templates. Install it with: bun add graphql",
|
|
200
|
+
cause
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
return (0, neverthrow.ok)(_graphqlModule);
|
|
204
|
+
};
|
|
179
205
|
/**
|
|
180
206
|
* Simple recursive AST traversal
|
|
181
207
|
*/
|
|
@@ -236,7 +262,7 @@ const traverse = (module$1, gqlIdentifiers, onObjectExpression) => {
|
|
|
236
262
|
* Optionally injects fragment keys for anonymous fragments.
|
|
237
263
|
*/
|
|
238
264
|
const format = (options) => {
|
|
239
|
-
const { sourceCode, filePath, injectFragmentKeys = false } = options;
|
|
265
|
+
const { sourceCode, filePath, injectFragmentKeys = false, formatTaggedTemplates = false } = options;
|
|
240
266
|
let module$1;
|
|
241
267
|
try {
|
|
242
268
|
const program = (0, __swc_core.parseSync)(sourceCode, {
|
|
@@ -289,13 +315,37 @@ const format = (options) => {
|
|
|
289
315
|
content: NEWLINE_INSERTION
|
|
290
316
|
});
|
|
291
317
|
});
|
|
318
|
+
if (formatTaggedTemplates) {
|
|
319
|
+
const graphqlResult = getGraphqlModule();
|
|
320
|
+
if (graphqlResult.isErr()) return (0, neverthrow.err)(graphqlResult.error);
|
|
321
|
+
const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;
|
|
322
|
+
const positionCtx = {
|
|
323
|
+
spanOffset,
|
|
324
|
+
converter: (0, __soda_gql_common_utils.createSwcSpanConverter)(sourceCode)
|
|
325
|
+
};
|
|
326
|
+
const templates = (0, __soda_gql_common_template_extraction.walkAndExtract)(module$1, gqlIdentifiers, positionCtx);
|
|
327
|
+
if (templates.length > 0) {
|
|
328
|
+
const defaultFormat = (source) => {
|
|
329
|
+
return printGraphql(parseGraphql(source, { noLocation: false }));
|
|
330
|
+
};
|
|
331
|
+
const templateEdits = (0, __soda_gql_common_template_extraction.formatTemplatesInSource)(templates, sourceCode, defaultFormat);
|
|
332
|
+
for (const edit of templateEdits) insertionPoints.push({
|
|
333
|
+
position: edit.start,
|
|
334
|
+
content: edit.newText,
|
|
335
|
+
endPosition: edit.end
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
}
|
|
292
339
|
if (insertionPoints.length === 0) return (0, neverthrow.ok)({
|
|
293
340
|
modified: false,
|
|
294
341
|
sourceCode
|
|
295
342
|
});
|
|
296
343
|
const sortedPoints = [...insertionPoints].sort((a, b) => b.position - a.position);
|
|
297
344
|
let result = sourceCode;
|
|
298
|
-
for (const point of sortedPoints)
|
|
345
|
+
for (const point of sortedPoints) {
|
|
346
|
+
const end = point.endPosition ?? point.position;
|
|
347
|
+
result = result.slice(0, point.position) + point.content + result.slice(end);
|
|
348
|
+
}
|
|
299
349
|
return (0, neverthrow.ok)({
|
|
300
350
|
modified: true,
|
|
301
351
|
sourceCode: result
|
|
@@ -306,7 +356,7 @@ const format = (options) => {
|
|
|
306
356
|
* Useful for pre-commit hooks or CI checks.
|
|
307
357
|
*/
|
|
308
358
|
const needsFormat = (options) => {
|
|
309
|
-
const { sourceCode, filePath } = options;
|
|
359
|
+
const { sourceCode, filePath, formatTaggedTemplates = false } = options;
|
|
310
360
|
let module$1;
|
|
311
361
|
try {
|
|
312
362
|
const program = (0, __swc_core.parseSync)(sourceCode, {
|
|
@@ -339,6 +389,22 @@ const needsFormat = (options) => {
|
|
|
339
389
|
if (callbackContext.isFragmentConfig) return;
|
|
340
390
|
if (!hasExistingNewline(sourceCode, object.span.start - spanOffset)) needsFormatting = true;
|
|
341
391
|
});
|
|
392
|
+
if (!needsFormatting && formatTaggedTemplates) {
|
|
393
|
+
const graphqlResult = getGraphqlModule();
|
|
394
|
+
if (graphqlResult.isErr()) return (0, neverthrow.err)(graphqlResult.error);
|
|
395
|
+
const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;
|
|
396
|
+
const positionCtx = {
|
|
397
|
+
spanOffset,
|
|
398
|
+
converter: (0, __soda_gql_common_utils.createSwcSpanConverter)(sourceCode)
|
|
399
|
+
};
|
|
400
|
+
const templates = (0, __soda_gql_common_template_extraction.walkAndExtract)(module$1, gqlIdentifiers, positionCtx);
|
|
401
|
+
if (templates.length > 0) {
|
|
402
|
+
const defaultFormat = (source) => {
|
|
403
|
+
return printGraphql(parseGraphql(source, { noLocation: false }));
|
|
404
|
+
};
|
|
405
|
+
if ((0, __soda_gql_common_template_extraction.formatTemplatesInSource)(templates, sourceCode, defaultFormat).length > 0) needsFormatting = true;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
342
408
|
return (0, neverthrow.ok)(needsFormatting);
|
|
343
409
|
};
|
|
344
410
|
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;\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,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gBAAgB,iBAAkB;AAGtC,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","require","_graphqlModule: GraphqlModule | undefined","_graphqlModuleError: Error | undefined","initialContext: TraversalContext","module","module: Module","insertionPoints: InsertionPoint[]","positionCtx: PositionTrackingContext","defaultFormat: FormatGraphqlFn"],"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 // 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 --format-tagged-templates. 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 --format-tagged-templates. 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, formatTaggedTemplates = 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 // Tagged template formatting (when enabled)\n if (formatTaggedTemplates) {\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 converter = createSwcSpanConverter(sourceCode);\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\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, formatTaggedTemplates = 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 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 // Check tagged templates when enabled\n if (!needsFormatting && formatTaggedTemplates) {\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 converter = createSwcSpanConverter(sourceCode);\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,aACrB,QAAO,eAAe,IAAI,UAAU,MAAM;AAE5C,KAAI,UAAU,SAAS,sBAAsB,UAAU,SAAS,SAAS,gBAAgB,UAAU,SAAS,UAAU,MACpH,QAAO;AAET,QAAO;;;;;;AAOT,MAAa,uBAAuB,MAAsB,mBAAiD;AACzG,KAAI,KAAK,OAAO,SAAS,mBAAoB,QAAO;CACpD,MAAM,EAAE,WAAW,KAAK;AAGxB,KAAI,CAAC,eAA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O,CAAC,CAC/B;;AAI1B,0EAD8C,WAAW,YAAY,cAAc,CACjE,SAAS,EACzB,mBAAkB;;;AAKxB,2BAAU,gBAAgB"}
|
package/dist/index.d.cts
CHANGED
|
@@ -5,6 +5,7 @@ type FormatOptions = {
|
|
|
5
5
|
readonly sourceCode: string;
|
|
6
6
|
readonly filePath?: string;
|
|
7
7
|
readonly injectFragmentKeys?: boolean;
|
|
8
|
+
readonly formatTaggedTemplates?: boolean;
|
|
8
9
|
};
|
|
9
10
|
type FormatResult = {
|
|
10
11
|
readonly modified: boolean;
|
|
@@ -12,7 +13,7 @@ type FormatResult = {
|
|
|
12
13
|
};
|
|
13
14
|
type FormatError = {
|
|
14
15
|
readonly type: "FormatError";
|
|
15
|
-
readonly code: "PARSE_ERROR" | "TRANSFORM_ERROR";
|
|
16
|
+
readonly code: "PARSE_ERROR" | "TRANSFORM_ERROR" | "MISSING_DEPENDENCY";
|
|
16
17
|
readonly message: string;
|
|
17
18
|
readonly cause?: unknown;
|
|
18
19
|
};
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;EAOb,SAAA,qBAAY,CAAA,EAAA,OAAA;AAKxB,CAAA;KALY,YAAA;;;ACmMZ,CAAA;AAAgC,KD9LpB,WAAA,GC8LoB;EAAuB,SAAA,IAAA,EAAA,aAAA;EAAc,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA,GAAA,oBAAA;EAArB,SAAA,OAAA,EAAA,MAAA;EAAM,SAAA,KAAA,CAAA,EAAA,OAAA;AAqItD,CAAA;;;;AD/UA;AAOA;AAKA;cC8La,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cAqI1C,WArI0C,EAAA,CAAA,OAAA,EAqIlB,aArIkB,EAAA,GAqIF,MArIE,CAAA,OAAA,EAqIc,WArId,CAAA"}
|
package/dist/index.d.mts
CHANGED
|
@@ -5,6 +5,7 @@ type FormatOptions = {
|
|
|
5
5
|
readonly sourceCode: string;
|
|
6
6
|
readonly filePath?: string;
|
|
7
7
|
readonly injectFragmentKeys?: boolean;
|
|
8
|
+
readonly formatTaggedTemplates?: boolean;
|
|
8
9
|
};
|
|
9
10
|
type FormatResult = {
|
|
10
11
|
readonly modified: boolean;
|
|
@@ -12,7 +13,7 @@ type FormatResult = {
|
|
|
12
13
|
};
|
|
13
14
|
type FormatError = {
|
|
14
15
|
readonly type: "FormatError";
|
|
15
|
-
readonly code: "PARSE_ERROR" | "TRANSFORM_ERROR";
|
|
16
|
+
readonly code: "PARSE_ERROR" | "TRANSFORM_ERROR" | "MISSING_DEPENDENCY";
|
|
16
17
|
readonly message: string;
|
|
17
18
|
readonly cause?: unknown;
|
|
18
19
|
};
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;EAOb,SAAA,qBAAY,CAAA,EAAA,OAAA;AAKxB,CAAA;KALY,YAAA;;;ACmMZ,CAAA;AAAgC,KD9LpB,WAAA,GC8LoB;EAAuB,SAAA,IAAA,EAAA,aAAA;EAAc,SAAA,IAAA,EAAA,aAAA,GAAA,iBAAA,GAAA,oBAAA;EAArB,SAAA,OAAA,EAAA,MAAA;EAAM,SAAA,KAAA,CAAA,EAAA,OAAA;AAqItD,CAAA;;;;AD/UA;AAOA;AAKA;cC8La,kBAAmB,kBAAgB,OAAO,cAAc;;;AAArE;;AAAuD,cAqI1C,WArI0C,EAAA,CAAA,OAAA,EAqIlB,aArIkB,EAAA,GAqIF,MArIE,CAAA,OAAA,EAqIc,WArId,CAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { formatTemplatesInSource, walkAndExtract } from "@soda-gql/common/template-extraction";
|
|
3
|
+
import { createSwcSpanConverter } from "@soda-gql/common/utils";
|
|
1
4
|
import { parseSync } from "@swc/core";
|
|
2
5
|
import { err, ok } from "neverthrow";
|
|
3
6
|
import { randomBytes } from "node:crypto";
|
|
@@ -8,8 +11,9 @@ import { randomBytes } from "node:crypto";
|
|
|
8
11
|
* Handles: gql, namespace.gql
|
|
9
12
|
*/
|
|
10
13
|
const isGqlReference = (node, gqlIdentifiers) => {
|
|
11
|
-
|
|
12
|
-
if (
|
|
14
|
+
const unwrapped = node.type === "TsNonNullExpression" ? node.expression : node;
|
|
15
|
+
if (unwrapped.type === "Identifier") return gqlIdentifiers.has(unwrapped.value);
|
|
16
|
+
if (unwrapped.type === "MemberExpression" && unwrapped.property.type === "Identifier" && unwrapped.property.value === "gql") return true;
|
|
13
17
|
return false;
|
|
14
18
|
};
|
|
15
19
|
/**
|
|
@@ -21,7 +25,7 @@ const isGqlDefinitionCall = (node, gqlIdentifiers) => {
|
|
|
21
25
|
const { object } = node.callee;
|
|
22
26
|
if (!isGqlReference(object, gqlIdentifiers)) return false;
|
|
23
27
|
const firstArg = node.arguments[0];
|
|
24
|
-
if (!firstArg || firstArg.expression.type !== "ArrowFunctionExpression") return false;
|
|
28
|
+
if (!firstArg || firstArg.expression.type !== "ArrowFunctionExpression" && firstArg.expression.type !== "FunctionExpression") return false;
|
|
25
29
|
return true;
|
|
26
30
|
};
|
|
27
31
|
/**
|
|
@@ -176,6 +180,28 @@ const detectIndentationAfterBrace = (source, objectStartPos) => {
|
|
|
176
180
|
|
|
177
181
|
//#endregion
|
|
178
182
|
//#region packages/formatter/src/format.ts
|
|
183
|
+
const require = createRequire(import.meta.url);
|
|
184
|
+
let _graphqlModule;
|
|
185
|
+
let _graphqlModuleError;
|
|
186
|
+
const getGraphqlModule = () => {
|
|
187
|
+
if (_graphqlModuleError) return err({
|
|
188
|
+
type: "FormatError",
|
|
189
|
+
code: "MISSING_DEPENDENCY",
|
|
190
|
+
message: "The \"graphql\" package is required for --format-tagged-templates. Install it with: bun add graphql"
|
|
191
|
+
});
|
|
192
|
+
if (!_graphqlModule) try {
|
|
193
|
+
_graphqlModule = require("graphql");
|
|
194
|
+
} catch (cause) {
|
|
195
|
+
_graphqlModuleError = cause instanceof Error ? cause : new Error(String(cause));
|
|
196
|
+
return err({
|
|
197
|
+
type: "FormatError",
|
|
198
|
+
code: "MISSING_DEPENDENCY",
|
|
199
|
+
message: "The \"graphql\" package is required for --format-tagged-templates. Install it with: bun add graphql",
|
|
200
|
+
cause
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
return ok(_graphqlModule);
|
|
204
|
+
};
|
|
179
205
|
/**
|
|
180
206
|
* Simple recursive AST traversal
|
|
181
207
|
*/
|
|
@@ -236,7 +262,7 @@ const traverse = (module, gqlIdentifiers, onObjectExpression) => {
|
|
|
236
262
|
* Optionally injects fragment keys for anonymous fragments.
|
|
237
263
|
*/
|
|
238
264
|
const format = (options) => {
|
|
239
|
-
const { sourceCode, filePath, injectFragmentKeys = false } = options;
|
|
265
|
+
const { sourceCode, filePath, injectFragmentKeys = false, formatTaggedTemplates = false } = options;
|
|
240
266
|
let module;
|
|
241
267
|
try {
|
|
242
268
|
const program = parseSync(sourceCode, {
|
|
@@ -289,13 +315,37 @@ const format = (options) => {
|
|
|
289
315
|
content: NEWLINE_INSERTION
|
|
290
316
|
});
|
|
291
317
|
});
|
|
318
|
+
if (formatTaggedTemplates) {
|
|
319
|
+
const graphqlResult = getGraphqlModule();
|
|
320
|
+
if (graphqlResult.isErr()) return err(graphqlResult.error);
|
|
321
|
+
const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;
|
|
322
|
+
const positionCtx = {
|
|
323
|
+
spanOffset,
|
|
324
|
+
converter: createSwcSpanConverter(sourceCode)
|
|
325
|
+
};
|
|
326
|
+
const templates = walkAndExtract(module, gqlIdentifiers, positionCtx);
|
|
327
|
+
if (templates.length > 0) {
|
|
328
|
+
const defaultFormat = (source) => {
|
|
329
|
+
return printGraphql(parseGraphql(source, { noLocation: false }));
|
|
330
|
+
};
|
|
331
|
+
const templateEdits = formatTemplatesInSource(templates, sourceCode, defaultFormat);
|
|
332
|
+
for (const edit of templateEdits) insertionPoints.push({
|
|
333
|
+
position: edit.start,
|
|
334
|
+
content: edit.newText,
|
|
335
|
+
endPosition: edit.end
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
}
|
|
292
339
|
if (insertionPoints.length === 0) return ok({
|
|
293
340
|
modified: false,
|
|
294
341
|
sourceCode
|
|
295
342
|
});
|
|
296
343
|
const sortedPoints = [...insertionPoints].sort((a, b) => b.position - a.position);
|
|
297
344
|
let result = sourceCode;
|
|
298
|
-
for (const point of sortedPoints)
|
|
345
|
+
for (const point of sortedPoints) {
|
|
346
|
+
const end = point.endPosition ?? point.position;
|
|
347
|
+
result = result.slice(0, point.position) + point.content + result.slice(end);
|
|
348
|
+
}
|
|
299
349
|
return ok({
|
|
300
350
|
modified: true,
|
|
301
351
|
sourceCode: result
|
|
@@ -306,7 +356,7 @@ const format = (options) => {
|
|
|
306
356
|
* Useful for pre-commit hooks or CI checks.
|
|
307
357
|
*/
|
|
308
358
|
const needsFormat = (options) => {
|
|
309
|
-
const { sourceCode, filePath } = options;
|
|
359
|
+
const { sourceCode, filePath, formatTaggedTemplates = false } = options;
|
|
310
360
|
let module;
|
|
311
361
|
try {
|
|
312
362
|
const program = parseSync(sourceCode, {
|
|
@@ -339,6 +389,22 @@ const needsFormat = (options) => {
|
|
|
339
389
|
if (callbackContext.isFragmentConfig) return;
|
|
340
390
|
if (!hasExistingNewline(sourceCode, object.span.start - spanOffset)) needsFormatting = true;
|
|
341
391
|
});
|
|
392
|
+
if (!needsFormatting && formatTaggedTemplates) {
|
|
393
|
+
const graphqlResult = getGraphqlModule();
|
|
394
|
+
if (graphqlResult.isErr()) return err(graphqlResult.error);
|
|
395
|
+
const { parse: parseGraphql, print: printGraphql } = graphqlResult.value;
|
|
396
|
+
const positionCtx = {
|
|
397
|
+
spanOffset,
|
|
398
|
+
converter: createSwcSpanConverter(sourceCode)
|
|
399
|
+
};
|
|
400
|
+
const templates = walkAndExtract(module, gqlIdentifiers, positionCtx);
|
|
401
|
+
if (templates.length > 0) {
|
|
402
|
+
const defaultFormat = (source) => {
|
|
403
|
+
return printGraphql(parseGraphql(source, { noLocation: false }));
|
|
404
|
+
};
|
|
405
|
+
if (formatTemplatesInSource(templates, sourceCode, defaultFormat).length > 0) needsFormatting = true;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
342
408
|
return ok(needsFormatting);
|
|
343
409
|
};
|
|
344
410
|
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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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AAC,GAAG,gBAAgB,CAAC,MAAM,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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["bodyObject: ObjectExpression | null","_graphqlModule: GraphqlModule | undefined","_graphqlModuleError: Error | undefined","initialContext: TraversalContext","module: Module","insertionPoints: InsertionPoint[]","positionCtx: PositionTrackingContext","defaultFormat: FormatGraphqlFn"],"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 // 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 --format-tagged-templates. 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 --format-tagged-templates. 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, formatTaggedTemplates = 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 // Tagged template formatting (when enabled)\n if (formatTaggedTemplates) {\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 converter = createSwcSpanConverter(sourceCode);\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\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, formatTaggedTemplates = 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 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 // Check tagged templates when enabled\n if (!needsFormatting && formatTaggedTemplates) {\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 converter = createSwcSpanConverter(sourceCode);\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,aACrB,QAAO,eAAe,IAAI,UAAU,MAAM;AAE5C,KAAI,UAAU,SAAS,sBAAsB,UAAU,SAAS,SAAS,gBAAgB,UAAU,SAAS,UAAU,MACpH,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,YAAa,SAAS,WAAW,SAAS,6BAA6B,SAAS,WAAW,SAAS,qBACvG,QAAO;AAET,QAAO;;;;;;AAOT,MAAa,0BAA0B,QAA0B,WAA6C;CAG5G,IAAIA,aAAsC;AAE1C,KAAI,OAAO,KAAK,SAAS,mBACvB,cAAa,OAAO;UACX,OAAO,KAAK,SAAS,yBAAyB;EAEvD,MA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-gql/formatter",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.4",
|
|
4
4
|
"description": "GraphQL document formatter for soda-gql",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
@@ -48,13 +48,21 @@
|
|
|
48
48
|
"./package.json": "./package.json"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
+
"@soda-gql/common": "0.12.4",
|
|
51
52
|
"neverthrow": "^8.1.1"
|
|
52
53
|
},
|
|
53
54
|
"devDependencies": {
|
|
54
|
-
"@swc/types": "^0.1.0"
|
|
55
|
+
"@swc/types": "^0.1.0",
|
|
56
|
+
"graphql": "^16.11.0"
|
|
55
57
|
},
|
|
56
58
|
"peerDependencies": {
|
|
57
|
-
"@swc/core": "^1.0.0"
|
|
59
|
+
"@swc/core": "^1.0.0",
|
|
60
|
+
"graphql": "^16.11.0"
|
|
58
61
|
},
|
|
59
|
-
"optionalDependencies": {}
|
|
62
|
+
"optionalDependencies": {},
|
|
63
|
+
"peerDependenciesMeta": {
|
|
64
|
+
"graphql": {
|
|
65
|
+
"optional": true
|
|
66
|
+
}
|
|
67
|
+
}
|
|
60
68
|
}
|