@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
package/src/core.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  AddRedirectRequest,
3
3
  CollectionDefinition,
4
+ CollectionScanReport,
4
5
  ComponentDefinition,
5
6
  CreatePageRequest,
6
7
  DeletePageRequest,
@@ -14,7 +15,7 @@ import type {
14
15
  RedirectOperationResponse,
15
16
  UpdateRedirectRequest,
16
17
  } from '@nuasite/cms-types'
17
- import { scanCollections } from './collection-scanner'
18
+ import { collectionScanReport, scanCollections } from './collection-scanner'
18
19
  import { scanComponentDefinitions } from './component-registry'
19
20
  import { type ParseCache } from './content-config-ast'
20
21
  import type { CmsFileSystem } from './fs/types'
@@ -68,8 +69,22 @@ export interface CmsCoreOptions {
68
69
  */
69
70
  export interface CmsCore {
70
71
  // READ / SCAN
71
- /** Scan all content collections, returning their inferred definitions keyed by name. */
72
- scanCollections(): Promise<Record<string, CollectionDefinition>>
72
+ /**
73
+ * Scan all content collections, returning their inferred definitions keyed by name.
74
+ *
75
+ * The scan carries a report (see {@link CmsCore.collectionScanReport}) only when asked for
76
+ * `{ report: true }`. Building one costs a listing per declared collection, so it is paid
77
+ * only where it is read. A wrapper around this method has to pass `options` on: one that
78
+ * drops them leaves its caller without a report, which reads as "not reported".
79
+ */
80
+ scanCollections(options?: { report?: boolean }): Promise<Record<string, CollectionDefinition>>
81
+ /**
82
+ * What the scan that returned `collections` could not vouch for: pass the record
83
+ * `scanCollections()` resolved to. `undefined` when it has no report: read that as "not
84
+ * reported", never as "nothing unresolved". Optional, so a core built before the report
85
+ * existed is still a `CmsCore`.
86
+ */
87
+ collectionScanReport?(collections: Record<string, CollectionDefinition>): CollectionScanReport | undefined
73
88
  /** Resolve the Astro component definitions used for MDX import injection. */
74
89
  scanComponents(): Promise<Record<string, ComponentDefinition>>
75
90
  /** Read a single entry's frontmatter + body, or `null` when it does not exist. */
@@ -118,9 +133,10 @@ export function createCmsCore(fs: CmsFileSystem, opts: CmsCoreOptions = {}): Cms
118
133
  }
119
134
 
120
135
  return {
121
- scanCollections() {
122
- return scanCollections(fs, contentDir, parseCache)
136
+ scanCollections(options) {
137
+ return scanCollections(fs, contentDir, parseCache, { report: options?.report ?? false })
123
138
  },
139
+ collectionScanReport,
124
140
  scanComponents() {
125
141
  return scanComponentDefinitions(fs, componentDirs)
126
142
  },
package/src/fs/glob.ts CHANGED
@@ -1,3 +1,21 @@
1
+ /**
2
+ * A directory a glob had to read and could not. Kept apart from every other failure so a
3
+ * caller can report it as a finding and still let a bug (or a path traversal) surface.
4
+ */
5
+ export class UnreadableDirectoryError extends Error {
6
+ /** Root-relative, forward slashes; the root itself is `.`. */
7
+ readonly directory: string
8
+ /** The runtime's error code, e.g. `EACCES`. */
9
+ readonly code: string
10
+
11
+ constructor(directory: string, code: string, options?: ErrorOptions) {
12
+ super(`Cannot read directory "${directory}" (${code})`, options)
13
+ this.name = 'UnreadableDirectoryError'
14
+ this.directory = directory
15
+ this.code = code
16
+ }
17
+ }
18
+
1
19
  /** Convert a glob pattern (supports `*`, `**`, `?`, `{a,b}`) to an anchored RegExp. */
2
20
  export function globToRegExp(glob: string): RegExp {
3
21
  let re = ''
@@ -30,3 +48,24 @@ export function globToRegExp(glob: string): RegExp {
30
48
  }
31
49
  return new RegExp(`^${re}$`)
32
50
  }
51
+
52
+ /**
53
+ * Whether `glob` could match a file somewhere below the directory `dir` (both root-relative,
54
+ * forward slashes). Errs on the side of yes: only a directory that no path the pattern
55
+ * matches can run through is ruled out.
56
+ */
57
+ export function globMayMatchUnder(glob: string, dir: string): boolean {
58
+ // A brace that spans a slash does not split into segments; do not guess.
59
+ if (/\{[^}]*\//.test(glob)) return true
60
+ const segments = glob.split('/').filter(segment => segment !== '' && segment !== '.')
61
+ const dirs = dir.split('/').filter(segment => segment !== '' && segment !== '.')
62
+ const reaches = (i: number, j: number): boolean => {
63
+ // Inside `dir`: the pattern has to have a segment left for a file below it.
64
+ if (j === dirs.length) return i < segments.length
65
+ if (i >= segments.length) return false
66
+ // `**` runs through any number of directories.
67
+ if (segments[i]!.includes('**')) return true
68
+ return globToRegExp(segments[i]!).test(dirs[j]!) && reaches(i + 1, j + 1)
69
+ }
70
+ return reaches(0, 0)
71
+ }
package/src/fs/node-fs.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { Dirent } from 'node:fs'
2
2
  import fs from 'node:fs/promises'
3
3
  import path from 'node:path'
4
- import { globToRegExp } from './glob'
4
+ import { globMayMatchUnder, globToRegExp, UnreadableDirectoryError } from './glob'
5
5
  import type { CmsFileSystem } from './types'
6
6
 
7
7
  /**
@@ -29,21 +29,83 @@ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
29
29
  return error instanceof Error && 'code' in error
30
30
  }
31
31
 
32
- /** Recursively list files under `absDir`, returning forward-slash paths relative to `absRoot`. */
33
- async function walkFiles(absRoot: string, absDir: string): Promise<string[]> {
32
+ /** What one walk is after, and how far it may go. */
33
+ interface Walk {
34
+ absRoot: string
35
+ /** Whether a directory (root-relative) could hold anything the caller is after. */
36
+ mayHold: (dir: string) => boolean
37
+ /** Directories (root-relative) the caller does not want walked at all. */
38
+ skip: (dir: string) => boolean
39
+ /** Enter linked directories and list linked files, which the walk otherwise leaves out. */
40
+ followSymlinks: boolean
41
+ /** The root's own real path, which every linked directory entered has to stay under. */
42
+ realRoot: string
43
+ /** How many directories may be read behind links, and how many of those are left; `undefined` for as many as there are. */
44
+ maxLinkedDirectories: number | undefined
45
+ linkedDirectoriesLeft: number | undefined
46
+ }
47
+
48
+ /** Is `abs` the directory `root` or below it? Both are real paths. */
49
+ const isWithin = (root: string, abs: string): boolean => abs === root || abs.startsWith(root.endsWith(path.sep) ? root : root + path.sep)
50
+
51
+ const relativeTo = (absRoot: string, abs: string): string => path.relative(absRoot, abs).split(path.sep).join('/') || '.'
52
+
53
+ /**
54
+ * Recursively list files under `absDir`, returning forward-slash paths relative to the root.
55
+ * A directory that cannot hold anything the caller is after is not entered at all.
56
+ *
57
+ * `linked` holds the real paths of the linked directories on the way down, so that a link
58
+ * back into one of them is entered once and not again.
59
+ */
60
+ async function walkFiles(walk: Walk, absDir: string, linked: ReadonlySet<string>): Promise<string[]> {
61
+ // The tree itself is as large as it is. What links add to it has no such bound: they can
62
+ // lead anywhere, and into each other.
63
+ if (linked.size > 0 && walk.linkedDirectoriesLeft !== undefined && walk.linkedDirectoriesLeft-- <= 0) {
64
+ throw new Error(`More than ${walk.maxLinkedDirectories} directories to list behind symbolic links`)
65
+ }
34
66
  let dirEntries: Dirent[]
35
67
  try {
36
68
  dirEntries = await fs.readdir(absDir, { withFileTypes: true })
37
- } catch {
38
- return []
69
+ } catch (error) {
70
+ // Only a directory that is not there is an empty one. One that cannot be read
71
+ // (EACCES) must not pass for it: the caller would take its files for absent.
72
+ if (!isNodeError(error)) throw error
73
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return []
74
+ // Named by its root-relative path: the runtime's own message spells out the absolute one.
75
+ throw new UnreadableDirectoryError(relativeTo(walk.absRoot, absDir), error.code ?? 'unknown error', { cause: error })
39
76
  }
40
77
  const out: string[] = []
41
78
  for (const entry of dirEntries) {
42
79
  const abs = path.join(absDir, entry.name)
43
- if (entry.isDirectory()) {
44
- out.push(...await walkFiles(absRoot, abs))
45
- } else if (entry.isFile()) {
46
- out.push(path.relative(absRoot, abs).split(path.sep).join('/'))
80
+ let isDirectory = entry.isDirectory()
81
+ let isFile = entry.isFile()
82
+ let within = linked
83
+ let real: string | null = null
84
+ if (walk.followSymlinks && entry.isSymbolicLink()) {
85
+ // A link that leads nowhere is not a file anyone loads.
86
+ const target = await fs.stat(abs).catch(() => null)
87
+ // Without a real path the link is entered as it is: a directory that cannot be read
88
+ // then fails the walk, as it would unlinked.
89
+ real = target?.isDirectory() ? await fs.realpath(abs).catch(() => abs) : null
90
+ isFile = target?.isFile() ?? false
91
+ isDirectory = real !== null && !linked.has(real)
92
+ if (real !== null) within = new Set([...linked, real])
93
+ }
94
+ if (isDirectory) {
95
+ // Not walked, so not read either: whatever is in there the caller would discard.
96
+ if (walk.skip(relativeTo(walk.absRoot, abs))) continue
97
+ // Nothing the caller wants can be in a directory its pattern cannot reach, so it is
98
+ // neither read nor, when it cannot be read, a reason to fail.
99
+ if (!walk.mayHold(relativeTo(walk.absRoot, abs))) continue
100
+ // A link out of the project leads into a tree nobody vouched for (the host's own
101
+ // files, on a hosted checkout), so it is not walked. Nor is it skipped: the listing
102
+ // would then pass for whole.
103
+ if (real !== null && !isWithin(walk.realRoot, real)) {
104
+ throw new Error(`Symbolic link "${relativeTo(walk.absRoot, abs)}" leads out of the project root`)
105
+ }
106
+ out.push(...await walkFiles(walk, abs, within))
107
+ } else if (isFile) {
108
+ out.push(relativeTo(walk.absRoot, abs))
47
109
  }
48
110
  }
49
111
  return out
@@ -126,11 +188,25 @@ export function createNodeFs(root: string): CmsFileSystem {
126
188
  }
127
189
  },
128
190
 
129
- async glob(pattern) {
191
+ async glob(pattern, options) {
130
192
  const baseRel = staticPrefixDir(pattern)
131
193
  const absBase = resolve(baseRel)
132
194
  const matcher = globToRegExp(pattern)
133
- const files = await walkFiles(resolvedRoot, absBase)
195
+ const followSymlinks = options?.followSymlinks ?? false
196
+ const walk: Walk = {
197
+ absRoot: resolvedRoot,
198
+ mayHold: dir => globMayMatchUnder(pattern, dir),
199
+ skip: options?.skipDirectory ?? (() => false),
200
+ followSymlinks,
201
+ // The root may itself sit behind a link (a temporary directory on macOS does).
202
+ realRoot: followSymlinks ? await fs.realpath(resolvedRoot).catch(() => resolvedRoot) : resolvedRoot,
203
+ maxLinkedDirectories: options?.maxLinkedDirectories,
204
+ linkedDirectoriesLeft: options?.maxLinkedDirectories,
205
+ }
206
+ // Asked of the starting directory as of any other, so that one the pattern cannot match
207
+ // under is not read, and not a reason to fail when it cannot be.
208
+ if (!walk.mayHold(relativeTo(resolvedRoot, absBase))) return []
209
+ const files = await walkFiles(walk, absBase, new Set())
134
210
  return files.filter(rel => matcher.test(rel))
135
211
  },
136
212
 
package/src/fs/types.ts CHANGED
@@ -6,6 +6,31 @@
6
6
  * escapes it (path traversal). The same brain therefore runs unchanged over
7
7
  * `node:fs` (sidecar + local dev) and, in principle, over a remote adapter.
8
8
  */
9
+ export interface GlobOptions {
10
+ /**
11
+ * Directories (root-relative, forward slashes) whose files the caller would throw away.
12
+ * An implementation may leave them unread, so one that cannot be read fails nothing.
13
+ * A match under one may still come back: the caller filters its results as before.
14
+ */
15
+ skipDirectory?: (dir: string) => boolean
16
+ /**
17
+ * Symbolic links below the pattern's static prefix are left out unless this is set. With it,
18
+ * a linked file is listed under the link's own path, wherever it points, and a linked
19
+ * directory is walked as if it were there, as often as a path leads into it; a link back
20
+ * into a directory already entered through a link on the same path is not entered again.
21
+ * A linked directory whose real path is outside the root is not walked: when the pattern
22
+ * could match under it, the call rejects instead of answering without it. An implementation
23
+ * that ignores the option keeps leaving them out.
24
+ */
25
+ followSymlinks?: boolean
26
+ /**
27
+ * Bounds what following links adds to the walk: when listing would have to read more
28
+ * directories than that behind links, the call rejects instead of answering with a part of
29
+ * the files. Directories reached without a link do not count.
30
+ */
31
+ maxLinkedDirectories?: number
32
+ }
33
+
9
34
  export interface CmsFileSystem {
10
35
  /** Read a UTF-8 text file. Rejects when the file does not exist. */
11
36
  readFile(path: string): Promise<string>
@@ -21,8 +46,12 @@ export interface CmsFileSystem {
21
46
  exists(path: string): Promise<boolean>
22
47
  /** List the immediate children of a directory. Returns [] when it does not exist. */
23
48
  list(dir: string): Promise<{ name: string; isDirectory: boolean }[]>
24
- /** Resolve a glob pattern (supports `*`, `**`, `?`, `{a,b}`) to matching file paths, root-relative. */
25
- glob(pattern: string): Promise<string[]>
49
+ /**
50
+ * Resolve a glob pattern (supports `*`, `**`, `?`, `{a,b}`) to matching file paths, root-relative.
51
+ * Rejects with an `UnreadableDirectoryError` for a directory it cannot read that may hold a match.
52
+ * See {@link GlobOptions} for skipping directories and following symbolic links.
53
+ */
54
+ glob(pattern: string, options?: GlobOptions): Promise<string[]>
26
55
  /** File metadata. Rejects when the path does not exist. */
27
56
  stat(path: string): Promise<{ mtimeMs: number; size: number }>
28
57
  }
@@ -1,7 +1,8 @@
1
1
  import type { CollectionEntryInfo, ComponentDefinition, MutationResult } from '@nuasite/cms-types'
2
+ import path from 'node:path'
2
3
  import yaml from 'yaml'
3
4
  import { assetBaseDir, resolveAssetCandidates } from '../asset-paths'
4
- import { scanCollections } from '../collection-scanner'
5
+ import { normalizeBasePath, scanCollections } from '../collection-scanner'
5
6
  import { type ParseCache, parseContentConfig, type ParsedField } from '../content-config-ast'
6
7
  import {
7
8
  blankRequiredFields,
@@ -61,17 +62,14 @@ function isDataFile(filePath: string): boolean {
61
62
  * `glob({ base: './content/blog' })` points outside `contentDir`, and the
62
63
  * collection name (`o-virivkach`) need not match the directory. Falls back to the
63
64
  * default `<contentDir>/<collection>` layout for collections without a custom
64
- * loader base. This mirrors the scanner's `getCollectionSourceBasePath`, so the
65
- * mutation/read path resolves entries in the very same place the listing scan does.
65
+ * loader base. The base goes through the scanner's own `normalizeBasePath`, so the
66
+ * mutation/read path resolves entries in the very same place the listing scan does,
67
+ * the project root (`base: './'`) included.
66
68
  */
67
69
  async function resolveCollectionDir(deps: EntryOpsDeps, collection: string): Promise<string> {
68
70
  const parsed = await parseContentConfig(deps.fs, deps.parseCache)
69
71
  const loaderBase = parsed.get(collection)?.loaderBase
70
- if (loaderBase) {
71
- // Loader base is root-relative; strip a leading `./` and any trailing slash.
72
- const normalized = loaderBase.replace(/^\.\/+/, '').replace(/[/\\]+$/, '')
73
- if (normalized) return normalized
74
- }
72
+ if (loaderBase) return normalizeBasePath(loaderBase)
75
73
  return `${deps.contentDir}/${collection}`
76
74
  }
77
75
 
@@ -86,11 +84,11 @@ async function resolveEntryPath(deps: EntryOpsDeps, collection: string, slug: st
86
84
  const base = await resolveCollectionDir(deps, collection)
87
85
  const flatExts = ['md', 'mdx', 'json', 'yaml', 'yml']
88
86
  for (const ext of flatExts) {
89
- const candidate = `${base}/${slug}.${ext}`
87
+ const candidate = path.posix.join(base, `${slug}.${ext}`)
90
88
  if (await deps.fs.exists(candidate)) return candidate
91
89
  }
92
90
  for (const ext of MARKDOWN_EXTENSIONS) {
93
- const candidate = `${base}/${slug}/index.${ext}`
91
+ const candidate = path.posix.join(base, slug, `index.${ext}`)
94
92
  if (await deps.fs.exists(candidate)) return candidate
95
93
  }
96
94
  return null
@@ -302,7 +300,7 @@ async function inferLayoutFromExistingEntries(deps: EntryOpsDeps, collection: st
302
300
  const indexLookups = await Promise.all(subdirs.map(async dir => {
303
301
  if (flatSlugs.has(dir.name)) return false
304
302
  for (const ext of MARKDOWN_EXTENSIONS) {
305
- if (await deps.fs.exists(`${collectionPath}/${dir.name}/index.${ext}`)) return true
303
+ if (await deps.fs.exists(path.posix.join(collectionPath, dir.name, `index.${ext}`))) return true
306
304
  }
307
305
  return false
308
306
  }))
@@ -559,8 +557,8 @@ export async function createEntry(deps: EntryOpsDeps, input: CreateEntryInput):
559
557
  const layout = isData ? 'flat' : await detectCollectionMarkdownLayout(deps, collection)
560
558
  const collectionDir = await resolveCollectionDir(deps, collection)
561
559
  const sourcePath = layout === 'index'
562
- ? `${collectionDir}/${normalizedSlug}/index.${ext}`
563
- : `${collectionDir}/${normalizedSlug}.${ext}`
560
+ ? path.posix.join(collectionDir, normalizedSlug, `index.${ext}`)
561
+ : path.posix.join(collectionDir, `${normalizedSlug}.${ext}`)
564
562
 
565
563
  let fileContent: string
566
564
  if (isData) {
package/src/index.ts CHANGED
@@ -1,4 +1,13 @@
1
1
  export { resolveAssetCandidates } from './asset-paths'
2
+ export {
3
+ analyzeAstroScript,
4
+ analyzeAstroSource,
5
+ type AstroCollectionBinding,
6
+ type AstroContentAccessor,
7
+ type AstroContentCall,
8
+ type AstroSourceAnalysis,
9
+ type AstroSourceImport,
10
+ } from './astro-source-analysis'
2
11
  export { checkContent, type CheckContentOptions, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check'
3
12
  export {
4
13
  collectionKind,
@@ -13,11 +22,13 @@ export {
13
22
  export { checkAgainstSchemas, type LiveCheckInput } from './check-live'
14
23
  export { checkFieldShapes, type ShapeCheckInput } from './check-shape'
15
24
  export { checkEditorWrites, type WriteCheckInput } from './check-write'
16
- export { scanCollections } from './collection-scanner'
25
+ export { collectionScanReport, scanCollections } from './collection-scanner'
17
26
  export { scanComponentDefinitions } from './component-registry'
18
27
  export {
19
28
  classifyEmptyContentConfig,
20
29
  CONTENT_CONFIG_PATHS,
30
+ type ContentConfigRead,
31
+ type DeclaredCollection,
21
32
  type EmptyContentConfigReason,
22
33
  type ParseCache,
23
34
  parseConfigSource,
@@ -26,6 +37,8 @@ export {
26
37
  type ParsedConfig,
27
38
  type ParsedField,
28
39
  type ParsedReference,
40
+ readContentConfig,
41
+ UNREAD_CONTENT_CONFIG_PATHS,
29
42
  } from './content-config-ast'
30
43
  export { createCmsCore } from './core'
31
44
  export type { CmsCore, CmsCoreOptions } from './core'
@@ -46,9 +59,9 @@ export {
46
59
  withoutBlankArrayItems,
47
60
  type WriteModelField,
48
61
  } from './editor-write-model'
49
- export { globToRegExp } from './fs/glob'
62
+ export { globMayMatchUnder, globToRegExp, UnreadableDirectoryError } from './fs/glob'
50
63
  export { createNodeFs } from './fs/node-fs'
51
- export type { CmsFileSystem } from './fs/types'
64
+ export type { CmsFileSystem, GlobOptions } from './fs/types'
52
65
  export {
53
66
  type AddArrayItemInput,
54
67
  type CreateEntryInput,
@@ -66,16 +79,28 @@ export {
66
79
  createContemberStorageAdapter,
67
80
  createLocalStorageAdapter,
68
81
  createS3StorageAdapter,
82
+ decodeFilteredMediaCursor,
69
83
  getFileExtension,
84
+ isUnsafeFolder,
85
+ listFilteredMedia,
70
86
  listProjectImages,
71
87
  type ListProjectImagesOptions,
72
88
  type LocalStorageOptions,
89
+ MEDIA_CURSOR_TYPE_MISMATCH,
90
+ MEDIA_INVALID_CURSOR,
91
+ MEDIA_INVALID_FOLDER,
92
+ MEDIA_INVALID_ID,
93
+ MEDIA_NOT_FOUND,
94
+ MediaCursorError,
95
+ mediaErrorStatus,
73
96
  MIME_BY_EXT,
74
97
  mimeFromExt,
98
+ parseMediaTypeFilter,
75
99
  type S3StorageOptions,
76
100
  uploadsDirRelativeToRoot,
77
101
  } from './media/index'
78
102
  export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast'
103
+ export { type RouteCollectionScan, scanRouteCollections } from './route-scan'
79
104
  export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port'
80
105
  export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe'
81
106
  export {
@@ -1,4 +1,5 @@
1
- import type { MediaStorageAdapter } from '@nuasite/cms-types'
1
+ import type { MediaStorageAdapter, MediaUploadResult } from '@nuasite/cms-types'
2
+ import { MEDIA_INVALID_ID } from './errors'
2
3
 
3
4
  export interface ContemberStorageOptions {
4
5
  /** Base URL of the worker API, e.g. 'https://api.example.com' */
@@ -69,10 +70,17 @@ export function createContemberStorageAdapter(options: ContemberStorageOptions):
69
70
 
70
71
  const data: unknown = await res.json()
71
72
  const payload = (data && typeof data === 'object') ? data : {}
72
- return { success: true, ...payload }
73
+ const result: MediaUploadResult = { success: true, ...payload }
74
+ // Whatever the service reports stays marked as its own, like the status above, so it
75
+ // cannot read as one of the adapter's refusals.
76
+ if (result.error !== undefined) result.error = `Upload failed: ${String(result.error)}`
77
+ return result
73
78
  },
74
79
 
75
80
  async delete(id) {
81
+ // `encodeURIComponent` keeps the id one path segment, but leaves `.` and `..` as they
82
+ // are, and a URL resolves those away: the request would address a different endpoint.
83
+ if (id === '' || id === '.' || id === '..') return { success: false, error: MEDIA_INVALID_ID }
76
84
  const res = await fetch(`${base}/${encodeURIComponent(id)}`, {
77
85
  method: 'DELETE',
78
86
  headers: headers(),
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The `error` a media adapter answers with when it refuses what the caller named, or
3
+ * when the file is not there. They are exact strings so a host can tell these apart
4
+ * from a storage failure by comparing, not by reading the text of an arbitrary error:
5
+ * an HTTP layer answers the first two with a 400 and the third with a 404.
6
+ */
7
+ export const MEDIA_INVALID_ID = 'Invalid media id'
8
+ export const MEDIA_INVALID_FOLDER = 'Invalid folder name'
9
+ export const MEDIA_NOT_FOUND = 'Media file not found'
10
+
11
+ /**
12
+ * The HTTP status for a failed media adapter result: 400 for an id or folder the adapter
13
+ * refuses, 404 for a file that is not there, 500 for anything else. Only the exact
14
+ * strings above decide; the text of any other error may come from an SDK or an upstream
15
+ * service and is a storage failure whatever it says.
16
+ */
17
+ export function mediaErrorStatus(error: string | undefined): 400 | 404 | 500 {
18
+ if (error === MEDIA_INVALID_ID || error === MEDIA_INVALID_FOLDER) return 400
19
+ if (error === MEDIA_NOT_FOUND) return 404
20
+ return 500
21
+ }
@@ -1,4 +1,14 @@
1
1
  export { type ContemberStorageOptions, createContemberStorageAdapter } from './contember'
2
+ export { MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND, mediaErrorStatus } from './errors'
2
3
  export { createLocalStorageAdapter, getFileExtension, type LocalStorageOptions, MIME_BY_EXT, mimeFromExt } from './local'
4
+ export { isUnsafeFolder } from './names'
3
5
  export { listProjectImages, type ListProjectImagesOptions, uploadsDirRelativeToRoot } from './project-images'
4
6
  export { createS3StorageAdapter, type S3StorageOptions } from './s3'
7
+ export {
8
+ decodeFilteredMediaCursor,
9
+ listFilteredMedia,
10
+ MEDIA_CURSOR_TYPE_MISMATCH,
11
+ MEDIA_INVALID_CURSOR,
12
+ MediaCursorError,
13
+ parseMediaTypeFilter,
14
+ } from './type-filter'