@sanity/codegen 5.0.0-next-major.12 → 5.0.0-next-major.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,18 +1,20 @@
1
1
  import fs$1, { readFile } from "node:fs/promises";
2
2
  import json5 from "json5";
3
3
  import * as z from "zod";
4
- import { parse } from "groq-js";
4
+ import { parse, typeEvaluate } from "groq-js";
5
5
  import createDebug from "debug";
6
6
  import glob from "globby";
7
7
  import fs, { existsSync } from "node:fs";
8
8
  import path, { dirname, join, resolve } from "node:path";
9
- import { createRequire } from "node:module";
10
9
  import { fileURLToPath } from "node:url";
11
- import { parse as parse$1, traverse as traverse$1 } from "@babel/core";
10
+ import { createRequire } from "node:module";
11
+ import { parse as parse$1, traverse } from "@babel/core";
12
12
  import * as t from "@babel/types";
13
- import traverse, { Scope } from "@babel/traverse";
13
+ import { Scope } from "@babel/traverse";
14
14
  import { loadConfig, createMatchPath } from "tsconfig-paths";
15
15
  import register from "@babel/register";
16
+ import process from "node:process";
17
+ import { createSelector } from "reselect";
16
18
  import { CodeGenerator } from "@babel/generator";
17
19
  const configDefinition = z.object({
18
20
  path: z.string().or(z.array(z.string())).default([
@@ -62,7 +64,7 @@ function* extractSliceParams(query) {
62
64
  end !== null && (yield end);
63
65
  }
64
66
  }
65
- const __dirname$1 = dirname(new URL(import.meta.url).pathname);
67
+ const __dirname$1 = dirname(fileURLToPath(import.meta.url));
66
68
  function findBabelConfig(path2) {
67
69
  const configPath = join(path2, "babel.config.json");
68
70
  if (existsSync(configPath))
@@ -236,6 +238,17 @@ function resolveExpression({
236
238
  babelConfig,
237
239
  fnArguments
238
240
  });
241
+ if (t.isTSAsExpression(node))
242
+ return resolveExpression({
243
+ node: node.expression,
244
+ scope,
245
+ filename,
246
+ file,
247
+ resolver,
248
+ params,
249
+ babelConfig,
250
+ fnArguments
251
+ });
239
252
  throw new Error(
240
253
  `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
241
254
  );
@@ -417,10 +430,29 @@ function resolveExportSpecifier({
417
430
  cause: `noBinding:${importName}`
418
431
  });
419
432
  }
420
- const __filename$1 = fileURLToPath(import.meta.url), require$2 = createRequire(__filename$1), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
433
+ const isRecord = (value) => (typeof value == "object" || typeof value == "function") && !!value;
434
+ class QueryExtractionError extends Error {
435
+ variable;
436
+ filename;
437
+ constructor({ variable, cause, filename }) {
438
+ super(
439
+ `Error while extracting query ${variable ? `from variable '${variable.id.name}' ` : ""}in ${filename}: ${isRecord(cause) && typeof cause.message == "string" ? cause.message : "Unknown error"}`
440
+ ), this.name = "QueryExtractionError", this.cause = cause, this.variable = variable, this.filename = filename;
441
+ }
442
+ }
443
+ class QueryEvaluationError extends Error {
444
+ variable;
445
+ filename;
446
+ constructor({ variable, cause, filename }) {
447
+ super(
448
+ `Error while evaluating query ${variable ? `from variable '${variable.id.name}' ` : ""}in ${filename}: ${isRecord(cause) && typeof cause.message == "string" ? cause.message : "Unknown error"}`
449
+ ), this.name = "QueryEvaluationError", this.cause = cause, this.variable = variable, this.filename = filename;
450
+ }
451
+ }
452
+ const require$2 = createRequire(import.meta.url), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
421
453
  function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require$2.resolve) {
422
- const queries = [], file = parseSourceFile(source, filename, babelConfig);
423
- return traverse$1(file, {
454
+ const queries = [], errors = [], file = parseSourceFile(source, filename, babelConfig);
455
+ return traverse(file, {
424
456
  // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
425
457
  // The variable name is used as the name of the query result type
426
458
  VariableDeclarator(path2) {
@@ -428,25 +460,23 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
428
460
  if (t.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {
429
461
  if (declarationLeadingCommentContains(path2, ignoreValue))
430
462
  return;
431
- const queryName = `${node.id.name}`, queryResult = resolveExpression({
432
- node: init,
433
- file,
434
- scope,
435
- babelConfig,
436
- filename,
437
- resolver
438
- }), location = node.loc ? {
439
- start: {
440
- ...node.loc?.start
441
- },
442
- end: {
443
- ...node.loc?.end
444
- }
445
- } : {};
446
- queries.push({ name: queryName, result: queryResult, location });
463
+ const { id, start, end } = node, variable = { id, ...start && { start }, ...end && { end } };
464
+ try {
465
+ const query = resolveExpression({
466
+ node: init,
467
+ file,
468
+ scope,
469
+ babelConfig,
470
+ filename,
471
+ resolver
472
+ });
473
+ queries.push({ variable, query, filename });
474
+ } catch (cause) {
475
+ errors.push(new QueryExtractionError({ filename, variable, cause }));
476
+ }
447
477
  }
448
478
  }
449
- }), queries;
479
+ }), { filename, queries, errors };
450
480
  }
451
481
  function declarationLeadingCommentContains(path2, comment) {
452
482
  const variableDeclaration = path2.find((node) => node.isVariableDeclaration());
@@ -498,7 +528,7 @@ function getResolver(cwd) {
498
528
  return resolve2.paths = (request) => require$1.resolve.paths(request), resolve2;
499
529
  }
500
530
  const debug = createDebug("sanity:codegen:findQueries:debug");
501
- async function* findQueriesInPath({
531
+ function findQueriesInPath({
502
532
  path: path2,
503
533
  babelOptions = getBabelConfig(),
504
534
  resolver = getResolver()
@@ -511,138 +541,105 @@ async function* findQueriesInPath({
511
541
  // we never want to look in node_modules
512
542
  onlyFiles: !0
513
543
  }).sort();
514
- for (const filename of files)
515
- if (typeof filename == "string") {
516
- debug(`Found file "${filename}"`);
517
- try {
518
- const source = await fs$1.readFile(filename, "utf8"), queries = findQueriesInSource(source, filename, babelOptions, resolver);
519
- for (const query of queries) {
520
- if (queryNames.has(query.name))
521
- throw new Error(
522
- `Duplicate query name found: "${query.name}". Query names must be unique across all files.`
523
- );
524
- queryNames.add(query.name);
544
+ async function* getQueries() {
545
+ for (const filename of files)
546
+ if (typeof filename == "string") {
547
+ debug(`Found file "${filename}"`);
548
+ try {
549
+ const source = await fs$1.readFile(filename, "utf8"), pluckedModuleResult = findQueriesInSource(source, filename, babelOptions, resolver);
550
+ for (const { variable } of pluckedModuleResult.queries) {
551
+ if (queryNames.has(variable.id.name))
552
+ throw new Error(
553
+ `Duplicate query name found: "${variable.id.name}". Query names must be unique across all files.`
554
+ );
555
+ queryNames.add(variable.id.name);
556
+ }
557
+ yield pluckedModuleResult;
558
+ } catch (cause) {
559
+ debug(`Error in file "${filename}"`, cause), yield {
560
+ filename,
561
+ queries: [],
562
+ errors: [new QueryExtractionError({ cause, filename })]
563
+ };
525
564
  }
526
- yield { type: "queries", filename, queries };
527
- } catch (error) {
528
- debug(`Error in file "${filename}"`, error), yield { type: "error", error, filename };
529
565
  }
530
- }
566
+ }
567
+ return { files, queries: getQueries() };
531
568
  }
532
569
  function registerBabel(babelOptions) {
533
570
  const options = babelOptions || getBabelConfig();
534
571
  register({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
535
572
  }
536
- const REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo", ALL_SCHEMA_TYPES = "AllSanitySchemaTypes";
537
- class TypeGenerator {
538
- // Simple set to keep track of generated type names, to avoid conflicts
539
- generatedTypeName = /* @__PURE__ */ new Set();
540
- // Map between type names and their generated type names, used to resolve the correct generated type name
541
- typeNameMap = /* @__PURE__ */ new Map();
542
- // Map between type nodes and their generated type names, used for query mapping
543
- typeNodeNameMap = /* @__PURE__ */ new Map();
573
+ function resultSuffix(variableName) {
574
+ if (!variableName) return "result";
575
+ const isUpperSnake = /^[A-Z0-9_]+$/.test(variableName), isSnake = /^[a-z0-9_]+$/.test(variableName) && variableName.includes("_");
576
+ return /^[a-z][A-Za-z0-9]*$/.test(variableName) ? `${variableName}Result` : isUpperSnake ? `${variableName}_RESULT` : isSnake ? `${variableName}_result` : `${variableName.replace(/[^A-Za-z0-9]/g, "")}Result`;
577
+ }
578
+ const INTERNAL_REFERENCE_SYMBOL = t.identifier("internalGroqTypeReferenceTo"), ALL_SANITY_SCHEMA_TYPES = t.identifier("AllSanitySchemaTypes"), SANITY_QUERIES = t.identifier("SanityQueries"), RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set();
579
+ RESERVED_IDENTIFIERS.add(SANITY_QUERIES.name);
580
+ RESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name);
581
+ RESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name);
582
+ function normalizePath(root, filename) {
583
+ const resolved = path.resolve(root, filename);
584
+ return path.relative(root, resolved);
585
+ }
586
+ function sanitizeIdentifier(input) {
587
+ return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
588
+ }
589
+ function normalizeIdentifier(input) {
590
+ const sanitized = sanitizeIdentifier(input);
591
+ return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`;
592
+ }
593
+ function getUniqueIdentifierForName(name, currentIdentifiers) {
594
+ const desiredName = normalizeIdentifier(name);
595
+ let resultingName = desiredName, index = 2;
596
+ for (; currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName); )
597
+ resultingName = `${desiredName}_${index}`, index++;
598
+ return t.identifier(resultingName);
599
+ }
600
+ function computeOnce(fn) {
601
+ const ref = { current: void 0, computed: !1 };
602
+ return function() {
603
+ return ref.computed || (ref.current = fn(), ref.computed = !0), ref.current;
604
+ };
605
+ }
606
+ function weakMapMemo(fn) {
607
+ const cache = /* @__PURE__ */ new WeakMap();
608
+ return function(arg) {
609
+ if (cache.has(arg)) return cache.get(arg);
610
+ const result = fn(arg);
611
+ return cache.set(arg, result), result;
612
+ };
613
+ }
614
+ function generateCode(node) {
615
+ return `${new CodeGenerator(node).generate().code.trim()}
616
+
617
+ `;
618
+ }
619
+ class SchemaTypeGenerator {
544
620
  schema;
621
+ tsTypes = /* @__PURE__ */ new Map();
622
+ identifiers = /* @__PURE__ */ new Map();
545
623
  constructor(schema) {
546
- this.schema = schema, this.schema.forEach((s) => {
547
- this.getTypeName(s.name, s);
548
- });
549
- }
550
- /**
551
- * Generate TypeScript types for the given schema
552
- * @returns string
553
- * @internal
554
- * @beta
555
- */
556
- generateSchemaTypes() {
557
- const typeDeclarations = [], schemaNames = /* @__PURE__ */ new Set();
558
- return this.schema.forEach((schema) => {
559
- const typeLiteral = this.getTypeNodeType(schema), schemaName = this.typeNodeNameMap.get(schema);
560
- if (!schemaName)
561
- throw new Error(`Schema name not found for schema ${schema.name}`);
562
- schemaNames.add(schemaName);
563
- const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral);
564
- typeDeclarations.push(t.exportNamedDeclaration(typeAlias));
565
- }), typeDeclarations.push(
566
- t.exportNamedDeclaration(
567
- t.tsTypeAliasDeclaration(
568
- t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),
569
- null,
570
- t.tsUnionType(
571
- [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName)))
572
- )
573
- )
574
- )
575
- ), typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join(`
576
-
577
- `);
578
- }
579
- /**
580
- * Takes a identifier and a type node and generates a type alias for the type node.
581
- * @param identifierName - The name of the type to generated
582
- * @param typeNode - The type node to generate the type for
583
- * @returns
584
- * @internal
585
- * @beta
586
- */
587
- generateTypeNodeTypes(identifierName, typeNode) {
588
- const type = this.getTypeNodeType(typeNode), typeName = this.getTypeName(identifierName, typeNode), typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type);
589
- return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim();
590
- }
591
- static generateKnownTypes() {
592
- const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), "unique"), identifier = t.identifier(REFERENCE_SYMBOL_NAME);
593
- identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator);
594
- const decleration = t.variableDeclaration("const", [t.variableDeclarator(identifier)]);
595
- return decleration.declare = !0, new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim();
596
- }
597
- /**
598
- * Takes a list of queries from the codebase and generates a type declaration
599
- * for SanityClient to consume.
600
- *
601
- * Note: only types that have previously been generated with `generateTypeNodeTypes`
602
- * will be included in the query map.
603
- *
604
- * @param queries - A list of queries to generate a type declaration for
605
- * @returns
606
- * @internal
607
- * @beta
608
- */
609
- generateQueryMap(queries) {
610
- const typesByQuerystring = {};
611
- for (const query of queries) {
612
- const name = this.typeNodeNameMap.get(query.typeNode);
613
- name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
624
+ this.schema = schema;
625
+ const uniqueTypeNames = /* @__PURE__ */ new Set();
626
+ for (const type of schema) {
627
+ if (uniqueTypeNames.has(type.name))
628
+ throw new Error(
629
+ `Duplicate type name "${type.name}" in schema. Type names must be unique within the same schema.`
630
+ );
631
+ uniqueTypeNames.add(type.name);
614
632
  }
615
- const queryReturnInterface = t.tsInterfaceDeclaration(
616
- t.identifier("SanityQueries"),
617
- null,
618
- [],
619
- t.tsInterfaceBody(
620
- Object.entries(typesByQuerystring).map(([query, types]) => t.tsPropertySignature(
621
- t.stringLiteral(query),
622
- t.tsTypeAnnotation(
623
- t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))
624
- )
625
- ))
626
- )
627
- ), declareModule = t.declareModule(
628
- t.stringLiteral("@sanity/client"),
629
- t.blockStatement([queryReturnInterface])
630
- ), clientImport = t.importDeclaration([], t.stringLiteral("@sanity/client"));
631
- return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim();
632
- }
633
- /**
634
- * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these
635
- * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.
636
- * When we reference a type we also keep track of the original name so we can reference the correct type later.
637
- */
638
- getTypeName(name, typeNode) {
639
- const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name));
640
- let generatedName = desiredName, i = 2;
641
- for (; this.generatedTypeName.has(generatedName); )
642
- generatedName = `${desiredName}_${i++}`;
643
- return this.generatedTypeName.add(generatedName), this.typeNameMap.set(name, generatedName), typeNode && this.typeNodeNameMap.set(typeNode, generatedName), generatedName;
633
+ for (const type of schema) {
634
+ const currentIdentifierNames = new Set(
635
+ Array.from(this.identifiers.values()).map((id) => id.name)
636
+ ), uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames);
637
+ this.identifiers.set(type.name, uniqueIdentifier);
638
+ }
639
+ for (const type of schema)
640
+ this.tsTypes.set(type.name, this.generateTsType(type));
644
641
  }
645
- getTypeNodeType(typeNode) {
642
+ generateTsType(typeNode) {
646
643
  switch (typeNode.type) {
647
644
  case "string":
648
645
  return typeNode.value !== void 0 ? t.tsLiteralType(t.stringLiteral(typeNode.value)) : t.tsStringKeyword();
@@ -653,9 +650,9 @@ class TypeGenerator {
653
650
  case "unknown":
654
651
  return t.tsUnknownKeyword();
655
652
  case "document":
656
- return this.generateDocumentType(typeNode);
653
+ return this.generateDocumentTsType(typeNode);
657
654
  case "type":
658
- return this.getTypeNodeType(typeNode.value);
655
+ return this.generateTsType(typeNode.value);
659
656
  case "array":
660
657
  return this.generateArrayTsType(typeNode);
661
658
  case "object":
@@ -667,20 +664,20 @@ class TypeGenerator {
667
664
  case "null":
668
665
  return t.tsNullKeyword();
669
666
  default:
670
- throw new Error(`Type "${typeNode.type}" not found in schema`);
667
+ throw new Error(
668
+ `Encountered unsupported node type "${// @ts-expect-error This should never happen
669
+ typeNode.type}" while generating schema types`
670
+ );
671
671
  }
672
672
  }
673
673
  // Helper function used to generate TS types for array type nodes.
674
674
  generateArrayTsType(typeNode) {
675
- const typeNodes = this.getTypeNodeType(typeNode.of);
676
- return t.tsTypeReference(
677
- t.identifier("Array"),
678
- t.tsTypeParameterInstantiation([typeNodes])
679
- );
675
+ const typeNodes = this.generateTsType(typeNode.of);
676
+ return t.tsTypeReference(t.identifier("Array"), t.tsTypeParameterInstantiation([typeNodes]));
680
677
  }
681
678
  // Helper function used to generate TS types for object properties.
682
- generateObjectProperty(key, attribute) {
683
- const type = this.getTypeNodeType(attribute.value), propertySignature = t.tsPropertySignature(
679
+ generateTsObjectProperty(key, attribute) {
680
+ const type = this.generateTsType(attribute.value), propertySignature = t.tsPropertySignature(
684
681
  t.identifier(sanitizeIdentifier(key)),
685
682
  t.tsTypeAnnotation(type)
686
683
  );
@@ -690,16 +687,16 @@ class TypeGenerator {
690
687
  generateObjectTsType(typeNode) {
691
688
  const props = [];
692
689
  Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
693
- props.push(this.generateObjectProperty(key, attribute));
690
+ props.push(this.generateTsObjectProperty(key, attribute));
694
691
  });
695
692
  const rest = typeNode.rest;
696
- if (rest !== void 0)
693
+ if (rest)
697
694
  switch (rest.type) {
698
695
  case "unknown":
699
696
  return t.tsUnknownKeyword();
700
697
  case "object": {
701
698
  Object.entries(rest.attributes).forEach(([key, attribute]) => {
702
- props.push(this.generateObjectProperty(key, attribute));
699
+ props.push(this.generateTsObjectProperty(key, attribute));
703
700
  });
704
701
  break;
705
702
  }
@@ -710,56 +707,243 @@ class TypeGenerator {
710
707
  default:
711
708
  throw new Error(`Type "${rest.type}" not found in schema`);
712
709
  }
713
- if (typeNode.dereferencesTo !== void 0) {
714
- const derefType = t.tsPropertySignature(
715
- t.identifier(REFERENCE_SYMBOL_NAME),
716
- t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo)))
710
+ if (typeNode.dereferencesTo) {
711
+ const derefType = Object.assign(
712
+ t.tsPropertySignature(
713
+ INTERNAL_REFERENCE_SYMBOL,
714
+ t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo)))
715
+ ),
716
+ { computed: !0, optional: !0 }
717
717
  );
718
- derefType.computed = !0, derefType.optional = !0, props.push(derefType);
718
+ props.push(derefType);
719
719
  }
720
720
  return t.tsTypeLiteral(props);
721
721
  }
722
722
  generateInlineTsType(typeNode) {
723
- const referencedTypeNode = this.schema.find((schema) => schema.name === typeNode.name);
724
- if (referencedTypeNode === void 0) {
725
- const generatedName2 = this.typeNameMap.get(typeNode.name);
726
- if (generatedName2)
727
- return t.tsTypeReference(t.identifier(generatedName2));
728
- const missing = t.tsUnknownKeyword();
729
- return missing.trailingComments = [
730
- {
731
- type: "CommentLine",
732
- value: ` Unable to locate the referenced type "${typeNode.name}" in schema`
733
- }
734
- ], missing;
735
- }
736
- const generatedName = this.typeNameMap.get(referencedTypeNode.name);
737
- return generatedName ? t.tsTypeReference(t.identifier(generatedName)) : t.tsUnknownKeyword();
723
+ const id = this.identifiers.get(typeNode.name);
724
+ return id ? t.tsTypeReference(id) : t.addComment(
725
+ t.tsUnknownKeyword(),
726
+ "trailing",
727
+ ` Unable to locate the referenced type "${typeNode.name}" in schema`,
728
+ !0
729
+ );
738
730
  }
739
731
  // Helper function used to generate TS types for union type nodes.
740
732
  generateUnionTsType(typeNode) {
741
- if (typeNode.of.length === 0)
742
- return t.tsNeverKeyword();
743
- if (typeNode.of.length === 1)
744
- return this.getTypeNodeType(typeNode.of[0]);
745
- const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node));
746
- return t.tsUnionType(typeNodes);
733
+ return typeNode.of.length === 0 ? t.tsNeverKeyword() : typeNode.of.length === 1 ? this.generateTsType(typeNode.of[0]) : t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)));
747
734
  }
748
735
  // Helper function used to generate TS types for document type nodes.
749
- generateDocumentType(document) {
736
+ generateDocumentTsType(document) {
750
737
  const props = Object.entries(document.attributes).map(
751
- ([key, node]) => this.generateObjectProperty(key, node)
738
+ ([key, node]) => this.generateTsObjectProperty(key, node)
752
739
  );
753
740
  return t.tsTypeLiteral(props);
754
741
  }
742
+ typeNames() {
743
+ return this.schema.map((schemaType) => schemaType.name);
744
+ }
745
+ getType(typeName) {
746
+ const tsType = this.tsTypes.get(typeName), id = this.identifiers.get(typeName);
747
+ if (tsType && id) return { tsType, id };
748
+ }
749
+ hasType(typeName) {
750
+ return this.tsTypes.has(typeName);
751
+ }
752
+ evaluateQuery = weakMapMemo(
753
+ ({ query }) => {
754
+ const ast = safeParseQuery(query), typeNode = typeEvaluate(ast, this.schema), tsType = this.generateTsType(typeNode), stats = walkAndCountQueryTypeNodeStats(typeNode);
755
+ return { tsType, stats };
756
+ }
757
+ );
758
+ *[Symbol.iterator]() {
759
+ for (const { name } of this.schema)
760
+ yield { name, ...this.getType(name) };
761
+ }
755
762
  }
756
- function uppercaseFirstLetter(input) {
757
- return input.charAt(0).toUpperCase() + input.slice(1);
763
+ function walkAndCountQueryTypeNodeStats(typeNode) {
764
+ switch (typeNode.type) {
765
+ case "unknown":
766
+ return { allTypes: 1, unknownTypes: 1, emptyUnions: 0 };
767
+ case "array": {
768
+ const acc = walkAndCountQueryTypeNodeStats(typeNode.of);
769
+ return acc.allTypes += 1, acc;
770
+ }
771
+ case "object": {
772
+ if (typeNode.rest && typeNode.rest.type === "unknown")
773
+ return { allTypes: 2, unknownTypes: 1, emptyUnions: 0 };
774
+ const restStats = typeNode.rest ? walkAndCountQueryTypeNodeStats(typeNode.rest) : { allTypes: 0, unknownTypes: 0, emptyUnions: 0 };
775
+ return restStats.allTypes += 1, Object.values(typeNode.attributes).reduce((acc, attribute) => {
776
+ const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(
777
+ attribute.value
778
+ );
779
+ return {
780
+ allTypes: acc.allTypes + allTypes,
781
+ unknownTypes: acc.unknownTypes + unknownTypes,
782
+ emptyUnions: acc.emptyUnions + emptyUnions
783
+ };
784
+ }, restStats);
785
+ }
786
+ case "union":
787
+ return typeNode.of.length === 0 ? { allTypes: 1, unknownTypes: 0, emptyUnions: 1 } : typeNode.of.reduce(
788
+ (acc, type) => {
789
+ const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(type);
790
+ return {
791
+ allTypes: acc.allTypes + allTypes,
792
+ unknownTypes: acc.unknownTypes + unknownTypes,
793
+ emptyUnions: acc.emptyUnions + emptyUnions
794
+ };
795
+ },
796
+ { allTypes: 1, unknownTypes: 0, emptyUnions: 0 }
797
+ // count the union type itself
798
+ );
799
+ default:
800
+ return { allTypes: 1, unknownTypes: 0, emptyUnions: 0 };
801
+ }
758
802
  }
759
- function sanitizeIdentifier(input) {
760
- return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
803
+ class TypeGenerator {
804
+ getInternalReferenceSymbolDeclaration = computeOnce(() => {
805
+ const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), "unique"), id = INTERNAL_REFERENCE_SYMBOL;
806
+ id.typeAnnotation = t.tsTypeAnnotation(typeOperator);
807
+ const declaration = t.variableDeclaration("const", [t.variableDeclarator(id)]);
808
+ declaration.declare = !0;
809
+ const ast = t.exportNamedDeclaration(declaration), code = generateCode(ast);
810
+ return { id, code, ast };
811
+ });
812
+ getSchemaTypeGenerator = createSelector(
813
+ [(options) => options.schema],
814
+ (schema) => new SchemaTypeGenerator(schema)
815
+ );
816
+ getSchemaTypeDeclarations = createSelector(
817
+ [
818
+ (options) => options.root,
819
+ (options) => options.schemaPath,
820
+ this.getSchemaTypeGenerator
821
+ ],
822
+ (root = process.cwd(), schemaPath, schema) => Array.from(schema).map(({ id, name, tsType }, index) => {
823
+ const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType);
824
+ let ast = t.exportNamedDeclaration(typeAlias);
825
+ index === 0 && schemaPath && (ast = t.addComments(ast, "leading", [
826
+ { type: "CommentLine", value: ` Source: ${normalizePath(root, schemaPath)}` }
827
+ ]));
828
+ const code = generateCode(ast);
829
+ return { id, code, name, tsType, ast };
830
+ })
831
+ );
832
+ getAllSanitySchemaTypesDeclaration = createSelector(
833
+ [this.getSchemaTypeDeclarations],
834
+ (schemaTypes) => {
835
+ const ast = t.exportNamedDeclaration(
836
+ t.tsTypeAliasDeclaration(
837
+ ALL_SANITY_SCHEMA_TYPES,
838
+ null,
839
+ schemaTypes.length ? t.tsUnionType(schemaTypes.map(({ id }) => t.tsTypeReference(id))) : t.tsNeverKeyword()
840
+ )
841
+ ), code = generateCode(ast);
842
+ return { id: ALL_SANITY_SCHEMA_TYPES, code, ast };
843
+ }
844
+ );
845
+ static async getEvaluatedModules({
846
+ root = process.cwd(),
847
+ reporter: report,
848
+ schemaTypeGenerator,
849
+ schemaTypeDeclarations,
850
+ queries: extractedModules
851
+ }) {
852
+ if (!extractedModules)
853
+ return report?.stream.evaluatedModules.end(), [];
854
+ const currentIdentifiers = new Set(schemaTypeDeclarations.map(({ id }) => id.name)), evaluatedModuleResults = [];
855
+ for await (const { filename, ...extractedModule } of extractedModules) {
856
+ const queries = [], errors = [...extractedModule.errors];
857
+ for (const extractedQuery of extractedModule.queries) {
858
+ const { variable } = extractedQuery;
859
+ try {
860
+ const { tsType, stats } = schemaTypeGenerator.evaluateQuery(extractedQuery), id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers), typeAlias = t.tsTypeAliasDeclaration(id, null, tsType), trimmedQuery = extractedQuery.query.replace(/(\r\n|\n|\r)/gm, "").trim(), ast = t.addComments(t.exportNamedDeclaration(typeAlias), "leading", [
861
+ { type: "CommentLine", value: ` Source: ${normalizePath(root, filename)}` },
862
+ { type: "CommentLine", value: ` Variable: ${variable.id.name}` },
863
+ { type: "CommentLine", value: ` Query: ${trimmedQuery}` }
864
+ ]), evaluatedQueryResult = {
865
+ id,
866
+ code: generateCode(ast),
867
+ ast,
868
+ stats,
869
+ tsType,
870
+ ...extractedQuery
871
+ };
872
+ currentIdentifiers.add(id.name), queries.push(evaluatedQueryResult);
873
+ } catch (cause) {
874
+ errors.push(new QueryEvaluationError({ variable, cause, filename }));
875
+ }
876
+ }
877
+ const evaluatedModule = {
878
+ filename,
879
+ queries,
880
+ errors
881
+ };
882
+ report?.stream.evaluatedModules.emit(evaluatedModule), evaluatedModuleResults.push(evaluatedModule);
883
+ }
884
+ return report?.stream.evaluatedModules.end(), evaluatedModuleResults;
885
+ }
886
+ static async getQueryMapDeclaration({
887
+ overloadClientMethods = !0,
888
+ evaluatedModules
889
+ }) {
890
+ if (!overloadClientMethods) return { code: "", ast: t.program([]) };
891
+ const queries = evaluatedModules.flatMap((module) => module.queries);
892
+ if (!queries.length) return { code: "", ast: t.program([]) };
893
+ const typesByQuerystring = {};
894
+ for (const { id, query } of queries)
895
+ typesByQuerystring[query] ??= [], typesByQuerystring[query].push(id.name);
896
+ const queryReturnInterface = t.tsInterfaceDeclaration(
897
+ SANITY_QUERIES,
898
+ null,
899
+ [],
900
+ t.tsInterfaceBody(
901
+ Object.entries(typesByQuerystring).map(([query, types]) => t.tsPropertySignature(
902
+ t.stringLiteral(query),
903
+ t.tsTypeAnnotation(
904
+ types.length ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))) : t.tsNeverKeyword()
905
+ )
906
+ ))
907
+ )
908
+ ), declareModule = t.declareModule(
909
+ t.stringLiteral("@sanity/client"),
910
+ t.blockStatement([queryReturnInterface])
911
+ ), clientImport = t.addComments(
912
+ t.importDeclaration([], t.stringLiteral("@sanity/client")),
913
+ "leading",
914
+ [{ type: "CommentLine", value: " Query TypeMap" }]
915
+ ), ast = t.program([clientImport, declareModule]);
916
+ return { code: generateCode(ast), ast };
917
+ }
918
+ async generateTypes(options) {
919
+ const { reporter: report } = options, internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration(), schemaTypeDeclarations = this.getSchemaTypeDeclarations(options), allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options);
920
+ report?.event.generatedSchemaTypes({
921
+ internalReferenceSymbol,
922
+ schemaTypeDeclarations,
923
+ allSanitySchemaTypesDeclaration
924
+ });
925
+ const program = t.program([]);
926
+ let code = "";
927
+ for (const declaration of schemaTypeDeclarations)
928
+ program.body.push(declaration.ast), code += declaration.code;
929
+ program.body.push(allSanitySchemaTypesDeclaration.ast), code += allSanitySchemaTypesDeclaration.code, program.body.push(internalReferenceSymbol.ast), code += internalReferenceSymbol.code;
930
+ const evaluatedModules = await TypeGenerator.getEvaluatedModules({
931
+ ...options,
932
+ schemaTypeDeclarations,
933
+ schemaTypeGenerator: this.getSchemaTypeGenerator(options)
934
+ });
935
+ for (const { queries } of evaluatedModules)
936
+ for (const query of queries)
937
+ program.body.push(query.ast), code += query.code;
938
+ const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({
939
+ ...options,
940
+ evaluatedModules
941
+ });
942
+ return program.body.push(...queryMapDeclaration.ast.body), code += queryMapDeclaration.code, report?.event.generatedQueryTypes({ queryMapDeclaration }), { code, ast: program };
943
+ }
761
944
  }
762
945
  export {
946
+ QueryExtractionError,
763
947
  TypeGenerator,
764
948
  configDefinition,
765
949
  findQueriesInPath,