@sanity/codegen 8.1.1 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/findQueriesInSource.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {type NodePath, type TransformOptions, traverse} from '@babel/core'\nimport {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {resolveExpression} from './expressionResolvers.js'\nimport {parseSourceFile} from './parseSource.js'\nimport {type ExtractedModule, type ExtractedQuery, QueryExtractionError} from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\nconst sveltekitModuleName = '@sanity/sveltekit'\n\nconst ignoreValue = '@sanity-typegen-ignore'\n\n/**\n * findQueriesInSource takes a source string and returns all GROQ queries in it.\n * @param source - The source code to search for queries\n * @param filename - The filename of the source code\n * @param babelConfig - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns\n * @beta\n * @internal\n */\nexport function findQueriesInSource(\n source: string,\n filename: string,\n babelConfig: TransformOptions = getBabelConfig(),\n resolver: NodeJS.RequireResolve = require.resolve,\n): ExtractedModule {\n const queries: ExtractedQuery[] = []\n const errors: QueryExtractionError[] = []\n const file = parseSourceFile(source, filename, babelConfig)\n\n traverse(file, {\n // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.\n // The variable name is used as the name of the query result type\n VariableDeclarator(path) {\n const {node, scope} = path\n\n const init = node.init\n\n // Look for tagged template expressions that are called with the `groq` tag\n const isGroqTemplateTag =\n babelTypes.isTaggedTemplateExpression(init) &&\n babelTypes.isIdentifier(init.tag) &&\n init.tag.name === groqTagName\n\n // Look for strings wrapped in a defineQuery function call\n const isDefineQueryCall =\n babelTypes.isCallExpression(init) &&\n (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(sveltekitModuleName, defineQueryFunctionName, scope, init.callee))\n\n if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {\n // If we find a comment leading the decleration which macthes with ignoreValue we don't add\n // the query\n if (declarationLeadingCommentContains(path, ignoreValue)) {\n return\n }\n\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n babelConfig,\n file,\n filename,\n node: init,\n resolver,\n scope,\n })\n queries.push({filename, query, variable})\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n },\n })\n\n return {errors, filename, queries}\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n"],"names":["createRequire","traverse","babelTypes","getBabelConfig","resolveExpression","parseSourceFile","QueryExtractionError","require","url","groqTagName","defineQueryFunctionName","groqModuleName","nextSanityModuleName","sveltekitModuleName","ignoreValue","findQueriesInSource","source","filename","babelConfig","resolver","resolve","queries","errors","file","VariableDeclarator","path","node","scope","init","isGroqTemplateTag","isTaggedTemplateExpression","isIdentifier","tag","name","isDefineQueryCall","isCallExpression","isImportFrom","callee","id","declarationLeadingCommentContains","end","start","variable","query","push","cause","comment","variableDeclaration","find","isVariableDeclaration","leadingComments","commentItem","value","trim","parent","moduleName","importName","binding","getBinding","isImportSpecifier","importKind","parentPath","isImportDeclaration","imported","isVariableDeclarator","isStringLiteral","arguments","isMemberExpression","object","property","isImportNamespaceSpecifier"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,SAA8CC,QAAQ,QAAO,cAAa;AAE1E,YAAYC,gBAAgB,eAAc;AAE1C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,iBAAiB,QAAO,2BAA0B;AAC1D,SAAQC,eAAe,QAAO,mBAAkB;AAChD,SAAmDC,oBAAoB,QAAO,aAAY;AAE1F,MAAMC,UAAUP,cAAc,YAAYQ,GAAG;AAE7C,MAAMC,cAAc;AACpB,MAAMC,0BAA0B;AAChC,MAAMC,iBAAiB;AACvB,MAAMC,uBAAuB;AAC7B,MAAMC,sBAAsB;AAE5B,MAAMC,cAAc;AAEpB;;;;;;;;;CASC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,QAAgB,EAChBC,cAAgCf,gBAAgB,EAChDgB,WAAkCZ,QAAQa,OAAO;IAEjD,MAAMC,UAA4B,EAAE;IACpC,MAAMC,SAAiC,EAAE;IACzC,MAAMC,OAAOlB,gBAAgBW,QAAQC,UAAUC;IAE/CjB,SAASsB,MAAM;QACb,wFAAwF;QACxF,iEAAiE;QACjEC,oBAAmBC,IAAI;YACrB,MAAM,EAACC,IAAI,EAAEC,KAAK,EAAC,GAAGF;YAEtB,MAAMG,OAAOF,KAAKE,IAAI;YAEtB,2EAA2E;YAC3E,MAAMC,oBACJ3B,WAAW4B,0B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S,CAAC,EAAE,KAC5CtC,KAAKsC,SAAS,CAAC,EAAE,CAACd,KAAK,KAAKG;QAEhC;IACF;IAEA,8BAA8B;IAC9B,uBAAuB;IACvB,IAAIrD,WAAWiE,kBAAkB,CAACzC,OAAO;QACvC,MAAM,EAAC0C,MAAM,EAAEC,QAAQ,EAAC,GAAG3C;QAE3B,IAAI,CAACxB,WAAW6B,YAAY,CAACqC,SAAS;YACpC,OAAO;QACT;QAEA,MAAMX,UAAU9B,MAAM+B,UAAU,CAACU,OAAOnC,IAAI;QAC5C,IAAI,CAACwB,SAAS;YACZ,OAAO;QACT;QACA,MAAM,EAAChC,IAAI,EAAC,GAAGgC;QAEf,OACEvD,WAAW6B,YAAY,CAACqC,WACxBlE,WAAW6B,YAAY,CAACsC,aACxBA,SAASpC,IAAI,KAAKuB,cAClBtD,WAAWoE,0BAA0B,CAAC7C,KAAKC,IAAI,KAC/CD,KAAKoC,UAAU,IACf3D,WAAW4D,mBAAmB,CAACrC,KAAKoC,UAAU,CAACnC,IAAI,KACnDD,KAAKoC,UAAU,CAACnC,IAAI,CAACV,MAAM,CAACoC,KAAK,KAAKG;IAE1C;IAEA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../src/typescript/findQueriesInSource.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {type NodePath, type TransformOptions, traverse} from '@babel/core'\nimport {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {resolveExpression} from './expressionResolvers.js'\nimport {parseSourceFile} from './parseSource.js'\nimport {\n type ExtractedModule,\n type ExtractedProjection,\n type ExtractedQuery,\n QueryExtractionError,\n} from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\nconst sveltekitModuleName = '@sanity/sveltekit'\nconst defineProjectionFunctionName = 'defineProjection'\nconst projectionModuleNames = ['@sanity/sdk', '@sanity/sdk-react']\n\nconst ignoreValue = '@sanity-typegen-ignore'\n\n/**\n * findQueriesInSource takes a source string and returns all GROQ queries in it.\n * @param source - The source code to search for queries\n * @param filename - The filename of the source code\n * @param babelConfig - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns\n * @beta\n * @internal\n */\nexport function findQueriesInSource(\n source: string,\n filename: string,\n babelConfig: TransformOptions = getBabelConfig(),\n resolver: NodeJS.RequireResolve = require.resolve,\n): ExtractedModule {\n const queries: ExtractedQuery[] = []\n const projections: ExtractedProjection[] = []\n const errors: QueryExtractionError[] = []\n const file = parseSourceFile(source, filename, babelConfig)\n\n traverse(file, {\n // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.\n // The variable name is used as the name of the query result type\n VariableDeclarator(path) {\n const {node, scope} = path\n\n const init = node.init\n\n // Look for tagged template expressions that are called with the `groq` tag\n const isGroqTemplateTag =\n babelTypes.isTaggedTemplateExpression(init) &&\n babelTypes.isIdentifier(init.tag) &&\n init.tag.name === groqTagName\n\n // Look for strings wrapped in a defineQuery function call\n const isDefineQueryCall =\n babelTypes.isCallExpression(init) &&\n (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(sveltekitModuleName, defineQueryFunctionName, scope, init.callee))\n\n if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {\n // If we find a comment leading the decleration which macthes with ignoreValue we don't add\n // the query\n if (declarationLeadingCommentContains(path, ignoreValue)) {\n return\n }\n\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n babelConfig,\n file,\n filename,\n node: init,\n resolver,\n scope,\n })\n queries.push({filename, query, variable})\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n\n // Look for `defineProjection(projection)` or `defineProjection(documentType, projection)`\n // imported from the App SDK\n if (\n babelTypes.isIdentifier(node.id) &&\n babelTypes.isCallExpression(init) &&\n projectionModuleNames.some((moduleName) =>\n isImportFrom(moduleName, defineProjectionFunctionName, scope, init.callee),\n ) &&\n !declarationLeadingCommentContains(path, ignoreValue)\n ) {\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n const resolve = (argument: babelTypes.Node) =>\n resolveExpression({babelConfig, file, filename, node: argument, resolver, scope})\n\n try {\n const [first, second] = init.arguments\n const projectionNode = second ?? first\n if (!projectionNode) throw new Error('defineProjection needs a projection')\n\n projections.push({\n filename,\n projection: resolve(projectionNode),\n variable,\n ...(second && first ? {documentType: resolve(first)} : {}),\n })\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n },\n })\n\n return {errors, filename, projections, queries}\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n"],"names":["createRequire","traverse","babelTypes","getBabelConfig","resolveExpression","parseSourceFile","QueryExtractionError","require","url","groqTagName","defineQueryFunctionName","groqModuleName","nextSanityModuleName","sveltekitModuleName","defineProjectionFunctionName","projectionModuleNames","ignoreValue","findQueriesInSource","source","filename","babelConfig","resolver","resolve","queries","projections","errors","file","VariableDeclarator","path","node","scope","init","isGroqTemplateTag","isTaggedTemplateExpression","isIdentifier","tag","name","isDefineQueryCall","isCallExpression","isImportFrom","callee","id","declarationLeadingCommentContains","end","start","variable","query","push","cause","some","moduleName","argument","first","second","arguments","projectionNode","Error","projection","documentType","comment","variableDeclaration","find","isVariableDeclaration","leadingComments","commentItem","value","trim","parent","importName","binding","getBinding","isImportSpecifier","importKind","parentPath","isImportDeclaration","imported","isVariableDeclarator","isStringLiteral","isMemberExpression","object","property","isImportNamespaceSpecifier"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,SAA8CC,QAAQ,QAAO,cAAa;AAE1E,YAAYC,gBAAgB,eAAc;AAE1C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,iBAAiB,QAAO,2BAA0B;AAC1D,SAAQC,eAAe,QAAO,mBAAkB;AAChD,SAIEC,oBAAoB,QACf,aAAY;AAEnB,MAAMC,UAAUP,cAAc,YAAYQ,GAAG;AAE7C,MAAMC,cAAc;AACpB,MAAMC,0BAA0B;AAChC,MAAMC,iBAAiB;AACvB,MAAMC,uBAAuB;AAC7B,MAAMC,sBAAsB;AAC5B,MAAMC,+BAA+B;AACrC,MAAMC,wBAAwB;IAAC;IAAe;CAAoB;AAElE,MAAMC,cAAc;AAEpB;;;;;;;;;CASC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,QAAgB,EAChBC,cAAgCjB,gBAAgB,EAChDkB,WAAkCd,QAAQe,OAAO;IAEjD,MAAMC,UAA4B,EAAE;IACpC,MAAMC,cAAqC,EAAE;IAC7C,MAAMC,SAAiC,EAAE;IACzC,MAAMC,OAAOrB,gBAAgBa,QAAQC,UAAUC;IAE/CnB,SAASyB,MAAM;QACb,wFAAw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AAKf;QAEhC;IACF;IAEA,8BAA8B;IAC9B,uBAAuB;IACvB,IAAIhD,WAAW4E,kBAAkB,CAACjD,OAAO;QACvC,MAAM,EAACkD,MAAM,EAAEC,QAAQ,EAAC,GAAGnD;QAE3B,IAAI,CAAC3B,WAAWgC,YAAY,CAAC6C,SAAS;YACpC,OAAO;QACT;QAEA,MAAMV,UAAUvC,MAAMwC,UAAU,CAACS,OAAO3C,IAAI;QAC5C,IAAI,CAACiC,SAAS;YACZ,OAAO;QACT;QACA,MAAM,EAACzC,IAAI,EAAC,GAAGyC;QAEf,OACEnE,WAAWgC,YAAY,CAAC6C,WACxB7E,WAAWgC,YAAY,CAAC8C,aACxBA,SAAS5C,IAAI,KAAKgC,cAClBlE,WAAW+E,0BAA0B,CAACrD,KAAKC,IAAI,KAC/CD,KAAK6C,UAAU,IACfvE,WAAWwE,mBAAmB,CAAC9C,KAAK6C,UAAU,CAAC5C,IAAI,KACnDD,KAAK6C,UAAU,CAAC5C,IAAI,CAACX,MAAM,CAAC+C,KAAK,KAAKf;IAE1C;IAEA,OAAO;AACT"}
@@ -39,6 +39,20 @@ export class SchemaTypeGenerator {
39
39
  this.tsTypes.set(type.name, this.generateTsType(type));
40
40
  }
41
41
  }
42
+ /** The names of the schema's document types, in schema order. */ documentTypeNames() {
43
+ return this.schema.filter((schemaType)=>schemaType.type === 'document').map(({ name })=>name);
44
+ }
45
+ /**
46
+ * Evaluates a projection for one document type, as `*[_type == TYPE][0]PROJECTION` without
47
+ * the `null` for a missing document: the SDK projects documents it has found.
48
+ */ evaluateProjection({ documentType, projection }) {
49
+ const ast = safeParseQuery(`*[_type == ${JSON.stringify(documentType)}][0]${projection}`);
50
+ const typeNode = withoutNull(typeEvaluate(ast, this.schema));
51
+ return {
52
+ stats: walkAndCountQueryTypeNodeStats(typeNode),
53
+ tsType: this.generateTsType(typeNode)
54
+ };
55
+ }
42
56
  getType(typeName) {
43
57
  const tsType = this.tsTypes.get(typeName);
44
58
  const id = this.identifiers.get(typeName);
@@ -324,5 +338,13 @@ export function walkAndCountQueryTypeNodeStats(typeNode) {
324
338
  }
325
339
  }
326
340
  }
341
+ function withoutNull(typeNode) {
342
+ if (typeNode.type !== 'union') return typeNode;
343
+ const of = typeNode.of.filter((member)=>member.type !== 'null');
344
+ return of.length === 1 ? of[0] : {
345
+ ...typeNode,
346
+ of
347
+ };
348
+ }
327
349
 
328
350
  //# sourceMappingURL=schemaTypeGenerator.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/schemaTypeGenerator.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type InlineTypeNode,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n typeEvaluate,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nimport {safeParseQuery} from '../safeParseQuery.js'\nimport {ARRAY_OF, INTERNAL_REFERENCE_SYMBOL} from './constants.js'\nimport {\n getFilterArrayUnionType,\n getUniqueIdentifierForName,\n isIdentifierName,\n weakMapMemo,\n} from './helpers.js'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types.js'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n evaluateQuery = weakMapMemo(\n // eslint-disable-next-line unicorn/consistent-function-scoping\n ({query}: Pick<ExtractedQuery, 'query'>): {stats: TypeEvaluationStats; tsType: t.TSType} => {\n const ast = safeParseQuery(query)\n const typeNode = typeEvaluate(ast, this.schema)\n const tsType = this.generateTsType(typeNode)\n const stats = walkAndCountQueryTypeNodeStats(typeNode)\n return {stats, tsType}\n },\n )\n private arrayOfUsed = false\n\n private identifiers = new Map<string, t.Identifier>()\n\n private tsTypes = new Map<string, t.TSType>()\n\n constructor(schema: SchemaType) {\n this.schema = schema\n\n const uniqueTypeNames = new Set<string>()\n for (const type of schema) {\n if (uniqueTypeNames.has(type.name)) {\n throw new Error(\n `Duplicate type name \"${type.name}\" in schema. Type names must be unique within the same schema.`,\n )\n }\n uniqueTypeNames.add(type.name)\n }\n\n for (const type of schema) {\n const currentIdentifierNames = new Set([...this.identifiers.values()].map((id) => id.name))\n const uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames)\n this.identifiers.set(type.name, uniqueIdentifier)\n }\n\n for (const type of schema) {\n this.tsTypes.set(type.name, this.generateTsType(type))\n }\n }\n\n getType(typeName: string): {id: t.Identifier; tsType: t.TSType} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {id, tsType}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n isArrayOfUsed(): boolean {\n return this.arrayOfUsed\n }\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n\n typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n /**\n * Helper function used to generate TS types for arrays of inline types, or arrays of inline types\n * wrapped in the ArrayOf wrapper that adds _key prop\n */\n private generateArrayOfTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n this.arrayOfUsed = true\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(ARRAY_OF, t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference | t.TSUnionType {\n // if it's an array of a single inline type, wrap it in ArrayOf\n if (typeNode.of.type === 'inline') {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // if it's not an inline object and not a union, wrap in Array\n if (typeNode.of.type !== 'union') {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // if it's not a union type or all of the union type members are non-inlines, wrap type in Array\n if (typeNode.of.of.every((unionTypeNode) => unionTypeNode.type !== 'inline')) {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // all the union types nodes are inline\n if (typeNode.of.of.every((unionMember) => unionMember.type === 'inline')) {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // some of the union types are inlines, while some are not - split and recurse\n const arrayOfNonInline = getFilterArrayUnionType(typeNode, (member) => member.type !== 'inline')\n const arrayOfInline = getFilterArrayUnionType(typeNode, (member) => member.type === 'inline')\n\n return t.tsUnionType([\n this.generateArrayTsType(arrayOfNonInline),\n this.generateArrayTsType(arrayOfInline),\n ])\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentTsType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateTsObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n\n private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {\n const id = this.identifiers.get(typeNode.name)\n if (!id) {\n // Not found in schema, return unknown type\n return t.addComment(\n t.tsUnknownKeyword(),\n 'trailing',\n ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n true,\n )\n }\n\n return t.tsTypeReference(id)\n }\n\n // Helper function used to generate TS types for object type nodes.\n private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {\n const props: t.TSPropertySignature[] = []\n for (const [key, attribute] of Object.entries(typeNode.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'inline': {\n const resolved = this.generateInlineTsType(rest)\n // if object rest is unknown, we can't generate a type literal for it\n if (t.isTSUnknownKeyword(resolved)) return resolved\n return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])\n }\n case 'object': {\n for (const [key, attribute] of Object.entries(rest.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n break\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n default: {\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${rest.type}\" not found in schema`)\n }\n }\n }\n\n if (typeNode.dereferencesTo) {\n const derefType = Object.assign(\n t.tsPropertySignature(\n INTERNAL_REFERENCE_SYMBOL,\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n ),\n {computed: true, optional: true},\n )\n props.push(derefType)\n }\n\n return t.tsTypeLiteral(props)\n }\n\n // Helper function used to generate TS types for object properties.\n private generateTsObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.generateTsType(attribute.value)\n const keyNode = isIdentifierName(key) ? t.identifier(key) : t.stringLiteral(key)\n const propertySignature = t.tsPropertySignature(keyNode, t.tsTypeAnnotation(type))\n propertySignature.optional = attribute.optional\n\n return propertySignature\n }\n\n private generateTsType(\n typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode,\n ): t.TSType {\n switch (typeNode.type) {\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n case 'number': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.numericLiteral(typeNode.value))\n }\n return t.tsNumberKeyword()\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n\n default: {\n throw new Error(\n `Encountered unsupported node type \"${\n // @ts-expect-error This should never happen\n typeNode.type\n }\" while generating schema types`,\n )\n }\n }\n }\n\n // Helper function used to generate TS types for union type nodes.\n private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {\n if (typeNode.of.length === 0) return t.tsNeverKeyword()\n if (typeNode.of.length === 1) return this.generateTsType(typeNode.of[0]!)\n return t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)))\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'array': {\n const acc = walkAndCountQueryTypeNodeStats(typeNode.of)\n acc.allTypes += 1 // count the array type itself\n return acc\n }\n case 'object': {\n // if the rest is unknown, we count it as one unknown type\n if (typeNode.rest && typeNode.rest.type === 'unknown') {\n return {allTypes: 2, emptyUnions: 0, unknownTypes: 1} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, emptyUnions: 0, unknownTypes: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n const attrs = Object.values(typeNode.attributes)\n let acc = restStats\n for (const attribute of attrs) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, emptyUnions: 1, unknownTypes: 0}\n }\n\n let acc = {allTypes: 1, emptyUnions: 0, unknownTypes: 0} // count the union type itself\n for (const type of typeNode.of) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(type)\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'unknown': {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 1}\n }\n default: {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 0}\n }\n }\n}\n"],"names":["t","typeEvaluate","safeParseQuery","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","getFilterArrayUnionType","getUniqueIdentifierForName","isIdentifierName","weakMapMemo","SchemaTypeGenerator","schema","evaluateQuery","query","ast","typeNode","tsType","generateTsType","stats","walkAndCountQueryTypeNodeStats","arrayOfUsed","identifiers","Map","tsTypes","uniqueTypeNames","Set","type","has","name","Error","add","currentIdentifierNames","values","map","id","uniqueIdentifier","set","getType","typeName","get","undefined","hasType","isArrayOfUsed","Symbol","iterator","typeNames","schemaType","generateArrayOfTsType","typeNodes","of","tsTypeReference","tsTypeParameterInstantiation","generateArrayTsType","identifier","every","unionTypeNode","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","generateDocumentTsType","document","props","Object","entries","attributes","key","node","generateTsObjectProperty","tsTypeLiteral","generateInlineTsType","addComment","tsUnknownKeyword","generateObjectTsType","attribute","push","rest","resolved","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","tsLiteralType","stringLiteral","computed","optional","value","keyNode","propertySignature","booleanLiteral","tsBooleanKeyword","tsNullKeyword","numericLiteral","tsNumberKeyword","tsStringKeyword","generateUnionTsType","length","tsNeverKeyword","acc","allTypes","emptyUnions","unknownTypes","restStats","attrs"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AACjC,SAQEC,YAAY,QAGP,UAAS;AAEhB,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,QAAQ,EAAEC,yBAAyB,QAAO,iBAAgB;AAClE,SACEC,uBAAuB,EACvBC,0BAA0B,EAC1BC,gBAAgB,EAChBC,WAAW,QACN,eAAc;AAGrB,OAAO,MAAMC;IACKC,OAAkB;IAClCC,gBAAgBH,YACd,+DAA+D;IAC/D,CAAC,EAACI,KAAK,EAAgC;QACrC,MAAMC,MAAMX,eAAeU;QAC3B,MAAME,WAAWb,aAAaY,KAAK,IAAI,CAACH,MAAM;QAC9C,MAAMK,SAAS,IAAI,CAACC,cAAc,CAACF;QACnC,MAAMG,QAAQC,+BAA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,UAAUD,IAAIC,QAAQ,GAAGA;wBACzBC,aAAaF,IAAIE,WAAW,GAAGA;wBAC/BC,cAAcH,IAAIG,YAAY,GAAGA;oBACnC;gBACF;gBACA,OAAOH;YACT;QACA,KAAK;YAAS;gBACZ,IAAIvF,SAASkC,EAAE,CAACmD,MAAM,KAAK,GAAG;oBAC5B,OAAO;wBAACG,UAAU;wBAAGC,aAAa;wBAAGC,cAAc;oBAAC;gBACtD;gBAEA,IAAIH,MAAM;oBAACC,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC,EAAE,8BAA8B;;gBACvF,KAAK,MAAM/E,QAAQX,SAASkC,EAAE,CAAE;oBAC9B,MAAM,EAACsD,QAAQ,EAAEC,WAAW,EAAEC,YAAY,EAAC,GAAGtF,+BAA+BO;oBAC7E4E,MAAM;wBACJC,UAAUD,IAAIC,QAAQ,GAAGA;wBACzBC,aAAaF,IAAIE,WAAW,GAAGA;wBAC/BC,cAAcH,IAAIG,YAAY,GAAGA;oBACnC;gBACF;gBACA,OAAOH;YACT;QACA,KAAK;YAAW;gBACd,OAAO;oBAACC,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC;YACtD;QACA;YAAS;gBACP,OAAO;oBAACF,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC;YACtD;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/schemaTypeGenerator.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type InlineTypeNode,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n typeEvaluate,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nimport {safeParseQuery} from '../safeParseQuery.js'\nimport {ARRAY_OF, INTERNAL_REFERENCE_SYMBOL} from './constants.js'\nimport {\n getFilterArrayUnionType,\n getUniqueIdentifierForName,\n isIdentifierName,\n weakMapMemo,\n} from './helpers.js'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types.js'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n evaluateQuery = weakMapMemo(\n // eslint-disable-next-line unicorn/consistent-function-scoping\n ({query}: Pick<ExtractedQuery, 'query'>): {stats: TypeEvaluationStats; tsType: t.TSType} => {\n const ast = safeParseQuery(query)\n const typeNode = typeEvaluate(ast, this.schema)\n const tsType = this.generateTsType(typeNode)\n const stats = walkAndCountQueryTypeNodeStats(typeNode)\n return {stats, tsType}\n },\n )\n private arrayOfUsed = false\n\n private identifiers = new Map<string, t.Identifier>()\n\n private tsTypes = new Map<string, t.TSType>()\n\n constructor(schema: SchemaType) {\n this.schema = schema\n\n const uniqueTypeNames = new Set<string>()\n for (const type of schema) {\n if (uniqueTypeNames.has(type.name)) {\n throw new Error(\n `Duplicate type name \"${type.name}\" in schema. Type names must be unique within the same schema.`,\n )\n }\n uniqueTypeNames.add(type.name)\n }\n\n for (const type of schema) {\n const currentIdentifierNames = new Set([...this.identifiers.values()].map((id) => id.name))\n const uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames)\n this.identifiers.set(type.name, uniqueIdentifier)\n }\n\n for (const type of schema) {\n this.tsTypes.set(type.name, this.generateTsType(type))\n }\n }\n\n /** The names of the schema's document types, in schema order. */\n documentTypeNames(): string[] {\n return this.schema.filter((schemaType) => schemaType.type === 'document').map(({name}) => name)\n }\n\n /**\n * Evaluates a projection for one document type, as `*[_type == TYPE][0]PROJECTION` without\n * the `null` for a missing document: the SDK projects documents it has found.\n */\n evaluateProjection({documentType, projection}: {documentType: string; projection: string}): {\n stats: TypeEvaluationStats\n tsType: t.TSType\n } {\n const ast = safeParseQuery(`*[_type == ${JSON.stringify(documentType)}][0]${projection}`)\n const typeNode = withoutNull(typeEvaluate(ast, this.schema))\n return {stats: walkAndCountQueryTypeNodeStats(typeNode), tsType: this.generateTsType(typeNode)}\n }\n\n getType(typeName: string): {id: t.Identifier; tsType: t.TSType} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {id, tsType}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n isArrayOfUsed(): boolean {\n return this.arrayOfUsed\n }\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n\n typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n /**\n * Helper function used to generate TS types for arrays of inline types, or arrays of inline types\n * wrapped in the ArrayOf wrapper that adds _key prop\n */\n private generateArrayOfTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n this.arrayOfUsed = true\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(ARRAY_OF, t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference | t.TSUnionType {\n // if it's an array of a single inline type, wrap it in ArrayOf\n if (typeNode.of.type === 'inline') {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // if it's not an inline object and not a union, wrap in Array\n if (typeNode.of.type !== 'union') {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // if it's not a union type or all of the union type members are non-inlines, wrap type in Array\n if (typeNode.of.of.every((unionTypeNode) => unionTypeNode.type !== 'inline')) {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // all the union types nodes are inline\n if (typeNode.of.of.every((unionMember) => unionMember.type === 'inline')) {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // some of the union types are inlines, while some are not - split and recurse\n const arrayOfNonInline = getFilterArrayUnionType(typeNode, (member) => member.type !== 'inline')\n const arrayOfInline = getFilterArrayUnionType(typeNode, (member) => member.type === 'inline')\n\n return t.tsUnionType([\n this.generateArrayTsType(arrayOfNonInline),\n this.generateArrayTsType(arrayOfInline),\n ])\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentTsType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateTsObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n\n private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {\n const id = this.identifiers.get(typeNode.name)\n if (!id) {\n // Not found in schema, return unknown type\n return t.addComment(\n t.tsUnknownKeyword(),\n 'trailing',\n ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n true,\n )\n }\n\n return t.tsTypeReference(id)\n }\n\n // Helper function used to generate TS types for object type nodes.\n private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {\n const props: t.TSPropertySignature[] = []\n for (const [key, attribute] of Object.entries(typeNode.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'inline': {\n const resolved = this.generateInlineTsType(rest)\n // if object rest is unknown, we can't generate a type literal for it\n if (t.isTSUnknownKeyword(resolved)) return resolved\n return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])\n }\n case 'object': {\n for (const [key, attribute] of Object.entries(rest.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n break\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n default: {\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${rest.type}\" not found in schema`)\n }\n }\n }\n\n if (typeNode.dereferencesTo) {\n const derefType = Object.assign(\n t.tsPropertySignature(\n INTERNAL_REFERENCE_SYMBOL,\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n ),\n {computed: true, optional: true},\n )\n props.push(derefType)\n }\n\n return t.tsTypeLiteral(props)\n }\n\n // Helper function used to generate TS types for object properties.\n private generateTsObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.generateTsType(attribute.value)\n const keyNode = isIdentifierName(key) ? t.identifier(key) : t.stringLiteral(key)\n const propertySignature = t.tsPropertySignature(keyNode, t.tsTypeAnnotation(type))\n propertySignature.optional = attribute.optional\n\n return propertySignature\n }\n\n private generateTsType(\n typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode,\n ): t.TSType {\n switch (typeNode.type) {\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n case 'number': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.numericLiteral(typeNode.value))\n }\n return t.tsNumberKeyword()\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n\n default: {\n throw new Error(\n `Encountered unsupported node type \"${\n // @ts-expect-error This should never happen\n typeNode.type\n }\" while generating schema types`,\n )\n }\n }\n }\n\n // Helper function used to generate TS types for union type nodes.\n private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {\n if (typeNode.of.length === 0) return t.tsNeverKeyword()\n if (typeNode.of.length === 1) return this.generateTsType(typeNode.of[0]!)\n return t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)))\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'array': {\n const acc = walkAndCountQueryTypeNodeStats(typeNode.of)\n acc.allTypes += 1 // count the array type itself\n return acc\n }\n case 'object': {\n // if the rest is unknown, we count it as one unknown type\n if (typeNode.rest && typeNode.rest.type === 'unknown') {\n return {allTypes: 2, emptyUnions: 0, unknownTypes: 1} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, emptyUnions: 0, unknownTypes: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n const attrs = Object.values(typeNode.attributes)\n let acc = restStats\n for (const attribute of attrs) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, emptyUnions: 1, unknownTypes: 0}\n }\n\n let acc = {allTypes: 1, emptyUnions: 0, unknownTypes: 0} // count the union type itself\n for (const type of typeNode.of) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(type)\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'unknown': {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 1}\n }\n default: {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 0}\n }\n }\n}\n\nfunction withoutNull(typeNode: TypeNode): TypeNode {\n if (typeNode.type !== 'union') return typeNode\n const of = typeNode.of.filter((member) => member.type !== 'null')\n return of.length === 1 ? of[0]! : {...typeNode, of}\n}\n"],"names":["t","typeEvaluate","safeParseQuery","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","getFilterArrayUnionType","getUniqueIdentifierForName","isIdentifierName","weakMapMemo","SchemaTypeGenerator","schema","evaluateQuery","query","ast","typeNode","tsType","generateTsType","stats","walkAndCountQueryTypeNodeStats","arrayOfUsed","identifiers","Map","tsTypes","uniqueTypeNames","Set","type","has","name","Error","add","currentIdentifierNames","values","map","id","uniqueIdentifier","set","documentTypeNames","filter","schemaType","evaluateProjection","documentType","projection","JSON","stringify","withoutNull","getType","typeName","get","undefined","hasType","isArrayOfUsed","Symbol","iterator","typeNames","generateArrayOfTsType","typeNodes","of","tsTypeReference","tsTypeParameterInstantiation","generateArrayTsType","identifier","every","unionTypeNode","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","generateDocumentTsType","document","props","Object","entries","attributes","key","node","generateTsObjectProperty","tsTypeLiteral","generateInlineTsType","addComment","tsUnknownKeyword","generateObjectTsType","attribute","push","rest","resolved","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","tsLiteralType","stringLiteral","computed","optional","value","keyNode","propertySignature","booleanLiteral","tsBooleanKeyword","tsNullKeyword","numericLiteral","tsNumberKeyword","tsStringKeyword","generateUnionTsType","length","tsNeverKeyword","acc","allTypes","emptyUnions","unknownTypes","restStats","attrs"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AACjC,SAQEC,YAAY,QAGP,UAAS;AAEhB,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,QAAQ,EAAEC,yBAAyB,QAAO,iBAAgB;AAClE,SACEC,uBAAuB,EACvBC,0BAA0B,EAC1BC,gBAAgB,EAChBC,WAAW,QACN,eAAc;AAGrB,OAAO,MAAMC;IACKC,OAAkB;IAClCC,gBAAgBH,YACd,+DAA+D;IAC/D,CAAC,EAACI,KAAK,EAAgC;QACrC,MAAMC,MAAMX,eAAeU;QAC3B,MAAME,WAAWb,aAAaY,KAAK,IAAI,CAACH,MAAM;QAC9C,MAAMK,SAAS,IAAI,CAACC,cAAc,CAACF;QACnC,MAAMG,QAAQC,+BAA+BJ;QAC7C,OAAO;YAACG;YAAOF;QAAM;IACvB,GACD;IACOI,cAAc,MAAK;IAEnBC,cAAc,IAAIC,MAA2B;IAE7CC,UAAU,IAAID,MAAuB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rC,IAAIA,SAASW,IAAI,KAAK,SAAS,OAAOX;IACtC,MAAM0C,KAAK1C,SAAS0C,EAAE,CAACnB,MAAM,CAAC,CAAC4B,SAAWA,OAAOxC,IAAI,KAAK;IAC1D,OAAO+B,GAAGmD,MAAM,KAAK,IAAInD,EAAE,CAAC,EAAE,GAAI;QAAC,GAAG1C,QAAQ;QAAE0C;IAAE;AACpD"}
@@ -2,7 +2,7 @@
2
2
  import * as t from '@babel/types';
3
3
  import { createSelector } from 'reselect';
4
4
  import { resultSuffix } from '../casing.js';
5
- import { ALL_SANITY_SCHEMA_TYPES, ARRAY_OF, INTERNAL_REFERENCE_SYMBOL, SANITY_QUERIES } from './constants.js';
5
+ import { ALL_SANITY_SCHEMA_TYPES, ARRAY_OF, INTERNAL_REFERENCE_SYMBOL, SANITY_PROJECTIONS_BY_RESOURCE, SANITY_QUERIES, SANITY_QUERIES_BY_RESOURCE, SANITY_SCHEMAS_BY_RESOURCE } from './constants.js';
6
6
  import { computeOnce, generateCode, getUniqueIdentifierForName, normalizePrintablePath, tsDeclareGlobal, tsDeclareModule } from './helpers.js';
7
7
  import { SchemaTypeGenerator } from './schemaTypeGenerator.js';
8
8
  import { QueryEvaluationError } from './types.js';
@@ -88,13 +88,69 @@ import { QueryEvaluationError } from './types.js';
88
88
  id
89
89
  };
90
90
  });
91
- static async getEvaluatedModules({ queries: extractedModules, reporter: report, root = process.cwd(), schemaTypeDeclarations, schemaTypeGenerator }) {
91
+ /**
92
+ * Evaluates a projection against its document type, or against every document type when it
93
+ * names none. Document types with the same result share one group, so a projection that does
94
+ * not apply to most types does not repeat the same type once per document type.
95
+ *
96
+ * Returns `undefined` for a document type this schema does not have when generating for a
97
+ * resource: datasets of one app can scan the same files, and the type can belong to another.
98
+ */ static evaluateProjection({ extractedProjection, filename, resource, schemaTypeGenerator }) {
99
+ const { documentType, projection } = extractedProjection;
100
+ const documentTypeNames = schemaTypeGenerator.documentTypeNames();
101
+ // Without this, an unknown or non-document type evaluates to `null` and is registered as if
102
+ // it were a result. An object type is a mistake in any run.
103
+ if (documentType !== undefined && !documentTypeNames.includes(documentType)) {
104
+ if (resource && !schemaTypeGenerator.hasType(documentType)) return undefined;
105
+ throw new Error(`"${documentType}" is not a document type in the schema`);
106
+ }
107
+ const documentTypes = documentType === undefined ? documentTypeNames : [
108
+ documentType
109
+ ];
110
+ const groups = new Map();
111
+ const stats = {
112
+ allTypes: 0,
113
+ emptyUnions: 0,
114
+ unknownTypes: 0
115
+ };
116
+ for (const type of documentTypes){
117
+ const result = schemaTypeGenerator.evaluateProjection({
118
+ documentType: type,
119
+ projection
120
+ });
121
+ const key = generateCode(result.tsType);
122
+ const group = groups.get(key);
123
+ if (group) {
124
+ group.documentTypes.push(type);
125
+ continue;
126
+ }
127
+ groups.set(key, {
128
+ documentTypes: [
129
+ type
130
+ ],
131
+ tsType: result.tsType
132
+ });
133
+ stats.allTypes += result.stats.allTypes;
134
+ stats.emptyUnions += result.stats.emptyUnions;
135
+ stats.unknownTypes += result.stats.unknownTypes;
136
+ }
137
+ return {
138
+ extractedProjection,
139
+ filename,
140
+ groups: [
141
+ ...groups.values()
142
+ ],
143
+ stats
144
+ };
145
+ }
146
+ static async getEvaluatedModules({ queries: extractedModules, reporter: report, resource, root = process.cwd(), schemaTypeDeclarations, schemaTypeGenerator }) {
92
147
  if (!extractedModules) {
93
148
  report?.stream.evaluatedModules.end();
94
149
  return [];
95
150
  }
96
151
  const currentIdentifiers = new Set(schemaTypeDeclarations.map(({ id })=>id.name));
97
152
  const evaluatedModuleResults = [];
153
+ const unnamedProjectionsByModule = new Map();
98
154
  for await (const { filename, ...extractedModule } of extractedModules){
99
155
  const queries = [];
100
156
  const errors = [
@@ -139,6 +195,26 @@ import { QueryEvaluationError } from './types.js';
139
195
  }));
140
196
  }
141
197
  }
198
+ const unnamedProjections = [];
199
+ for (const extractedProjection of extractedModule.projections ?? []){
200
+ const { variable } = extractedProjection;
201
+ try {
202
+ const unnamedProjection = TypeGenerator.evaluateProjection({
203
+ extractedProjection,
204
+ filename,
205
+ resource,
206
+ schemaTypeGenerator
207
+ });
208
+ if (unnamedProjection) unnamedProjections.push(unnamedProjection);
209
+ } catch (cause) {
210
+ errors.push(new QueryEvaluationError({
211
+ cause,
212
+ filename,
213
+ variable
214
+ }));
215
+ }
216
+ }
217
+ // Streamed without projections, which are named once every file has been read.
142
218
  const evaluatedModule = {
143
219
  errors,
144
220
  filename,
@@ -146,28 +222,48 @@ import { QueryEvaluationError } from './types.js';
146
222
  };
147
223
  report?.stream.evaluatedModules.emit(evaluatedModule);
148
224
  evaluatedModuleResults.push(evaluatedModule);
225
+ unnamedProjectionsByModule.set(evaluatedModule, unnamedProjections);
149
226
  }
150
227
  report?.stream.evaluatedModules.end();
228
+ // Projections are named after every query, so a query result keeps the name it had before
229
+ // projections were generated, whatever the file order. A projection sharing a query's
230
+ // variable name gets the numeric suffix instead.
231
+ for (const [evaluatedModule, unnamedProjections] of unnamedProjectionsByModule){
232
+ evaluatedModule.projections = unnamedProjections.map((unnamedProjection)=>TypeGenerator.nameProjection({
233
+ currentIdentifiers,
234
+ root,
235
+ unnamedProjection
236
+ }));
237
+ }
151
238
  return evaluatedModuleResults;
152
239
  }
240
+ /**
241
+ * One property per document type, each holding one property per distinct projection string,
242
+ * typed as the union of every result alias generated for that pair.
243
+ */ static getProjectionResultProperties(evaluatedModules) {
244
+ const typesByDocumentType = {};
245
+ for (const { projections = [] } of evaluatedModules){
246
+ for (const { projection, resultsByDocumentType } of projections){
247
+ for (const [documentType, id] of Object.entries(resultsByDocumentType)){
248
+ typesByDocumentType[documentType] ??= {};
249
+ typesByDocumentType[documentType][projection] ??= [];
250
+ typesByDocumentType[documentType][projection].push(id.name);
251
+ }
252
+ }
253
+ }
254
+ return Object.entries(typesByDocumentType).map(([documentType, typesByProjection])=>t.tsPropertySignature(t.stringLiteral(documentType), t.tsTypeAnnotation(t.tsTypeLiteral(Object.entries(typesByProjection).map(([projection, types])=>t.tsPropertySignature(t.stringLiteral(projection), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type)))))))))));
255
+ }
153
256
  static async getQueryMapDeclaration({ evaluatedModules, overloadClientMethods = true }) {
154
257
  if (!overloadClientMethods) return {
155
258
  ast: t.program([]),
156
259
  code: ''
157
260
  };
158
- const queries = evaluatedModules.flatMap((module)=>module.queries);
159
- if (queries.length === 0) return {
261
+ const properties = TypeGenerator.getQueryResultProperties(evaluatedModules);
262
+ if (properties.length === 0) return {
160
263
  ast: t.program([]),
161
264
  code: ''
162
265
  };
163
- const typesByQuerystring = {};
164
- for (const { id, query } of queries){
165
- typesByQuerystring[query] ??= [];
166
- typesByQuerystring[query].push(id.name);
167
- }
168
- const queryReturnInterface = t.tsInterfaceDeclaration(SANITY_QUERIES, null, [], t.tsInterfaceBody(Object.entries(typesByQuerystring).map(([query, types])=>{
169
- return t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type))))));
170
- })));
266
+ const queryReturnInterface = t.tsInterfaceDeclaration(SANITY_QUERIES, null, [], t.tsInterfaceBody(properties));
171
267
  const globalRegistry = t.addComments(tsDeclareGlobal([
172
268
  queryReturnInterface
173
269
  ]), 'leading', [
@@ -198,7 +294,95 @@ import { QueryEvaluationError } from './types.js';
198
294
  code
199
295
  };
200
296
  }
297
+ /**
298
+ * One property per distinct query string, typed as the union of every result type generated
299
+ * for it. Two variables holding the same query text share a key.
300
+ */ static getQueryResultProperties(evaluatedModules) {
301
+ const typesByQuerystring = {};
302
+ for (const { queries } of evaluatedModules){
303
+ for (const { id, query } of queries){
304
+ typesByQuerystring[query] ??= [];
305
+ typesByQuerystring[query].push(id.name);
306
+ }
307
+ }
308
+ return Object.entries(typesByQuerystring).map(([query, types])=>t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type)))))));
309
+ }
310
+ static getResourceRegistryDeclaration({ evaluatedModules, resource }) {
311
+ const key = `${resource.projectId}.${resource.dataset}`;
312
+ const schemas = t.tsInterfaceDeclaration(SANITY_SCHEMAS_BY_RESOURCE, null, [], t.tsInterfaceBody([
313
+ t.tsPropertySignature(t.stringLiteral(key), t.tsTypeAnnotation(t.tsTypeReference(ALL_SANITY_SCHEMA_TYPES)))
314
+ ]));
315
+ // Written even with no queries, and the projection entry below even with no projections. An
316
+ // entry, empty or not, tells consumers this resource is generated, so a query or projection
317
+ // missing from it is a miss rather than a reason to fall back.
318
+ const queries = t.tsInterfaceDeclaration(SANITY_QUERIES_BY_RESOURCE, null, [], t.tsInterfaceBody([
319
+ t.tsPropertySignature(t.stringLiteral(key), t.tsTypeAnnotation(t.tsTypeLiteral(TypeGenerator.getQueryResultProperties(evaluatedModules))))
320
+ ]));
321
+ const projections = t.tsInterfaceDeclaration(SANITY_PROJECTIONS_BY_RESOURCE, null, [], t.tsInterfaceBody([
322
+ t.tsPropertySignature(t.stringLiteral(key), t.tsTypeAnnotation(t.tsTypeLiteral(TypeGenerator.getProjectionResultProperties(evaluatedModules))))
323
+ ]));
324
+ // No `declare module "@sanity/client"` bridge, unlike the flat map. These registries first
325
+ // shipped already global, so no client release needs one, and an augmentation would fail
326
+ // with TS2664 wherever `@sanity/client` is not resolvable from the generated file.
327
+ const ast = t.program([
328
+ t.addComments(tsDeclareGlobal([
329
+ schemas,
330
+ queries,
331
+ projections
332
+ ]), 'leading', [
333
+ {
334
+ type: 'CommentLine',
335
+ value: ` Resource TypeMap: ${key}`
336
+ }
337
+ ])
338
+ ]);
339
+ const code = generateCode(ast);
340
+ return {
341
+ ast,
342
+ code
343
+ };
344
+ }
345
+ /** Declares one result alias per group, with names not yet in `currentIdentifiers`. */ static nameProjection({ currentIdentifiers, root, unnamedProjection: { extractedProjection, filename, groups, stats } }) {
346
+ const { projection, variable } = extractedProjection;
347
+ const trimmedProjection = projection.replaceAll(/(\r\n|\n|\r)/gm, '').trim();
348
+ const declarations = [];
349
+ const resultsByDocumentType = {};
350
+ for (const group of groups){
351
+ const name = groups.length === 1 ? variable.id.name : `${variable.id.name}${pascalCase(group.documentTypes[0])}`;
352
+ const id = getUniqueIdentifierForName(resultSuffix(name), currentIdentifiers);
353
+ currentIdentifiers.add(id.name);
354
+ const ast = t.addComments(t.exportNamedDeclaration(t.tsTypeAliasDeclaration(id, null, group.tsType)), 'leading', [
355
+ {
356
+ type: 'CommentLine',
357
+ value: ` Source: ${normalizePrintablePath(root, filename)}`
358
+ },
359
+ {
360
+ type: 'CommentLine',
361
+ value: ` Variable: ${variable.id.name}`
362
+ },
363
+ {
364
+ type: 'CommentLine',
365
+ value: ` Projection on ${group.documentTypes.join(', ')}: ${trimmedProjection}`
366
+ }
367
+ ]);
368
+ declarations.push({
369
+ ast,
370
+ code: generateCode(ast),
371
+ id
372
+ });
373
+ for (const type of group.documentTypes)resultsByDocumentType[type] = id;
374
+ }
375
+ return {
376
+ ...extractedProjection,
377
+ declarations,
378
+ resultsByDocumentType,
379
+ stats
380
+ };
381
+ }
201
382
  async generateTypes(options) {
383
+ if (options.resource && (!options.resource.projectId || !options.resource.dataset)) {
384
+ throw new TypeError('A typegen resource needs both a projectId and a dataset');
385
+ }
202
386
  const { reporter: report } = options;
203
387
  const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration();
204
388
  const schemaTypeGenerator = this.getSchemaTypeGenerator(options);
@@ -239,12 +423,29 @@ import { QueryEvaluationError } from './types.js';
239
423
  code += query.code;
240
424
  }
241
425
  }
426
+ for (const { projections = [] } of evaluatedModules){
427
+ for (const { declarations } of projections){
428
+ for (const declaration of declarations){
429
+ program.body.push(declaration.ast);
430
+ code += declaration.code;
431
+ }
432
+ }
433
+ }
242
434
  const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({
243
435
  ...options,
244
436
  evaluatedModules
245
437
  });
246
438
  program.body.push(...queryMapDeclaration.ast.body);
247
439
  code += queryMapDeclaration.code;
440
+ if (options.resource) {
441
+ const resourceRegistry = TypeGenerator.getResourceRegistryDeclaration({
442
+ ...options,
443
+ evaluatedModules,
444
+ resource: options.resource
445
+ });
446
+ program.body.push(...resourceRegistry.ast.body);
447
+ code += resourceRegistry.code;
448
+ }
248
449
  report?.event.generatedQueryTypes({
249
450
  queryMapDeclaration
250
451
  });
@@ -254,5 +455,8 @@ import { QueryEvaluationError } from './types.js';
254
455
  };
255
456
  }
256
457
  }
458
+ /** `sanity.imageAsset` to `SanityImageAsset`, for naming a result alias after a document type. */ function pascalCase(value) {
459
+ return value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part)=>part[0].toUpperCase() + part.slice(1)).join('');
460
+ }
257
461
 
258
462
  //# sourceMappingURL=typeGenerator.js.map