@sanity/codegen 7.0.3 → 8.1.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/helpers.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type ArrayTypeNode, type UnionTypeNode} from 'groq-js'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {RESERVED_IDENTIFIERS} from './constants.js'\n\nexport function normalizePrintablePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n // Always use Unix-style paths for consistent output across platforms\n return formatPath(path.relative(root, resolved))\n}\n\n/**\n * Normalizes a glob pattern to use forward slashes (POSIX-style paths).\n * Glob patterns must use forward slashes, even on Windows.\n *\n * @param pattern - A glob pattern string or array of patterns\n * @returns The normalized pattern(s) with forward slashes\n * @see https://github.com/sindresorhus/globby#api\n */\nexport function normalizeGlobPattern(pattern: string | string[]): string | string[] {\n if (Array.isArray(pattern)) {\n return pattern.map((p) => formatPath(p))\n }\n return formatPath(pattern)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replaceAll(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\n/**\n * Checks if a string is a valid ECMAScript IdentifierName.\n * IdentifierNames start with a letter, underscore, or $, and contain only\n * alphanumeric characters, underscores, or $.\n */\nexport function isIdentifierName(input: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(input)\n}\n\nfunction normalizeIdentifier(input: string): string {\n const sanitized = sanitizeIdentifier(input)\n return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`\n}\n\nexport function getUniqueIdentifierForName(name: string, currentIdentifiers: Set<string>) {\n const desiredName = normalizeIdentifier(name)\n let resultingName = desiredName\n let index = 2\n while (currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName)) {\n resultingName = `${desiredName}_${index}`\n index++\n }\n return t.identifier(resultingName)\n}\n\nexport function computeOnce<TReturn>(fn: () => TReturn): () => TReturn {\n const ref = {computed: false, current: undefined as TReturn | undefined}\n\n return function () {\n if (ref.computed) return ref.current as TReturn\n ref.current = fn()\n ref.computed = true\n return ref.current\n }\n}\n\nexport function weakMapMemo<TParam extends object, TReturn>(fn: (arg: TParam) => TReturn) {\n const cache = new WeakMap<object, TReturn>()\n\n const wrapped = function (arg: TParam) {\n if (cache.has(arg)) return cache.get(arg)!\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }\n\n return wrapped\n}\n\nexport function generateCode(node: t.Node) {\n return `${new CodeGenerator(node).generate().code.trim()}\\n\\n`\n}\n\nexport function getFilterArrayUnionType(\n typeNode: ArrayTypeNode,\n predicate: (unionTypeNode: UnionTypeNode['of'][number]) => boolean,\n): ArrayTypeNode {\n if (typeNode.of.type !== 'union') {\n return typeNode\n }\n\n return {\n ...typeNode,\n of: {\n ...typeNode.of,\n of: typeNode.of.of.filter((unionTypeNode) => predicate(unionTypeNode)),\n },\n } satisfies ArrayTypeNode<UnionTypeNode>\n}\n"],"names":["path","CodeGenerator","t","formatPath","RESERVED_IDENTIFIERS","normalizePrintablePath","root","filename","resolved","resolve","relative","normalizeGlobPattern","pattern","Array","isArray","map","p","sanitizeIdentifier","input","replace","replaceAll","_","char","toUpperCase","isIdentifierName","test","normalizeIdentifier","sanitized","charAt","slice","getUniqueIdentifierForName","name","currentIdentifiers","desiredName","resultingName","index","has","identifier","computeOnce","fn","ref","computed","current","undefined","weakMapMemo","cache","WeakMap","wrapped","arg","get","result","set","generateCode","node","generate","code","trim","getFilterArrayUnionType","typeNode","predicate","of","type","filter","unionTypeNode"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,YAAYC,OAAO,eAAc;AAGjC,SAAQC,UAAU,QAAO,yBAAwB;AACjD,SAAQC,oBAAoB,QAAO,iBAAgB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ACf,OAAOD,IAAIE,OAAO;IACpB;AACF;AAEA,OAAO,SAASE,YAA4CL,EAA4B;IACtF,MAAMM,QAAQ,IAAIC;IAElB,MAAMC,UAAU,SAAUC,GAAW;QACnC,IAAIH,MAAMT,GAAG,CAACY,MAAM,OAAOH,MAAMI,GAAG,CAACD;QACrC,MAAME,SAASX,GAAGS;QAClBH,MAAMM,GAAG,CAACH,KAAKE;QACf,OAAOA;IACT;IAEA,OAAOH;AACT;AAEA,OAAO,SAASK,aAAaC,IAAY;IACvC,OAAO,GAAG,IAAIpD,cAAcoD,MAAMC,QAAQ,GAAGC,IAAI,CAACC,IAAI,GAAG,IAAI,CAAC;AAChE;AAEA,OAAO,SAASC,wBACdC,QAAuB,EACvBC,SAAkE;IAElE,IAAID,SAASE,EAAE,CAACC,IAAI,KAAK,SAAS;QAChC,OAAOH;IACT;IAEA,OAAO;QACL,GAAGA,QAAQ;QACXE,IAAI;YACF,GAAGF,SAASE,EAAE;YACdA,IAAIF,SAASE,EAAE,CAACA,EAAE,CAACE,MAAM,CAAC,CAACC,gBAAkBJ,UAAUI;QACzD;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/helpers.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type ArrayTypeNode, type UnionTypeNode} from 'groq-js'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {RESERVED_IDENTIFIERS} from './constants.js'\n\nexport function normalizePrintablePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n // Always use Unix-style paths for consistent output across platforms\n return formatPath(path.relative(root, resolved))\n}\n\n/**\n * Normalizes a glob pattern to use forward slashes (POSIX-style paths).\n * Glob patterns must use forward slashes, even on Windows.\n *\n * @param pattern - A glob pattern string or array of patterns\n * @returns The normalized pattern(s) with forward slashes\n * @see https://github.com/sindresorhus/globby#api\n */\nexport function normalizeGlobPattern(pattern: string | string[]): string | string[] {\n if (Array.isArray(pattern)) {\n return pattern.map((p) => formatPath(p))\n }\n return formatPath(pattern)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replaceAll(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\n/**\n * Checks if a string is a valid ECMAScript IdentifierName.\n * IdentifierNames start with a letter, underscore, or $, and contain only\n * alphanumeric characters, underscores, or $.\n */\nexport function isIdentifierName(input: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(input)\n}\n\nfunction normalizeIdentifier(input: string): string {\n const sanitized = sanitizeIdentifier(input)\n return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`\n}\n\nexport function getUniqueIdentifierForName(name: string, currentIdentifiers: Set<string>) {\n const desiredName = normalizeIdentifier(name)\n let resultingName = desiredName\n let index = 2\n while (currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName)) {\n resultingName = `${desiredName}_${index}`\n index++\n }\n return t.identifier(resultingName)\n}\n\nexport function computeOnce<TReturn>(fn: () => TReturn): () => TReturn {\n const ref = {computed: false, current: undefined as TReturn | undefined}\n\n return function () {\n if (ref.computed) return ref.current as TReturn\n ref.current = fn()\n ref.computed = true\n return ref.current\n }\n}\n\nexport function weakMapMemo<TParam extends object, TReturn>(fn: (arg: TParam) => TReturn) {\n const cache = new WeakMap<object, TReturn>()\n\n const wrapped = function (arg: TParam) {\n if (cache.has(arg)) return cache.get(arg)!\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }\n\n return wrapped\n}\n\nexport function generateCode(node: t.Node) {\n return `${new CodeGenerator(node).generate().code.trim()}\\n\\n`\n}\n\n/**\n * Builds a `declare global { … }` block.\n */\nexport function tsDeclareGlobal(body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body))\n declaration.declare = true\n // Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the\n // output is `declare global {` on either.\n declaration.global = true\n declaration.kind = 'global'\n return declaration\n}\n\n/**\n * Builds a `declare module \"<name>\" { … }` block.\n */\nexport function tsDeclareModule(name: string, body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body))\n declaration.declare = true\n declaration.kind = 'module'\n return declaration\n}\n\nexport function getFilterArrayUnionType(\n typeNode: ArrayTypeNode,\n predicate: (unionTypeNode: UnionTypeNode['of'][number]) => boolean,\n): ArrayTypeNode {\n if (typeNode.of.type !== 'union') {\n return typeNode\n }\n\n return {\n ...typeNode,\n of: {\n ...typeNode.of,\n of: typeNode.of.of.filter((unionTypeNode) => predicate(unionTypeNode)),\n },\n } satisfies ArrayTypeNode<UnionTypeNode>\n}\n"],"names":["path","CodeGenerator","t","formatPath","RESERVED_IDENTIFIERS","normalizePrintablePath","root","filename","resolved","resolve","relative","normalizeGlobPattern","pattern","Array","isArray","map","p","sanitizeIdentifier","input","replace","replaceAll","_","char","toUpperCase","isIdentifierName","test","normalizeIdentifier","sanitized","charAt","slice","getUniqueIdentifierForName","name","currentIdentifiers","desiredName","resultingName","index","has","identifier","computeOnce","fn","ref","computed","current","undefined","weakMapMemo","cache","WeakMap","wrapped","arg","get","result","set","generateCode","node","generate","code","trim","tsDeclareGlobal","body","declaration","tsModuleDeclaration","tsModuleBlock","declare","global","kind","tsDeclareModule","stringLiteral","getFilterArrayUnionType","typeNode","predicate","of","type","filter","unionTypeNode"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,YAAYC,OAAO,eAAc;AAGjC,SAAQC,UAAU,QAAO,yBAAwB;AACjD,SAAQC,oBAAoB,QAAO,iBAAgB;AAEnD,OAAO,SAASC,uBAAuBC,IAAY,EAAEC,QAAgB;IACnE,MAAMC,WAAWR,KAAKS,OAAO,CAACH,MAAMC;IACpC,qEAAqE;IACrE,OAAOJ,WAAWH,KAAKU,QAAQ,CAACJ,MAAME;AACxC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,OAAOH,MAAMI,GAAG,CAACD;QACrC,MAAME,SAASX,GAAGS;QAClBH,MAAMM,GAAG,CAACH,KAAKE;QACf,OAAOA;IACT;IAEA,OAAOH;AACT;AAEA,OAAO,SAASK,aAAaC,IAAY;IACvC,OAAO,GAAG,IAAIpD,cAAcoD,MAAMC,QAAQ,GAAGC,IAAI,CAACC,IAAI,GAAG,IAAI,CAAC;AAChE;AAEA;;CAEC,GACD,OAAO,SAASC,gBAAgBC,IAAmB;IACjD,MAAMC,cAAczD,EAAE0D,mBAAmB,CAAC1D,EAAEmC,UAAU,CAAC,WAAWnC,EAAE2D,aAAa,CAACH;IAClFC,YAAYG,OAAO,GAAG;IACtB,8FAA8F;IAC9F,0CAA0C;IAC1CH,YAAYI,MAAM,GAAG;IACrBJ,YAAYK,IAAI,GAAG;IACnB,OAAOL;AACT;AAEA;;CAEC,GACD,OAAO,SAASM,gBAAgBlC,IAAY,EAAE2B,IAAmB;IAC/D,MAAMC,cAAczD,EAAE0D,mBAAmB,CAAC1D,EAAEgE,aAAa,CAACnC,OAAO7B,EAAE2D,aAAa,CAACH;IACjFC,YAAYG,OAAO,GAAG;IACtBH,YAAYK,IAAI,GAAG;IACnB,OAAOL;AACT;AAEA,OAAO,SAASQ,wBACdC,QAAuB,EACvBC,SAAkE;IAElE,IAAID,SAASE,EAAE,CAACC,IAAI,KAAK,SAAS;QAChC,OAAOH;IACT;IAEA,OAAO;QACL,GAAGA,QAAQ;QACXE,IAAI;YACF,GAAGF,SAASE,EAAE;YACdA,IAAIF,SAASE,EAAE,CAACA,EAAE,CAACE,MAAM,CAAC,CAACC,gBAAkBJ,UAAUI;QACzD;IACF;AACF"}
@@ -3,7 +3,7 @@ import * as t from '@babel/types';
3
3
  import { createSelector } from 'reselect';
4
4
  import { resultSuffix } from '../casing.js';
5
5
  import { ALL_SANITY_SCHEMA_TYPES, ARRAY_OF, INTERNAL_REFERENCE_SYMBOL, SANITY_QUERIES } from './constants.js';
6
- import { computeOnce, generateCode, getUniqueIdentifierForName, normalizePrintablePath } from './helpers.js';
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';
9
9
  /**
@@ -166,20 +166,41 @@ import { QueryEvaluationError } from './types.js';
166
166
  typesByQuerystring[query].push(id.name);
167
167
  }
168
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(types.length > 0 ? t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type)))) : t.tsNeverKeyword()));
169
+ return t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type))))));
170
170
  })));
171
- const declareModule = t.declareModule(t.stringLiteral('@sanity/client'), t.blockStatement([
171
+ // The registry lives on the global `SanityQueries` interface, which `@sanity/client`'s exported
172
+ // `SanityQueries` inherits from. Registering globally needs no import of, and no module
173
+ // resolution to, `@sanity/client`: the registrations are seen whether or not the client is a
174
+ // direct dependency of this file, however many copies of it are installed, and from every entry
175
+ // point including `@sanity/client/stega`.
176
+ const globalRegistry = t.addComments(tsDeclareGlobal([
172
177
  queryReturnInterface
173
- ]));
174
- const clientImport = t.addComments(t.importDeclaration([], t.stringLiteral('@sanity/client')), 'leading', [
178
+ ]), 'leading', [
175
179
  {
176
180
  type: 'CommentLine',
177
181
  value: ' Query TypeMap'
178
182
  }
179
183
  ]);
184
+ // `@sanity/client` releases that predate the global registry only read their exported
185
+ // `SanityQueries` interface. Interface merging unions the `extends` clauses of every
186
+ // declaration, so adding the global interface as a base type makes those releases read the
187
+ // registry above. Releases that already inherit the global see a duplicate `extends` of the
188
+ // same type, which is accepted, so the same output works with either.
189
+ // `SANITY_QUERIES` is already the registry's identifier and a node must not appear twice in one
190
+ // tree, so the bridge mints its own.
191
+ const bridge = t.addComments(tsDeclareModule('@sanity/client', [
192
+ t.tsInterfaceDeclaration(t.identifier(SANITY_QUERIES.name), null, [
193
+ t.tsExpressionWithTypeArguments(t.tsQualifiedName(t.identifier('globalThis'), t.identifier(SANITY_QUERIES.name)))
194
+ ], t.tsInterfaceBody([]))
195
+ ]), 'leading', [
196
+ {
197
+ type: 'CommentLine',
198
+ value: ' Lets @sanity/client releases that predate the global registry read it too'
199
+ }
200
+ ]);
180
201
  const ast = t.program([
181
- clientImport,
182
- declareModule
202
+ globalRegistry,
203
+ bridge
183
204
  ]);
184
205
  const code = generateCode(ast);
185
206
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types.js'\n\n/** @public */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\n/** @public */\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n errors,\n filename,\n queries,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (queries.length === 0) return {ast: t.program([]), code: ''}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n types.length > 0\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n // Queries can produce `inline` type nodes that the schema-side generator\n // never sees (e.g. filtering a tagged-union array down to its inline\n // members). Evaluate modules before deciding whether the ArrayOf helper is\n // needed, so query-only usage still triggers the declaration.\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n const program = t.program([])\n let code = ''\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_QUERIES","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","filename","extractedModule","errors","extractedQuery","variable","stats","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","push","cause","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","Object","entries","types","stringLiteral","declareModule","blockStatement","clientImport","importDeclaration","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","generatedQueryTypes"],"mappings":"AAAA,sDAAsD,GACtD,OAAOA,aAAa,eAAc;AAElC,YAAYC,OAAO,eAAc;AAGjC,SAAQC,cAAc,QAAO,WAAU;AAEvC,SAAQC,YAAY,QAAO,eAAc;AACzC,SACEC,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CAACsB,wBAAwBlF,GAAG;QAC7CK,QAAQ6E,wBAAwB7E,IAAI;QAEpC,IAAImC,oBAAoB+C,aAAa,IAAI;YACvC,MAAMC,qBAAqB,IAAI,CAAC5E,qBAAqB;YACrDsD,QAAQoB,IAAI,CAAC1B,IAAI,CAAC4B,mBAAmBxF,GAAG;YACxCK,QAAQmF,mBAAmBnF,IAAI;QACjC;QAEA,KAAK,MAAMyB,eAAeS,uBAAwB;YAChD2B,QAAQoB,IAAI,CAAC1B,IAAI,CAAC9B,YAAY9B,GAAG;YACjCK,QAAQyB,YAAYzB,IAAI;QAC1B;QAEA6D,QAAQoB,IAAI,CAAC1B,IAAI,CAACuB,gCAAgCnF,GAAG;QACrDK,QAAQ8E,gCAAgC9E,IAAI;QAE5C,KAAK,MAAM,EAAC8B,OAAO,EAAC,IAAIO,iBAAkB;YACxC,KAAK,MAAMa,SAASpB,QAAS;gBAC3B+B,QAAQoB,IAAI,CAAC1B,IAAI,CAACL,MAAMvD,GAAG;gBAC3BK,QAAQkD,MAAMlD,IAAI;YACpB;QACF;QAEA,MAAMoF,sBAAsB,MAAMxG,cAAc+E,sBAAsB,CAAC;YACrE,GAAG7E,OAAO;YACVuD;QACF;QACAwB,QAAQoB,IAAI,CAAC1B,IAAI,IAAI6B,oBAAoBzF,GAAG,CAACsF,IAAI;QACjDjF,QAAQoF,oBAAoBpF,IAAI;QAEhCiC,QAAQ8C,MAAMM,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACzF,KAAKkE;YAAS7D;QAAI;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n tsDeclareGlobal,\n tsDeclareModule,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types.js'\n\n/** @public */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\n/** @public */\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n errors,\n filename,\n queries,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (queries.length === 0) return {ast: t.program([]), code: ''}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),\n ),\n )\n }),\n ),\n )\n\n // The registry lives on the global `SanityQueries` interface, which `@sanity/client`'s exported\n // `SanityQueries` inherits from. Registering globally needs no import of, and no module\n // resolution to, `@sanity/client`: the registrations are seen whether or not the client is a\n // direct dependency of this file, however many copies of it are installed, and from every entry\n // point including `@sanity/client/stega`.\n const globalRegistry = t.addComments(tsDeclareGlobal([queryReturnInterface]), 'leading', [\n {type: 'CommentLine', value: ' Query TypeMap'},\n ])\n\n // `@sanity/client` releases that predate the global registry only read their exported\n // `SanityQueries` interface. Interface merging unions the `extends` clauses of every\n // declaration, so adding the global interface as a base type makes those releases read the\n // registry above. Releases that already inherit the global see a duplicate `extends` of the\n // same type, which is accepted, so the same output works with either.\n // `SANITY_QUERIES` is already the registry's identifier and a node must not appear twice in one\n // tree, so the bridge mints its own.\n const bridge = t.addComments(\n tsDeclareModule('@sanity/client', [\n t.tsInterfaceDeclaration(\n t.identifier(SANITY_QUERIES.name),\n null,\n [\n t.tsExpressionWithTypeArguments(\n t.tsQualifiedName(t.identifier('globalThis'), t.identifier(SANITY_QUERIES.name)),\n ),\n ],\n t.tsInterfaceBody([]),\n ),\n ]),\n 'leading',\n [\n {\n type: 'CommentLine',\n value: ' Lets @sanity/client releases that predate the global registry read it too',\n },\n ],\n )\n\n const ast = t.program([globalRegistry, bridge])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n // Queries can produce `inline` type nodes that the schema-side generator\n // never sees (e.g. filtering a tagged-union array down to its inline\n // members). Evaluate modules before deciding whether the ArrayOf helper is\n // needed, so query-only usage still triggers the declaration.\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n const program = t.program([])\n let code = ''\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_QUERIES","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","tsDeclareGlobal","tsDeclareModule","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","filename","extractedModule","errors","extractedQuery","variable","stats","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","push","cause","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","Object","entries","types","stringLiteral","globalRegistry","bridge","tsExpressionWithTypeArguments","tsQualifiedName","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","generatedQueryTypes"],"mappings":"AAAA,sDAAsD,GACtD,OAAOA,aAAa,eAAc;AAElC,YAAYC,OAAO,eAAc;AAGjC,SAAQC,cAAc,QAAO,WAAU;AAEvC,SAAQC,YAAY,QAAO,eAAc;AACzC,SACEC,uBAAuB,EACvBC,QAAQ,EACRC,yBAAyB,EACzBC,cAAc,QACT,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0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4 @@
1
- import { subdebug } from '@sanity/cli-core';
2
- export const debug = subdebug('typegen:generate');
1
+ import createDebug from 'debug';
2
+ export const debug = createDebug('sanity:typegen:generate');
3
3
 
4
4
  //# sourceMappingURL=debug.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\n\nexport const debug = subdebug('typegen:generate')\n"],"names":["subdebug","debug"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAO,MAAMC,QAAQD,SAAS,oBAAmB"}
1
+ {"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import createDebug from 'debug'\n\nexport const debug = createDebug('sanity:typegen:generate')\n"],"names":["createDebug","debug"],"mappings":"AAAA,OAAOA,iBAAiB,QAAO;AAE/B,OAAO,MAAMC,QAAQD,YAAY,2BAA0B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/codegen",
3
- "version": "7.0.3",
3
+ "version": "8.1.0",
4
4
  "description": "Codegen toolkit for Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -33,8 +33,6 @@
33
33
  "types": "./dist/_exports/index.d.ts",
34
34
  "files": [
35
35
  "dist",
36
- "oclif.manifest.json",
37
- "oclif.config.js",
38
36
  "babel.config.json"
39
37
  ],
40
38
  "dependencies": {
@@ -52,20 +50,20 @@
52
50
  "debug": "^4.4.3",
53
51
  "globby": "^11.1.0",
54
52
  "groq": "^6.0.0",
55
- "groq-js": "^1.30.2",
53
+ "groq-js": "^2.0.0",
56
54
  "json5": "^2.2.3",
57
55
  "lodash-es": "^4.18.1",
58
56
  "prettier": "^3.8.3",
59
57
  "reselect": "^5.2.0",
60
58
  "tsconfig-paths": "^4.2.0",
61
- "zod": "^4.4.3"
59
+ "valibot": "^1.4.2"
62
60
  },
63
61
  "devDependencies": {
64
62
  "@eslint/compat": "^2.1.0",
65
- "@sanity/cli-core": "^2.0.1",
66
- "@sanity/cli-test": "^1.0.1",
67
63
  "@sanity/eslint-config-cli": "^1.1.2",
68
64
  "@sanity/pkg-utils": "^10.5.5",
65
+ "@size-limit/esbuild": "^13.0.3",
66
+ "@size-limit/file": "^13.0.3",
69
67
  "@swc/cli": "^0.8.1",
70
68
  "@swc/core": "^1.15.40",
71
69
  "@types/babel__core": "^7.20.5",
@@ -74,24 +72,22 @@
74
72
  "@types/babel__traverse": "^7.28.0",
75
73
  "@types/debug": "^4.1.13",
76
74
  "@types/lodash-es": "^4.17.12",
77
- "@types/node": "^24.13.0",
75
+ "@types/node": "^24.13.3",
78
76
  "@vitest/coverage-istanbul": "^4.1.8",
79
77
  "eslint": "^9.39.4",
80
78
  "husky": "^9.1.7",
81
79
  "lint-staged": "^16.4.0",
82
- "oclif": "^4.23.10",
83
- "oxfmt": "^0.53.0",
84
- "pkg-pr-new": "^0.0.75",
80
+ "oxfmt": "^0.66.0",
81
+ "pkg-pr-new": "^0.0.88",
85
82
  "prettier-plugin-packagejson": "^3.0.2",
86
83
  "rimraf": "^5.0.10",
84
+ "size-limit": "^13.0.3",
87
85
  "tinyglobby": "^0.2.17",
88
86
  "typescript": "^5.9.3",
89
- "vite": "^8.0.16",
87
+ "vite": "^8.2.2",
90
88
  "vitest": "^4.1.8"
91
89
  },
92
90
  "peerDependencies": {
93
- "@oclif/core": "^4.8.0",
94
- "@sanity/cli-core": "^2",
95
91
  "oxfmt": "*"
96
92
  },
97
93
  "peerDependenciesMeta": {
@@ -100,17 +96,17 @@
100
96
  }
101
97
  },
102
98
  "engines": {
103
- "node": ">=20.19 <22 || >=22.12"
99
+ "node": ">=22.12"
104
100
  },
105
101
  "publishConfig": {
106
102
  "access": "public"
107
103
  },
108
104
  "scripts": {
109
105
  "build": "swc --delete-dir-on-start src -d dist --strip-leading-paths --ignore '**/__tests__/**' && pnpm run build:types",
110
- "postbuild": "oclif manifest",
111
106
  "build:types": "pkg-utils build --emitDeclarationOnly",
112
107
  "clean": "rimraf dist coverage",
113
108
  "lint": "eslint . --fix",
109
+ "size": "size-limit",
114
110
  "pretest": "pnpm build",
115
111
  "test": "vitest",
116
112
  "watch": "swc src -d dist --strip-leading-paths --watch"
@@ -1,185 +0,0 @@
1
- import { stat } from 'node:fs/promises';
2
- import { styleText } from 'node:util';
3
- import { Flags } from '@oclif/core';
4
- import { SanityCommand } from '@sanity/cli-core';
5
- import { spinner } from '@sanity/cli-core/ux';
6
- import omit from 'lodash-es/omit.js';
7
- import once from 'lodash-es/once.js';
8
- import { runTypegenGenerate } from '../../actions/typegenGenerate.js';
9
- import { runTypegenWatcher } from '../../actions/typegenWatch.js';
10
- import { configDefinition, readConfig } from '../../readConfig.js';
11
- import { TypegenWatchModeTrace, TypesGeneratedTrace } from '../../typegen.telemetry.js';
12
- import { debug } from '../../utils/debug.js';
13
- import { promiseWithResolvers } from '../../utils/promiseWithResolvers.js';
14
- const description = `Sanity TypeGen
15
-
16
- ${styleText('bold', 'Configuration:')}
17
- This command can utilize configuration settings defined in a \`sanity-typegen.json\` file. These settings include:
18
-
19
- - "path": Specifies a glob pattern to locate your TypeScript or JavaScript files.
20
- Default: "./src/**/*.{ts,tsx,js,jsx}"
21
-
22
- - "schema": Defines the path to your Sanity schema file. This file should be generated using the \`sanity schema extract\` command.
23
- Default: "schema.json"
24
-
25
- - "generates": Indicates the path where the generated TypeScript type definitions will be saved.
26
- Default: "./sanity.types.ts"
27
-
28
- The default configuration values listed above are used if not overridden in your \`sanity-typegen.json\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.
29
-
30
- ${styleText('bold', 'Note:')}
31
- - The \`sanity schema extract\` command is a prerequisite for extracting your Sanity Studio schema into a \`schema.json\` file, which is then used by the \`sanity typegen generate\` command to generate type definitions.`.trim();
32
- /**
33
- * @internal
34
- */ export class TypegenGenerateCommand extends SanityCommand {
35
- static description = description;
36
- static examples = [
37
- {
38
- command: '<%= config.bin %> <%= command.id %>',
39
- description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \`sanity schema extract\` command.`
40
- }
41
- ];
42
- static flags = {
43
- 'config-path': Flags.string({
44
- description: '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.'
45
- }),
46
- watch: Flags.boolean({
47
- default: false,
48
- description: '[Default: false] Run the typegen in watch mode'
49
- })
50
- };
51
- async run() {
52
- const { flags } = await this.parse(TypegenGenerateCommand);
53
- if (flags.watch) {
54
- await this.runWatcher();
55
- return;
56
- }
57
- await this.runSingle();
58
- }
59
- async getConfig() {
60
- const spin = spinner({}).start('Loading config…');
61
- try {
62
- const { flags } = await this.parse(TypegenGenerateCommand);
63
- const rootDir = await this.getProjectRoot();
64
- const config = await this.getCliConfig();
65
- const configPath = flags['config-path'];
66
- const workDir = rootDir.directory;
67
- // check if the legacy config exist
68
- const legacyConfigPath = configPath || 'sanity-typegen.json';
69
- let hasLegacyConfig = false;
70
- try {
71
- const file = await stat(legacyConfigPath);
72
- hasLegacyConfig = file.isFile();
73
- } catch (err) {
74
- if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {
75
- spin.fail();
76
- this.error(`Typegen config file not found: ${configPath}`, {
77
- exit: 1
78
- });
79
- }
80
- if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {
81
- spin.fail();
82
- this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {
83
- exit: 1
84
- });
85
- }
86
- }
87
- // we have both legacy and cli config with typegen
88
- if (config?.typegen && hasLegacyConfig) {
89
- spin.warn(styleText('yellow', `You've specified typegen in your Sanity CLI config, but also have a typegen config.
90
-
91
- The config from the Sanity CLI config is used.
92
- `));
93
- return {
94
- config: configDefinition.parse(config.typegen || {}),
95
- path: rootDir.path,
96
- type: 'cli',
97
- workDir
98
- };
99
- }
100
- // we only have legacy typegen config
101
- if (hasLegacyConfig) {
102
- spin.warn(styleText('yellow', `The separate typegen config has been deprecated. Use \`typegen\` in the sanity CLI config instead.
103
-
104
- See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`));
105
- return {
106
- config: await readConfig(legacyConfigPath),
107
- path: legacyConfigPath,
108
- type: 'legacy',
109
- workDir
110
- };
111
- }
112
- spin.succeed(`Config loaded from sanity.cli.ts`);
113
- // we only have cli config
114
- return {
115
- config: configDefinition.parse(config.typegen || {}),
116
- path: rootDir.path,
117
- type: 'cli',
118
- workDir
119
- };
120
- } catch (err) {
121
- spin.fail();
122
- this.error(`An error occured during config loading ${err}`, {
123
- exit: 1
124
- });
125
- }
126
- }
127
- async runSingle() {
128
- const trace = this.telemetry.trace(TypesGeneratedTrace);
129
- try {
130
- const { config: typegenConfig, type: typegenConfigMethod, workDir } = await this.getConfig();
131
- trace.start();
132
- const result = await runTypegenGenerate({
133
- config: typegenConfig,
134
- workDir
135
- });
136
- const traceStats = omit(result, 'code', 'duration');
137
- trace.log({
138
- configMethod: typegenConfigMethod,
139
- configOverloadClientMethods: typegenConfig.overloadClientMethods,
140
- ...traceStats
141
- });
142
- trace.complete();
143
- } catch (error) {
144
- debug(error);
145
- trace.error(error);
146
- this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
147
- exit: 1
148
- });
149
- }
150
- }
151
- async runWatcher() {
152
- const trace = this.telemetry.trace(TypegenWatchModeTrace);
153
- try {
154
- const { config: typegenConfig, workDir } = await this.getConfig();
155
- trace.start();
156
- const { promise, resolve } = promiseWithResolvers();
157
- const typegenWatcher = runTypegenWatcher({
158
- config: typegenConfig,
159
- workDir
160
- });
161
- const stop = once(async ()=>{
162
- process.off('SIGINT', stop);
163
- process.off('SIGTERM', stop);
164
- trace.log({
165
- step: 'stopped',
166
- ...typegenWatcher.getStats()
167
- });
168
- trace.complete();
169
- await typegenWatcher.stop();
170
- resolve();
171
- });
172
- process.on('SIGINT', stop);
173
- process.on('SIGTERM', stop);
174
- await promise;
175
- } catch (error) {
176
- debug(error);
177
- trace.error(error);
178
- this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
179
- exit: 1
180
- });
181
- }
182
- }
183
- }
184
-
185
- //# sourceMappingURL=generate.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\nimport omit from 'lodash-es/omit.js'\nimport once from 'lodash-es/once.js'\n\nimport {runTypegenGenerate} from '../../actions/typegenGenerate.js'\nimport {runTypegenWatcher} from '../../actions/typegenWatch.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {TypegenWatchModeTrace, TypesGeneratedTrace} from '../../typegen.telemetry.js'\nimport {debug} from '../../utils/debug.js'\nimport {promiseWithResolvers} from '../../utils/promiseWithResolvers.js'\n\nconst description = `Sanity TypeGen\n\n${styleText('bold', 'Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${styleText('bold', 'Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.`.trim()\n\n/**\n * @internal\n */\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n watch: Flags.boolean({\n default: false,\n description: '[Default: false] Run the typegen in watch mode',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n\n if (flags.watch) {\n await this.runWatcher()\n return\n }\n\n await this.runSingle()\n }\n\n private async getConfig(): Promise<{\n config: TypeGenConfig\n path?: string\n type: 'cli' | 'legacy'\n workDir: string\n }> {\n const spin = spinner({}).start('Loading config…')\n\n try {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n const configPath = flags['config-path']\n const workDir = rootDir.directory\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n\n try {\n const file = await stat(legacyConfigPath)\n hasLegacyConfig = file.isFile()\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n spin.fail()\n this.error(`Typegen config file not found: ${configPath}`, {exit: 1})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n spin.fail()\n this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n exit: 1,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n styleText(\n 'yellow',\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n styleText(\n 'yellow',\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n workDir,\n }\n }\n\n spin.succeed(`Config loaded from sanity.cli.ts`)\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n } catch (err) {\n spin.fail()\n this.error(`An error occured during config loading ${err}`, {exit: 1})\n }\n }\n\n private async runSingle() {\n const trace = this.telemetry.trace(TypesGeneratedTrace)\n\n try {\n const {config: typegenConfig, type: typegenConfigMethod, workDir} = await this.getConfig()\n trace.start()\n\n const result = await runTypegenGenerate({\n config: typegenConfig,\n workDir,\n })\n\n const traceStats = omit(result, 'code', 'duration')\n\n trace.log({\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: typegenConfig.overloadClientMethods,\n ...traceStats,\n })\n trace.complete()\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n\n private async runWatcher() {\n const trace = this.telemetry.trace(TypegenWatchModeTrace)\n\n try {\n const {config: typegenConfig, workDir} = await this.getConfig()\n trace.start()\n\n const {promise, resolve} = promiseWithResolvers()\n\n const typegenWatcher = runTypegenWatcher({\n config: typegenConfig,\n workDir,\n })\n\n const stop = once(async () => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n\n trace.log({\n step: 'stopped',\n ...typegenWatcher.getStats(),\n })\n trace.complete()\n\n await typegenWatcher.stop()\n resolve()\n })\n\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n await promise\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n}\n"],"names":["stat","styleText","Flags","SanityCommand","spinner","omit","once","runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","TypegenWatchModeTrace","TypesGeneratedTrace","debug","promiseWithResolvers","description","trim","TypegenGenerateCommand","examples","command","flags","string","watch","boolean","default","run","parse","runWatcher","runSingle","getConfig","spin","start","rootDir","getProjectRoot","config","getCliConfig","configPath","workDir","directory","legacyConfigPath","hasLegacyConfig","file","isFile","err","Error","code","fail","error","exit","typegen","warn","path","type","succeed","trace","telemetry","typegenConfig","typegenConfigMethod","result","traceStats","log","configMethod","configOverloadClientMethods","overloadClientMethods","complete","message","promise","resolve","typegenWatcher","stop","process","off","step","getStats","on"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,OAAOC,UAAU,oBAAmB;AACpC,OAAOC,UAAU,oBAAmB;AAEpC,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,iBAAiB,QAAO,gCAA+B;AAC/D,SAAQC,gBAAgB,EAAEC,UAAU,QAA2B,sBAAqB;AACpF,SAAQC,qBAAqB,EAAEC,mBAAmB,QAAO,6BAA4B;AACrF,SAAQC,KAAK,QAAO,uBAAsB;AAC1C,SAAQC,oBAAoB,QAAO,sCAAqC;AAExE,MAAMC,cAAc,CAAC;;AAErB,EAAEd,UAAU,QAAQ,kBAAkB;;;;;;;;;;;;;;AActC,EAAEA,UAAU,QAAQ,SAAS;2NAC8L,CAAC,CAACe,IAAI;AAEjO;;CAEC,GACD,OAAO,MAAMC,+BAA+Bd;IAC1C,OAAgBY,cAAcA,YAAW;IAEzC,OAAgBG,WAAW;QACzB;YACEC,SAAS;YACTJ,aAAa,CAAC,uHAAuH,CAAC;QACxI;KACD,CAAA;IAED,OAAgBK,QAAQ;QACtB,eAAelB,MAAMmB,MAAM,CAAC;YAC1BN,aACE;QACJ;QACAO,OAAOpB,MAAMqB,OAAO,CAAC;YACnBC,SAAS;YACTT,aAAa;QACf;IACF,EAAC;IAED,MAAaU,MAAM;QACjB,MAAM,EAACL,KAAK,EAAC,GAAG,MAAM,IA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AAI,CAACC,SAAS,CAACD,KAAK,CAAC3C;QAEnC,IAAI;YACF,MAAM,EAACuB,QAAQsB,aAAa,EAAEnB,OAAO,EAAC,GAAG,MAAM,IAAI,CAACR,SAAS;YAC7DyB,MAAMvB,KAAK;YAEX,MAAM,EAACmC,OAAO,EAAEC,OAAO,EAAC,GAAGrD;YAE3B,MAAMsD,iBAAiB5D,kBAAkB;gBACvC0B,QAAQsB;gBACRnB;YACF;YAEA,MAAMgC,OAAO/D,KAAK;gBAChBgE,QAAQC,GAAG,CAAC,UAAUF;gBACtBC,QAAQC,GAAG,CAAC,WAAWF;gBAEvBf,MAAMM,GAAG,CAAC;oBACRY,MAAM;oBACN,GAAGJ,eAAeK,QAAQ,EAAE;gBAC9B;gBACAnB,MAAMU,QAAQ;gBAEd,MAAMI,eAAeC,IAAI;gBACzBF;YACF;YAEAG,QAAQI,EAAE,CAAC,UAAUL;YACrBC,QAAQI,EAAE,CAAC,WAAWL;YAEtB,MAAMH;QACR,EAAE,OAAOnB,OAAO;YACdlC,MAAMkC;YACNO,MAAMP,KAAK,CAACA;YACZ,IAAI,CAACA,KAAK,CAAC,GAAGA,iBAAiBH,QAAQG,MAAMkB,OAAO,GAAG,iBAAiB,EAAE;gBACxEjB,MAAM;YACR;QACF;IACF;AACF"}
@@ -1,6 +0,0 @@
1
- export const count = (amount, plural = '', singular = plural.slice(0, Math.max(0, plural.length - 1)))=>[
2
- amount.toLocaleString('en-US'),
3
- amount === 1 ? singular : plural
4
- ].filter(Boolean).join(' ');
5
-
6
- //# sourceMappingURL=count.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/utils/count.ts"],"sourcesContent":["export const count = (\n amount: number,\n plural: string = '',\n singular: string = plural.slice(0, Math.max(0, plural.length - 1)),\n): string =>\n [amount.toLocaleString('en-US'), amount === 1 ? singular : plural].filter(Boolean).join(' ')\n"],"names":["count","amount","plural","singular","slice","Math","max","length","toLocaleString","filter","Boolean","join"],"mappings":"AAAA,OAAO,MAAMA,QAAQ,CACnBC,QACAC,SAAiB,EAAE,EACnBC,WAAmBD,OAAOE,KAAK,CAAC,GAAGC,KAAKC,GAAG,CAAC,GAAGJ,OAAOK,MAAM,GAAG,GAAG,GAElE;QAACN,OAAOO,cAAc,CAAC;QAAUP,WAAW,IAAIE,WAAWD;KAAO,CAACO,MAAM,CAACC,SAASC,IAAI,CAAC,KAAI"}
@@ -1,8 +0,0 @@
1
- const formatter = new Intl.NumberFormat('en-US', {
2
- maximumFractionDigits: 1,
3
- minimumFractionDigits: 1,
4
- style: 'percent'
5
- });
6
- export const percent = (value)=>formatter.format(Math.min(value, 1));
7
-
8
- //# sourceMappingURL=percent.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/utils/percent.ts"],"sourcesContent":["const formatter = new Intl.NumberFormat('en-US', {\n maximumFractionDigits: 1,\n minimumFractionDigits: 1,\n style: 'percent',\n})\n\nexport const percent = (value: number): string => formatter.format(Math.min(value, 1))\n"],"names":["formatter","Intl","NumberFormat","maximumFractionDigits","minimumFractionDigits","style","percent","value","format","Math","min"],"mappings":"AAAA,MAAMA,YAAY,IAAIC,KAAKC,YAAY,CAAC,SAAS;IAC/CC,uBAAuB;IACvBC,uBAAuB;IACvBC,OAAO;AACT;AAEA,OAAO,MAAMC,UAAU,CAACC,QAA0BP,UAAUQ,MAAM,CAACC,KAAKC,GAAG,CAACH,OAAO,IAAG"}
@@ -1,67 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import once from 'lodash-es/once.js';
5
- const BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../bin/run.js');
6
- const isAssertionError = (e)=>e instanceof Error && e.name === 'AssertionError';
7
- export async function testLongRunning(command, opts) {
8
- const { cwd = process.cwd(), expect: assertion, interval = 150, timeout = 20_000 } = opts;
9
- let stderr = '', stdout = '';
10
- // spawn command in child process
11
- const child = spawn('node', [
12
- BIN,
13
- ...command
14
- ], {
15
- cwd,
16
- env: {
17
- ...process.env,
18
- NO_COLOR: '1'
19
- },
20
- stdio: [
21
- 'pipe',
22
- 'pipe',
23
- 'pipe'
24
- ]
25
- });
26
- // track err and out
27
- child.stdout?.on('data', (d)=>stdout += d);
28
- child.stderr?.on('data', (d)=>stderr += d);
29
- const kill = once(()=>child.kill('SIGTERM'));
30
- // track errors from the child process
31
- let exitError = null;
32
- child.on('exit', (code)=>{
33
- if (code === 0) return;
34
- exitError = new Error(`Process exited with code ${code}\nstderr: ${stderr}`);
35
- });
36
- child.on('error', (e)=>{
37
- exitError = e;
38
- });
39
- // assert once every interval until expectation met, error or timeout
40
- const start = Date.now();
41
- async function assertExpectation() {
42
- if (exitError) throw exitError;
43
- try {
44
- await assertion({
45
- stderr,
46
- stdout
47
- });
48
- return {
49
- stderr,
50
- stdout
51
- };
52
- } catch (e) {
53
- if (!isAssertionError(e)) throw e;
54
- if (Date.now() - start > timeout) throw e;
55
- return new Promise((resolve)=>{
56
- setTimeout(()=>resolve(assertExpectation()), interval);
57
- });
58
- }
59
- }
60
- try {
61
- return await assertExpectation();
62
- } finally{
63
- kill();
64
- }
65
- }
66
-
67
- //# sourceMappingURL=testLongRunning.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/utils/test/testLongRunning.ts"],"sourcesContent":["import {spawn} from 'node:child_process'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport once from 'lodash-es/once.js'\n\nconst BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../bin/run.js')\n\ninterface Options {\n expect: (o: {stderr: string; stdout: string}) => Promise<void> | void\n\n cwd?: string\n interval?: number\n timeout?: number\n}\n\nconst isAssertionError = (e: unknown) => e instanceof Error && e.name === 'AssertionError'\n\nexport async function testLongRunning(\n command: string[],\n opts: Options,\n): Promise<{stderr: string; stdout: string}> {\n const {cwd = process.cwd(), expect: assertion, interval = 150, timeout = 20_000} = opts\n let stderr = '',\n stdout = ''\n\n // spawn command in child process\n const child = spawn('node', [BIN, ...command], {\n cwd,\n env: {...process.env, NO_COLOR: '1'},\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n\n // track err and out\n child.stdout?.on('data', (d) => (stdout += d))\n child.stderr?.on('data', (d) => (stderr += d))\n\n const kill = once(() => child.kill('SIGTERM'))\n\n // track errors from the child process\n let exitError: Error | null = null\n child.on('exit', (code) => {\n if (code === 0) return\n exitError = new Error(`Process exited with code ${code}\\nstderr: ${stderr}`)\n })\n\n child.on('error', (e) => {\n exitError = e\n })\n\n // assert once every interval until expectation met, error or timeout\n const start = Date.now()\n async function assertExpectation(): Promise<{stderr: string; stdout: string}> {\n if (exitError) throw exitError\n\n try {\n await assertion({stderr, stdout})\n return {stderr, stdout}\n } catch (e) {\n if (!isAssertionError(e)) throw e\n if (Date.now() - start > timeout) throw e\n\n return new Promise((resolve) => {\n setTimeout(() => resolve(assertExpectation()), interval)\n })\n }\n }\n\n try {\n return await assertExpectation()\n } finally {\n kill()\n }\n}\n"],"names":["spawn","path","fileURLToPath","once","BIN","resolve","dirname","url","isAssertionError","e","Error","name","testLongRunning","command","opts","cwd","process","expect","assertion","interval","timeout","stderr","stdout","child","env","NO_COLOR","stdio","on","d","kill","exitError","code","start","Date","now","assertExpectation","Promise","setTimeout"],"mappings":"AAAA,SAAQA,KAAK,QAAO,qBAAoB;AACxC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,aAAa,QAAO,WAAU;AAEtC,OAAOC,UAAU,oBAAmB;AAEpC,MAAMC,MAAMH,KAAKI,OAAO,CAACJ,KAAKK,OAAO,CAACJ,cAAc,YAAYK,GAAG,IAAI;AAUvE,MAAMC,mBAAmB,CAACC,IAAeA,aAAaC,SAASD,EAAEE,IAAI,KAAK;AAE1E,OAAO,eAAeC,gBACpBC,OAAiB,EACjBC,IAAa;IAEb,MAAM,EAACC,MAAMC,QAAQD,GAAG,EAAE,EAAEE,QAAQC,SAAS,EAAEC,WAAW,GAAG,EAAEC,UAAU,MAAM,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