@sanity/codegen 5.8.0 → 5.9.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.
- package/dist/actions/streamProcessor.js.map +1 -1
- package/dist/actions/typegenGenerate.js +2 -1
- package/dist/actions/typegenGenerate.js.map +1 -1
- package/dist/actions/typegenWatch.js +2 -1
- package/dist/actions/typegenWatch.js.map +1 -1
- package/dist/actions/types.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/utils/config.js +11 -0
- package/dist/utils/config.js.map +1 -0
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/streamProcessor.ts"],"sourcesContent":["import {debug} from 'node:console'\nimport {writeFile} from 'node:fs/promises'\n\nimport {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\nimport {format, resolveConfig as resolvePrettierConfig} from 'prettier'\n\nimport {count} from '../utils/count.js'\nimport {formatPath} from '../utils/formatPath.js'\nimport {getMessage} from '../utils/getMessage.js'\nimport {percent} from '../utils/percent.js'\nimport {generatedFileWarning} from './generatedFileWarning.js'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/actions/streamProcessor.ts"],"sourcesContent":["import {debug} from 'node:console'\nimport {writeFile} from 'node:fs/promises'\n\nimport {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\nimport {format, resolveConfig as resolvePrettierConfig} from 'prettier'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {count} from '../utils/count.js'\nimport {formatPath} from '../utils/formatPath.js'\nimport {getMessage} from '../utils/getMessage.js'\nimport {percent} from '../utils/percent.js'\nimport {generatedFileWarning} from './generatedFileWarning.js'\nimport {TypegenWorkerChannel} from './types.js'\n\n/**\n * Processes the event stream from a typegen worker thread.\n *\n * Listens to worker channel events, displays progress via CLI spinners,\n * writes the generated types to disk, and optionally formats with prettier.\n *\n * @param receiver - Worker channel receiver for typegen events\n * @param options - Typegen configuration options\n * @returns Generation result containing the generated code and statistics\n */\nexport async function processTypegenWorkerStream(\n receiver: WorkerChannelReceiver<TypegenWorkerChannel>,\n options: TypeGenConfig,\n) {\n const start = Date.now()\n const {formatGeneratedCode, generates, schema} = options\n let code = ''\n\n try {\n const spin = spinner().start(`Loading schema…`)\n\n await receiver.event.loadedSchema()\n spin.succeed(`Schema loaded from ${formatPath(schema ?? '')}`)\n\n spin.start('Generating schema types…')\n const {expectedFileCount} = await receiver.event.typegenStarted()\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n\n spin.text = 'Generating query types…'\n let queriesCount = 0\n let evaluatedFiles = 0\n let filesWithErrors = 0\n let queryFilesCount = 0\n let typeNodesGenerated = 0\n let unknownTypeNodesGenerated = 0\n let emptyUnionTypeNodesGenerated = 0\n\n for await (const {errors, queries} of receiver.stream.evaluatedModules()) {\n evaluatedFiles++\n queriesCount += queries.length\n queryFilesCount += queries.length > 0 ? 1 : 0\n filesWithErrors += errors.length > 0 ? 1 : 0\n\n for (const {stats} of queries) {\n typeNodesGenerated += stats.allTypes\n unknownTypeNodesGenerated += stats.unknownTypes\n emptyUnionTypeNodesGenerated += stats.emptyUnions\n }\n\n for (const error of errors) {\n spin.fail(getMessage(error))\n }\n\n if (!spin.isSpinning) {\n spin.start()\n }\n\n spin.text =\n `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\\n` +\n ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` +\n `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`\n }\n\n const result = await receiver.event.typegenComplete()\n code = `${generatedFileWarning}${result.code}`\n await writeFile(generates, code)\n\n let formattingError = false\n if (formatGeneratedCode) {\n spin.text = `Formatting generated types with prettier…`\n\n try {\n const prettierConfig = await resolvePrettierConfig(generates)\n const formattedCode = await format(code, {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await writeFile(generates, formattedCode)\n } catch (err) {\n formattingError = true\n spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`)\n }\n }\n\n if (filesWithErrors > 0) {\n spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`)\n }\n\n const stats = {\n duration: Date.now() - start,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n }\n\n let successText =\n `Successfully generated types to ${formatPath(generates)} in ${Number(stats.duration).toFixed(0)}ms` +\n `\\n └─ ${count(queriesCount, 'queries', 'query')} and ${count(schemaTypesCount, 'schema types', 'schema type')}` +\n `\\n └─ found queries in ${count(queryFilesCount, 'files', 'file')} after evaluating ${count(evaluatedFiles, 'files', 'file')}`\n\n if (formatGeneratedCode) {\n successText += `\\n └─ ${formattingError ? 'an error occured during formatting' : 'formatted the generated code with prettier'}`\n }\n\n spin.succeed(successText)\n\n return {\n ...stats,\n code,\n }\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n receiver.unsubscribe()\n }\n}\n"],"names":["debug","writeFile","spinner","format","resolveConfig","resolvePrettierConfig","count","formatPath","getMessage","percent","generatedFileWarning","processTypegenWorkerStream","receiver","options","start","Date","now","formatGeneratedCode","generates","schema","code","spin","event","loadedSchema","succeed","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","text","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","error","fail","isSpinning","result","typegenComplete","formattingError","prettierConfig","formattedCode","parser","err","warn","duration","outputSize","Buffer","by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gD,MAAM;YAChF;QACF;QAEA,IAAItB,kBAAkB,GAAG;YACvBb,KAAKoC,IAAI,CAAC,CAAC,sBAAsB,EAAEnD,MAAM4B,iBAAiB,SAAS,uBAAuB,CAAC;QAC7F;QAEA,MAAMS,QAAQ;YACZe,UAAU3C,KAAKC,GAAG,KAAKF;YACvBwB;YACAJ;YACAyB,YAAYC,OAAOC,UAAU,CAACzC;YAC9BY;YACAG;YACAN;YACAO;YACAC;YACAyB,uBACE1B,qBAAqB,IAAIC,4BAA4BD,qBAAqB;QAC9E;QAEA,IAAI2B,cACF,CAAC,gCAAgC,EAAExD,WAAWW,WAAW,IAAI,EAAE8C,OAAOrB,MAAMe,QAAQ,EAAEO,OAAO,CAAC,GAAG,EAAE,CAAC,GACpG,CAAC,OAAO,EAAE3D,MAAM0B,cAAc,WAAW,SAAS,KAAK,EAAE1B,MAAMuB,kBAAkB,gBAAgB,gBAAgB,GACjH,CAAC,wBAAwB,EAAEvB,MAAM6B,iBAAiB,SAAS,QAAQ,kBAAkB,EAAE7B,MAAM2B,gBAAgB,SAAS,SAAS;QAEjI,IAAIhB,qBAAqB;YACvB8C,eAAe,CAAC,OAAO,EAAEX,kBAAkB,uCAAuC,8CAA8C;QAClI;QAEA/B,KAAKG,OAAO,CAACuC;QAEb,OAAO;YACL,GAAGpB,KAAK;YACRvB;QACF;IACF,EAAE,OAAOoC,KAAK;QACZxD,MAAM,0BAA0BwD;QAChC,MAAMA;IACR,SAAU;QACR5C,SAASsD,WAAW;IACtB;AACF"}
|
|
@@ -4,6 +4,7 @@ import { dirname, isAbsolute, join } from 'node:path';
|
|
|
4
4
|
import { env } from 'node:process';
|
|
5
5
|
import { Worker } from 'node:worker_threads';
|
|
6
6
|
import { WorkerChannelReceiver } from '@sanity/worker-channels';
|
|
7
|
+
import { prepareConfig } from '../utils/config.js';
|
|
7
8
|
import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
8
9
|
/**
|
|
9
10
|
* Runs a single typegen generation.
|
|
@@ -15,7 +16,7 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
|
15
16
|
* @returns Generation result containing the generated code and statistics
|
|
16
17
|
*/ export async function runTypegenGenerate(options) {
|
|
17
18
|
const { config, workDir } = options;
|
|
18
|
-
const { formatGeneratedCode, generates, overloadClientMethods, path, schema } = config;
|
|
19
|
+
const { formatGeneratedCode, generates, overloadClientMethods, path, schema } = prepareConfig(config);
|
|
19
20
|
const outputPath = isAbsolute(generates) ? generates : join(workDir, generates);
|
|
20
21
|
// create output dir if it isn't there
|
|
21
22
|
const outputDir = dirname(outputPath);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/typegenGenerate.ts"],"sourcesContent":["import {debug} from 'node:console'\nimport {mkdir} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {processTypegenWorkerStream} from './streamProcessor.js'\nimport {\n type GenerationResult,\n type RunTypegenOptions,\n TypegenGenerateTypesWorkerData,\n TypegenWorkerChannel,\n} from './types.js'\n\n/**\n * Runs a single typegen generation.\n *\n * This is the programmatic API for generating TypeScript types from GROQ queries.\n * It spawns a worker thread to perform the generation and displays progress via CLI spinners.\n *\n * @param options - Configuration options including typegen config and working directory\n * @returns Generation result containing the generated code and statistics\n */\nexport async function runTypegenGenerate(options: RunTypegenOptions): Promise<GenerationResult> {\n const {config, workDir} = options\n\n const {formatGeneratedCode, generates, overloadClientMethods, path, schema}
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenGenerate.ts"],"sourcesContent":["import {debug} from 'node:console'\nimport {mkdir} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {prepareConfig} from '../utils/config.js'\nimport {processTypegenWorkerStream} from './streamProcessor.js'\nimport {\n type GenerationResult,\n type RunTypegenOptions,\n TypegenGenerateTypesWorkerData,\n TypegenWorkerChannel,\n} from './types.js'\n\n/**\n * Runs a single typegen generation.\n *\n * This is the programmatic API for generating TypeScript types from GROQ queries.\n * It spawns a worker thread to perform the generation and displays progress via CLI spinners.\n *\n * @param options - Configuration options including typegen config and working directory\n * @returns Generation result containing the generated code and statistics\n */\nexport async function runTypegenGenerate(options: RunTypegenOptions): Promise<GenerationResult> {\n const {config, workDir} = options\n\n const {formatGeneratedCode, generates, overloadClientMethods, path, schema} =\n prepareConfig(config)\n\n const outputPath = isAbsolute(generates) ? generates : join(workDir, generates)\n\n // create output dir if it isn't there\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n // set up worker\n const workerPath = new URL('../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath: schema,\n searchPath: path,\n workDir,\n }\n const worker = new Worker(workerPath, {env, workerData})\n\n try {\n const result = await processTypegenWorkerStream(\n WorkerChannelReceiver.from<TypegenWorkerChannel>(worker),\n {\n formatGeneratedCode,\n generates: outputPath,\n overloadClientMethods,\n path,\n schema,\n },\n )\n\n return result\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n worker.terminate()\n }\n}\n"],"names":["debug","mkdir","dirname","isAbsolute","join","env","Worker","WorkerChannelReceiver","prepareConfig","processTypegenWorkerStream","runTypegenGenerate","options","config","workDir","formatGeneratedCode","generates","overloadClientMethods","path","schema","outputPath","outputDir","recursive","workerPath","URL","url","workerData","schemaPath","searchPath","worker","result","from","err","terminate"],"mappings":"AAAA,SAAQA,KAAK,QAAO,eAAc;AAClC,SAAQC,KAAK,QAAO,mBAAkB;AACtC,SAAQC,OAAO,EAAEC,UAAU,EAAEC,IAAI,QAAO,YAAW;AACnD,SAAQC,GAAG,QAAO,eAAc;AAChC,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,0BAA0B,QAAO,uBAAsB;AAQ/D;;;;;;;;CAQC,GACD,OAAO,eAAeC,mBAAmBC,OAA0B;IACjE,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;IAE1B,MAAM,EAACG,mBAAmB,EAAEC,SAAS,EAAEC,qBAAqB,EAAEC,IAAI,EAAEC,MAAM,EAAC,GACzEV,cAAcI;IAEhB,MAAMO,aAAahB,WAAWY,aAAaA,YAAYX,KAAKS,SAASE;IAErE,sCAAsC;IACtC,MAAMK,YAAYlB,QAAQiB;IAC1B,MAAMlB,MAAMmB,WAAW;QAACC,WAAW;IAAI;IAEvC,gBAAgB;IAChB,MAAMC,aAAa,IAAIC,IAAI,wCAAwC,YAAYC,GAAG;IAClF,MAAMC,aAA6C;QACjDT;QACAU,YAAYR;QACZS,YAAYV;QACZJ;IACF;IACA,MAAMe,SAAS,IAAItB,OAAOgB,YAAY;QAACjB;QAAKoB;IAAU;IAEtD,IAAI;QACF,MAAMI,SAAS,MAAMpB,2BACnBF,sBAAsBuB,IAAI,CAAuBF,SACjD;YACEd;YACAC,WAAWI;YACXH;YACAC;YACAC;QACF;QAGF,OAAOW;IACT,EAAE,OAAOE,KAAK;QACZ/B,MAAM,0BAA0B+B;QAChC,MAAMA;IACR,SAAU;QACRH,OAAOI,SAAS;IAClB;AACF"}
|
|
@@ -2,6 +2,7 @@ import { debug, error } from 'node:console';
|
|
|
2
2
|
import { isAbsolute, join, relative } from 'node:path';
|
|
3
3
|
import chokidar from 'chokidar';
|
|
4
4
|
import { debounce, mean } from 'lodash-es';
|
|
5
|
+
import { prepareConfig } from '../utils/config.js';
|
|
5
6
|
import { runTypegenGenerate } from './typegenGenerate.js';
|
|
6
7
|
const IGNORED_PATTERNS = [
|
|
7
8
|
'**/node_modules/**',
|
|
@@ -48,7 +49,7 @@ const IGNORED_PATTERNS = [
|
|
|
48
49
|
* Implements debouncing and concurrency control to prevent multiple generations.
|
|
49
50
|
*/ export function runTypegenWatcher(options) {
|
|
50
51
|
const { config, workDir } = options;
|
|
51
|
-
const { path, schema } = config;
|
|
52
|
+
const { path, schema } = prepareConfig(config);
|
|
52
53
|
const stats = {
|
|
53
54
|
failedCount: 0,
|
|
54
55
|
startTime: Date.now(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {debug, error} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\n\nimport chokidar, {FSWatcher} from 'chokidar'\nimport {debounce, mean} from 'lodash-es'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {runTypegenGenerate} from './typegenGenerate.js'\nimport {type RunTypegenOptions} from './types.js'\n\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\n/** State for tracking generation status */\nexport interface WatchState {\n isGenerating: boolean\n pendingGeneration: boolean\n}\n\n/** Return type for createTypegenRunner */\ninterface TypegenRunner {\n runGeneration: () => Promise<void>\n state: WatchState\n}\n\ntype WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {step: 'stopped'}>, 'step'>\n\n/**\n * Creates a typegen runner with concurrency control.\n * If generation is already running, queues one more generation to run after completion.\n * Multiple queued requests are coalesced into a single pending generation.\n */\nexport function createTypegenRunner(onGenerate: () => Promise<unknown>): TypegenRunner {\n const state: WatchState = {\n isGenerating: false,\n pendingGeneration: false,\n }\n\n async function runGeneration(): Promise<void> {\n if (state.isGenerating) {\n state.pendingGeneration = true\n return\n }\n\n state.isGenerating = true\n state.pendingGeneration = false\n\n try {\n await onGenerate()\n } finally {\n state.isGenerating = false\n\n // If a change came in during generation, run again\n if (state.pendingGeneration) {\n state.pendingGeneration = false\n await runGeneration()\n }\n }\n }\n\n return {runGeneration, state}\n}\n\n/**\n * Starts a file watcher that triggers typegen on changes.\n * Watches both query files (via patterns) and the schema JSON file.\n * Implements debouncing and concurrency control to prevent multiple generations.\n */\nexport function runTypegenWatcher(options: RunTypegenOptions): {\n getStats: () => WatcherStats\n stop: () => Promise<void>\n watcher: FSWatcher\n} {\n const {config, workDir} = options\n const {path, schema} = config\n\n const stats = {\n failedCount: 0,\n startTime: Date.now(),\n successfulDurations: [] as number[],\n }\n\n const {runGeneration} = createTypegenRunner(async () => {\n try {\n const {duration} = await runTypegenGenerate(options)\n stats.successfulDurations.push(duration)\n } catch {\n stats.failedCount++\n }\n })\n\n // Debounced generation trigger\n const debouncedGenerate = debounce(runGeneration, 1000)\n\n // Build absolute patterns for query files and schema file\n const paths = Array.isArray(path) ? path : [path]\n const absoluteQueryPatterns = paths.map((pattern) =>\n isAbsolute(pattern) ? pattern : join(workDir, pattern),\n )\n const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema)\n const watchTargets = [...absoluteQueryPatterns, absoluteSchemaPath]\n\n // perform initial generation\n debouncedGenerate()\n\n // set up watcher\n const watcher = chokidar.watch(watchTargets, {\n cwd: workDir,\n ignored: IGNORED_PATTERNS,\n ignoreInitial: true,\n })\n\n watcher.on('all', (event: string, filePath: string) => {\n const timestamp = new Date().toLocaleTimeString()\n const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath\n debug(`[${timestamp}] ${event}: ${relativePath}`)\n debouncedGenerate()\n })\n\n watcher.on('error', (err: Error) => {\n error(`Watcher error: ${err.message}`)\n })\n\n return {\n getStats: () => ({\n averageGenerationDuration: mean(stats.successfulDurations) || 0,\n generationFailedCount: stats.failedCount,\n generationSuccessfulCount: stats.successfulDurations.length,\n watcherDuration: Date.now() - stats.startTime,\n }),\n stop: async () => {\n await watcher.close()\n },\n watcher,\n }\n}\n"],"names":["debug","error","isAbsolute","join","relative","chokidar","debounce","mean","runTypegenGenerate","IGNORED_PATTERNS","createTypegenRunner","onGenerate","state","isGenerating","pendingGeneration","runGeneration","runTypegenWatcher","options","config","workDir","path","schema","stats","failedCount","startTime","Date","now","successfulDurations","duration","push","debouncedGenerate","paths","Array","isArray","absoluteQueryPatterns","map","pattern","absoluteSchemaPath","watchTargets","watcher","watch","cwd","ignored","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","err","message","getStats","averageGenerationDuration","generationFailedCount","generationSuccessfulCount","length","watcherDuration","stop","close"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,KAAK,QAAO,eAAc;AACzC,SAAQC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,QAAO,YAAW;AAEpD,OAAOC,cAA2B,WAAU;AAC5C,SAAQC,QAAQ,EAAEC,IAAI,QAAO,YAAW;AAGxC,SAAQC,kBAAkB,QAAO,uBAAsB;AAGvD,MAAMC,mBAAmB;IACvB;IACA;IACA;IACA;IACA;CACD;AAgBD;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,UAAkC;IACpE,MAAMC,QAAoB;QACxBC,cAAc;QACdC,mBAAmB;IACrB;IAEA,eAAeC;QACb,IAAIH,MAAMC,YAAY,EAAE;YACtBD,MAAME,iBAAiB,GAAG;YAC1B;QACF;QAEAF,MAAMC,YAAY,GAAG;QACrBD,MAAME,iBAAiB,GAAG;QAE1B,IAAI;YACF,MAAMH;QACR,SAAU;YACRC,MAAMC,YAAY,GAAG;YAErB,mDAAmD;YACnD,IAAID,MAAME,iBAAiB,EAAE;gBAC3BF,MAAME,iBAAiB,GAAG;gBAC1B,MAAMC;YACR;QACF;IACF;IAEA,OAAO;QAACA;QAAeH;IAAK;AAC9B;AAEA;;;;CAIC,GACD,OAAO,SAASI,kBAAkBC,OAA0B;IAK1D,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;IAC1B,MAAM,EAACG,IAAI,EAAEC,MAAM,EAAC,
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {debug, error} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\n\nimport chokidar, {FSWatcher} from 'chokidar'\nimport {debounce, mean} from 'lodash-es'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {prepareConfig} from '../utils/config.js'\nimport {runTypegenGenerate} from './typegenGenerate.js'\nimport {type RunTypegenOptions} from './types.js'\n\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\n/** State for tracking generation status */\nexport interface WatchState {\n isGenerating: boolean\n pendingGeneration: boolean\n}\n\n/** Return type for createTypegenRunner */\ninterface TypegenRunner {\n runGeneration: () => Promise<void>\n state: WatchState\n}\n\ntype WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {step: 'stopped'}>, 'step'>\n\n/**\n * Creates a typegen runner with concurrency control.\n * If generation is already running, queues one more generation to run after completion.\n * Multiple queued requests are coalesced into a single pending generation.\n */\nexport function createTypegenRunner(onGenerate: () => Promise<unknown>): TypegenRunner {\n const state: WatchState = {\n isGenerating: false,\n pendingGeneration: false,\n }\n\n async function runGeneration(): Promise<void> {\n if (state.isGenerating) {\n state.pendingGeneration = true\n return\n }\n\n state.isGenerating = true\n state.pendingGeneration = false\n\n try {\n await onGenerate()\n } finally {\n state.isGenerating = false\n\n // If a change came in during generation, run again\n if (state.pendingGeneration) {\n state.pendingGeneration = false\n await runGeneration()\n }\n }\n }\n\n return {runGeneration, state}\n}\n\n/**\n * Starts a file watcher that triggers typegen on changes.\n * Watches both query files (via patterns) and the schema JSON file.\n * Implements debouncing and concurrency control to prevent multiple generations.\n */\nexport function runTypegenWatcher(options: RunTypegenOptions): {\n getStats: () => WatcherStats\n stop: () => Promise<void>\n watcher: FSWatcher\n} {\n const {config, workDir} = options\n const {path, schema} = prepareConfig(config)\n\n const stats = {\n failedCount: 0,\n startTime: Date.now(),\n successfulDurations: [] as number[],\n }\n\n const {runGeneration} = createTypegenRunner(async () => {\n try {\n const {duration} = await runTypegenGenerate(options)\n stats.successfulDurations.push(duration)\n } catch {\n stats.failedCount++\n }\n })\n\n // Debounced generation trigger\n const debouncedGenerate = debounce(runGeneration, 1000)\n\n // Build absolute patterns for query files and schema file\n const paths = Array.isArray(path) ? path : [path]\n const absoluteQueryPatterns = paths.map((pattern) =>\n isAbsolute(pattern) ? pattern : join(workDir, pattern),\n )\n const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema)\n const watchTargets = [...absoluteQueryPatterns, absoluteSchemaPath]\n\n // perform initial generation\n debouncedGenerate()\n\n // set up watcher\n const watcher = chokidar.watch(watchTargets, {\n cwd: workDir,\n ignored: IGNORED_PATTERNS,\n ignoreInitial: true,\n })\n\n watcher.on('all', (event: string, filePath: string) => {\n const timestamp = new Date().toLocaleTimeString()\n const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath\n debug(`[${timestamp}] ${event}: ${relativePath}`)\n debouncedGenerate()\n })\n\n watcher.on('error', (err: Error) => {\n error(`Watcher error: ${err.message}`)\n })\n\n return {\n getStats: () => ({\n averageGenerationDuration: mean(stats.successfulDurations) || 0,\n generationFailedCount: stats.failedCount,\n generationSuccessfulCount: stats.successfulDurations.length,\n watcherDuration: Date.now() - stats.startTime,\n }),\n stop: async () => {\n await watcher.close()\n },\n watcher,\n }\n}\n"],"names":["debug","error","isAbsolute","join","relative","chokidar","debounce","mean","prepareConfig","runTypegenGenerate","IGNORED_PATTERNS","createTypegenRunner","onGenerate","state","isGenerating","pendingGeneration","runGeneration","runTypegenWatcher","options","config","workDir","path","schema","stats","failedCount","startTime","Date","now","successfulDurations","duration","push","debouncedGenerate","paths","Array","isArray","absoluteQueryPatterns","map","pattern","absoluteSchemaPath","watchTargets","watcher","watch","cwd","ignored","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","err","message","getStats","averageGenerationDuration","generationFailedCount","generationSuccessfulCount","length","watcherDuration","stop","close"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,KAAK,QAAO,eAAc;AACzC,SAAQC,UAAU,EAAEC,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AO,CAACb,QAAQA,OAAO;QAACA;KAAK;IACjD,MAAMc,wBAAwBH,MAAMI,GAAG,CAAC,CAACC,UACvCnC,WAAWmC,WAAWA,UAAUlC,KAAKiB,SAASiB;IAEhD,MAAMC,qBAAqBpC,WAAWoB,UAAUA,SAASnB,KAAKiB,SAASE;IACvE,MAAMiB,eAAe;WAAIJ;QAAuBG;KAAmB;IAEnE,6BAA6B;IAC7BP;IAEA,iBAAiB;IACjB,MAAMS,UAAUnC,SAASoC,KAAK,CAACF,cAAc;QAC3CG,KAAKtB;QACLuB,SAASjC;QACTkC,eAAe;IACjB;IAEAJ,QAAQK,EAAE,CAAC,OAAO,CAACC,OAAeC;QAChC,MAAMC,YAAY,IAAItB,OAAOuB,kBAAkB;QAC/C,MAAMC,eAAehD,WAAW6C,YAAY3C,SAASgB,SAAS2B,YAAYA;QAC1E/C,MAAM,CAAC,CAAC,EAAEgD,UAAU,EAAE,EAAEF,MAAM,EAAE,EAAEI,cAAc;QAChDnB;IACF;IAEAS,QAAQK,EAAE,CAAC,SAAS,CAACM;QACnBlD,MAAM,CAAC,eAAe,EAAEkD,IAAIC,OAAO,EAAE;IACvC;IAEA,OAAO;QACLC,UAAU,IAAO,CAAA;gBACfC,2BAA2B/C,KAAKgB,MAAMK,mBAAmB,KAAK;gBAC9D2B,uBAAuBhC,MAAMC,WAAW;gBACxCgC,2BAA2BjC,MAAMK,mBAAmB,CAAC6B,MAAM;gBAC3DC,iBAAiBhC,KAAKC,GAAG,KAAKJ,MAAME,SAAS;YAC/C,CAAA;QACAkC,MAAM;YACJ,MAAMnB,QAAQoB,KAAK;QACrB;QACApB;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\nimport {telemetry} from '../utils/telemetryLogger.js'\n\n/**\n * Data passed to the typegen worker thread.\n * @internal\n */\nexport interface TypegenGenerateTypesWorkerData {\n /** Path to the schema JSON file */\n schemaPath: string\n /** Glob pattern(s) for finding query files */\n searchPath: string | string[]\n /** Working directory (project root) */\n workDir: string\n\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n}\n\n/**\n * Worker channel definition for typegen worker communication.\n * Extends the base TypegenWorkerChannel with additional events for progress tracking.\n * @internal\n */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n\n/**\n * Options for running a single typegen generation.\n * This is the programmatic API for one-off generation without file watching.\n */\nexport interface RunTypegenOptions {\n /**
|
|
1
|
+
{"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\nimport {telemetry} from '../utils/telemetryLogger.js'\n\n/**\n * Data passed to the typegen worker thread.\n * @internal\n */\nexport interface TypegenGenerateTypesWorkerData {\n /** Path to the schema JSON file */\n schemaPath: string\n /** Glob pattern(s) for finding query files */\n searchPath: string | string[]\n /** Working directory (project root) */\n workDir: string\n\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n}\n\n/**\n * Worker channel definition for typegen worker communication.\n * Extends the base TypegenWorkerChannel with additional events for progress tracking.\n * @internal\n */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n\n/**\n * Options for running a single typegen generation.\n * This is the programmatic API for one-off generation without file watching.\n */\nexport interface RunTypegenOptions {\n /** Working directory (usually project root) */\n workDir: string\n\n /** Typegen configuration */\n config?: Partial<TypeGenConfig>\n\n /** Optional spinner instance for progress display */\n spin?: ReturnType<typeof spinner>\n\n /** Optional telemetry instance for tracking usage */\n telemetry?: typeof telemetry\n}\n\n/**\n * Result from a single generation run.\n * @internal\n */\nexport interface GenerationResult {\n code: string\n duration: number\n emptyUnionTypeNodesGenerated: number\n filesWithErrors: number\n outputSize: number\n queriesCount: number\n queryFilesCount: number\n schemaTypesCount: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n}\n"],"names":[],"mappings":"AAsDA;;;CAGC,GACD,WAYC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -417,10 +417,10 @@ export declare function runTypegenGenerate(options: RunTypegenOptions): Promise<
|
|
|
417
417
|
* This is the programmatic API for one-off generation without file watching.
|
|
418
418
|
*/
|
|
419
419
|
export declare interface RunTypegenOptions {
|
|
420
|
-
/** Typegen configuration */
|
|
421
|
-
config: TypeGenConfig;
|
|
422
420
|
/** Working directory (usually project root) */
|
|
423
421
|
workDir: string;
|
|
422
|
+
/** Typegen configuration */
|
|
423
|
+
config?: Partial<TypeGenConfig>;
|
|
424
424
|
/** Optional spinner instance for progress display */
|
|
425
425
|
spin?: ReturnType<typeof spinner>;
|
|
426
426
|
/** Optional telemetry instance for tracking usage */
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function prepareConfig(config) {
|
|
2
|
+
return {
|
|
3
|
+
formatGeneratedCode: config?.formatGeneratedCode ?? false,
|
|
4
|
+
generates: config?.generates ?? 'sanity.types.ts',
|
|
5
|
+
overloadClientMethods: config?.overloadClientMethods ?? false,
|
|
6
|
+
path: config?.path ?? './src/**/*.{ts,tsx,js,jsx}',
|
|
7
|
+
schema: config?.schema ?? 'schema.json'
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/config.ts"],"sourcesContent":["import {TypeGenConfig} from '../readConfig.js'\n\nexport function prepareConfig(config?: Partial<TypeGenConfig>): TypeGenConfig {\n return {\n formatGeneratedCode: config?.formatGeneratedCode ?? false,\n generates: config?.generates ?? 'sanity.types.ts',\n overloadClientMethods: config?.overloadClientMethods ?? false,\n path: config?.path ?? './src/**/*.{ts,tsx,js,jsx}',\n schema: config?.schema ?? 'schema.json',\n }\n}\n"],"names":["prepareConfig","config","formatGeneratedCode","generates","overloadClientMethods","path","schema"],"mappings":"AAEA,OAAO,SAASA,cAAcC,MAA+B;IAC3D,OAAO;QACLC,qBAAqBD,QAAQC,uBAAuB;QACpDC,WAAWF,QAAQE,aAAa;QAChCC,uBAAuBH,QAAQG,yBAAyB;QACxDC,MAAMJ,QAAQI,QAAQ;QACtBC,QAAQL,QAAQK,UAAU;IAC5B;AACF"}
|
package/oclif.manifest.json
CHANGED