@nuasite/cms-core 0.56.4 → 0.58.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 (56) hide show
  1. package/dist/types/astro-source-analysis.d.ts +32 -0
  2. package/dist/types/astro-source-analysis.d.ts.map +1 -0
  3. package/dist/types/check-entries.d.ts +2 -0
  4. package/dist/types/check-entries.d.ts.map +1 -1
  5. package/dist/types/check.d.ts.map +1 -1
  6. package/dist/types/collection-scanner.d.ts +22 -2
  7. package/dist/types/collection-scanner.d.ts.map +1 -1
  8. package/dist/types/content-config-ast.d.ts +76 -2
  9. package/dist/types/content-config-ast.d.ts.map +1 -1
  10. package/dist/types/core.d.ts +19 -3
  11. package/dist/types/core.d.ts.map +1 -1
  12. package/dist/types/fs/glob.d.ts +17 -0
  13. package/dist/types/fs/glob.d.ts.map +1 -1
  14. package/dist/types/fs/node-fs.d.ts.map +1 -1
  15. package/dist/types/fs/types.d.ts +30 -2
  16. package/dist/types/fs/types.d.ts.map +1 -1
  17. package/dist/types/handlers/entry-ops.d.ts.map +1 -1
  18. package/dist/types/index.d.ts +7 -5
  19. package/dist/types/index.d.ts.map +1 -1
  20. package/dist/types/media/contember.d.ts.map +1 -1
  21. package/dist/types/media/errors.d.ts +17 -0
  22. package/dist/types/media/errors.d.ts.map +1 -0
  23. package/dist/types/media/index.d.ts +3 -0
  24. package/dist/types/media/index.d.ts.map +1 -1
  25. package/dist/types/media/local.d.ts.map +1 -1
  26. package/dist/types/media/names.d.ts +17 -0
  27. package/dist/types/media/names.d.ts.map +1 -0
  28. package/dist/types/media/s3.d.ts.map +1 -1
  29. package/dist/types/media/type-filter.d.ts +67 -0
  30. package/dist/types/media/type-filter.d.ts.map +1 -0
  31. package/dist/types/project-config-ast.d.ts +5 -1
  32. package/dist/types/project-config-ast.d.ts.map +1 -1
  33. package/dist/types/route-scan.d.ts +10 -0
  34. package/dist/types/route-scan.d.ts.map +1 -0
  35. package/dist/types/tsconfig.tsbuildinfo +1 -1
  36. package/package.json +2 -2
  37. package/src/astro-source-analysis.ts +562 -0
  38. package/src/check-entries.ts +16 -1
  39. package/src/check.ts +14 -1
  40. package/src/collection-scanner.ts +413 -19
  41. package/src/content-config-ast.ts +616 -13
  42. package/src/core.ts +21 -5
  43. package/src/fs/glob.ts +39 -0
  44. package/src/fs/node-fs.ts +87 -11
  45. package/src/fs/types.ts +31 -2
  46. package/src/handlers/entry-ops.ts +11 -13
  47. package/src/index.ts +28 -3
  48. package/src/media/contember.ts +10 -2
  49. package/src/media/errors.ts +21 -0
  50. package/src/media/index.ts +10 -0
  51. package/src/media/local.ts +177 -79
  52. package/src/media/names.ts +24 -0
  53. package/src/media/s3.ts +33 -3
  54. package/src/media/type-filter.ts +186 -0
  55. package/src/project-config-ast.ts +185 -10
  56. package/src/route-scan.ts +32 -0
@@ -0,0 +1,562 @@
1
+ import { parse as parseBabel } from '@babel/parser'
2
+ import type * as t from '@babel/types'
3
+
4
+ export type AstroContentAccessor = 'getCollection' | 'getEntry' | 'getEntryBySlug' | 'getEntries'
5
+
6
+ export interface AstroSourceImport {
7
+ source: string
8
+ }
9
+
10
+ export interface AstroContentCall {
11
+ accessor: AstroContentAccessor
12
+ collectionName: string | null
13
+ inExportedGetStaticPaths: boolean
14
+ }
15
+
16
+ export interface AstroCollectionBinding {
17
+ localName: string
18
+ collectionName: string
19
+ /** Path from an item (array) or value (entry) to the value held by this binding. */
20
+ itemPath: string
21
+ }
22
+
23
+ export interface AstroSourceAnalysis {
24
+ imports: AstroSourceImport[]
25
+ collectionCalls: AstroContentCall[]
26
+ collectionBindings: AstroCollectionBinding[]
27
+ }
28
+
29
+ interface CollectionBinding {
30
+ collectionName: string
31
+ itemPath: string
32
+ shape: 'array' | 'entry'
33
+ }
34
+
35
+ interface AnalyzerContext {
36
+ insideExportedGetStaticPaths: boolean
37
+ shadowed: ReadonlySet<string>
38
+ }
39
+
40
+ const FUNCTION_NODE_TYPES = new Set([
41
+ 'ArrowFunctionExpression',
42
+ 'FunctionDeclaration',
43
+ 'FunctionExpression',
44
+ 'ObjectMethod',
45
+ 'ClassMethod',
46
+ 'ClassPrivateMethod',
47
+ ])
48
+
49
+ const SKIPPED_CHILD_KEYS = new Set([
50
+ 'loc',
51
+ 'start',
52
+ 'end',
53
+ 'range',
54
+ 'leadingComments',
55
+ 'trailingComments',
56
+ 'innerComments',
57
+ 'extra',
58
+ 'errors',
59
+ ])
60
+
61
+ function isContentAccessor(value: string): value is AstroContentAccessor {
62
+ return value === 'getCollection'
63
+ || value === 'getEntry'
64
+ || value === 'getEntryBySlug'
65
+ || value === 'getEntries'
66
+ }
67
+
68
+ function isNode(value: unknown): value is t.Node {
69
+ return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'type') === 'string'
70
+ }
71
+
72
+ function childNodes(node: t.Node): t.Node[] {
73
+ const children: t.Node[] = []
74
+ for (const key of Object.keys(node)) {
75
+ if (SKIPPED_CHILD_KEYS.has(key)) continue
76
+ const value: unknown = Reflect.get(node, key)
77
+ if (isNode(value)) {
78
+ children.push(value)
79
+ } else if (Array.isArray(value)) {
80
+ for (const item of value) {
81
+ if (isNode(item)) children.push(item)
82
+ }
83
+ }
84
+ }
85
+ return children
86
+ }
87
+
88
+ /** Matches the opening fence: an optional BOM, any leading whitespace, `---`, then the end of that line. */
89
+ const OPENING_FENCE = /^?\s*---[ \t]*\r?\n/
90
+
91
+ /**
92
+ * Extract the frontmatter of an Astro component.
93
+ *
94
+ * Mirrors `@astrojs/compiler` on the fences it accepts: blank lines or indentation before the
95
+ * opening `---`, and spaces or tabs around either fence. Anything other than whitespace before
96
+ * the opening fence means there is no frontmatter to read.
97
+ */
98
+ function extractAstroFrontmatter(source: string): string | null {
99
+ const opening = OPENING_FENCE.exec(source)
100
+ if (!opening) return null
101
+ const codeStart = opening[0].length
102
+
103
+ let lineStart = codeStart
104
+ while (lineStart <= source.length) {
105
+ const newline = source.indexOf('\n', lineStart)
106
+ const lineEnd = newline === -1 ? source.length : newline
107
+ if (source.slice(lineStart, lineEnd).trim() === '---') {
108
+ let codeEnd = lineStart
109
+ if (codeEnd > codeStart && source.charCodeAt(codeEnd - 1) === 10) {
110
+ codeEnd--
111
+ if (codeEnd > codeStart && source.charCodeAt(codeEnd - 1) === 13) codeEnd--
112
+ }
113
+ return source.slice(codeStart, codeEnd)
114
+ }
115
+ if (newline === -1) return null
116
+ lineStart = newline + 1
117
+ }
118
+ return null
119
+ }
120
+
121
+ function parseScript(source: string): t.File | null {
122
+ try {
123
+ return parseBabel(source, {
124
+ sourceType: 'module',
125
+ plugins: ['typescript', 'jsx'],
126
+ errorRecovery: true,
127
+ })
128
+ } catch {
129
+ return null
130
+ }
131
+ }
132
+
133
+ function importedName(specifier: t.ImportSpecifier): string {
134
+ return specifier.imported.type === 'Identifier' ? specifier.imported.name : specifier.imported.value
135
+ }
136
+
137
+ function importFacts(ast: t.File): AstroSourceImport[] {
138
+ return ast.program.body.flatMap(statement => statement.type === 'ImportDeclaration' ? [{ source: statement.source.value }] : [])
139
+ }
140
+
141
+ function contentImportBindings(ast: t.File): {
142
+ named: Map<string, AstroContentAccessor>
143
+ namespaces: Set<string>
144
+ } {
145
+ const named = new Map<string, AstroContentAccessor>()
146
+ const namespaces = new Set<string>()
147
+ for (const statement of ast.program.body) {
148
+ if (
149
+ statement.type !== 'ImportDeclaration'
150
+ || statement.source.value !== 'astro:content'
151
+ || statement.importKind === 'type'
152
+ || statement.importKind === 'typeof'
153
+ ) continue
154
+ for (const specifier of statement.specifiers) {
155
+ if (specifier.type === 'ImportNamespaceSpecifier') namespaces.add(specifier.local.name)
156
+ if (
157
+ specifier.type === 'ImportSpecifier'
158
+ && specifier.importKind !== 'type'
159
+ && specifier.importKind !== 'typeof'
160
+ ) {
161
+ const name = importedName(specifier)
162
+ if (isContentAccessor(name)) named.set(specifier.local.name, name)
163
+ }
164
+ }
165
+ }
166
+ return { named, namespaces }
167
+ }
168
+
169
+ function addPatternNames(pattern: t.Node | null | undefined, names: Set<string>): void {
170
+ if (!pattern) return
171
+ switch (pattern.type) {
172
+ case 'Identifier':
173
+ names.add(pattern.name)
174
+ return
175
+ case 'ObjectPattern':
176
+ for (const property of pattern.properties) {
177
+ if (property.type === 'RestElement') addPatternNames(property.argument, names)
178
+ else addPatternNames(property.value, names)
179
+ }
180
+ return
181
+ case 'ArrayPattern':
182
+ for (const element of pattern.elements) addPatternNames(element, names)
183
+ return
184
+ case 'AssignmentPattern':
185
+ addPatternNames(pattern.left, names)
186
+ return
187
+ case 'RestElement':
188
+ addPatternNames(pattern.argument, names)
189
+ return
190
+ case 'TSParameterProperty':
191
+ addPatternNames(pattern.parameter, names)
192
+ return
193
+ }
194
+ }
195
+
196
+ function declarationFromStatement(
197
+ statement: t.Statement | t.ModuleDeclaration,
198
+ ): t.VariableDeclaration | t.FunctionDeclaration | t.ClassDeclaration | null {
199
+ if (statement.type === 'VariableDeclaration' || statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') {
200
+ return statement
201
+ }
202
+ if (statement.type !== 'ExportNamedDeclaration' && statement.type !== 'ExportDefaultDeclaration') return null
203
+ const declaration = statement.declaration
204
+ return declaration?.type === 'VariableDeclaration'
205
+ || declaration?.type === 'FunctionDeclaration'
206
+ || declaration?.type === 'ClassDeclaration'
207
+ ? declaration
208
+ : null
209
+ }
210
+
211
+ function addDirectLexicalNames(
212
+ statements: Array<t.Statement | t.ModuleDeclaration>,
213
+ names: Set<string>,
214
+ includeVar: boolean,
215
+ ): void {
216
+ for (const statement of statements) {
217
+ const declaration = declarationFromStatement(statement)
218
+ if (!declaration) continue
219
+ if (declaration.type === 'VariableDeclaration') {
220
+ if (!includeVar && declaration.kind === 'var') continue
221
+ for (const declarator of declaration.declarations) addPatternNames(declarator.id, names)
222
+ } else if (
223
+ (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration')
224
+ && declaration.id
225
+ ) {
226
+ names.add(declaration.id.name)
227
+ }
228
+ }
229
+ }
230
+
231
+ function addVarNames(node: t.Node, names: Set<string>, root = true): void {
232
+ if (!root && FUNCTION_NODE_TYPES.has(node.type)) return
233
+ if (node.type === 'VariableDeclaration' && node.kind === 'var') {
234
+ for (const declarator of node.declarations) addPatternNames(declarator.id, names)
235
+ }
236
+ for (const child of childNodes(node)) addVarNames(child, names, false)
237
+ }
238
+
239
+ function functionScopeNames(node: t.Node): Set<string> | null {
240
+ const names = new Set<string>()
241
+ switch (node.type) {
242
+ case 'ArrowFunctionExpression':
243
+ case 'FunctionExpression':
244
+ case 'FunctionDeclaration':
245
+ case 'ObjectMethod':
246
+ case 'ClassMethod':
247
+ case 'ClassPrivateMethod':
248
+ for (const parameter of node.params) addPatternNames(parameter, names)
249
+ if ((node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration') && node.id) {
250
+ names.add(node.id.name)
251
+ }
252
+ addVarNames(node.body, names)
253
+ return names
254
+ default:
255
+ return null
256
+ }
257
+ }
258
+
259
+ function withNames(base: ReadonlySet<string>, additions: ReadonlySet<string>): ReadonlySet<string> {
260
+ if (additions.size === 0) return base
261
+ return new Set([...base, ...additions])
262
+ }
263
+
264
+ function topLevelShadowedNames(ast: t.File, importedLocals: ReadonlySet<string>): Set<string> {
265
+ const declared = new Set<string>()
266
+ addDirectLexicalNames(ast.program.body, declared, true)
267
+ addVarNames(ast.program, declared)
268
+ for (const imported of importedLocals) declared.delete(imported)
269
+ return declared
270
+ }
271
+
272
+ function exportedName(specifier: t.ExportSpecifier): string {
273
+ return specifier.exported.type === 'Identifier' ? specifier.exported.name : specifier.exported.value
274
+ }
275
+
276
+ function unwrapExpression(node: t.Node): t.Node {
277
+ let current = node
278
+ while (
279
+ current.type === 'AwaitExpression'
280
+ || current.type === 'TSAsExpression'
281
+ || current.type === 'TSSatisfiesExpression'
282
+ || current.type === 'TSTypeAssertion'
283
+ || current.type === 'TSNonNullExpression'
284
+ || current.type === 'ParenthesizedExpression'
285
+ || current.type === 'TypeCastExpression'
286
+ ) {
287
+ current = current.type === 'AwaitExpression' ? current.argument : current.expression
288
+ }
289
+ return current
290
+ }
291
+
292
+ function topLevelValueNodes(ast: t.File): Map<string, t.Node> {
293
+ const values = new Map<string, t.Node>()
294
+ for (const statement of ast.program.body) {
295
+ const declaration = declarationFromStatement(statement)
296
+ if (!declaration) continue
297
+ if (declaration.type === 'FunctionDeclaration' && declaration.id) {
298
+ values.set(declaration.id.name, declaration)
299
+ } else if (declaration.type === 'VariableDeclaration') {
300
+ for (const declarator of declaration.declarations) {
301
+ if (declarator.id.type === 'Identifier' && declarator.init) {
302
+ values.set(declarator.id.name, unwrapExpression(declarator.init))
303
+ }
304
+ }
305
+ }
306
+ }
307
+ return values
308
+ }
309
+
310
+ function exportedGetStaticPathsNodes(ast: t.File): Set<t.Node> {
311
+ const exportedLocals = new Set<string>()
312
+ for (const statement of ast.program.body) {
313
+ if (statement.type !== 'ExportNamedDeclaration') continue
314
+ const declaration = statement.declaration
315
+ if (declaration?.type === 'FunctionDeclaration' && declaration.id?.name === 'getStaticPaths') {
316
+ exportedLocals.add('getStaticPaths')
317
+ } else if (declaration?.type === 'VariableDeclaration') {
318
+ for (const declarator of declaration.declarations) {
319
+ if (declarator.id.type === 'Identifier' && declarator.id.name === 'getStaticPaths') {
320
+ exportedLocals.add('getStaticPaths')
321
+ }
322
+ }
323
+ }
324
+ if (statement.source) continue
325
+ for (const specifier of statement.specifiers) {
326
+ if (specifier.type === 'ExportSpecifier' && exportedName(specifier) === 'getStaticPaths') {
327
+ exportedLocals.add(specifier.local.name)
328
+ }
329
+ }
330
+ }
331
+
332
+ const values = topLevelValueNodes(ast)
333
+ const nodes = new Set<t.Node>()
334
+ for (const local of exportedLocals) {
335
+ const node = values.get(local)
336
+ if (node && FUNCTION_NODE_TYPES.has(node.type)) nodes.add(node)
337
+ }
338
+ return nodes
339
+ }
340
+
341
+ function staticString(node: t.Node | null | undefined): string | null {
342
+ if (!node) return null
343
+ const value = unwrapExpression(node)
344
+ if (value.type === 'StringLiteral') return value.value
345
+ if (value.type === 'TemplateLiteral' && value.expressions.length === 0 && value.quasis.length === 1) {
346
+ return value.quasis[0]?.value.cooked ?? value.quasis[0]?.value.raw ?? null
347
+ }
348
+ return null
349
+ }
350
+
351
+ function memberPropertyName(node: t.MemberExpression | t.OptionalMemberExpression): string | null {
352
+ if (!node.computed && node.property.type === 'Identifier') return node.property.name
353
+ if (node.computed && node.property.type === 'StringLiteral') return node.property.value
354
+ return null
355
+ }
356
+
357
+ function callAccessor(
358
+ node: t.CallExpression | t.OptionalCallExpression,
359
+ named: ReadonlyMap<string, AstroContentAccessor>,
360
+ namespaces: ReadonlySet<string>,
361
+ shadowed: ReadonlySet<string>,
362
+ ): AstroContentAccessor | null {
363
+ const callee = unwrapExpression(node.callee)
364
+ if (callee.type === 'Identifier') {
365
+ if (shadowed.has(callee.name)) return null
366
+ return named.get(callee.name) ?? null
367
+ }
368
+ if (callee.type !== 'MemberExpression' && callee.type !== 'OptionalMemberExpression') return null
369
+ const object = unwrapExpression(callee.object)
370
+ if (object.type !== 'Identifier' || shadowed.has(object.name) || !namespaces.has(object.name)) return null
371
+ const property = memberPropertyName(callee)
372
+ if (!property || !isContentAccessor(property)) return null
373
+ return property
374
+ }
375
+
376
+ function collectionNameFromCall(node: t.CallExpression | t.OptionalCallExpression): string | null {
377
+ const first = node.arguments[0]
378
+ return first && first.type !== 'SpreadElement' && first.type !== 'ArgumentPlaceholder'
379
+ ? staticString(first)
380
+ : null
381
+ }
382
+
383
+ function collectCalls(
384
+ ast: t.File,
385
+ named: ReadonlyMap<string, AstroContentAccessor>,
386
+ namespaces: ReadonlySet<string>,
387
+ ): AstroContentCall[] {
388
+ const calls: AstroContentCall[] = []
389
+ const staticPathsNodes = exportedGetStaticPathsNodes(ast)
390
+ const importedLocals = new Set([...named.keys(), ...namespaces])
391
+ const rootShadowed = topLevelShadowedNames(ast, importedLocals)
392
+
393
+ function visit(node: t.Node, context: AnalyzerContext): void {
394
+ let shadowed = context.shadowed
395
+ const functionNames = functionScopeNames(node)
396
+ if (functionNames) shadowed = withNames(shadowed, functionNames)
397
+ if (node.type === 'BlockStatement') {
398
+ const blockNames = new Set<string>()
399
+ addDirectLexicalNames(node.body, blockNames, false)
400
+ shadowed = withNames(shadowed, blockNames)
401
+ } else if (node.type === 'CatchClause') {
402
+ const catchNames = new Set<string>()
403
+ addPatternNames(node.param, catchNames)
404
+ shadowed = withNames(shadowed, catchNames)
405
+ }
406
+
407
+ const insideExportedGetStaticPaths = context.insideExportedGetStaticPaths || staticPathsNodes.has(node)
408
+ if (node.type === 'CallExpression' || node.type === 'OptionalCallExpression') {
409
+ const accessor = callAccessor(node, named, namespaces, shadowed)
410
+ if (accessor) {
411
+ calls.push({
412
+ accessor,
413
+ collectionName: collectionNameFromCall(node),
414
+ inExportedGetStaticPaths: insideExportedGetStaticPaths,
415
+ })
416
+ }
417
+ }
418
+
419
+ const childContext = { insideExportedGetStaticPaths, shadowed }
420
+ for (const child of childNodes(node)) visit(child, childContext)
421
+ }
422
+
423
+ const context: AnalyzerContext = { insideExportedGetStaticPaths: false, shadowed: rootShadowed }
424
+ for (const statement of ast.program.body) visit(statement, context)
425
+ return calls
426
+ }
427
+
428
+ function expressionAccessor(node: t.Node): { base: string; path: string } | null {
429
+ const value = unwrapExpression(node)
430
+ if (value.type === 'Identifier') return { base: value.name, path: '' }
431
+ if (value.type !== 'MemberExpression' && value.type !== 'OptionalMemberExpression') return null
432
+ const object = expressionAccessor(value.object)
433
+ if (!object) return null
434
+ if (!value.computed && value.property.type === 'Identifier') {
435
+ return { base: object.base, path: `${object.path}.${value.property.name}` }
436
+ }
437
+ if (value.computed && value.property.type === 'NumericLiteral') {
438
+ return { base: object.base, path: `${object.path}[${value.property.value}]` }
439
+ }
440
+ return null
441
+ }
442
+
443
+ function returnedExpression(callback: t.ArrowFunctionExpression | t.FunctionExpression): t.Node | null {
444
+ if (callback.body.type !== 'BlockStatement') return callback.body
445
+ for (const statement of callback.body.body) {
446
+ if (statement.type === 'ReturnStatement' && statement.argument) return statement.argument
447
+ }
448
+ return null
449
+ }
450
+
451
+ function mapBinding(
452
+ node: t.Node,
453
+ bindings: ReadonlyMap<string, CollectionBinding>,
454
+ ): CollectionBinding | null {
455
+ const value = unwrapExpression(node)
456
+ if (value.type !== 'CallExpression' && value.type !== 'OptionalCallExpression') return null
457
+ const callee = unwrapExpression(value.callee)
458
+ if (callee.type !== 'MemberExpression' && callee.type !== 'OptionalMemberExpression') return null
459
+ if (memberPropertyName(callee) !== 'map') return null
460
+ const source = expressionAccessor(callee.object)
461
+ if (!source || source.path !== '') return null
462
+ const sourceBinding = bindings.get(source.base)
463
+ if (!sourceBinding || sourceBinding.shape !== 'array') return null
464
+
465
+ const callback = value.arguments[0]
466
+ if (!callback || (callback.type !== 'ArrowFunctionExpression' && callback.type !== 'FunctionExpression')) return null
467
+ const parameter = callback.params[0]
468
+ if (!parameter || parameter.type !== 'Identifier') return null
469
+ const returned = returnedExpression(callback)
470
+ if (!returned) return null
471
+ const projection = expressionAccessor(returned)
472
+ if (!projection || projection.base !== parameter.name) return null
473
+
474
+ return { ...sourceBinding, itemPath: sourceBinding.itemPath + projection.path }
475
+ }
476
+
477
+ function directCallBinding(
478
+ node: t.Node,
479
+ named: ReadonlyMap<string, AstroContentAccessor>,
480
+ namespaces: ReadonlySet<string>,
481
+ shadowed: ReadonlySet<string>,
482
+ ): CollectionBinding | null {
483
+ const value = unwrapExpression(node)
484
+ if (value.type !== 'CallExpression' && value.type !== 'OptionalCallExpression') return null
485
+ const matched = callAccessor(value, named, namespaces, shadowed)
486
+ const collectionName = collectionNameFromCall(value)
487
+ if (!matched || matched === 'getEntries' || !collectionName) return null
488
+ return {
489
+ collectionName,
490
+ shape: matched === 'getCollection' ? 'array' : 'entry',
491
+ itemPath: '',
492
+ }
493
+ }
494
+
495
+ function topLevelVariableDeclarations(ast: t.File): t.VariableDeclaration[] {
496
+ const declarations: t.VariableDeclaration[] = []
497
+ for (const statement of ast.program.body) {
498
+ if (statement.type === 'VariableDeclaration') declarations.push(statement)
499
+ else if (statement.type === 'ExportNamedDeclaration' && statement.declaration?.type === 'VariableDeclaration') {
500
+ declarations.push(statement.declaration)
501
+ }
502
+ }
503
+ return declarations
504
+ }
505
+
506
+ function collectBindings(
507
+ ast: t.File,
508
+ named: ReadonlyMap<string, AstroContentAccessor>,
509
+ namespaces: ReadonlySet<string>,
510
+ ): AstroCollectionBinding[] {
511
+ const facts: AstroCollectionBinding[] = []
512
+ const bindings = new Map<string, CollectionBinding>()
513
+ const importedLocals = new Set([...named.keys(), ...namespaces])
514
+ const shadowed = topLevelShadowedNames(ast, importedLocals)
515
+
516
+ for (const declaration of topLevelVariableDeclarations(ast)) {
517
+ for (const declarator of declaration.declarations) {
518
+ if (declarator.id.type !== 'Identifier' || !declarator.init) continue
519
+ const name = declarator.id.name
520
+ const direct = directCallBinding(declarator.init, named, namespaces, shadowed)
521
+ const alias = expressionAccessor(declarator.init)
522
+ const aliased = alias?.path === '' ? bindings.get(alias.base) : undefined
523
+ const mapped = mapBinding(declarator.init, bindings)
524
+ const base = direct ?? mapped ?? aliased
525
+ if (!base) continue
526
+
527
+ bindings.set(name, base)
528
+ facts.push({ localName: name, collectionName: base.collectionName, itemPath: base.itemPath })
529
+ }
530
+ }
531
+ return facts
532
+ }
533
+
534
+ function analyzeAstroContentAst(ast: t.File): AstroSourceAnalysis {
535
+ const imports = importFacts(ast)
536
+ const { named, namespaces } = contentImportBindings(ast)
537
+ return {
538
+ imports,
539
+ collectionCalls: collectCalls(ast, named, namespaces),
540
+ collectionBindings: collectBindings(ast, named, namespaces),
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Analyze JavaScript or TypeScript containing Astro content accessors: a module, or the
546
+ * frontmatter of an `.astro` file once it has been extracted.
547
+ *
548
+ * A caller that already holds the frontmatter (or a Babel parse of it, as the CMS source
549
+ * finder does) passes that directly, so the source is neither re-extracted nor re-parsed.
550
+ */
551
+ export function analyzeAstroScript(source: string | t.File): AstroSourceAnalysis {
552
+ const ast = typeof source === 'string' ? parseScript(source) : source
553
+ return ast ? analyzeAstroContentAst(ast) : { imports: [], collectionCalls: [], collectionBindings: [] }
554
+ }
555
+
556
+ /** Analyze the frontmatter of a complete `.astro` source string. */
557
+ export function analyzeAstroSource(source: string): AstroSourceAnalysis {
558
+ const frontmatter = extractAstroFrontmatter(source)
559
+ return frontmatter === null
560
+ ? { imports: [], collectionCalls: [], collectionBindings: [] }
561
+ : analyzeAstroScript(frontmatter)
562
+ }
@@ -11,6 +11,7 @@ import path from 'node:path'
11
11
  import yaml from 'yaml'
12
12
  import type { ParsedCollection, ParsedConfig } from './content-config-ast'
13
13
  import type { CollectionKind } from './editor-write-model'
14
+ import { UnreadableDirectoryError } from './fs/glob'
14
15
  import type { CmsFileSystem } from './fs/types'
15
16
 
16
17
  export interface LoadedEntry {
@@ -30,6 +31,8 @@ export interface LoadedCollection {
30
31
  base: string
31
32
  /** False when the loader base directory is not there at all. */
32
33
  exists: boolean
34
+ /** Why the collection's files could not be listed, when they could not: its `entries` are then no account of it. */
35
+ unreadable?: string
33
36
  entries: LoadedEntry[]
34
37
  }
35
38
 
@@ -103,8 +106,20 @@ export async function loadCollections(fs: CmsFileSystem, config: ParsedConfig):
103
106
  continue
104
107
  }
105
108
 
109
+ let files: string[]
110
+ try {
111
+ files = await collectEntryFiles(fs, collection, base)
112
+ } catch (error) {
113
+ // Anything else (a path traversal, a bug) is not a fact about the content: let it surface.
114
+ if (!(error instanceof UnreadableDirectoryError)) throw error
115
+ // A directory under the base that cannot be read. Which entries it holds is unknown,
116
+ // so the collection is handed on as unreadable instead of as whatever was listed so far.
117
+ loaded.set(name, { name, base, exists: true, unreadable: error.message, entries: [] })
118
+ continue
119
+ }
120
+
106
121
  const entries: LoadedEntry[] = []
107
- for (const file of await collectEntryFiles(fs, collection, base)) {
122
+ for (const file of files) {
108
123
  const parsed = parseEntry(file, await fs.readFile(file))
109
124
  entries.push({
110
125
  file,
package/src/check.ts CHANGED
@@ -262,6 +262,18 @@ export async function checkContent(fs: CmsFileSystem, options: CheckContentOptio
262
262
  })
263
263
  continue
264
264
  }
265
+ if (loaded.unreadable !== undefined) {
266
+ // An error, not a shorter count: nothing was checked, and the build reads the same directory.
267
+ findings.push({
268
+ severity: 'error',
269
+ code: 'config/unreadable-dir',
270
+ file: loaded.base,
271
+ field: name,
272
+ message: `Collection "${name}" could not be read: ${loaded.unreadable}. `
273
+ + `Make the directory readable, or narrow the loader's base or pattern so it does not reach there.`,
274
+ })
275
+ continue
276
+ }
265
277
  if (loaded.entries.length === 0) {
266
278
  findings.push({
267
279
  severity: 'warning',
@@ -327,7 +339,8 @@ export async function checkContent(fs: CmsFileSystem, options: CheckContentOptio
327
339
  const reference = field.reference
328
340
  if (!reference) continue
329
341
  const targets = stems.get(reference.target)
330
- // An unresolvable target collection is already reported once by config/missing-dir.
342
+ // An unresolvable target collection is already reported once by config/missing-dir
343
+ // or config/unreadable-dir.
331
344
  if (!targets || targets.size === 0) continue
332
345
  const values = reference.isArray ? (Array.isArray(value) ? value : [value]) : [value]
333
346
  for (const item of values) {