@sanity/codegen 8.0.0 → 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.
- package/README.md +26 -0
- package/dist/_exports/index.d.ts +23 -19
- package/dist/readConfig.js +15 -15
- package/dist/readConfig.js.map +1 -1
- package/dist/typescript/helpers.js +19 -0
- package/dist/typescript/helpers.js.map +1 -1
- package/dist/typescript/typeGenerator.js +28 -7
- package/dist/typescript/typeGenerator.js.map +1 -1
- package/package.json +10 -6
package/README.md
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
1
1
|
# @sanity/codegen
|
|
2
2
|
|
|
3
3
|
Codegen toolkit for Sanity.io, used to generate Typescript types for a Sanity Schema & GROQ queries.
|
|
4
|
+
|
|
5
|
+
## Typed `client.fetch` results
|
|
6
|
+
|
|
7
|
+
With `overloadClientMethods` enabled (the default), the generated file ends with a query type map that registers every query it found, so `client.fetch(query)` in `@sanity/client`, and `sanityFetch({query})` in `next-sanity`, return the generated result type without a generic:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// Query TypeMap
|
|
11
|
+
declare global {
|
|
12
|
+
interface SanityQueries {
|
|
13
|
+
'*[_type == "post"]': PostsQueryResult
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
// Lets @sanity/client releases that predate the global registry read it too
|
|
17
|
+
declare module '@sanity/client' {
|
|
18
|
+
interface SanityQueries extends globalThis.SanityQueries {}
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The two blocks serve different `@sanity/client` releases, and the same generated file works with all of them:
|
|
23
|
+
|
|
24
|
+
- The `declare global` block is the registry. `@sanity/client` releases that know about it read it directly, and because it is a global interface rather than a module augmentation, it does not depend on module resolution: it is seen whether or not `@sanity/client` is a direct dependency of the project that holds the generated file, however many copies of the client are installed (a copy nested inside `next-sanity` reads the same registry), and from every entry point, `@sanity/client/stega` included.
|
|
25
|
+
- The `declare module '@sanity/client'` block is a bridge for releases that only read the `SanityQueries` interface exported from `@sanity/client`, which is every release since 6.21.0. Interface merging unions the `extends` clauses of an interface's declarations, so the bridge makes that interface inherit the global registry. On releases that already inherit it, the bridge is a duplicate `extends` of the same type, which TypeScript accepts.
|
|
26
|
+
|
|
27
|
+
The bridge is the only line that resolves `@sanity/client`. When the client cannot be resolved from the generated file, TypeScript reports `TS2664: Invalid module name in augmentation` for it in a `.ts` file, while in a declaration file an augmentation whose module cannot be found is skipped silently. Pointing `generates` at a `.d.ts` path therefore keeps the file valid in such a layout, and the global registry still types the client that is installed.
|
|
28
|
+
|
|
29
|
+
The earlier output, a `declare module '@sanity/client'` block that carried the whole map, keeps working with every `@sanity/client` release that accepts the new one.
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -4,9 +4,9 @@ import {FSWatcher} from 'chokidar'
|
|
|
4
4
|
import {SchemaType} from 'groq-js'
|
|
5
5
|
import * as t from '@babel/types'
|
|
6
6
|
import {TransformOptions} from '@babel/core'
|
|
7
|
+
import * as v from 'valibot'
|
|
7
8
|
import {WorkerChannel} from '@sanity/worker-channels'
|
|
8
9
|
import {WorkerChannelReporter} from '@sanity/worker-channels'
|
|
9
|
-
import * as z from 'zod/mini'
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* @deprecated use TypeGenConfig
|
|
@@ -17,27 +17,31 @@ export declare type CodegenConfig = TypeGenConfig
|
|
|
17
17
|
/**
|
|
18
18
|
* @public
|
|
19
19
|
*/
|
|
20
|
-
export declare const configDefinition:
|
|
20
|
+
export declare const configDefinition: v.ObjectSchema<
|
|
21
21
|
{
|
|
22
|
-
formatGeneratedCode:
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
prettier: 'prettier'
|
|
29
|
-
}>,
|
|
30
|
-
]
|
|
31
|
-
>
|
|
22
|
+
readonly formatGeneratedCode: v.OptionalSchema<
|
|
23
|
+
v.UnionSchema<
|
|
24
|
+
[v.BooleanSchema<undefined>, v.PicklistSchema<['oxfmt', 'prettier'], undefined>],
|
|
25
|
+
undefined
|
|
26
|
+
>,
|
|
27
|
+
true
|
|
32
28
|
>
|
|
33
|
-
generates:
|
|
34
|
-
overloadClientMethods:
|
|
35
|
-
path:
|
|
36
|
-
|
|
29
|
+
readonly generates: v.OptionalSchema<v.StringSchema<undefined>, './sanity.types.ts'>
|
|
30
|
+
readonly overloadClientMethods: v.OptionalSchema<v.BooleanSchema<undefined>, true>
|
|
31
|
+
readonly path: v.OptionalSchema<
|
|
32
|
+
v.UnionSchema<
|
|
33
|
+
[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>],
|
|
34
|
+
undefined
|
|
35
|
+
>,
|
|
36
|
+
readonly [
|
|
37
|
+
'./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
38
|
+
'./app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
39
|
+
'./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',
|
|
40
|
+
]
|
|
37
41
|
>
|
|
38
|
-
schema:
|
|
42
|
+
readonly schema: v.OptionalSchema<v.StringSchema<undefined>, './schema.json'>
|
|
39
43
|
},
|
|
40
|
-
|
|
44
|
+
undefined
|
|
41
45
|
>
|
|
42
46
|
|
|
43
47
|
/**
|
|
@@ -440,7 +444,7 @@ declare interface TypeEvaluationStats {
|
|
|
440
444
|
}
|
|
441
445
|
|
|
442
446
|
/** @public */
|
|
443
|
-
export declare type TypeGenConfig =
|
|
447
|
+
export declare type TypeGenConfig = v.InferOutput<typeof configDefinition>
|
|
444
448
|
|
|
445
449
|
/**
|
|
446
450
|
* A class used to generate TypeScript types from a given schema
|
package/dist/readConfig.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import json5 from 'json5';
|
|
3
|
-
import * as
|
|
3
|
+
import * as v from 'valibot';
|
|
4
4
|
/**
|
|
5
5
|
* @public
|
|
6
|
-
*/ export const configDefinition =
|
|
7
|
-
formatGeneratedCode:
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
*/ export const configDefinition = v.object({
|
|
7
|
+
formatGeneratedCode: v.optional(v.union([
|
|
8
|
+
v.boolean(),
|
|
9
|
+
v.picklist([
|
|
10
10
|
'oxfmt',
|
|
11
11
|
'prettier'
|
|
12
12
|
])
|
|
13
13
|
]), true),
|
|
14
|
-
generates:
|
|
15
|
-
overloadClientMethods:
|
|
16
|
-
path:
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
generates: v.optional(v.string(), './sanity.types.ts'),
|
|
15
|
+
overloadClientMethods: v.optional(v.boolean(), true),
|
|
16
|
+
path: v.optional(v.union([
|
|
17
|
+
v.string(),
|
|
18
|
+
v.array(v.string())
|
|
19
19
|
]), [
|
|
20
20
|
'./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
21
21
|
'./app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
22
22
|
'./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}'
|
|
23
23
|
]),
|
|
24
|
-
schema:
|
|
24
|
+
schema: v.optional(v.string(), './schema.json')
|
|
25
25
|
});
|
|
26
26
|
/**
|
|
27
27
|
* Read, parse and process a config file
|
|
@@ -31,15 +31,15 @@ import * as z from 'zod/mini';
|
|
|
31
31
|
const content = await readFile(path, 'utf8');
|
|
32
32
|
// eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports
|
|
33
33
|
const json = json5.parse(content);
|
|
34
|
-
return
|
|
34
|
+
return v.parseAsync(configDefinition, json);
|
|
35
35
|
} catch (error) {
|
|
36
|
-
if (
|
|
37
|
-
throw new TypeError(`Error in config file\n ${error.issues.map((
|
|
36
|
+
if (v.isValiError(error)) {
|
|
37
|
+
throw new TypeError(`Error in config file\n ${error.issues.map((issue)=>issue.message).join('\n')}`, {
|
|
38
38
|
cause: error
|
|
39
39
|
});
|
|
40
40
|
}
|
|
41
41
|
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
|
|
42
|
-
return
|
|
42
|
+
return v.parse(configDefinition, {});
|
|
43
43
|
}
|
|
44
44
|
throw error;
|
|
45
45
|
}
|
package/dist/readConfig.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as
|
|
1
|
+
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as v from 'valibot'\n\n/**\n * The formatter to use for generated code.\n * - `false` - Do not format generated code.\n * - `true` | `'prettier'` - Format with prettier.\n * - `'oxfmt'` - Format with oxfmt. Throws if oxfmt is not installed.\n * @public\n */\nexport type FormatGeneratedCode = 'oxfmt' | 'prettier' | boolean\n\n/**\n * @public\n */\nexport const configDefinition = v.object({\n formatGeneratedCode: v.optional(v.union([v.boolean(), v.picklist(['oxfmt', 'prettier'])]), true),\n generates: v.optional(v.string(), './sanity.types.ts'),\n overloadClientMethods: v.optional(v.boolean(), true),\n path: v.optional(v.union([v.string(), v.array(v.string())]), [\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: v.optional(v.string(), './schema.json'),\n})\n\n/** @public */\nexport type TypeGenConfig = v.InferOutput<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n * @public\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 // eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports\n const json = json5.parse(content)\n return v.parseAsync(configDefinition, json)\n } catch (error) {\n if (v.isValiError(error)) {\n throw new TypeError(\n `Error in config file\\n ${error.issues.map((issue) => issue.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return v.parse(configDefinition, {})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","v","configDefinition","object","formatGeneratedCode","optional","union","boolean","picklist","generates","string","overloadClientMethods","path","array","schema","readConfig","content","json","parse","parseAsync","error","isValiError","TypeError","issues","map","issue","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,UAAS;AAW5B;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAEM,OAAO;QAAIN,EAAEO,QAAQ,CAAC;YAAC;YAAS;SAAW;KAAE,GAAG;IAC3FC,WAAWR,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;IAClCC,uBAAuBV,EAAEI,QAAQ,CAACJ,EAAEM,OAAO,IAAI;IAC/CK,MAAMX,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAES,MAAM;QAAIT,EAAEY,KAAK,CAACZ,EAAES,MAAM;KAAI,GAAG;QAC3D;QACA;QACA;KACD;IACDI,QAAQb,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;AACjC,GAAE;AAWF;;;CAGC,GACD,OAAO,eAAeK,WAAWH,IAAY;IAC3C,IAAI;QACF,MAAMI,UAAU,MAAMjB,SAASa,MAAM;QACrC,iHAAiH;QACjH,MAAMK,OAAOjB,MAAMkB,KAAK,CAACF;QACzB,OAAOf,EAAEkB,UAAU,CAACjB,kBAAkBe;IACxC,EAAE,OAAOG,OAAO;QACd,IAAInB,EAAEoB,WAAW,CAACD,QAAQ;YACxB,MAAM,IAAIE,UACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,QAAUA,MAAMC,OAAO,EAAEC,IAAI,CAAC,OAAO,EACjF;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO5B,EAAEiB,KAAK,CAAChB,kBAAkB,CAAC;QACpC;QAEA,MAAMkB;IACR;AACF"}
|
|
@@ -70,6 +70,25 @@ export function weakMapMemo(fn) {
|
|
|
70
70
|
export function generateCode(node) {
|
|
71
71
|
return `${new CodeGenerator(node).generate().code.trim()}\n\n`;
|
|
72
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Builds a `declare global { … }` block.
|
|
75
|
+
*/ export function tsDeclareGlobal(body) {
|
|
76
|
+
const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body));
|
|
77
|
+
declaration.declare = true;
|
|
78
|
+
// Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the
|
|
79
|
+
// output is `declare global {` on either.
|
|
80
|
+
declaration.global = true;
|
|
81
|
+
declaration.kind = 'global';
|
|
82
|
+
return declaration;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Builds a `declare module "<name>" { … }` block.
|
|
86
|
+
*/ export function tsDeclareModule(name, body) {
|
|
87
|
+
const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body));
|
|
88
|
+
declaration.declare = true;
|
|
89
|
+
declaration.kind = 'module';
|
|
90
|
+
return declaration;
|
|
91
|
+
}
|
|
73
92
|
export function getFilterArrayUnionType(typeNode, predicate) {
|
|
74
93
|
if (typeNode.of.type !== 'union') {
|
|
75
94
|
return typeNode;
|
|
@@ -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;AAEnD,OAAO,SAASC,uBAAuBC,IAAY,EAAEC,QAAgB;IACnE,MAAMC,WAAWR,KAAKS,OAAO,CAACH,MAAMC;IACpC,qEAAqE;IACrE,OAAOJ,WAAWH,KAAKU,QAAQ,CAACJ,MAAME;AACxC;AAEA;;;;;;;CAOC,GAC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AACD;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;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,qBAAqBC,OAA0B;IAC7D,IAAIC,MAAMC,OAAO,CAACF,UAAU;QAC1B,OAAOA,QAAQG,GAAG,CAAC,CAACC,IAAMb,WAAWa;IACvC;IACA,OAAOb,WAAWS;AACpB;AA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AcoD,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(
|
|
169
|
+
return t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type))))));
|
|
170
170
|
})));
|
|
171
|
-
|
|
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
|
-
|
|
182
|
-
|
|
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,O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F,EAAE8F,OAAO,CAAC,EAAE;QAC5B,IAAI7D,OAAO;QAEX6D,QAAQoB,IAAI,CAAC1B,IAAI,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,uBAAu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M,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACzF,KAAKkE;YAAS7D;QAAI;IAC5B;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/codegen",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.1.0",
|
|
4
4
|
"description": "Codegen toolkit for Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -56,12 +56,14 @@
|
|
|
56
56
|
"prettier": "^3.8.3",
|
|
57
57
|
"reselect": "^5.2.0",
|
|
58
58
|
"tsconfig-paths": "^4.2.0",
|
|
59
|
-
"
|
|
59
|
+
"valibot": "^1.4.2"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"@eslint/compat": "^2.1.0",
|
|
63
63
|
"@sanity/eslint-config-cli": "^1.1.2",
|
|
64
64
|
"@sanity/pkg-utils": "^10.5.5",
|
|
65
|
+
"@size-limit/esbuild": "^13.0.3",
|
|
66
|
+
"@size-limit/file": "^13.0.3",
|
|
65
67
|
"@swc/cli": "^0.8.1",
|
|
66
68
|
"@swc/core": "^1.15.40",
|
|
67
69
|
"@types/babel__core": "^7.20.5",
|
|
@@ -70,18 +72,19 @@
|
|
|
70
72
|
"@types/babel__traverse": "^7.28.0",
|
|
71
73
|
"@types/debug": "^4.1.13",
|
|
72
74
|
"@types/lodash-es": "^4.17.12",
|
|
73
|
-
"@types/node": "^24.13.
|
|
75
|
+
"@types/node": "^24.13.3",
|
|
74
76
|
"@vitest/coverage-istanbul": "^4.1.8",
|
|
75
77
|
"eslint": "^9.39.4",
|
|
76
78
|
"husky": "^9.1.7",
|
|
77
79
|
"lint-staged": "^16.4.0",
|
|
78
|
-
"oxfmt": "^0.
|
|
79
|
-
"pkg-pr-new": "^0.0.
|
|
80
|
+
"oxfmt": "^0.66.0",
|
|
81
|
+
"pkg-pr-new": "^0.0.88",
|
|
80
82
|
"prettier-plugin-packagejson": "^3.0.2",
|
|
81
83
|
"rimraf": "^5.0.10",
|
|
84
|
+
"size-limit": "^13.0.3",
|
|
82
85
|
"tinyglobby": "^0.2.17",
|
|
83
86
|
"typescript": "^5.9.3",
|
|
84
|
-
"vite": "^8.
|
|
87
|
+
"vite": "^8.2.2",
|
|
85
88
|
"vitest": "^4.1.8"
|
|
86
89
|
},
|
|
87
90
|
"peerDependencies": {
|
|
@@ -103,6 +106,7 @@
|
|
|
103
106
|
"build:types": "pkg-utils build --emitDeclarationOnly",
|
|
104
107
|
"clean": "rimraf dist coverage",
|
|
105
108
|
"lint": "eslint . --fix",
|
|
109
|
+
"size": "size-limit",
|
|
106
110
|
"pretest": "pnpm build",
|
|
107
111
|
"test": "vitest",
|
|
108
112
|
"watch": "swc src -d dist --strip-leading-paths --watch"
|