@nuasite/cms-core 0.52.0 → 0.54.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 (40) hide show
  1. package/dist/types/asset-paths.d.ts +28 -0
  2. package/dist/types/asset-paths.d.ts.map +1 -0
  3. package/dist/types/check-entries.d.ts +50 -0
  4. package/dist/types/check-entries.d.ts.map +1 -0
  5. package/dist/types/check-live.d.ts +25 -0
  6. package/dist/types/check-live.d.ts.map +1 -0
  7. package/dist/types/check-shape.d.ts +28 -0
  8. package/dist/types/check-shape.d.ts.map +1 -0
  9. package/dist/types/check-write.d.ts +35 -0
  10. package/dist/types/check-write.d.ts.map +1 -0
  11. package/dist/types/check.d.ts +21 -1
  12. package/dist/types/check.d.ts.map +1 -1
  13. package/dist/types/content-config-ast.d.ts +2 -0
  14. package/dist/types/content-config-ast.d.ts.map +1 -1
  15. package/dist/types/editor-write-model.d.ts +48 -0
  16. package/dist/types/editor-write-model.d.ts.map +1 -0
  17. package/dist/types/handlers/entry-ops.d.ts.map +1 -1
  18. package/dist/types/index.d.ts +9 -1
  19. package/dist/types/index.d.ts.map +1 -1
  20. package/dist/types/schema-port.d.ts +43 -0
  21. package/dist/types/schema-port.d.ts.map +1 -0
  22. package/dist/types/schema-probe.d.ts +53 -0
  23. package/dist/types/schema-probe.d.ts.map +1 -0
  24. package/dist/types/shared.d.ts +3 -10
  25. package/dist/types/shared.d.ts.map +1 -1
  26. package/dist/types/tsconfig.tsbuildinfo +1 -1
  27. package/package.json +7 -2
  28. package/src/asset-paths.ts +54 -0
  29. package/src/check-entries.ts +120 -0
  30. package/src/check-live.ts +61 -0
  31. package/src/check-shape.ts +137 -0
  32. package/src/check-write.ts +280 -0
  33. package/src/check.ts +198 -63
  34. package/src/content-config-ast.ts +196 -17
  35. package/src/editor-write-model.ts +82 -0
  36. package/src/handlers/entry-ops.ts +42 -64
  37. package/src/index.ts +30 -1
  38. package/src/schema-port.ts +46 -0
  39. package/src/schema-probe.ts +133 -0
  40. package/src/shared.ts +3 -19
package/src/check.ts CHANGED
@@ -12,10 +12,15 @@
12
12
  * `astro sync` already provides.
13
13
  */
14
14
 
15
- import path from 'node:path'
16
- import yaml from 'yaml'
15
+ import { assetBaseDir, resolveAssetCandidates } from './asset-paths'
16
+ import { isPlainObject, loadCollections, type LoadedEntry } from './check-entries'
17
+ import { checkAgainstSchemas } from './check-live'
18
+ import { checkFieldShapes } from './check-shape'
19
+ import { checkEditorWrites } from './check-write'
17
20
  import { parseContentConfig, type ParsedCollection, type ParsedField } from './content-config-ast'
18
21
  import type { CmsFileSystem } from './fs/types'
22
+ import { type LiveSchemas, schemaFor } from './schema-port'
23
+ import { computePathnameFromSpec } from './shared'
19
24
 
20
25
  export type CheckSeverity = 'error' | 'warning'
21
26
 
@@ -25,8 +30,19 @@ export interface CheckFinding {
25
30
  code: string
26
31
  /** Root-relative path of the file the finding is about. */
27
32
  file: string
33
+ /** 1-based position in that file, when the underlying parser reports one. */
34
+ line?: number
35
+ column?: number
28
36
  field?: string
29
37
  message: string
38
+ /**
39
+ * What to change to make the finding go away, when there is a specific answer.
40
+ *
41
+ * Separate from `message` because it is a different kind of claim: the message states
42
+ * what the checker observed, the hint proposes an edit it cannot verify. Rules add one
43
+ * only where the remedy follows from the evidence — never as a restatement.
44
+ */
45
+ hint?: string
30
46
  }
31
47
 
32
48
  export interface CheckReport {
@@ -35,14 +51,6 @@ export interface CheckReport {
35
51
  entries: number
36
52
  }
37
53
 
38
- const DATA_EXTENSIONS = new Set(['.json', '.yaml', '.yml'])
39
-
40
- /** `./content/articles` and `content/articles/` both mean the same directory. */
41
- const normalizeBase = (base: string): string => path.normalize(base).replace(/^\.\//, '').replace(/\/+$/, '')
42
-
43
- /** The id Astro's `glob()` loader derives from a file, and therefore what a `reference()` must hold. */
44
- const entryStem = (file: string): string => path.basename(file).replace(/\.(md|mdx|json|ya?ml)$/, '')
45
-
46
54
  const typeName = (value: unknown): string => {
47
55
  if (value === null) return 'null'
48
56
  if (Array.isArray(value)) return 'array'
@@ -50,10 +58,6 @@ const typeName = (value: unknown): string => {
50
58
  return typeof value
51
59
  }
52
60
 
53
- function isPlainObject(value: unknown): value is Record<string, unknown> {
54
- return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
55
- }
56
-
57
61
  /** Whether a value satisfies a field's declared type. `null` means "no opinion". */
58
62
  function typeMismatch(field: ParsedField, value: unknown): string | null {
59
63
  switch (field.type) {
@@ -94,36 +98,124 @@ function typeMismatch(field: ParsedField, value: unknown): string | null {
94
98
  }
95
99
  }
96
100
 
97
- async function collectEntryFiles(fs: CmsFileSystem, collection: ParsedCollection, base: string): Promise<string[]> {
98
- const pattern = collection.loaderPattern ?? '**/*.{md,mdx,json,yaml,yml}'
99
- const files = await fs.glob(`${base}/${pattern}`)
100
- return files.filter(file => !path.basename(file).startsWith('_')).sort()
101
+ /**
102
+ * The on-disk path an `image` value names, or `null` when it names none: the s3/contember
103
+ * media adapters store absolute URLs, and a `~/…`/`@…` value is a Vite alias, which Astro
104
+ * hands to Vite's resolver (see `astro/src/content/utils.ts`) and this cannot follow.
105
+ * A cache-busting `?v=2`/`#frag` is trimmed off rather than discarding the whole value.
106
+ */
107
+ function projectAssetPath(value: string): string | null {
108
+ if (value === '' || value.startsWith('//')) return null
109
+ // A scheme — `https:`, `data:`, `file:`.
110
+ if (/^[a-z][a-z\d+\-.]*:/i.test(value)) return null
111
+ // A Vite alias or a `#imports` subpath — an import specifier, not a path.
112
+ if (/^[~@#]/.test(value)) return null
113
+ const withoutQuery = value.split(/[?#]/)[0] ?? ''
114
+ return withoutQuery === '' ? null : withoutQuery
101
115
  }
102
116
 
103
- function parseEntry(file: string, raw: string): { frontmatter: Record<string, unknown> } | { error: string } {
104
- const extension = path.extname(file)
105
- if (DATA_EXTENSIONS.has(extension)) {
106
- try {
107
- const parsed: unknown = extension === '.json' ? JSON.parse(raw) : yaml.parse(raw)
108
- // A data collection file may legitimately hold an array of entries; nothing to field-check then.
109
- return { frontmatter: isPlainObject(parsed) ? parsed : {} }
110
- } catch (error) {
111
- return { error: error instanceof Error ? error.message.split('\n')[0]! : String(error) }
117
+ /**
118
+ * Report `image` values pointing at no file, walking nested objects and object-array items
119
+ * the same way the field data is shaped. Resolution goes through `resolveAssetCandidates`
120
+ * with the entry's own directory, which is what `getEntryAsset` serves a relative value
121
+ * from — the check therefore looks exactly where serving the asset looks.
122
+ */
123
+ async function checkAssets(
124
+ fs: CmsFileSystem,
125
+ fields: ParsedField[],
126
+ data: Record<string, unknown>,
127
+ file: string,
128
+ prefix: string,
129
+ findings: CheckFinding[],
130
+ ): Promise<void> {
131
+ for (const field of fields) {
132
+ const value = data[field.name]
133
+ if (value === undefined || value === null) continue
134
+ const label = prefix === '' ? field.name : `${prefix}.${field.name}`
135
+
136
+ if (field.type === 'object' && field.fields && isPlainObject(value)) {
137
+ await checkAssets(fs, field.fields, value, file, label, findings)
138
+ continue
139
+ }
140
+
141
+ if (field.type === 'array' && field.itemType === 'object' && field.fields && Array.isArray(value)) {
142
+ for (const [index, item] of value.entries()) {
143
+ if (isPlainObject(item)) await checkAssets(fs, field.fields, item, file, `${label}[${index}]`, findings)
144
+ }
145
+ continue
146
+ }
147
+
148
+ if (field.type !== 'image' || typeof value !== 'string') continue
149
+ const assetPath = projectAssetPath(value)
150
+ if (assetPath === null) continue
151
+
152
+ const candidates = resolveAssetCandidates(assetBaseDir(file), assetPath)
153
+ // No candidates left means the path climbs above the project root — outside what this can judge.
154
+ if (candidates.length === 0) continue
155
+
156
+ let found = false
157
+ for (const candidate of candidates) {
158
+ if (await fs.exists(candidate)) {
159
+ found = true
160
+ break
161
+ }
112
162
  }
163
+ if (found) continue
164
+
165
+ findings.push({
166
+ severity: 'warning',
167
+ code: 'entry/missing-asset',
168
+ file,
169
+ field: label,
170
+ message: `${label}: "${value}" points at no file (tried ${candidates.join(', ')}).`,
171
+ })
113
172
  }
173
+ }
114
174
 
115
- const trimmed = raw.trimStart()
116
- if (!trimmed.startsWith('---')) return { frontmatter: {} }
117
- const lines = trimmed.split('\n')
118
- const end = lines.findIndex((line, index) => index > 0 && line.trimEnd() === '---')
119
- if (end === -1) return { error: 'frontmatter is never closed (missing the second `---`)' }
120
-
121
- try {
122
- const parsed: unknown = yaml.parse(lines.slice(1, end).join('\n').trim())
123
- return { frontmatter: isPlainObject(parsed) ? parsed : {} }
124
- } catch (error) {
125
- return { error: error instanceof Error ? error.message.split('\n')[0]! : String(error) }
175
+ /**
176
+ * Entries whose declarative `cms.pathname` rule resolves to a URL another entry already took —
177
+ * the later ones render over the first, so only one of them is reachable. A warning, not an
178
+ * error: this builds green and only goes wrong at render time.
179
+ *
180
+ * `collection-scanner.ts` warns about the same thing on the dev-server path; the duplication
181
+ * is deliberate, because this check must stay scanner-free.
182
+ */
183
+ function pathnameCollisions(collection: ParsedCollection, entries: LoadedEntry[]): CheckFinding[] {
184
+ // `fragment` needs no guard here — parsing already drops the `pathname` of a fragment collection.
185
+ if (!collection.pathname) return []
186
+
187
+ const findings: CheckFinding[] = []
188
+ const firstAt = new Map<string, LoadedEntry>()
189
+ for (const entry of entries) {
190
+ if (!entry.frontmatter) continue
191
+ const pathname = computePathnameFromSpec(collection.pathname, entry.frontmatter)
192
+ // An unresolved spec (a missing/uncoercible field) yields no URL, so there is nothing to collide.
193
+ if (pathname === undefined) continue
194
+
195
+ const first = firstAt.get(pathname)
196
+ if (!first) {
197
+ firstAt.set(pathname, entry)
198
+ continue
199
+ }
200
+ findings.push({
201
+ severity: 'warning',
202
+ code: 'entry/pathname-collision',
203
+ file: entry.file,
204
+ field: collection.name,
205
+ // The path, not the stem: bundle entries are all named `index`.
206
+ message: `The pathname rule maps this entry and ${first.file} to ${pathname} — they collide on one page.`,
207
+ })
126
208
  }
209
+ return findings
210
+ }
211
+
212
+ export interface CheckContentOptions {
213
+ /**
214
+ * The project's real collection schemas. Given these, the check also reports what the
215
+ * build would reject and what the editor's next write would break — see `check-live.ts`
216
+ * and `check-write.ts`. Absent, only the AST/data rules below run.
217
+ */
218
+ schemas?: LiveSchemas
127
219
  }
128
220
 
129
221
  /**
@@ -132,7 +224,7 @@ function parseEntry(file: string, raw: string): { frontmatter: Record<string, un
132
224
  * Errors are things that fail the build; warnings are things that pass it and then go wrong
133
225
  * at render time (a reference pointing at nothing is the documented example).
134
226
  */
135
- export async function checkContent(fs: CmsFileSystem): Promise<CheckReport> {
227
+ export async function checkContent(fs: CmsFileSystem, options: CheckContentOptions = {}): Promise<CheckReport> {
136
228
  const findings: CheckFinding[] = []
137
229
  const config = await parseContentConfig(fs, new Map())
138
230
 
@@ -146,36 +238,29 @@ export async function checkContent(fs: CmsFileSystem): Promise<CheckReport> {
146
238
  return { findings, collections: 0, entries: 0 }
147
239
  }
148
240
 
149
- // Resolve every collection's files first: a reference can point at a collection checked later.
150
- const bases = new Map<string, string>()
151
- const files = new Map<string, string[]>()
241
+ // Read everything first: a reference can point at a collection checked later.
242
+ const collections = await loadCollections(fs, config)
152
243
  const stems = new Map<string, Set<string>>()
153
244
 
154
- for (const [name, collection] of config) {
155
- const base = normalizeBase(collection.loaderBase ?? `src/content/${name}`)
156
- bases.set(name, base)
157
- if (!(await fs.exists(base))) {
245
+ for (const [name, loaded] of collections) {
246
+ stems.set(name, new Set(loaded.entries.map(entry => entry.stem)))
247
+ if (!loaded.exists) {
158
248
  findings.push({
159
249
  severity: 'error',
160
250
  code: 'config/missing-dir',
161
251
  file: 'src/content.config.ts',
162
252
  field: name,
163
- message: `Collection "${name}" loads from ${base}/, which does not exist.`,
253
+ message: `Collection "${name}" loads from ${loaded.base}/, which does not exist.`,
164
254
  })
165
- files.set(name, [])
166
- stems.set(name, new Set())
167
255
  continue
168
256
  }
169
- const collectionFiles = await collectEntryFiles(fs, collection, base)
170
- files.set(name, collectionFiles)
171
- stems.set(name, new Set(collectionFiles.map(entryStem)))
172
- if (collectionFiles.length === 0) {
257
+ if (loaded.entries.length === 0) {
173
258
  findings.push({
174
259
  severity: 'warning',
175
260
  code: 'config/empty-collection',
176
- file: base,
261
+ file: loaded.base,
177
262
  field: name,
178
- message: `Collection "${name}" matched no entries under ${base}/.`,
263
+ message: `Collection "${name}" matched no entries under ${loaded.base}/.`,
179
264
  })
180
265
  }
181
266
  }
@@ -185,20 +270,35 @@ export async function checkContent(fs: CmsFileSystem): Promise<CheckReport> {
185
270
  for (const [name, collection] of config) {
186
271
  // A bare `reference()` carries no field type, so it has to be kept explicitly.
187
272
  const typedFields = collection.fields.filter(field => field.type !== undefined || field.required || field.reference)
273
+ const declared = new Set(collection.fields.map(field => field.name))
274
+ const loadedEntries = collections.get(name)?.entries ?? []
275
+ /**
276
+ * Whether the real schema is available to judge this collection's entries.
277
+ *
278
+ * When it is, `entry/missing-required` and `entry/field-type` stand down: both infer a rule
279
+ * from the config's *surface* and are wrong wherever the surface and the schema differ.
280
+ * `required` is only "no `.optional()` was visible" — a field schema wrapped in a helper call
281
+ * hides it. And a type name does not fix a type: `n.date()` is
282
+ * `z.preprocess(toISODate, z.string())` with no validation, so `date: ''` is legal content
283
+ * that this rule called a broken date. Both produced build-failing errors on production sites
284
+ * that build. `entry/schema-rejected` answers properly, and `cms/required-drift` reports the
285
+ * disagreement itself, once, against the config rather than once per entry.
286
+ */
287
+ const schemaJudgesEntries = options.schemas !== undefined && schemaFor(options.schemas, name) !== undefined
188
288
 
189
- for (const file of files.get(name) ?? []) {
289
+ for (const entry of loadedEntries) {
190
290
  entries++
191
- const parsed = parseEntry(file, await fs.readFile(file))
192
- if ('error' in parsed) {
193
- findings.push({ severity: 'error', code: 'entry/syntax', file, message: `Frontmatter does not parse: ${parsed.error}` })
291
+ const file = entry.file
292
+ if (entry.frontmatter === undefined) {
293
+ findings.push({ severity: 'error', code: 'entry/syntax', file, message: `Frontmatter does not parse: ${entry.parseError}` })
194
294
  continue
195
295
  }
196
296
 
197
297
  for (const field of typedFields) {
198
- const value = parsed.frontmatter[field.name]
298
+ const value = entry.frontmatter[field.name]
199
299
 
200
300
  if (value === undefined || value === null) {
201
- if (field.required) {
301
+ if (field.required && !schemaJudgesEntries) {
202
302
  findings.push({
203
303
  severity: 'error',
204
304
  code: 'entry/missing-required',
@@ -210,7 +310,7 @@ export async function checkContent(fs: CmsFileSystem): Promise<CheckReport> {
210
310
  continue
211
311
  }
212
312
 
213
- const mismatch = field.type === undefined ? null : typeMismatch(field, value)
313
+ const mismatch = field.type === undefined || schemaJudgesEntries ? null : typeMismatch(field, value)
214
314
  if (mismatch) {
215
315
  findings.push({ severity: 'error', code: 'entry/field-type', file, field: field.name, message: `${field.name}: ${mismatch}` })
216
316
  continue
@@ -234,7 +334,34 @@ export async function checkContent(fs: CmsFileSystem): Promise<CheckReport> {
234
334
  })
235
335
  }
236
336
  }
337
+
338
+ await checkAssets(fs, collection.fields, entry.frontmatter, file, '', findings)
339
+
340
+ // Only a field list known to be complete can call a key unknown. It is short when the
341
+ // schema never unwrapped at all (renamed import, an unsupported wrapper) and when a
342
+ // spread or computed key was skipped — warning on every key of a valid project is the
343
+ // false positive this check exists to avoid.
344
+ if (declared.size > 0 && !collection.partialFields) {
345
+ for (const key of Object.keys(entry.frontmatter)) {
346
+ if (declared.has(key)) continue
347
+ findings.push({
348
+ severity: 'warning',
349
+ code: 'entry/unknown-key',
350
+ file,
351
+ field: key,
352
+ // Astro's schema strips what it does not declare, so the value is written and then never read.
353
+ message: `"${key}" is not a field of "${name}" — nothing reads it.`,
354
+ })
355
+ }
356
+ }
237
357
  }
358
+
359
+ findings.push(...pathnameCollisions(collection, loadedEntries))
360
+ }
361
+
362
+ if (options.schemas) {
363
+ const input = { config, collections, schemas: options.schemas }
364
+ findings.push(...await checkAgainstSchemas(input), ...await checkEditorWrites(input), ...await checkFieldShapes(input))
238
365
  }
239
366
 
240
367
  return { findings, collections: config.size, entries }
@@ -254,8 +381,16 @@ export function formatCheckReport(report: CheckReport): string {
254
381
  const lines: string[] = []
255
382
  for (const [file, findings] of byFile) {
256
383
  lines.push(file)
384
+ // One remedy usually covers a run of findings — five missing fields in one collection get the
385
+ // same sentence. Printed once per run, and reset per file so a block never opens without it.
386
+ let lastHint: string | undefined
257
387
  for (const finding of findings) {
258
- lines.push(` ${finding.severity === 'error' ? 'error' : 'warn '} ${finding.message} [${finding.code}]`)
388
+ // eslint's shape: position, severity, message, rule. Familiar, and greppable by column.
389
+ const at = finding.line === undefined ? '' : `${finding.line}:${finding.column ?? 0}`
390
+ lines.push(` ${at.padEnd(8)}${(finding.severity === 'error' ? 'error' : 'warn').padEnd(6)} ${finding.message} [${finding.code}]`)
391
+ // Indented under its finding, so the proposal never reads as another observation.
392
+ if (finding.hint !== undefined && finding.hint !== lastHint) lines.push(` ${' '.repeat(14)}→ ${finding.hint}`)
393
+ lastHint = finding.hint
259
394
  }
260
395
  }
261
396
  return lines.join('\n')
@@ -48,6 +48,8 @@ export interface ParsedFieldLayout {
48
48
  export interface ParsedCollection {
49
49
  name: string
50
50
  fields: ParsedField[]
51
+ /** `fields` is known to be incomplete — a spread or computed key in the schema was skipped. */
52
+ partialFields?: true
51
53
  loaderPattern?: string
52
54
  loaderBase?: string
53
55
  /** Declarative form layout from a `defineCmsCollection({ cms: { … } })` block. */
@@ -103,19 +105,113 @@ type Bindings = Map<string, t.Node>
103
105
 
104
106
  /**
105
107
  * Follow `Identifier` references through same-file `const` bindings until reaching
106
- * a non-Identifier node. Cycle-safe via the visited set. Returns the original node
107
- * unchanged when the identifier is unbound or already visited.
108
+ * a non-Identifier node, seeing through type-only wrappers (`as const`, `satisfies`,
109
+ * `!`) on the way — they change nothing about the value a schema declares. Cycle-safe
110
+ * via the visited set. Returns the node it stopped on — the peeled original when the
111
+ * identifier is unbound or already visited.
108
112
  */
109
113
  function resolveExpression(node: t.Node, bindings: Bindings, visited: Set<string> = new Set()): t.Node {
110
114
  let current: t.Node = node
111
- while (current.type === 'Identifier') {
115
+ for (;;) {
116
+ if (
117
+ current.type === 'TSAsExpression'
118
+ || current.type === 'TSSatisfiesExpression'
119
+ || current.type === 'TSNonNullExpression'
120
+ || current.type === 'TSTypeAssertion'
121
+ ) {
122
+ current = current.expression
123
+ continue
124
+ }
125
+ if (current.type !== 'Identifier') return current
112
126
  if (visited.has(current.name)) return current
113
127
  visited.add(current.name)
114
128
  const next = bindings.get(current.name)
115
129
  if (!next) return current
116
130
  current = next
117
131
  }
118
- return current
132
+ }
133
+
134
+ function isAstNode(value: unknown): value is t.Node {
135
+ return typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string'
136
+ }
137
+
138
+ /** Visit `node` and everything beneath it, finding children by shape — no @babel/traverse dependency. */
139
+ function walkNodes(node: t.Node, visit: (n: t.Node) => void): void {
140
+ visit(node)
141
+ const children: unknown[] = Object.values(node)
142
+ for (const child of children) {
143
+ if (Array.isArray(child)) {
144
+ for (const item of child) {
145
+ if (isAstNode(item)) walkNodes(item, visit)
146
+ }
147
+ } else if (isAstNode(child)) {
148
+ walkNodes(child, visit)
149
+ }
150
+ }
151
+ }
152
+
153
+ /** Record every name a binding construct introduces, destructuring patterns included. */
154
+ function declaredPatternNames(node: t.Node, record: (name: string) => void): void {
155
+ switch (node.type) {
156
+ case 'Identifier':
157
+ record(node.name)
158
+ return
159
+ case 'ObjectPattern':
160
+ for (const prop of node.properties) declaredPatternNames(prop.type === 'RestElement' ? prop.argument : prop.value, record)
161
+ return
162
+ case 'ArrayPattern':
163
+ for (const el of node.elements) {
164
+ if (el) declaredPatternNames(el, record)
165
+ }
166
+ return
167
+ case 'AssignmentPattern':
168
+ declaredPatternNames(node.left, record)
169
+ return
170
+ case 'RestElement':
171
+ declaredPatternNames(node.argument, record)
172
+ return
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Names the file declares more than once, anywhere.
178
+ *
179
+ * `bindings` is module-scope only, so a same-named local — a `const` inside the schema
180
+ * callback, a parameter — is invisible to it and an identifier would resolve to the
181
+ * module-level declaration instead: the wrong option list, the wrong type, the wrong
182
+ * `required` flag. Modelling scopes properly is a bigger job than this parser wants, so
183
+ * a name declared twice is simply not resolved and the field degrades as it did before.
184
+ */
185
+ function shadowedNames(ast: t.File): Set<string> {
186
+ const seen = new Set<string>()
187
+ const shadowed = new Set<string>()
188
+ const record = (name: string): void => {
189
+ if (seen.has(name)) shadowed.add(name)
190
+ seen.add(name)
191
+ }
192
+
193
+ walkNodes(ast, node => {
194
+ switch (node.type) {
195
+ case 'VariableDeclarator':
196
+ declaredPatternNames(node.id, record)
197
+ return
198
+ case 'FunctionDeclaration':
199
+ case 'FunctionExpression':
200
+ case 'ArrowFunctionExpression':
201
+ for (const param of node.params) declaredPatternNames(param, record)
202
+ if (node.type !== 'ArrowFunctionExpression' && node.id) record(node.id.name)
203
+ return
204
+ case 'ClassDeclaration':
205
+ if (node.id) record(node.id.name)
206
+ return
207
+ case 'ImportSpecifier':
208
+ case 'ImportDefaultSpecifier':
209
+ case 'ImportNamespaceSpecifier':
210
+ record(node.local.name)
211
+ return
212
+ }
213
+ })
214
+ return shadowed
119
215
  }
120
216
 
121
217
  /**
@@ -219,6 +315,10 @@ export function parseConfigSource(source: string, _sourcePath?: string): ParsedC
219
315
  }
220
316
  }
221
317
 
318
+ // A name the file declares twice cannot be resolved to one binding without a scope
319
+ // model, so drop it and let the fields that mention it stay untyped.
320
+ for (const name of shadowedNames(ast)) bindings.delete(name)
321
+
222
322
  // Unify both styles: inline `name: defineCollection({...})` and the
223
323
  // `const x = defineCollection({...}); collections = { name: x }` reference form.
224
324
  const collectionObjects = new Map<string, t.ObjectExpression>(inlineCollections)
@@ -301,6 +401,7 @@ export function parseConfigSource(source: string, _sourcePath?: string): ParsedC
301
401
  result.set(collectionName, {
302
402
  name: collectionName,
303
403
  fields: parseSchemaFields(schemaObject, bindings),
404
+ ...(hasSkippedMembers(schemaObject) ? { partialFields: true as const } : {}),
304
405
  loaderPattern,
305
406
  loaderBase,
306
407
  layout,
@@ -361,6 +462,23 @@ function parseLayoutSection(node: t.Node): CollectionLayoutSection | null {
361
462
  return collapsed ? { title, fields, collapsed } : { title, fields }
362
463
  }
363
464
 
465
+ /**
466
+ * The complete option list of an `enum([…])` array, or null when any member is unreadable.
467
+ *
468
+ * All-or-nothing on purpose: these options become a *closed* set downstream, so reading
469
+ * `[...BASE, 'blog']` as just `['blog']` would lock the field to the one member we
470
+ * understood — every existing entry invalid, and the editor refusing to write the values
471
+ * the schema does allow. A list we cannot read whole leaves the field open instead.
472
+ */
473
+ function readEnumOptions(node: t.ArrayExpression): string[] | null {
474
+ const options: string[] = []
475
+ for (const el of node.elements) {
476
+ if (el?.type !== 'StringLiteral') return null
477
+ options.push(el.value)
478
+ }
479
+ return options.length > 0 ? options : null
480
+ }
481
+
364
482
  /** Collect string-literal elements from an array expression. */
365
483
  function stringArray(node: t.ArrayExpression): string[] {
366
484
  const out: string[] = []
@@ -583,6 +701,18 @@ function parseSchemaFields(schemaObject: t.ObjectExpression, bindings: Bindings)
583
701
  return fields
584
702
  }
585
703
 
704
+ /**
705
+ * Whether members of the schema object were skipped, leaving the field list short.
706
+ *
707
+ * A spread (`n.object({ ...base, order: n.number() })`) or a computed key contributes real
708
+ * fields that never make it into `fields`. The difference matters to anything that treats
709
+ * the list as exhaustive: an incomplete list is not the same as an empty one, and reading
710
+ * it as complete turns a legitimate config into a page of warnings.
711
+ */
712
+ function hasSkippedMembers(schemaObject: t.ObjectExpression): boolean {
713
+ return schemaObject.properties.some(prop => prop.type !== 'ObjectProperty' || !propertyKeyName(prop.key))
714
+ }
715
+
586
716
  /**
587
717
  * Walk a field's value expression. Each layer is either a wrapper method call
588
718
  * (`.optional()`, `.default()`, `.nullable()`, `.nullish()`, `.orderBy(...)`)
@@ -592,7 +722,7 @@ function parseSchemaFields(schemaObject: t.ObjectExpression, bindings: Bindings)
592
722
  * patterns like `cs: TestimonialTranslation` and `en: TestimonialTranslation.optional()`
593
723
  * are followed back to their defining call.
594
724
  */
595
- function analyzeFieldExpression(node: t.Node, field: ParsedField, bindings: Bindings): void {
725
+ function analyzeFieldExpression(node: t.Node, field: ParsedField, bindings: Bindings, helpers: Set<string> = new Set()): void {
596
726
  let current: t.Node | null = resolveExpression(node, bindings)
597
727
  while (current) {
598
728
  if (current.type !== 'CallExpression') return
@@ -602,10 +732,34 @@ function analyzeFieldExpression(node: t.Node, field: ParsedField, bindings: Bind
602
732
  return
603
733
  }
604
734
 
735
+ // `tag: optionalTag()` — continue into what the helper returns, so both its type and
736
+ // the `.optional()` it hides reach the field.
737
+ if (current.callee.type === 'Identifier') {
738
+ const returned = sameFileHelperReturn(current, bindings, helpers)
739
+ if (returned) analyzeFieldExpression(returned, field, bindings, helpers)
740
+ return
741
+ }
742
+
605
743
  if (current.callee.type !== 'MemberExpression') return
606
744
  const property = current.callee.property
607
745
  const methodName = property.type === 'Identifier' ? property.name : ''
608
746
 
747
+ // `n.text().array()` — the postfix spelling of `n.array(n.text())`. Without this the
748
+ // walk steps into the receiver and stamps the *element* type on the list itself.
749
+ if (methodName === 'array') {
750
+ const item: ParsedField = { name: '__item__', required: true }
751
+ analyzeFieldExpression(current.callee.object, item, bindings, helpers)
752
+ // Keep an array of references flat, exactly as the `n.array(reference())` branch does.
753
+ if (item.reference) {
754
+ field.reference = { target: item.reference.target, isArray: true }
755
+ return
756
+ }
757
+ field.type = 'array'
758
+ if (item.type) field.itemType = item.type
759
+ if (item.fields) field.fields = item.fields
760
+ return
761
+ }
762
+
609
763
  if (WRAPPER_METHODS.has(methodName)) {
610
764
  field.required = false
611
765
  } else if (methodName === 'orderBy') {
@@ -618,6 +772,28 @@ function analyzeFieldExpression(node: t.Node, field: ParsedField, bindings: Bind
618
772
  }
619
773
  }
620
774
 
775
+ /**
776
+ * The expression a same-file zero-argument helper returns, for field values written as
777
+ * `tag: optionalTag()`. Cycle-safe via `seen`. A helper taking arguments, or one imported
778
+ * from another module, resolves to null — its body is not here to read, and guessing at a
779
+ * type the schema may not declare is worse than leaving the field untyped.
780
+ */
781
+ function sameFileHelperReturn(call: t.CallExpression, bindings: Bindings, seen: Set<string>): t.Node | null {
782
+ if (call.callee.type !== 'Identifier' || call.arguments.length > 0) return null
783
+ if (seen.has(call.callee.name)) return null
784
+ seen.add(call.callee.name)
785
+
786
+ const fn = resolveExpression(call.callee, bindings)
787
+ if (fn.type !== 'ArrowFunctionExpression' && fn.type !== 'FunctionExpression') return null
788
+ if (fn.params.length > 0) return null
789
+
790
+ if (fn.body.type !== 'BlockStatement') return fn.body
791
+ for (const stmt of fn.body.body) {
792
+ if (stmt.type === 'ReturnStatement' && stmt.argument) return stmt.argument
793
+ }
794
+ return null
795
+ }
796
+
621
797
  /**
622
798
  * A "base call" is the innermost call that defines the field's type: a Zod/n
623
799
  * helper invocation or a bare `image()` / `reference()` from a callback param.
@@ -660,8 +836,9 @@ function analyzeBaseCall(node: t.CallExpression, field: ParsedField, bindings: B
660
836
  const fn = callee.property.name
661
837
 
662
838
  // n.image(), n.url(), n.text(...), etc. — semantic field types from @nuasite/cms.
663
- // FIELD_HELPER_TYPES gates to the helper subset (excludes boolean/select/array/object/
664
- // reference, which are inferred elsewhere); isFieldType narrows `fn` to FieldType.
839
+ // FIELD_HELPER_TYPES gates to the helper subset (excludes select/array/object/reference,
840
+ // inferred below, and boolean, which `z` declares the same way); isFieldType narrows
841
+ // `fn` to FieldType.
665
842
  if (ns === 'n' && FIELD_HELPER_TYPES.has(fn) && isFieldType(fn)) {
666
843
  field.type = fn
667
844
  const firstArg = node.arguments[0]
@@ -674,18 +851,20 @@ function analyzeBaseCall(node: t.CallExpression, field: ParsedField, bindings: B
674
851
  return
675
852
  }
676
853
 
854
+ // (z|n).boolean() → checkbox. Not in FIELD_HELPER_TYPES because that gate is `n`-only,
855
+ // and a plain `z.boolean()` declares the very same field.
856
+ if ((ns === 'z' || ns === 'n') && fn === 'boolean') {
857
+ field.type = 'boolean'
858
+ return
859
+ }
860
+
677
861
  // (z|n).enum([...]) → select with options
678
862
  if ((ns === 'z' || ns === 'n') && fn === 'enum') {
679
- const arg = node.arguments[0]
680
- if (arg?.type === 'ArrayExpression') {
681
- const options: string[] = []
682
- for (const el of arg.elements) {
683
- if (el?.type === 'StringLiteral') options.push(el.value)
684
- }
685
- if (options.length > 0) {
686
- field.type = 'select'
687
- field.options = options
688
- }
863
+ const arg = node.arguments[0] ? resolveExpression(node.arguments[0], bindings) : undefined
864
+ const options = arg?.type === 'ArrayExpression' ? readEnumOptions(arg) : null
865
+ if (options) {
866
+ field.type = 'select'
867
+ field.options = options
689
868
  }
690
869
  // `n.enum([…], { label, help, … })` — the value list takes the first argument, so
691
870
  // layout hints ride in the second one; every other marker carries them in the first.