@sanity/codegen 5.0.0-next-major.20251215144759 → 5.0.0-next-major.20251215213859
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.d.ts +0 -1
- package/lib/index.js +8 -29
- package/lib/index.js.map +1 -1
- package/package.json +6 -6
package/lib/index.d.ts
CHANGED
|
@@ -227,7 +227,6 @@ export declare type TypeGenConfig = z.infer<typeof configDefinition>
|
|
|
227
227
|
*/
|
|
228
228
|
export declare class TypeGenerator {
|
|
229
229
|
private getInternalReferenceSymbolDeclaration
|
|
230
|
-
private getArrayMemberDeclaration
|
|
231
230
|
private getSchemaTypeGenerator
|
|
232
231
|
private getSchemaTypeDeclarations
|
|
233
232
|
private getAllSanitySchemaTypesDeclaration
|
package/lib/index.js
CHANGED
|
@@ -575,11 +575,10 @@ function resultSuffix(variableName) {
|
|
|
575
575
|
const isUpperSnake = /^[A-Z0-9_]+$/.test(variableName), isSnake = /^[a-z0-9_]+$/.test(variableName) && variableName.includes("_");
|
|
576
576
|
return /^[a-z][A-Za-z0-9]*$/.test(variableName) ? `${variableName}Result` : isUpperSnake ? `${variableName}_RESULT` : isSnake ? `${variableName}_result` : `${variableName.replace(/[^A-Za-z0-9]/g, "")}Result`;
|
|
577
577
|
}
|
|
578
|
-
const INTERNAL_REFERENCE_SYMBOL = t.identifier("internalGroqTypeReferenceTo"), ALL_SANITY_SCHEMA_TYPES = t.identifier("AllSanitySchemaTypes"), SANITY_QUERIES = t.identifier("SanityQueries"),
|
|
578
|
+
const INTERNAL_REFERENCE_SYMBOL = t.identifier("internalGroqTypeReferenceTo"), ALL_SANITY_SCHEMA_TYPES = t.identifier("AllSanitySchemaTypes"), SANITY_QUERIES = t.identifier("SanityQueries"), RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set();
|
|
579
579
|
RESERVED_IDENTIFIERS.add(SANITY_QUERIES.name);
|
|
580
580
|
RESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name);
|
|
581
581
|
RESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name);
|
|
582
|
-
RESERVED_IDENTIFIERS.add(ARRAY_MEMBER.name);
|
|
583
582
|
function normalizePath(root, filename) {
|
|
584
583
|
const resolved = path.resolve(root, filename);
|
|
585
584
|
return path.relative(root, resolved);
|
|
@@ -617,10 +616,6 @@ function generateCode(node) {
|
|
|
617
616
|
|
|
618
617
|
`;
|
|
619
618
|
}
|
|
620
|
-
function isObjectArrayMember(typeNode) {
|
|
621
|
-
const { attributes, rest } = typeNode;
|
|
622
|
-
return "_key" in attributes || rest?.type === "object" && "_key" in rest.attributes;
|
|
623
|
-
}
|
|
624
619
|
class SchemaTypeGenerator {
|
|
625
620
|
schema;
|
|
626
621
|
tsTypes = /* @__PURE__ */ new Map();
|
|
@@ -690,9 +685,9 @@ class SchemaTypeGenerator {
|
|
|
690
685
|
}
|
|
691
686
|
// Helper function used to generate TS types for object type nodes.
|
|
692
687
|
generateObjectTsType(typeNode) {
|
|
693
|
-
const props = []
|
|
688
|
+
const props = [];
|
|
694
689
|
Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
|
|
695
|
-
|
|
690
|
+
props.push(this.generateTsObjectProperty(key, attribute));
|
|
696
691
|
});
|
|
697
692
|
const rest = typeNode.rest;
|
|
698
693
|
if (rest)
|
|
@@ -701,13 +696,13 @@ class SchemaTypeGenerator {
|
|
|
701
696
|
return t.tsUnknownKeyword();
|
|
702
697
|
case "object": {
|
|
703
698
|
Object.entries(rest.attributes).forEach(([key, attribute]) => {
|
|
704
|
-
|
|
699
|
+
props.push(this.generateTsObjectProperty(key, attribute));
|
|
705
700
|
});
|
|
706
701
|
break;
|
|
707
702
|
}
|
|
708
703
|
case "inline": {
|
|
709
704
|
const resolved = this.generateInlineTsType(rest);
|
|
710
|
-
return t.isTSUnknownKeyword(resolved) ? resolved :
|
|
705
|
+
return t.isTSUnknownKeyword(resolved) ? resolved : t.tsIntersectionType([t.tsTypeLiteral(props), resolved]);
|
|
711
706
|
}
|
|
712
707
|
default:
|
|
713
708
|
throw new Error(`Type "${rest.type}" not found in schema`);
|
|
@@ -722,10 +717,7 @@ class SchemaTypeGenerator {
|
|
|
722
717
|
);
|
|
723
718
|
props.push(derefType);
|
|
724
719
|
}
|
|
725
|
-
return
|
|
726
|
-
ARRAY_MEMBER,
|
|
727
|
-
t.tsTypeParameterInstantiation([t.tsTypeLiteral(props)])
|
|
728
|
-
) : t.tsTypeLiteral(props);
|
|
720
|
+
return t.tsTypeLiteral(props);
|
|
729
721
|
}
|
|
730
722
|
generateInlineTsType(typeNode) {
|
|
731
723
|
const id = this.identifiers.get(typeNode.name);
|
|
@@ -817,19 +809,6 @@ class TypeGenerator {
|
|
|
817
809
|
const ast = t.exportNamedDeclaration(declaration), code = generateCode(ast);
|
|
818
810
|
return { id, code, ast };
|
|
819
811
|
});
|
|
820
|
-
getArrayMemberDeclaration = computeOnce(() => {
|
|
821
|
-
const typeParam = t.tsTypeParameter(null, null, "T"), intersectionType = t.tsIntersectionType([
|
|
822
|
-
t.tsTypeReference(t.identifier("T")),
|
|
823
|
-
t.tsTypeLiteral([
|
|
824
|
-
t.tsPropertySignature(t.identifier("_key"), t.tsTypeAnnotation(t.tsStringKeyword()))
|
|
825
|
-
])
|
|
826
|
-
]), typeAlias = t.tsTypeAliasDeclaration(
|
|
827
|
-
ARRAY_MEMBER,
|
|
828
|
-
t.tsTypeParameterDeclaration([typeParam]),
|
|
829
|
-
intersectionType
|
|
830
|
-
), ast = t.exportNamedDeclaration(typeAlias), code = generateCode(ast);
|
|
831
|
-
return { id: ARRAY_MEMBER, code, ast };
|
|
832
|
-
});
|
|
833
812
|
getSchemaTypeGenerator = createSelector(
|
|
834
813
|
[(options) => options.schema],
|
|
835
814
|
(schema) => new SchemaTypeGenerator(schema)
|
|
@@ -937,7 +916,7 @@ class TypeGenerator {
|
|
|
937
916
|
return { code: generateCode(ast), ast };
|
|
938
917
|
}
|
|
939
918
|
async generateTypes(options) {
|
|
940
|
-
const { reporter: report } = options, internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration(),
|
|
919
|
+
const { reporter: report } = options, internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration(), schemaTypeDeclarations = this.getSchemaTypeDeclarations(options), allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options);
|
|
941
920
|
report?.event.generatedSchemaTypes({
|
|
942
921
|
internalReferenceSymbol,
|
|
943
922
|
schemaTypeDeclarations,
|
|
@@ -947,7 +926,7 @@ class TypeGenerator {
|
|
|
947
926
|
let code = "";
|
|
948
927
|
for (const declaration of schemaTypeDeclarations)
|
|
949
928
|
program.body.push(declaration.ast), code += declaration.code;
|
|
950
|
-
program.body.push(allSanitySchemaTypesDeclaration.ast), code += allSanitySchemaTypesDeclaration.code, program.body.push(internalReferenceSymbol.ast), code += internalReferenceSymbol.code
|
|
929
|
+
program.body.push(allSanitySchemaTypesDeclaration.ast), code += allSanitySchemaTypesDeclaration.code, program.body.push(internalReferenceSymbol.ast), code += internalReferenceSymbol.code;
|
|
951
930
|
const evaluatedModules = await TypeGenerator.getEvaluatedModules({
|
|
952
931
|
...options,
|
|
953
932
|
schemaTypeDeclarations,
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/types.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/casing.ts","../src/typescript/constants.ts","../src/typescript/helpers.ts","../src/typescript/schemaTypeGenerator.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as z from 'zod'\n\n/**\n * @internal\n */\nexport const configDefinition = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(true),\n})\n\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefinition.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {dirname, join, resolve} from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {type TransformOptions} from '@babel/core'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n _source: string,\n _filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n let source = _source\n let filename = _filename\n if (filename.endsWith('.astro')) {\n // append .ts to the filename so babel will parse it as typescript\n filename += '.ts'\n source = parseAstro(source)\n } else if (filename.endsWith('.vue')) {\n // append .ts to the filename so babel will parse it as typescript\n filename += '.ts'\n source = parseVue(source)\n }\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n\nfunction parseAstro(source: string): string {\n // find all code fences, the js code is between --- and ---\n const codeFences = source.match(/---\\n([\\s\\S]*?)\\n---/g)\n if (!codeFences) {\n return ''\n }\n\n return codeFences\n .map((codeFence) => {\n return codeFence.split('\\n').slice(1, -1).join('\\n')\n })\n .join('\\n')\n}\n\nfunction parseVue(source: string): string {\n // find all script tags, the js code is between <script> and </script>\n const scriptRegex = /<script(?:\\s+generic=[\"'][^\"']*[\"'])?[^>]*>([\\s\\S]*?)<\\/script>/g\n // const matches = [...source.matchAll(scriptRegex)]\n // TODO: swap once this code runs in `ES2020`\n const matches = matchAllPolyfill(source, scriptRegex)\n if (!matches.length) {\n return ''\n }\n\n return matches.map((match) => match[1]).join('\\n')\n}\n\n// TODO: remove once this code runs in `ES2020`\nfunction matchAllPolyfill(str: string, regex: RegExp): RegExpMatchArray[] {\n if (!regex.global) {\n throw new Error('matchAll polyfill requires a global regex (with /g flag)')\n }\n\n const matches = []\n let match\n while ((match = regex.exec(str)) !== null) {\n matches.push(match)\n }\n return matches\n}\n","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 {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['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 node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\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.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\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 node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\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 node: init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\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 params.forEach((param, i) => {\n newScope.push({\n id: param as babelTypes.LVal,\n init: fnArguments[i] as babelTypes.Expression | undefined,\n })\n })\n\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope: newScope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, fnArguments, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n // Handle TypeScript type assertions (e.g., `'foo' as string`)\n if (babelTypes.isTSAsExpression(node)) {\n return resolveExpression({\n node: node.expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\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 node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\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 >= 0 && babelTypes.isAssignmentPattern(params[paramIndex])) {\n argument = params[paramIndex].right\n }\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\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 node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\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 node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n fnArguments,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n fnArguments: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\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 (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\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 // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(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 node: binding.path.node,\n file: tree,\n scope: newScope,\n fnArguments,\n babelConfig,\n filename: resolvedFile,\n resolver,\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 node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n fnArguments,\n resolver,\n babelConfig,\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 node: p.node,\n importName,\n filename: resolvedFile,\n fnArguments,\n resolver,\n babelConfig,\n })\n } catch (e) {\n if (e.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 node,\n importName,\n filename,\n fnArguments,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration | babelTypes.ExportAllDeclaration\n importName: string\n filename: string\n fnArguments: babelTypes.Node[]\n babelConfig: TransformOptions\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(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 node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: resolvedFile,\n babelConfig,\n resolver,\n fnArguments,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`, {\n cause: `noBinding:${importName}`,\n })\n}\n","import type * as t from '@babel/types'\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n (typeof value === 'object' || typeof value === 'function') && !!value\n\n/**\n * Statistics from the query type evaluation process.\n * @public\n */\nexport interface TypeEvaluationStats {\n allTypes: number\n unknownTypes: number\n emptyUnions: number\n}\n\ninterface QueryVariable {\n id: t.Identifier\n start?: number\n end?: number\n}\n\n/**\n * A GROQ query extracted from a source file.\n * @public\n */\nexport interface ExtractedQuery {\n variable: QueryVariable\n query: string\n filename: string\n}\n\n/**\n * A module (file) containing extracted GROQ queries.\n * @public\n */\nexport interface ExtractedModule {\n filename: string\n queries: ExtractedQuery[]\n errors: QueryExtractionError[]\n}\n\n/**\n * An `ExtractedQuery` that has been evaluated against a schema, yielding a TypeScript type.\n * @public\n */\nexport interface EvaluatedQuery extends ExtractedQuery {\n id: t.Identifier\n code: string\n tsType: t.TSType\n ast: t.ExportNamedDeclaration\n stats: TypeEvaluationStats\n}\n\n/**\n * A module containing queries that have been evaluated.\n * @public\n */\nexport interface EvaluatedModule {\n filename: string\n queries: EvaluatedQuery[]\n errors: (QueryExtractionError | QueryEvaluationError)[]\n}\n\ninterface QueryExtractionErrorOptions {\n variable?: QueryVariable\n cause: unknown\n filename: string\n}\n\n/**\n * An error that occurred during query extraction.\n * @public\n */\nexport class QueryExtractionError extends Error {\n variable?: QueryVariable\n filename: string\n constructor({variable, cause, filename}: QueryExtractionErrorOptions) {\n super(\n `Error while extracting query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryExtractionError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n\ninterface QueryEvaluationErrorOptions {\n variable?: QueryVariable\n cause: unknown\n filename: string\n}\n\n/**\n * An error that occurred during query evaluation.\n * @public\n */\nexport class QueryEvaluationError extends Error {\n variable?: QueryVariable\n filename: string\n constructor({variable, cause, filename}: QueryEvaluationErrorOptions) {\n super(\n `Error while evaluating query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryEvaluationError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n","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'\nimport {resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\nimport {type ExtractedModule, type ExtractedQuery, QueryExtractionError} from './types'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\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\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 {id, start, end} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n queries.push({variable, query, filename})\n } catch (cause) {\n errors.push(new QueryExtractionError({filename, variable, cause}))\n }\n }\n },\n })\n\n return {filename, queries, errors}\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","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","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'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\nimport {type ExtractedModule, QueryExtractionError} from './types'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ninterface FindQueriesInPathOptions {\n path: string | string[]\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 path,\n babelOptions = getBabelConfig(),\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 const files = glob\n .sync(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n .sort()\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 filename,\n queries: [],\n errors: [new QueryExtractionError({cause, filename})],\n }\n }\n }\n }\n\n return {files, queries: getQueries()}\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","/*\n * resultSuffix takes a variable name and appends \"result\" in the same casing style.\n * Supported: camelCase, PascalCase, snake_case, UPPER_SNAKE.\n * Falls back to camelCase-style suffix when casing is unknown.\n */\nexport function resultSuffix(variableName: string): string {\n if (!variableName) return 'result'\n\n const isUpperSnake = /^[A-Z0-9_]+$/.test(variableName) // VALUE, USER_NAME\n const isSnake = /^[a-z0-9_]+$/.test(variableName) && variableName.includes('_') // user_name\n const isCamel = /^[a-z][A-Za-z0-9]*$/.test(variableName) // userName\n\n if (isCamel) {\n return `${variableName}Result`\n }\n\n if (isUpperSnake) {\n return `${variableName}_RESULT`\n }\n\n if (isSnake) {\n return `${variableName}_result`\n }\n\n // Fallback: clean weird chars and use camel-style suffix\n const cleaned = variableName.replace(/[^A-Za-z0-9]/g, '')\n\n return `${cleaned}Result`\n}\n","import * as t from '@babel/types'\n\nexport const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo')\nexport const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes')\nexport const SANITY_QUERIES = t.identifier('SanityQueries')\nexport const ARRAY_MEMBER = t.identifier('ArrayMember')\n\nexport const RESERVED_IDENTIFIERS = new Set<string>()\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name)\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name)\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name)\nRESERVED_IDENTIFIERS.add(ARRAY_MEMBER.name)\n","import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type ObjectTypeNode} from 'groq-js'\n\nimport {RESERVED_IDENTIFIERS} from './constants'\n\nexport function normalizePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n return path.relative(root, resolved)\n}\n\nexport function sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\nexport function 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 = {current: undefined as TReturn | undefined, computed: false}\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 isObjectArrayMember(typeNode: ObjectTypeNode): boolean {\n const {attributes, rest} = typeNode\n return '_key' in attributes || (rest?.type === 'object' && '_key' in rest.attributes)\n}\n","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'\nimport {ARRAY_MEMBER, INTERNAL_REFERENCE_SYMBOL} from './constants'\nimport {\n getUniqueIdentifierForName,\n isObjectArrayMember,\n sanitizeIdentifier,\n weakMapMemo,\n} from './helpers'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n private tsTypes = new Map<string, t.TSType>()\n private identifiers = new Map<string, t.Identifier>()\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(\n Array.from(this.identifiers.values()).map((id) => id.name),\n )\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 private generateTsType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\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 array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\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 propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 const isArrayMember = isObjectArrayMember(typeNode)\n\n // Skip _key if this is an array member - it will be added via ArrayMember<T>\n Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n if (isArrayMember && key === '_key') return\n props.push(this.generateTsObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n // Skip _key - it will be added via ArrayMember<T> wrapper\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n if (key === '_key') return\n props.push(this.generateTsObjectProperty(key, attribute))\n })\n break\n }\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 // If this is an array member, wrap inline type with ArrayMember\n if (isArrayMember) {\n return t.tsTypeReference(ARRAY_MEMBER, t.tsTypeParameterInstantiation([resolved]))\n }\n return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])\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 // Wrap with ArrayMember if this is an array member pattern\n if (isArrayMember) {\n return t.tsTypeReference(\n ARRAY_MEMBER,\n t.tsTypeParameterInstantiation([t.tsTypeLiteral(props)]),\n )\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 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 // 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 typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n getType(typeName: string): {tsType: t.TSType; id: t.Identifier} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {tsType, id}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n evaluateQuery = weakMapMemo(\n ({query}: Pick<ExtractedQuery, 'query'>): {tsType: t.TSType; stats: TypeEvaluationStats} => {\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 {tsType, stats}\n },\n );\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'unknown': {\n return {allTypes: 1, unknownTypes: 1, emptyUnions: 0}\n }\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, unknownTypes: 1, emptyUnions: 0} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, unknownTypes: 0, emptyUnions: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n return Object.values(typeNode.attributes).reduce((acc, attribute) => {\n const {allTypes, unknownTypes, emptyUnions} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n return {\n allTypes: acc.allTypes + allTypes,\n unknownTypes: acc.unknownTypes + unknownTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n }\n }, restStats)\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, unknownTypes: 0, emptyUnions: 1}\n }\n\n return typeNode.of.reduce(\n (acc, type) => {\n const {allTypes, unknownTypes, emptyUnions} = walkAndCountQueryTypeNodeStats(type)\n return {\n allTypes: acc.allTypes + allTypes,\n unknownTypes: acc.unknownTypes + unknownTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n }\n },\n {allTypes: 1, unknownTypes: 0, emptyUnions: 0}, // count the union type itself\n )\n }\n default: {\n return {allTypes: 1, unknownTypes: 0, emptyUnions: 0}\n }\n }\n}\n","import process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_MEMBER,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants'\nimport {computeOnce, generateCode, getUniqueIdentifierForName, normalizePath} from './helpers'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types'\n\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n generatedSchemaTypes: WorkerChannel.Event<{\n internalReferenceSymbol: {\n id: t.Identifier\n code: string\n ast: t.ExportNamedDeclaration\n }\n schemaTypeDeclarations: {\n id: t.Identifier\n name: string\n code: string\n tsType: t.TSType\n ast: t.ExportNamedDeclaration\n }[]\n allSanitySchemaTypesDeclaration: {\n code: string\n id: t.Identifier\n ast: t.ExportNamedDeclaration\n }\n }>\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {code: string; ast: t.Program}\n }>\n}>\n\nexport interface GenerateTypesOptions {\n schema: SchemaType\n schemaPath?: string\n queries?: AsyncIterable<ExtractedModule>\n root?: string\n overloadClientMethods?: boolean\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {id, code, ast}\n })\n\n private getArrayMemberDeclaration = computeOnce(() => {\n // Creates: export type ArrayMember<T> = T & { _key: string };\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n\n const typeAlias = t.tsTypeAliasDeclaration(\n ARRAY_MEMBER,\n t.tsTypeParameterDeclaration([typeParam]),\n intersectionType,\n )\n const ast = t.exportNamedDeclaration(typeAlias)\n const code = generateCode(ast)\n\n return {id: ARRAY_MEMBER, code, ast}\n })\n\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n (root = process.cwd(), schemaPath, schema) =>\n Array.from(schema).map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {id, code, name, tsType, ast}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {id: ALL_SANITY_SCHEMA_TYPES, code, ast}\n },\n )\n\n private static async getEvaluatedModules({\n root = process.cwd(),\n reporter: report,\n schemaTypeGenerator,\n schemaTypeDeclarations,\n queries: extractedModules,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryExtractionError | QueryEvaluationError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {tsType, stats} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replace(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n id,\n code: generateCode(ast),\n ast,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({variable, cause, filename}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n filename,\n queries,\n errors,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n overloadClientMethods = true,\n evaluatedModules,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {code: '', ast: t.program([])}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (!queries.length) return {code: '', ast: t.program([])}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n types.length\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\n const code = generateCode(ast)\n return {code, ast}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const arrayMemberDeclaration = this.getArrayMemberDeclaration()\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n internalReferenceSymbol,\n schemaTypeDeclarations,\n allSanitySchemaTypesDeclaration,\n })\n\n const program = t.program([])\n let code = ''\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n program.body.push(arrayMemberDeclaration.ast)\n code += arrayMemberDeclaration.code\n\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator: this.getSchemaTypeGenerator(options),\n })\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {code, ast: program}\n }\n}\n"],"names":["path","__dirname","parse","debug","babelTypes","require","loadTSConfig","resolve","fs"],"mappings":";;;;;;;;;;;;;;;;;;AAQO,MAAM,mBAAmB,EAAE,OAAO;AAAA,EACvC,MAAM,EACH,OAAA,EACA,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,EACtB,QAAQ;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAAA,EACH,QAAQ,EAAE,SAAS,QAAQ,eAAe;AAAA,EAC1C,WAAW,EAAE,SAAS,QAAQ,mBAAmB;AAAA,EACjD,qBAAqB,EAAE,UAAU,QAAQ,EAAI;AAAA,EAC7C,uBAAuB,EAAE,QAAA,EAAU,QAAQ,EAAI;AACjD,CAAC;AAaD,eAAsB,WAAWA,OAAsC;AACrE,MAAI;AACF,UAAM,UAAU,MAAM,SAASA,OAAM,OAAO,GACtC,OAAO,MAAM,MAAM,OAAO;AAChC,WAAO,iBAAiB,WAAW,IAAI;AAAA,EACzC,SAAS,OAAO;AACd,QAAI,iBAAiB,EAAE;AACrB,YAAM,IAAI;AAAA,QACR;AAAA,GAA0B,MAAM,OAAO,IAAI,CAAC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oB,MAE5B,QAAQ,MAAM,oBAAoB,EAAC,oBAAA,CAAoB,GAEhD,EAAC,MAAM,KAAK,QAAA;AAAA,EACrB;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/types.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/casing.ts","../src/typescript/constants.ts","../src/typescript/helpers.ts","../src/typescript/schemaTypeGenerator.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as z from 'zod'\n\n/**\n * @internal\n */\nexport const configDefinition = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(true),\n})\n\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefinition.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {dirname, join, resolve} from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {type TransformOptions} from '@babel/core'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n _source: string,\n _filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n let source = _source\n let filename = _filename\n if (filename.endsWith('.astro')) {\n // append .ts to the filename so babel will parse it as typescript\n filename += '.ts'\n source = parseAstro(source)\n } else if (filename.endsWith('.vue')) {\n // append .ts to the filename so babel will parse it as typescript\n filename += '.ts'\n source = parseVue(source)\n }\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n\nfunction parseAstro(source: string): string {\n // find all code fences, the js code is between --- and ---\n const codeFences = source.match(/---\\n([\\s\\S]*?)\\n---/g)\n if (!codeFences) {\n return ''\n }\n\n return codeFences\n .map((codeFence) => {\n return codeFence.split('\\n').slice(1, -1).join('\\n')\n })\n .join('\\n')\n}\n\nfunction parseVue(source: string): string {\n // find all script tags, the js code is between <script> and </script>\n const scriptRegex = /<script(?:\\s+generic=[\"'][^\"']*[\"'])?[^>]*>([\\s\\S]*?)<\\/script>/g\n // const matches = [...source.matchAll(scriptRegex)]\n // TODO: swap once this code runs in `ES2020`\n const matches = matchAllPolyfill(source, scriptRegex)\n if (!matches.length) {\n return ''\n }\n\n return matches.map((match) => match[1]).join('\\n')\n}\n\n// TODO: remove once this code runs in `ES2020`\nfunction matchAllPolyfill(str: string, regex: RegExp): RegExpMatchArray[] {\n if (!regex.global) {\n throw new Error('matchAll polyfill requires a global regex (with /g flag)')\n }\n\n const matches = []\n let match\n while ((match = regex.exec(str)) !== null) {\n matches.push(match)\n }\n return matches\n}\n","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 {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['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 node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\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.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\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 node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\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 node: init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\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 params.forEach((param, i) => {\n newScope.push({\n id: param as babelTypes.LVal,\n init: fnArguments[i] as babelTypes.Expression | undefined,\n })\n })\n\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope: newScope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, fnArguments, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n // Handle TypeScript type assertions (e.g., `'foo' as string`)\n if (babelTypes.isTSAsExpression(node)) {\n return resolveExpression({\n node: node.expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\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 node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\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 >= 0 && babelTypes.isAssignmentPattern(params[paramIndex])) {\n argument = params[paramIndex].right\n }\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\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 node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\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 node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n fnArguments,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n fnArguments: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\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 (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\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 // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(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 node: binding.path.node,\n file: tree,\n scope: newScope,\n fnArguments,\n babelConfig,\n filename: resolvedFile,\n resolver,\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 node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n fnArguments,\n resolver,\n babelConfig,\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 node: p.node,\n importName,\n filename: resolvedFile,\n fnArguments,\n resolver,\n babelConfig,\n })\n } catch (e) {\n if (e.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 node,\n importName,\n filename,\n fnArguments,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration | babelTypes.ExportAllDeclaration\n importName: string\n filename: string\n fnArguments: babelTypes.Node[]\n babelConfig: TransformOptions\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(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 node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: resolvedFile,\n babelConfig,\n resolver,\n fnArguments,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`, {\n cause: `noBinding:${importName}`,\n })\n}\n","import type * as t from '@babel/types'\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n (typeof value === 'object' || typeof value === 'function') && !!value\n\n/**\n * Statistics from the query type evaluation process.\n * @public\n */\nexport interface TypeEvaluationStats {\n allTypes: number\n unknownTypes: number\n emptyUnions: number\n}\n\ninterface QueryVariable {\n id: t.Identifier\n start?: number\n end?: number\n}\n\n/**\n * A GROQ query extracted from a source file.\n * @public\n */\nexport interface ExtractedQuery {\n variable: QueryVariable\n query: string\n filename: string\n}\n\n/**\n * A module (file) containing extracted GROQ queries.\n * @public\n */\nexport interface ExtractedModule {\n filename: string\n queries: ExtractedQuery[]\n errors: QueryExtractionError[]\n}\n\n/**\n * An `ExtractedQuery` that has been evaluated against a schema, yielding a TypeScript type.\n * @public\n */\nexport interface EvaluatedQuery extends ExtractedQuery {\n id: t.Identifier\n code: string\n tsType: t.TSType\n ast: t.ExportNamedDeclaration\n stats: TypeEvaluationStats\n}\n\n/**\n * A module containing queries that have been evaluated.\n * @public\n */\nexport interface EvaluatedModule {\n filename: string\n queries: EvaluatedQuery[]\n errors: (QueryExtractionError | QueryEvaluationError)[]\n}\n\ninterface QueryExtractionErrorOptions {\n variable?: QueryVariable\n cause: unknown\n filename: string\n}\n\n/**\n * An error that occurred during query extraction.\n * @public\n */\nexport class QueryExtractionError extends Error {\n variable?: QueryVariable\n filename: string\n constructor({variable, cause, filename}: QueryExtractionErrorOptions) {\n super(\n `Error while extracting query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryExtractionError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n\ninterface QueryEvaluationErrorOptions {\n variable?: QueryVariable\n cause: unknown\n filename: string\n}\n\n/**\n * An error that occurred during query evaluation.\n * @public\n */\nexport class QueryEvaluationError extends Error {\n variable?: QueryVariable\n filename: string\n constructor({variable, cause, filename}: QueryEvaluationErrorOptions) {\n super(\n `Error while evaluating query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryEvaluationError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n","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'\nimport {resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\nimport {type ExtractedModule, type ExtractedQuery, QueryExtractionError} from './types'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\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\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 {id, start, end} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n queries.push({variable, query, filename})\n } catch (cause) {\n errors.push(new QueryExtractionError({filename, variable, cause}))\n }\n }\n },\n })\n\n return {filename, queries, errors}\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","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","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'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\nimport {type ExtractedModule, QueryExtractionError} from './types'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ninterface FindQueriesInPathOptions {\n path: string | string[]\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 path,\n babelOptions = getBabelConfig(),\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 const files = glob\n .sync(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n .sort()\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 filename,\n queries: [],\n errors: [new QueryExtractionError({cause, filename})],\n }\n }\n }\n }\n\n return {files, queries: getQueries()}\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","/*\n * resultSuffix takes a variable name and appends \"result\" in the same casing style.\n * Supported: camelCase, PascalCase, snake_case, UPPER_SNAKE.\n * Falls back to camelCase-style suffix when casing is unknown.\n */\nexport function resultSuffix(variableName: string): string {\n if (!variableName) return 'result'\n\n const isUpperSnake = /^[A-Z0-9_]+$/.test(variableName) // VALUE, USER_NAME\n const isSnake = /^[a-z0-9_]+$/.test(variableName) && variableName.includes('_') // user_name\n const isCamel = /^[a-z][A-Za-z0-9]*$/.test(variableName) // userName\n\n if (isCamel) {\n return `${variableName}Result`\n }\n\n if (isUpperSnake) {\n return `${variableName}_RESULT`\n }\n\n if (isSnake) {\n return `${variableName}_result`\n }\n\n // Fallback: clean weird chars and use camel-style suffix\n const cleaned = variableName.replace(/[^A-Za-z0-9]/g, '')\n\n return `${cleaned}Result`\n}\n","import * as t from '@babel/types'\n\nexport const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo')\nexport const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes')\nexport const SANITY_QUERIES = t.identifier('SanityQueries')\n\nexport const RESERVED_IDENTIFIERS = new Set<string>()\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name)\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name)\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name)\n","import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\n\nimport {RESERVED_IDENTIFIERS} from './constants'\n\nexport function normalizePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n return path.relative(root, resolved)\n}\n\nexport function sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\nexport function 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 = {current: undefined as TReturn | undefined, computed: false}\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","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'\nimport {INTERNAL_REFERENCE_SYMBOL} from './constants'\nimport {getUniqueIdentifierForName, sanitizeIdentifier, weakMapMemo} from './helpers'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n private tsTypes = new Map<string, t.TSType>()\n private identifiers = new Map<string, t.Identifier>()\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(\n Array.from(this.identifiers.values()).map((id) => id.name),\n )\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 private generateTsType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\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 array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\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 propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n props.push(this.generateTsObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n props.push(this.generateTsObjectProperty(key, attribute))\n })\n break\n }\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 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 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 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 // 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 typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n getType(typeName: string): {tsType: t.TSType; id: t.Identifier} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {tsType, id}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n evaluateQuery = weakMapMemo(\n ({query}: Pick<ExtractedQuery, 'query'>): {tsType: t.TSType; stats: TypeEvaluationStats} => {\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 {tsType, stats}\n },\n );\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'unknown': {\n return {allTypes: 1, unknownTypes: 1, emptyUnions: 0}\n }\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, unknownTypes: 1, emptyUnions: 0} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, unknownTypes: 0, emptyUnions: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n return Object.values(typeNode.attributes).reduce((acc, attribute) => {\n const {allTypes, unknownTypes, emptyUnions} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n return {\n allTypes: acc.allTypes + allTypes,\n unknownTypes: acc.unknownTypes + unknownTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n }\n }, restStats)\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, unknownTypes: 0, emptyUnions: 1}\n }\n\n return typeNode.of.reduce(\n (acc, type) => {\n const {allTypes, unknownTypes, emptyUnions} = walkAndCountQueryTypeNodeStats(type)\n return {\n allTypes: acc.allTypes + allTypes,\n unknownTypes: acc.unknownTypes + unknownTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n }\n },\n {allTypes: 1, unknownTypes: 0, emptyUnions: 0}, // count the union type itself\n )\n }\n default: {\n return {allTypes: 1, unknownTypes: 0, emptyUnions: 0}\n }\n }\n}\n","import process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing'\nimport {ALL_SANITY_SCHEMA_TYPES, INTERNAL_REFERENCE_SYMBOL, SANITY_QUERIES} from './constants'\nimport {computeOnce, generateCode, getUniqueIdentifierForName, normalizePath} from './helpers'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types'\n\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n generatedSchemaTypes: WorkerChannel.Event<{\n internalReferenceSymbol: {\n id: t.Identifier\n code: string\n ast: t.ExportNamedDeclaration\n }\n schemaTypeDeclarations: {\n id: t.Identifier\n name: string\n code: string\n tsType: t.TSType\n ast: t.ExportNamedDeclaration\n }[]\n allSanitySchemaTypesDeclaration: {\n code: string\n id: t.Identifier\n ast: t.ExportNamedDeclaration\n }\n }>\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {code: string; ast: t.Program}\n }>\n}>\n\nexport interface GenerateTypesOptions {\n schema: SchemaType\n schemaPath?: string\n queries?: AsyncIterable<ExtractedModule>\n root?: string\n overloadClientMethods?: boolean\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {id, code, ast}\n })\n\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n (root = process.cwd(), schemaPath, schema) =>\n Array.from(schema).map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {id, code, name, tsType, ast}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {id: ALL_SANITY_SCHEMA_TYPES, code, ast}\n },\n )\n\n private static async getEvaluatedModules({\n root = process.cwd(),\n reporter: report,\n schemaTypeGenerator,\n schemaTypeDeclarations,\n queries: extractedModules,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryExtractionError | QueryEvaluationError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {tsType, stats} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replace(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n id,\n code: generateCode(ast),\n ast,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({variable, cause, filename}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n filename,\n queries,\n errors,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n overloadClientMethods = true,\n evaluatedModules,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {code: '', ast: t.program([])}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (!queries.length) return {code: '', ast: t.program([])}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n types.length\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\n const code = generateCode(ast)\n return {code, ast}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n internalReferenceSymbol,\n schemaTypeDeclarations,\n allSanitySchemaTypesDeclaration,\n })\n\n const program = t.program([])\n let code = ''\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator: this.getSchemaTypeGenerator(options),\n })\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {code, ast: program}\n }\n}\n"],"names":["path","__dirname","parse","debug","babelTypes","require","loadTSConfig","resolve","fs"],"mappings":";;;;;;;;;;;;;;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0B,KAAK,sCAAA,GAC/B,yBAAyB,KAAK,0BAA0B,OAAO,GAC/D,kCAAkC,KAAK,mCAAmC,OAAO;AAEvF,YAAQ,MAAM,qBAAqB;AAAA,MACjC;AAAA,MACA;AAAA,MACA;AAAA,IAAA,CACD;AAED,UAAM,UAAU,EAAE,QAAQ,EAAE;AAC5B,QAAI,OAAO;AAEX,eAAW,eAAe;AACxB,cAAQ,KAAK,KAAK,YAAY,GAAG,GACjC,QAAQ,YAAY;AAGtB,YAAQ,KAAK,KAAK,gCAAgC,GAAG,GACrD,QAAQ,gCAAgC,MAExC,QAAQ,KAAK,KAAK,wBAAwB,GAAG,GAC7C,QAAQ,wBAAwB;AAEhC,UAAM,mBAAmB,MAAM,cAAc,oBAAoB;AAAA,MAC/D,GAAG;AAAA,MACH;AAAA,MACA,qBAAqB,KAAK,uBAAuB,OAAO;AAAA,IAAA,CACzD;AACD,eAAW,EAAC,aAAY;AACtB,iBAAW,SAAS;AAClB,gBAAQ,KAAK,KAAK,MAAM,GAAG,GAC3B,QAAQ,MAAM;AAIlB,UAAM,sBAAsB,MAAM,cAAc,uBAAuB;AAAA,MACrE,GAAG;AAAA,MACH;AAAA,IAAA,CACD;AACD,WAAA,QAAQ,KAAK,KAAK,GAAG,oBAAoB,IAAI,IAAI,GACjD,QAAQ,oBAAoB,MAE5B,QAAQ,MAAM,oBAAoB,EAAC,oBAAA,CAAoB,GAEhD,EAAC,MAAM,KAAK,QAAA;AAAA,EACrB;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/codegen",
|
|
3
|
-
"version": "5.0.0-next-major.
|
|
3
|
+
"version": "5.0.0-next-major.20251215213859+afca06069e",
|
|
4
4
|
"description": "Codegen toolkit for Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"reselect": "^5.1.1",
|
|
54
54
|
"tsconfig-paths": "^4.2.0",
|
|
55
55
|
"zod": "^3.25.76",
|
|
56
|
-
"groq": "5.0.0-next-major.
|
|
56
|
+
"groq": "5.0.0-next-major.20251215213859+afca06069e"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@sanity/pkg-utils": "^10.2.0",
|
|
@@ -67,10 +67,10 @@
|
|
|
67
67
|
"eslint": "^9.39.1",
|
|
68
68
|
"rimraf": "^5.0.10",
|
|
69
69
|
"vitest": "^3.2.4",
|
|
70
|
-
"@repo/eslint-config": "5.0.0-next-major.
|
|
71
|
-
"@repo/
|
|
72
|
-
"@repo/
|
|
73
|
-
"@repo/
|
|
70
|
+
"@repo/eslint-config": "5.0.0-next-major.20251215213859+afca06069e",
|
|
71
|
+
"@repo/test-config": "5.0.0-next-major.20251215213859+afca06069e",
|
|
72
|
+
"@repo/tsconfig": "5.0.0-next-major.20251215213859+afca06069e",
|
|
73
|
+
"@repo/package.config": "5.0.0-next-major.20251215213859+afca06069e"
|
|
74
74
|
},
|
|
75
75
|
"engines": {
|
|
76
76
|
"node": ">=20.19 <22 || >=22.12"
|