@sanity/codegen 8.1.0 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/expressionResolvers.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions, traverse} from '@babel/core'\nimport {Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {parseSourceFile} from './parseSource.js'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = new Set(['groq'])\nconst FUNCTION_WRAPPER_ALLOW_LIST = new Set(['defineQuery'])\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments = [],\n node,\n params = [],\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments?: babelTypes.Node[]\n node: babelTypes.Node\n params?: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.has(node.tag.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.quasi,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: expression,\n params,\n resolver,\n scope,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n const init = node.init ?? (babelTypes.isAssignmentPattern(node.id) && node.id.right)\n if (!init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: init,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.has(node.callee.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.arguments[0]!,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n const newScope = new Scope(scope.path, scope)\n\n for (const [i, param] of params.entries()) {\n newScope.push({\n id: param as babelTypes.LVal,\n init: fnArguments[i] as babelTypes.Expression | undefined,\n })\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.body,\n params: node.params,\n resolver,\n scope: newScope,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.callee,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({babelConfig, file, filename, fnArguments, node, resolver})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.right,\n params,\n resolver,\n scope,\n })\n }\n\n // Handle TypeScript type assertions (e.g., `'foo' as string`)\n if (babelTypes.isTSAsExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.expression,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: prop.value,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.Identifier\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n let argument = fnArguments[paramIndex]\n if (!argument && paramIndex !== -1 && babelTypes.isAssignmentPattern(params[paramIndex])) {\n argument = params[paramIndex].right\n }\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: argument,\n params,\n resolver,\n scope,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: binding.path.node,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n babelConfig,\n file,\n filename,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.CallExpression\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments: node.arguments,\n node: callee,\n params,\n resolver,\n scope,\n })\n}\n\nfunction resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}) {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (\n babelTypes.isImportDefaultSpecifier(specifier) &&\n specifier.local.loc?.identifierName === node.local.name\n ) {\n importDeclaration = n.node\n break\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name\n const importFileName = importDeclaration.source.value\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let scope: Scope | undefined\n traverse(tree, {\n Program(p) {\n scope = p.scope\n },\n })\n if (!scope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = scope.getBinding(importName)\n return {binding, importFileName, importName, resolvedFile, scope, tree}\n}\n\nfunction resolveImportSpecifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName: newImportName,\n node: namedExport,\n resolver,\n })\n }\n\n let result: resolveExpressionReturnType | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportAllDeclaration') {\n try {\n result = resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName,\n node: p.node,\n resolver,\n })\n } catch (e) {\n if ((e as Error).cause !== `noBinding:${importName}`) throw e\n }\n }\n },\n })\n if (result) return result\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n babelConfig,\n filename,\n fnArguments,\n importName,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n filename: string\n fnArguments: babelTypes.Node[]\n importName: string\n node: babelTypes.ExportAllDeclaration | babelTypes.ExportNamedDeclaration\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope: newScope,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`, {\n cause: `noBinding:${importName}`,\n })\n}\n\nfunction getMemberPropertyName(node: babelTypes.MemberExpression): string {\n const {computed, loc, property} = node\n if (!computed && babelTypes.isIdentifier(property)) {\n return property.name\n }\n if (computed && babelTypes.isStringLiteral(property)) {\n return property.value\n }\n const locInfo = loc ? `${loc.filename}:${loc.start.line}:${loc.start.column}` : 'unknown location'\n throw new Error(`Unsupported MemberExpression property type: ${property.type} @ ${locInfo}`)\n}\n\nfunction findObjectProperty(\n objExpr: babelTypes.ObjectExpression,\n propertyName: string,\n filename: string,\n node: babelTypes.Node,\n): babelTypes.ObjectProperty {\n for (const prop of objExpr.properties) {\n if (!babelTypes.isObjectProperty(prop)) continue\n if (babelTypes.isIdentifier(prop.key) && prop.key.name === propertyName) {\n return prop\n }\n if (babelTypes.isStringLiteral(prop.key) && prop.key.value === propertyName) {\n return prop\n }\n }\n throw new Error(\n `Could not find property \"${propertyName}\" in object expression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.Node\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): babelTypes.ObjectExpression {\n if (babelTypes.isObjectExpression(node)) {\n return node\n }\n if (babelTypes.isTSAsExpression(node)) {\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.expression,\n resolver,\n scope,\n })\n }\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n throw new Error(`Could not find binding for \"${node.name}\" in ${filename}`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Variable declarator has no init`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.init,\n resolver,\n scope,\n })\n }\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: prop.value,\n resolver,\n scope,\n })\n }\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportToObjectExpression({babelConfig, file, filename, node, resolver})\n }\n throw new Error(\n `Cannot resolve node type \"${node.type}\" to ObjectExpression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveImportToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): babelTypes.ObjectExpression {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (!binding) {\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n }\n\n return resolveToObjectExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n node: binding.path.node,\n resolver,\n scope,\n })\n}\n"],"names":["fs","path","traverse","Scope","babelTypes","createDebug","formatPath","parseSourceFile","debug","TAGGED_TEMPLATE_ALLOW_LIST","Set","FUNCTION_WRAPPER_ALLOW_LIST","resolveExpression","babelConfig","file","filename","fnArguments","node","params","resolver","scope","type","loc","start","line","column","isTaggedTemplateExpression","isIdentifier","tag","has","name","quasi","isTemplateLiteral","resolvedExpressions","expressions","map","expression","quasis","idx","value","cooked","join","isLiteral","Error","toString","resolveIdentifier","isVariableDeclarator","init","isAssignmentPattern","id","right","isCallExpression","callee","arguments","resolveCallExpression","isArrowFunctionExpression","isFunctionDeclaration","isFunctionExpression","newScope","i","param","entries","push","body","isNewExpression","isImportDefaultSpecifier","isImportSpecifier","resolveImportSpecifier","isTSAsExpression","isMemberExpression","propertyName","getMemberPropertyName","objExpr","resolveToObjectExpression","object","prop","findObjectProperty","paramIndex","findIndex","left","argument","binding","getBinding","isSame","resolveImportBinding","importDeclaration","ImportDeclaration","n","isImportDeclaration","specifier","specifiers","local","identifierName","importName","importFileName","source","importPath","startsWith","resolve","dirname","resolvedFile","readFileSync","tree","Program","p","namedExport","newImportName","ExportDeclaration","exported","resolveExportSpecifier","result","e","cause","computed","property","isStringLiteral","locInfo","properties","isObjectProperty","key","isObjectExpression","resolveImportToObjectExpression"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAA+BC,QAAQ,QAAO,cAAa;AAC3D,SAAQC,KAAK,QAAO,kBAAiB;AACrC,YA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AqB;QAC5FvE;QACAC;QACAC;QACAE;QACAE;IACF;IAEA,IAAI,CAAC8D,SAAS;QACZ,MAAM,IAAItC,MAAM,CAAC,mCAAmC,EAAEkD,WAAW,KAAK,EAAEC,gBAAgB;IAC1F;IAEA,OAAOrB,0BAA0B;QAC/B5D;QACAC,MAAMwF;QACNvF,UAAUqF;QACVnF,MAAMgE,QAAQhF,IAAI,CAACgB,IAAI;QACvBE;QACAC;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/expressionResolvers.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions, traverse} from '@babel/core'\nimport {Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport {createDebug} from 'obug'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {parseSourceFile} from './parseSource.js'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = new Set(['groq'])\nconst FUNCTION_WRAPPER_ALLOW_LIST = new Set(['defineQuery'])\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments = [],\n node,\n params = [],\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments?: babelTypes.Node[]\n node: babelTypes.Node\n params?: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.has(node.tag.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.quasi,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: expression,\n params,\n resolver,\n scope,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n const init = node.init ?? (babelTypes.isAssignmentPattern(node.id) && node.id.right)\n if (!init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: init,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.has(node.callee.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.arguments[0]!,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n const newScope = new Scope(scope.path, scope)\n\n for (const [i, param] of params.entries()) {\n newScope.push({\n id: param as babelTypes.LVal,\n init: fnArguments[i] as babelTypes.Expression | undefined,\n })\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.body,\n params: node.params,\n resolver,\n scope: newScope,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.callee,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({babelConfig, file, filename, fnArguments, node, resolver})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.right,\n params,\n resolver,\n scope,\n })\n }\n\n // Handle TypeScript type assertions (e.g., `'foo' as string`)\n if (babelTypes.isTSAsExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.expression,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: prop.value,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.Identifier\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n let argument = fnArguments[paramIndex]\n if (!argument && paramIndex !== -1 && babelTypes.isAssignmentPattern(params[paramIndex])) {\n argument = params[paramIndex].right\n }\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: argument,\n params,\n resolver,\n scope,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: binding.path.node,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n babelConfig,\n file,\n filename,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.CallExpression\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments: node.arguments,\n node: callee,\n params,\n resolver,\n scope,\n })\n}\n\nfunction resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}) {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (\n babelTypes.isImportDefaultSpecifier(specifier) &&\n specifier.local.loc?.identifierName === node.local.name\n ) {\n importDeclaration = n.node\n break\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name\n const importFileName = importDeclaration.source.value\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let scope: Scope | undefined\n traverse(tree, {\n Program(p) {\n scope = p.scope\n },\n })\n if (!scope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = scope.getBinding(importName)\n return {binding, importFileName, importName, resolvedFile, scope, tree}\n}\n\nfunction resolveImportSpecifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName: newImportName,\n node: namedExport,\n resolver,\n })\n }\n\n let result: resolveExpressionReturnType | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportAllDeclaration') {\n try {\n result = resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName,\n node: p.node,\n resolver,\n })\n } catch (e) {\n if ((e as Error).cause !== `noBinding:${importName}`) throw e\n }\n }\n },\n })\n if (result) return result\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n babelConfig,\n filename,\n fnArguments,\n importName,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n filename: string\n fnArguments: babelTypes.Node[]\n importName: string\n node: babelTypes.ExportAllDeclaration | babelTypes.ExportNamedDeclaration\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope: newScope,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`, {\n cause: `noBinding:${importName}`,\n })\n}\n\nfunction getMemberPropertyName(node: babelTypes.MemberExpression): string {\n const {computed, loc, property} = node\n if (!computed && babelTypes.isIdentifier(property)) {\n return property.name\n }\n if (computed && babelTypes.isStringLiteral(property)) {\n return property.value\n }\n const locInfo = loc ? `${loc.filename}:${loc.start.line}:${loc.start.column}` : 'unknown location'\n throw new Error(`Unsupported MemberExpression property type: ${property.type} @ ${locInfo}`)\n}\n\nfunction findObjectProperty(\n objExpr: babelTypes.ObjectExpression,\n propertyName: string,\n filename: string,\n node: babelTypes.Node,\n): babelTypes.ObjectProperty {\n for (const prop of objExpr.properties) {\n if (!babelTypes.isObjectProperty(prop)) continue\n if (babelTypes.isIdentifier(prop.key) && prop.key.name === propertyName) {\n return prop\n }\n if (babelTypes.isStringLiteral(prop.key) && prop.key.value === propertyName) {\n return prop\n }\n }\n throw new Error(\n `Could not find property \"${propertyName}\" in object expression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.Node\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): babelTypes.ObjectExpression {\n if (babelTypes.isObjectExpression(node)) {\n return node\n }\n if (babelTypes.isTSAsExpression(node)) {\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.expression,\n resolver,\n scope,\n })\n }\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n throw new Error(`Could not find binding for \"${node.name}\" in ${filename}`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Variable declarator has no init`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.init,\n resolver,\n scope,\n })\n }\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: prop.value,\n resolver,\n scope,\n })\n }\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportToObjectExpression({babelConfig, file, filename, node, resolver})\n }\n throw new Error(\n `Cannot resolve node type \"${node.type}\" to ObjectExpression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveImportToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): babelTypes.ObjectExpression {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (!binding) {\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n }\n\n return resolveToObjectExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n node: binding.path.node,\n resolver,\n scope,\n })\n}\n"],"names":["fs","path","traverse","Scope","babelTypes","createDebug","formatPath","parseSourceFile","debug","TAGGED_TEMPLATE_ALLOW_LIST","Set","FUNCTION_WRAPPER_ALLOW_LIST","resolveExpression","babelConfig","file","filename","fnArguments","node","params","resolver","scope","type","loc","start","line","column","isTaggedTemplateExpression","isIdentifier","tag","has","name","quasi","isTemplateLiteral","resolvedExpressions","expressions","map","expression","quasis","idx","value","cooked","join","isLiteral","Error","toString","resolveIdentifier","isVariableDeclarator","init","isAssignmentPattern","id","right","isCallExpression","callee","arguments","resolveCallExpression","isArrowFunctionExpression","isFunctionDeclaration","isFunctionExpression","newScope","i","param","entries","push","body","isNewExpression","isImportDefaultSpecifier","isImportSpecifier","resolveImportSpecifier","isTSAsExpression","isMemberExpression","propertyName","getMemberPropertyName","objExpr","resolveToObjectExpression","object","prop","findObjectProperty","paramIndex","findIndex","left","argument","binding","getBinding","isSame","resolveImportBinding","importDeclaration","ImportDeclaration","n","isImportDeclaration","specifier","specifiers","local","identifierName","importName","importFileName","source","importPath","startsWith","resolve","dirname","resolvedFile","readFileSync","tree","Program","p","namedExport","newImportName","ExportDeclaration","exported","resolveExportSpecifier","result","e","cause","computed","property","isStringLiteral","locInfo","properties","isObjectProperty","key","is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ACXC,IAAI,EACJC,QAAQ,EACRE,IAAI,EACJE,QAAQ,EAOT;IACC,MAAM,EAAC8D,OAAO,EAAEa,cAAc,EAAED,UAAU,EAAEO,YAAY,EAAEhF,KAAK,EAAEkF,IAAI,EAAC,GAAGlB,qBAAqB;QAC5FvE;QACAC;QACAC;QACAE;QACAE;IACF;IAEA,IAAI,CAAC8D,SAAS;QACZ,MAAM,IAAItC,MAAM,CAAC,mCAAmC,EAAEkD,WAAW,KAAK,EAAEC,gBAAgB;IAC1F;IAEA,OAAOrB,0BAA0B;QAC/B5D;QACAC,MAAMwF;QACNvF,UAAUqF;QACVnF,MAAMgE,QAAQhF,IAAI,CAACgB,IAAI;QACvBE;QACAC;IACF;AACF"}
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs/promises';
2
- import createDebug from 'debug';
3
2
  import glob from 'globby';
3
+ import { createDebug } from 'obug';
4
4
  import { getBabelConfig } from '../getBabelConfig.js';
5
5
  import { findQueriesInSource } from './findQueriesInSource.js';
6
6
  import { normalizeGlobPattern } from './helpers.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/findQueriesInPath.ts"],"sourcesContent":["import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport createDebug from 'debug'\nimport glob from 'globby'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {findQueriesInSource} from './findQueriesInSource.js'\nimport {normalizeGlobPattern} from './helpers.js'\nimport {getResolver} from './moduleResolver.js'\nimport {type ExtractedModule, QueryExtractionError} from './types.js'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ninterface FindQueriesInPathOptions {\n path: string | string[]\n\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport function findQueriesInPath({\n babelOptions = getBabelConfig(),\n path,\n resolver = getResolver(),\n}: FindQueriesInPathOptions): {files: string[]; queries: AsyncIterable<ExtractedModule>} {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n // Normalize glob patterns to use forward slashes on all platforms\n const normalizedPath = normalizeGlobPattern(path)\n\n const files = glob\n .sync(normalizedPath, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n .toSorted()\n\n async function* getQueries(): AsyncGenerator<ExtractedModule> {\n for (const filename of files) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const pluckedModuleResult = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const {variable} of pluckedModuleResult.queries) {\n if (queryNames.has(variable.id.name)) {\n throw new Error(\n `Duplicate query name found: \"${variable.id.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(variable.id.name)\n }\n\n yield pluckedModuleResult\n } catch (cause) {\n debug(`Error in file \"${filename}\"`, cause)\n\n yield {\n errors: [new QueryExtractionError({cause, filename})],\n filename,\n queries: [],\n }\n }\n }\n }\n\n return {files, queries: getQueries()}\n}\n"],"names":["fs","createDebug","glob","getBabelConfig","findQueriesInSource","normalizeGlobPattern","getResolver","QueryExtractionError","debug","findQueriesInPath","babelOptions","path","resolver","queryNames","Set","normalizedPath","files","sync","absolute","ignore","onlyFiles","toSorted","getQueries","filename","source","readFile","pluckedModuleResult","variable","queries","has","id","name","Error","add","cause","errors"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AAGjC,OAAOC,iBAAiB,QAAO;AAC/B,OAAOC,UAAU,SAAQ;AAEzB,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAAQC,oBAAoB,QAAO,eAAc;AACjD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AE;gBACb;YACF;QACF;IACF;IAEA,OAAO;QAACZ;QAAOY,SAASN;IAAY;AACtC"}
1
+ {"version":3,"sources":["../../src/typescript/findQueriesInPath.ts"],"sourcesContent":["import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport glob from 'globby'\nimport {createDebug} from 'obug'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {findQueriesInSource} from './findQueriesInSource.js'\nimport {normalizeGlobPattern} from './helpers.js'\nimport {getResolver} from './moduleResolver.js'\nimport {type ExtractedModule, QueryExtractionError} from './types.js'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ninterface FindQueriesInPathOptions {\n path: string | string[]\n\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport function findQueriesInPath({\n babelOptions = getBabelConfig(),\n path,\n resolver = getResolver(),\n}: FindQueriesInPathOptions): {files: string[]; queries: AsyncIterable<ExtractedModule>} {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n // Normalize glob patterns to use forward slashes on all platforms\n const normalizedPath = normalizeGlobPattern(path)\n\n const files = glob\n .sync(normalizedPath, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n .toSorted()\n\n async function* getQueries(): AsyncGenerator<ExtractedModule> {\n for (const filename of files) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const pluckedModuleResult = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const {variable} of pluckedModuleResult.queries) {\n if (queryNames.has(variable.id.name)) {\n throw new Error(\n `Duplicate query name found: \"${variable.id.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(variable.id.name)\n }\n\n yield pluckedModuleResult\n } catch (cause) {\n debug(`Error in file \"${filename}\"`, cause)\n\n yield {\n errors: [new QueryExtractionError({cause, filename})],\n filename,\n queries: [],\n }\n }\n }\n }\n\n return {files, queries: getQueries()}\n}\n"],"names":["fs","glob","createDebug","getBabelConfig","findQueriesInSource","normalizeGlobPattern","getResolver","QueryExtractionError","debug","findQueriesInPath","babelOptions","path","resolver","queryNames","Set","normalizedPath","files","sync","absolute","ignore","onlyFiles","toSorted","getQueries","filename","source","readFile","pluckedModuleResult","variable","queries","has","id","name","Error","add","cause","errors"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AAGjC,OAAOC,UAAU,SAAQ;AACzB,SAAQC,WAAW,QAAO,OAAM;AAEhC,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAAQC,oBAAoB,QAAO,eAAc;AACjD,SAAQC,WAAW,QAAO,sBAAqB;AAC/C,SAA8BC,oBAAoB,QAAO,aAAY;AAErE,MAAMC,QAAQN,YAAY;AAS1B;;;;;;;;CAQC,GACD,OAAO,SAASO,kBAAkB,EAChCC,eAAeP,gBAAgB,EAC/BQ,IAAI,EACJC,WAAWN,aAAa,EACC;IACzB,MAAMO,aAAa,IAAIC;IACvB,kDAAkD;IAClDN,MAAM,CAAC,QAAQ,EAAEG,MAAM;IAEvB,kEAAkE;IAClE,MAAMI,iBAAiBV,qBAAqBM;IAE5C,MAAMK,QAAQf,KACXgB,IAAI,CAACF,gBAAgB;QACpBG,UAAU;QACVC,QAAQ;YAAC;SAAqB;QAC9BC,WAAW;IACb,GACCC,QAAQ;IAEX,gBAAgBC;QACd,KAAK,MAAMC,YAAYP,MAAO;YAC5B,IAAI,OAAOO,aAAa,UAAU;gBAChC;YACF;YAEAf,MAAM,CAAC,YAAY,EAAEe,SAAS,CAAC,CAAC;YAChC,IAAI;gBACF,MAAMC,SAAS,MAAMxB,GAAGyB,QAAQ,CAACF,UAAU;gBAC3C,MAAMG,sBAAsBtB,oBAAoBoB,QAAQD,UAAUb,cAAcE;gBAChF,gGAAgG;gBAChG,KAAK,MAAM,EAACe,QAAQ,EAAC,IAAID,oBAAoBE,OAAO,CAAE;oBACpD,IAAIf,WAAWgB,GAAG,CAACF,SAASG,EAAE,CAACC,IAAI,GAAG;wBACpC,MAAM,IAAIC,MACR,CAAC,6BAA6B,EAAEL,SAASG,EAAE,CAACC,IAAI,CAAC,+CAA+C,CAAC;oBAErG;oBACAlB,WAAWoB,GAAG,CAACN,SAASG,EAAE,CAACC,IAAI;gBACjC;gBAEA,MAAML;YACR,EAAE,OAAOQ,OAAO;gBACd1B,MAAM,CAAC,eAAe,EAAEe,SAAS,CAAC,CAAC,EAAEW;gBAErC,MAAM;oBACJC,QAAQ;wBAAC,IAAI5B,qBAAqB;4BAAC2B;4BAAOX;wBAAQ;qBAAG;oBACrDA;oBACAK,SAAS,EAAE;gBACb;YACF;QACF;IACF;IAEA,OAAO;QAACZ;QAAOY,SAASN;IAAY;AACtC"}
@@ -11,6 +11,11 @@ const defineQueryFunctionName = 'defineQuery';
11
11
  const groqModuleName = 'groq';
12
12
  const nextSanityModuleName = 'next-sanity';
13
13
  const sveltekitModuleName = '@sanity/sveltekit';
14
+ const defineProjectionFunctionName = 'defineProjection';
15
+ const projectionModuleNames = [
16
+ '@sanity/sdk',
17
+ '@sanity/sdk-react'
18
+ ];
14
19
  const ignoreValue = '@sanity-typegen-ignore';
15
20
  /**
16
21
  * findQueriesInSource takes a source string and returns all GROQ queries in it.
@@ -23,6 +28,7 @@ const ignoreValue = '@sanity-typegen-ignore';
23
28
  * @internal
24
29
  */ export function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require.resolve) {
25
30
  const queries = [];
31
+ const projections = [];
26
32
  const errors = [];
27
33
  const file = parseSourceFile(source, filename, babelConfig);
28
34
  traverse(file, {
@@ -73,11 +79,53 @@ const ignoreValue = '@sanity-typegen-ignore';
73
79
  }));
74
80
  }
75
81
  }
82
+ // Look for `defineProjection(projection)` or `defineProjection(documentType, projection)`
83
+ // imported from the App SDK
84
+ if (babelTypes.isIdentifier(node.id) && babelTypes.isCallExpression(init) && projectionModuleNames.some((moduleName)=>isImportFrom(moduleName, defineProjectionFunctionName, scope, init.callee)) && !declarationLeadingCommentContains(path, ignoreValue)) {
85
+ const { end, id, start } = node;
86
+ const variable = {
87
+ id,
88
+ ...start && {
89
+ start
90
+ },
91
+ ...end && {
92
+ end
93
+ }
94
+ };
95
+ const resolve = (argument)=>resolveExpression({
96
+ babelConfig,
97
+ file,
98
+ filename,
99
+ node: argument,
100
+ resolver,
101
+ scope
102
+ });
103
+ try {
104
+ const [first, second] = init.arguments;
105
+ const projectionNode = second ?? first;
106
+ if (!projectionNode) throw new Error('defineProjection needs a projection');
107
+ projections.push({
108
+ filename,
109
+ projection: resolve(projectionNode),
110
+ variable,
111
+ ...second && first ? {
112
+ documentType: resolve(first)
113
+ } : {}
114
+ });
115
+ } catch (cause) {
116
+ errors.push(new QueryExtractionError({
117
+ cause,
118
+ filename,
119
+ variable
120
+ }));
121
+ }
122
+ }
76
123
  }
77
124
  });
78
125
  return {
79
126
  errors,
80
127
  filename,
128
+ projections,
81
129
  queries
82
130
  };
83
131
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/findQueriesInSource.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {type NodePath, type TransformOptions, traverse} from '@babel/core'\nimport {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {resolveExpression} from './expressionResolvers.js'\nimport {parseSourceFile} from './parseSource.js'\nimport {type ExtractedModule, type ExtractedQuery, QueryExtractionError} from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\nconst sveltekitModuleName = '@sanity/sveltekit'\n\nconst ignoreValue = '@sanity-typegen-ignore'\n\n/**\n * findQueriesInSource takes a source string and returns all GROQ queries in it.\n * @param source - The source code to search for queries\n * @param filename - The filename of the source code\n * @param babelConfig - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns\n * @beta\n * @internal\n */\nexport function findQueriesInSource(\n source: string,\n filename: string,\n babelConfig: TransformOptions = getBabelConfig(),\n resolver: NodeJS.RequireResolve = require.resolve,\n): ExtractedModule {\n const queries: ExtractedQuery[] = []\n const errors: QueryExtractionError[] = []\n const file = parseSourceFile(source, filename, babelConfig)\n\n traverse(file, {\n // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.\n // The variable name is used as the name of the query result type\n VariableDeclarator(path) {\n const {node, scope} = path\n\n const init = node.init\n\n // Look for tagged template expressions that are called with the `groq` tag\n const isGroqTemplateTag =\n babelTypes.isTaggedTemplateExpression(init) &&\n babelTypes.isIdentifier(init.tag) &&\n init.tag.name === groqTagName\n\n // Look for strings wrapped in a defineQuery function call\n const isDefineQueryCall =\n babelTypes.isCallExpression(init) &&\n (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(sveltekitModuleName, defineQueryFunctionName, scope, init.callee))\n\n if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {\n // If we find a comment leading the decleration which macthes with ignoreValue we don't add\n // the query\n if (declarationLeadingCommentContains(path, ignoreValue)) {\n return\n }\n\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n babelConfig,\n file,\n filename,\n node: init,\n resolver,\n scope,\n })\n queries.push({filename, query, variable})\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n },\n })\n\n return {errors, filename, queries}\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n"],"names":["createRequire","traverse","babelTypes","getBabelConfig","resolveExpression","parseSourceFile","QueryExtractionError","require","url","groqTagName","defineQueryFunctionName","groqModuleName","nextSanityModuleName","sveltekitModuleName","ignoreValue","findQueriesInSource","source","filename","babelConfig","resolver","resolve","queries","errors","file","VariableDeclarator","path","node","scope","init","isGroqTemplateTag","isTaggedTemplateExpression","isIdentifier","tag","name","isDefineQueryCall","isCallExpression","isImportFrom","callee","id","declarationLeadingCommentContains","end","start","variable","query","push","cause","comment","variableDeclaration","find","isVariableDeclaration","leadingComments","commentItem","value","trim","parent","moduleName","importName","binding","getBinding","isImportSpecifier","importKind","parentPath","isImportDeclaration","imported","isVariableDeclarator","isStringLiteral","arguments","isMemberExpression","object","property","isImportNamespaceSpecifier"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,SAA8CC,QAAQ,QAAO,cAAa;AAE1E,YAAYC,gBAAgB,eAAc;AAE1C,S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,KAAKuB,cAClBtD,WAAWoE,0BAA0B,CAAC7C,KAAKC,IAAI,KAC/CD,KAAKoC,UAAU,IACf3D,WAAW4D,mBAAmB,CAACrC,KAAKoC,UAAU,CAACnC,IAAI,KACnDD,KAAKoC,UAAU,CAACnC,IAAI,CAACV,MAAM,CAACoC,KAAK,KAAKG;IAE1C;IAEA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../src/typescript/findQueriesInSource.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {type NodePath, type TransformOptions, traverse} from '@babel/core'\nimport {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {resolveExpression} from './expressionResolvers.js'\nimport {parseSourceFile} from './parseSource.js'\nimport {\n type ExtractedModule,\n type ExtractedProjection,\n type ExtractedQuery,\n QueryExtractionError,\n} from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\nconst sveltekitModuleName = '@sanity/sveltekit'\nconst defineProjectionFunctionName = 'defineProjection'\nconst projectionModuleNames = ['@sanity/sdk', '@sanity/sdk-react']\n\nconst ignoreValue = '@sanity-typegen-ignore'\n\n/**\n * findQueriesInSource takes a source string and returns all GROQ queries in it.\n * @param source - The source code to search for queries\n * @param filename - The filename of the source code\n * @param babelConfig - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns\n * @beta\n * @internal\n */\nexport function findQueriesInSource(\n source: string,\n filename: string,\n babelConfig: TransformOptions = getBabelConfig(),\n resolver: NodeJS.RequireResolve = require.resolve,\n): ExtractedModule {\n const queries: ExtractedQuery[] = []\n const projections: ExtractedProjection[] = []\n const errors: QueryExtractionError[] = []\n const file = parseSourceFile(source, filename, babelConfig)\n\n traverse(file, {\n // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.\n // The variable name is used as the name of the query result type\n VariableDeclarator(path) {\n const {node, scope} = path\n\n const init = node.init\n\n // Look for tagged template expressions that are called with the `groq` tag\n const isGroqTemplateTag =\n babelTypes.isTaggedTemplateExpression(init) &&\n babelTypes.isIdentifier(init.tag) &&\n init.tag.name === groqTagName\n\n // Look for strings wrapped in a defineQuery function call\n const isDefineQueryCall =\n babelTypes.isCallExpression(init) &&\n (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(sveltekitModuleName, defineQueryFunctionName, scope, init.callee))\n\n if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {\n // If we find a comment leading the decleration which macthes with ignoreValue we don't add\n // the query\n if (declarationLeadingCommentContains(path, ignoreValue)) {\n return\n }\n\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n babelConfig,\n file,\n filename,\n node: init,\n resolver,\n scope,\n })\n queries.push({filename, query, variable})\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n\n // Look for `defineProjection(projection)` or `defineProjection(documentType, projection)`\n // imported from the App SDK\n if (\n babelTypes.isIdentifier(node.id) &&\n babelTypes.isCallExpression(init) &&\n projectionModuleNames.some((moduleName) =>\n isImportFrom(moduleName, defineProjectionFunctionName, scope, init.callee),\n ) &&\n !declarationLeadingCommentContains(path, ignoreValue)\n ) {\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n const resolve = (argument: babelTypes.Node) =>\n resolveExpression({babelConfig, file, filename, node: argument, resolver, scope})\n\n try {\n const [first, second] = init.arguments\n const projectionNode = second ?? first\n if (!projectionNode) throw new Error('defineProjection needs a projection')\n\n projections.push({\n filename,\n projection: resolve(projectionNode),\n variable,\n ...(second && first ? {documentType: resolve(first)} : {}),\n })\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n },\n })\n\n return {errors, filename, projections, queries}\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n"],"names":["createRequire","traverse","babelTypes","getBabelConfig","resolveExpression","parseSourceFile","QueryExtractionError","require","url","groqTagName","defineQueryFunctionName","groqModuleName","nextSanityModuleName","sveltekitModuleName","defineProjectionFunctionName","projectionModuleNames","ignoreValue","findQueriesInSource","source","filename","babelConfig","resolver","resolve","queries","projections","errors","file","VariableDeclarator","path","node","scope","init","isGroqTemplateTag","isTaggedTemplateExpression","isIdentifier","tag","name","isDefineQueryCall","isCallExpression","isImportFrom","callee","id","declarationLeadingCommentContains","end","start","variable","query","push","cause","some","moduleName","argument","first","second","arguments","projectionNode","Error","projection","documentType","comment","variableDeclaration","find","isVariableDeclaration","leadingComments","commentItem","value","trim","parent","importName","binding","getBinding","isImportSpecifier","importKind","parentPath","isImportDeclaration","imported","isVariableDeclarator","isStringLiteral","isMemberExpression","object","property","isImportNamespaceSpecifier"],"mappings":"AAAA,SAAQA,aA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/CD,KAAK6C,UAAU,IACfvE,WAAWwE,mBAAmB,CAAC9C,KAAK6C,UAAU,CAAC5C,IAAI,KACnDD,KAAK6C,UAAU,CAAC5C,IAAI,CAACX,MAAM,CAAC+C,KAAK,KAAKf;IAE1C;IAEA,OAAO;AACT"}
@@ -70,9 +70,7 @@ export function weakMapMemo(fn) {
70
70
  export function generateCode(node) {
71
71
  return `${new CodeGenerator(node).generate().code.trim()}\n\n`;
72
72
  }
73
- /**
74
- * Builds a `declare global { … }` block.
75
- */ export function tsDeclareGlobal(body) {
73
+ export function tsDeclareGlobal(body) {
76
74
  const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body));
77
75
  declaration.declare = true;
78
76
  // Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the
@@ -81,9 +79,7 @@ export function generateCode(node) {
81
79
  declaration.kind = 'global';
82
80
  return declaration;
83
81
  }
84
- /**
85
- * Builds a `declare module "<name>" { … }` block.
86
- */ export function tsDeclareModule(name, body) {
82
+ export function tsDeclareModule(name, body) {
87
83
  const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body));
88
84
  declaration.declare = true;
89
85
  declaration.kind = 'module';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/helpers.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type ArrayTypeNode, type UnionTypeNode} from 'groq-js'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {RESERVED_IDENTIFIERS} from './constants.js'\n\nexport function normalizePrintablePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n // Always use Unix-style paths for consistent output across platforms\n return formatPath(path.relative(root, resolved))\n}\n\n/**\n * Normalizes a glob pattern to use forward slashes (POSIX-style paths).\n * Glob patterns must use forward slashes, even on Windows.\n *\n * @param pattern - A glob pattern string or array of patterns\n * @returns The normalized pattern(s) with forward slashes\n * @see https://github.com/sindresorhus/globby#api\n */\nexport function normalizeGlobPattern(pattern: string | string[]): string | string[] {\n if (Array.isArray(pattern)) {\n return pattern.map((p) => formatPath(p))\n }\n return formatPath(pattern)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replaceAll(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\n/**\n * Checks if a string is a valid ECMAScript IdentifierName.\n * IdentifierNames start with a letter, underscore, or $, and contain only\n * alphanumeric characters, underscores, or $.\n */\nexport function isIdentifierName(input: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(input)\n}\n\nfunction normalizeIdentifier(input: string): string {\n const sanitized = sanitizeIdentifier(input)\n return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`\n}\n\nexport function getUniqueIdentifierForName(name: string, currentIdentifiers: Set<string>) {\n const desiredName = normalizeIdentifier(name)\n let resultingName = desiredName\n let index = 2\n while (currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName)) {\n resultingName = `${desiredName}_${index}`\n index++\n }\n return t.identifier(resultingName)\n}\n\nexport function computeOnce<TReturn>(fn: () => TReturn): () => TReturn {\n const ref = {computed: false, current: undefined as TReturn | undefined}\n\n return function () {\n if (ref.computed) return ref.current as TReturn\n ref.current = fn()\n ref.computed = true\n return ref.current\n }\n}\n\nexport function weakMapMemo<TParam extends object, TReturn>(fn: (arg: TParam) => TReturn) {\n const cache = new WeakMap<object, TReturn>()\n\n const wrapped = function (arg: TParam) {\n if (cache.has(arg)) return cache.get(arg)!\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }\n\n return wrapped\n}\n\nexport function generateCode(node: t.Node) {\n return `${new CodeGenerator(node).generate().code.trim()}\\n\\n`\n}\n\n/**\n * Builds a `declare global { … }` block.\n */\nexport function tsDeclareGlobal(body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body))\n declaration.declare = true\n // Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the\n // output is `declare global {` on either.\n declaration.global = true\n declaration.kind = 'global'\n return declaration\n}\n\n/**\n * Builds a `declare module \"<name>\" { … }` block.\n */\nexport function tsDeclareModule(name: string, body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body))\n declaration.declare = true\n declaration.kind = 'module'\n return declaration\n}\n\nexport function getFilterArrayUnionType(\n typeNode: ArrayTypeNode,\n predicate: (unionTypeNode: UnionTypeNode['of'][number]) => boolean,\n): ArrayTypeNode {\n if (typeNode.of.type !== 'union') {\n return typeNode\n }\n\n return {\n ...typeNode,\n of: {\n ...typeNode.of,\n of: typeNode.of.of.filter((unionTypeNode) => predicate(unionTypeNode)),\n },\n } satisfies ArrayTypeNode<UnionTypeNode>\n}\n"],"names":["path","CodeGenerator","t","formatPath","RESERVED_IDENTIFIERS","normalizePrintablePath","root","filename","resolved","resolve","relative","normalizeGlobPattern","pattern","Array","isArray","map","p","sanitizeIdentifier","input","replace","replaceAll","_","char","toUpperCase","isIdentifierName","test","normalizeIdentifier","sanitized","charAt","slice","getUniqueIdentifierForName","name","currentIdentifiers","desiredName","resultingName","index","has","identifier","computeOnce","fn","ref","computed","current","undefined","weakMapMemo","cache","WeakMap","wrapped","arg","get","result","set","generateCode","node","generate","code","trim","tsDeclareGlobal","body","declaration","tsModuleDeclaration","tsModuleBlock","declare","global","kind","tsDeclareModule","stringLiteral","getFilterArrayUnionType","typeNode","predicate","of","type","filter","unionTypeNode"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,YAAYC,OAAO,eAAc;AAGjC,SAAQC,UAAU,QAAO,yBAAwB;AACjD,SAAQC,oBAAoB,QAAO,iBAAgB;AAEnD,OAAO,SAASC,uBAAuBC,IAAY,EAAEC,QAAgB;IACnE,MAAMC,WAAWR,KAAKS,OAAO,CAACH,MAAMC;IAC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B,MAAMC,UAAU,SAAUC,GAAW;QACnC,IAAIH,MAAMT,GAAG,CAACY,MAAM,OAAOH,MAAMI,GAAG,CAACD;QACrC,MAAME,SAASX,GAAGS;QAClBH,MAAMM,GAAG,CAACH,KAAKE;QACf,OAAOA;IACT;IAEA,OAAOH;AACT;AAEA,OAAO,SAASK,aAAaC,IAAY;IACvC,OAAO,GAAG,IAAIpD,cAAcoD,MAAMC,QAAQ,GAAGC,IAAI,CAACC,IAAI,GAAG,IAAI,CAAC;AAChE;AAEA;;CAEC,GACD,OAAO,SAASC,gBAAgBC,IAAmB;IACjD,MAAMC,cAAczD,EAAE0D,mBAAmB,CAAC1D,EAAEmC,UAAU,CAAC,WAAWnC,EAAE2D,aAAa,CAACH;IAClFC,YAAYG,OAAO,GAAG;IACtB,8FAA8F;IAC9F,0CAA0C;IAC1CH,YAAYI,MAAM,GAAG;IACrBJ,YAAYK,IAAI,GAAG;IACnB,OAAOL;AACT;AAEA;;CAEC,GACD,OAAO,SAASM,gBAAgBlC,IAAY,EAAE2B,IAAmB;IAC/D,MAAMC,cAAczD,EAAE0D,mBAAmB,CAAC1D,EAAEgE,aAAa,CAACnC,OAAO7B,EAAE2D,aAAa,CAACH;IACjFC,YAAYG,OAAO,GAAG;IACtBH,YAAYK,IAAI,GAAG;IACnB,OAAOL;AACT;AAEA,OAAO,SAASQ,wBACdC,QAAuB,EACvBC,SAAkE;IAElE,IAAID,SAASE,EAAE,CAACC,IAAI,KAAK,SAAS;QAChC,OAAOH;IACT;IAEA,OAAO;QACL,GAAGA,QAAQ;QACXE,IAAI;YACF,GAAGF,SAASE,EAAE;YACdA,IAAIF,SAASE,EAAE,CAACA,EAAE,CAACE,MAAM,CAAC,CAACC,gBAAkBJ,UAAUI;QACzD;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/helpers.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type ArrayTypeNode, type UnionTypeNode} from 'groq-js'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {RESERVED_IDENTIFIERS} from './constants.js'\n\nexport function normalizePrintablePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n // Always use Unix-style paths for consistent output across platforms\n return formatPath(path.relative(root, resolved))\n}\n\n/**\n * Normalizes a glob pattern to use forward slashes (POSIX-style paths).\n * Glob patterns must use forward slashes, even on Windows.\n *\n * @param pattern - A glob pattern string or array of patterns\n * @returns The normalized pattern(s) with forward slashes\n * @see https://github.com/sindresorhus/globby#api\n */\nexport function normalizeGlobPattern(pattern: string | string[]): string | string[] {\n if (Array.isArray(pattern)) {\n return pattern.map((p) => formatPath(p))\n }\n return formatPath(pattern)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replaceAll(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\n/**\n * Checks if a string is a valid ECMAScript IdentifierName.\n * IdentifierNames start with a letter, underscore, or $, and contain only\n * alphanumeric characters, underscores, or $.\n */\nexport function isIdentifierName(input: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(input)\n}\n\nfunction normalizeIdentifier(input: string): string {\n const sanitized = sanitizeIdentifier(input)\n return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`\n}\n\nexport function getUniqueIdentifierForName(name: string, currentIdentifiers: Set<string>) {\n const desiredName = normalizeIdentifier(name)\n let resultingName = desiredName\n let index = 2\n while (currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName)) {\n resultingName = `${desiredName}_${index}`\n index++\n }\n return t.identifier(resultingName)\n}\n\nexport function computeOnce<TReturn>(fn: () => TReturn): () => TReturn {\n const ref = {computed: false, current: undefined as TReturn | undefined}\n\n return function () {\n if (ref.computed) return ref.current as TReturn\n ref.current = fn()\n ref.computed = true\n return ref.current\n }\n}\n\nexport function weakMapMemo<TParam extends object, TReturn>(fn: (arg: TParam) => TReturn) {\n const cache = new WeakMap<object, TReturn>()\n\n const wrapped = function (arg: TParam) {\n if (cache.has(arg)) return cache.get(arg)!\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }\n\n return wrapped\n}\n\nexport function generateCode(node: t.Node) {\n return `${new CodeGenerator(node).generate().code.trim()}\\n\\n`\n}\n\nexport function tsDeclareGlobal(body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body))\n declaration.declare = true\n // Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the\n // output is `declare global {` on either.\n declaration.global = true\n declaration.kind = 'global'\n return declaration\n}\n\nexport function tsDeclareModule(name: string, body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body))\n declaration.declare = true\n declaration.kind = 'module'\n return declaration\n}\n\nexport function getFilterArrayUnionType(\n typeNode: ArrayTypeNode,\n predicate: (unionTypeNode: UnionTypeNode['of'][number]) => boolean,\n): ArrayTypeNode {\n if (typeNode.of.type !== 'union') {\n return typeNode\n }\n\n return {\n ...typeNode,\n of: {\n ...typeNode.of,\n of: typeNode.of.of.filter((unionTypeNode) => predicate(unionTypeNode)),\n },\n } satisfies ArrayTypeNode<UnionTypeNode>\n}\n"],"names":["path","CodeGenerator","t","formatPath","RESERVED_IDENTIFIERS","normalizePrintablePath","root","filename","resolved","resolve","relative","normalizeGlobPattern","pattern","Array","isArray","map","p","sanitizeIdentifier","input","replace","replaceAll","_","char","toUpperCase","isIdentifierName","test","normalizeIdentifier","sanitized","charAt","slice","getUniqueIdentifierForName","name","currentIdentifiers","desiredName","resultingName","index","has","identifier","computeOnce","fn","ref","computed","current","undefined","weakMapMemo","cache","WeakMap","wrapped","arg","get","result","set","generateCode","node","generate","code","trim","tsDeclareGlobal","body","declaration","tsModuleDeclaration","tsModuleBlock","declare","global","kind","tsDeclareModule","stringLiteral","getFilterArrayUnionType","typeNode","predicate","of","type","filter","union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AAGF,SAASE,EAAE;YACdA,IAAIF,SAASE,EAAE,CAACA,EAAE,CAACE,MAAM,CAAC,CAACC,gBAAkBJ,UAAUI;QACzD;IACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'node:module';
2
- import createDebug from 'debug';
2
+ import { createDebug } from 'obug';
3
3
  import { createMatchPath, loadConfig as loadTSConfig } from 'tsconfig-paths';
4
4
  const require = createRequire(import.meta.url);
5
5
  const debug = createDebug('sanity:codegen:moduleResolver');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/moduleResolver.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst require = createRequire(import.meta.url)\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n"],"names":["createRequire","createDebug","createMatchPath","loadConfig","loadTSConfig","require","url","debug","getResolver","cwd","tsConfig","resultType","message","resolve","matchPath","absoluteBaseUrl","paths","mainFields","addMatchAll","request","options","found","undefined"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,OAAOC,iBAAiB,QAAO;AAC/B,SAAQC,eAAe,EAAEC,cAAcC,YAAY,QAAO,iBAAgB;AAE1E,MAAMC,UAAUL,cAAc,YAAYM,GAAG;AAC7C,MAAMC,QAAQN,YAAY;AAE1B;;;;;;CAMC,GACD,OAAO,SAASO,YAAYC,GAAY;IACtC,MAAMC,WAAWN,aAAaK;IAE9B,IAAIC,SAASC,UAAU,KAAK,UAAU;QACpCJ,MAAM,uDAAuDG,SAASE,OAAO;QAC7E,OAAOP,QAAQQ,OAAO;IACxB;IAEA,MAAMC,YAAYZ,gBAChBQ,SAASK,eAAe,EACxBL,SAASM,KAAK,EACdN,SAASO,UAAU,EACnBP,SAASQ,WAAW;IAGtB,MAAML,UAAU,SAAUM,OAAe,EAAEC,OAA4B;QACrE,MAAMC,QAAQP,UAAUK;QACxB,IAAIE,UAAUC,WAAW;YACvB,OAAOjB,QAAQQ,OAAO,CAACQ,OAAOD;QAChC;QACA,OAAOf,QAAQQ,OAAO,CAACM,SAASC;IAClC;IAEA,uDAAuD;IACvDP,QAAQG,KAAK,GAAG,CAACG;QACf,OAAOd,QAAQQ,OAAO,CAACG,KAAK,CAACG;IAC/B;IACA,OAAON;AACT"}
1
+ {"version":3,"sources":["../../src/typescript/moduleResolver.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {createDebug} from 'obug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst require = createRequire(import.meta.url)\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n"],"names":["createRequire","createDebug","createMatchPath","loadConfig","loadTSConfig","require","url","debug","getResolver","cwd","tsConfig","resultType","message","resolve","matchPath","absoluteBaseUrl","paths","mainFields","addMatchAll","request","options","found","undefined"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,SAAQC,WAAW,QAAO,OAAM;AAChC,SAAQC,eAAe,EAAEC,cAAcC,YAAY,QAAO,iBAAgB;AAE1E,MAAMC,UAAUL,cAAc,YAAYM,GAAG;AAC7C,MAAMC,QAAQN,YAAY;AAE1B;;;;;;CAMC,GACD,OAAO,SAASO,YAAYC,GAAY;IACtC,MAAMC,WAAWN,aAAaK;IAE9B,IAAIC,SAASC,UAAU,KAAK,UAAU;QACpCJ,MAAM,uDAAuDG,SAASE,OAAO;QAC7E,OAAOP,QAAQQ,OAAO;IACxB;IAEA,MAAMC,YAAYZ,gBAChBQ,SAASK,eAAe,EACxBL,SAASM,KAAK,EACdN,SAASO,UAAU,EACnBP,SAASQ,WAAW;IAGtB,MAAML,UAAU,SAAUM,OAAe,EAAEC,OAA4B;QACrE,MAAMC,QAAQP,UAAUK;QACxB,IAAIE,UAAUC,WAAW;YACvB,OAAOjB,QAAQQ,OAAO,CAACQ,OAAOD;QAChC;QACA,OAAOf,QAAQQ,OAAO,CAACM,SAASC;IAClC;IAEA,uDAAuD;IACvDP,QAAQG,KAAK,GAAG,CAACG;QACf,OAAOd,QAAQQ,OAAO,CAACG,KAAK,CAACG;IAC/B;IACA,OAAON;AACT"}
@@ -39,6 +39,20 @@ export class SchemaTypeGenerator {
39
39
  this.tsTypes.set(type.name, this.generateTsType(type));
40
40
  }
41
41
  }
42
+ /** The names of the schema's document types, in schema order. */ documentTypeNames() {
43
+ return this.schema.filter((schemaType)=>schemaType.type === 'document').map(({ name })=>name);
44
+ }
45
+ /**
46
+ * Evaluates a projection for one document type, as `*[_type == TYPE][0]PROJECTION` without
47
+ * the `null` for a missing document: the SDK projects documents it has found.
48
+ */ evaluateProjection({ documentType, projection }) {
49
+ const ast = safeParseQuery(`*[_type == ${JSON.stringify(documentType)}][0]${projection}`);
50
+ const typeNode = withoutNull(typeEvaluate(ast, this.schema));
51
+ return {
52
+ stats: walkAndCountQueryTypeNodeStats(typeNode),
53
+ tsType: this.generateTsType(typeNode)
54
+ };
55
+ }
42
56
  getType(typeName) {
43
57
  const tsType = this.tsTypes.get(typeName);
44
58
  const id = this.identifiers.get(typeName);
@@ -324,5 +338,13 @@ export function walkAndCountQueryTypeNodeStats(typeNode) {
324
338
  }
325
339
  }
326
340
  }
341
+ function withoutNull(typeNode) {
342
+ if (typeNode.type !== 'union') return typeNode;
343
+ const of = typeNode.of.filter((member)=>member.type !== 'null');
344
+ return of.length === 1 ? of[0] : {
345
+ ...typeNode,
346
+ of
347
+ };
348
+ }
327
349
 
328
350
  //# sourceMappingURL=schemaTypeGenerator.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/schemaTypeGenerator.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type InlineTypeNode,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n typeEvaluate,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nimport {safeParseQuery} from '../safeParseQuery.js'\nimport {ARRAY_OF, INTERNAL_REFERENCE_SYMBOL} from './constants.js'\nimport {\n getFilterArrayUnionType,\n getUniqueIdentifierForName,\n isIdentifierName,\n weakMapMemo,\n} from './helpers.js'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types.js'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n evaluateQuery = weakMapMemo(\n // eslint-disable-next-line unicorn/consistent-function-scoping\n ({query}: Pick<ExtractedQuery, 'query'>): {stats: TypeEvaluationStats; tsType: t.TSType} => {\n const ast = safeParseQuery(query)\n const typeNode = typeEvaluate(ast, this.schema)\n const tsType = this.generateTsType(typeNode)\n const stats = walkAndCountQueryTypeNodeStats(typeNode)\n return {stats, tsType}\n },\n )\n private arrayOfUsed = false\n\n private identifiers = new Map<string, t.Identifier>()\n\n private tsTypes = new Map<string, t.TSType>()\n\n constructor(schema: SchemaType) {\n this.schema = schema\n\n const uniqueTypeNames = new Set<string>()\n for (const type of schema) {\n if (uniqueTypeNames.has(type.name)) {\n throw new Error(\n `Duplicate type name \"${type.name}\" in schema. Type names must be unique within the same schema.`,\n )\n }\n uniqueTypeNames.add(type.name)\n }\n\n for (const type of schema) {\n const currentIdentifierNames = new Set([...this.identifiers.values()].map((id) => id.name))\n const uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames)\n this.identifiers.set(type.name, uniqueIdentifier)\n }\n\n for (const type of schema) {\n this.tsTypes.set(type.name, this.generateTsType(type))\n }\n }\n\n getType(typeName: string): {id: t.Identifier; tsType: t.TSType} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {id, tsType}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n isArrayOfUsed(): boolean {\n return this.arrayOfUsed\n }\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n\n typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n /**\n * Helper function used to generate TS types for arrays of inline types, or arrays of inline types\n * wrapped in the ArrayOf wrapper that adds _key prop\n */\n private generateArrayOfTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n this.arrayOfUsed = true\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(ARRAY_OF, t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference | t.TSUnionType {\n // if it's an array of a single inline type, wrap it in ArrayOf\n if (typeNode.of.type === 'inline') {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // if it's not an inline object and not a union, wrap in Array\n if (typeNode.of.type !== 'union') {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // if it's not a union type or all of the union type members are non-inlines, wrap type in Array\n if (typeNode.of.of.every((unionTypeNode) => unionTypeNode.type !== 'inline')) {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // all the union types nodes are inline\n if (typeNode.of.of.every((unionMember) => unionMember.type === 'inline')) {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // some of the union types are inlines, while some are not - split and recurse\n const arrayOfNonInline = getFilterArrayUnionType(typeNode, (member) => member.type !== 'inline')\n const arrayOfInline = getFilterArrayUnionType(typeNode, (member) => member.type === 'inline')\n\n return t.tsUnionType([\n this.generateArrayTsType(arrayOfNonInline),\n this.generateArrayTsType(arrayOfInline),\n ])\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentTsType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateTsObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n\n private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {\n const id = this.identifiers.get(typeNode.name)\n if (!id) {\n // Not found in schema, return unknown type\n return t.addComment(\n t.tsUnknownKeyword(),\n 'trailing',\n ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n true,\n )\n }\n\n return t.tsTypeReference(id)\n }\n\n // Helper function used to generate TS types for object type nodes.\n private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {\n const props: t.TSPropertySignature[] = []\n for (const [key, attribute] of Object.entries(typeNode.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'inline': {\n const resolved = this.generateInlineTsType(rest)\n // if object rest is unknown, we can't generate a type literal for it\n if (t.isTSUnknownKeyword(resolved)) return resolved\n return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])\n }\n case 'object': {\n for (const [key, attribute] of Object.entries(rest.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n break\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n default: {\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${rest.type}\" not found in schema`)\n }\n }\n }\n\n if (typeNode.dereferencesTo) {\n const derefType = Object.assign(\n t.tsPropertySignature(\n INTERNAL_REFERENCE_SYMBOL,\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n ),\n {computed: true, optional: true},\n )\n props.push(derefType)\n }\n\n return t.tsTypeLiteral(props)\n }\n\n // Helper function used to generate TS types for object properties.\n private generateTsObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.generateTsType(attribute.value)\n const keyNode = isIdentifierName(key) ? t.identifier(key) : t.stringLiteral(key)\n const propertySignature = t.tsPropertySignature(keyNode, t.tsTypeAnnotation(type))\n propertySignature.optional = attribute.optional\n\n return propertySignature\n }\n\n private generateTsType(\n typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode,\n ): t.TSType {\n switch (typeNode.type) {\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n case 'number': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.numericLiteral(typeNode.value))\n }\n return t.tsNumberKeyword()\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n\n default: {\n throw new Error(\n `Encountered unsupported node type \"${\n // @ts-expect-error This should never happen\n typeNode.type\n }\" while generating schema types`,\n )\n }\n }\n }\n\n // Helper function used to generate TS types for union type nodes.\n private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {\n if (typeNode.of.length === 0) return t.tsNeverKeyword()\n if (typeNode.of.length === 1) return this.generateTsType(typeNode.of[0]!)\n return t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)))\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'array': {\n const acc = walkAndCountQueryTypeNodeStats(typeNode.of)\n acc.allTypes += 1 // count the array type itself\n return acc\n }\n case 'object': {\n // if the rest is unknown, we count it as one unknown type\n if (typeNode.rest && typeNode.rest.type === 'unknown') {\n return {allTypes: 2, emptyUnions: 0, unknownTypes: 1} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, emptyUnions: 0, unknownTypes: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n const attrs = Object.values(typeNode.attributes)\n let acc = restStats\n for (const attribute of attrs) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, emptyUnions: 1, unknownTypes: 0}\n }\n\n let acc = {allTypes: 1, emptyUnions: 0, unknownTypes: 0} // count the union type itself\n for (const type of typeNode.of) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(type)\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'unknown': {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 1}\n }\n default: {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 0}\n }\n }\n}\n"],"names":["t","typeEvaluate","safeParseQuery","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","getFilterArrayUnionType","getUniqueIdentifierForName","isIdentifierName","weakMapMemo","SchemaTypeGenerator","schema","evaluateQuery","query","ast","typeNode","tsType","generateTsType","stats","walkAndCountQueryTypeNodeStats","arrayOfUsed","identifiers","Map","tsTypes","uniqueTypeNames","Set","type","has","name","Error","add","currentIdentifierNames","values","map","id","uniqueIdentifier","set","getType","typeName","get","undefined","hasType","isArrayOfUsed","Symbol","iterator","typeNames","schemaType","generateArrayOfTsType","typeNodes","of","tsTypeReference","tsTypeParameterInstantiation","generateArrayTsType","identifier","every","unionTypeNode","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","generateDocumentTsType","document","props","Object","entries","attributes","key","node","generateTsObjectProperty","tsTypeLiteral","generateInlineTsType","addComment","tsUnknownKeyword","generateObjectTsType","attribute","push","rest","resolved","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","tsLiteralType","stringLiteral","computed","optional","value","keyNode","propertySignature","booleanLiteral","tsBooleanKeyword","tsNullKeyword","numericLiteral","tsNumberKeyword","tsStringKeyword","generateUnionTsType","length","t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cAAc;gBAAC;YACtD;QACA;YAAS;gBACP,OAAO;oBAACF,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC;YACtD;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/schemaTypeGenerator.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type InlineTypeNode,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n typeEvaluate,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nimport {safeParseQuery} from '../safeParseQuery.js'\nimport {ARRAY_OF, INTERNAL_REFERENCE_SYMBOL} from './constants.js'\nimport {\n getFilterArrayUnionType,\n getUniqueIdentifierForName,\n isIdentifierName,\n weakMapMemo,\n} from './helpers.js'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types.js'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n evaluateQuery = weakMapMemo(\n // eslint-disable-next-line unicorn/consistent-function-scoping\n ({query}: Pick<ExtractedQuery, 'query'>): {stats: TypeEvaluationStats; tsType: t.TSType} => {\n const ast = safeParseQuery(query)\n const typeNode = typeEvaluate(ast, this.schema)\n const tsType = this.generateTsType(typeNode)\n const stats = walkAndCountQueryTypeNodeStats(typeNode)\n return {stats, tsType}\n },\n )\n private arrayOfUsed = false\n\n private identifiers = new Map<string, t.Identifier>()\n\n private tsTypes = new Map<string, t.TSType>()\n\n constructor(schema: SchemaType) {\n this.schema = schema\n\n const uniqueTypeNames = new Set<string>()\n for (const type of schema) {\n if (uniqueTypeNames.has(type.name)) {\n throw new Error(\n `Duplicate type name \"${type.name}\" in schema. Type names must be unique within the same schema.`,\n )\n }\n uniqueTypeNames.add(type.name)\n }\n\n for (const type of schema) {\n const currentIdentifierNames = new Set([...this.identifiers.values()].map((id) => id.name))\n const uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames)\n this.identifiers.set(type.name, uniqueIdentifier)\n }\n\n for (const type of schema) {\n this.tsTypes.set(type.name, this.generateTsType(type))\n }\n }\n\n /** The names of the schema's document types, in schema order. */\n documentTypeNames(): string[] {\n return this.schema.filter((schemaType) => schemaType.type === 'document').map(({name}) => name)\n }\n\n /**\n * Evaluates a projection for one document type, as `*[_type == TYPE][0]PROJECTION` without\n * the `null` for a missing document: the SDK projects documents it has found.\n */\n evaluateProjection({documentType, projection}: {documentType: string; projection: string}): {\n stats: TypeEvaluationStats\n tsType: t.TSType\n } {\n const ast = safeParseQuery(`*[_type == ${JSON.stringify(documentType)}][0]${projection}`)\n const typeNode = withoutNull(typeEvaluate(ast, this.schema))\n return {stats: walkAndCountQueryTypeNodeStats(typeNode), tsType: this.generateTsType(typeNode)}\n }\n\n getType(typeName: string): {id: t.Identifier; tsType: t.TSType} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {id, tsType}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n isArrayOfUsed(): boolean {\n return this.arrayOfUsed\n }\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n\n typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n /**\n * Helper function used to generate TS types for arrays of inline types, or arrays of inline types\n * wrapped in the ArrayOf wrapper that adds _key prop\n */\n private generateArrayOfTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n this.arrayOfUsed = true\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(ARRAY_OF, t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference | t.TSUnionType {\n // if it's an array of a single inline type, wrap it in ArrayOf\n if (typeNode.of.type === 'inline') {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // if it's not an inline object and not a union, wrap in Array\n if (typeNode.of.type !== 'union') {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // if it's not a union type or all of the union type members are non-inlines, wrap type in Array\n if (typeNode.of.of.every((unionTypeNode) => unionTypeNode.type !== 'inline')) {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // all the union types nodes are inline\n if (typeNode.of.of.every((unionMember) => unionMember.type === 'inline')) {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // some of the union types are inlines, while some are not - split and recurse\n const arrayOfNonInline = getFilterArrayUnionType(typeNode, (member) => member.type !== 'inline')\n const arrayOfInline = getFilterArrayUnionType(typeNode, (member) => member.type === 'inline')\n\n return t.tsUnionType([\n this.generateArrayTsType(arrayOfNonInline),\n this.generateArrayTsType(arrayOfInline),\n ])\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentTsType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateTsObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n\n private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {\n const id = this.identifiers.get(typeNode.name)\n if (!id) {\n // Not found in schema, return unknown type\n return t.addComment(\n t.tsUnknownKeyword(),\n 'trailing',\n ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n true,\n )\n }\n\n return t.tsTypeReference(id)\n }\n\n // Helper function used to generate TS types for object type nodes.\n private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {\n const props: t.TSPropertySignature[] = []\n for (const [key, attribute] of Object.entries(typeNode.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'inline': {\n const resolved = this.generateInlineTsType(rest)\n // if object rest is unknown, we can't generate a type literal for it\n if (t.isTSUnknownKeyword(resolved)) return resolved\n return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])\n }\n case 'object': {\n for (const [key, attribute] of Object.entries(rest.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n break\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n default: {\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${rest.type}\" not found in schema`)\n }\n }\n }\n\n if (typeNode.dereferencesTo) {\n const derefType = Object.assign(\n t.tsPropertySignature(\n INTERNAL_REFERENCE_SYMBOL,\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n ),\n {computed: true, optional: true},\n )\n props.push(derefType)\n }\n\n return t.tsTypeLiteral(props)\n }\n\n // Helper function used to generate TS types for object properties.\n private generateTsObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.generateTsType(attribute.value)\n const keyNode = isIdentifierName(key) ? t.identifier(key) : t.stringLiteral(key)\n const propertySignature = t.tsPropertySignature(keyNode, t.tsTypeAnnotation(type))\n propertySignature.optional = attribute.optional\n\n return propertySignature\n }\n\n private generateTsType(\n typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode,\n ): t.TSType {\n switch (typeNode.type) {\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n case 'number': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.numericLiteral(typeNode.value))\n }\n return t.tsNumberKeyword()\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n\n default: {\n throw new Error(\n `Encountered unsupported node type \"${\n // @ts-expect-error This should never happen\n typeNode.type\n }\" while generating schema types`,\n )\n }\n }\n }\n\n // Helper function used to generate TS types for union type nodes.\n private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {\n if (typeNode.of.length === 0) return t.tsNeverKeyword()\n if (typeNode.of.length === 1) return this.generateTsType(typeNode.of[0]!)\n return t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)))\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'array': {\n const acc = walkAndCountQueryTypeNodeStats(typeNode.of)\n acc.allTypes += 1 // count the array type itself\n return acc\n }\n case 'object': {\n // if the rest is unknown, we count it as one unknown type\n if (typeNode.rest && typeNode.rest.type === 'unknown') {\n return {allTypes: 2, emptyUnions: 0, unknownTypes: 1} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, emptyUnions: 0, unknownTypes: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n const attrs = Object.values(typeNode.attributes)\n let acc = restStats\n for (const attribute of attrs) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, emptyUnions: 1, unknownTypes: 0}\n }\n\n let acc = {allTypes: 1, emptyUnions: 0, unknownTypes: 0} // count the union type itself\n for (const type of typeNode.of) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(type)\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'unknown': {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 1}\n }\n default: {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 0}\n }\n }\n}\n\nfunction withoutNull(typeNode: TypeNode): TypeNode {\n if (typeNode.type !== 'union') return typeNode\n const of = typeNode.of.filter((member) => member.type !== 'null')\n return of.length === 1 ? of[0]! : {...typeNode, of}\n}\n"],"names":["t","typeEvaluate","safeParseQuery","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","getFilterArrayUnionType","getUniqueIdentifierForName","isIdentifierName","weakMapMemo","SchemaTypeGenerator","schema","evaluateQuery","query","ast","typeNode","tsType","generateTsType","stats","walkAndCountQueryTypeNodeStats","arrayOfUsed","identifiers","Map","tsTypes","uniqueTypeNames","Set","type","has","name","Error","add","currentIdentifierNames","values","map","id","uniqueIdentifier","set","documentTypeNames","filter","schemaType","evaluateProjection","documentType","projection","JSON","stringify","withoutNull","getType","typeName","get","undefined","hasType","isArrayOfUsed","Symbol","iterator","typeNames","generateArrayOfTsType","typeNodes","of","tsTypeReference","tsTypeParameterInstantiation","generateArrayTsType","identifier","every","unionTypeNode","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","generateDocumentTsType","document","props","Object","entries","attributes","key","node","generateTsObjectProperty","tsTypeLiteral","generateInlineTsType","addComment","tsUnknownKeyword","generateObjectTsType","attribute","push","rest","resolved","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","tsLiteralType","stringLiteral","computed","optional","value","keyNode","propertySignature","booleanLiteral","tsBooleanKeyword","tsNullKeyword","numericLiteral","tsNumberKeyword","tsStringKeyword","generateUnionTsType","length","tsNeverKeyword","acc","allTypes","emptyUnions","unknownTypes","restStats","attrs"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AACjC,SAQEC,YAAY,QAGP,UAAS;AAEhB,SAA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