@sanity/codegen 3.86.2-experimental.0 → 3.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/asyncQueue.ts","../src/typescript/schemaTypeGenerator.ts","../src/typescript/generateTypes.ts","../src/typescript/registerBabel.ts"],"sourcesContent":["/* eslint-disable camelcase */\nimport {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nconst defaultPaths = [\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\n/**\n * Define a raw config schema that accepts either a single 'schema' or an array 'schemas'.\n *\n * @remarks\n * - Both fields are optional, but if both are provided, that is an error\n * - If 'schemas' is provided, it cannot be an empty array\n */\nconst rawConfigSchema = z\n .object({\n path: z.union([z.string(), z.array(z.string())]).optional(),\n generates: z.string().optional(),\n formatGeneratedCode: z.boolean().optional(),\n overloadClientMethods: z.boolean().optional(),\n augmentGroqModule: z.boolean().optional(),\n schema: z.string().optional(),\n schemas: z\n .array(\n z.object({\n projectId: z.string().optional(),\n dataset: z.string().optional(),\n schemaPath: z.string(),\n }),\n )\n .optional(),\n })\n .superRefine((data, ctx) => {\n if (data.schema !== undefined && data.schemas !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Configuration cannot contain both \"schema\" and \"schemas\". Use one or the other.',\n })\n }\n })\n .refine((d) => d.schemas === undefined || d.schemas.length > 0, {\n message:\n '\"schemas\" array cannot be empty. Please provide at least one schema definition or use the \"schema\" property instead.',\n })\n\n/**\n * Normalized config type always containing a \"schemas\" array and no \"schema\" property\n */\nexport type NormalizedTypegenConfig = {\n path: string[]\n generates: string\n formatGeneratedCode: boolean\n overloadClientMethods: boolean\n augmentGroqModule: boolean\n schemas: Array<{projectId: string; dataset: string; schemaPath: string}>\n}\n\n// Transform the raw config to normalized output by applying defaults and ensuring a schemas array exists.\nexport const normalizedConfigSchema = rawConfigSchema.transform((d) => {\n return {\n path: typeof d.path === 'string' ? [d.path] : (d.path ?? defaultPaths),\n generates: d.generates ?? './sanity.types.ts',\n formatGeneratedCode: d.formatGeneratedCode ?? true,\n overloadClientMethods: d.overloadClientMethods ?? true,\n augmentGroqModule: d.augmentGroqModule ?? true,\n schemas: d.schemas\n ? d.schemas.map((s) => ({\n projectId: s.projectId ?? 'default',\n dataset: s.dataset ?? 'default',\n schemaPath: s.schemaPath,\n }))\n : [{projectId: 'default', dataset: 'default', schemaPath: d.schema ?? './schema.json'}],\n }\n})\n\nexport async function readConfig(path: string): Promise<NormalizedTypegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return normalizedConfigSchema.parse(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n // If the config file doesn't exist, use defaults by parsing an empty object\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return normalizedConfigSchema.parse({})\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 {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\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 }\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","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {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\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n /** type indicates whether this is a query or projection */\n type: 'query' | 'projection'\n /** location is the location of the query in the source */\n location?: {\n start?: {\n line: number\n column: number\n index: number\n }\n end?: {\n line: number\n column: number\n index: number\n }\n }\n}\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery', 'defineProjection']\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 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: importFileName,\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 {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 {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst defineProjectionFunctionName = 'defineProjection'\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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 or defineProjection function call\n const isDefineCall =\n babelTypes.isCallExpression(init) &&\n (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) ||\n isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee))\n\n if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {\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 queryName = `${node.id.name}`\n\n // Determine the kind based on the call or tag\n let resultType: 'query' | 'projection' = 'query' // Default to query\n let expressionToResolve: babelTypes.Expression = init // Default to the original init expression\n\n if (isDefineCall) {\n // If it's a define call, resolve the first argument instead of the whole call\n if (init.arguments.length > 0 && babelTypes.isExpression(init.arguments[0])) {\n expressionToResolve = init.arguments[0]\n }\n // Check specifically if it's a defineProjection call from groq\n if (isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee)) {\n resultType = 'projection'\n }\n // Otherwise, it remains 'query' (for defineQuery from groq or next-sanity)\n }\n // isGroqTemplateTag implies 'query', and we resolve the tagged template itself\n\n const queryResult = resolveExpression({\n node: expressionToResolve, // Use the potentially updated expression node\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n const location = node.loc\n ? {\n start: {\n ...node.loc?.start,\n },\n end: {\n ...node.loc?.end,\n },\n }\n : {}\n\n queries.push({name: queryName, result: queryResult, type: resultType, location})\n }\n },\n })\n\n return queries\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\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 {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\nexport type ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\nexport type ResultError = {\n type: 'error'\n error: Error\n filename: string\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 async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\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 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 queries = 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 query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\n}\n","/**\n * Implements an asynchronous queue pattern. Allows enqueueing items,\n * consuming them via an async iterator, and signaling completion or errors.\n */\nexport class AsyncQueue<T> {\n // Internal state:\n // `queue`: Holds items yet to be consumed.\n // `resume`: A callback to signal the consumer when new items arrive or the queue finishes/errors.\n // `finished`: Flag indicating if the producer is done adding items (via `finish` or `throwError`).\n // `pendingError`: Stores an error passed to `throwError`, to be thrown by the consumer.\n private queue: T[] = []\n private resume: (() => void) | null = null\n private finished = false\n private pendingError: unknown = null\n\n /**\n * Enqueues an item. Throws if `finish` or `throwError` has been called.\n */\n public enqueue(item: T): void {\n if (this.finished) {\n throw new Error('Cannot enqueue items to a finished AsyncQueue.')\n }\n this.queue.push(item)\n // If the iterator is waiting, resume it.\n if (this.resume) {\n this.resume()\n this.resume = null\n }\n }\n\n /**\n * Signals that no more items will be enqueued. Idempotent.\n */\n public finish(): void {\n if (!this.finished) {\n this.finished = true\n // If the iterator is waiting, resume it.\n if (this.resume) {\n this.resume()\n this.resume = null\n }\n }\n }\n\n /**\n * Signals an error occurred during production. Finishes the queue. Idempotent.\n */\n public throwError(error: unknown): void {\n if (!this.finished) {\n this.pendingError = error\n this.finished = true\n // If the iterator is waiting, resume it.\n if (this.resume) {\n this.resume()\n this.resume = null\n }\n }\n }\n\n /**\n * Async iterator to consume enqueued items.\n * Throws if `throwError` was called.\n */\n public async *[Symbol.asyncIterator](): AsyncIterableIterator<T> {\n while (true) {\n // Throw immediately if an error occurred before or during waiting.\n if (this.pendingError) {\n throw this.pendingError\n }\n\n // Wait for new items if the queue is empty and not finished.\n if (this.queue.length === 0 && !this.finished) {\n await new Promise<void>((resolve) => {\n this.resume = resolve\n })\n // Re-check for errors after resuming, as `throwError` could have been called\n // while we were waiting.\n if (this.pendingError) {\n throw this.pendingError\n }\n }\n\n // Yield available items.\n while (this.queue.length > 0) {\n // `!` is safe because `this.queue.length > 0`.\n yield this.queue.shift()!\n }\n\n // If finished and queue is empty, the loop is done.\n if (this.finished && this.queue.length === 0) {\n break\n }\n }\n // Final check for errors, in case `throwError` was called after the last item\n // was yielded but before the loop condition was checked again.\n if (this.pendingError) {\n throw this.pendingError\n }\n }\n}\n","import * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\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'\n\n/** @internal */\nexport interface TypeEvaluationStats {\n totalTypeNodes: number\n unknownTypeCount: number\n emptyUnionCount: number\n}\n\n// Helper: Uppercase first letter\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\n// Helper: Sanitize identifier\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\ninterface TypeGeneratorOptions {\n schema: SchemaType\n projectId: string | 'default'\n dataset: string | 'default'\n}\n\nexport class SchemaTypeGenerator {\n private tsTypes: Map<string, t.TSType>\n private documentTypeNames: Set<string>\n private identifiers: Map<string, t.Identifier>\n\n public schema: SchemaType\n public projectId: string | 'default'\n public dataset: string | 'default'\n\n static REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\n\n static sanitizeIdentifier(input: string): string {\n return uppercaseFirstLetter(sanitizeIdentifier(input))\n }\n\n constructor({dataset, projectId, schema}: TypeGeneratorOptions) {\n this.dataset = dataset\n this.projectId = projectId\n this.schema = schema\n\n // Build unique sanitized name mapping to avoid collisions\n const sanitizedCounts: Record<string, number> = {}\n\n this.identifiers = this.schema.reduce((acc, {name}) => {\n const base = SchemaTypeGenerator.sanitizeIdentifier(name)\n const count = (sanitizedCounts[base] || 0) + 1\n sanitizedCounts[base] = count\n const uniqueName = count === 1 ? base : `${base}_${count}`\n acc.set(name, t.identifier(uniqueName))\n return acc\n }, new Map<string, t.Identifier>())\n\n this.documentTypeNames = new Set(schema.filter((i) => i.type === 'document').map((i) => i.name))\n\n this.tsTypes = schema.reduce((acc, i) => {\n acc.set(i.name, this.getTypeNodeType(i))\n return acc\n }, new Map<string, t.TSType>())\n }\n\n getTypeNames(): string[] {\n return Array.from(this.tsTypes.keys())\n }\n\n getDocumentTypeNames(): string[] {\n return Array.from(this.documentTypeNames)\n }\n\n getTsType(name: string): t.TSType | undefined {\n return this.tsTypes.get(name)\n }\n\n getIdentifier(name: string): t.Identifier | undefined {\n return this.identifiers.get(name)\n }\n\n evaluateQuery(query: string): {tsType: t.TSType; stats: TypeEvaluationStats} {\n const ast = safeParseQuery(query)\n const typeNode = typeEvaluate(ast, this.schema)\n const tsType = this.getTypeNodeType(typeNode)\n const stats = SchemaTypeGenerator.calculateTypeStats(typeNode)\n return {tsType, stats}\n }\n\n evaluateProjection(projection: string): {tsType: t.TSType; stats: TypeEvaluationStats} {\n const results = this.getDocumentTypeNames()\n .map((typeName) => {\n const ast = safeParseQuery(`* [_type==${JSON.stringify(typeName)}] ${projection} [0]`)\n let typeNode = typeEvaluate(ast, this.schema)\n\n // manually remove `null` from type node since `[0]` will always result\n // in a union with null\n if (typeNode.type === 'union') {\n const nonNullMembers = typeNode.of.filter((member) => member.type !== 'null')\n if (nonNullMembers.length === 0) {\n return null\n } else if (nonNullMembers.length === 1) {\n typeNode = nonNullMembers[0]\n } else {\n typeNode = {...typeNode, of: nonNullMembers}\n }\n }\n\n if (typeNode.type === 'object') {\n // Check if all attributes are null and there is no meaningful rest\n const attributeValues = Object.values(typeNode.attributes)\n const allAttributesNull = attributeValues.every((attr) => attr.value.type === 'null')\n const hasMeaningfulRest = typeNode.rest && typeNode.rest.type !== 'unknown'\n\n // Only simplify if there are attributes AND all are null\n if (attributeValues.length > 0 && allAttributesNull && !hasMeaningfulRest) {\n return null\n }\n }\n\n if (typeNode.type === 'null') {\n return null\n }\n\n const stats = SchemaTypeGenerator.calculateTypeStats(typeNode)\n const tsType = t.tsTypeReference(\n t.identifier('DocumentTypeScoped'),\n t.tsTypeParameterInstantiation([\n this.getTypeNodeType(typeNode),\n t.tsLiteralType(t.stringLiteral(typeName)),\n ]),\n )\n\n return {tsType, stats}\n })\n .filter((i) => !!i)\n\n if (!results.length) {\n return {\n tsType: t.tsNeverKeyword(),\n // emptyUnions is 1 because the union type has no members, resulting in a `never` type\n stats: {totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 1},\n }\n }\n\n if (results.length === 1) return results[0]\n\n const combinedTsType = t.tsUnionType(results.map((i) => i.tsType))\n const accumulatedStats = results.reduce(\n (acc, {stats}) => ({\n totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,\n emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount,\n unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount,\n }),\n {totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0},\n )\n // Add 1 for the final union type since multiple results were combined\n accumulatedStats.totalTypeNodes += 1\n\n return {tsType: combinedTsType, stats: accumulatedStats}\n }\n\n private getTypeNodeType(\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.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(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 const identifier = this.getIdentifier(typeNode.name)\n if (!identifier) throw new Error(`Type \"${typeNode.name}\" not found in schema`)\n return t.tsTypeReference(identifier)\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n\n default:\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\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.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(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.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\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.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const identifier = this.getIdentifier(rest.name)\n if (!identifier) {\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${rest.name}\" in schema`,\n },\n ]\n return missing\n }\n\n return t.tsIntersectionType([t.tsTypeLiteral(props), t.tsTypeReference(identifier)])\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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n\n // Helper function to calculate statistics for a TypeNode\n private static calculateTypeStats(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'unknown':\n return {totalTypeNodes: 1, unknownTypeCount: 1, emptyUnionCount: 0}\n\n case 'array': {\n const stats = SchemaTypeGenerator.calculateTypeStats(typeNode.of)\n stats.totalTypeNodes += 1 // count the array type itself\n return stats\n }\n\n case 'object': {\n const initialStats: TypeEvaluationStats = {\n totalTypeNodes: 1,\n unknownTypeCount: 0,\n emptyUnionCount: 0,\n } // count the object type itself\n\n const restStats = typeNode.rest\n ? SchemaTypeGenerator.calculateTypeStats(typeNode.rest)\n : null\n if (restStats) {\n initialStats.totalTypeNodes += restStats.totalTypeNodes\n initialStats.unknownTypeCount += restStats.unknownTypeCount\n initialStats.emptyUnionCount += restStats.emptyUnionCount\n }\n\n return Object.values(typeNode.attributes).reduce<TypeEvaluationStats>((acc, attribute) => {\n const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value)\n acc.totalTypeNodes += stats.totalTypeNodes\n acc.unknownTypeCount += stats.unknownTypeCount\n acc.emptyUnionCount += stats.emptyUnionCount\n return acc\n }, initialStats)\n }\n\n case 'union': {\n if (typeNode.of.length === 0) {\n return {totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 1}\n }\n\n return typeNode.of.reduce(\n (acc, type) => {\n const stats = SchemaTypeGenerator.calculateTypeStats(type)\n acc.totalTypeNodes += stats.totalTypeNodes\n acc.unknownTypeCount += stats.unknownTypeCount\n acc.emptyUnionCount += stats.emptyUnionCount\n return acc\n },\n {totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0}, // count the union type itself\n )\n }\n\n case 'type': {\n // Type declarations don't add to the count themselves, only their value does.\n return SchemaTypeGenerator.calculateTypeStats(typeNode.value)\n }\n\n case 'document': {\n // Documents behave like objects for stats calculation\n const initialStats: TypeEvaluationStats = {\n totalTypeNodes: 1,\n unknownTypeCount: 0,\n emptyUnionCount: 0,\n }\n return Object.values(typeNode.attributes).reduce<TypeEvaluationStats>((acc, attribute) => {\n const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value)\n acc.totalTypeNodes += stats.totalTypeNodes\n acc.unknownTypeCount += stats.unknownTypeCount\n acc.emptyUnionCount += stats.emptyUnionCount\n return acc\n }, initialStats)\n }\n\n // Base types\n case 'string':\n case 'number':\n case 'boolean':\n case 'null':\n case 'inline':\n default:\n return {totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0}\n }\n }\n}\n","/* eslint-disable max-depth */\n/* eslint-disable max-statements */\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type SchemaType} from 'groq-js'\n\nimport {AsyncQueue} from './asyncQueue'\nimport {type ResultError, type ResultQueries} from './findQueriesInPath'\nimport {SchemaTypeGenerator, type TypeEvaluationStats} from './schemaTypeGenerator'\n\nconst SanityQueries = t.identifier('SanityQueries')\nconst SanityProjections = t.identifier('SanityProjections')\nconst SanitySchemas = t.identifier('SanitySchemas')\nconst DocumentTypeScoped = t.identifier('DocumentTypeScoped')\nconst DatasetScoped = t.identifier('DatasetScoped')\nconst ExtractDataset = t.identifier('ExtractDataset')\nconst AllSchemaTypes = t.identifier('AllSanitySchemaTypes')\nconst ReferenceSymbol = Object.assign(t.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME), {\n typeAnnotation: t.tsTypeAnnotation(\n Object.assign(t.tsTypeOperator(t.tsSymbolKeyword()), {operator: 'unique'}),\n ),\n})\n\nexport interface GeneratedSchema {\n code: string\n schemas: {\n filename: string\n projectId: string | 'default'\n dataset: string | 'default'\n typeCount: number\n }[]\n}\n\nexport interface GeneratedQueries {\n filename: string\n results: GeneratedQuery[]\n error?: unknown\n}\n\nexport interface GeneratedQuery {\n name: string\n query: string\n code: string\n type: 'query' | 'projection'\n stats: TypeEvaluationStats\n}\n\nexport interface GeneratedTypemap {\n code: string\n stats: TypeEvaluationStats\n}\n\nexport interface TypegenResults {\n generatedSchema: () => Promise<GeneratedSchema>\n generatedQueries: () => AsyncIterable<GeneratedQueries>\n generatedTypemap: () => Promise<GeneratedTypemap>\n}\n\nexport interface GenerateTypesOptions {\n schemas: {\n projectId: string\n dataset: string\n filename: string\n schema: SchemaType\n }[]\n queriesByFile: AsyncIterable<ResultQueries | ResultError>\n augmentGroqModule: boolean\n overloadClientMethods: boolean\n}\n\nfunction generateCode(node: t.Node) {\n return `${new CodeGenerator(node).generate().code.trim()}\\n\\n`\n}\n\nfunction scopeByDataset(tsType: t.TSType, options: {dataset: string; projectId: string}) {\n return t.tsTypeReference(\n DatasetScoped,\n t.tsTypeParameterInstantiation([\n tsType,\n t.tsLiteralType(t.stringLiteral(options.dataset)),\n t.tsLiteralType(t.stringLiteral(options.projectId)),\n ]),\n )\n}\n\n// TODO: replace with `Promise.withResolvers` once the environments supports it\nfunction PromiseWithResolvers<T = void>() {\n let resolve!: (value: T) => void\n let reject!: (error: unknown) => void\n const promise = new Promise<T>((thisResolve, thisReject) => {\n resolve = thisResolve\n reject = thisReject\n })\n return {promise, resolve, reject}\n}\n\nexport function generateTypes({\n schemas,\n queriesByFile,\n augmentGroqModule,\n overloadClientMethods,\n}: GenerateTypesOptions): TypegenResults {\n const globalIdentifiers = new Set<string>()\n\n globalIdentifiers.add(SanityQueries.name)\n globalIdentifiers.add(SanityProjections.name)\n globalIdentifiers.add(SanitySchemas.name)\n globalIdentifiers.add(DocumentTypeScoped.name)\n globalIdentifiers.add(DatasetScoped.name)\n globalIdentifiers.add(ExtractDataset.name)\n globalIdentifiers.add(AllSchemaTypes.name)\n globalIdentifiers.add(ReferenceSymbol.name)\n\n const generatedQueries = new AsyncQueue<GeneratedQueries>()\n const {\n promise: generatedSchema,\n resolve: resolveGeneratedSchema,\n reject: rejectGeneratedSchema,\n } = PromiseWithResolvers<GeneratedSchema>()\n const {\n promise: generatedTypemap,\n resolve: resolveGeneratedTypemap,\n reject: rejectGeneratedTypemap,\n } = PromiseWithResolvers<GeneratedTypemap>()\n\n ;(async () => {\n const schemaGenerators = schemas.map((options) => new SchemaTypeGenerator(options))\n const typeNames = new Set(schemaGenerators.flatMap((i) => i.getTypeNames()))\n\n let schemaCode = ''\n\n if (overloadClientMethods) {\n schemaCode += generateCode(t.importDeclaration([], t.stringLiteral('@sanity/client')))\n }\n\n schemaCode += generateCode(\n Object.assign(\n t.importDeclaration(\n [\n t.importSpecifier(DocumentTypeScoped, DocumentTypeScoped),\n t.importSpecifier(ExtractDataset, ExtractDataset),\n t.importSpecifier(DatasetScoped, DatasetScoped),\n ],\n t.stringLiteral('groq'),\n ),\n {importKind: 'type'},\n ),\n )\n\n schemaCode += generateCode(\n t.exportNamedDeclaration(\n Object.assign(t.variableDeclaration('const', [t.variableDeclarator(ReferenceSymbol)]), {\n declare: true,\n }),\n ),\n )\n\n const schemaIdentifiers = new Set<string>()\n\n for (const typeName of typeNames) {\n const identifiers = new Set(\n schemaGenerators\n .map((i) => i.getIdentifier(typeName)?.name)\n .filter((i) => typeof i === 'string'),\n )\n\n for (const identifier of identifiers) {\n globalIdentifiers.add(identifier)\n\n const tsTypes = schemaGenerators\n .filter((i) => i.getIdentifier(typeName)?.name === identifier)\n .map((i) => {\n const tsType = i.getTsType(typeName)\n if (tsType && schemaGenerators.length > 1) return scopeByDataset(tsType, i)\n return tsType\n })\n .filter((i) => i !== undefined)\n\n const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)\n\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(identifier), null, tsType)\n const code = generateCode(t.exportNamedDeclaration(typeAlias))\n schemaIdentifiers.add(identifier)\n schemaCode += code\n }\n }\n\n const allSchemaTypesDeclaration = generateCode(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n AllSchemaTypes,\n null,\n t.tsUnionType(\n Array.from(schemaIdentifiers).map((identifier) =>\n t.tsTypeReference(t.identifier(identifier)),\n ),\n ),\n ),\n ),\n )\n\n schemaCode += allSchemaTypesDeclaration\n\n if (augmentGroqModule) {\n const sanitySchemasProperties = schemas.map(({dataset, projectId}) =>\n t.tsPropertySignature(\n t.stringLiteral(`${projectId}:${dataset}`),\n t.tsTypeAnnotation(\n t.tsTypeReference(\n ExtractDataset,\n t.tsTypeParameterInstantiation([\n t.tsTypeReference(AllSchemaTypes),\n t.tsLiteralType(t.stringLiteral(dataset)),\n t.tsLiteralType(t.stringLiteral(projectId)),\n ]),\n ),\n ),\n ),\n )\n\n const sanitySchemasDeclaration = generateCode(\n t.declareModule(\n t.stringLiteral('groq'),\n t.blockStatement([\n t.tsInterfaceDeclaration(\n SanitySchemas,\n null,\n [],\n t.tsInterfaceBody(sanitySchemasProperties),\n ),\n ]),\n ),\n )\n schemaCode += sanitySchemasDeclaration\n }\n\n resolveGeneratedSchema({\n code: schemaCode,\n schemas: schemas.map(({schema, ...rest}) => ({\n ...rest,\n typeCount: schema.length,\n })),\n })\n\n const queryIdentifiers = new Map<string, t.Identifier[]>()\n const projectionIdentifiers = new Map<string, t.Identifier[]>()\n const totalStats: TypeEvaluationStats = {\n totalTypeNodes: 0,\n unknownTypeCount: 0,\n emptyUnionCount: 0,\n }\n\n for await (const input of queriesByFile) {\n try {\n if (input.type === 'error') throw input.error\n\n const results: GeneratedQuery[] = []\n for (const query of input.queries) {\n const desiredName = SchemaTypeGenerator.sanitizeIdentifier(\n query.type === 'projection' ? `${query.name}ProjectionResult` : `${query.name}Result`,\n )\n\n let resultingName = desiredName\n let index = 2\n while (globalIdentifiers.has(resultingName)) {\n resultingName = `${desiredName}_${index}`\n index++\n }\n\n const identifier = t.identifier(resultingName)\n let identifiers =\n query.type === 'projection'\n ? projectionIdentifiers.get(query.result)\n : queryIdentifiers.get(query.result)\n\n if (!identifiers) {\n identifiers = []\n if (query.type === 'projection') {\n projectionIdentifiers.set(query.result, identifiers)\n } else {\n queryIdentifiers.set(query.result, identifiers)\n }\n }\n identifiers.push(identifier)\n\n const evaluationResults = schemaGenerators.map((i) => {\n const result =\n query.type === 'projection'\n ? i.evaluateProjection(query.result)\n : i.evaluateQuery(query.result)\n\n return result\n })\n\n const aggregatedQueryStats = evaluationResults.reduce<TypeEvaluationStats>(\n (acc, {stats}) => ({\n totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,\n unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount,\n emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount,\n }),\n {totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0},\n )\n\n totalStats.totalTypeNodes += aggregatedQueryStats.totalTypeNodes\n totalStats.unknownTypeCount += aggregatedQueryStats.unknownTypeCount\n totalStats.emptyUnionCount += aggregatedQueryStats.emptyUnionCount\n\n const tsTypes = evaluationResults.map(({tsType}, resultIndex) => {\n if (schemas.length === 1) return tsType\n return scopeByDataset(tsType, schemaGenerators[resultIndex])\n })\n\n const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)\n const typeAlias = t.tsTypeAliasDeclaration(identifier, null, tsType)\n\n const code = generateCode(\n t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${input.filename}`},\n {type: 'CommentLine', value: ` Variable: ${query.name}`},\n {\n type: 'CommentLine',\n value: ` ${query.type === 'projection' ? 'Projection' : 'Query'}: ${query.result.replace(/(\\r\\n|\\n|\\r)/gm, '').trim()}`,\n },\n ]),\n )\n\n results.push({\n name: query.name,\n query: query.result,\n type: query.type,\n code,\n stats: aggregatedQueryStats,\n })\n }\n generatedQueries.enqueue({filename: input.filename, results})\n } catch (error) {\n generatedQueries.enqueue({filename: input.filename, results: [], error})\n }\n }\n\n generatedQueries.finish()\n\n let typemapCode = ''\n const clientModuleBlockStatement: t.Statement[] = []\n const groqModuleBlockStatement: t.Statement[] = []\n\n // Only generate SanityQueries if there are query results\n if (queryIdentifiers.size > 0) {\n const sanityQueriesInterfaceDeclaration = t.tsInterfaceDeclaration(\n SanityQueries,\n null,\n [],\n t.tsInterfaceBody(\n Array.from(queryIdentifiers).map(([query, identifiers]) =>\n t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n identifiers.length === 1\n ? t.tsTypeReference(identifiers[0])\n : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),\n ),\n ),\n ),\n ),\n )\n // Add to both module declarations if needed\n clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)\n groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)\n }\n\n // Only generate SanityProjections if there are projection results\n if (projectionIdentifiers.size > 0) {\n const sanityProjectionsInterfaceDeclaration = t.tsInterfaceDeclaration(\n SanityProjections,\n null,\n [],\n t.tsInterfaceBody(\n Array.from(projectionIdentifiers).map(([projection, identifiers]) =>\n t.tsPropertySignature(\n t.stringLiteral(projection),\n t.tsTypeAnnotation(\n identifiers.length === 1\n ? t.tsTypeReference(identifiers[0])\n : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),\n ),\n ),\n ),\n ),\n )\n // Add only to groq module declaration\n groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration)\n }\n\n if (overloadClientMethods && clientModuleBlockStatement.length > 0) {\n const clientModuleDeclaration = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement(clientModuleBlockStatement),\n )\n typemapCode += generateCode(clientModuleDeclaration)\n }\n\n if (augmentGroqModule && groqModuleBlockStatement.length > 0) {\n const groqModuleDeclaration = t.declareModule(\n t.stringLiteral('groq'),\n t.blockStatement(groqModuleBlockStatement),\n )\n typemapCode += generateCode(groqModuleDeclaration)\n }\n\n resolveGeneratedTypemap({\n code: typemapCode,\n stats: totalStats,\n })\n })().catch((err) => {\n generatedQueries.throwError(err)\n rejectGeneratedSchema(err)\n rejectGeneratedTypemap(err)\n })\n\n return {\n generatedSchema: () => generatedSchema,\n generatedQueries: () => generatedQueries,\n generatedTypemap: () => generatedTypemap,\n }\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"],"names":["path","parse","debug","babelTypes","require","traverse","loadTSConfig","resolve","fs","tsType"],"mappings":";;;;;;;;;;;;;;;AAMA,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AACF,GASM,kBAAkB,EACrB,OAAO;AAAA,EACN,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,MAAM,EAAE,OAAQ,CAAA,CAAC,CAAC,EAAE,SAAS;AAAA,EAC1D,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,qBAAqB,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC1C,uBAAuB,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC5C,mBAAmB,EAAE,QAAQ,EAAE,SAAS;AAAA,EACxC,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,SA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","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nexport const configDefintion = 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 CodegenConfig = z.infer<typeof configDefintion>\n\nexport async function readConfig(path: string): Promise<CodegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefintion.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefintion.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 {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\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 }\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","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {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\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n\n /** location is the location of the query in the source */\n location: {\n start?: {\n line: number\n column: number\n index: number\n }\n end?: {\n line: number\n column: number\n index: number\n }\n }\n}\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 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: importFileName,\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 {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 {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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 queryName = `${node.id.name}`\n const queryResult = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n const location = node.loc\n ? {\n start: {\n ...node.loc?.start,\n },\n end: {\n ...node.loc?.end,\n },\n }\n : {}\n\n queries.push({name: queryName, result: queryResult, location})\n }\n },\n })\n\n return queries\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\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 {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\ntype ResultError = {\n type: 'error'\n error: Error\n filename: string\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 async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\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 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 queries = 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 query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\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","import {CodeGenerator} from '@babel/generator'\nimport * 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 type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nconst REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\nconst ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'\n\ntype QueryWithTypeNode = {\n query: string\n typeNode: TypeNode\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @internal\n * @beta\n */\nexport class TypeGenerator {\n // Simple set to keep track of generated type names, to avoid conflicts\n private generatedTypeName: Set<string> = new Set()\n // Map between type names and their generated type names, used to resolve the correct generated type name\n private typeNameMap: Map<string, string> = new Map()\n // Map between type nodes and their generated type names, used for query mapping\n private typeNodeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =\n new Map()\n\n private readonly schema: SchemaType\n\n constructor(schema: SchemaType) {\n this.schema = schema\n\n this.schema.forEach((s) => {\n this.getTypeName(s.name, s)\n })\n }\n\n /**\n * Generate TypeScript types for the given schema\n * @returns string\n * @internal\n * @beta\n */\n generateSchemaTypes(): string {\n const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []\n\n const schemaNames = new Set<string>()\n this.schema.forEach((schema) => {\n const typeLiteral = this.getTypeNodeType(schema)\n\n const schemaName = this.typeNodeNameMap.get(schema)\n if (!schemaName) {\n throw new Error(`Schema name not found for schema ${schema.name}`)\n }\n\n schemaNames.add(schemaName)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)\n\n typeDeclarations.push(t.exportNamedDeclaration(typeAlias))\n })\n\n typeDeclarations.push(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),\n null,\n t.tsUnionType(\n [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),\n ),\n ),\n ),\n )\n\n // Generate TypeScript code from the AST nodes\n return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\\n\\n')\n }\n\n /**\n * Takes a identifier and a type node and generates a type alias for the type node.\n * @param identifierName - The name of the type to generated\n * @param typeNode - The type node to generate the type for\n * @returns\n * @internal\n * @beta\n */\n generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {\n const type = this.getTypeNodeType(typeNode)\n\n const typeName = this.getTypeName(identifierName, typeNode)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)\n\n return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()\n }\n\n static generateKnownTypes(): string {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())\n typeOperator.operator = 'unique'\n\n const identifier = t.identifier(REFERENCE_SYMBOL_NAME)\n identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])\n decleration.declare = true\n return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()\n }\n\n /**\n * Takes a list of queries from the codebase and generates a type declaration\n * for SanityClient to consume.\n *\n * Note: only types that have previously been generated with `generateTypeNodeTypes`\n * will be included in the query map.\n *\n * @param queries - A list of queries to generate a type declaration for\n * @returns\n * @internal\n * @beta\n */\n generateQueryMap(queries: QueryWithTypeNode[]): string {\n const typesByQuerystring: {[query: string]: string[]} = {}\n\n for (const query of queries) {\n const name = this.typeNodeNameMap.get(query.typeNode)\n if (!name) {\n continue\n }\n\n typesByQuerystring[query.query] ??= []\n typesByQuerystring[query.query].push(name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n t.identifier('SanityQueries'),\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 t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),\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.importDeclaration([], t.stringLiteral('@sanity/client'))\n\n return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()\n }\n\n /**\n * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these\n * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.\n * When we reference a type we also keep track of the original name so we can reference the correct type later.\n */\n private getTypeName(\n name: string,\n typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,\n ): string {\n const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))\n\n let generatedName = desiredName\n let i = 2\n while (this.generatedTypeName.has(generatedName)) {\n // add _ and a index and increment that index until we find a name that is not in the map\n generatedName = `${desiredName}_${i++}`\n }\n this.generatedTypeName.add(generatedName)\n this.typeNameMap.set(name, generatedName)\n if (typeNode) {\n this.typeNodeNameMap.set(typeNode, generatedName)\n }\n\n return generatedName\n }\n\n private getTypeNodeType(\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.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(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 // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\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.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(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.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\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.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const resolved = this.generateInlineTsType(rest)\n\n // if an object's rest type is unknown, we can't generate a type literal for it\n // so we return unknown\n if (t.isTSUnknownKeyword(resolved)) {\n return 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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\n }\n\n private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {\n const referencedTypeNode = this.schema.find((schema) => schema.name === typeNode.name)\n // Check if we have a schema reference for the type node\n if (referencedTypeNode === undefined) {\n // Is it already generated by another type node?\n const generatedName = this.typeNameMap.get(typeNode.name)\n if (generatedName) {\n return t.tsTypeReference(t.identifier(generatedName))\n }\n\n // Not found in schema, return unknown type\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n },\n ]\n return missing\n }\n\n const generatedName = this.typeNameMap.get(referencedTypeNode.name)\n\n if (generatedName) {\n return t.tsTypeReference(t.identifier(generatedName))\n }\n\n return t.tsUnknownKeyword()\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n}\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n"],"names":["path","parse","debug","babelTypes","require","traverse","loadTSConfig","resolve","fs","generatedName"],"mappings":";;;;;;;;;;;;;;;AAKa,MAAA,kBAAkB,EAAE,OAAO;AAAA,EACtC,MAAM,EACH,OAAO,EACP,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,QAAQ,EAAE,QAAQ,EAAI;AACjD,CAAC;AAID,eAAsB,WAAWA,OAAsC;AACjE,MAAA;AACI,UAAA,UAAU,MAAM,SAASA,OAAM,OAAO,GACtC,OAAO,MAAM,MAAM,OAAO;AACzB,WAAA,gBAAgB,WAAW,IAAI;AAA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D,KAAK,uBAAuB,KAAK,IAAI;AAAA,IACvC;AAEO,WAAA,EAAE,cAAc,KAAK;AAAA,EAAA;AAEhC;AACA,SAAS,qBAAqB,OAAuB;AAC5C,SAAA,MAAM,OAAO,CAAC,EAAE,gBAAgB,MAAM,MAAM,CAAC;AACtD;AAEA,SAAS,mBAAmB,OAAuB;AACjD,SAAO,GAAG,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,eAAe,CAAC,GAAG,SAAS,KAAK,YAAA,CAAa,CAAC;AAC7F;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/codegen",
3
- "version": "3.86.2-experimental.0",
3
+ "version": "3.87.0",
4
4
  "description": "Codegen toolkit for Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -41,6 +41,15 @@
41
41
  "!**/__tests__/**",
42
42
  "babel.config.json"
43
43
  ],
44
+ "scripts": {
45
+ "build": "pkg-utils build --strict --check --clean",
46
+ "check:types": "tsc --project tsconfig.lib.json",
47
+ "clean": "rimraf lib coverage",
48
+ "lint": "eslint --cache .",
49
+ "prepublishOnly": "turbo run build",
50
+ "test": "vitest",
51
+ "watch": "pkg-utils watch"
52
+ },
44
53
  "dependencies": {
45
54
  "@babel/core": "^7.23.9",
46
55
  "@babel/generator": "^7.23.6",
@@ -52,22 +61,22 @@
52
61
  "@babel/types": "^7.23.9",
53
62
  "debug": "^4.3.4",
54
63
  "globby": "^11.1.0",
64
+ "groq": "3.87.0",
55
65
  "groq-js": "^1.16.1",
56
66
  "json5": "^2.2.3",
57
67
  "tsconfig-paths": "^4.2.0",
58
- "zod": "^3.22.4",
59
- "groq": "3.86.2-experimental.0"
68
+ "zod": "^3.22.4"
60
69
  },
61
70
  "devDependencies": {
71
+ "@repo/package.config": "3.87.0",
72
+ "@repo/test-config": "3.87.0",
62
73
  "@types/babel__core": "^7.20.5",
63
74
  "@types/babel__generator": "^7.6.8",
64
75
  "@types/babel__register": "^7.17.3",
65
76
  "@types/babel__traverse": "^7.20.5",
66
77
  "@types/debug": "^4.1.12",
67
78
  "rimraf": "^5.0.10",
68
- "vitest": "^3.1.1",
69
- "@repo/test-config": "0.0.0",
70
- "@repo/package.config": "0.0.0"
79
+ "vitest": "^3.1.1"
71
80
  },
72
81
  "engines": {
73
82
  "node": ">=18"
@@ -75,12 +84,5 @@
75
84
  "publishConfig": {
76
85
  "access": "public"
77
86
  },
78
- "scripts": {
79
- "build": "pkg-utils build --strict --check --clean",
80
- "check:types": "tsc --project tsconfig.lib.json",
81
- "clean": "rimraf lib coverage",
82
- "lint": "eslint --cache .",
83
- "test": "vitest",
84
- "watch": "pkg-utils watch"
85
- }
86
- }
87
+ "gitHead": "97c3b32940f2324a9f0fc25097c33f1813374644"
88
+ }
@@ -1,21 +1,8 @@
1
- export {type NormalizedTypegenConfig, readConfig} from '../readConfig'
1
+ export {type CodegenConfig, readConfig} from '../readConfig'
2
2
  export {readSchema} from '../readSchema'
3
3
  export {safeParseQuery} from '../safeParseQuery'
4
- export {
5
- findQueriesInPath,
6
- type ResultError,
7
- type ResultQueries,
8
- } from '../typescript/findQueriesInPath'
4
+ export {findQueriesInPath} from '../typescript/findQueriesInPath'
9
5
  export {findQueriesInSource} from '../typescript/findQueriesInSource'
10
- export {
11
- type GeneratedQueries,
12
- type GeneratedQuery,
13
- type GeneratedSchema,
14
- type GeneratedTypemap,
15
- generateTypes,
16
- type GenerateTypesOptions,
17
- type TypegenResults,
18
- } from '../typescript/generateTypes'
19
6
  export {getResolver} from '../typescript/moduleResolver'
20
7
  export {registerBabel} from '../typescript/registerBabel'
21
- export {type TypeEvaluationStats} from '../typescript/schemaTypeGenerator'
8
+ export {TypeGenerator} from '../typescript/typeGenerator'
package/src/readConfig.ts CHANGED
@@ -1,96 +1,38 @@
1
- /* eslint-disable camelcase */
2
1
  import {readFile} from 'node:fs/promises'
3
2
 
4
3
  import * as json5 from 'json5'
5
4
  import * as z from 'zod'
6
5
 
7
- const defaultPaths = [
8
- './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}',
9
- './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',
10
- './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',
11
- ]
12
-
13
- /**
14
- * Define a raw config schema that accepts either a single 'schema' or an array 'schemas'.
15
- *
16
- * @remarks
17
- * - Both fields are optional, but if both are provided, that is an error
18
- * - If 'schemas' is provided, it cannot be an empty array
19
- */
20
- const rawConfigSchema = z
21
- .object({
22
- path: z.union([z.string(), z.array(z.string())]).optional(),
23
- generates: z.string().optional(),
24
- formatGeneratedCode: z.boolean().optional(),
25
- overloadClientMethods: z.boolean().optional(),
26
- augmentGroqModule: z.boolean().optional(),
27
- schema: z.string().optional(),
28
- schemas: z
29
- .array(
30
- z.object({
31
- projectId: z.string().optional(),
32
- dataset: z.string().optional(),
33
- schemaPath: z.string(),
34
- }),
35
- )
36
- .optional(),
37
- })
38
- .superRefine((data, ctx) => {
39
- if (data.schema !== undefined && data.schemas !== undefined) {
40
- ctx.addIssue({
41
- code: z.ZodIssueCode.custom,
42
- message: 'Configuration cannot contain both "schema" and "schemas". Use one or the other.',
43
- })
44
- }
45
- })
46
- .refine((d) => d.schemas === undefined || d.schemas.length > 0, {
47
- message:
48
- '"schemas" array cannot be empty. Please provide at least one schema definition or use the "schema" property instead.',
49
- })
50
-
51
- /**
52
- * Normalized config type always containing a "schemas" array and no "schema" property
53
- */
54
- export type NormalizedTypegenConfig = {
55
- path: string[]
56
- generates: string
57
- formatGeneratedCode: boolean
58
- overloadClientMethods: boolean
59
- augmentGroqModule: boolean
60
- schemas: Array<{projectId: string; dataset: string; schemaPath: string}>
61
- }
62
-
63
- // Transform the raw config to normalized output by applying defaults and ensuring a schemas array exists.
64
- export const normalizedConfigSchema = rawConfigSchema.transform((d) => {
65
- return {
66
- path: typeof d.path === 'string' ? [d.path] : (d.path ?? defaultPaths),
67
- generates: d.generates ?? './sanity.types.ts',
68
- formatGeneratedCode: d.formatGeneratedCode ?? true,
69
- overloadClientMethods: d.overloadClientMethods ?? true,
70
- augmentGroqModule: d.augmentGroqModule ?? true,
71
- schemas: d.schemas
72
- ? d.schemas.map((s) => ({
73
- projectId: s.projectId ?? 'default',
74
- dataset: s.dataset ?? 'default',
75
- schemaPath: s.schemaPath,
76
- }))
77
- : [{projectId: 'default', dataset: 'default', schemaPath: d.schema ?? './schema.json'}],
78
- }
6
+ export const configDefintion = z.object({
7
+ path: z
8
+ .string()
9
+ .or(z.array(z.string()))
10
+ .default([
11
+ './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}',
12
+ './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',
13
+ './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',
14
+ ]),
15
+ schema: z.string().default('./schema.json'),
16
+ generates: z.string().default('./sanity.types.ts'),
17
+ formatGeneratedCode: z.boolean().default(true),
18
+ overloadClientMethods: z.boolean().default(true),
79
19
  })
80
20
 
81
- export async function readConfig(path: string): Promise<NormalizedTypegenConfig> {
21
+ export type CodegenConfig = z.infer<typeof configDefintion>
22
+
23
+ export async function readConfig(path: string): Promise<CodegenConfig> {
82
24
  try {
83
25
  const content = await readFile(path, 'utf-8')
84
26
  const json = json5.parse(content)
85
- return normalizedConfigSchema.parse(json)
27
+ return configDefintion.parseAsync(json)
86
28
  } catch (error) {
87
29
  if (error instanceof z.ZodError) {
88
30
  throw new Error(`Error in config file\n ${error.errors.map((err) => err.message).join('\n')}`)
89
31
  }
90
- // If the config file doesn't exist, use defaults by parsing an empty object
91
32
  if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
92
- return normalizedConfigSchema.parse({})
33
+ return configDefintion.parse({})
93
34
  }
35
+
94
36
  throw error
95
37
  }
96
38
  }
@@ -20,10 +20,9 @@ export interface NamedQueryResult {
20
20
  name: string
21
21
  /** result is a groq query */
22
22
  result: resolveExpressionReturnType
23
- /** type indicates whether this is a query or projection */
24
- type: 'query' | 'projection'
23
+
25
24
  /** location is the location of the query in the source */
26
- location?: {
25
+ location: {
27
26
  start?: {
28
27
  line: number
29
28
  column: number
@@ -38,7 +37,7 @@ export interface NamedQueryResult {
38
37
  }
39
38
 
40
39
  const TAGGED_TEMPLATE_ALLOW_LIST = ['groq']
41
- const FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery', 'defineProjection']
40
+ const FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']
42
41
 
43
42
  /**
44
43
  * resolveExpression takes a node and returns the resolved value of the expression.
@@ -11,12 +11,12 @@ import {getResolver} from './moduleResolver'
11
11
 
12
12
  const debug = createDebug('sanity:codegen:findQueries:debug')
13
13
 
14
- export type ResultQueries = {
14
+ type ResultQueries = {
15
15
  type: 'queries'
16
16
  filename: string
17
17
  queries: NamedQueryResult[]
18
18
  }
19
- export type ResultError = {
19
+ type ResultError = {
20
20
  type: 'error'
21
21
  error: Error
22
22
  filename: string