@nuasite/cms-core 0.58.2 → 0.60.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 (39) hide show
  1. package/dist/types/core.d.ts +8 -0
  2. package/dist/types/core.d.ts.map +1 -1
  3. package/dist/types/fs/node-fs.d.ts.map +1 -1
  4. package/dist/types/fs/staged.d.ts +65 -0
  5. package/dist/types/fs/staged.d.ts.map +1 -0
  6. package/dist/types/fs/types.d.ts +2 -0
  7. package/dist/types/fs/types.d.ts.map +1 -1
  8. package/dist/types/handlers/redirect-ops.d.ts.map +1 -1
  9. package/dist/types/index.d.ts +2 -22
  10. package/dist/types/index.d.ts.map +1 -1
  11. package/dist/types/media/file-system.d.ts +15 -0
  12. package/dist/types/media/file-system.d.ts.map +1 -0
  13. package/dist/types/media/index.d.ts +2 -1
  14. package/dist/types/media/index.d.ts.map +1 -1
  15. package/dist/types/media/local.d.ts +0 -3
  16. package/dist/types/media/local.d.ts.map +1 -1
  17. package/dist/types/media/mime.d.ts +4 -0
  18. package/dist/types/media/mime.d.ts.map +1 -0
  19. package/dist/types/portable.d.ts +29 -0
  20. package/dist/types/portable.d.ts.map +1 -0
  21. package/dist/types/redirects.d.ts +99 -0
  22. package/dist/types/redirects.d.ts.map +1 -0
  23. package/dist/types/tsconfig.tsbuildinfo +1 -1
  24. package/package.json +3 -2
  25. package/src/core.ts +43 -21
  26. package/src/fs/node-fs.ts +18 -12
  27. package/src/fs/staged.ts +230 -0
  28. package/src/fs/types.ts +2 -0
  29. package/src/handlers/entry-ops.ts +1 -1
  30. package/src/handlers/redirect-ops.ts +31 -27
  31. package/src/index.ts +2 -115
  32. package/src/media/file-system.ts +133 -0
  33. package/src/media/index.ts +2 -1
  34. package/src/media/local.ts +1 -24
  35. package/src/media/mime.ts +23 -0
  36. package/src/media/project-images.ts +1 -1
  37. package/src/media/s3.ts +1 -1
  38. package/src/portable.ts +142 -0
  39. package/src/redirects.ts +246 -0
@@ -0,0 +1,133 @@
1
+ import type { MediaFolderItem, MediaItem, MediaListResult, MediaStorageAdapter } from '@nuasite/cms-types'
2
+ import type { CmsFileSystem } from '../fs/types'
3
+ import { MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND } from './errors'
4
+ import { getFileExtension, mimeFromExt } from './mime'
5
+ import { isUnsafeFolder } from './names'
6
+
7
+ export interface FileSystemStorageOptions {
8
+ /** Directory to store media files in, relative to the filesystem's root. Default: `public/uploads`. */
9
+ dir?: string
10
+ /** URL prefix the files are served under. Default: `/uploads`. */
11
+ urlPrefix?: string
12
+ }
13
+
14
+ /**
15
+ * Written into a folder created empty, since a `CmsFileSystem` has directories only for the files
16
+ * in them. Hidden from listings like every name starting with a dot.
17
+ */
18
+ const FOLDER_PLACEHOLDER = '.gitkeep'
19
+
20
+ /** `a/b` spelled the way ids and folders are handed out, or `null` for anything else. */
21
+ function parseNames(value: string): string[] | null {
22
+ const names = value.split('/')
23
+ if (value.includes('\0') || names.some(name => name === '' || name === '.' || name === '..')) return null
24
+ return names
25
+ }
26
+
27
+ function errorMessage(action: string, error: unknown): string {
28
+ const code = error instanceof Error && 'code' in error && typeof error.code === 'string' ? error.code : undefined
29
+ return code ? `Failed to ${action} (${code})` : `Failed to ${action}`
30
+ }
31
+
32
+ /**
33
+ * Media stored in the project itself, through the same `CmsFileSystem` the core edits it with: the
34
+ * counterpart of the local adapter for a host without `node:fs`. Uploads land at
35
+ * `<dir>/<folder>/<uuid>.<ext>` and are listed newest first.
36
+ */
37
+ export function createFileSystemStorageAdapter(fs: CmsFileSystem, options: FileSystemStorageOptions = {}): MediaStorageAdapter {
38
+ const dir = (options.dir ?? 'public/uploads').split('/').filter(name => name !== '' && name !== '.').join('/')
39
+ const urlPrefix = (options.urlPrefix ?? '/uploads').replace(/\/$/, '')
40
+
41
+ /** The folder option as `a/b` (stray slashes dropped) plus its path under the root; `null` when it names no folder. */
42
+ function resolveFolder(input: string | undefined, use: 'read' | 'write'): { folder: string; path: string } | null {
43
+ const folder = (input ?? '').split('/').filter(Boolean).join('/')
44
+ if (!folder) return { folder, path: dir }
45
+ if (parseNames(folder) === null || (use === 'write' && isUnsafeFolder(folder))) return null
46
+ return { folder, path: `${dir}/${folder}` }
47
+ }
48
+
49
+ return {
50
+ staticFiles: { urlPrefix, dir },
51
+
52
+ async list(opts) {
53
+ const limit = opts?.limit ?? 50
54
+ const offset = opts?.cursor ? parseInt(opts.cursor, 10) : 0
55
+ const target = resolveFolder(opts?.folder, 'read')
56
+ if (!target) return { items: [], folders: [], hasMore: false }
57
+ try {
58
+ const entries = (await fs.list(target.path)).filter(entry => !entry.name.startsWith('.'))
59
+ const folders: MediaFolderItem[] = entries
60
+ .filter(entry => entry.isDirectory)
61
+ .map(entry => ({ name: entry.name, path: target.folder ? `${target.folder}/${entry.name}` : entry.name }))
62
+ .sort((a, b) => a.name.localeCompare(b.name))
63
+ const files = await Promise.all(
64
+ entries
65
+ .filter(entry => !entry.isDirectory)
66
+ .map(async entry => ({ name: entry.name, stat: await fs.stat(`${target.path}/${entry.name}`) })),
67
+ )
68
+ files.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs)
69
+
70
+ const urlFolder = target.folder ? `/${target.folder}` : ''
71
+ const items: MediaItem[] = files.slice(offset, offset + limit).map(file => {
72
+ const ext = getFileExtension(file.name)
73
+ return {
74
+ id: target.folder ? `${target.folder}/${file.name}` : file.name,
75
+ url: `${urlPrefix}${urlFolder}/${file.name}`,
76
+ filename: file.name,
77
+ contentType: mimeFromExt(ext ? `.${ext}` : ''),
78
+ uploadedAt: new Date(file.stat.mtimeMs).toISOString(),
79
+ folder: target.folder || undefined,
80
+ }
81
+ })
82
+ const hasMore = offset + limit < files.length
83
+ return { items, folders, hasMore, cursor: hasMore ? String(offset + limit) : undefined } satisfies MediaListResult
84
+ } catch (error) {
85
+ // Deliberately without `cause`: whatever renders this error must not get the path back.
86
+ // oxlint-disable-next-line preserve-caught-error
87
+ throw new Error(errorMessage('list media', error))
88
+ }
89
+ },
90
+
91
+ async upload(file, filename, _contentType, uploadOpts) {
92
+ const target = resolveFolder(uploadOpts?.folder, 'write')
93
+ if (!target) return { success: false, error: MEDIA_INVALID_FOLDER }
94
+ const ext = getFileExtension(filename)
95
+ const newFilename = `${crypto.randomUUID()}${ext ? `.${ext}` : ''}`
96
+ try {
97
+ await fs.writeBytes(`${target.path}/${newFilename}`, file)
98
+ } catch (error) {
99
+ return { success: false, error: errorMessage('store media file', error) }
100
+ }
101
+ const urlFolder = target.folder ? `/${target.folder}` : ''
102
+ return {
103
+ success: true,
104
+ url: `${urlPrefix}${urlFolder}/${newFilename}`,
105
+ filename: newFilename,
106
+ id: target.folder ? `${target.folder}/${newFilename}` : newFilename,
107
+ }
108
+ },
109
+
110
+ async delete(id) {
111
+ if (parseNames(id) === null) return { success: false, error: MEDIA_INVALID_ID }
112
+ const path = `${dir}/${id}`
113
+ try {
114
+ if (!(await fs.exists(path))) return { success: false, error: MEDIA_NOT_FOUND }
115
+ await fs.remove(path)
116
+ return { success: true }
117
+ } catch (error) {
118
+ return { success: false, error: errorMessage('delete media file', error) }
119
+ }
120
+ },
121
+
122
+ async createFolder(folder) {
123
+ const target = resolveFolder(folder, 'write')
124
+ if (!target) return { success: false, error: MEDIA_INVALID_FOLDER }
125
+ try {
126
+ if (!(await fs.exists(target.path))) await fs.writeFile(`${target.path}/${FOLDER_PLACEHOLDER}`, '')
127
+ return { success: true }
128
+ } catch (error) {
129
+ return { success: false, error: errorMessage('create folder', error) }
130
+ }
131
+ },
132
+ }
133
+ }
@@ -1,6 +1,7 @@
1
1
  export { type ContemberStorageOptions, createContemberStorageAdapter } from './contember'
2
2
  export { MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND, mediaErrorStatus } from './errors'
3
- export { createLocalStorageAdapter, getFileExtension, type LocalStorageOptions, MIME_BY_EXT, mimeFromExt } from './local'
3
+ export { createFileSystemStorageAdapter, type FileSystemStorageOptions } from './file-system'
4
+ export { getFileExtension, MIME_BY_EXT, mimeFromExt } from './mime'
4
5
  export { isUnsafeFolder } from './names'
5
6
  export { listProjectImages, type ListProjectImagesOptions, uploadsDirRelativeToRoot } from './project-images'
6
7
  export { createS3StorageAdapter, type S3StorageOptions } from './s3'
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'
3
3
  import fs from 'node:fs/promises'
4
4
  import path from 'node:path'
5
5
  import { MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND } from './errors'
6
+ import { getFileExtension, mimeFromExt } from './mime'
6
7
  import { isUnsafeFolder } from './names'
7
8
 
8
9
  export interface LocalStorageOptions {
@@ -227,27 +228,3 @@ export function createLocalStorageAdapter(options: LocalStorageOptions = {}): Me
227
228
  },
228
229
  }
229
230
  }
230
-
231
- export function getFileExtension(filename: string): string {
232
- const parts = filename.split('.')
233
- const ext = parts.length > 1 ? (parts.pop()?.toLowerCase() ?? '') : ''
234
- return /^[a-z0-9]+$/.test(ext) ? ext : ''
235
- }
236
-
237
- export const MIME_BY_EXT: Record<string, string> = {
238
- '.jpg': 'image/jpeg',
239
- '.jpeg': 'image/jpeg',
240
- '.png': 'image/png',
241
- '.gif': 'image/gif',
242
- '.webp': 'image/webp',
243
- '.avif': 'image/avif',
244
- '.svg': 'image/svg+xml',
245
- '.ico': 'image/x-icon',
246
- '.mp4': 'video/mp4',
247
- '.webm': 'video/webm',
248
- '.pdf': 'application/pdf',
249
- }
250
-
251
- export function mimeFromExt(ext: string): string {
252
- return MIME_BY_EXT[ext] ?? 'application/octet-stream'
253
- }
@@ -0,0 +1,23 @@
1
+ export function getFileExtension(filename: string): string {
2
+ const parts = filename.split('.')
3
+ const ext = parts.length > 1 ? (parts.pop()?.toLowerCase() ?? '') : ''
4
+ return /^[a-z0-9]+$/.test(ext) ? ext : ''
5
+ }
6
+
7
+ export const MIME_BY_EXT: Record<string, string> = {
8
+ '.jpg': 'image/jpeg',
9
+ '.jpeg': 'image/jpeg',
10
+ '.png': 'image/png',
11
+ '.gif': 'image/gif',
12
+ '.webp': 'image/webp',
13
+ '.avif': 'image/avif',
14
+ '.svg': 'image/svg+xml',
15
+ '.ico': 'image/x-icon',
16
+ '.mp4': 'video/mp4',
17
+ '.webm': 'video/webm',
18
+ '.pdf': 'application/pdf',
19
+ }
20
+
21
+ export function mimeFromExt(ext: string): string {
22
+ return MIME_BY_EXT[ext] ?? 'application/octet-stream'
23
+ }
@@ -1,6 +1,6 @@
1
1
  import type { MediaItem } from '@nuasite/cms-types'
2
2
  import type { CmsFileSystem } from '../fs/types'
3
- import { MIME_BY_EXT, mimeFromExt } from './local'
3
+ import { MIME_BY_EXT, mimeFromExt } from './mime'
4
4
 
5
5
  const IMAGE_EXTENSIONS = new Set(Object.entries(MIME_BY_EXT).filter(([, mime]) => mime.startsWith('image/')).map(([ext]) => ext))
6
6
 
package/src/media/s3.ts CHANGED
@@ -2,7 +2,7 @@ import type { MediaFolderItem, MediaListResult, MediaStorageAdapter, MediaUpload
2
2
  import { randomUUID } from 'node:crypto'
3
3
  import path from 'node:path'
4
4
  import { MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID } from './errors'
5
- import { getFileExtension, mimeFromExt } from './local'
5
+ import { getFileExtension, mimeFromExt } from './mime'
6
6
  import { hasDotSegment, isUnsafeFolder } from './names'
7
7
 
8
8
  /*
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Everything cms-core offers that runs without `node:fs`. The package root resolves here under the
3
+ * `workerd` condition; the default root adds the Node filesystem and the local media adapter.
4
+ */
5
+ export { resolveAssetCandidates } from './asset-paths'
6
+ export {
7
+ analyzeAstroScript,
8
+ analyzeAstroSource,
9
+ type AstroCollectionBinding,
10
+ type AstroContentAccessor,
11
+ type AstroContentCall,
12
+ type AstroSourceAnalysis,
13
+ type AstroSourceImport,
14
+ } from './astro-source-analysis'
15
+ export { checkContent, type CheckContentOptions, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check'
16
+ export {
17
+ collectionKind,
18
+ entryStem,
19
+ loadCollections,
20
+ type LoadedCollection,
21
+ type LoadedCollections,
22
+ type LoadedEntry,
23
+ normalizeBase,
24
+ parseEntry,
25
+ } from './check-entries'
26
+ export { checkAgainstSchemas, type LiveCheckInput } from './check-live'
27
+ export { checkFieldShapes, type ShapeCheckInput } from './check-shape'
28
+ export { checkEditorWrites, type WriteCheckInput } from './check-write'
29
+ export { collectionScanReport, scanCollections } from './collection-scanner'
30
+ export { scanComponentDefinitions } from './component-registry'
31
+ export {
32
+ classifyEmptyContentConfig,
33
+ CONTENT_CONFIG_PATHS,
34
+ type ContentConfigRead,
35
+ type DeclaredCollection,
36
+ type EmptyContentConfigReason,
37
+ type ParseCache,
38
+ parseConfigSource,
39
+ parseContentConfig,
40
+ type ParsedCollection,
41
+ type ParsedConfig,
42
+ type ParsedField,
43
+ type ParsedReference,
44
+ readContentConfig,
45
+ UNREAD_CONTENT_CONFIG_PATHS,
46
+ } from './content-config-ast'
47
+ export { createCmsCore } from './core'
48
+ export type { CmsCore, CmsCoreOptions } from './core'
49
+ export {
50
+ applyCreateRouteFields,
51
+ blankFieldValue,
52
+ blankRequiredFields,
53
+ type CollectionKind,
54
+ type CreateWriteField,
55
+ isBlankFieldValue,
56
+ newEntryFrontmatter,
57
+ newRepeaterItem,
58
+ normalizeCreateWrite,
59
+ omitEmptyOnCreate,
60
+ type RepeaterItemField,
61
+ type RequiredGuardField,
62
+ seedValueForRequiredField,
63
+ withoutBlankArrayItems,
64
+ type WriteModelField,
65
+ } from './editor-write-model'
66
+ export { globMayMatchUnder, globToRegExp, UnreadableDirectoryError } from './fs/glob'
67
+ export {
68
+ type CmsChangeset,
69
+ type CmsCommit,
70
+ CmsCommitConflictError,
71
+ type CmsFileVersion,
72
+ type CmsStagedChange,
73
+ commitChangeset,
74
+ createStagedFileSystem,
75
+ digestBytes,
76
+ type StagedFileSystem,
77
+ versionMatches,
78
+ versionOf,
79
+ } from './fs/staged'
80
+ export type { CmsFileSystem, GlobOptions } from './fs/types'
81
+ export {
82
+ type AddArrayItemInput,
83
+ type CreateEntryInput,
84
+ ensureMdxImports,
85
+ type EntryAsset,
86
+ type EntryOpsDeps,
87
+ type GetEntryResult,
88
+ parseFrontmatter,
89
+ type RemoveArrayItemInput,
90
+ serializeFrontmatter,
91
+ type UpdateEntryInput,
92
+ } from './handlers/entry-ops'
93
+ export {
94
+ type ContemberStorageOptions,
95
+ createContemberStorageAdapter,
96
+ createFileSystemStorageAdapter,
97
+ createS3StorageAdapter,
98
+ decodeFilteredMediaCursor,
99
+ type FileSystemStorageOptions,
100
+ getFileExtension,
101
+ isUnsafeFolder,
102
+ listFilteredMedia,
103
+ listProjectImages,
104
+ type ListProjectImagesOptions,
105
+ MEDIA_CURSOR_TYPE_MISMATCH,
106
+ MEDIA_INVALID_CURSOR,
107
+ MEDIA_INVALID_FOLDER,
108
+ MEDIA_INVALID_ID,
109
+ MEDIA_NOT_FOUND,
110
+ MediaCursorError,
111
+ mediaErrorStatus,
112
+ MIME_BY_EXT,
113
+ mimeFromExt,
114
+ parseMediaTypeFilter,
115
+ type S3StorageOptions,
116
+ uploadsDirRelativeToRoot,
117
+ } from './media/index'
118
+ export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast'
119
+ export {
120
+ CLOUDFLARE_REDIRECT_LIMITS,
121
+ CMS_REDIRECTS_FILE,
122
+ type MergedRedirects,
123
+ mergeRedirects,
124
+ parseRedirectRule,
125
+ type RedirectLayer,
126
+ type RedirectLine,
127
+ type RedirectRuleLine,
128
+ } from './redirects'
129
+ export { type RouteCollectionScan, scanRouteCollections } from './route-scan'
130
+ export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port'
131
+ export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe'
132
+ export {
133
+ applyDerivedTransform,
134
+ computeDerivedFieldUpdates,
135
+ computePathnameFromSpec,
136
+ type DerivedFieldSpec,
137
+ escapeHtml,
138
+ relativeImportPath,
139
+ resolvePathnameFromSpec,
140
+ slugify,
141
+ slugifyHref,
142
+ } from './shared'
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Merge the `_redirects` rules a site gets from several places into the one file a host reads.
3
+ *
4
+ * A nua site has three: `src/_redirects`, which editors maintain through the CMS, the hand-written
5
+ * `public/_redirects`, and the `redirects` map in the Astro config. Each used to be written into
6
+ * `dist/_redirects` on its own, so a path redirected in two of them was listed twice. Cloudflare
7
+ * Pages rejects a file with a repeated source, and with it the whole deploy.
8
+ *
9
+ * Only what is understood is changed: a line this reader cannot take apart (a Netlify role gate with
10
+ * no destination, a trailing comment) is kept as written, where it was. Merging is idempotent, so it
11
+ * does not matter which build step merges last, or how often.
12
+ */
13
+
14
+ /** Where the CMS keeps the redirects editors manage, relative to the project root. */
15
+ export const CMS_REDIRECTS_FILE = 'src/_redirects'
16
+
17
+ /** One source of rules, in the order of precedence the caller passes them (first wins). */
18
+ export interface RedirectLayer {
19
+ /** Where the rules come from, for messages: `src/_redirects`, `public/_redirects`. */
20
+ name: string
21
+ text: string
22
+ /**
23
+ * Rules written by people with less say over the site than its code, such as CMS editors. Such a
24
+ * layer may only redirect (a 3xx status, no conditions, so no proxying), and none of its rules may
25
+ * touch a path a guard from an unrestricted layer covers: a role gate, a 4xx, or any line not read
26
+ * as a rule. Otherwise an editor's rule, listed first, could take access control off a path.
27
+ */
28
+ restricted?: boolean
29
+ }
30
+
31
+ export interface RedirectLine {
32
+ layer: string
33
+ /** 1-based line number within its layer's text. */
34
+ lineNumber: number
35
+ line: string
36
+ }
37
+
38
+ export interface MergedRedirects {
39
+ /** The merged file, or `''` when no layer holds a rule. */
40
+ text: string
41
+ /** The lines written, in order: rules with their fields joined by single spaces, other lines as written. */
42
+ lines: string[]
43
+ /** Rules dropped for a rule with the same source (and conditions) earlier in precedence. */
44
+ overridden: Array<{ kept: RedirectLine; dropped: RedirectLine }>
45
+ /** Rules kept but never reached: a pattern from a layer of higher precedence matches their source first. */
46
+ shadowed: Array<{ by: RedirectLine; rule: RedirectLine }>
47
+ /** Lines not read as a rule, kept as written. */
48
+ unrecognised: RedirectLine[]
49
+ /** Rules of a restricted layer left out: not a plain redirect, or touching a path a guard from code covers. */
50
+ refused: Array<{ rule: RedirectLine; reason: string }>
51
+ /** Rules with a literal source, and rules with a `*` or `:placeholder` in it. */
52
+ counts: { exact: number; pattern: number }
53
+ }
54
+
55
+ /**
56
+ * Cloudflare Pages' limits on a `_redirects` file. Netlify has none, so going over them is worth a
57
+ * warning, not a failed build.
58
+ */
59
+ export const CLOUDFLARE_REDIRECT_LIMITS = { exact: 2000, pattern: 100 } as const
60
+
61
+ const HEADER = '# Merged by @nuasite. A host applies the first rule that matches, so each source of rules\n'
62
+ + '# is listed ahead of the ones it takes precedence over.\n'
63
+
64
+ /** One `_redirects` line, read the way a host reads it. */
65
+ export interface RedirectRuleLine {
66
+ source: string
67
+ destination: string
68
+ /** The status as written (`301`, `302!`), or `undefined` for the host's default. */
69
+ status: string | undefined
70
+ /** Netlify query matches (`id=:id`) and conditions (`Language=cs`). */
71
+ conditions: string[]
72
+ /** Source plus conditions: two rules with the same key are the same rule. */
73
+ key: string
74
+ /** A `*` or `:placeholder` in the source's path. */
75
+ pattern: boolean
76
+ /** The fields joined by single spaces. */
77
+ text: string
78
+ }
79
+
80
+ const isTarget = (field: string) => field.startsWith('/') || /^https?:\/\/\S/.test(field)
81
+ const isCondition = (field: string) => field.includes('=') && !isTarget(field)
82
+ const pathOf = (source: string) => source.replace(/^https?:\/\/[^/]*/, '')
83
+
84
+ /**
85
+ * Read one `_redirects` line: `source [query matches] destination [status] [conditions]`. `undefined`
86
+ * for a line that does not have that shape, such as one with no destination, a source or destination
87
+ * that is not a path or URL, a status that is not a three-digit code, or a stray field.
88
+ */
89
+ export function parseRedirectRule(line: string): RedirectRuleLine | undefined {
90
+ const fields = line.trim().split(/\s+/)
91
+ const source = fields.shift()
92
+ if (!source || !isTarget(source)) return undefined
93
+
94
+ const conditions: string[] = []
95
+ while (fields[0] !== undefined && isCondition(fields[0])) conditions.push(fields.shift()!)
96
+ const destination = fields.shift()
97
+ if (!destination || !isTarget(destination)) return undefined
98
+ const status = fields[0] !== undefined && /^\d{3}!?$/.test(fields[0]) ? fields.shift() : undefined
99
+ while (fields[0] !== undefined && isCondition(fields[0])) conditions.push(fields.shift()!)
100
+ if (fields.length > 0) return undefined
101
+
102
+ return {
103
+ source,
104
+ destination,
105
+ status,
106
+ conditions,
107
+ key: [source, ...conditions.toSorted()].join(' '),
108
+ pattern: /\*|:[A-Za-z_]/.test(pathOf(source)),
109
+ text: line.trim().split(/\s+/).join(' '),
110
+ }
111
+ }
112
+
113
+ type Entry =
114
+ | { kind: 'rule'; at: RedirectLine; rule: RedirectRuleLine; layer: number }
115
+ | { kind: 'line'; at: RedirectLine }
116
+
117
+ /**
118
+ * Merge `layers`, earlier layers taking precedence. Each layer's lines are written as a block, in their
119
+ * own order, ahead of every layer they take precedence over: a host applies the first rule that
120
+ * matches, so a higher layer wins for every path it covers, by an exact rule or by a pattern, and the
121
+ * order an author chose within a file is kept. Two rules are the same rule when they share a source
122
+ * and, for Netlify, the same conditions (`Language=cs`) and query matches (`id=:id`); the first wins.
123
+ */
124
+ export function mergeRedirects(layers: RedirectLayer[]): MergedRedirects {
125
+ const entries: Entry[] = []
126
+ const kept = new Map<string, Entry & { kind: 'rule' }>()
127
+ const overridden: MergedRedirects['overridden'] = []
128
+ const unrecognised: RedirectLine[] = []
129
+
130
+ const refused: MergedRedirects['refused'] = []
131
+ const guards = layers.filter(l => !l.restricted).flatMap(l => guardSources(l.text))
132
+
133
+ layers.forEach((layer, layerIndex) => {
134
+ const lines = layer.text.split('\n')
135
+ for (let i = 0; i < lines.length; i++) {
136
+ const line = lines[i]!.trim()
137
+ if (!line || line.startsWith('#')) continue
138
+ const at: RedirectLine = { layer: layer.name, lineNumber: i + 1, line }
139
+ const rule = parseRedirectRule(line)
140
+ if (layer.restricted) {
141
+ const reason = refusal(rule, guards)
142
+ if (reason) {
143
+ refused.push({ rule: at, reason })
144
+ continue
145
+ }
146
+ }
147
+ if (!rule) {
148
+ unrecognised.push(at)
149
+ entries.push({ kind: 'line', at })
150
+ continue
151
+ }
152
+ const existing = kept.get(rule.key)
153
+ if (existing) {
154
+ if (existing.rule.text !== rule.text) overridden.push({ kept: existing.at, dropped: at })
155
+ continue
156
+ }
157
+ const entry = { kind: 'rule' as const, at, rule, layer: layerIndex }
158
+ kept.set(rule.key, entry)
159
+ entries.push(entry)
160
+ }
161
+ })
162
+
163
+ const lines = entries.map(e => e.kind === 'rule' ? e.rule.text : e.at.line)
164
+ const pattern = entries.filter(e => e.kind === 'rule' && e.rule.pattern).length
165
+ return {
166
+ text: lines.length ? `${HEADER}${lines.join('\n')}\n` : '',
167
+ lines,
168
+ overridden,
169
+ shadowed: findShadowed(entries),
170
+ unrecognised,
171
+ refused,
172
+ counts: { exact: lines.length - pattern, pattern },
173
+ }
174
+ }
175
+
176
+ /** Exact rules a pattern from a layer of higher precedence reaches first. Conditional patterns may not apply, so they shadow nothing. */
177
+ function findShadowed(entries: Entry[]): MergedRedirects['shadowed'] {
178
+ const patterns = entries.flatMap(e =>
179
+ e.kind === 'rule' && e.rule.pattern && e.rule.conditions.length === 0 ? [{ entry: e, matches: patternMatcher(e.rule.source) }] : []
180
+ )
181
+ const shadowed: MergedRedirects['shadowed'] = []
182
+ for (const e of entries) {
183
+ if (e.kind !== 'rule' || e.rule.pattern) continue
184
+ const by = patterns.find(p => p.entry.layer < e.layer && p.matches.test(e.rule.source))
185
+ if (by) shadowed.push({ by: by.entry.at, rule: e.at })
186
+ }
187
+ return shadowed
188
+ }
189
+
190
+ function patternMatcher(source: string): RegExp {
191
+ const escaped = source.replace(/[.+?^${}()|[\]\\]/g, '\\$&')
192
+ return new RegExp(`^${escaped.replace(/\*/g, '.*').replace(/:[A-Za-z_]\w*/g, '[^/]+')}$`)
193
+ }
194
+
195
+ const isPlainRedirect = (rule: RedirectRuleLine) => rule.conditions.length === 0 && (rule.status === undefined || /^30[12378]!?$/.test(rule.status))
196
+
197
+ /**
198
+ * The sources of the lines in an unrestricted layer that control access to a path: one with
199
+ * conditions (a role gate), a 4xx status (a refusal), or a line not read as a rule at all, which may
200
+ * be either. A plain rewrite (`200` with no conditions) only serves a path from elsewhere, so an
201
+ * editor may still redirect it, for instance to a replacement file.
202
+ */
203
+ function guardSources(text: string): string[] {
204
+ return text.split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')).flatMap(line => {
205
+ const rule = parseRedirectRule(line)
206
+ if (rule && rule.conditions.length === 0 && !/^4/.test(rule.status ?? '')) return []
207
+ return [rule?.source ?? line.split(/\s+/)[0]!]
208
+ })
209
+ }
210
+
211
+ /** Why a restricted layer's line may not be merged, or `undefined` when it may. */
212
+ function refusal(rule: RedirectRuleLine | undefined, guards: string[]): string | undefined {
213
+ if (!rule) return 'not read as a rule'
214
+ if (!isPlainRedirect(rule)) return 'only a redirect with a 3xx status and no conditions is allowed here'
215
+ const guard = guards.find(g => overlaps(g, rule.source))
216
+ if (guard) return `${guard} is guarded in code`
217
+ return undefined
218
+ }
219
+
220
+ /**
221
+ * Whether some request path could match both sources. Deliberately looser than any host: paths are
222
+ * compared decoded and case-insensitively, without repeated or trailing slashes, a `:param` matches any
223
+ * one segment, and a segment with a `*` matches anything from there on, nothing included (so
224
+ * `/admin/*` covers `/admin`). A guard must not be passed by spelling its path another way.
225
+ */
226
+ function overlaps(a: string, b: string): boolean {
227
+ const as = segments(a)
228
+ const bs = segments(b)
229
+ for (let i = 0;; i++) {
230
+ const x = as[i]
231
+ const y = bs[i]
232
+ if (x?.includes('*') || y?.includes('*')) return true
233
+ if (x === undefined || y === undefined) return x === y
234
+ if (x !== y && !x.startsWith(':') && !y.startsWith(':')) return false
235
+ }
236
+ }
237
+
238
+ function segments(source: string): string[] {
239
+ let path = pathOf(source)
240
+ try {
241
+ path = decodeURIComponent(path)
242
+ } catch {
243
+ // Malformed escapes: compare as written.
244
+ }
245
+ return path.toLowerCase().split('/').filter(Boolean)
246
+ }