@sanity/codegen 5.8.0 → 5.9.0-watch-mode.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/actions/typegenGenerate.worker.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport path from 'node:path'\nimport {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\n\nimport {readSchema} from '../readSchema.js'\nimport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nimport {getResolver} from '../typescript/moduleResolver.js'\nimport {registerBabel} from '../typescript/registerBabel.js'\nimport {TypeGenerator} from '../typescript/typeGenerator.js'\nimport {TypegenGenerateTypesWorkerData, TypegenWorkerChannel} from './types.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nregisterBabel()\n\nasync function main({\n overloadClientMethods,\n schemaPath,\n searchPath,\n workDir,\n}: TypegenGenerateTypesWorkerData) {\n const report = WorkerChannelReporter.from<TypegenWorkerChannel>(parentPort)\n\n const fullPath = path.join(workDir, schemaPath)\n\n try {\n const schemaStats = await stat(fullPath)\n if (!schemaStats.isFile()) {\n throw new Error(`Schema path is not a file: ${schemaPath}`)\n }\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {\n // If the user has not provided a specific schema path (eg we're using the default), give some help\n const hint = schemaPath === './schema.json' ? ` - did you run \"sanity schema extract\"?` : ''\n throw new Error(`Schema file not found: ${fullPath}${hint}`, {cause: err})\n }\n throw err\n }\n\n const schema = await readSchema(fullPath)\n\n report.event.loadedSchema()\n\n const typeGenerator = new TypeGenerator()\n\n const {files, queries} = findQueriesInPath({\n path: searchPath,\n resolver: getResolver(workDir),\n })\n report.event.typegenStarted({expectedFileCount: files.length})\n\n const result = await typeGenerator.generateTypes({\n overloadClientMethods,\n queries,\n reporter: report,\n root: workDir,\n schema,\n schemaPath,\n })\n report.event.typegenComplete(result)\n}\n\nawait main(workerData)\n"],"names":["stat","path","isMainThread","parentPort","workerData","WorkerChannelReporter","readSchema","findQueriesInPath","getResolver","registerBabel","TypeGenerator","Error","main","overloadClientMethods","schemaPath","searchPath","workDir","report","from","fullPath","join","schemaStats","isFile","err","code","hint","cause","schema","event","loadedSchema","typeGenerator","files","queries","resolver","typegenStarted","expectedFileCount","length","result","generateTypes","reporter","root","typegenComplete"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,YAAY,EAAEC,UAAU,EAAEC,UAAU,QAAO,sBAAqB;AAExE,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,iBAAiB,QAAO,qCAAoC;AACpE,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAAQC,aAAa,QAAO,iCAAgC;AAG5D,IAAIR,gBAAgB,CAACC,YAAY;IAC/B,MAAM,IAAIQ,MAAM;AAClB;AAEAF;AAEA,eAAeG,KAAK,EAClBC,qBAAqB,EACrBC,UAAU,EACVC,UAAU,EACVC,OAAO,EACwB;IAC/B,MAAMC,SAASZ,sBAAsBa,IAAI,CAAuBf;IAEhE,MAAMgB,WAAWlB,KAAKmB,IAAI,CAACJ,SAASF;IAEpC,IAAI;QACF,MAAMO,cAAc,MAAMrB,KAAKmB;QAC/B,IAAI,CAACE,YAAYC,MAAM,IAAI;YACzB,MAAM,IAAIX,MAAM,CAAC,2BAA2B,EAAEG,YAAY;QAC5D;IACF,EAAE,OAAOS,KAAK;QACZ,IAAIA,eAAeZ,SAAS,UAAUY,OAAOA,IAAIC,IAAI,KAAK,UAAU;YAClE,mGAAmG;YACnG,MAAMC,OAAOX,eAAe,kBAAkB,CAAC,uCAAuC,CAAC,GAAG;YAC1F,MAAM,IAAIH,MAAM,CAAC,uBAAuB,EAAEQ,WAAWM,MAAM,EAAE;gBAACC,OAAOH;YAAG;QAC1E;QACA,MAAMA;IACR;IAEA,MAAMI,SAAS,MAAMrB,WAAWa;IAEhCF,OAAOW,KAAK,CAACC,YAAY;IAEzB,MAAMC,gBAAgB,IAAIpB;IAE1B,MAAM,EAACqB,KAAK,EAAEC,OAAO,EAAC,GAAGzB,kBAAkB;QACzCN,MAAMc;QACNkB,UAAUzB,YAAYQ;IACxB;IACAC,OAAOW,KAAK,CAACM,cAAc,CAAC;QAACC,mBAAmBJ,MAAMK,MAAM;IAAA;IAE5D,MAAMC,SAAS,MAAMP,cAAcQ,aAAa,CAAC;QAC/CzB;QACAmB;QACAO,UAAUtB;QACVuB,MAAMxB;QACNW;QACAb;IACF;IACAG,OAAOW,KAAK,CAACa,eAAe,CAACJ;AAC/B;AAEA,MAAMzB,KAAKR"}
1
+ {"version":3,"sources":["../../src/actions/typegenGenerate.worker.js"],"sourcesContent":["// src/actions/typegenGenerate.worker.ts\nimport { stat } from \"node:fs/promises\";\nimport { isAbsolute, join as join2 } from \"node:path\";\nimport { isMainThread, parentPort, workerData } from \"node:worker_threads\";\nimport { WorkerChannelReporter } from \"@sanity/worker-channels\";\n\n// src/readSchema.ts\nimport { readFile } from \"node:fs/promises\";\nasync function readSchema(path3) {\n const content = await readFile(path3, \"utf8\");\n return JSON.parse(content);\n}\n\n// src/typescript/findQueriesInPath.ts\nimport fs2 from \"node:fs/promises\";\nimport createDebug3 from \"debug\";\nimport glob from \"globby\";\n\n// src/getBabelConfig.ts\nimport { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nvar __dirname = dirname(fileURLToPath(import.meta.url));\nfunction findBabelConfig(path3) {\n const configPath = join(path3, \"babel.config.json\");\n if (existsSync(configPath)) {\n return configPath;\n }\n const parent = resolve(join(path3, \"..\"));\n if (parent && parent !== path3) {\n return findBabelConfig(parent);\n }\n throw new Error(\"Could not find `babel.config.json` in @sanity/codegen\");\n}\nfunction getBabelConfig(path3) {\n const configPath = findBabelConfig(path3 || __dirname);\n return { extends: configPath };\n}\n\n// src/typescript/findQueriesInSource.ts\nimport { createRequire } from \"node:module\";\nimport { traverse as traverse2 } from \"@babel/core\";\nimport * as babelTypes2 from \"@babel/types\";\n\n// src/typescript/expressionResolvers.ts\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { traverse } from \"@babel/core\";\nimport { Scope } from \"@babel/traverse\";\nimport * as babelTypes from \"@babel/types\";\nimport createDebug from \"debug\";\n\n// src/utils/formatPath.ts\nfunction formatPath(path3) {\n return path3.replaceAll(\"\\\\\", \"/\");\n}\n\n// src/typescript/parseSource.ts\nimport { parse } from \"@babel/core\";\nfunction parseSourceFile(_source, _filename, babelOptions) {\n let source = _source;\n let filename = _filename;\n if (filename.endsWith(\".astro\")) {\n filename += \".ts\";\n source = parseAstro(source);\n } else if (filename.endsWith(\".vue\")) {\n filename += \".ts\";\n source = parseVue(source);\n } else if (filename.endsWith(\".svelte\")) {\n filename += \".ts\";\n source = parseSvelte(source);\n }\n const result = parse(source, {\n ...babelOptions,\n filename\n });\n if (!result) {\n throw new Error(`Failed to parse ${filename}`);\n }\n return result;\n}\nfunction parseAstro(source) {\n const codeFences = source.match(/---\\r?\\n([\\s\\S]*?)\\r?\\n---/g);\n if (!codeFences) {\n return \"\";\n }\n return codeFences.map((codeFence) => {\n return codeFence.split(/\\r?\\n/).slice(1, -1).join(\"\\n\");\n }).join(\"\\n\");\n}\nfunction parseVue(source) {\n const scriptRegex = /<script(?:\\s+generic=[\"'][^\"']*[\"'])?[^>]*>([\\s\\S]*?)<\\/script>/g;\n const matches = matchAllPolyfill(source, scriptRegex);\n if (matches.length === 0) {\n return \"\";\n }\n return matches.map((match) => match[1]).join(\"\\n\");\n}\nfunction parseSvelte(source) {\n const scriptRegex = /<script[^>]*>([\\s\\S]*?)<\\/script>/g;\n const matches = matchAllPolyfill(source, scriptRegex);\n if (matches.length === 0) {\n return \"\";\n }\n return matches.map((match) => match[1]).join(\"\\n\");\n}\nfunction matchAllPolyfill(str, regex) {\n if (!regex.global) {\n throw new Error(\"matchAll polyfill requires a global regex (with /g flag)\");\n }\n const matches = [];\n let match;\n while ((match = regex.exec(str)) !== null) {\n matches.push(match);\n }\n return matches;\n}\n\n// src/typescript/expressionResolvers.ts\nvar debug = createDebug(\"sanity:codegen:findQueries:debug\");\nvar TAGGED_TEMPLATE_ALLOW_LIST = /* @__PURE__ */ new Set([\"groq\"]);\nvar FUNCTION_WRAPPER_ALLOW_LIST = /* @__PURE__ */ new Set([\"defineQuery\"]);\nfunction resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments = [],\n node,\n params = [],\n resolver,\n scope\n}) {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`\n );\n if (babelTypes.isTaggedTemplateExpression(node) && babelTypes.isIdentifier(node.tag) && TAGGED_TEMPLATE_ALLOW_LIST.has(node.tag.name)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.quasi,\n params,\n resolver,\n scope\n });\n }\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map(\n (expression) => resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: expression,\n params,\n resolver,\n scope\n })\n );\n return node.quasis.map((quasi, idx) => {\n return (quasi.value.cooked || \"\") + (resolvedExpressions[idx] || \"\");\n }).join(\"\");\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 return node.value.toString();\n }\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope\n });\n }\n 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 return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: init,\n resolver,\n scope\n });\n }\n if (babelTypes.isCallExpression(node) && babelTypes.isIdentifier(node.callee) && FUNCTION_WRAPPER_ALLOW_LIST.has(node.callee.name)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.arguments[0],\n params,\n resolver,\n scope\n });\n }\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope\n });\n }\n if (babelTypes.isArrowFunctionExpression(node) || babelTypes.isFunctionDeclaration(node) || babelTypes.isFunctionExpression(node)) {\n const newScope = new Scope(scope.path, scope);\n for (const [i, param] of params.entries()) {\n newScope.push({\n id: param,\n init: fnArguments[i]\n });\n }\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.body,\n params: node.params,\n resolver,\n scope: newScope\n });\n }\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.callee,\n resolver,\n scope\n });\n }\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({ babelConfig, file, filename, fnArguments, node, resolver, scope });\n }\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.right,\n params,\n resolver,\n scope\n });\n }\n if (babelTypes.isTSAsExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.expression,\n params,\n resolver,\n scope\n });\n }\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`\n );\n}\nfunction resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope\n}) {\n const paramIndex = params.findIndex(\n (param) => babelTypes.isIdentifier(param) && node.name === param.name || babelTypes.isAssignmentPattern(param) && babelTypes.isIdentifier(param.left) && node.name === param.left.name\n );\n let argument = fnArguments[paramIndex];\n if (!argument && paramIndex !== -1 && babelTypes.isAssignmentPattern(params[paramIndex])) {\n argument = params[paramIndex].right;\n }\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: argument,\n params,\n resolver,\n scope\n });\n }\n const binding = scope.getBinding(node.name);\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name;\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`\n );\n }\n }\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: binding.path.node,\n params,\n resolver,\n scope\n });\n }\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`\n );\n}\nfunction resolveCallExpression({\n babelConfig,\n file,\n filename,\n node,\n params,\n resolver,\n scope\n}) {\n const { callee } = node;\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments: node.arguments,\n node: callee,\n params,\n resolver,\n scope\n });\n}\nfunction resolveImportSpecifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n resolver\n}) {\n let importDeclaration2;\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) && specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration2 = n.node;\n break;\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration2 = n.node;\n }\n }\n }\n });\n if (!importDeclaration2) {\n throw new Error(`Could not find import declaration for ${node.local.name}`);\n }\n const importName = node.local.name;\n const importFileName = importDeclaration2.source.value;\n const importPath = importFileName.startsWith(\"./\") || importFileName.startsWith(\"../\") ? path.resolve(path.dirname(filename), importFileName) : importFileName;\n const resolvedFile = resolver(formatPath(importPath));\n const source = fs.readFileSync(resolvedFile);\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig);\n let newScope;\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 const binding = newScope.getBinding(importName);\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope: newScope\n });\n }\n let namedExport;\n let newImportName;\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === \"ExportNamedDeclaration\") {\n for (const specifier of p.node.specifiers) {\n if (specifier.type === \"ExportSpecifier\" && specifier.exported.type === \"Identifier\" && specifier.exported.name === importName) {\n namedExport = p.node;\n newImportName = specifier.exported.name;\n }\n }\n }\n }\n });\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName: newImportName,\n node: namedExport,\n resolver\n });\n }\n let result;\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === \"ExportAllDeclaration\") {\n try {\n result = resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName,\n node: p.node,\n resolver\n });\n } catch (e) {\n if (e.cause !== `noBinding:${importName}`) throw e;\n }\n }\n }\n });\n if (result) return result;\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`);\n}\nfunction resolveExportSpecifier({\n babelConfig,\n filename,\n fnArguments,\n importName,\n node,\n resolver\n}) {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`);\n }\n const importFileName = node.source.value;\n const importPath = path.resolve(path.dirname(filename), importFileName);\n const resolvedFile = resolver(formatPath(importPath));\n const source = fs.readFileSync(resolvedFile);\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig);\n let newScope;\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 const binding = newScope.getBinding(importName);\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope: newScope\n });\n }\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`, {\n cause: `noBinding:${importName}`\n });\n}\n\n// src/typescript/types.ts\nvar isRecord = (value) => (typeof value === \"object\" || typeof value === \"function\") && !!value;\nvar QueryExtractionError = class extends Error {\n filename;\n variable;\n constructor({ cause, filename, variable }) {\n super(\n `Error while extracting query ${variable ? `from variable '${variable.id.name}' ` : \"\"}in ${filename}: ${isRecord(cause) && typeof cause.message === \"string\" ? cause.message : \"Unknown error\"}`\n );\n this.name = \"QueryExtractionError\";\n this.cause = cause;\n this.variable = variable;\n this.filename = filename;\n }\n};\nvar QueryEvaluationError = class extends Error {\n filename;\n variable;\n constructor({ cause, filename, variable }) {\n super(\n `Error while evaluating query ${variable ? `from variable '${variable.id.name}' ` : \"\"}in ${filename}: ${isRecord(cause) && typeof cause.message === \"string\" ? cause.message : \"Unknown error\"}`\n );\n this.name = \"QueryEvaluationError\";\n this.cause = cause;\n this.variable = variable;\n this.filename = filename;\n }\n};\n\n// src/typescript/findQueriesInSource.ts\nvar require2 = createRequire(import.meta.url);\nvar groqTagName = \"groq\";\nvar defineQueryFunctionName = \"defineQuery\";\nvar groqModuleName = \"groq\";\nvar nextSanityModuleName = \"next-sanity\";\nvar sveltekitModuleName = \"@sanity/sveltekit\";\nvar ignoreValue = \"@sanity-typegen-ignore\";\nfunction findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require2.resolve) {\n const queries = [];\n const errors = [];\n const file = parseSourceFile(source, filename, babelConfig);\n traverse2(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(path3) {\n const { node, scope } = path3;\n const init = node.init;\n const isGroqTemplateTag = babelTypes2.isTaggedTemplateExpression(init) && babelTypes2.isIdentifier(init.tag) && init.tag.name === groqTagName;\n const isDefineQueryCall = babelTypes2.isCallExpression(init) && (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(sveltekitModuleName, defineQueryFunctionName, scope, init.callee));\n if (babelTypes2.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {\n if (declarationLeadingCommentContains(path3, ignoreValue)) {\n return;\n }\n const { end, id, start } = node;\n const variable = { id, ...start && { start }, ...end && { end } };\n try {\n const query = resolveExpression({\n babelConfig,\n file,\n filename,\n node: init,\n resolver,\n scope\n });\n queries.push({ filename, query, variable });\n } catch (cause) {\n errors.push(new QueryExtractionError({ cause, filename, variable }));\n }\n }\n }\n });\n return { errors, filename, queries };\n}\nfunction declarationLeadingCommentContains(path3, comment) {\n const variableDeclaration2 = path3.find((node) => node.isVariableDeclaration());\n if (!variableDeclaration2) return false;\n if (variableDeclaration2.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment\n )) {\n return true;\n }\n if (variableDeclaration2.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment\n )) {\n return true;\n }\n return false;\n}\nfunction isImportFrom(moduleName, importName, scope, node) {\n if (babelTypes2.isIdentifier(node)) {\n const binding = scope.getBinding(node.name);\n if (!binding) {\n return false;\n }\n const { path: path3 } = binding;\n if (babelTypes2.isImportSpecifier(path3.node)) {\n return path3.node.importKind === \"value\" && path3.parentPath && babelTypes2.isImportDeclaration(path3.parentPath.node) && path3.parentPath.node.source.value === moduleName && babelTypes2.isIdentifier(path3.node.imported) && path3.node.imported.name === importName;\n }\n if (babelTypes2.isVariableDeclarator(path3.node)) {\n const { init } = path3.node;\n return babelTypes2.isCallExpression(init) && babelTypes2.isIdentifier(init.callee) && init.callee.name === \"require\" && babelTypes2.isStringLiteral(init.arguments[0]) && init.arguments[0].value === moduleName;\n }\n }\n if (babelTypes2.isMemberExpression(node)) {\n const { object, property } = node;\n if (!babelTypes2.isIdentifier(object)) {\n return false;\n }\n const binding = scope.getBinding(object.name);\n if (!binding) {\n return false;\n }\n const { path: path3 } = binding;\n return babelTypes2.isIdentifier(object) && babelTypes2.isIdentifier(property) && property.name === importName && babelTypes2.isImportNamespaceSpecifier(path3.node) && path3.parentPath && babelTypes2.isImportDeclaration(path3.parentPath.node) && path3.parentPath.node.source.value === moduleName;\n }\n return false;\n}\n\n// src/typescript/helpers.ts\nimport path2 from \"node:path\";\nimport { CodeGenerator } from \"@babel/generator\";\nimport * as t2 from \"@babel/types\";\n\n// src/typescript/constants.ts\nimport * as t from \"@babel/types\";\nvar INTERNAL_REFERENCE_SYMBOL = t.identifier(\"internalGroqTypeReferenceTo\");\nvar ALL_SANITY_SCHEMA_TYPES = t.identifier(\"AllSanitySchemaTypes\");\nvar SANITY_QUERIES = t.identifier(\"SanityQueries\");\nvar ARRAY_OF = t.identifier(\"ArrayOf\");\nvar RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set();\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name);\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name);\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name);\nRESERVED_IDENTIFIERS.add(ARRAY_OF.name);\n\n// src/typescript/helpers.ts\nfunction normalizePrintablePath(root, filename) {\n const resolved = path2.resolve(root, filename);\n return formatPath(path2.relative(root, resolved));\n}\nfunction normalizeGlobPattern(pattern) {\n if (Array.isArray(pattern)) {\n return pattern.map((p) => formatPath(p));\n }\n return formatPath(pattern);\n}\nfunction sanitizeIdentifier(input) {\n return `${input.replace(/^\\d/, \"_\").replaceAll(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`;\n}\nfunction isIdentifierName(input) {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(input);\n}\nfunction normalizeIdentifier(input) {\n const sanitized = sanitizeIdentifier(input);\n return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`;\n}\nfunction getUniqueIdentifierForName(name, currentIdentifiers) {\n const desiredName = normalizeIdentifier(name);\n let resultingName = desiredName;\n let index = 2;\n while (currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName)) {\n resultingName = `${desiredName}_${index}`;\n index++;\n }\n return t2.identifier(resultingName);\n}\nfunction computeOnce(fn) {\n const ref = { computed: false, current: void 0 };\n return function() {\n if (ref.computed) return ref.current;\n ref.current = fn();\n ref.computed = true;\n return ref.current;\n };\n}\nfunction weakMapMemo(fn) {\n const cache = /* @__PURE__ */ new WeakMap();\n const wrapped = function(arg) {\n if (cache.has(arg)) return cache.get(arg);\n const result = fn(arg);\n cache.set(arg, result);\n return result;\n };\n return wrapped;\n}\nfunction generateCode(node) {\n return `${new CodeGenerator(node).generate().code.trim()}\n\n`;\n}\nfunction getFilterArrayUnionType(typeNode, predicate) {\n if (typeNode.of.type !== \"union\") {\n return typeNode;\n }\n return {\n ...typeNode,\n of: {\n ...typeNode.of,\n of: typeNode.of.of.filter((unionTypeNode) => predicate(unionTypeNode))\n }\n };\n}\n\n// src/typescript/moduleResolver.ts\nimport { createRequire as createRequire2 } from \"node:module\";\nimport createDebug2 from \"debug\";\nimport { createMatchPath, loadConfig as loadTSConfig } from \"tsconfig-paths\";\nvar require3 = createRequire2(import.meta.url);\nvar debug2 = createDebug2(\"sanity:codegen:moduleResolver\");\nfunction getResolver(cwd) {\n const tsConfig = loadTSConfig(cwd);\n if (tsConfig.resultType === \"failed\") {\n debug2(\"Could not load tsconfig, using default resolver: %s\", tsConfig.message);\n return require3.resolve;\n }\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll\n );\n const resolve2 = function(request, options) {\n const found = matchPath(request);\n if (found !== void 0) {\n return require3.resolve(found, options);\n }\n return require3.resolve(request, options);\n };\n resolve2.paths = (request) => {\n return require3.resolve.paths(request);\n };\n return resolve2;\n}\n\n// src/typescript/findQueriesInPath.ts\nvar debug3 = createDebug3(\"sanity:codegen:findQueries:debug\");\nfunction findQueriesInPath({\n babelOptions = getBabelConfig(),\n path: path3,\n resolver = getResolver()\n}) {\n const queryNames = /* @__PURE__ */ new Set();\n debug3(`Globing ${path3}`);\n const normalizedPath = normalizeGlobPattern(path3);\n const files = glob.sync(normalizedPath, {\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n // we never want to look in node_modules\n onlyFiles: true\n }).toSorted();\n async function* getQueries() {\n for (const filename of files) {\n if (typeof filename !== \"string\") {\n continue;\n }\n debug3(`Found file \"${filename}\"`);\n try {\n const source = await fs2.readFile(filename, \"utf8\");\n const pluckedModuleResult = findQueriesInSource(source, filename, babelOptions, resolver);\n for (const { variable } of pluckedModuleResult.queries) {\n if (queryNames.has(variable.id.name)) {\n throw new Error(\n `Duplicate query name found: \"${variable.id.name}\". Query names must be unique across all files.`\n );\n }\n queryNames.add(variable.id.name);\n }\n yield pluckedModuleResult;\n } catch (cause) {\n debug3(`Error in file \"${filename}\"`, cause);\n yield {\n errors: [new QueryExtractionError({ cause, filename })],\n filename,\n queries: []\n };\n }\n }\n }\n return { files, queries: getQueries() };\n}\n\n// src/typescript/registerBabel.ts\nimport register from \"@babel/register\";\nfunction registerBabel(babelOptions) {\n const options = babelOptions || getBabelConfig();\n register({ ...options, extensions: [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"] });\n}\n\n// src/typescript/typeGenerator.ts\nimport process from \"node:process\";\nimport * as t4 from \"@babel/types\";\nimport { createSelector } from \"reselect\";\n\n// src/casing.ts\nfunction resultSuffix(variableName) {\n if (!variableName) return \"result\";\n const isUpperSnake = /^[A-Z0-9_]+$/.test(variableName);\n const isSnake = /^[a-z0-9_]+$/.test(variableName) && variableName.includes(\"_\");\n const isCamel = /^[a-z][A-Za-z0-9]*$/.test(variableName);\n if (isCamel) {\n return `${variableName}Result`;\n }\n if (isUpperSnake) {\n return `${variableName}_RESULT`;\n }\n if (isSnake) {\n return `${variableName}_result`;\n }\n const cleaned = variableName.replaceAll(/[^A-Za-z0-9]/g, \"\");\n return `${cleaned}Result`;\n}\n\n// src/typescript/schemaTypeGenerator.ts\nimport * as t3 from \"@babel/types\";\nimport {\n typeEvaluate\n} from \"groq-js\";\n\n// src/safeParseQuery.ts\nimport { parse as parse2 } from \"groq-js\";\nfunction safeParseQuery(query) {\n const params = {};\n for (const param of extractSliceParams(query)) {\n params[param] = 0;\n }\n return parse2(query, { params });\n}\nfunction* extractSliceParams(query) {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g;\n const matches = query.matchAll(sliceRegex);\n if (!matches) {\n return;\n }\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\n// src/typescript/schemaTypeGenerator.ts\nvar SchemaTypeGenerator = class {\n schema;\n evaluateQuery = weakMapMemo(\n // eslint-disable-next-line unicorn/consistent-function-scoping\n ({ query }) => {\n const ast = safeParseQuery(query);\n const typeNode = typeEvaluate(ast, this.schema);\n const tsType = this.generateTsType(typeNode);\n const stats = walkAndCountQueryTypeNodeStats(typeNode);\n return { stats, tsType };\n }\n );\n identifiers = /* @__PURE__ */ new Map();\n tsTypes = /* @__PURE__ */ new Map();\n constructor(schema) {\n this.schema = schema;\n const uniqueTypeNames = /* @__PURE__ */ new Set();\n for (const type of schema) {\n if (uniqueTypeNames.has(type.name)) {\n throw new Error(\n `Duplicate type name \"${type.name}\" in schema. Type names must be unique within the same schema.`\n );\n }\n uniqueTypeNames.add(type.name);\n }\n for (const type of schema) {\n const currentIdentifierNames = new Set([...this.identifiers.values()].map((id) => id.name));\n const uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames);\n this.identifiers.set(type.name, uniqueIdentifier);\n }\n for (const type of schema) {\n this.tsTypes.set(type.name, this.generateTsType(type));\n }\n }\n getType(typeName) {\n const tsType = this.tsTypes.get(typeName);\n const id = this.identifiers.get(typeName);\n if (tsType && id) return { id, tsType };\n return void 0;\n }\n hasType(typeName) {\n return this.tsTypes.has(typeName);\n }\n *[Symbol.iterator]() {\n for (const { name } of this.schema) {\n yield { name, ...this.getType(name) };\n }\n }\n typeNames() {\n return this.schema.map((schemaType) => schemaType.name);\n }\n /**\n * Helper function used to generate TS types for arrays of inline types, or arrays of inline types\n * wrapped in the ArrayOf wrapper that adds _key prop\n */\n generateArrayOfTsType(typeNode) {\n const typeNodes = this.generateTsType(typeNode.of);\n return t3.tsTypeReference(ARRAY_OF, t3.tsTypeParameterInstantiation([typeNodes]));\n }\n // Helper function used to generate TS types for array type nodes.\n generateArrayTsType(typeNode) {\n if (typeNode.of.type === \"inline\") {\n return this.generateArrayOfTsType(typeNode);\n }\n if (typeNode.of.type !== \"union\") {\n const typeNodes = this.generateTsType(typeNode.of);\n return t3.tsTypeReference(t3.identifier(\"Array\"), t3.tsTypeParameterInstantiation([typeNodes]));\n }\n if (typeNode.of.of.every((unionTypeNode) => unionTypeNode.type !== \"inline\")) {\n const typeNodes = this.generateTsType(typeNode.of);\n return t3.tsTypeReference(t3.identifier(\"Array\"), t3.tsTypeParameterInstantiation([typeNodes]));\n }\n if (typeNode.of.of.every((unionMember) => unionMember.type === \"inline\")) {\n return this.generateArrayOfTsType(typeNode);\n }\n const arrayOfNonInline = getFilterArrayUnionType(typeNode, (member) => member.type !== \"inline\");\n const arrayOfInline = getFilterArrayUnionType(typeNode, (member) => member.type === \"inline\");\n return t3.tsUnionType([\n this.generateArrayTsType(arrayOfNonInline),\n this.generateArrayTsType(arrayOfInline)\n ]);\n }\n // Helper function used to generate TS types for document type nodes.\n generateDocumentTsType(document) {\n const props = Object.entries(document.attributes).map(\n ([key, node]) => this.generateTsObjectProperty(key, node)\n );\n return t3.tsTypeLiteral(props);\n }\n generateInlineTsType(typeNode) {\n const id = this.identifiers.get(typeNode.name);\n if (!id) {\n return t3.addComment(\n t3.tsUnknownKeyword(),\n \"trailing\",\n ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n true\n );\n }\n return t3.tsTypeReference(id);\n }\n // Helper function used to generate TS types for object type nodes.\n generateObjectTsType(typeNode) {\n const props = [];\n for (const [key, attribute] of Object.entries(typeNode.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute));\n }\n const rest = typeNode.rest;\n if (rest) {\n switch (rest.type) {\n case \"inline\": {\n const resolved = this.generateInlineTsType(rest);\n if (t3.isTSUnknownKeyword(resolved)) return resolved;\n return t3.tsIntersectionType([t3.tsTypeLiteral(props), resolved]);\n }\n case \"object\": {\n for (const [key, attribute] of Object.entries(rest.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute));\n }\n break;\n }\n case \"unknown\": {\n return t3.tsUnknownKeyword();\n }\n default: {\n throw new Error(`Type \"${rest.type}\" not found in schema`);\n }\n }\n }\n if (typeNode.dereferencesTo) {\n const derefType = Object.assign(\n t3.tsPropertySignature(\n INTERNAL_REFERENCE_SYMBOL,\n t3.tsTypeAnnotation(t3.tsLiteralType(t3.stringLiteral(typeNode.dereferencesTo)))\n ),\n { computed: true, optional: true }\n );\n props.push(derefType);\n }\n return t3.tsTypeLiteral(props);\n }\n // Helper function used to generate TS types for object properties.\n generateTsObjectProperty(key, attribute) {\n const type = this.generateTsType(attribute.value);\n const keyNode = isIdentifierName(key) ? t3.identifier(key) : t3.stringLiteral(key);\n const propertySignature = t3.tsPropertySignature(keyNode, t3.tsTypeAnnotation(type));\n propertySignature.optional = attribute.optional;\n return propertySignature;\n }\n generateTsType(typeNode) {\n switch (typeNode.type) {\n case \"array\": {\n return this.generateArrayTsType(typeNode);\n }\n case \"boolean\": {\n if (typeNode.value !== void 0) {\n return t3.tsLiteralType(t3.booleanLiteral(typeNode.value));\n }\n return t3.tsBooleanKeyword();\n }\n case \"document\": {\n return this.generateDocumentTsType(typeNode);\n }\n case \"inline\": {\n return this.generateInlineTsType(typeNode);\n }\n case \"null\": {\n return t3.tsNullKeyword();\n }\n case \"number\": {\n if (typeNode.value !== void 0) {\n return t3.tsLiteralType(t3.numericLiteral(typeNode.value));\n }\n return t3.tsNumberKeyword();\n }\n case \"object\": {\n return this.generateObjectTsType(typeNode);\n }\n case \"string\": {\n if (typeNode.value !== void 0) {\n return t3.tsLiteralType(t3.stringLiteral(typeNode.value));\n }\n return t3.tsStringKeyword();\n }\n case \"type\": {\n return this.generateTsType(typeNode.value);\n }\n case \"union\": {\n return this.generateUnionTsType(typeNode);\n }\n case \"unknown\": {\n return t3.tsUnknownKeyword();\n }\n default: {\n throw new Error(\n `Encountered unsupported node type \"${// @ts-expect-error This should never happen\n typeNode.type}\" while generating schema types`\n );\n }\n }\n }\n // Helper function used to generate TS types for union type nodes.\n generateUnionTsType(typeNode) {\n if (typeNode.of.length === 0) return t3.tsNeverKeyword();\n if (typeNode.of.length === 1) return this.generateTsType(typeNode.of[0]);\n return t3.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)));\n }\n};\nfunction walkAndCountQueryTypeNodeStats(typeNode) {\n switch (typeNode.type) {\n case \"array\": {\n const acc = walkAndCountQueryTypeNodeStats(typeNode.of);\n acc.allTypes += 1;\n return acc;\n }\n case \"object\": {\n if (typeNode.rest && typeNode.rest.type === \"unknown\") {\n return { allTypes: 2, emptyUnions: 0, unknownTypes: 1 };\n }\n const restStats = typeNode.rest ? walkAndCountQueryTypeNodeStats(typeNode.rest) : { allTypes: 0, emptyUnions: 0, unknownTypes: 0 };\n restStats.allTypes += 1;\n const attrs = Object.values(typeNode.attributes);\n let acc = restStats;\n for (const attribute of attrs) {\n const { allTypes, emptyUnions, unknownTypes } = walkAndCountQueryTypeNodeStats(\n attribute.value\n );\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes\n };\n }\n return acc;\n }\n case \"union\": {\n if (typeNode.of.length === 0) {\n return { allTypes: 1, emptyUnions: 1, unknownTypes: 0 };\n }\n let acc = { allTypes: 1, emptyUnions: 0, unknownTypes: 0 };\n for (const type of typeNode.of) {\n const { allTypes, emptyUnions, unknownTypes } = walkAndCountQueryTypeNodeStats(type);\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes\n };\n }\n return acc;\n }\n case \"unknown\": {\n return { allTypes: 1, emptyUnions: 0, unknownTypes: 1 };\n }\n default: {\n return { allTypes: 1, emptyUnions: 0, unknownTypes: 0 };\n }\n }\n}\n\n// src/typescript/typeGenerator.ts\nvar TypeGenerator = class _TypeGenerator {\n getSchemaTypeGenerator = createSelector(\n [(options) => options.schema],\n (schema) => new SchemaTypeGenerator(schema)\n );\n getSchemaTypeDeclarations = createSelector(\n [\n (options) => options.root,\n (options) => options.schemaPath,\n this.getSchemaTypeGenerator\n ],\n (root = process.cwd(), schemaPath, schema) => [...schema].map(({ id, name, tsType }, index) => {\n const typeAlias = t4.tsTypeAliasDeclaration(id, null, tsType);\n let ast = t4.exportNamedDeclaration(typeAlias);\n if (index === 0 && schemaPath) {\n ast = t4.addComments(ast, \"leading\", [\n { type: \"CommentLine\", value: ` Source: ${normalizePrintablePath(root, schemaPath)}` }\n ]);\n }\n const code = generateCode(ast);\n return { ast, code, id, name, tsType };\n })\n );\n getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t4.exportNamedDeclaration(\n t4.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0 ? t4.tsUnionType(schemaTypes.map(({ id }) => t4.tsTypeReference(id))) : t4.tsNeverKeyword()\n )\n );\n const code = generateCode(ast);\n return { ast, code, id: ALL_SANITY_SCHEMA_TYPES };\n }\n );\n getArrayOfDeclaration = computeOnce(() => {\n const typeParam = t4.tsTypeParameter(null, null, \"T\");\n const intersectionType = t4.tsIntersectionType([\n t4.tsTypeReference(t4.identifier(\"T\")),\n t4.tsTypeLiteral([\n t4.tsPropertySignature(t4.identifier(\"_key\"), t4.tsTypeAnnotation(t4.tsStringKeyword()))\n ])\n ]);\n const arrayType = t4.tsTypeReference(\n t4.identifier(\"Array\"),\n t4.tsTypeParameterInstantiation([intersectionType])\n );\n const ast = t4.tsTypeAliasDeclaration(\n ARRAY_OF,\n t4.tsTypeParameterDeclaration([typeParam]),\n arrayType\n );\n const code = generateCode(ast);\n return { ast, code, id: ARRAY_OF };\n });\n getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t4.tsTypeOperator(t4.tsSymbolKeyword(), \"unique\");\n const id = INTERNAL_REFERENCE_SYMBOL;\n id.typeAnnotation = t4.tsTypeAnnotation(typeOperator);\n const declaration = t4.variableDeclaration(\"const\", [t4.variableDeclarator(id)]);\n declaration.declare = true;\n const ast = t4.exportNamedDeclaration(declaration);\n const code = generateCode(ast);\n return { ast, code, id };\n });\n static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator\n }) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end();\n return [];\n }\n const currentIdentifiers = new Set(schemaTypeDeclarations.map(({ id }) => id.name));\n const evaluatedModuleResults = [];\n for await (const { filename, ...extractedModule } of extractedModules) {\n const queries = [];\n const errors = [...extractedModule.errors];\n for (const extractedQuery of extractedModule.queries) {\n const { variable } = extractedQuery;\n try {\n const { stats, tsType } = schemaTypeGenerator.evaluateQuery(extractedQuery);\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers);\n const typeAlias = t4.tsTypeAliasDeclaration(id, null, tsType);\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, \"\").trim();\n const ast = t4.addComments(t4.exportNamedDeclaration(typeAlias), \"leading\", [\n { type: \"CommentLine\", value: ` Source: ${normalizePrintablePath(root, filename)}` },\n { type: \"CommentLine\", value: ` Variable: ${variable.id.name}` },\n { type: \"CommentLine\", value: ` Query: ${trimmedQuery}` }\n ]);\n const evaluatedQueryResult = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery\n };\n currentIdentifiers.add(id.name);\n queries.push(evaluatedQueryResult);\n } catch (cause) {\n errors.push(new QueryEvaluationError({ cause, filename, variable }));\n }\n }\n const evaluatedModule = {\n errors,\n filename,\n queries\n };\n report?.stream.evaluatedModules.emit(evaluatedModule);\n evaluatedModuleResults.push(evaluatedModule);\n }\n report?.stream.evaluatedModules.end();\n return evaluatedModuleResults;\n }\n static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true\n }) {\n if (!overloadClientMethods) return { ast: t4.program([]), code: \"\" };\n const queries = evaluatedModules.flatMap((module) => module.queries);\n if (queries.length === 0) return { ast: t4.program([]), code: \"\" };\n const typesByQuerystring = {};\n for (const { id, query } of queries) {\n typesByQuerystring[query] ??= [];\n typesByQuerystring[query].push(id.name);\n }\n const queryReturnInterface = t4.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t4.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t4.tsPropertySignature(\n t4.stringLiteral(query),\n t4.tsTypeAnnotation(\n types.length > 0 ? t4.tsUnionType(types.map((type) => t4.tsTypeReference(t4.identifier(type)))) : t4.tsNeverKeyword()\n )\n );\n })\n )\n );\n const declareModule2 = t4.declareModule(\n t4.stringLiteral(\"@sanity/client\"),\n t4.blockStatement([queryReturnInterface])\n );\n const clientImport = t4.addComments(\n t4.importDeclaration([], t4.stringLiteral(\"@sanity/client\")),\n \"leading\",\n [{ type: \"CommentLine\", value: \" Query TypeMap\" }]\n );\n const ast = t4.program([clientImport, declareModule2]);\n const code = generateCode(ast);\n return { ast, code };\n }\n async generateTypes(options) {\n const { reporter: report } = options;\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration();\n const arrayOfDeclaration = this.getArrayOfDeclaration();\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options);\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options);\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations\n });\n const program2 = t4.program([]);\n let code = \"\";\n for (const declaration of schemaTypeDeclarations) {\n program2.body.push(declaration.ast);\n code += declaration.code;\n }\n program2.body.push(allSanitySchemaTypesDeclaration.ast);\n code += allSanitySchemaTypesDeclaration.code;\n program2.body.push(internalReferenceSymbol.ast);\n code += internalReferenceSymbol.code;\n program2.body.push(arrayOfDeclaration.ast);\n code += arrayOfDeclaration.code;\n const evaluatedModules = await _TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator: this.getSchemaTypeGenerator(options)\n });\n for (const { queries } of evaluatedModules) {\n for (const query of queries) {\n program2.body.push(query.ast);\n code += query.code;\n }\n }\n const queryMapDeclaration = await _TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules\n });\n program2.body.push(...queryMapDeclaration.ast.body);\n code += queryMapDeclaration.code;\n report?.event.generatedQueryTypes({ queryMapDeclaration });\n return { ast: program2, code };\n }\n};\n\n// src/actions/typegenGenerate.worker.ts\nif (isMainThread || !parentPort) {\n throw new Error(\"This module must be run as a worker thread\");\n}\nregisterBabel();\nasync function main({\n overloadClientMethods,\n schemaPath,\n searchPath,\n workDir\n}) {\n const report = WorkerChannelReporter.from(parentPort);\n const fullPath = isAbsolute(schemaPath) ? schemaPath : join2(workDir, schemaPath);\n try {\n const schemaStats = await stat(fullPath);\n if (!schemaStats.isFile()) {\n throw new Error(`Schema path is not a file: ${schemaPath}`);\n }\n } catch (err) {\n if (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n const hint = schemaPath === \"./schema.json\" ? ` - did you run \"sanity schema extract\"?` : \"\";\n throw new Error(`Schema file not found: ${fullPath}${hint}`, { cause: err });\n }\n throw err;\n }\n const schema = await readSchema(fullPath);\n report.event.loadedSchema();\n const typeGenerator = new TypeGenerator();\n const { files, queries } = findQueriesInPath({\n path: searchPath,\n resolver: getResolver(workDir)\n });\n report.event.typegenStarted({ expectedFileCount: files.length });\n const result = await typeGenerator.generateTypes({\n overloadClientMethods,\n queries,\n reporter: report,\n root: workDir,\n schema,\n schemaPath\n });\n report.event.typegenComplete(result);\n}\nawait main(workerData);\n"],"names":["stat","isAbsolute","join","join2","isMainThread","parentPort","workerData","WorkerChannelReporter","readFile","readSchema","path3","content","JSON","parse","fs2","createDebug3","glob","existsSync","dirname","resolve","fileURLToPath","__dirname","url","findBabelConfig","configPath","parent","Error","getBabelConfig","extends","createRequire","traverse","traverse2","babelTypes2","fs","path","Scope","babelTypes","createDebug","formatPath","replaceAll","parseSourceFile","_source","_filename","babelOptions","source","filename","endsWith","parseAstro","parseVue","parseSvelte","result","codeFences","match","map","codeFence","split","slice","scriptRegex","matches","matchAllPolyfill","length","str","regex","global","exec","push","debug","TAGGED_TEMPLATE_ALLOW_LIST","Set","FUNCTION_WRAPPER_ALLOW_LIST","resolveExpression","babelConfig","file","fnArguments","node","params","resolver","scope","type","loc","start","line","column","isTaggedTemplateExpression","isIdentifier","tag","has","name","quasi","isTemplateLiteral","resolvedExpressions","expressions","expression","quasis","idx","value","cooked","isLiteral","toString","resolveIdentifier","isVariableDeclarator","init","isAssignmentPattern","id","right","isCallExpression","callee","arguments","resolveCallExpression","isArrowFunctionExpression","isFunctionDeclaration","isFunctionExpression","newScope","i","param","entries","body","isNewExpression","isImportDefaultSpecifier","isImportSpecifier","resolveImportSpecifier","isTSAsExpression","paramIndex","findIndex","left","argument","binding","getBinding","isSame","importDeclaration2","ImportDeclaration","n","isImportDeclaration","specifier","specifiers","local","identifierName","importName","importFileName","importPath","startsWith","resolvedFile","readFileSync","tree","Program","p","namedExport","newImportName","ExportDeclaration","exported","resolveExportSpecifier","e","cause","isRecord","QueryExtractionError","variable","message","QueryEvaluationError","require2","groqTagName","defineQueryFunctionName","groqModuleName","nextSanityModuleName","sveltekitModuleName","ignoreValue","findQueriesInSource","queries","errors","VariableDeclarator","isGroqTemplateTag","isDefineQueryCall","isImportFrom","declarationLeadingCommentContains","end","query","comment","variableDeclaration2","find","isVariableDeclaration","leadingComments","commentItem","trim","moduleName","importKind","parentPath","imported","isStringLiteral","isMemberExpression","object","property","isImportNamespaceSpecifier","path2","CodeGenerator","t2","t","INTERNAL_REFERENCE_SYMBOL","identifier","ALL_SANITY_SCHEMA_TYPES","SANITY_QUERIES","ARRAY_OF","RESERVED_IDENTIFIERS","add","normalizePrintablePath","root","resolved","relative","normalizeGlobPattern","pattern","Array","isArray","sanitizeIdentifier","input","replace","_","char","toUpperCase","isIdentifierName","test","normalizeIdentifier","sanitized","charAt","getUniqueIdentifierForName","currentIdentifiers","desiredName","resultingName","index","computeOnce","fn","ref","computed","current","weakMapMemo","cache","WeakMap","wrapped","arg","get","set","generateCode","generate","code","getFilterArrayUnionType","typeNode","predicate","of","filter","unionTypeNode","createRequire2","createDebug2","createMatchPath","loadConfig","loadTSConfig","require3","debug2","getResolver","cwd","tsConfig","resultType","matchPath","absoluteBaseUrl","paths","mainFields","addMatchAll","resolve2","request","options","found","debug3","findQueriesInPath","queryNames","normalizedPath","files","sync","absolute","ignore","onlyFiles","toSorted","getQueries","pluckedModuleResult","register","registerBabel","extensions","process","t4","createSelector","resultSuffix","variableName","isUpperSnake","isSnake","includes","isCamel","cleaned","t3","typeEvaluate","parse2","safeParseQuery","extractSliceParams","sliceRegex","matchAll","SchemaTypeGenerator","schema","evaluateQuery","ast","tsType","generateTsType","stats","walkAndCountQueryTypeNodeStats","identifiers","Map","tsTypes","uniqueTypeNames","currentIdentifierNames","values","uniqueIdentifier","getType","typeName","hasType","Symbol","iterator","typeNames","schemaType","generateArrayOfTsType","typeNodes","tsTypeReference","tsTypeParameterInstantiation","generateArrayTsType","every","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","generateDocumentTsType","document","props","Object","attributes","key","generateTsObjectProperty","tsTypeLiteral","generateInlineTsType","addComment","tsUnknownKeyword","generateObjectTsType","attribute","rest","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","tsLiteralType","stringLiteral","optional","keyNode","propertySignature","booleanLiteral","tsBooleanKeyword","tsNullKeyword","numericLiteral","tsNumberKeyword","tsStringKeyword","generateUnionTsType","tsNeverKeyword","acc","allTypes","emptyUnions","unknownTypes","restStats","attrs","TypeGenerator","_TypeGenerator","getSchemaTypeGenerator","getSchemaTypeDeclarations","schemaPath","typeAlias","tsTypeAliasDeclaration","exportNamedDeclaration","addComments","getAllSanitySchemaTypesDeclaration","schemaTypes","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","arrayType","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","evaluatedModuleResults","extractedModule","extractedQuery","trimmedQuery","evaluatedQueryResult","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","types","declareModule2","declareModule","blockStatement","clientImport","importDeclaration","generateTypes","internalReferenceSymbol","arrayOfDeclaration","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","program2","queryMapDeclaration","generatedQueryTypes","main","searchPath","workDir","from","fullPath","schemaStats","isFile","err","hint","loadedSchema","typeGenerator","typegenStarted","expectedFileCount","typegenComplete"],"mappings":"AAAA,wCAAwC;AACxC,SAASA,IAAI,QAAQ,mBAAmB;AACxC,SAASC,UAAU,EAAEC,QAAQC,KAAK,QAAQ,YAAY;AACtD,SAASC,YAAY,EAAEC,UAAU,EAAEC,UAAU,QAAQ,sBAAsB;AAC3E,SAASC,qBAAqB,QAAQ,0BAA0B;AAEhE,oBAAoB;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M,EAAE;gBAAErS,OAAOoS;YAAI;QAC5E;QACA,MAAMA;IACR;IACA,MAAMhJ,SAAS,MAAMnS,WAAWgb;IAChCxC,OAAO+B,KAAK,CAACc,YAAY;IACzB,MAAMC,gBAAgB,IAAI3E;IAC1B,MAAM,EAAErG,KAAK,EAAEzG,OAAO,EAAE,GAAGsG,kBAAkB;QAC3C1O,MAAMoZ;QACN1W,UAAUkL,YAAYyL;IACxB;IACAtC,OAAO+B,KAAK,CAACgB,cAAc,CAAC;QAAEC,mBAAmBlL,MAAMnN,MAAM;IAAC;IAC9D,MAAMV,SAAS,MAAM6Y,cAAcnB,aAAa,CAAC;QAC/Cd;QACAxP;QACA0O,UAAUC;QACVtM,MAAM4O;QACN3I;QACA4E;IACF;IACAyB,OAAO+B,KAAK,CAACkB,eAAe,CAAChZ;AAC/B;AACA,MAAMmY,KAAK/a"}
@@ -1,7 +1,9 @@
1
- import { debug, error } from 'node:console';
1
+ import { error, log } from 'node:console';
2
2
  import { isAbsolute, join, relative } from 'node:path';
3
+ import { chalk } from '@sanity/cli-core/ux';
3
4
  import chokidar from 'chokidar';
4
5
  import { debounce, mean } from 'lodash-es';
6
+ import { prepareConfig } from '../utils/config.js';
5
7
  import { runTypegenGenerate } from './typegenGenerate.js';
6
8
  const IGNORED_PATTERNS = [
7
9
  '**/node_modules/**',
@@ -48,7 +50,7 @@ const IGNORED_PATTERNS = [
48
50
  * Implements debouncing and concurrency control to prevent multiple generations.
49
51
  */ export function runTypegenWatcher(options) {
50
52
  const { config, workDir } = options;
51
- const { path, schema } = config;
53
+ const { path, schema } = prepareConfig(config);
52
54
  const stats = {
53
55
  failedCount: 0,
54
56
  startTime: Date.now(),
@@ -56,9 +58,13 @@ const IGNORED_PATTERNS = [
56
58
  };
57
59
  const { runGeneration } = createTypegenRunner(async ()=>{
58
60
  try {
59
- const { duration } = await runTypegenGenerate(options);
61
+ const { duration } = await runTypegenGenerate({
62
+ ...options
63
+ });
60
64
  stats.successfulDurations.push(duration);
61
- } catch {
65
+ } catch (err) {
66
+ const errorMessage = err instanceof Error ? err.message : err;
67
+ error(` ${chalk.red('›')} ${errorMessage}`);
62
68
  stats.failedCount++;
63
69
  }
64
70
  });
@@ -85,7 +91,7 @@ const IGNORED_PATTERNS = [
85
91
  watcher.on('all', (event, filePath)=>{
86
92
  const timestamp = new Date().toLocaleTimeString();
87
93
  const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath;
88
- debug(`[${timestamp}] ${event}: ${relativePath}`);
94
+ log(`[${timestamp}] ${event}: ${relativePath}`);
89
95
  debouncedGenerate();
90
96
  });
91
97
  watcher.on('error', (err)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {debug, error} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\n\nimport chokidar, {FSWatcher} from 'chokidar'\nimport {debounce, mean} from 'lodash-es'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {runTypegenGenerate} from './typegenGenerate.js'\nimport {type RunTypegenOptions} from './types.js'\n\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\n/** State for tracking generation status */\nexport interface WatchState {\n isGenerating: boolean\n pendingGeneration: boolean\n}\n\n/** Return type for createTypegenRunner */\ninterface TypegenRunner {\n runGeneration: () => Promise<void>\n state: WatchState\n}\n\ntype WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {step: 'stopped'}>, 'step'>\n\n/**\n * Creates a typegen runner with concurrency control.\n * If generation is already running, queues one more generation to run after completion.\n * Multiple queued requests are coalesced into a single pending generation.\n */\nexport function createTypegenRunner(onGenerate: () => Promise<unknown>): TypegenRunner {\n const state: WatchState = {\n isGenerating: false,\n pendingGeneration: false,\n }\n\n async function runGeneration(): Promise<void> {\n if (state.isGenerating) {\n state.pendingGeneration = true\n return\n }\n\n state.isGenerating = true\n state.pendingGeneration = false\n\n try {\n await onGenerate()\n } finally {\n state.isGenerating = false\n\n // If a change came in during generation, run again\n if (state.pendingGeneration) {\n state.pendingGeneration = false\n await runGeneration()\n }\n }\n }\n\n return {runGeneration, state}\n}\n\n/**\n * Starts a file watcher that triggers typegen on changes.\n * Watches both query files (via patterns) and the schema JSON file.\n * Implements debouncing and concurrency control to prevent multiple generations.\n */\nexport function runTypegenWatcher(options: RunTypegenOptions): {\n getStats: () => WatcherStats\n stop: () => Promise<void>\n watcher: FSWatcher\n} {\n const {config, workDir} = options\n const {path, schema} = config\n\n const stats = {\n failedCount: 0,\n startTime: Date.now(),\n successfulDurations: [] as number[],\n }\n\n const {runGeneration} = createTypegenRunner(async () => {\n try {\n const {duration} = await runTypegenGenerate(options)\n stats.successfulDurations.push(duration)\n } catch {\n stats.failedCount++\n }\n })\n\n // Debounced generation trigger\n const debouncedGenerate = debounce(runGeneration, 1000)\n\n // Build absolute patterns for query files and schema file\n const paths = Array.isArray(path) ? path : [path]\n const absoluteQueryPatterns = paths.map((pattern) =>\n isAbsolute(pattern) ? pattern : join(workDir, pattern),\n )\n const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema)\n const watchTargets = [...absoluteQueryPatterns, absoluteSchemaPath]\n\n // perform initial generation\n debouncedGenerate()\n\n // set up watcher\n const watcher = chokidar.watch(watchTargets, {\n cwd: workDir,\n ignored: IGNORED_PATTERNS,\n ignoreInitial: true,\n })\n\n watcher.on('all', (event: string, filePath: string) => {\n const timestamp = new Date().toLocaleTimeString()\n const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath\n debug(`[${timestamp}] ${event}: ${relativePath}`)\n debouncedGenerate()\n })\n\n watcher.on('error', (err: Error) => {\n error(`Watcher error: ${err.message}`)\n })\n\n return {\n getStats: () => ({\n averageGenerationDuration: mean(stats.successfulDurations) || 0,\n generationFailedCount: stats.failedCount,\n generationSuccessfulCount: stats.successfulDurations.length,\n watcherDuration: Date.now() - stats.startTime,\n }),\n stop: async () => {\n await watcher.close()\n },\n watcher,\n }\n}\n"],"names":["debug","error","isAbsolute","join","relative","chokidar","debounce","mean","runTypegenGenerate","IGNORED_PATTERNS","createTypegenRunner","onGenerate","state","isGenerating","pendingGeneration","runGeneration","runTypegenWatcher","options","config","workDir","path","schema","stats","failedCount","startTime","Date","now","successfulDurations","duration","push","debouncedGenerate","paths","Array","isArray","absoluteQueryPatterns","map","pattern","absoluteSchemaPath","watchTargets","watcher","watch","cwd","ignored","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","err","message","getStats","averageGenerationDuration","generationFailedCount","generationSuccessfulCount","length","watcherDuration","stop","close"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,KAAK,QAAO,eAAc;AACzC,SAAQC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,QAAO,YAAW;AAEpD,OAAOC,cAA2B,WAAU;AAC5C,SAAQC,QAAQ,EAAEC,IAAI,QAAO,YAAW;AAGxC,SAAQC,kBAAkB,QAAO,uBAAsB;AAGvD,MAAMC,mBAAmB;IACvB;IACA;IACA;IACA;IACA;CACD;AAgBD;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,UAAkC;IACpE,MAAMC,QAAoB;QACxBC,cAAc;QACdC,mBAAmB;IACrB;IAEA,eAAeC;QACb,IAAIH,MAAMC,YAAY,EAAE;YACtBD,MAAME,iBAAiB,GAAG;YAC1B;QACF;QAEAF,MAAMC,YAAY,GAAG;QACrBD,MAAME,iBAAiB,GAAG;QAE1B,IAAI;YACF,MAAMH;QACR,SAAU;YACRC,MAAMC,YAAY,GAAG;YAErB,mDAAmD;YACnD,IAAID,MAAME,iBAAiB,EAAE;gBAC3BF,MAAME,iBAAiB,GAAG;gBAC1B,MAAMC;YACR;QACF;IACF;IAEA,OAAO;QAACA;QAAeH;IAAK;AAC9B;AAEA;;;;CAIC,GACD,OAAO,SAASI,kBAAkBC,OAA0B;IAK1D,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;IA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mB,KAAK;gBAC9D2B,uBAAuBhC,MAAMC,WAAW;gBACxCgC,2BAA2BjC,MAAMK,mBAAmB,CAAC6B,MAAM;gBAC3DC,iBAAiBhC,KAAKC,GAAG,KAAKJ,MAAME,SAAS;YAC/C,CAAA;QACAkC,MAAM;YACJ,MAAMnB,QAAQoB,KAAK;QACrB;QACApB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {error, log} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\n\nimport {chalk} from '@sanity/cli-core/ux'\nimport chokidar, {FSWatcher} from 'chokidar'\nimport {debounce, mean} from 'lodash-es'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {prepareConfig} from '../utils/config.js'\nimport {runTypegenGenerate} from './typegenGenerate.js'\nimport {type RunTypegenOptions} from './types.js'\n\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\n/** State for tracking generation status */\nexport interface WatchState {\n isGenerating: boolean\n pendingGeneration: boolean\n}\n\n/** Return type for createTypegenRunner */\ninterface TypegenRunner {\n runGeneration: () => Promise<void>\n state: WatchState\n}\n\ntype WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {step: 'stopped'}>, 'step'>\n\n/**\n * Creates a typegen runner with concurrency control.\n * If generation is already running, queues one more generation to run after completion.\n * Multiple queued requests are coalesced into a single pending generation.\n */\nexport function createTypegenRunner(onGenerate: () => Promise<unknown>): TypegenRunner {\n const state: WatchState = {\n isGenerating: false,\n pendingGeneration: false,\n }\n\n async function runGeneration(): Promise<void> {\n if (state.isGenerating) {\n state.pendingGeneration = true\n return\n }\n\n state.isGenerating = true\n state.pendingGeneration = false\n\n try {\n await onGenerate()\n } finally {\n state.isGenerating = false\n\n // If a change came in during generation, run again\n if (state.pendingGeneration) {\n state.pendingGeneration = false\n await runGeneration()\n }\n }\n }\n\n return {runGeneration, state}\n}\n\n/**\n * Starts a file watcher that triggers typegen on changes.\n * Watches both query files (via patterns) and the schema JSON file.\n * Implements debouncing and concurrency control to prevent multiple generations.\n */\nexport function runTypegenWatcher(options: RunTypegenOptions): {\n getStats: () => WatcherStats\n stop: () => Promise<void>\n watcher: FSWatcher\n} {\n const {config, workDir} = options\n const {path, schema} = prepareConfig(config)\n\n const stats = {\n failedCount: 0,\n startTime: Date.now(),\n successfulDurations: [] as number[],\n }\n\n const {runGeneration} = createTypegenRunner(async () => {\n try {\n const {duration} = await runTypegenGenerate({...options})\n stats.successfulDurations.push(duration)\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : err\n error(` ${chalk.red('›')} ${errorMessage}`)\n stats.failedCount++\n }\n })\n\n // Debounced generation trigger\n const debouncedGenerate = debounce(runGeneration, 1000)\n\n // Build absolute patterns for query files and schema file\n const paths = Array.isArray(path) ? path : [path]\n const absoluteQueryPatterns = paths.map((pattern) =>\n isAbsolute(pattern) ? pattern : join(workDir, pattern),\n )\n const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema)\n const watchTargets = [...absoluteQueryPatterns, absoluteSchemaPath]\n\n // perform initial generation\n debouncedGenerate()\n\n // set up watcher\n const watcher = chokidar.watch(watchTargets, {\n cwd: workDir,\n ignored: IGNORED_PATTERNS,\n ignoreInitial: true,\n })\n\n watcher.on('all', (event: string, filePath: string) => {\n const timestamp = new Date().toLocaleTimeString()\n const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath\n log(`[${timestamp}] ${event}: ${relativePath}`)\n debouncedGenerate()\n })\n\n watcher.on('error', (err: Error) => {\n error(`Watcher error: ${err.message}`)\n })\n\n return {\n getStats: () => ({\n averageGenerationDuration: mean(stats.successfulDurations) || 0,\n generationFailedCount: stats.failedCount,\n generationSuccessfulCount: stats.successfulDurations.length,\n watcherDuration: Date.now() - stats.startTime,\n }),\n stop: async () => {\n await watcher.close()\n },\n watcher,\n }\n}\n"],"names":["error","log","isAbsolute","join","relative","chalk","chokidar","debounce","mean","prepareConfig","runTypegenGenerate","IGNORED_PATTERNS","createTypegenRunner","onGenerate","state","isGenerating","pendingGeneration","runGeneration","runTypegenWatcher","options","config","workDir","path","schema","stats","failedCount","startTime","Date","now","successfulDurations","duration","push","err","errorMessage","Error","message","red","debouncedGenerate","paths","Array","isArray","absoluteQueryPatterns","map","pattern","absoluteSchemaPath","watchTargets","watcher","watch","cwd","ignored","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","getStats","averageGenerationDuration","generationFailedCount","generationSuccessfulCount","length","watcherDuration","stop","close"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,GAAG,QAAO,eAAc;AACvC,SAAQC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,QAAO,YAAW;AAEpD,SAAQC,KAAK,QAAO,sBAAqB;AACzC,OAAOC,cAA2B,WAAU;AAC5C,SAAQC,QAAQ,EAAEC,IAAI,QAAO,YAAW;AAGxC,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,kBAAkB,QAAO,uBAAsB;AAGvD,MAAMC,mBAAmB;IACvB;IACA;IACA;IACA;IACA;CACD;AAgBD;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,UAAkC;IACpE,MAAMC,QAAoB;QACxBC,cAAc;QACdC,mBAAmB;IACrB;IAEA,eAAeC;QACb,IAAIH,MAAMC,YAAY,EAAE;YACtBD,MAAME,iBAAiB,GAAG;YAC1B;QACF;QAEAF,MAAMC,YAAY,GAAG;QACrBD,MAAME,iBAAiB,GAAG;QAE1B,IAAI;YACF,MAAMH;QACR,SAAU;YACRC,MAAMC,YAAY,GAAG;YAErB,mDAAmD;YACnD,IAAID,MAAME,iBAAiB,EAAE;gBAC3BF,MAAME,iBAAiB,GAAG;gBAC1B,MAAMC;YACR;QACF;IACF;IAEA,OAAO;QAACA;QAAeH;IAAK;AAC9B;AAEA;;;;CAIC,GACD,OAAO,SAASI,kBAAkBC,OAA0B;IAK1D,MAAM,EAACC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AEF,MAAM,EAAE,EAAEI,cAAc;QAC9CnB;IACF;IAEAS,QAAQK,EAAE,CAAC,SAAS,CAACnB;QACnBhC,MAAM,CAAC,eAAe,EAAEgC,IAAIG,OAAO,EAAE;IACvC;IAEA,OAAO;QACLsB,UAAU,IAAO,CAAA;gBACfC,2BAA2BlD,KAAKgB,MAAMK,mBAAmB,KAAK;gBAC9D8B,uBAAuBnC,MAAMC,WAAW;gBACxCmC,2BAA2BpC,MAAMK,mBAAmB,CAACgC,MAAM;gBAC3DC,iBAAiBnC,KAAKC,GAAG,KAAKJ,MAAME,SAAS;YAC/C,CAAA;QACAqC,MAAM;YACJ,MAAMjB,QAAQkB,KAAK;QACrB;QACAlB;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\nimport {telemetry} from '../utils/telemetryLogger.js'\n\n/**\n * Data passed to the typegen worker thread.\n * @internal\n */\nexport interface TypegenGenerateTypesWorkerData {\n /** Path to the schema JSON file */\n schemaPath: string\n /** Glob pattern(s) for finding query files */\n searchPath: string | string[]\n /** Working directory (project root) */\n workDir: string\n\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n}\n\n/**\n * Worker channel definition for typegen worker communication.\n * Extends the base TypegenWorkerChannel with additional events for progress tracking.\n * @internal\n */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n\n/**\n * Options for running a single typegen generation.\n * This is the programmatic API for one-off generation without file watching.\n */\nexport interface RunTypegenOptions {\n /** Typegen configuration */\n config: TypeGenConfig\n\n /** Working directory (usually project root) */\n workDir: string\n\n /** Optional spinner instance for progress display */\n spin?: ReturnType<typeof spinner>\n\n /** Optional telemetry instance for tracking usage */\n telemetry?: typeof telemetry\n}\n\n/**\n * Result from a single generation run.\n * @internal\n */\nexport interface GenerationResult {\n code: string\n duration: number\n emptyUnionTypeNodesGenerated: number\n filesWithErrors: number\n outputSize: number\n queriesCount: number\n queryFilesCount: number\n schemaTypesCount: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n}\n"],"names":[],"mappings":"AAsDA;;;CAGC,GACD,WAYC"}
1
+ {"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\nimport {telemetry} from '../utils/telemetryLogger.js'\n\n/**\n * Data passed to the typegen worker thread.\n * @internal\n */\nexport interface TypegenGenerateTypesWorkerData {\n /** Path to the schema JSON file */\n schemaPath: string\n /** Glob pattern(s) for finding query files */\n searchPath: string | string[]\n /** Working directory (project root) */\n workDir: string\n\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n}\n\n/**\n * Worker channel definition for typegen worker communication.\n * Extends the base TypegenWorkerChannel with additional events for progress tracking.\n * @internal\n */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n\n/**\n * Options for running a single typegen generation.\n * This is the programmatic API for one-off generation without file watching.\n */\nexport interface RunTypegenOptions {\n /** Working directory (usually project root) */\n workDir: string\n\n /** Typegen configuration */\n config?: Partial<TypeGenConfig>\n\n /** Optional spinner instance for progress display */\n spin?: ReturnType<typeof spinner>\n\n /** Optional telemetry instance for tracking usage */\n telemetry?: typeof telemetry\n}\n\n/**\n * Result from a single generation run.\n * @internal\n */\nexport interface GenerationResult {\n code: string\n duration: number\n emptyUnionTypeNodesGenerated: number\n filesWithErrors: number\n outputSize: number\n queriesCount: number\n queryFilesCount: number\n schemaTypesCount: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n}\n"],"names":[],"mappings":"AAsDA;;;CAGC,GACD,WAYC"}
@@ -1,15 +1,15 @@
1
1
  import { stat } from 'node:fs/promises';
2
2
  import { Flags } from '@oclif/core';
3
- import { SanityCommand, subdebug } from '@sanity/cli-core';
3
+ import { SanityCommand } from '@sanity/cli-core';
4
4
  import { chalk, spinner } from '@sanity/cli-core/ux';
5
5
  import { omit, once } from 'lodash-es';
6
6
  import { runTypegenGenerate } from '../../actions/typegenGenerate.js';
7
7
  import { runTypegenWatcher } from '../../actions/typegenWatch.js';
8
8
  import { configDefinition, readConfig } from '../../readConfig.js';
9
9
  import { TypegenWatchModeTrace, TypesGeneratedTrace } from '../../typegen.telemetry.js';
10
+ import { debug } from '../../utils/debug.js';
10
11
  import { promiseWithResolvers } from '../../utils/promiseWithResolvers.js';
11
12
  import { telemetry } from '../../utils/telemetryLogger.js';
12
- const debug = subdebug('typegen:generate');
13
13
  const description = `Sanity TypeGen (Beta)
14
14
  This command is currently in beta and may undergo significant changes. Feedback is welcome!
15
15
 
@@ -59,62 +59,71 @@ ${chalk.bold('Note:')}
59
59
  }
60
60
  async getConfig() {
61
61
  const spin = spinner({}).start('Loading config…');
62
- const { flags } = await this.parse(TypegenGenerateCommand);
63
- const rootDir = await this.getProjectRoot();
64
- const config = await this.getCliConfig();
65
- const configPath = flags['config-path'];
66
- const workDir = rootDir.directory;
67
- // check if the legacy config exist
68
- const legacyConfigPath = configPath || 'sanity-typegen.json';
69
- let hasLegacyConfig = false;
70
62
  try {
71
- const file = await stat(legacyConfigPath);
72
- hasLegacyConfig = file.isFile();
73
- } catch (err) {
74
- if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {
75
- throw new Error(`Typegen config file not found: ${configPath}`, {
76
- cause: err
77
- });
63
+ const { flags } = await this.parse(TypegenGenerateCommand);
64
+ const rootDir = await this.getProjectRoot();
65
+ const config = await this.getCliConfig();
66
+ const configPath = flags['config-path'];
67
+ const workDir = rootDir.directory;
68
+ // check if the legacy config exist
69
+ const legacyConfigPath = configPath || 'sanity-typegen.json';
70
+ let hasLegacyConfig = false;
71
+ try {
72
+ const file = await stat(legacyConfigPath);
73
+ hasLegacyConfig = file.isFile();
74
+ } catch (err) {
75
+ if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {
76
+ spin.fail();
77
+ this.error(`Typegen config file not found: ${configPath}`, {
78
+ exit: 1
79
+ });
80
+ }
81
+ if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {
82
+ spin.fail();
83
+ this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {
84
+ exit: 1
85
+ });
86
+ }
78
87
  }
79
- if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {
80
- throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {
81
- cause: err
82
- });
88
+ // we have both legacy and cli config with typegen
89
+ if (config?.typegen && hasLegacyConfig) {
90
+ spin.warn(chalk.yellow(`You've specified typegen in your Sanity CLI config, but also have a typegen config.
91
+
92
+ The config from the Sanity CLI config is used.
93
+ `));
94
+ return {
95
+ config: configDefinition.parse(config.typegen || {}),
96
+ path: rootDir.path,
97
+ type: 'cli',
98
+ workDir
99
+ };
83
100
  }
84
- }
85
- // we have both legacy and cli config with typegen
86
- if (config?.typegen && hasLegacyConfig) {
87
- spin.warn(chalk.yellow(`You've specified typegen in your Sanity CLI config, but also have a typegen config.
101
+ // we only have legacy typegen config
102
+ if (hasLegacyConfig) {
103
+ spin.warn(chalk.yellow(`The separate typegen config has been deprecated. Use \`typegen\` in the sanity CLI config instead.
88
104
 
89
- The config from the Sanity CLI config is used.
90
- `));
105
+ See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`));
106
+ return {
107
+ config: await readConfig(legacyConfigPath),
108
+ path: legacyConfigPath,
109
+ type: 'legacy',
110
+ workDir
111
+ };
112
+ }
113
+ spin.succeed(`Config loaded from sanity.cli.ts`);
114
+ // we only have cli config
91
115
  return {
92
116
  config: configDefinition.parse(config.typegen || {}),
93
117
  path: rootDir.path,
94
118
  type: 'cli',
95
119
  workDir
96
120
  };
121
+ } catch (err) {
122
+ spin.fail();
123
+ this.error(`An error occured during config loading ${err}`, {
124
+ exit: 1
125
+ });
97
126
  }
98
- // we only have legacy typegen config
99
- if (hasLegacyConfig) {
100
- spin.warn(chalk.yellow(`The separate typegen config has been deprecated. Use \`typegen\` in the sanity CLI config instead.
101
-
102
- See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`));
103
- return {
104
- config: await readConfig(legacyConfigPath),
105
- path: legacyConfigPath,
106
- type: 'legacy',
107
- workDir
108
- };
109
- }
110
- spin.succeed(`Config loaded from sanity.cli.ts`);
111
- // we only have cli config
112
- return {
113
- config: configDefinition.parse(config.typegen || {}),
114
- path: rootDir.path,
115
- type: 'cli',
116
- workDir
117
- };
118
127
  }
119
128
  async runSingle() {
120
129
  const trace = telemetry.trace(TypesGeneratedTrace);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand, subdebug} from '@sanity/cli-core'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {omit, once} from 'lodash-es'\n\nimport {runTypegenGenerate} from '../../actions/typegenGenerate.js'\nimport {runTypegenWatcher} from '../../actions/typegenWatch.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {TypegenWatchModeTrace, TypesGeneratedTrace} from '../../typegen.telemetry.js'\nimport {promiseWithResolvers} from '../../utils/promiseWithResolvers.js'\nimport {telemetry} from '../../utils/telemetryLogger.js'\n\nconst debug = subdebug('typegen:generate')\n\nconst description = `Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n${chalk.bold('Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${chalk.bold('Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim()\n\n/**\n * @internal\n */\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n watch: Flags.boolean({\n default: false,\n description: '[Default: false] Run the typegen in watch mode',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n\n if (flags.watch) {\n await this.runWatcher()\n return\n }\n\n await this.runSingle()\n }\n\n private async getConfig(): Promise<{\n config: TypeGenConfig\n path?: string\n type: 'cli' | 'legacy'\n workDir: string\n }> {\n const spin = spinner({}).start('Loading config…')\n\n const {flags} = await this.parse(TypegenGenerateCommand)\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n const configPath = flags['config-path']\n const workDir = rootDir.directory\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n try {\n const file = await stat(legacyConfigPath)\n hasLegacyConfig = file.isFile()\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n throw new Error(`Typegen config file not found: ${configPath}`, {cause: err})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n cause: err,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n workDir,\n }\n }\n\n spin.succeed(`Config loaded from sanity.cli.ts`)\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n }\n\n private async runSingle() {\n const trace = telemetry.trace(TypesGeneratedTrace)\n\n try {\n const {config: typegenConfig, type: typegenConfigMethod, workDir} = await this.getConfig()\n trace.start()\n\n const result = await runTypegenGenerate({\n config: typegenConfig,\n workDir,\n })\n\n const traceStats = omit(result, 'code', 'duration')\n\n trace.log({\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: typegenConfig.overloadClientMethods,\n ...traceStats,\n })\n trace.complete()\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n\n private async runWatcher() {\n const trace = telemetry.trace(TypegenWatchModeTrace)\n\n try {\n const {config: typegenConfig, workDir} = await this.getConfig()\n trace.start()\n\n const {promise, resolve} = promiseWithResolvers()\n\n const typegenWatcher = runTypegenWatcher({\n config: typegenConfig,\n workDir,\n })\n\n const stop = once(async () => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n\n trace.log({\n step: 'stopped',\n ...typegenWatcher.getStats(),\n })\n trace.complete()\n\n await typegenWatcher.stop()\n resolve()\n })\n\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n await promise\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n}\n"],"names":["stat","Flags","SanityCommand","subdebug","chalk","spinner","omit","once","runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","TypegenWatchModeTrace","TypesGeneratedTrace","promiseWithResolvers","telemetry","debug","description","bold","trim","TypegenGenerateCommand","examples","command","flags","string","watch","boolean","default","run","parse","runWatcher","runSingle","getConfig","spin","start","rootDir","getProjectRoot","config","getCliConfig","configPath","workDir","directory","legacyConfigPath","hasLegacyConfig","file","isFile","err","Error","code","cause","typegen","warn","yellow","path","type","succeed","trace","typegenConfig","typegenConfigMethod","result","traceStats","log","configMethod","configOverloadClientMethods","overloadClientMethods","complete","error","message","exit","promise","resolve","typegenWatcher","stop","process","off","step","getStats","on"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AAErC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACxD,SAAQC,KAAK,EAAEC,OAAO,QAAO,sBAAqB;AAClD,SAAQC,IAAI,EAAEC,IAAI,QAAO,YAAW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AAK,CAACA;YACZ,IAAI,CAACA,KAAK,CAAC,GAAGA,iBAAiBnB,QAAQmB,MAAMC,OAAO,GAAG,iBAAiB,EAAE;gBACxEC,MAAM;YACR;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {omit, once} from 'lodash-es'\n\nimport {runTypegenGenerate} from '../../actions/typegenGenerate.js'\nimport {runTypegenWatcher} from '../../actions/typegenWatch.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {TypegenWatchModeTrace, TypesGeneratedTrace} from '../../typegen.telemetry.js'\nimport {debug} from '../../utils/debug.js'\nimport {promiseWithResolvers} from '../../utils/promiseWithResolvers.js'\nimport {telemetry} from '../../utils/telemetryLogger.js'\n\nconst description = `Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n${chalk.bold('Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${chalk.bold('Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim()\n\n/**\n * @internal\n */\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n watch: Flags.boolean({\n default: false,\n description: '[Default: false] Run the typegen in watch mode',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n\n if (flags.watch) {\n await this.runWatcher()\n return\n }\n\n await this.runSingle()\n }\n\n private async getConfig(): Promise<{\n config: TypeGenConfig\n path?: string\n type: 'cli' | 'legacy'\n workDir: string\n }> {\n const spin = spinner({}).start('Loading config…')\n\n try {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n const configPath = flags['config-path']\n const workDir = rootDir.directory\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n\n try {\n const file = await stat(legacyConfigPath)\n hasLegacyConfig = file.isFile()\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n spin.fail()\n this.error(`Typegen config file not found: ${configPath}`, {exit: 1})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n spin.fail()\n this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n exit: 1,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n workDir,\n }\n }\n\n spin.succeed(`Config loaded from sanity.cli.ts`)\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n } catch (err) {\n spin.fail()\n this.error(`An error occured during config loading ${err}`, {exit: 1})\n }\n }\n\n private async runSingle() {\n const trace = telemetry.trace(TypesGeneratedTrace)\n\n try {\n const {config: typegenConfig, type: typegenConfigMethod, workDir} = await this.getConfig()\n trace.start()\n\n const result = await runTypegenGenerate({\n config: typegenConfig,\n workDir,\n })\n\n const traceStats = omit(result, 'code', 'duration')\n\n trace.log({\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: typegenConfig.overloadClientMethods,\n ...traceStats,\n })\n trace.complete()\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n\n private async runWatcher() {\n const trace = telemetry.trace(TypegenWatchModeTrace)\n\n try {\n const {config: typegenConfig, workDir} = await this.getConfig()\n trace.start()\n\n const {promise, resolve} = promiseWithResolvers()\n\n const typegenWatcher = runTypegenWatcher({\n config: typegenConfig,\n workDir,\n })\n\n const stop = once(async () => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n\n trace.log({\n step: 'stopped',\n ...typegenWatcher.getStats(),\n })\n trace.complete()\n\n await typegenWatcher.stop()\n resolve()\n })\n\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n await promise\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n}\n"],"names":["stat","Flags","SanityCommand","chalk","spinner","omit","once","runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","TypegenWatchModeTrace","TypesGeneratedTrace","debug","promiseWithResolvers","telemetry","description","bold","trim","TypegenGenerateCommand","examples","command","flags","string","watch","boolean","default","run","parse","runWatcher","runSingle","getConfig","spin","start","rootDir","getProjectRoot","config","getCliConfig","configPath","workDir","directory","legacyConfigPath","hasLegacyConfig","file","isFile","err","Error","code","fail","error","exit","typegen","warn","yellow","path","type","succeed","trace","typegenConfig","typegenConfigMethod","result","traceStats","log","configMethod","configOverloadClientMethods","overloadClientMethods","complete","message","promise","resolve","typegenWatcher","stop","process","off","step","getStats","on"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AAErC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,KAAK,EAAEC,OAAO,QAAO,sBAAqB;AAClD,SAAQC,IAAI,EAAEC,IAAI,QAAO,YAAW;AAEpC,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,iBAAiB,QAAO,gCAA+B;AAC/D,SAAQC,gBAAgB,EAAEC,UAAU,QAA2B,sBAAqB;AACpF,SAAQC,qBAAqB,EAAEC,mBAAmB,QAAO,6BAA4B;AACrF,SAAQC,KAAK,QAAO,uBAAsB;AAC1C,SAAQC,oBAAoB,QAAO,sCAAqC;AACxE,SAAQC,SAAS,QAAO,iCAAgC;AAExD,MAAMC,cAAc,CAAC;;;AAGrB,EAAEb,MAAMc,IAAI,CAAC,kBAAkB;;;;;;;;;;;;;;AAc/B,EAAEd,MAAMc,IAAI,CAAC,SAAS;;4JAEsI,CAAC,CAACC,IAAI;AAElK;;CAEC,GACD,OAAO,MAAMC,+BAA+BjB;IAC1C,OAAgBc,cAAcA,YAAW;IAEzC,OAAgBI,WAAW;QACzB;YACEC,SAAS;YACTL,aAAa,CAAC,uHAAuH,CAAC;QACxI;KACD,CAAA;IAED,OAAgBM,QAAQ;QACtB,eAAerB,MAAM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NQ,MAAMR,KAAK,CAACA;YACZ,IAAI,CAACA,KAAK,CAAC,GAAGA,iBAAiBH,QAAQG,MAAMkB,OAAO,GAAG,iBAAiB,EAAE;gBACxEjB,MAAM;YACR;QACF;IACF;IAEA,MAAcrB,aAAa;QACzB,MAAM4B,QAAQ1C,UAAU0C,KAAK,CAAC9C;QAE9B,IAAI;YACF,MAAM,EAACyB,QAAQsB,aAAa,EAAEnB,OAAO,EAAC,GAAG,MAAM,IAAI,CAACR,SAAS;YAC7D0B,MAAMxB,KAAK;YAEX,MAAM,EAACmC,OAAO,EAAEC,OAAO,EAAC,GAAGvD;YAE3B,MAAMwD,iBAAiB9D,kBAAkB;gBACvC4B,QAAQsB;gBACRnB;YACF;YAEA,MAAMgC,OAAOjE,KAAK;gBAChBkE,QAAQC,GAAG,CAAC,UAAUF;gBACtBC,QAAQC,GAAG,CAAC,WAAWF;gBAEvBd,MAAMK,GAAG,CAAC;oBACRY,MAAM;oBACN,GAAGJ,eAAeK,QAAQ,EAAE;gBAC9B;gBACAlB,MAAMS,QAAQ;gBAEd,MAAMI,eAAeC,IAAI;gBACzBF;YACF;YAEAG,QAAQI,EAAE,CAAC,UAAUL;YACrBC,QAAQI,EAAE,CAAC,WAAWL;YAEtB,MAAMH;QACR,EAAE,OAAOnB,OAAO;YACdpC,MAAMoC;YACNQ,MAAMR,KAAK,CAACA;YACZ,IAAI,CAACA,KAAK,CAAC,GAAGA,iBAAiBH,QAAQG,MAAMkB,OAAO,GAAG,iBAAiB,EAAE;gBACxEjB,MAAM;YACR;QACF;IACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -417,10 +417,10 @@ export declare function runTypegenGenerate(options: RunTypegenOptions): Promise<
417
417
  * This is the programmatic API for one-off generation without file watching.
418
418
  */
419
419
  export declare interface RunTypegenOptions {
420
- /** Typegen configuration */
421
- config: TypeGenConfig;
422
420
  /** Working directory (usually project root) */
423
421
  workDir: string;
422
+ /** Typegen configuration */
423
+ config?: Partial<TypeGenConfig>;
424
424
  /** Optional spinner instance for progress display */
425
425
  spin?: ReturnType<typeof spinner>;
426
426
  /** Optional telemetry instance for tracking usage */
@@ -0,0 +1,11 @@
1
+ export function prepareConfig(config) {
2
+ return {
3
+ formatGeneratedCode: config?.formatGeneratedCode ?? false,
4
+ generates: config?.generates ?? 'sanity.types.ts',
5
+ overloadClientMethods: config?.overloadClientMethods ?? false,
6
+ path: config?.path ?? './src/**/*.{ts,tsx,js,jsx}',
7
+ schema: config?.schema ?? 'schema.json'
8
+ };
9
+ }
10
+
11
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/config.ts"],"sourcesContent":["import {TypeGenConfig} from '../readConfig.js'\n\nexport function prepareConfig(config?: Partial<TypeGenConfig>): TypeGenConfig {\n return {\n formatGeneratedCode: config?.formatGeneratedCode ?? false,\n generates: config?.generates ?? 'sanity.types.ts',\n overloadClientMethods: config?.overloadClientMethods ?? false,\n path: config?.path ?? './src/**/*.{ts,tsx,js,jsx}',\n schema: config?.schema ?? 'schema.json',\n }\n}\n"],"names":["prepareConfig","config","formatGeneratedCode","generates","overloadClientMethods","path","schema"],"mappings":"AAEA,OAAO,SAASA,cAAcC,MAA+B;IAC3D,OAAO;QACLC,qBAAqBD,QAAQC,uBAAuB;QACpDC,WAAWF,QAAQE,aAAa;QAChCC,uBAAuBH,QAAQG,yBAAyB;QACxDC,MAAMJ,QAAQI,QAAQ;QACtBC,QAAQL,QAAQK,UAAU;IAC5B;AACF"}
@@ -0,0 +1,4 @@
1
+ import { subdebug } from '@sanity/cli-core';
2
+ export const debug = subdebug('typegen:generate');
3
+
4
+ //# sourceMappingURL=debug.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\n\nexport const debug = subdebug('typegen:generate')\n"],"names":["subdebug","debug"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAO,MAAMC,QAAQD,SAAS,oBAAmB"}
@@ -3,7 +3,7 @@
3
3
  "typegen:generate": {
4
4
  "aliases": [],
5
5
  "args": {},
6
- "description": "Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\nConfiguration:\nThis command can utilize configuration settings defined in a `sanity-typegen.json` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the `sanity schema extract` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your `sanity-typegen.json` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\nNote:\n- The `sanity schema extract` command is a prerequisite for extracting your Sanity Studio schema into a `schema.json` file, which is then used by the `sanity typegen generate` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.",
6
+ "description": "Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n\u001b[1mConfiguration:\u001b[22m\nThis command can utilize configuration settings defined in a `sanity-typegen.json` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the `sanity schema extract` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your `sanity-typegen.json` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n\u001b[1mNote:\u001b[22m\n- The `sanity schema extract` command is a prerequisite for extracting your Sanity Studio schema into a `schema.json` file, which is then used by the `sanity typegen generate` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.",
7
7
  "examples": [
8
8
  {
9
9
  "command": "<%= config.bin %> <%= command.id %>",
@@ -41,5 +41,5 @@
41
41
  ]
42
42
  }
43
43
  },
44
- "version": "5.8.0"
44
+ "version": "5.9.0-watch-mode.2"
45
45
  }