@sanity/codegen 5.7.0-next.8 → 5.7.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.
Files changed (59) hide show
  1. package/bin/run.js +31 -0
  2. package/dist/_exports/index.js +11 -0
  3. package/dist/_exports/index.js.map +1 -0
  4. package/dist/actions/generatedFileWarning.js +15 -0
  5. package/dist/actions/generatedFileWarning.js.map +1 -0
  6. package/dist/actions/typegenGenerate.worker.js +54 -0
  7. package/dist/actions/typegenGenerate.worker.js.map +1 -0
  8. package/dist/actions/types.js +3 -0
  9. package/dist/actions/types.js.map +1 -0
  10. package/dist/casing.js +27 -0
  11. package/dist/casing.js.map +1 -0
  12. package/dist/commands/typegen/generate.js +237 -0
  13. package/dist/commands/typegen/generate.js.map +1 -0
  14. package/dist/getBabelConfig.js +37 -0
  15. package/dist/getBabelConfig.js.map +1 -0
  16. package/dist/index.d.ts +459 -0
  17. package/dist/readConfig.js +38 -0
  18. package/dist/readConfig.js.map +1 -0
  19. package/dist/readSchema.js +14 -0
  20. package/dist/readSchema.js.map +1 -0
  21. package/dist/safeParseQuery.js +37 -0
  22. package/dist/safeParseQuery.js.map +1 -0
  23. package/dist/typeUtils.js +37 -0
  24. package/dist/typeUtils.js.map +1 -0
  25. package/dist/typescript/constants.js +12 -0
  26. package/dist/typescript/constants.js.map +1 -0
  27. package/dist/typescript/expressionResolvers.js +356 -0
  28. package/dist/typescript/expressionResolvers.js.map +1 -0
  29. package/dist/typescript/findQueriesInPath.js +69 -0
  30. package/dist/typescript/findQueriesInPath.js.map +1 -0
  31. package/dist/typescript/findQueriesInSource.js +175 -0
  32. package/dist/typescript/findQueriesInSource.js.map +1 -0
  33. package/dist/typescript/helpers.js +86 -0
  34. package/dist/typescript/helpers.js.map +1 -0
  35. package/dist/typescript/moduleResolver.js +33 -0
  36. package/dist/typescript/moduleResolver.js.map +1 -0
  37. package/dist/typescript/parseSource.js +75 -0
  38. package/dist/typescript/parseSource.js.map +1 -0
  39. package/dist/typescript/registerBabel.js +23 -0
  40. package/dist/typescript/registerBabel.js.map +1 -0
  41. package/dist/typescript/schemaTypeGenerator.js +323 -0
  42. package/dist/typescript/schemaTypeGenerator.js.map +1 -0
  43. package/dist/typescript/typeGenerator.js +240 -0
  44. package/dist/typescript/typeGenerator.js.map +1 -0
  45. package/dist/typescript/types.js +31 -0
  46. package/dist/typescript/types.js.map +1 -0
  47. package/dist/utils/count.js +6 -0
  48. package/dist/utils/count.js.map +1 -0
  49. package/dist/utils/formatPath.js +8 -0
  50. package/dist/utils/formatPath.js.map +1 -0
  51. package/dist/utils/getMessage.js +3 -0
  52. package/dist/utils/getMessage.js.map +1 -0
  53. package/dist/utils/percent.js +8 -0
  54. package/dist/utils/percent.js.map +1 -0
  55. package/oclif.manifest.json +39 -0
  56. package/package.json +49 -23
  57. package/lib/index.d.ts +0 -433
  58. package/lib/index.js +0 -1011
  59. package/lib/index.js.map +0 -1
@@ -0,0 +1,459 @@
1
+ import { ExprNode } from 'groq-js';
2
+ import { SchemaType } from 'groq-js';
3
+ import * as t from '@babel/types';
4
+ import { TransformOptions } from '@babel/core';
5
+ import { WorkerChannel } from '@sanity/worker-channels';
6
+ import { WorkerChannelReporter } from '@sanity/worker-channels';
7
+ import * as z from 'zod';
8
+
9
+ /**
10
+ * @deprecated use TypeGenConfig
11
+ */
12
+ export declare type CodegenConfig = TypeGenConfig;
13
+
14
+ /**
15
+ * @internal
16
+ */
17
+ export declare const configDefinition: z.ZodObject<{
18
+ formatGeneratedCode: z.ZodDefault<z.ZodBoolean>;
19
+ generates: z.ZodDefault<z.ZodString>;
20
+ overloadClientMethods: z.ZodDefault<z.ZodBoolean>;
21
+ path: z.ZodDefault<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
22
+ schema: z.ZodDefault<z.ZodString>;
23
+ }, "strip", z.ZodTypeAny, {
24
+ formatGeneratedCode: boolean;
25
+ generates: string;
26
+ overloadClientMethods: boolean;
27
+ path: string | string[];
28
+ schema: string;
29
+ }, {
30
+ formatGeneratedCode?: boolean | undefined;
31
+ generates?: string | undefined;
32
+ overloadClientMethods?: boolean | undefined;
33
+ path?: string | string[] | undefined;
34
+ schema?: string | undefined;
35
+ }>;
36
+
37
+ /**
38
+ * A module containing queries that have been evaluated.
39
+ * @public
40
+ */
41
+ export declare interface EvaluatedModule {
42
+ errors: (QueryEvaluationError | QueryExtractionError)[];
43
+ filename: string;
44
+ queries: EvaluatedQuery[];
45
+ }
46
+
47
+ /**
48
+ * An `ExtractedQuery` that has been evaluated against a schema, yielding a TypeScript type.
49
+ * @public
50
+ */
51
+ export declare interface EvaluatedQuery extends ExtractedQuery {
52
+ ast: t.ExportNamedDeclaration;
53
+ code: string;
54
+ id: t.Identifier;
55
+ stats: TypeEvaluationStats;
56
+ tsType: t.TSType;
57
+ }
58
+
59
+ /**
60
+ * A module (file) containing extracted GROQ queries.
61
+ * @public
62
+ */
63
+ export declare interface ExtractedModule {
64
+ errors: QueryExtractionError[];
65
+ filename: string;
66
+ queries: ExtractedQuery[];
67
+ }
68
+
69
+ /**
70
+ * A GROQ query extracted from a source file.
71
+ * @public
72
+ */
73
+ export declare interface ExtractedQuery {
74
+ filename: string;
75
+ query: string;
76
+ variable: QueryVariable;
77
+ }
78
+
79
+ /**
80
+ * Filter a union of object types by the _type property. This is handy when working with page builder
81
+ * setups where the returned type is an array containing multiple types.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ *
86
+ * export type Callout = {
87
+ * _type: 'callout'
88
+ * title?: string
89
+ * content?: string
90
+ * }
91
+ *
92
+ * export type Video = {
93
+ * _type: 'video'
94
+ * url?: string
95
+ * caption?: string
96
+ * }
97
+ * type FORM_QUERY_RESULT = {
98
+ * _id: string
99
+ * title?: string
100
+ * content?: Array<
101
+ * | ({ _key: string } & Callout)
102
+ * | ({ _key: string } & Video)
103
+ * >
104
+ * } | null
105
+ *
106
+ * // Get the type of the content with the Get helper
107
+ * type Content = Get<FORM_QUERY_RESULT, 'content', number>
108
+ *
109
+ * // Get the type for a callout module from the page builder type
110
+ * type CalloutModule = FilterByType<Content, 'callout'>
111
+ * // → { _key: string } & Callout
112
+ * ```
113
+ */
114
+ export declare type FilterByType<U extends {
115
+ _type: string;
116
+ }, T extends U['_type']> = Extract<U, {
117
+ _type: T;
118
+ }>;
119
+
120
+ /**
121
+ * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.
122
+ * @param path - The path or array of paths to search for queries
123
+ * @param babelOptions - The babel configuration to use when parsing the source
124
+ * @param resolver - A resolver function to use when resolving module imports
125
+ * @returns An async generator that yields the results of the search
126
+ * @beta
127
+ * @internal
128
+ */
129
+ export declare function findQueriesInPath({ babelOptions, path, resolver, }: FindQueriesInPathOptions): {
130
+ files: string[];
131
+ queries: AsyncIterable<ExtractedModule>;
132
+ };
133
+
134
+ declare interface FindQueriesInPathOptions {
135
+ path: string | string[];
136
+ babelOptions?: TransformOptions;
137
+ resolver?: NodeJS.RequireResolve;
138
+ }
139
+
140
+ /**
141
+ * findQueriesInSource takes a source string and returns all GROQ queries in it.
142
+ * @param source - The source code to search for queries
143
+ * @param filename - The filename of the source code
144
+ * @param babelConfig - The babel configuration to use when parsing the source
145
+ * @param resolver - A resolver function to use when resolving module imports
146
+ * @returns
147
+ * @beta
148
+ * @internal
149
+ */
150
+ export declare function findQueriesInSource(source: string, filename: string, babelConfig?: TransformOptions, resolver?: NodeJS.RequireResolve): ExtractedModule;
151
+
152
+ export declare interface GenerateTypesOptions {
153
+ schema: SchemaType;
154
+ overloadClientMethods?: boolean;
155
+ queries?: AsyncIterable<ExtractedModule>;
156
+ reporter?: WorkerChannelReporter<TypegenWorkerChannel>;
157
+ root?: string;
158
+ schemaPath?: string;
159
+ }
160
+
161
+ /**
162
+ * Get a deeply nested property type from a complex type structure. Safely navigates
163
+ * through nullable types (`T | null | undefined`) at each level, preserving the
164
+ * nullability of the final accessed property.
165
+ *
166
+ * Supports up to 20 levels of nesting.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * type POST_QUERY_RESULT = {
171
+ * _id: string
172
+ * author: {
173
+ * profile: {
174
+ * name: string;
175
+ * } | null;
176
+ * } | null;
177
+ * links: Array<{
178
+ * _key: string
179
+ * type: 'link'
180
+ * label: string
181
+ * url: string
182
+ * }> | null
183
+ * } | null
184
+ *
185
+ * // Basic property access:
186
+ * type Id = Get<POST_QUERY_RESULT, '_id'>;
187
+ * // → string
188
+ *
189
+ * // Nested property access:
190
+ * type Profile = Get<POST_QUERY_RESULT, 'author', 'profile';
191
+ * // → { name: string } | null
192
+ *
193
+ * // Array element access using `number`:
194
+ * type Link = Get<POST_QUERY_RESULT, 'links', number, 'label'>;
195
+ * // → string
196
+ * ```
197
+ */
198
+ export declare type Get<T, K1 extends keyof NonNullish<T>, K2 extends keyof NavigatePath<T, [K1]> = never, K3 extends keyof NavigatePath<T, [K1, K2]> = never, K4 extends keyof NavigatePath<T, [K1, K2, K3]> = never, K5 extends keyof NavigatePath<T, [K1, K2, K3, K4]> = never, K6 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5]> = never, K7 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6]> = never, K8 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7]> = never, K9 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8]> = never, K10 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9]> = never, K11 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10]> = never, K12 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11]> = never, K13 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12]> = never, K14 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13]> = never, K15 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14]> = never, K16 extends keyof NavigatePath<T, [
199
+ K1,
200
+ K2,
201
+ K3,
202
+ K4,
203
+ K5,
204
+ K6,
205
+ K7,
206
+ K8,
207
+ K9,
208
+ K10,
209
+ K11,
210
+ K12,
211
+ K13,
212
+ K14,
213
+ K15
214
+ ]> = never, K17 extends keyof NavigatePath<T, [
215
+ K1,
216
+ K2,
217
+ K3,
218
+ K4,
219
+ K5,
220
+ K6,
221
+ K7,
222
+ K8,
223
+ K9,
224
+ K10,
225
+ K11,
226
+ K12,
227
+ K13,
228
+ K14,
229
+ K15,
230
+ K16
231
+ ]> = never, K18 extends keyof NavigatePath<T, [
232
+ K1,
233
+ K2,
234
+ K3,
235
+ K4,
236
+ K5,
237
+ K6,
238
+ K7,
239
+ K8,
240
+ K9,
241
+ K10,
242
+ K11,
243
+ K12,
244
+ K13,
245
+ K14,
246
+ K15,
247
+ K16,
248
+ K17
249
+ ]> = never, K19 extends keyof NavigatePath<T, [
250
+ K1,
251
+ K2,
252
+ K3,
253
+ K4,
254
+ K5,
255
+ K6,
256
+ K7,
257
+ K8,
258
+ K9,
259
+ K10,
260
+ K11,
261
+ K12,
262
+ K13,
263
+ K14,
264
+ K15,
265
+ K16,
266
+ K17,
267
+ K18
268
+ ]> = never, K20 extends keyof NavigatePath<T, [
269
+ K1,
270
+ K2,
271
+ K3,
272
+ K4,
273
+ K5,
274
+ K6,
275
+ K7,
276
+ K8,
277
+ K9,
278
+ K10,
279
+ K11,
280
+ K12,
281
+ K13,
282
+ K14,
283
+ K15,
284
+ K16,
285
+ K17,
286
+ K18,
287
+ K19
288
+ ]> = never> = GetAtPath<T, TakeUntilNever<[
289
+ K1,
290
+ K2,
291
+ K3,
292
+ K4,
293
+ K5,
294
+ K6,
295
+ K7,
296
+ K8,
297
+ K9,
298
+ K10,
299
+ K11,
300
+ K12,
301
+ K13,
302
+ K14,
303
+ K15,
304
+ K16,
305
+ K17,
306
+ K18,
307
+ K19,
308
+ K20
309
+ ]>>;
310
+
311
+ /** Recursively gets value at path, preserving nullability at final access. */
312
+ declare type GetAtPath<T, Path extends unknown[]> = Path extends [] ? T : Path extends [infer K] ? K extends keyof NonNullish<T> ? NonNullish<T>[K] : never : Path extends [infer K, ...infer Rest] ? K extends keyof NonNullish<T> ? GetAtPath<NonNullish<T>[K], Rest> : never : never;
313
+
314
+ /**
315
+ * This is a custom implementation of require.resolve that takes into account the paths
316
+ * configuration in tsconfig.json. This is necessary if we want to resolve paths that are
317
+ * custom defined in the tsconfig.json file.
318
+ * Resolving here is best effort and might not work in all cases.
319
+ * @beta
320
+ */
321
+ export declare function getResolver(cwd?: string): NodeJS.RequireResolve;
322
+
323
+ /** Recursively navigates through a path, stripping nullability for key lookup. */
324
+ declare type NavigatePath<T, Path extends unknown[]> = Path extends [] ? NonNullish<T> : Path extends [infer K, ...infer Rest] ? K extends keyof NonNullish<T> ? NavigatePath<NonNullish<T>[K], Rest> : never : never;
325
+
326
+ /** Excludes `null` and `undefined` from a type. */
327
+ declare type NonNullish<T> = T extends null | undefined ? never : T;
328
+
329
+ /**
330
+ * An error that occurred during query evaluation.
331
+ * @public
332
+ */
333
+ declare class QueryEvaluationError extends Error {
334
+ filename: string;
335
+ variable?: QueryVariable;
336
+ constructor({ cause, filename, variable }: QueryEvaluationErrorOptions);
337
+ }
338
+
339
+ declare interface QueryEvaluationErrorOptions {
340
+ cause: unknown;
341
+ filename: string;
342
+ variable?: QueryVariable;
343
+ }
344
+
345
+ /**
346
+ * An error that occurred during query extraction.
347
+ * @public
348
+ */
349
+ export declare class QueryExtractionError extends Error {
350
+ filename: string;
351
+ variable?: QueryVariable;
352
+ constructor({ cause, filename, variable }: QueryExtractionErrorOptions);
353
+ }
354
+
355
+ declare interface QueryExtractionErrorOptions {
356
+ cause: unknown;
357
+ filename: string;
358
+ variable?: QueryVariable;
359
+ }
360
+
361
+ declare interface QueryVariable {
362
+ id: t.Identifier;
363
+ end?: number;
364
+ start?: number;
365
+ }
366
+
367
+ /**
368
+ * Read, parse and process a config file
369
+ * @internal
370
+ */
371
+ export declare function readConfig(path: string): Promise<TypeGenConfig>;
372
+
373
+ /**
374
+ * Read a schema from a given path
375
+ * @param path - The path to the schema
376
+ * @returns The schema
377
+ * @internal
378
+ * @beta
379
+ **/
380
+ export declare function readSchema(path: string): Promise<SchemaType>;
381
+
382
+ /**
383
+ * Register Babel with the given options
384
+ *
385
+ * @param babelOptions - The options to use when registering Babel
386
+ * @beta
387
+ */
388
+ export declare function registerBabel(babelOptions?: TransformOptions): void;
389
+
390
+ /**
391
+ * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_
392
+ * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.
393
+ * @internal
394
+ */
395
+ export declare function safeParseQuery(query: string): ExprNode;
396
+
397
+ /** Builds a tuple from elements, stopping at the first `never`. */
398
+ declare type TakeUntilNever<T extends unknown[]> = T extends [infer H, ...infer Rest] ? [H] extends [never] ? [] : [H, ...TakeUntilNever<Rest>] : [];
399
+
400
+ /**
401
+ * Statistics from the query type evaluation process.
402
+ * @public
403
+ */
404
+ declare interface TypeEvaluationStats {
405
+ allTypes: number;
406
+ emptyUnions: number;
407
+ unknownTypes: number;
408
+ }
409
+
410
+ export declare type TypeGenConfig = z.infer<typeof configDefinition>;
411
+
412
+ /**
413
+ * A class used to generate TypeScript types from a given schema
414
+ * @beta
415
+ */
416
+ export declare class TypeGenerator {
417
+ private getSchemaTypeGenerator;
418
+ private getSchemaTypeDeclarations;
419
+ private getAllSanitySchemaTypesDeclaration;
420
+ private getArrayOfDeclaration;
421
+ private getInternalReferenceSymbolDeclaration;
422
+ private static getEvaluatedModules;
423
+ private static getQueryMapDeclaration;
424
+ generateTypes(options: GenerateTypesOptions): Promise<{
425
+ ast: t.Program;
426
+ code: string;
427
+ }>;
428
+ }
429
+
430
+ export declare type TypegenWorkerChannel = WorkerChannel.Definition<{
431
+ evaluatedModules: WorkerChannel.Stream<EvaluatedModule>;
432
+ generatedQueryTypes: WorkerChannel.Event<{
433
+ queryMapDeclaration: {
434
+ ast: t.Program;
435
+ code: string;
436
+ };
437
+ }>;
438
+ generatedSchemaTypes: WorkerChannel.Event<{
439
+ allSanitySchemaTypesDeclaration: {
440
+ ast: t.ExportNamedDeclaration;
441
+ code: string;
442
+ id: t.Identifier;
443
+ };
444
+ internalReferenceSymbol: {
445
+ ast: t.ExportNamedDeclaration;
446
+ code: string;
447
+ id: t.Identifier;
448
+ };
449
+ schemaTypeDeclarations: {
450
+ ast: t.ExportNamedDeclaration;
451
+ code: string;
452
+ id: t.Identifier;
453
+ name: string;
454
+ tsType: t.TSType;
455
+ }[];
456
+ }>;
457
+ }>;
458
+
459
+ export { }
@@ -0,0 +1,38 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import json5 from 'json5';
3
+ import * as z from 'zod';
4
+ /**
5
+ * @internal
6
+ */ export const configDefinition = z.object({
7
+ formatGeneratedCode: z.boolean().default(true),
8
+ generates: z.string().default('./sanity.types.ts'),
9
+ overloadClientMethods: z.boolean().default(true),
10
+ path: z.string().or(z.array(z.string())).default([
11
+ './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
12
+ './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
13
+ './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}'
14
+ ]),
15
+ schema: z.string().default('./schema.json')
16
+ });
17
+ /**
18
+ * Read, parse and process a config file
19
+ * @internal
20
+ */ export async function readConfig(path) {
21
+ try {
22
+ const content = await readFile(path, 'utf8');
23
+ const json = json5.parse(content);
24
+ return configDefinition.parseAsync(json);
25
+ } catch (error) {
26
+ if (error instanceof z.ZodError) {
27
+ throw new Error(`Error in config file\n ${error.errors.map((err)=>err.message).join('\n')}`, {
28
+ cause: error
29
+ });
30
+ }
31
+ if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
32
+ return configDefinition.parse({});
33
+ }
34
+ throw error;
35
+ }
36
+ }
37
+
38
+ //# sourceMappingURL=readConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as z from 'zod'\n\n/**\n * @internal\n */\nexport const configDefinition = z.object({\n formatGeneratedCode: z.boolean().default(true),\n generates: z.string().default('./sanity.types.ts'),\n overloadClientMethods: z.boolean().default(true),\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n})\n\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf8')\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefinition.parse({})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","z","configDefinition","object","formatGeneratedCode","boolean","default","generates","string","overloadClientMethods","path","or","array","schema","readConfig","content","json","parse","parseAsync","error","ZodError","Error","errors","map","err","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,MAAK;AAExB;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,OAAO,GAAGC,OAAO,CAAC;IACzCC,WAAWN,EAAEO,MAAM,GAAGF,OAAO,CAAC;IAC9BG,uBAAuBR,EAAEI,OAAO,GAAGC,OAAO,CAAC;IAC3CI,MAAMT,EACHO,MAAM,GACNG,EAAE,CAACV,EAAEW,KAAK,CAACX,EAAEO,MAAM,KACnBF,OAAO,CAAC;QACP;QACA;QACA;KACD;IACHO,QAAQZ,EAAEO,MAAM,GAAGF,OAAO,CAAC;AAC7B,GAAE;AASF;;;CAGC,GACD,OAAO,eAAeQ,WAAWJ,IAAY;IAC3C,IAAI;QACF,MAAMK,UAAU,MAAMhB,SAASW,MAAM;QACrC,MAAMM,OAAOhB,MAAMiB,KAAK,CAACF;QACzB,OAAOb,iBAAiBgB,UAAU,CAACF;IACrC,EAAE,OAAOG,OAAO;QACd,IAAIA,iBAAiBlB,EAAEmB,QAAQ,EAAE;YAC/B,MAAM,IAAIC,MACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,MAAQA,IAAIC,OAAO,EAAEC,IAAI,CAAC,OAAO,EAC7E;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO1B,iBAAiBe,KAAK,CAAC,CAAC;QACjC;QAEA,MAAME;IACR;AACF"}
@@ -0,0 +1,14 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ /**
3
+ * Read a schema from a given path
4
+ * @param path - The path to the schema
5
+ * @returns The schema
6
+ * @internal
7
+ * @beta
8
+ **/ export async function readSchema(path) {
9
+ const content = await readFile(path, 'utf8');
10
+ return JSON.parse(content) // todo: ZOD validation?
11
+ ;
12
+ }
13
+
14
+ //# sourceMappingURL=readSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/readSchema.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n"],"names":["readFile","readSchema","path","content","JSON","parse"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAIzC;;;;;;EAME,GACF,OAAO,eAAeC,WAAWC,IAAY;IAC3C,MAAMC,UAAU,MAAMH,SAASE,MAAM;IACrC,OAAOE,KAAKC,KAAK,CAACF,SAAS,wBAAwB;;AACrD"}
@@ -0,0 +1,37 @@
1
+ import { parse } from 'groq-js';
2
+ /**
3
+ * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_
4
+ * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.
5
+ * @internal
6
+ */ export function safeParseQuery(query) {
7
+ const params = {};
8
+ for (const param of extractSliceParams(query)){
9
+ params[param] = 0; // we don't care about the value, just the type
10
+ }
11
+ return parse(query, {
12
+ params
13
+ });
14
+ }
15
+ /**
16
+ * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return
17
+ * the names of the start and end variables.
18
+ * @internal
19
+ */ export function* extractSliceParams(query) {
20
+ const sliceRegex = /\[(\$(\w+)|\d)\.\.\.?(\$(\w+)|\d)\]/g;
21
+ const matches = query.matchAll(sliceRegex);
22
+ if (!matches) {
23
+ return;
24
+ }
25
+ for (const match of matches){
26
+ const start = match[1] === `$${match[2]}` ? match[2] : null;
27
+ if (start !== null) {
28
+ yield start;
29
+ }
30
+ const end = match[3] === `$${match[4]}` ? match[4] : null;
31
+ if (end !== null) {
32
+ yield end;
33
+ }
34
+ }
35
+ }
36
+
37
+ //# sourceMappingURL=safeParseQuery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/safeParseQuery.ts"],"sourcesContent":["import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start!\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end!\n }\n }\n}\n"],"names":["parse","safeParseQuery","query","params","param","extractSliceParams","sliceRegex","matches","matchAll","match","start","end"],"mappings":"AAAA,SAAQA,KAAK,QAAO,UAAS;AAE7B;;;;CAIC,GACD,OAAO,SAASC,eAAeC,KAAa;IAC1C,MAAMC,SAAkC,CAAC;IAEzC,KAAK,MAAMC,SAASC,mBAAmBH,OAAQ;QAC7CC,MAAM,CAACC,MAAM,GAAG,GAAE,+CAA+C;IACnE;IACA,OAAOJ,MAAME,OAAO;QAACC;IAAM;AAC7B;AAEA;;;;CAIC,GACD,OAAO,UAAUE,mBAAmBH,KAAa;IAC/C,MAAMI,aAAa;IACnB,MAAMC,UAAUL,MAAMM,QAAQ,CAACF;IAC/B,IAAI,CAACC,SAAS;QACZ;IACF;IACA,KAAK,MAAME,SAASF,QAAS;QAC3B,MAAMG,QAAQD,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACvD,IAAIC,UAAU,MAAM;YAClB,MAAMA;QACR;QACA,MAAMC,MAAMF,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACrD,IAAIE,QAAQ,MAAM;YAChB,MAAMA;QACR;IACF;AACF"}
@@ -0,0 +1,37 @@
1
+ /** Excludes `null` and `undefined` from a type. */ /**
2
+ * Filter a union of object types by the _type property. This is handy when working with page builder
3
+ * setups where the returned type is an array containing multiple types.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ *
8
+ * export type Callout = {
9
+ * _type: 'callout'
10
+ * title?: string
11
+ * content?: string
12
+ * }
13
+ *
14
+ * export type Video = {
15
+ * _type: 'video'
16
+ * url?: string
17
+ * caption?: string
18
+ * }
19
+ * type FORM_QUERY_RESULT = {
20
+ * _id: string
21
+ * title?: string
22
+ * content?: Array<
23
+ * | ({ _key: string } & Callout)
24
+ * | ({ _key: string } & Video)
25
+ * >
26
+ * } | null
27
+ *
28
+ * // Get the type of the content with the Get helper
29
+ * type Content = Get<FORM_QUERY_RESULT, 'content', number>
30
+ *
31
+ * // Get the type for a callout module from the page builder type
32
+ * type CalloutModule = FilterByType<Content, 'callout'>
33
+ * // → { _key: string } & Callout
34
+ * ```
35
+ */ export { };
36
+
37
+ //# sourceMappingURL=typeUtils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/typeUtils.ts"],"sourcesContent":["/** Excludes `null` and `undefined` from a type. */\ntype NonNullish<T> = T extends null | undefined ? never : T\n\n/** Builds a tuple from elements, stopping at the first `never`. */\ntype TakeUntilNever<T extends unknown[]> = T extends [infer H, ...infer Rest]\n ? [H] extends [never]\n ? []\n : [H, ...TakeUntilNever<Rest>]\n : []\n\n/** Recursively navigates through a path, stripping nullability for key lookup. */\ntype NavigatePath<T, Path extends unknown[]> = Path extends []\n ? NonNullish<T>\n : Path extends [infer K, ...infer Rest]\n ? K extends keyof NonNullish<T>\n ? NavigatePath<NonNullish<T>[K], Rest>\n : never\n : never\n\n/** Recursively gets value at path, preserving nullability at final access. */\ntype GetAtPath<T, Path extends unknown[]> = Path extends []\n ? T\n : Path extends [infer K]\n ? K extends keyof NonNullish<T>\n ? NonNullish<T>[K]\n : never\n : Path extends [infer K, ...infer Rest]\n ? K extends keyof NonNullish<T>\n ? GetAtPath<NonNullish<T>[K], Rest>\n : never\n : never\n\n/**\n * Get a deeply nested property type from a complex type structure. Safely navigates\n * through nullable types (`T | null | undefined`) at each level, preserving the\n * nullability of the final accessed property.\n *\n * Supports up to 20 levels of nesting.\n *\n * @example\n * ```ts\n * type POST_QUERY_RESULT = {\n * _id: string\n * author: {\n * profile: {\n * name: string;\n * } | null;\n * } | null;\n * links: Array<{\n * _key: string\n * type: 'link'\n * label: string\n * url: string\n * }> | null\n * } | null\n *\n * // Basic property access:\n * type Id = Get<POST_QUERY_RESULT, '_id'>;\n * // → string\n *\n * // Nested property access:\n * type Profile = Get<POST_QUERY_RESULT, 'author', 'profile';\n * // → { name: string } | null\n *\n * // Array element access using `number`:\n * type Link = Get<POST_QUERY_RESULT, 'links', number, 'label'>;\n * // → string\n * ```\n */\nexport type Get<\n T,\n K1 extends keyof NonNullish<T>,\n K2 extends keyof NavigatePath<T, [K1]> = never,\n K3 extends keyof NavigatePath<T, [K1, K2]> = never,\n K4 extends keyof NavigatePath<T, [K1, K2, K3]> = never,\n K5 extends keyof NavigatePath<T, [K1, K2, K3, K4]> = never,\n K6 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5]> = never,\n K7 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6]> = never,\n K8 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7]> = never,\n K9 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8]> = never,\n K10 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9]> = never,\n K11 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10]> = never,\n K12 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11]> = never,\n K13 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12]> = never,\n K14 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13]> =\n never,\n K15 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14]> =\n never,\n K16 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15]\n > = never,\n K17 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16]\n > = never,\n K18 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17]\n > = never,\n K19 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18]\n > = never,\n K20 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18, K19]\n > = never,\n> = GetAtPath<\n T,\n TakeUntilNever<\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18, K19, K20]\n >\n>\n\n/**\n * Filter a union of object types by the _type property. This is handy when working with page builder\n * setups where the returned type is an array containing multiple types.\n *\n * @example\n * ```ts\n *\n * export type Callout = {\n * _type: 'callout'\n * title?: string\n * content?: string\n * }\n *\n * export type Video = {\n * _type: 'video'\n * url?: string\n * caption?: string\n * }\n * type FORM_QUERY_RESULT = {\n * _id: string\n * title?: string\n * content?: Array<\n * | ({ _key: string } & Callout)\n * | ({ _key: string } & Video)\n * >\n * } | null\n *\n * // Get the type of the content with the Get helper\n * type Content = Get<FORM_QUERY_RESULT, 'content', number>\n *\n * // Get the type for a callout module from the page builder type\n * type CalloutModule = FilterByType<Content, 'callout'>\n * // → { _key: string } & Callout\n * ```\n */\nexport type FilterByType<U extends {_type: string}, T extends U['_type']> = Extract<U, {_type: T}>\n"],"names":[],"mappings":"AAAA,iDAAiD,GAmHjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GACD,WAAkG"}
@@ -0,0 +1,12 @@
1
+ import * as t from '@babel/types';
2
+ export const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo');
3
+ export const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes');
4
+ export const SANITY_QUERIES = t.identifier('SanityQueries');
5
+ export const ARRAY_OF = t.identifier('ArrayOf');
6
+ export const RESERVED_IDENTIFIERS = new Set();
7
+ RESERVED_IDENTIFIERS.add(SANITY_QUERIES.name);
8
+ RESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name);
9
+ RESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name);
10
+ RESERVED_IDENTIFIERS.add(ARRAY_OF.name);
11
+
12
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/typescript/constants.ts"],"sourcesContent":["import * as t from '@babel/types'\n\nexport const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo')\nexport const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes')\nexport const SANITY_QUERIES = t.identifier('SanityQueries')\nexport const ARRAY_OF = t.identifier('ArrayOf')\n\nexport const RESERVED_IDENTIFIERS = new Set<string>()\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name)\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name)\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name)\nRESERVED_IDENTIFIERS.add(ARRAY_OF.name)\n"],"names":["t","INTERNAL_REFERENCE_SYMBOL","identifier","ALL_SANITY_SCHEMA_TYPES","SANITY_QUERIES","ARRAY_OF","RESERVED_IDENTIFIERS","Set","add","name"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AAEjC,OAAO,MAAMC,4BAA4BD,EAAEE,UAAU,CAAC,+BAA8B;AACpF,OAAO,MAAMC,0BAA0BH,EAAEE,UAAU,CAAC,wBAAuB;AAC3E,OAAO,MAAME,iBAAiBJ,EAAEE,UAAU,CAAC,iBAAgB;AAC3D,OAAO,MAAMG,WAAWL,EAAEE,UAAU,CAAC,WAAU;AAE/C,OAAO,MAAMI,uBAAuB,IAAIC,MAAa;AACrDD,qBAAqBE,GAAG,CAACJ,eAAeK,IAAI;AAC5CH,qBAAqBE,GAAG,CAACL,wBAAwBM,IAAI;AACrDH,qBAAqBE,GAAG,CAACP,0BAA0BQ,IAAI;AACvDH,qBAAqBE,GAAG,CAACH,SAASI,IAAI"}