@sanity/codegen 3.93.1-next.8.cf0bf8550a → 3.94.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,79 +0,0 @@
1
- import fs from 'node:fs/promises'
2
-
3
- import {type TransformOptions} from '@babel/core'
4
- import createDebug from 'debug'
5
- import glob from 'globby'
6
-
7
- import {getBabelConfig} from '../getBabelConfig'
8
- import {type NamedQueryResult} from './expressionResolvers'
9
- import {findQueriesInSource} from './findQueriesInSource'
10
- import {getResolver} from './moduleResolver'
11
-
12
- const debug = createDebug('sanity:codegen:findQueries:debug')
13
-
14
- type ResultQueries = {
15
- type: 'queries'
16
- filename: string
17
- queries: NamedQueryResult[]
18
- }
19
- type ResultError = {
20
- type: 'error'
21
- error: Error
22
- filename: string
23
- }
24
-
25
- /**
26
- * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.
27
- * @param path - The path or array of paths to search for queries
28
- * @param babelOptions - The babel configuration to use when parsing the source
29
- * @param resolver - A resolver function to use when resolving module imports
30
- * @returns An async generator that yields the results of the search
31
- * @beta
32
- * @internal
33
- */
34
- export async function* findQueriesInPath({
35
- path,
36
- babelOptions = getBabelConfig(),
37
- resolver = getResolver(),
38
- }: {
39
- path: string | string[]
40
- babelOptions?: TransformOptions
41
- resolver?: NodeJS.RequireResolve
42
- }): AsyncGenerator<ResultQueries | ResultError> {
43
- const queryNames = new Set()
44
- // Holds all query names found in the source files
45
- debug(`Globing ${path}`)
46
-
47
- const files = glob
48
- .sync(path, {
49
- absolute: false,
50
- ignore: ['**/node_modules/**'], // we never want to look in node_modules
51
- onlyFiles: true,
52
- })
53
- .sort()
54
-
55
- for (const filename of files) {
56
- if (typeof filename !== 'string') {
57
- continue
58
- }
59
-
60
- debug(`Found file "${filename}"`)
61
- try {
62
- const source = await fs.readFile(filename, 'utf8')
63
- const queries = findQueriesInSource(source, filename, babelOptions, resolver)
64
- // Check and error on duplicate query names, because we can't generate types with the same name.
65
- for (const query of queries) {
66
- if (queryNames.has(query.name)) {
67
- throw new Error(
68
- `Duplicate query name found: "${query.name}". Query names must be unique across all files.`,
69
- )
70
- }
71
- queryNames.add(query.name)
72
- }
73
- yield {type: 'queries', filename, queries}
74
- } catch (error) {
75
- debug(`Error in file "${filename}"`, error)
76
- yield {type: 'error', error, filename}
77
- }
78
- }
79
- }
@@ -1,232 +0,0 @@
1
- import {createRequire} from 'node:module'
2
-
3
- import {type NodePath, type TransformOptions, traverse} from '@babel/core'
4
- import {type Scope} from '@babel/traverse'
5
- import * as babelTypes from '@babel/types'
6
-
7
- import {getBabelConfig} from '../getBabelConfig'
8
- import {type NamedQueryResult, resolveExpression} from './expressionResolvers'
9
- import {parseSourceFile} from './parseSource'
10
-
11
- const require = createRequire(__filename)
12
-
13
- const groqTagName = 'groq'
14
- const defineQueryFunctionName = 'defineQuery'
15
- const groqModuleName = 'groq'
16
- const nextSanityModuleName = 'next-sanity'
17
-
18
- const ignoreValue = '@sanity-typegen-ignore'
19
-
20
- /**
21
- * findQueriesInSource takes a source string and returns all GROQ queries in it.
22
- * @param source - The source code to search for queries
23
- * @param filename - The filename of the source code
24
- * @param babelConfig - The babel configuration to use when parsing the source
25
- * @param resolver - A resolver function to use when resolving module imports
26
- * @returns
27
- * @beta
28
- * @internal
29
- */
30
- export function findQueriesInSource(
31
- source: string,
32
- filename: string,
33
- babelConfig: TransformOptions = getBabelConfig(),
34
- resolver: NodeJS.RequireResolve = require.resolve,
35
- ): NamedQueryResult[] {
36
- const queries: NamedQueryResult[] = []
37
- const file = parseSourceFile(source, filename, babelConfig)
38
-
39
- traverse(file, {
40
- // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
41
- // The variable name is used as the name of the query result type
42
- VariableDeclarator(path) {
43
- const {node, scope} = path
44
-
45
- const init = node.init
46
-
47
- // Look for tagged template expressions that are called with the `groq` tag
48
- const isGroqTemplateTag =
49
- babelTypes.isTaggedTemplateExpression(init) &&
50
- babelTypes.isIdentifier(init.tag) &&
51
- init.tag.name === groqTagName
52
-
53
- // Look for strings wrapped in a defineQuery function call
54
- const isDefineQueryCall =
55
- babelTypes.isCallExpression(init) &&
56
- (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||
57
- isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee))
58
-
59
- if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {
60
- // If we find a comment leading the decleration which macthes with ignoreValue we don't add
61
- // the query
62
- if (declarationLeadingCommentContains(path, ignoreValue)) {
63
- return
64
- }
65
-
66
- const queryName = `${node.id.name}`
67
- const queryResult = resolveExpression({
68
- node: init,
69
- file,
70
- scope,
71
- babelConfig,
72
- filename,
73
- resolver,
74
- })
75
-
76
- const location = node.loc
77
- ? {
78
- start: {
79
- ...node.loc?.start,
80
- },
81
- end: {
82
- ...node.loc?.end,
83
- },
84
- }
85
- : {}
86
-
87
- queries.push({name: queryName, result: queryResult, location})
88
- }
89
- },
90
- })
91
-
92
- return queries
93
- }
94
-
95
- function declarationLeadingCommentContains(path: NodePath, comment: string): boolean {
96
- /*
97
- * We have to consider these cases:
98
- *
99
- * // @sanity-typegen-ignore
100
- * const query = groq`...`
101
- *
102
- * // AST
103
- * VariableDeclaration {
104
- * declarations: [
105
- * VariableDeclarator: {init: tag: {name: "groq"}}
106
- * ],
107
- * leadingComments: ...
108
- * }
109
- *
110
- * // @sanity-typegen-ignore
111
- * const query1 = groq`...`, query2 = groq`...`
112
- *
113
- * // AST
114
- * VariableDeclaration {
115
- * declarations: [
116
- * VariableDeclarator: {init: tag: {name: "groq"}}
117
- * VariableDeclarator: {init: tag: {name: "groq"}}
118
- * ],
119
- * leadingComments: ...
120
- * }
121
- *
122
- * // @sanity-typegen-ignore
123
- * export const query = groq`...`
124
- *
125
- * // AST
126
- * ExportNamedDeclaration {
127
- * declaration: VariableDeclaration {
128
- * declarations: [
129
- * VariableDeclarator: {init: tag: {name: "groq"}}
130
- * VariableDeclarator: {init: tag: {name: "groq"}}
131
- * ],
132
- * },
133
- * leadingComments: ...
134
- * }
135
- *
136
- * In the case where multiple variables are under the same VariableDeclaration the leadingComments
137
- * will still be on the VariableDeclaration
138
- *
139
- * In the case where the variable is exported, the leadingComments are on the
140
- * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property
141
- */
142
-
143
- const variableDeclaration = path.find((node) => node.isVariableDeclaration())
144
- if (!variableDeclaration) return false
145
-
146
- if (
147
- variableDeclaration.node.leadingComments?.find(
148
- (commentItem) => commentItem.value.trim() === comment,
149
- )
150
- ) {
151
- return true
152
- }
153
-
154
- // If the declaration is exported, the comment lies on the parent of the export declaration
155
- if (
156
- variableDeclaration.parent.leadingComments?.find(
157
- (commentItem) => commentItem.value.trim() === comment,
158
- )
159
- ) {
160
- return true
161
- }
162
-
163
- return false
164
- }
165
-
166
- function isImportFrom(
167
- moduleName: string,
168
- importName: string,
169
- scope: Scope,
170
- node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,
171
- ) {
172
- if (babelTypes.isIdentifier(node)) {
173
- const binding = scope.getBinding(node.name)
174
- if (!binding) {
175
- return false
176
- }
177
-
178
- const {path} = binding
179
-
180
- // import { foo } from 'groq'
181
- if (babelTypes.isImportSpecifier(path.node)) {
182
- return (
183
- path.node.importKind === 'value' &&
184
- path.parentPath &&
185
- babelTypes.isImportDeclaration(path.parentPath.node) &&
186
- path.parentPath.node.source.value === moduleName &&
187
- babelTypes.isIdentifier(path.node.imported) &&
188
- path.node.imported.name === importName
189
- )
190
- }
191
-
192
- // const { defineQuery } = require('groq')
193
- if (babelTypes.isVariableDeclarator(path.node)) {
194
- const {init} = path.node
195
- return (
196
- babelTypes.isCallExpression(init) &&
197
- babelTypes.isIdentifier(init.callee) &&
198
- init.callee.name === 'require' &&
199
- babelTypes.isStringLiteral(init.arguments[0]) &&
200
- init.arguments[0].value === moduleName
201
- )
202
- }
203
- }
204
-
205
- // import * as foo from 'groq'
206
- // foo.defineQuery(...)
207
- if (babelTypes.isMemberExpression(node)) {
208
- const {object, property} = node
209
-
210
- if (!babelTypes.isIdentifier(object)) {
211
- return false
212
- }
213
-
214
- const binding = scope.getBinding(object.name)
215
- if (!binding) {
216
- return false
217
- }
218
- const {path} = binding
219
-
220
- return (
221
- babelTypes.isIdentifier(object) &&
222
- babelTypes.isIdentifier(property) &&
223
- property.name === importName &&
224
- babelTypes.isImportNamespaceSpecifier(path.node) &&
225
- path.parentPath &&
226
- babelTypes.isImportDeclaration(path.parentPath.node) &&
227
- path.parentPath.node.source.value === moduleName
228
- )
229
- }
230
-
231
- return false
232
- }
@@ -1,41 +0,0 @@
1
- import createDebug from 'debug'
2
- import {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'
3
-
4
- const debug = createDebug('sanity:codegen:moduleResolver')
5
-
6
- /**
7
- * This is a custom implementation of require.resolve that takes into account the paths
8
- * configuration in tsconfig.json. This is necessary if we want to resolve paths that are
9
- * custom defined in the tsconfig.json file.
10
- * Resolving here is best effort and might not work in all cases.
11
- * @beta
12
- */
13
- export function getResolver(cwd?: string): NodeJS.RequireResolve {
14
- const tsConfig = loadTSConfig(cwd)
15
-
16
- if (tsConfig.resultType === 'failed') {
17
- debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)
18
- return require.resolve
19
- }
20
-
21
- const matchPath = createMatchPath(
22
- tsConfig.absoluteBaseUrl,
23
- tsConfig.paths,
24
- tsConfig.mainFields,
25
- tsConfig.addMatchAll,
26
- )
27
-
28
- const resolve = function (request: string, options?: {paths?: string[]}): string {
29
- const found = matchPath(request)
30
- if (found !== undefined) {
31
- return require.resolve(found, options)
32
- }
33
- return require.resolve(request, options)
34
- }
35
-
36
- // wrap the resolve.path function to make it available.
37
- resolve.paths = (request: string): string[] | null => {
38
- return require.resolve.paths(request)
39
- }
40
- return resolve
41
- }
@@ -1,41 +0,0 @@
1
- import {parse, type TransformOptions} from '@babel/core'
2
- import type * as babelTypes from '@babel/types'
3
-
4
- // helper function to parse a source file
5
- export function parseSourceFile(
6
- _source: string,
7
- _filename: string,
8
- babelOptions: TransformOptions,
9
- ): babelTypes.File {
10
- let source = _source
11
- let filename = _filename
12
- if (filename.endsWith('.astro')) {
13
- // append .ts to the filename so babel will parse it as typescript
14
- filename += '.ts'
15
- source = parseAstro(source)
16
- }
17
- const result = parse(source, {
18
- ...babelOptions,
19
- filename,
20
- })
21
-
22
- if (!result) {
23
- throw new Error(`Failed to parse ${filename}`)
24
- }
25
-
26
- return result
27
- }
28
-
29
- function parseAstro(source: string): string {
30
- // find all code fences, the js code is between --- and ---
31
- const codeFences = source.match(/---\n([\s\S]*?)\n---/g)
32
- if (!codeFences) {
33
- return ''
34
- }
35
-
36
- return codeFences
37
- .map((codeFence) => {
38
- return codeFence.split('\n').slice(1, -1).join('\n')
39
- })
40
- .join('\n')
41
- }
@@ -1,16 +0,0 @@
1
- import {type TransformOptions} from '@babel/core'
2
- import register from '@babel/register'
3
-
4
- import {getBabelConfig} from '../getBabelConfig'
5
-
6
- /**
7
- * Register Babel with the given options
8
- *
9
- * @param babelOptions - The options to use when registering Babel
10
- * @beta
11
- */
12
- export function registerBabel(babelOptions?: TransformOptions): void {
13
- const options = babelOptions || getBabelConfig()
14
-
15
- register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})
16
- }