@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
@@ -77,12 +77,64 @@ export interface ParsedCollection {
77
77
  fragment?: true
78
78
  /** Preview target of a fragment collection, from a `defineCmsCollection({ cms: { previewOf } })` block. */
79
79
  previewOf?: string
80
+ /** Display label, from a `defineCmsCollection({ cms: { label } })` block. */
81
+ label?: string
82
+ /** The collection is left out of collection browsers, from a `defineCmsCollection({ cms: { hidden } })` block. */
83
+ hidden?: true
84
+ /** Position in collection browsers, from a `defineCmsCollection({ cms: { order } })` block. */
85
+ order?: number
86
+ /** Section heading in collection browsers, from a `defineCmsCollection({ cms: { group } })` block. */
87
+ group?: string
80
88
  }
81
89
 
82
90
  export type ParsedConfig = Map<string, ParsedCollection>
83
91
 
92
+ /**
93
+ * A key of the config's `collections` export, whether or not the rest of its declaration
94
+ * could be read. `ParsedConfig` only holds the collections with a readable schema or glob
95
+ * pattern; this is every name, so a scan can tell a collection it could not locate from one
96
+ * that does not exist.
97
+ *
98
+ * The loader facts are stricter than `ParsedCollection`'s: an option is only reported when
99
+ * nothing next to it (a spread) could replace it, because a scan report vouches by them.
100
+ */
101
+ export interface DeclaredCollection {
102
+ name: string
103
+ /** Literal `base` of a `glob()` loader; `.` when the options name none, which is the project root to Astro. */
104
+ loaderBase?: string
105
+ /** Literal `pattern` of a `glob()` loader. */
106
+ loaderPattern?: string
107
+ /** The patterns of a `glob()` loader that takes a list of them, when every one is a literal. */
108
+ loaderPatterns?: string[]
109
+ /** Literal path of a `file()` loader. */
110
+ loaderFile?: string
111
+ /** The declaration has a `loader`, whatever it is. */
112
+ hasLoader?: true
113
+ /** The declaration has no `loader` at all: its entries are the files of `<contentDir>/<name>`. */
114
+ noLoader?: true
115
+ }
116
+
117
+ /** One read of a content config: what {@link parseContentConfig} returns, and what the config declares beyond it. */
118
+ export interface ContentConfigRead {
119
+ parsed: ParsedConfig
120
+ /** Every collection name the reader could make out. */
121
+ declared: DeclaredCollection[]
122
+ /**
123
+ * The reader could not see the whole `collections` export, so `declared` may be missing
124
+ * names: the export is not an object literal (a call, a re-export from another module),
125
+ * the literal has a spread, a method, a `__proto__` or a computed key in it, or the file
126
+ * mentions `collections` in a way that may add to it.
127
+ */
128
+ partial: boolean
129
+ /**
130
+ * The file exports `collections`, or may through `export *`. Astro takes no collections
131
+ * from a content config that does not, whatever the file declares without exporting it.
132
+ */
133
+ exportsCollections: boolean
134
+ }
135
+
84
136
  /** Cached parse result keyed by config path; invalidated by mtime. */
85
- export type ParseCache = Map<string, { mtimeMs: number; parsed: ParsedConfig }>
137
+ export type ParseCache = Map<string, { mtimeMs: number } & ContentConfigRead>
86
138
 
87
139
  const FIELD_HELPER_TYPES = new Set([
88
140
  'text',
@@ -248,6 +300,19 @@ function parseSource(source: string): t.File | null {
248
300
  /** Where a project may keep its content config, in the order the parser prefers them. */
249
301
  export const CONTENT_CONFIG_PATHS = ['src/content/config.ts', 'src/content.config.ts'] as const
250
302
 
303
+ /**
304
+ * Where Astro also takes a content config from and this reader does not look. A project with
305
+ * one of these has a config; it is only out of the reader's sight.
306
+ */
307
+ export const UNREAD_CONTENT_CONFIG_PATHS = [
308
+ 'src/content.config.mjs',
309
+ 'src/content.config.js',
310
+ 'src/content.config.mts',
311
+ 'src/content/config.mjs',
312
+ 'src/content/config.js',
313
+ 'src/content/config.mts',
314
+ ] as const
315
+
251
316
  /**
252
317
  * Why `parseContentConfig` came back empty. Three different facts share that one return value, and
253
318
  * only two of them are a defect: a site with no content collections is a legitimate site.
@@ -283,6 +348,19 @@ export async function classifyEmptyContentConfig(fs: CmsFileSystem): Promise<Emp
283
348
  * re-reading and re-parsing an unchanged config file.
284
349
  */
285
350
  export async function parseContentConfig(fs: CmsFileSystem, cache: ParseCache): Promise<ParsedConfig> {
351
+ return (await readContentConfig(fs, cache)).parsed
352
+ }
353
+
354
+ /**
355
+ * {@link parseContentConfig}, plus every collection name the config declares — including the
356
+ * ones the parsed map leaves out because neither a schema nor a glob pattern could be read.
357
+ * Same file choice and the same cache.
358
+ */
359
+ export async function readContentConfig(fs: CmsFileSystem, cache: ParseCache): Promise<ContentConfigRead> {
360
+ // A config whose parsed map came back empty may still declare names, all of them unreadable
361
+ // declarations, or export a `collections` the reader cannot see into. The first such read
362
+ // is the answer when no config parses to anything.
363
+ let unparsed: ContentConfigRead | undefined
286
364
  for (const configPath of CONTENT_CONFIG_PATHS) {
287
365
  let stat: Awaited<ReturnType<CmsFileSystem['stat']>>
288
366
  try {
@@ -291,25 +369,27 @@ export async function parseContentConfig(fs: CmsFileSystem, cache: ParseCache):
291
369
  continue
292
370
  }
293
371
 
294
- const cached = cache.get(configPath)
295
- if (cached && cached.mtimeMs === stat.mtimeMs) {
296
- if (cached.parsed.size > 0) return cached.parsed
297
- continue
372
+ let cached = cache.get(configPath)
373
+ if (!cached || cached.mtimeMs !== stat.mtimeMs) {
374
+ const content = await fs.readFile(configPath)
375
+ cached = { mtimeMs: stat.mtimeMs, ...readConfigSource(content) }
376
+ cache.set(configPath, cached)
298
377
  }
299
-
300
- const content = await fs.readFile(configPath)
301
- const parsed = parseConfigSource(content, configPath)
302
- cache.set(configPath, { mtimeMs: stat.mtimeMs, parsed })
303
- if (parsed.size > 0) return parsed
378
+ if (cached.parsed.size > 0) return cached
379
+ if (!unparsed && (cached.declared.length > 0 || cached.exportsCollections)) unparsed = cached
304
380
  }
305
- return new Map()
381
+ return unparsed ?? { parsed: new Map(), declared: [], partial: false, exportsCollections: false }
306
382
  }
307
383
 
308
384
  /** Exported for unit testing — operates on a source string directly. */
309
385
  export function parseConfigSource(source: string, _sourcePath?: string): ParsedConfig {
386
+ return readConfigSource(source).parsed
387
+ }
388
+
389
+ function readConfigSource(source: string): ContentConfigRead {
310
390
  const result: ParsedConfig = new Map()
311
391
  const ast = parseSource(source)
312
- if (!ast) return result
392
+ if (!ast) return { parsed: result, declared: [], partial: false, exportsCollections: false }
313
393
 
314
394
  // Single pass: collect every top-level `const X = <expr>` binding (so we can
315
395
  // later resolve Identifier references like `cs: TestimonialTranslation`),
@@ -393,6 +473,7 @@ export function parseConfigSource(source: string, _sourcePath?: string): ParsedC
393
473
  const titleField = cmsProperty?.type === 'ObjectProperty' ? parseCmsTitleField(cmsProperty.value, bindings) : undefined
394
474
  const fragment = cmsProperty?.type === 'ObjectProperty' ? parseCmsFragment(cmsProperty.value, bindings) : undefined
395
475
  const previewOf = cmsProperty?.type === 'ObjectProperty' ? parseCmsPreviewOf(cmsProperty.value, bindings) : undefined
476
+ const nav = cmsProperty?.type === 'ObjectProperty' ? parseCmsNav(cmsProperty.value, bindings) : undefined
396
477
 
397
478
  // `fragment` (no page of its own) and `pathname` (compose the entry's page URL)
398
479
  // contradict each other. Report it rather than silently preferring one — over this
@@ -423,6 +504,7 @@ export function parseConfigSource(source: string, _sourcePath?: string): ParsedC
423
504
  titleField,
424
505
  fragment,
425
506
  previewOf,
507
+ ...nav,
426
508
  })
427
509
  continue
428
510
  }
@@ -440,6 +522,7 @@ export function parseConfigSource(source: string, _sourcePath?: string): ParsedC
440
522
  titleField,
441
523
  fragment,
442
524
  previewOf,
525
+ ...nav,
443
526
  })
444
527
  continue
445
528
  }
@@ -461,10 +544,25 @@ export function parseConfigSource(source: string, _sourcePath?: string): ParsedC
461
544
  titleField,
462
545
  fragment,
463
546
  previewOf,
547
+ ...nav,
464
548
  })
465
549
  }
466
550
 
467
- return result
551
+ return { parsed: result, ...declaredOrUnknown(ast) }
552
+ }
553
+
554
+ /**
555
+ * {@link readDeclaredCollections}, which runs on every parse, also for the callers that never
556
+ * ask for a scan report. A config form it trips over must not cost them the parse, so a throw
557
+ * reads as a config whose declarations could not be seen: nothing named, and possibly more.
558
+ */
559
+ function declaredOrUnknown(ast: t.File): Pick<ContentConfigRead, 'declared' | 'partial' | 'exportsCollections'> {
560
+ try {
561
+ return readDeclaredCollections(ast)
562
+ } catch (error) {
563
+ console.warn('[cms] Could not read the collections the content config declares:', error)
564
+ return { declared: [], partial: true, exportsCollections: true }
565
+ }
468
566
  }
469
567
 
470
568
  /**
@@ -628,6 +726,40 @@ function parseCmsPreviewOf(node: t.Node, bindings: Bindings): string | undefined
628
726
  return value.value
629
727
  }
630
728
 
729
+ /**
730
+ * Parse the collection-browser keys of a `cms: { label, hidden, order, group }` block: how
731
+ * the collection is named, placed and sectioned where collections are listed. Same
732
+ * shape-tolerant contract as {@link parseCmsTitleField}: a key whose value is not the
733
+ * expected literal (or is an empty string) is skipped, leaving the default in place. `label`
734
+ * and `group` also take a template literal without substitutions. As with `fragment`, only
735
+ * the literal `true` hides a collection.
736
+ */
737
+ function parseCmsNav(node: t.Node, bindings: Bindings): Pick<ParsedCollection, 'label' | 'hidden' | 'order' | 'group'> | undefined {
738
+ const resolved = resolveExpression(node, bindings)
739
+ if (resolved.type !== 'ObjectExpression') return undefined
740
+
741
+ const nav: Pick<ParsedCollection, 'label' | 'hidden' | 'order' | 'group'> = {}
742
+ for (const prop of resolved.properties) {
743
+ if (prop.type !== 'ObjectProperty') continue
744
+ const key = propertyKeyName(prop.key)
745
+ const value = resolveExpression(prop.value, bindings)
746
+ if (key === 'label' || key === 'group') {
747
+ // A plain string or a template literal without substitutions: both are static text.
748
+ const text = extractStaticString(value, bindings)
749
+ if (text) nav[key] = text
750
+ } else if (key === 'hidden') {
751
+ if (value.type === 'BooleanLiteral' && value.value) nav.hidden = true
752
+ } else if (key === 'order') {
753
+ if (value.type === 'NumericLiteral') {
754
+ nav.order = value.value
755
+ } else if (value.type === 'UnaryExpression' && value.operator === '-' && value.argument.type === 'NumericLiteral') {
756
+ nav.order = -value.argument.value
757
+ }
758
+ }
759
+ }
760
+ return nav
761
+ }
762
+
631
763
  /** Parse one `{ field, map? }` or `{ literal }` segment object. */
632
764
  function parsePathnameSegment(node: t.Node): PathnameSegment | null {
633
765
  if (node.type !== 'ObjectExpression') return null
@@ -699,6 +831,477 @@ function isGlobCallee(callee: t.Node): boolean {
699
831
  return callee.type === 'Identifier' && callee.name === 'glob'
700
832
  }
701
833
 
834
+ /**
835
+ * Every mention of the string option `name` in the code of a config file, comments aside: as
836
+ * an identifier or as a string of exactly that name, anywhere. One that is the key of a
837
+ * property given a plain string is that string. Any other mention is `null`: another kind of
838
+ * value (a call, a concatenation, a variable), a shorthand, a variable, a parameter or a
839
+ * member of that name, and the name as a string that is not such a key, since a string can be
840
+ * made a key in more ways than can be listed (`Object.defineProperty(config, 'srcDir', …)`,
841
+ * `const KEY = 'srcDir'`). A key given an object literal is left out: it is not a string option, so it is
842
+ * another option of that name. `null` instead of a list for a file that does not parse.
843
+ *
844
+ * For telling whether an option is set to a known value wherever the file could set it,
845
+ * without evaluating the file.
846
+ */
847
+ export function configOptionMentions(source: string, name: string): Array<string | null> | null {
848
+ const ast = parseSource(source)
849
+ if (!ast) return null
850
+ const mentions: Array<string | null> = []
851
+ walkValues(ast.program, path => {
852
+ const { node, key } = path.at(-1)!
853
+ const parent = path.at(-2)?.node
854
+ const isKey = parent?.type === 'ObjectProperty' && key === 'key'
855
+ const asString = node.type === 'StringLiteral'
856
+ ? node.value
857
+ : node.type === 'TemplateLiteral' && node.expressions.length === 0
858
+ ? node.quasis[0]?.value.cooked
859
+ : undefined
860
+ const named = node.type === 'Identifier' ? node.name === name : asString === name
861
+ if (!named) return
862
+ // `[name]: …` is keyed by a variable of that name, not by the name.
863
+ if (!isKey || (node.type === 'Identifier' && parent.computed)) mentions.push(null)
864
+ else if (parent.value.type !== 'ObjectExpression') mentions.push(extractStaticString(parent.value, new Map()) ?? null)
865
+ })
866
+ return mentions
867
+ }
868
+
869
+ /** The loaders' own calls. They read what they are handed and hand it on unchanged. */
870
+ const READER_CALLS = ['glob', 'file', 'defineCollection', 'defineCmsCollection']
871
+
872
+ /** Wrappers that change nothing about a value, the ones {@link resolveExpression} sees through. */
873
+ const VALUE_WRAPPERS = new Set(['TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion'])
874
+
875
+ /**
876
+ * TypeScript nodes that hold code and not only types; every other `TS…` node is skipped by
877
+ * {@link walkValues}. `TSQualifiedName` is among them for `import alias = blog.loader`, which
878
+ * compiles to a variable; in a type it is below a node that is skipped.
879
+ */
880
+ const TS_NODES_WITH_CODE = new Set([
881
+ ...VALUE_WRAPPERS,
882
+ 'TSInstantiationExpression',
883
+ 'TSEnumDeclaration',
884
+ 'TSEnumMember',
885
+ 'TSModuleDeclaration',
886
+ 'TSModuleBlock',
887
+ 'TSExportAssignment',
888
+ 'TSImportEqualsDeclaration',
889
+ 'TSQualifiedName',
890
+ 'TSParameterProperty',
891
+ ])
892
+
893
+ /** Keys of a node that hold no code. */
894
+ const NODE_METADATA = new Set(['loc', 'extra', 'leadingComments', 'trailingComments', 'innerComments'])
895
+
896
+ /** A node and the key of its parent it sits under; a path is these from the program down. */
897
+ interface PathStep {
898
+ node: t.Node
899
+ key: string
900
+ }
901
+
902
+ /** Visit every node that can run, with the path that leads to it. Types are passed over: they cannot touch a value. */
903
+ function walkValues(node: t.Node, visit: (path: PathStep[]) => void, path: PathStep[] = [{ node, key: '' }]): void {
904
+ visit(path)
905
+ const children: [string, unknown][] = Object.entries(node)
906
+ for (const [key, child] of children) {
907
+ if (NODE_METADATA.has(key)) continue
908
+ for (const item of Array.isArray(child) ? child : [child]) {
909
+ if (!isAstNode(item) || (item.type.startsWith('TS') && !TS_NODES_WITH_CODE.has(item.type))) continue
910
+ path.push({ node: item, key })
911
+ walkValues(item, visit, path)
912
+ path.pop()
913
+ }
914
+ }
915
+ }
916
+
917
+ /** Is the declarator at `path[index]` one of a module-level declaration? */
918
+ function isModuleLevelDeclarator(path: PathStep[], index: number): boolean {
919
+ const holder = path[index - 2]?.node
920
+ if (holder?.type === 'ExportNamedDeclaration') return path[index - 3]?.node.type === 'Program'
921
+ return holder?.type === 'Program'
922
+ }
923
+
924
+ /** A value that cannot be changed in place, so a `const` holding it is what it was declared as, whatever is done with it. */
925
+ function isImmutableLiteral(node: t.Node): boolean {
926
+ return node.type === 'StringLiteral' || node.type === 'TemplateLiteral' || node.type === 'NumericLiteral'
927
+ || node.type === 'BooleanLiteral' || node.type === 'NullLiteral' || node.type === 'BigIntLiteral'
928
+ }
929
+
930
+ /**
931
+ * The module-level `const`s whose value is, by the time Astro reads the config, what the file
932
+ * declares it as. Only these are followed; a name left out is unknown to the reader.
933
+ *
934
+ * A name is kept when every mention of it in the file is one of a short list of uses that can
935
+ * neither change the value nor hand it to code that can:
936
+ *
937
+ * - its one declaration;
938
+ * - the value of a property in an object literal the reader reads, a first argument of
939
+ * `glob`, `file`, `defineCollection` or `defineCmsCollection` where the reader reads that
940
+ * call, or the whole initializer of another `const` (an alias). "Where the reader reads" is
941
+ * the initializer of a `const` that is itself kept, so a name falls with the one that holds it;
942
+ * - `X.key` where the declaration gives `key` a string, a number, a boolean or `null`, read
943
+ * into a declaration, a property, a call argument, an array, a template, or a binary,
944
+ * logical or conditional expression;
945
+ * - `export { X }`, `export default X`, a type (`typeof X`), and `Object.keys(X)`.
946
+ *
947
+ * Any other mention drops the name: a call that takes it, a member written or called, an
948
+ * array or a spread that holds it, a loop, a conditional, a function that mentions it, a
949
+ * second declaration of the name anywhere (a parameter, a local). So does `eval` or
950
+ * `Function` anywhere in the file, for every name. Listing what is harmless instead of what
951
+ * is harmful means a use nobody thought of leaves a name unknown, not trusted.
952
+ *
953
+ * A `const` that holds a string, a number, a boolean or `null` is kept whatever mentions it:
954
+ * neither the binding nor the value can change.
955
+ *
956
+ * `trusted` names which of the loaders' calls, and `Object`, are not declared in the file
957
+ * itself; a local `glob` is not Astro's.
958
+ */
959
+ function followedConstants(ast: t.File, bindings: Bindings): { followed: Bindings; trusted: Set<string> } {
960
+ const dropped = new Set<string>()
961
+ /** A name → the `const`s whose initializer it is read in: it is kept only while they are. */
962
+ const heldBy = new Map<string, Set<string>>()
963
+ /** A name → the calls it is handed to: it is kept only while they are what they are taken for. */
964
+ const handedTo = new Map<string, Set<string>>()
965
+ const untrusted = new Set<string>()
966
+ let anythingMayChange = false
967
+
968
+ const note = (map: Map<string, Set<string>>, name: string, values: Iterable<string>): void => {
969
+ map.set(name, new Set([...map.get(name) ?? [], ...values]))
970
+ }
971
+
972
+ /** The primitive a `const`'s object literal gives `key`, if that is certain. */
973
+ const holdsPrimitiveAt = (name: string, key: string): boolean => {
974
+ const init = bindings.get(name)
975
+ const object = init && resolveExpression(init, new Map())
976
+ const member = object?.type === 'ObjectExpression' ? literalMember(object, key) : undefined
977
+ return !!member && isImmutableLiteral(resolveExpression(member, new Map()))
978
+ }
979
+
980
+ /**
981
+ * The `const` whose initializer the expression at `path[index]` is read in, and the loaders'
982
+ * calls it passes through on the way: it is that initializer, a property value of an object
983
+ * literal that is, or a first argument of one of those calls that is. `null` anywhere else.
984
+ */
985
+ const readIn = (path: PathStep[], index: number): { holder: string; calls: string[] } | null => {
986
+ const calls: string[] = []
987
+ for (let at = index;;) {
988
+ const parent = path[at - 1]?.node
989
+ const { node, key } = path[at]!
990
+ if (!parent) return null
991
+ if (VALUE_WRAPPERS.has(parent.type) && key === 'expression') {
992
+ at--
993
+ } else if (parent.type === 'ObjectProperty' && key === 'value' && path[at - 2]?.node.type === 'ObjectExpression') {
994
+ at -= 2
995
+ } else if (
996
+ parent.type === 'CallExpression' && parent.arguments[0] === node && parent.callee.type === 'Identifier'
997
+ && READER_CALLS.includes(parent.callee.name)
998
+ ) {
999
+ calls.push(parent.callee.name)
1000
+ at--
1001
+ } else {
1002
+ return parent.type === 'VariableDeclarator' && key === 'init' && parent.id.type === 'Identifier' && isModuleLevelDeclarator(path, at - 1)
1003
+ ? { holder: parent.id.name, calls }
1004
+ : null
1005
+ }
1006
+ }
1007
+ }
1008
+
1009
+ /** Is the expression at `path[index]` only read, into a place that keeps nothing but its value? */
1010
+ const isValueRead = (path: PathStep[], index: number): boolean => {
1011
+ let at = index
1012
+ while (VALUE_WRAPPERS.has(path[at - 1]?.node.type ?? '') && path[at]!.key === 'expression') at--
1013
+ const parent = path[at - 1]?.node
1014
+ const { key } = path[at]!
1015
+ switch (parent?.type) {
1016
+ case 'ObjectProperty':
1017
+ return key === 'value' && path[at - 2]?.node.type === 'ObjectExpression'
1018
+ case 'CallExpression':
1019
+ case 'OptionalCallExpression':
1020
+ case 'NewExpression':
1021
+ return key === 'arguments'
1022
+ case 'VariableDeclarator':
1023
+ case 'ArrayExpression':
1024
+ case 'TemplateLiteral':
1025
+ case 'BinaryExpression':
1026
+ case 'LogicalExpression':
1027
+ case 'ConditionalExpression':
1028
+ return true
1029
+ default:
1030
+ return false
1031
+ }
1032
+ }
1033
+
1034
+ walkValues(ast.program, path => {
1035
+ const { node, key } = path.at(-1)!
1036
+ const parent = path.at(-2)?.node
1037
+ if (node.type !== 'Identifier' || !parent) return
1038
+ const { name } = node
1039
+
1040
+ // Not a mention of the binding at all: the name of a property.
1041
+ const isMemberKey =
1042
+ (parent.type === 'ObjectProperty' || parent.type === 'ObjectMethod' || parent.type === 'ClassMethod' || parent.type === 'ClassProperty')
1043
+ && key === 'key' && !parent.computed
1044
+ const isMemberName = (parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') && key === 'property' && !parent.computed
1045
+ const isModuleName = (parent.type === 'ExportSpecifier' && key === 'exported') || (parent.type === 'ImportSpecifier' && key === 'imported')
1046
+ // Nor is the `meta` of `import.meta`.
1047
+ if (isMemberKey || isMemberName || isModuleName || parent.type === 'MetaProperty') return
1048
+
1049
+ if (name === 'eval' || name === 'Function') anythingMayChange = true
1050
+
1051
+ if (READER_CALLS.includes(name) || name === 'Object') {
1052
+ const imported = (parent.type === 'ImportSpecifier' || parent.type === 'ImportDefaultSpecifier' || parent.type === 'ImportNamespaceSpecifier')
1053
+ && key === 'local'
1054
+ // `Object` only as the one a method is called on: `Object.keys = …` makes it another.
1055
+ const grandparent = path.at(-3)?.node
1056
+ const called = (parent.type === 'CallExpression' && key === 'callee')
1057
+ || (name === 'Object' && parent.type === 'MemberExpression' && key === 'object' && !parent.computed
1058
+ && grandparent?.type === 'CallExpression' && grandparent.callee === parent)
1059
+ if (!imported && !called) untrusted.add(name)
1060
+ }
1061
+ if (!bindings.has(name)) return
1062
+
1063
+ // Its declaration. Any other declaration of the name is a mention like any other.
1064
+ if (parent.type === 'VariableDeclarator' && key === 'id' && isModuleLevelDeclarator(path, path.length - 2)) return
1065
+ if (parent.type === 'ExportDefaultDeclaration') return
1066
+ if (parent.type === 'ExportSpecifier' && key === 'local') return
1067
+ if (
1068
+ parent.type === 'CallExpression' && parent.arguments[0] === node && parent.callee.type === 'MemberExpression' && !parent.callee.computed
1069
+ && parent.callee.object.type === 'Identifier' && parent.callee.object.name === 'Object'
1070
+ && parent.callee.property.type === 'Identifier' && parent.callee.property.name === 'keys'
1071
+ ) {
1072
+ note(handedTo, name, ['Object'])
1073
+ return
1074
+ }
1075
+ if (
1076
+ (parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') && key === 'object' && !parent.computed
1077
+ && parent.property.type === 'Identifier' && holdsPrimitiveAt(name, parent.property.name) && isValueRead(path, path.length - 2)
1078
+ ) return
1079
+
1080
+ const read = readIn(path, path.length - 1)
1081
+ if (read === null) {
1082
+ dropped.add(name)
1083
+ return
1084
+ }
1085
+ note(heldBy, name, [read.holder])
1086
+ note(handedTo, name, read.calls)
1087
+ })
1088
+
1089
+ const trusted = new Set([...READER_CALLS, 'Object'].filter(name => !untrusted.has(name)))
1090
+ const keeps = (name: string): boolean => {
1091
+ const init = bindings.get(name)
1092
+ return init !== undefined && isImmutableLiteral(resolveExpression(init, new Map()))
1093
+ }
1094
+ const followed: Bindings = new Map()
1095
+ for (const [name, init] of bindings) {
1096
+ const handedOn = [...handedTo.get(name) ?? []].every(call => trusted.has(call))
1097
+ if (keeps(name) || (!anythingMayChange && !dropped.has(name) && handedOn)) followed.set(name, init)
1098
+ }
1099
+ // A name falls with the one whose initializer holds it.
1100
+ for (let fell = true; fell;) {
1101
+ fell = false
1102
+ for (const [name, holders] of heldBy) {
1103
+ if (!followed.has(name) || keeps(name) || [...holders].every(holder => followed.has(holder))) continue
1104
+ followed.delete(name)
1105
+ fell = true
1106
+ }
1107
+ }
1108
+ return { followed, trusted }
1109
+ }
1110
+
1111
+ /**
1112
+ * Every collection name the file's `collections` export declares, and whether that is all of
1113
+ * them. Reads more forms than the parse above follows (`as`, `satisfies`, a same-file
1114
+ * variable, a numeric key): naming a collection commits to nothing, while parsing one gives
1115
+ * it a schema and a place in every scan.
1116
+ *
1117
+ * Identifiers are followed through the module-level `const`s {@link followedConstants} keeps.
1118
+ */
1119
+ function readDeclaredCollections(ast: t.File): Pick<ContentConfigRead, 'declared' | 'partial' | 'exportsCollections'> {
1120
+ const bindings: Bindings = new Map()
1121
+ let collections: t.Node | undefined
1122
+ let exportsCollections = false
1123
+ // `collections` comes from where this reader does not look: another module, another local
1124
+ // name, a `let`, a destructuring…
1125
+ let outOfSight = false
1126
+ // …or would, unless this file declares it: `export * from`, `export { collections }` of an import.
1127
+ let exportedUndeclared = false
1128
+ for (const stmt of ast.program.body) {
1129
+ if (stmt.type === 'ExportAllDeclaration') {
1130
+ exportedUndeclared = true
1131
+ exportsCollections = true
1132
+ continue
1133
+ }
1134
+ if (stmt.type === 'ExportNamedDeclaration') {
1135
+ for (const specifier of stmt.specifiers) {
1136
+ const exported = specifier.exported.type === 'Identifier' ? specifier.exported.name : specifier.exported.value
1137
+ if (exported !== 'collections') continue
1138
+ exportsCollections = true
1139
+ if (stmt.source || specifier.type !== 'ExportSpecifier' || specifier.local.name !== 'collections') outOfSight = true
1140
+ else exportedUndeclared = true
1141
+ }
1142
+ }
1143
+ const varDecl = stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'VariableDeclaration'
1144
+ ? stmt.declaration
1145
+ : stmt.type === 'VariableDeclaration'
1146
+ ? stmt
1147
+ : null
1148
+ for (const decl of varDecl?.declarations ?? []) {
1149
+ if (stmt.type === 'ExportNamedDeclaration') {
1150
+ declaredPatternNames(decl.id, name => {
1151
+ if (name === 'collections') exportsCollections = true
1152
+ })
1153
+ }
1154
+ if (varDecl?.kind === 'const' && decl.id.type === 'Identifier' && decl.init) {
1155
+ bindings.set(decl.id.name, decl.init)
1156
+ if (decl.id.name === 'collections') collections = decl.init
1157
+ continue
1158
+ }
1159
+ declaredPatternNames(decl.id, name => {
1160
+ if (name === 'collections') outOfSight = true
1161
+ })
1162
+ }
1163
+ }
1164
+
1165
+ // A config that imports itself can change what it exports without naming it: `self.collections.x = …`.
1166
+ if (importsContentConfig(ast)) outOfSight = true
1167
+ if (!collections) return { declared: [], partial: outOfSight || exportedUndeclared, exportsCollections }
1168
+
1169
+ const { followed, trusted } = followedConstants(ast, bindings)
1170
+ const object = resolveExpression(collections, followed)
1171
+ if (object.type !== 'ObjectExpression') return { declared: [], partial: true, exportsCollections }
1172
+
1173
+ // What `collections` holds by the time Astro reads it may be more than the declaration says.
1174
+ let partial = outOfSight || !followed.has('collections') || !isPlainLiteralObject(object)
1175
+ // A name given twice holds what it was given last.
1176
+ const declared = new Map<string, DeclaredCollection>()
1177
+ for (const prop of object.properties) {
1178
+ // A spread, a method or a computed key that is not a string (`[name]: …` is not the name
1179
+ // it spells) hides a name.
1180
+ const name = staticKeyName(prop)
1181
+ if (prop.type !== 'ObjectProperty' || name === null) {
1182
+ partial = true
1183
+ continue
1184
+ }
1185
+ if (name === '__proto__') continue
1186
+ declared.set(name, { name, ...readDeclaredLoader(prop.value, followed, trusted) })
1187
+ }
1188
+ return { declared: [...declared.values()], partial, exportsCollections }
1189
+ }
1190
+
1191
+ /**
1192
+ * The key an object member is stored under, or `null` when it cannot be told: a spread, or
1193
+ * a computed key that is not a string (`['loader']` is `loader`; `[key]` could be anything).
1194
+ * A numeric key is a name like any other.
1195
+ */
1196
+ function staticKeyName(prop: t.ObjectExpression['properties'][number]): string | null {
1197
+ if (prop.type === 'SpreadElement') return null
1198
+ if (prop.computed) return prop.key.type === 'StringLiteral' ? prop.key.value : null
1199
+ return prop.key.type === 'NumericLiteral' ? String(prop.key.value) : propertyKeyName(prop.key)
1200
+ }
1201
+
1202
+ /**
1203
+ * An object literal that holds what its own keys say and nothing else: no spread, no key that
1204
+ * cannot be read, and no `__proto__`, which gives it another object's properties to answer with.
1205
+ */
1206
+ function isPlainLiteralObject(object: t.ObjectExpression): boolean {
1207
+ return object.properties.every(prop => {
1208
+ const key = staticKeyName(prop)
1209
+ return key !== null && key !== '__proto__'
1210
+ })
1211
+ }
1212
+
1213
+ /**
1214
+ * What an object literal holds under `key`: the last member of that name, as a later one
1215
+ * replaces an earlier. `undefined` when it has none; `null` when it has one that is not a
1216
+ * plain value (a getter, a setter, a method).
1217
+ */
1218
+ function literalMember(object: t.ObjectExpression, key: string): t.Node | null | undefined {
1219
+ const member = object.properties.findLast(prop => staticKeyName(prop) === key)
1220
+ if (member === undefined) return undefined
1221
+ return member.type === 'ObjectProperty' ? member.value : null
1222
+ }
1223
+
1224
+ /** A `this` anywhere below `node`: an accessor or a method of a literal can change the literal without naming it. */
1225
+ function mentionsThis(node: t.Node): boolean {
1226
+ let found = false
1227
+ walkNodes(node, inner => {
1228
+ if (inner.type === 'ThisExpression') found = true
1229
+ })
1230
+ return found
1231
+ }
1232
+
1233
+ /** A module specifier that may be the content config itself, whatever directory it is given from. */
1234
+ const CONTENT_CONFIG_SPECIFIER = /(?:^|\/)content(?:\.|\/)config(?:\.[cm]?[jt]s)?$/
1235
+
1236
+ /** Does the file import a content config, which may be itself? What it exports can then be changed through the import. */
1237
+ function importsContentConfig(ast: t.File): boolean {
1238
+ let found = false
1239
+ walkNodes(ast, node => {
1240
+ const source = node.type === 'ImportDeclaration' || node.type === 'ExportNamedDeclaration'
1241
+ ? node.source
1242
+ : node.type === 'CallExpression' && node.callee.type === 'Import'
1243
+ ? node.arguments[0]
1244
+ : undefined
1245
+ if (source?.type === 'StringLiteral' && CONTENT_CONFIG_SPECIFIER.test(source.value)) found = true
1246
+ })
1247
+ return found
1248
+ }
1249
+
1250
+ /** The loader facts of a {@link DeclaredCollection}, read off the value its `collections` key holds. */
1251
+ function readDeclaredLoader(value: t.Node, bindings: Bindings, trusted: Set<string>): Omit<DeclaredCollection, 'name'> {
1252
+ const isCallOf = (node: t.Node, names: string[]): node is t.CallExpression & { callee: t.Identifier } =>
1253
+ node.type === 'CallExpression' && node.callee.type === 'Identifier' && names.includes(node.callee.name) && trusted.has(node.callee.name)
1254
+
1255
+ const declaration = resolveExpression(value, bindings)
1256
+ if (!isCallOf(declaration, ['defineCollection', 'defineCmsCollection']) || !declaration.arguments[0]) return {}
1257
+ const options = resolveExpression(declaration.arguments[0], bindings)
1258
+ if (options.type !== 'ObjectExpression' || mentionsThis(options)) return {}
1259
+
1260
+ // The last `loader` is the one that counts. A spread or a key that cannot be read after it
1261
+ // may replace it, and a `__proto__` may supply one where the literal names none.
1262
+ const lastLoader = options.properties.findLastIndex(prop => staticKeyName(prop) === 'loader')
1263
+ const mayBeReplaced = options.properties.some((prop, index) => {
1264
+ const key = staticKeyName(prop)
1265
+ return key === '__proto__' || (key === null && index > lastLoader)
1266
+ })
1267
+ if (mayBeReplaced) return {}
1268
+ const loader = literalMember(options, 'loader')
1269
+ if (loader === undefined) return { noLoader: true }
1270
+ if (loader === null) return {}
1271
+
1272
+ const facts: Omit<DeclaredCollection, 'name'> = { hasLoader: true }
1273
+ const call = resolveExpression(loader, bindings)
1274
+ if (!isCallOf(call, ['glob', 'file']) || !call.arguments[0]) return facts
1275
+ if (call.callee.name === 'file') {
1276
+ const file = extractStaticString(call.arguments[0], bindings)
1277
+ if (file !== undefined) facts.loaderFile = file
1278
+ return facts
1279
+ }
1280
+
1281
+ const globOptions = resolveExpression(call.arguments[0], bindings)
1282
+ // A spread, a key that cannot be read or a `__proto__` may supply either option, so no literal next to one can be trusted.
1283
+ if (globOptions.type !== 'ObjectExpression' || !isPlainLiteralObject(globOptions) || mentionsThis(globOptions)) return facts
1284
+ const base = literalMember(globOptions, 'base')
1285
+ const pattern = literalMember(globOptions, 'pattern')
1286
+ // Without a `base`, Astro's glob loads from the project root.
1287
+ if (base === undefined) facts.loaderBase = '.'
1288
+ else if (base !== null) {
1289
+ const literal = extractStaticString(base, bindings)
1290
+ if (literal !== undefined) facts.loaderBase = literal
1291
+ }
1292
+ if (!pattern) return facts
1293
+ const literal = extractStaticString(pattern, bindings)
1294
+ if (literal !== undefined) {
1295
+ facts.loaderPattern = literal
1296
+ return facts
1297
+ }
1298
+ // A list of patterns is a union with its `!` members taken out again.
1299
+ const list = resolveExpression(pattern, bindings)
1300
+ const patterns = list.type === 'ArrayExpression' ? list.elements.map(element => element ? extractStaticString(element, bindings) : undefined) : []
1301
+ if (patterns.length > 0 && patterns.every(one => one !== undefined)) facts.loaderPatterns = patterns
1302
+ return facts
1303
+ }
1304
+
702
1305
  /**
703
1306
  * Unwrap a `schema:` value down to the top-level (z|n).object({ ... }) ObjectExpression.
704
1307
  * Handles direct calls, the Astro callback form `({ image }) => z.object({...})`,