@sanity/codegen 3.88.1-typegen-experimental.0 → 3.88.1

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
@@ -20,44 +20,29 @@ function _interopNamespaceCompat(e) {
20
20
  }), n.default = e, Object.freeze(n);
21
21
  }
22
22
  var fs__default$1 = /* @__PURE__ */ _interopDefaultCompat(fs), json5__namespace = /* @__PURE__ */ _interopNamespaceCompat(json5), z__namespace = /* @__PURE__ */ _interopNamespaceCompat(z), createDebug__default = /* @__PURE__ */ _interopDefaultCompat(createDebug), glob__default = /* @__PURE__ */ _interopDefaultCompat(glob), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs$1), path__default = /* @__PURE__ */ _interopDefaultCompat(path), t__namespace = /* @__PURE__ */ _interopNamespaceCompat(t), traverse__default = /* @__PURE__ */ _interopDefaultCompat(traverse), register__default = /* @__PURE__ */ _interopDefaultCompat(register);
23
- const defaultPaths = [
24
- "./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}",
25
- "./app/**/*.{ts,tsx,js,jsx,mjs,cjs}",
26
- "./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}"
27
- ], rawConfigSchema = z__namespace.object({
28
- path: z__namespace.union([z__namespace.string(), z__namespace.array(z__namespace.string())]).optional(),
29
- generates: z__namespace.string().optional(),
30
- formatGeneratedCode: z__namespace.boolean().optional(),
31
- overloadClientMethods: z__namespace.boolean().optional(),
32
- augmentGroqModule: z__namespace.boolean().optional(),
33
- schema: z__namespace.string().optional(),
34
- unstable_schemas: z__namespace.array(z__namespace.object({ schemaPath: z__namespace.string(), schemaId: z__namespace.string() })).optional()
35
- }).superRefine((data, ctx) => {
36
- data.schema !== void 0 && data.unstable_schemas !== void 0 && ctx.addIssue({
37
- code: z__namespace.ZodIssueCode.custom,
38
- message: 'Configuration cannot contain both "schema" and "unstable_schemas". Use one or the other.'
39
- });
40
- }).refine((d) => d.unstable_schemas === void 0 || d.unstable_schemas.length > 0, {
41
- message: '"unstable_schemas" array cannot be empty. Please provide at least one schema definition or use the "schema" property instead.'
42
- }), normalizedConfigSchema = rawConfigSchema.transform((d) => ({
43
- path: typeof d.path == "string" ? [d.path] : d.path ?? defaultPaths,
44
- generates: d.generates ?? "./sanity.types.ts",
45
- formatGeneratedCode: d.formatGeneratedCode ?? !0,
46
- overloadClientMethods: d.overloadClientMethods ?? !0,
47
- augmentGroqModule: d.augmentGroqModule ?? !0,
48
- schemas: d.unstable_schemas ? d.unstable_schemas.map((s) => ({
49
- schemaPath: s.schemaPath,
50
- schemaId: s.schemaId
51
- })) : [{ schemaId: "default", schemaPath: d.schema ?? "./schema.json" }]
52
- })), DEFAULT_CONFIG = normalizedConfigSchema.parse({});
23
+ const configDefintion = z__namespace.object({
24
+ path: z__namespace.string().or(z__namespace.array(z__namespace.string())).default([
25
+ "./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}",
26
+ "./app/**/*.{ts,tsx,js,jsx,mjs,cjs}",
27
+ "./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}"
28
+ ]),
29
+ schema: z__namespace.string().default("./schema.json"),
30
+ generates: z__namespace.string().default("./sanity.types.ts"),
31
+ formatGeneratedCode: z__namespace.boolean().default(!0),
32
+ overloadClientMethods: z__namespace.boolean().default(!0)
33
+ });
53
34
  async function readConfig(path2) {
54
35
  try {
55
36
  const content = await fs.readFile(path2, "utf-8"), json = json5__namespace.parse(content);
56
- return normalizedConfigSchema.parse(json);
37
+ return configDefintion.parseAsync(json);
57
38
  } catch (error) {
58
- throw error instanceof z__namespace.ZodError ? new Error(`Error in config file
39
+ if (error instanceof z__namespace.ZodError)
40
+ throw new Error(`Error in config file
59
41
  ${error.errors.map((err) => err.message).join(`
60
- `)}`) : error;
42
+ `)}`);
43
+ if (typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT")
44
+ return configDefintion.parse({});
45
+ throw error;
61
46
  }
62
47
  }
63
48
  async function readSchema(path2) {
@@ -110,7 +95,7 @@ function parseAstro(source) {
110
95
  `)).join(`
111
96
  `) : "";
112
97
  }
113
- const debug$2 = createDebug__default.default("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery", "defineProjection"];
98
+ const debug$2 = createDebug__default.default("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery"];
114
99
  function resolveExpression({
115
100
  node,
116
101
  file,
@@ -420,22 +405,19 @@ function resolveExportSpecifier({
420
405
  cause: `noBinding:${importName}`
421
406
  });
422
407
  }
423
- const require$1 = node_module.createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", defineProjectionFunctionName = "defineProjection", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
408
+ const require$1 = node_module.createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
424
409
  function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require$1.resolve) {
425
410
  const queries = [], file = parseSourceFile(source, filename, babelConfig);
426
411
  return core.traverse(file, {
427
412
  // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
428
413
  // The variable name is used as the name of the query result type
429
414
  VariableDeclarator(path2) {
430
- const { node, scope } = path2, init = node.init, isGroqTemplateTag = t__namespace.isTaggedTemplateExpression(init) && t__namespace.isIdentifier(init.tag) && init.tag.name === groqTagName, isDefineCall = t__namespace.isCallExpression(init) && (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) || isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee));
431
- if (t__namespace.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {
415
+ const { node, scope } = path2, init = node.init, isGroqTemplateTag = t__namespace.isTaggedTemplateExpression(init) && t__namespace.isIdentifier(init.tag) && init.tag.name === groqTagName, isDefineQueryCall = t__namespace.isCallExpression(init) && (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee));
416
+ if (t__namespace.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {
432
417
  if (declarationLeadingCommentContains(path2, ignoreValue))
433
418
  return;
434
- const queryName = `${node.id.name}`;
435
- let resultType = "query", expressionToResolve = init;
436
- isDefineCall && (init.arguments.length > 0 && t__namespace.isExpression(init.arguments[0]) && (expressionToResolve = init.arguments[0]), isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) && (resultType = "projection"));
437
- const queryResult = resolveExpression({
438
- node: expressionToResolve,
419
+ const queryName = `${node.id.name}`, queryResult = resolveExpression({
420
+ node: init,
439
421
  file,
440
422
  scope,
441
423
  babelConfig,
@@ -449,7 +431,7 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
449
431
  ...node.loc?.end
450
432
  }
451
433
  } : {};
452
- queries.push({ name: queryName, result: queryResult, type: resultType, location });
434
+ queries.push({ name: queryName, result: queryResult, location });
453
435
  }
454
436
  }
455
437
  }), queries;
@@ -517,7 +499,6 @@ async function* findQueriesInPath({
517
499
  // we never want to look in node_modules
518
500
  onlyFiles: !0
519
501
  }).sort();
520
- yield { type: "files", fileCount: files.length };
521
502
  for (const filename of files)
522
503
  if (typeof filename == "string") {
523
504
  debug(`Found file "${filename}"`);
@@ -540,100 +521,118 @@ function registerBabel(babelOptions) {
540
521
  const options = babelOptions || getBabelConfig();
541
522
  register__default.default({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
542
523
  }
543
- class AsyncQueue {
544
- // Internal state:
545
- // `queue`: Holds items yet to be consumed.
546
- // `resume`: A callback to signal the consumer when new items arrive or the queue finishes/errors.
547
- // `finished`: Flag indicating if the producer is done adding items (via `finish` or `throwError`).
548
- // `pendingError`: Stores an error passed to `throwError`, to be thrown by the consumer.
549
- queue = [];
550
- resume = null;
551
- finished = !1;
552
- pendingError = null;
553
- /**
554
- * Enqueues an item. Throws if `finish` or `throwError` has been called.
555
- */
556
- enqueue(item) {
557
- if (this.finished)
558
- throw new Error("Cannot enqueue items to a finished AsyncQueue.");
559
- this.queue.push(item), this.resume && (this.resume(), this.resume = null);
524
+ const REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo", ALL_SCHEMA_TYPES = "AllSanitySchemaTypes";
525
+ class TypeGenerator {
526
+ // Simple set to keep track of generated type names, to avoid conflicts
527
+ generatedTypeName = /* @__PURE__ */ new Set();
528
+ // Map between type names and their generated type names, used to resolve the correct generated type name
529
+ typeNameMap = /* @__PURE__ */ new Map();
530
+ // Map between type nodes and their generated type names, used for query mapping
531
+ typeNodeNameMap = /* @__PURE__ */ new Map();
532
+ schema;
533
+ constructor(schema) {
534
+ this.schema = schema, this.schema.forEach((s) => {
535
+ this.getTypeName(s.name, s);
536
+ });
560
537
  }
561
538
  /**
562
- * Signals that no more items will be enqueued. Idempotent.
539
+ * Generate TypeScript types for the given schema
540
+ * @returns string
541
+ * @internal
542
+ * @beta
563
543
  */
564
- finish() {
565
- this.finished || (this.finished = !0, this.resume && (this.resume(), this.resume = null));
544
+ generateSchemaTypes() {
545
+ const typeDeclarations = [], schemaNames = /* @__PURE__ */ new Set();
546
+ return this.schema.forEach((schema) => {
547
+ const typeLiteral = this.getTypeNodeType(schema), schemaName = this.typeNodeNameMap.get(schema);
548
+ if (!schemaName)
549
+ throw new Error(`Schema name not found for schema ${schema.name}`);
550
+ schemaNames.add(schemaName);
551
+ const typeAlias = t__namespace.tsTypeAliasDeclaration(t__namespace.identifier(schemaName), null, typeLiteral);
552
+ typeDeclarations.push(t__namespace.exportNamedDeclaration(typeAlias));
553
+ }), typeDeclarations.push(
554
+ t__namespace.exportNamedDeclaration(
555
+ t__namespace.tsTypeAliasDeclaration(
556
+ t__namespace.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),
557
+ null,
558
+ t__namespace.tsUnionType(
559
+ [...schemaNames].map((typeName) => t__namespace.tsTypeReference(t__namespace.identifier(typeName)))
560
+ )
561
+ )
562
+ )
563
+ ), typeDeclarations.map((decl) => new generator.CodeGenerator(decl).generate().code).join(`
564
+
565
+ `);
566
566
  }
567
567
  /**
568
- * Signals an error occurred during production. Finishes the queue. Idempotent.
568
+ * Takes a identifier and a type node and generates a type alias for the type node.
569
+ * @param identifierName - The name of the type to generated
570
+ * @param typeNode - The type node to generate the type for
571
+ * @returns
572
+ * @internal
573
+ * @beta
569
574
  */
570
- throwError(error) {
571
- this.finished || (this.pendingError = error, this.finished = !0, this.resume && (this.resume(), this.resume = null));
575
+ generateTypeNodeTypes(identifierName, typeNode) {
576
+ const type = this.getTypeNodeType(typeNode), typeName = this.getTypeName(identifierName, typeNode), typeAlias = t__namespace.tsTypeAliasDeclaration(t__namespace.identifier(typeName), null, type);
577
+ return new generator.CodeGenerator(t__namespace.exportNamedDeclaration(typeAlias)).generate().code.trim();
578
+ }
579
+ static generateKnownTypes() {
580
+ const typeOperator = t__namespace.tsTypeOperator(t__namespace.tsSymbolKeyword());
581
+ typeOperator.operator = "unique";
582
+ const identifier = t__namespace.identifier(REFERENCE_SYMBOL_NAME);
583
+ identifier.typeAnnotation = t__namespace.tsTypeAnnotation(typeOperator);
584
+ const decleration = t__namespace.variableDeclaration("const", [t__namespace.variableDeclarator(identifier)]);
585
+ return decleration.declare = !0, new generator.CodeGenerator(t__namespace.exportNamedDeclaration(decleration)).generate().code.trim();
572
586
  }
573
587
  /**
574
- * Async iterator to consume enqueued items.
575
- * Throws if `throwError` was called.
588
+ * Takes a list of queries from the codebase and generates a type declaration
589
+ * for SanityClient to consume.
590
+ *
591
+ * Note: only types that have previously been generated with `generateTypeNodeTypes`
592
+ * will be included in the query map.
593
+ *
594
+ * @param queries - A list of queries to generate a type declaration for
595
+ * @returns
596
+ * @internal
597
+ * @beta
576
598
  */
577
- async *[Symbol.asyncIterator]() {
578
- for (; ; ) {
579
- if (this.pendingError)
580
- throw this.pendingError;
581
- if (this.queue.length === 0 && !this.finished && (await new Promise((resolve) => {
582
- this.resume = resolve;
583
- }), this.pendingError))
584
- throw this.pendingError;
585
- for (; this.queue.length > 0; )
586
- yield this.queue.shift();
587
- if (this.finished && this.queue.length === 0)
588
- break;
599
+ generateQueryMap(queries) {
600
+ const typesByQuerystring = {};
601
+ for (const query of queries) {
602
+ const name = this.typeNodeNameMap.get(query.typeNode);
603
+ name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
589
604
  }
590
- if (this.pendingError)
591
- throw this.pendingError;
592
- }
593
- }
594
- class SchemaTypeGenerator {
595
- static ProjectionBase = t__namespace.identifier("ProjectionBase");
596
- static InternalReferenceSymbol = Object.assign(t__namespace.identifier("internalGroqTypeReferenceTo"), {
597
- typeAnnotation: t__namespace.tsTypeAnnotation(
598
- Object.assign(t__namespace.tsTypeOperator(t__namespace.tsSymbolKeyword()), { operator: "unique" })
599
- )
600
- });
601
- static sanitizeIdentifier(input) {
602
- return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
603
- }
604
- static normalizeIdentifier(input) {
605
- const sanitized = SchemaTypeGenerator.sanitizeIdentifier(input);
606
- return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`;
607
- }
608
- schema;
609
- schemaId;
610
- typeNames = /* @__PURE__ */ new Set();
611
- tsTypes = /* @__PURE__ */ new Map();
612
- identifiers = /* @__PURE__ */ new Map();
613
- constructor({ schema, schemaId }) {
614
- this.schemaId = schemaId, this.schema = schema;
615
- for (const type of schema) {
616
- if (this.typeNames.has(type.name))
617
- throw new Error(
618
- `Duplicate type name "${type.name}" in schema "${schemaId}". Type names must be unique within the same schema.`
619
- );
620
- this.typeNames.add(type.name);
621
- }
622
- const uniqueIdentifiers = /* @__PURE__ */ new Set();
623
- for (const type of schema) {
624
- const desiredName = SchemaTypeGenerator.normalizeIdentifier(type.name);
625
- let resultingName = desiredName, index = 2;
626
- for (; uniqueIdentifiers.has(resultingName); )
627
- resultingName = `${desiredName}_${index}`, index++;
628
- uniqueIdentifiers.add(resultingName), this.identifiers.set(type.name, t__namespace.identifier(resultingName));
629
- }
630
- for (const type of schema)
631
- this.tsTypes.set(type.name, this.generateTsType(type));
632
- }
633
- shouldOmitProjection({ rest, attributes }) {
634
- return rest?.type === "unknown" || rest?.type === "object" && this.shouldOmitProjection(rest) ? !0 : Object.values(attributes).every((attr) => attr.value.type === "null");
605
+ const queryReturnInterface = t__namespace.tsInterfaceDeclaration(
606
+ t__namespace.identifier("SanityQueries"),
607
+ null,
608
+ [],
609
+ t__namespace.tsInterfaceBody(
610
+ Object.entries(typesByQuerystring).map(([query, types]) => t__namespace.tsPropertySignature(
611
+ t__namespace.stringLiteral(query),
612
+ t__namespace.tsTypeAnnotation(
613
+ t__namespace.tsUnionType(types.map((type) => t__namespace.tsTypeReference(t__namespace.identifier(type))))
614
+ )
615
+ ))
616
+ )
617
+ ), declareModule = t__namespace.declareModule(
618
+ t__namespace.stringLiteral("@sanity/client"),
619
+ t__namespace.blockStatement([queryReturnInterface])
620
+ ), clientImport = t__namespace.importDeclaration([], t__namespace.stringLiteral("@sanity/client"));
621
+ return new generator.CodeGenerator(t__namespace.program([clientImport, declareModule])).generate().code.trim();
635
622
  }
636
- generateTsType(typeNode) {
623
+ /**
624
+ * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these
625
+ * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.
626
+ * When we reference a type we also keep track of the original name so we can reference the correct type later.
627
+ */
628
+ getTypeName(name, typeNode) {
629
+ const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name));
630
+ let generatedName = desiredName, i = 2;
631
+ for (; this.generatedTypeName.has(generatedName); )
632
+ generatedName = `${desiredName}_${i++}`;
633
+ return this.generatedTypeName.add(generatedName), this.typeNameMap.set(name, generatedName), typeNode && this.typeNodeNameMap.set(typeNode, generatedName), generatedName;
634
+ }
635
+ getTypeNodeType(typeNode) {
637
636
  switch (typeNode.type) {
638
637
  case "string":
639
638
  return typeNode.value !== void 0 ? t__namespace.tsLiteralType(t__namespace.stringLiteral(typeNode.value)) : t__namespace.tsStringKeyword();
@@ -644,9 +643,9 @@ class SchemaTypeGenerator {
644
643
  case "unknown":
645
644
  return t__namespace.tsUnknownKeyword();
646
645
  case "document":
647
- return this.generateDocumentTsType(typeNode);
646
+ return this.generateDocumentType(typeNode);
648
647
  case "type":
649
- return this.generateTsType(typeNode.value);
648
+ return this.getTypeNodeType(typeNode.value);
650
649
  case "array":
651
650
  return this.generateArrayTsType(typeNode);
652
651
  case "object":
@@ -658,21 +657,21 @@ class SchemaTypeGenerator {
658
657
  case "null":
659
658
  return t__namespace.tsNullKeyword();
660
659
  default:
661
- throw new Error(
662
- `Encountered unsupported node type "${// @ts-expect-error This should never happen
663
- typeNode.type}" while generating schema types for schema "${this.schemaId}"`
664
- );
660
+ throw new Error(`Type "${typeNode.type}" not found in schema`);
665
661
  }
666
662
  }
667
663
  // Helper function used to generate TS types for array type nodes.
668
664
  generateArrayTsType(typeNode) {
669
- const typeNodes = this.generateTsType(typeNode.of);
670
- return t__namespace.tsTypeReference(t__namespace.identifier("Array"), t__namespace.tsTypeParameterInstantiation([typeNodes]));
665
+ const typeNodes = this.getTypeNodeType(typeNode.of);
666
+ return t__namespace.tsTypeReference(
667
+ t__namespace.identifier("Array"),
668
+ t__namespace.tsTypeParameterInstantiation([typeNodes])
669
+ );
671
670
  }
672
671
  // Helper function used to generate TS types for object properties.
673
- generateTsObjectProperty(key, attribute) {
674
- const type = this.generateTsType(attribute.value), propertySignature = t__namespace.tsPropertySignature(
675
- t__namespace.identifier(SchemaTypeGenerator.sanitizeIdentifier(key)),
672
+ generateObjectProperty(key, attribute) {
673
+ const type = this.getTypeNodeType(attribute.value), propertySignature = t__namespace.tsPropertySignature(
674
+ t__namespace.identifier(sanitizeIdentifier(key)),
676
675
  t__namespace.tsTypeAnnotation(type)
677
676
  );
678
677
  return propertySignature.optional = attribute.optional, propertySignature;
@@ -681,16 +680,16 @@ class SchemaTypeGenerator {
681
680
  generateObjectTsType(typeNode) {
682
681
  const props = [];
683
682
  Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
684
- props.push(this.generateTsObjectProperty(key, attribute));
683
+ props.push(this.generateObjectProperty(key, attribute));
685
684
  });
686
685
  const rest = typeNode.rest;
687
- if (rest)
686
+ if (rest !== void 0)
688
687
  switch (rest.type) {
689
688
  case "unknown":
690
689
  return t__namespace.tsUnknownKeyword();
691
690
  case "object": {
692
691
  Object.entries(rest.attributes).forEach(([key, attribute]) => {
693
- props.push(this.generateTsObjectProperty(key, attribute));
692
+ props.push(this.generateObjectProperty(key, attribute));
694
693
  });
695
694
  break;
696
695
  }
@@ -701,419 +700,55 @@ class SchemaTypeGenerator {
701
700
  default:
702
701
  throw new Error(`Type "${rest.type}" not found in schema`);
703
702
  }
704
- if (typeNode.dereferencesTo) {
705
- const derefType = Object.assign(
706
- t__namespace.tsPropertySignature(
707
- SchemaTypeGenerator.InternalReferenceSymbol,
708
- t__namespace.tsTypeAnnotation(t__namespace.tsLiteralType(t__namespace.stringLiteral(typeNode.dereferencesTo)))
709
- ),
710
- { computed: !0, optional: !0 }
703
+ if (typeNode.dereferencesTo !== void 0) {
704
+ const derefType = t__namespace.tsPropertySignature(
705
+ t__namespace.identifier(REFERENCE_SYMBOL_NAME),
706
+ t__namespace.tsTypeAnnotation(t__namespace.tsLiteralType(t__namespace.stringLiteral(typeNode.dereferencesTo)))
711
707
  );
712
- props.push(derefType);
708
+ derefType.computed = !0, derefType.optional = !0, props.push(derefType);
713
709
  }
714
710
  return t__namespace.tsTypeLiteral(props);
715
711
  }
716
712
  generateInlineTsType(typeNode) {
717
- const identifier = this.getIdentifier(typeNode.name);
718
- return identifier ? t__namespace.tsTypeReference(identifier) : t__namespace.addComment(
719
- t__namespace.tsUnknownKeyword(),
720
- "trailing",
721
- ` Unable to locate the referenced type "${typeNode.name}" in schema "${this.schemaId}"`,
722
- !0
723
- );
713
+ const referencedTypeNode = this.schema.find((schema) => schema.name === typeNode.name);
714
+ if (referencedTypeNode === void 0) {
715
+ const generatedName2 = this.typeNameMap.get(typeNode.name);
716
+ if (generatedName2)
717
+ return t__namespace.tsTypeReference(t__namespace.identifier(generatedName2));
718
+ const missing = t__namespace.tsUnknownKeyword();
719
+ return missing.trailingComments = [
720
+ {
721
+ type: "CommentLine",
722
+ value: ` Unable to locate the referenced type "${typeNode.name}" in schema`
723
+ }
724
+ ], missing;
725
+ }
726
+ const generatedName = this.typeNameMap.get(referencedTypeNode.name);
727
+ return generatedName ? t__namespace.tsTypeReference(t__namespace.identifier(generatedName)) : t__namespace.tsUnknownKeyword();
724
728
  }
725
729
  // Helper function used to generate TS types for union type nodes.
726
730
  generateUnionTsType(typeNode) {
727
- return typeNode.of.length === 0 ? t__namespace.tsNeverKeyword() : typeNode.of.length === 1 ? this.generateTsType(typeNode.of[0]) : t__namespace.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)));
731
+ if (typeNode.of.length === 0)
732
+ return t__namespace.tsNeverKeyword();
733
+ if (typeNode.of.length === 1)
734
+ return this.getTypeNodeType(typeNode.of[0]);
735
+ const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node));
736
+ return t__namespace.tsUnionType(typeNodes);
728
737
  }
729
738
  // Helper function used to generate TS types for document type nodes.
730
- generateDocumentTsType(document) {
739
+ generateDocumentType(document) {
731
740
  const props = Object.entries(document.attributes).map(
732
- ([key, node]) => this.generateTsObjectProperty(key, node)
741
+ ([key, node]) => this.generateObjectProperty(key, node)
733
742
  );
734
743
  return t__namespace.tsTypeLiteral(props);
735
744
  }
736
- getTypeNames() {
737
- return Array.from(this.typeNames);
738
- }
739
- getTsType(typeName) {
740
- return this.tsTypes.get(typeName);
741
- }
742
- getIdentifier(typeName) {
743
- return this.identifiers.get(typeName);
744
- }
745
- evaluateQuery(query) {
746
- const ast = safeParseQuery(query), typeNode = groqJs.typeEvaluate(ast, this.schema), tsType = this.generateTsType(typeNode), stats = walkAndCountQueryTypeNodeStats(typeNode);
747
- return { tsType, stats };
748
- }
749
- evaluateProjection(projection) {
750
- const results = [];
751
- for (const schemaType of this.schema) {
752
- if (schemaType.type !== "document") continue;
753
- if (safeParseQuery(projection).type !== "Object")
754
- throw new Error(
755
- `Invalid projection syntax: Projections must be enclosed in curly braces, (e.g., "{_id, title}"). Received: "${projection}"`
756
- );
757
- const ast = safeParseQuery(`* [_type==${JSON.stringify(schemaType.name)}] ${projection} [0]`), result = groqJs.typeEvaluate(ast, this.schema);
758
- if (result.type !== "union" || result.of.length !== 2) continue;
759
- const projectionResult = result.of.find((node) => node.type !== "null");
760
- if (projectionResult?.type !== "object" || this.shouldOmitProjection(projectionResult)) continue;
761
- const stats = walkAndCountQueryTypeNodeStats(projectionResult), tsType = t__namespace.tsTypeReference(
762
- SchemaTypeGenerator.ProjectionBase,
763
- t__namespace.tsTypeParameterInstantiation([
764
- this.generateTsType(projectionResult),
765
- t__namespace.tsLiteralType(t__namespace.stringLiteral(schemaType.name))
766
- ])
767
- );
768
- results.push({ tsType, stats });
769
- }
770
- if (!results.length) return null;
771
- if (results.length === 1) return results[0];
772
- const combinedTsType = t__namespace.tsUnionType(results.map((i) => i.tsType)), accumulatedStats = results.reduce(
773
- (acc, { stats }) => ({
774
- allTypes: acc.allTypes + stats.allTypes,
775
- emptyUnions: acc.emptyUnions + stats.emptyUnions,
776
- unknownTypes: acc.unknownTypes + stats.unknownTypes
777
- }),
778
- { allTypes: 0, unknownTypes: 0, emptyUnions: 0 }
779
- );
780
- return accumulatedStats.allTypes += 1, { tsType: combinedTsType, stats: accumulatedStats };
781
- }
782
- }
783
- function walkAndCountQueryTypeNodeStats(typeNode) {
784
- switch (typeNode.type) {
785
- case "unknown":
786
- return { allTypes: 1, unknownTypes: 1, emptyUnions: 0 };
787
- case "array": {
788
- const acc = walkAndCountQueryTypeNodeStats(typeNode.of);
789
- return acc.allTypes += 1, acc;
790
- }
791
- case "object": {
792
- if (typeNode.rest && typeNode.rest.type === "unknown")
793
- return { allTypes: 2, unknownTypes: 1, emptyUnions: 0 };
794
- const restStats = typeNode.rest ? walkAndCountQueryTypeNodeStats(typeNode.rest) : { allTypes: 0, unknownTypes: 0, emptyUnions: 0 };
795
- return restStats.allTypes += 1, Object.values(typeNode.attributes).reduce((acc, attribute) => {
796
- const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(
797
- attribute.value
798
- );
799
- return {
800
- allTypes: acc.allTypes + allTypes,
801
- unknownTypes: acc.unknownTypes + unknownTypes,
802
- emptyUnions: acc.emptyUnions + emptyUnions
803
- };
804
- }, restStats);
805
- }
806
- case "union":
807
- return typeNode.of.length === 0 ? { allTypes: 1, unknownTypes: 0, emptyUnions: 1 } : typeNode.of.reduce(
808
- (acc, type) => {
809
- const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(type);
810
- return {
811
- allTypes: acc.allTypes + allTypes,
812
- unknownTypes: acc.unknownTypes + unknownTypes,
813
- emptyUnions: acc.emptyUnions + emptyUnions
814
- };
815
- },
816
- { allTypes: 1, unknownTypes: 0, emptyUnions: 0 }
817
- // count the union type itself
818
- );
819
- default:
820
- return { allTypes: 1, unknownTypes: 0, emptyUnions: 0 };
821
- }
822
- }
823
- const SanityQueries = t__namespace.identifier("SanityQueries"), SanityProjections = t__namespace.identifier("SanityProjections"), SanitySchemas = t__namespace.identifier("SanitySchemas"), SchemaOrigin = t__namespace.identifier("SchemaOrigin"), PickSchema = t__namespace.identifier("PickSchema"), AllSanitySchemaTypes = t__namespace.identifier("AllSanitySchemaTypes");
824
- class TypeGenerator {
825
- schemas;
826
- augmentGroqModule;
827
- overloadClientMethods;
828
- schemaFilenames = /* @__PURE__ */ new Map();
829
- globalIdentifiers = /* @__PURE__ */ new Set();
830
- identifiersByQuery = /* @__PURE__ */ new Map();
831
- identifiersByProjection = /* @__PURE__ */ new Map();
832
- queryResultsQueue = new AsyncQueue();
833
- augmentedQueryResultsPromise = promiseWithResolvers();
834
- queryFileCountPromise = promiseWithResolvers();
835
- constructor({
836
- schemas,
837
- queriesByFile,
838
- augmentGroqModule = !0,
839
- overloadClientMethods = !0
840
- }) {
841
- this.globalIdentifiers.add(SanityQueries.name), this.globalIdentifiers.add(SanityProjections.name), this.globalIdentifiers.add(SanitySchemas.name), this.globalIdentifiers.add(SchemaOrigin.name), this.globalIdentifiers.add(PickSchema.name), this.globalIdentifiers.add(AllSanitySchemaTypes.name), this.globalIdentifiers.add(SchemaTypeGenerator.InternalReferenceSymbol.name), this.globalIdentifiers.add(SchemaTypeGenerator.ProjectionBase.name);
842
- const schemaIds = /* @__PURE__ */ new Set();
843
- for (const { schemaId, filename } of schemas) {
844
- if (schemaIds.has(schemaId))
845
- throw new Error(`Duplicate schema ID "${schemaId}". Schema IDs must be unique.`);
846
- schemaIds.add(schemaId), filename && this.schemaFilenames.set(schemaId, filename);
847
- }
848
- this.schemas = schemas.map((opts) => new SchemaTypeGenerator(opts)), this.augmentGroqModule = augmentGroqModule, this.overloadClientMethods = overloadClientMethods, this.getSchemaTypeDeclarations(), this.getSchemaDeclarations(), queriesByFile ? this.handleQueries(queriesByFile).catch((error) => {
849
- this.queryFileCountPromise.reject(error), this.queryResultsQueue.throwError(error), this.augmentedQueryResultsPromise.reject(error);
850
- }) : this.queryFileCountPromise.resolve({ fileCount: 0 });
851
- }
852
- async handleQueries(queriesByFile) {
853
- for await (const result of queriesByFile) {
854
- if (result.type === "files") {
855
- this.queryFileCountPromise.resolve({ fileCount: result.fileCount });
856
- continue;
857
- }
858
- try {
859
- if (result.type === "error") throw result.error;
860
- const { filename, queries } = result, queryResultDeclarations = [];
861
- for (const query of queries)
862
- try {
863
- queryResultDeclarations.push({
864
- filename,
865
- query: query.result,
866
- ...this.generateQueryResultType({ ...query, filename })
867
- });
868
- } catch (error) {
869
- this.queryResultsQueue.enqueue({ type: "error", filename, error });
870
- }
871
- this.queryResultsQueue.enqueue({ type: "queries", filename, queryResultDeclarations });
872
- } catch (error) {
873
- this.queryResultsQueue.enqueue({ type: "error", filename: result.filename, error });
874
- }
875
- }
876
- this.queryResultsQueue.finish();
877
- let augmentedQueryResultsCode = "";
878
- const clientModuleBlockStatement = [], groqModuleBlockStatement = [];
879
- if (this.identifiersByQuery.size > 0) {
880
- const sanityQueriesInterfaceDeclaration = t__namespace.tsInterfaceDeclaration(
881
- SanityQueries,
882
- null,
883
- [],
884
- t__namespace.tsInterfaceBody(
885
- Array.from(this.identifiersByQuery).map(
886
- ([query, identifiers]) => t__namespace.tsPropertySignature(
887
- t__namespace.stringLiteral(query),
888
- t__namespace.tsTypeAnnotation(
889
- identifiers.length === 1 ? t__namespace.tsTypeReference(identifiers[0]) : t__namespace.tsUnionType(identifiers.map((i) => t__namespace.tsTypeReference(i)))
890
- )
891
- )
892
- )
893
- )
894
- );
895
- clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration), groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration);
896
- }
897
- if (this.identifiersByProjection.size > 0) {
898
- const sanityProjectionsInterfaceDeclaration = t__namespace.tsInterfaceDeclaration(
899
- SanityProjections,
900
- null,
901
- [],
902
- t__namespace.tsInterfaceBody(
903
- Array.from(this.identifiersByProjection).map(
904
- ([projection, identifiers]) => t__namespace.tsPropertySignature(
905
- t__namespace.stringLiteral(projection),
906
- t__namespace.tsTypeAnnotation(
907
- identifiers.length === 1 ? t__namespace.tsTypeReference(identifiers[0]) : t__namespace.tsUnionType(identifiers.map((i) => t__namespace.tsTypeReference(i)))
908
- )
909
- )
910
- )
911
- )
912
- );
913
- groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration);
914
- }
915
- if (this.overloadClientMethods && clientModuleBlockStatement.length > 0) {
916
- const clientModuleDeclaration = t__namespace.declareModule(
917
- t__namespace.stringLiteral("@sanity/client"),
918
- t__namespace.blockStatement(clientModuleBlockStatement)
919
- );
920
- augmentedQueryResultsCode += generateCode(clientModuleDeclaration);
921
- }
922
- if (this.augmentGroqModule && groqModuleBlockStatement.length > 0) {
923
- const groqModuleDeclaration = t__namespace.declareModule(
924
- t__namespace.stringLiteral("groq"),
925
- t__namespace.blockStatement(groqModuleBlockStatement)
926
- );
927
- augmentedQueryResultsCode += generateCode(groqModuleDeclaration);
928
- }
929
- this.augmentedQueryResultsPromise.resolve({ code: augmentedQueryResultsCode });
930
- }
931
- generateQueryResultType({
932
- name,
933
- result,
934
- type,
935
- filename
936
- }) {
937
- const evaluationResults = [];
938
- for (const schema of this.schemas) {
939
- const { schemaId } = schema;
940
- if (type === "projection") {
941
- const projectionResult = schema.evaluateProjection(result);
942
- if (!projectionResult) continue;
943
- evaluationResults.push({ schemaId, ...projectionResult });
944
- } else {
945
- const queryResult = schema.evaluateQuery(result);
946
- evaluationResults.push({ schemaId, ...queryResult });
947
- }
948
- }
949
- const tsTypes = evaluationResults.map(({ tsType: tsType2, schemaId }) => this.schemas.length === 1 ? tsType2 : addSchemaOrigin(tsType2, schemaId)), tsType = tsTypes.length === 1 ? tsTypes[0] : t__namespace.tsUnionType(tsTypes), { code, id } = this.generateAndRegisterExportedTypeAlias(
950
- `${name}${type === "projection" ? "ProjectionResult" : "Result"}`,
951
- tsType,
952
- [
953
- { type: "CommentLine", value: ` Source: ${filename}` },
954
- { type: "CommentLine", value: ` Variable: ${name}` },
955
- {
956
- type: "CommentLine",
957
- value: ` ${type === "projection" ? "Projection" : "Query"}: ${result.replace(/(\r\n|\n|\r)/gm, "").trim()}`
958
- }
959
- ]
960
- ), identifiersByProjectionOrQuery = type === "projection" ? this.identifiersByProjection : this.identifiersByQuery;
961
- let identifiers = identifiersByProjectionOrQuery.get(result);
962
- return identifiers || (identifiers = [], identifiersByProjectionOrQuery.set(result, identifiers)), identifiers.push(id), {
963
- code,
964
- id,
965
- name,
966
- type,
967
- stats: evaluationResults.reduce(
968
- (acc, { stats }) => ({
969
- allTypes: acc.allTypes + stats.allTypes,
970
- unknownTypes: acc.unknownTypes + stats.unknownTypes,
971
- emptyUnions: acc.emptyUnions + stats.emptyUnions
972
- }),
973
- { allTypes: 0, unknownTypes: 0, emptyUnions: 0 }
974
- )
975
- };
976
- }
977
- generateAndRegisterExportedTypeAlias(name, tsType, comments) {
978
- const desiredName = SchemaTypeGenerator.normalizeIdentifier(name);
979
- let resultingName = desiredName, index = 2;
980
- for (; this.globalIdentifiers.has(resultingName); )
981
- resultingName = `${desiredName}_${index}`, index++;
982
- this.globalIdentifiers.add(resultingName);
983
- const id = t__namespace.identifier(resultingName), typeAlias = t__namespace.tsTypeAliasDeclaration(id, null, tsType);
984
- let exportDeclaration = t__namespace.exportNamedDeclaration(typeAlias);
985
- comments && (exportDeclaration = t__namespace.addComments(exportDeclaration, "leading", comments));
986
- const code = generateCode(exportDeclaration);
987
- return { id, code };
988
- }
989
- getKnownTypes = computeOnce(() => {
990
- let code = "";
991
- this.overloadClientMethods && (code += generateCode(t__namespace.importDeclaration([], t__namespace.stringLiteral("@sanity/client"))));
992
- const importSpecifiers = [
993
- t__namespace.importSpecifier(SchemaTypeGenerator.ProjectionBase, SchemaTypeGenerator.ProjectionBase)
994
- ];
995
- return this.schemas.length > 1 && (importSpecifiers.push(t__namespace.importSpecifier(PickSchema, PickSchema)), importSpecifiers.push(t__namespace.importSpecifier(SchemaOrigin, SchemaOrigin))), code += generateCode(
996
- Object.assign(t__namespace.importDeclaration(importSpecifiers, t__namespace.stringLiteral("groq")), {
997
- importKind: "type"
998
- })
999
- ), code += generateCode(
1000
- t__namespace.exportNamedDeclaration(
1001
- Object.assign(
1002
- t__namespace.variableDeclaration("const", [
1003
- t__namespace.variableDeclarator(SchemaTypeGenerator.InternalReferenceSymbol)
1004
- ]),
1005
- { declare: !0 }
1006
- )
1007
- )
1008
- ), { code };
1009
- });
1010
- getSchemaTypeDeclarations = computeOnce(() => {
1011
- const typeNames = new Set(this.schemas.flatMap((schema) => schema.getTypeNames()));
1012
- return Array.from(typeNames).flatMap((typeName) => {
1013
- const identifiers = new Set(
1014
- this.schemas.map((schema) => schema.getIdentifier(typeName)?.name).filter((i) => typeof i == "string")
1015
- );
1016
- return Array.from(identifiers).map((identifier) => {
1017
- const types = this.schemas.filter(
1018
- (schema) => schema.getIdentifier(typeName)?.name === identifier && !!schema.getTsType(typeName)
1019
- ).map((schema) => {
1020
- const tsType2 = schema.getTsType(typeName), schemaId = schema.schemaId;
1021
- return this.schemas.length < 2 ? { schemaId, tsType: tsType2 } : { schemaId, tsType: addSchemaOrigin(tsType2, schemaId) };
1022
- }), schemaIds = types.map((i) => i.schemaId), tsType = types.length === 1 ? types[0].tsType : t__namespace.tsUnionType(types.map((i) => i.tsType)), { id, code } = this.generateAndRegisterExportedTypeAlias(identifier, tsType);
1023
- return { id, code, schemaIds };
1024
- });
1025
- });
1026
- });
1027
- getAllSanitySchemaTypesDeclaration = computeOnce(() => {
1028
- const schemaTypeDeclarations = this.getSchemaTypeDeclarations();
1029
- return { code: generateCode(
1030
- t__namespace.exportNamedDeclaration(
1031
- t__namespace.tsTypeAliasDeclaration(
1032
- AllSanitySchemaTypes,
1033
- null,
1034
- t__namespace.tsUnionType(schemaTypeDeclarations.map(({ id }) => t__namespace.tsTypeReference(id)))
1035
- )
1036
- )
1037
- ) };
1038
- });
1039
- getSchemaDeclarations = computeOnce(() => {
1040
- const identifierUsageCountBySchemaId = this.getSchemaTypeDeclarations().reduce((acc, { schemaIds, id }) => {
1041
- for (const schemaId of schemaIds)
1042
- acc[schemaId] = acc[schemaId] ?? {}, acc[schemaId][id.name] = schemaIds.length;
1043
- return acc;
1044
- }, {});
1045
- return this.schemas.map(({ schemaId }) => {
1046
- const tsTypes = Object.entries(identifierUsageCountBySchemaId[schemaId]).map(
1047
- ([identifierName, schemaCount]) => {
1048
- const schemaTypeReferencer = t__namespace.tsTypeReference(t__namespace.identifier(identifierName));
1049
- return schemaCount > 1 ? addPickSchema(schemaTypeReferencer, schemaId) : schemaTypeReferencer;
1050
- }
1051
- ), tsType = tsTypes.length === 1 ? tsTypes[0] : t__namespace.tsUnionType(tsTypes), comments = [], filename = this.schemaFilenames.get(schemaId);
1052
- filename && comments.push({ type: "CommentLine", value: ` Source: ${filename}` }), comments.push({ type: "CommentLine", value: ` Schema ID: ${schemaId}` });
1053
- const { id, code } = this.generateAndRegisterExportedTypeAlias(
1054
- `${schemaId}Schema`,
1055
- tsType,
1056
- comments
1057
- );
1058
- return { id, code, schemaId };
1059
- });
1060
- });
1061
- getAugmentedSchemasDeclarations = computeOnce(() => {
1062
- if (!this.augmentGroqModule) return { code: "" };
1063
- const schemaDeclarations = this.getSchemaDeclarations(), groqModuleDeclaration = t__namespace.declareModule(
1064
- t__namespace.stringLiteral("groq"),
1065
- t__namespace.blockStatement([
1066
- t__namespace.tsInterfaceDeclaration(
1067
- SanitySchemas,
1068
- null,
1069
- [],
1070
- t__namespace.tsInterfaceBody(
1071
- schemaDeclarations.map(
1072
- ({ id, schemaId }) => t__namespace.tsPropertySignature(
1073
- t__namespace.stringLiteral(schemaId),
1074
- t__namespace.tsTypeAnnotation(t__namespace.tsTypeReference(id))
1075
- )
1076
- )
1077
- )
1078
- )
1079
- ])
1080
- );
1081
- return { code: generateCode(groqModuleDeclaration) };
1082
- });
1083
- getQueryFileCount = () => this.queryFileCountPromise.promise;
1084
- getQueryResultDeclarations = () => this.queryResultsQueue;
1085
- getAugmentedQueryResultsDeclarations = () => this.augmentedQueryResultsPromise.promise;
1086
745
  }
1087
- function computeOnce(fn) {
1088
- const ref = { current: void 0, computed: !1 };
1089
- return function() {
1090
- return ref.computed || (ref.current = fn.call(this), ref.computed = !0), ref.current;
1091
- };
1092
- }
1093
- function addSchemaOrigin(tsType, schemaId) {
1094
- return t__namespace.tsTypeReference(
1095
- SchemaOrigin,
1096
- t__namespace.tsTypeParameterInstantiation([tsType, t__namespace.tsLiteralType(t__namespace.stringLiteral(schemaId))])
1097
- );
1098
- }
1099
- function addPickSchema(tsType, schemaId) {
1100
- return t__namespace.tsTypeReference(
1101
- PickSchema,
1102
- t__namespace.tsTypeParameterInstantiation([tsType, t__namespace.tsLiteralType(t__namespace.stringLiteral(schemaId))])
1103
- );
1104
- }
1105
- function generateCode(node) {
1106
- return `${new generator.CodeGenerator(node).generate().code.trim()}
1107
-
1108
- `;
746
+ function uppercaseFirstLetter(input) {
747
+ return input.charAt(0).toUpperCase() + input.slice(1);
1109
748
  }
1110
- function promiseWithResolvers() {
1111
- let resolve, reject;
1112
- return { promise: new Promise((thisResolve, thisReject) => {
1113
- resolve = thisResolve, reject = thisReject;
1114
- }), resolve, reject };
749
+ function sanitizeIdentifier(input) {
750
+ return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
1115
751
  }
1116
- exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
1117
752
  exports.TypeGenerator = TypeGenerator;
1118
753
  exports.findQueriesInPath = findQueriesInPath;
1119
754
  exports.findQueriesInSource = findQueriesInSource;