@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.
- package/dist/types/core.d.ts +8 -0
- package/dist/types/core.d.ts.map +1 -1
- package/dist/types/fs/node-fs.d.ts.map +1 -1
- package/dist/types/fs/staged.d.ts +65 -0
- package/dist/types/fs/staged.d.ts.map +1 -0
- package/dist/types/fs/types.d.ts +2 -0
- package/dist/types/fs/types.d.ts.map +1 -1
- package/dist/types/handlers/redirect-ops.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -22
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/media/file-system.d.ts +15 -0
- package/dist/types/media/file-system.d.ts.map +1 -0
- package/dist/types/media/index.d.ts +2 -1
- package/dist/types/media/index.d.ts.map +1 -1
- package/dist/types/media/local.d.ts +0 -3
- package/dist/types/media/local.d.ts.map +1 -1
- package/dist/types/media/mime.d.ts +4 -0
- package/dist/types/media/mime.d.ts.map +1 -0
- package/dist/types/portable.d.ts +29 -0
- package/dist/types/portable.d.ts.map +1 -0
- package/dist/types/redirects.d.ts +99 -0
- package/dist/types/redirects.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -2
- package/src/core.ts +43 -21
- package/src/fs/node-fs.ts +18 -12
- package/src/fs/staged.ts +230 -0
- package/src/fs/types.ts +2 -0
- package/src/handlers/entry-ops.ts +1 -1
- package/src/handlers/redirect-ops.ts +31 -27
- package/src/index.ts +2 -115
- package/src/media/file-system.ts +133 -0
- package/src/media/index.ts +2 -1
- package/src/media/local.ts +1 -24
- package/src/media/mime.ts +23 -0
- package/src/media/project-images.ts +1 -1
- package/src/media/s3.ts +1 -1
- package/src/portable.ts +142 -0
- package/src/redirects.ts +246 -0
package/src/core.ts
CHANGED
|
@@ -18,6 +18,7 @@ import type {
|
|
|
18
18
|
import { collectionScanReport, scanCollections } from './collection-scanner'
|
|
19
19
|
import { scanComponentDefinitions } from './component-registry'
|
|
20
20
|
import { type ParseCache } from './content-config-ast'
|
|
21
|
+
import { type CmsCommit, createStagedFileSystem } from './fs/staged'
|
|
21
22
|
import type { CmsFileSystem } from './fs/types'
|
|
22
23
|
import {
|
|
23
24
|
addArrayItem as addArrayItemOp,
|
|
@@ -57,6 +58,13 @@ export interface CmsCoreOptions {
|
|
|
57
58
|
media?: MediaStorageAdapter
|
|
58
59
|
/** Directories to scan for Astro components (used for MDX import resolution). Defaults to `['src/components']`. */
|
|
59
60
|
componentDirs?: string[]
|
|
61
|
+
/**
|
|
62
|
+
* Runs each mutation over a staged view of the filesystem and hands its changes to this
|
|
63
|
+
* function instead of writing them directly. See {@link CmsCommit}: it rejects with
|
|
64
|
+
* `CmsCommitConflictError` when a file the mutation read has changed meanwhile, and the
|
|
65
|
+
* mutation then rejects with it. Without it, mutations write as they go.
|
|
66
|
+
*/
|
|
67
|
+
commit?: CmsCommit
|
|
60
68
|
}
|
|
61
69
|
|
|
62
70
|
/**
|
|
@@ -121,15 +129,29 @@ export interface CmsCore {
|
|
|
121
129
|
export function createCmsCore(fs: CmsFileSystem, opts: CmsCoreOptions = {}): CmsCore {
|
|
122
130
|
const contentDir = opts.contentDir ?? 'src/content'
|
|
123
131
|
const componentDirs = opts.componentDirs ?? ['src/components']
|
|
132
|
+
const commit = opts.commit
|
|
124
133
|
// One mtime-keyed content-config parse cache per core instance (per project root).
|
|
125
134
|
const parseCache: ParseCache = new Map()
|
|
126
135
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
136
|
+
function entryDeps(over: CmsFileSystem): EntryOpsDeps {
|
|
137
|
+
return {
|
|
138
|
+
fs: over,
|
|
139
|
+
contentDir,
|
|
140
|
+
parseCache,
|
|
141
|
+
componentDirs,
|
|
142
|
+
resolveComponentDefinitions: () => scanComponentDefinitions(over, componentDirs),
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const readDeps = entryDeps(fs)
|
|
147
|
+
|
|
148
|
+
/** A mutation's result is returned once its changes are committed, whether it reports success or not. */
|
|
149
|
+
async function mutate<T>(operation: (over: CmsFileSystem) => Promise<T>): Promise<T> {
|
|
150
|
+
if (commit === undefined) return operation(fs)
|
|
151
|
+
const staged = createStagedFileSystem(fs)
|
|
152
|
+
const result = await operation(staged)
|
|
153
|
+
await commit(staged.changeset())
|
|
154
|
+
return result
|
|
133
155
|
}
|
|
134
156
|
|
|
135
157
|
return {
|
|
@@ -141,40 +163,40 @@ export function createCmsCore(fs: CmsFileSystem, opts: CmsCoreOptions = {}): Cms
|
|
|
141
163
|
return scanComponentDefinitions(fs, componentDirs)
|
|
142
164
|
},
|
|
143
165
|
getEntry(collection, slug) {
|
|
144
|
-
return getEntryOp(
|
|
166
|
+
return getEntryOp(readDeps, collection, slug)
|
|
145
167
|
},
|
|
146
168
|
getEntryAsset(collection, slug, assetPath) {
|
|
147
|
-
return getEntryAssetOp(
|
|
169
|
+
return getEntryAssetOp(readDeps, collection, slug, assetPath)
|
|
148
170
|
},
|
|
149
171
|
getProjectAsset(assetPath) {
|
|
150
|
-
return getProjectAssetOp(
|
|
172
|
+
return getProjectAssetOp(readDeps, assetPath)
|
|
151
173
|
},
|
|
152
174
|
createEntry(input) {
|
|
153
|
-
return createEntryOp(entryDeps, input)
|
|
175
|
+
return mutate(over => createEntryOp(entryDeps(over), input))
|
|
154
176
|
},
|
|
155
177
|
updateEntry(input) {
|
|
156
|
-
return updateEntryOp(entryDeps, input)
|
|
178
|
+
return mutate(over => updateEntryOp(entryDeps(over), input))
|
|
157
179
|
},
|
|
158
180
|
deleteEntry(collection, slug) {
|
|
159
|
-
return deleteEntryOp(entryDeps, collection, slug)
|
|
181
|
+
return mutate(over => deleteEntryOp(entryDeps(over), collection, slug))
|
|
160
182
|
},
|
|
161
183
|
renameEntry(collection, from, to) {
|
|
162
|
-
return renameEntryOp(entryDeps, collection, from, to)
|
|
184
|
+
return mutate(over => renameEntryOp(entryDeps(over), collection, from, to))
|
|
163
185
|
},
|
|
164
186
|
addArrayItem(input) {
|
|
165
|
-
return addArrayItemOp(entryDeps, input)
|
|
187
|
+
return mutate(over => addArrayItemOp(entryDeps(over), input))
|
|
166
188
|
},
|
|
167
189
|
removeArrayItem(input) {
|
|
168
|
-
return removeArrayItemOp(entryDeps, input)
|
|
190
|
+
return mutate(over => removeArrayItemOp(entryDeps(over), input))
|
|
169
191
|
},
|
|
170
192
|
createPage(input) {
|
|
171
|
-
return createPageOp({ fs }, input)
|
|
193
|
+
return mutate(over => createPageOp({ fs: over }, input))
|
|
172
194
|
},
|
|
173
195
|
duplicatePage(input) {
|
|
174
|
-
return duplicatePageOp({ fs }, input)
|
|
196
|
+
return mutate(over => duplicatePageOp({ fs: over }, input))
|
|
175
197
|
},
|
|
176
198
|
deletePage(input) {
|
|
177
|
-
return deletePageOp({ fs }, input)
|
|
199
|
+
return mutate(over => deletePageOp({ fs: over }, input))
|
|
178
200
|
},
|
|
179
201
|
getLayouts() {
|
|
180
202
|
return getLayoutsOp({ fs })
|
|
@@ -183,13 +205,13 @@ export function createCmsCore(fs: CmsFileSystem, opts: CmsCoreOptions = {}): Cms
|
|
|
183
205
|
return listRedirectsOp({ fs })
|
|
184
206
|
},
|
|
185
207
|
addRedirect(input) {
|
|
186
|
-
return addRedirectOp({ fs }, input)
|
|
208
|
+
return mutate(over => addRedirectOp({ fs: over }, input))
|
|
187
209
|
},
|
|
188
210
|
updateRedirect(input) {
|
|
189
|
-
return updateRedirectOp({ fs }, input)
|
|
211
|
+
return mutate(over => updateRedirectOp({ fs: over }, input))
|
|
190
212
|
},
|
|
191
213
|
deleteRedirect(input) {
|
|
192
|
-
return deleteRedirectOp({ fs }, input)
|
|
214
|
+
return mutate(over => deleteRedirectOp({ fs: over }, input))
|
|
193
215
|
},
|
|
194
216
|
media: opts.media,
|
|
195
217
|
}
|
package/src/fs/node-fs.ts
CHANGED
|
@@ -127,6 +127,19 @@ function staticPrefixDir(pattern: string): string {
|
|
|
127
127
|
return staticSegments.join('/')
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
+
/** Write to a unique temp file in the same directory, then rename: a killed write leaves only the temp file, never a half-written target. */
|
|
131
|
+
async function writeAtomically(fullPath: string, content: string | Uint8Array): Promise<void> {
|
|
132
|
+
await fs.mkdir(path.dirname(fullPath), { recursive: true })
|
|
133
|
+
const tempPath = `${fullPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
|
|
134
|
+
try {
|
|
135
|
+
await fs.writeFile(tempPath, content)
|
|
136
|
+
await fs.rename(tempPath, fullPath)
|
|
137
|
+
} catch (error) {
|
|
138
|
+
await fs.rm(tempPath, { force: true })
|
|
139
|
+
throw error
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
130
143
|
/**
|
|
131
144
|
* Create a `CmsFileSystem` backed by `node:fs`, rooted at `root`.
|
|
132
145
|
* Every path is resolved relative to `root` and validated to stay within it.
|
|
@@ -145,18 +158,11 @@ export function createNodeFs(root: string): CmsFileSystem {
|
|
|
145
158
|
},
|
|
146
159
|
|
|
147
160
|
async writeFile(filePath, content) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
try {
|
|
154
|
-
await fs.writeFile(tempPath, content, 'utf-8')
|
|
155
|
-
await fs.rename(tempPath, fullPath)
|
|
156
|
-
} catch (error) {
|
|
157
|
-
await fs.rm(tempPath, { force: true })
|
|
158
|
-
throw error
|
|
159
|
-
}
|
|
161
|
+
await writeAtomically(resolve(filePath), content)
|
|
162
|
+
},
|
|
163
|
+
|
|
164
|
+
async writeBytes(filePath, content) {
|
|
165
|
+
await writeAtomically(resolve(filePath), content)
|
|
160
166
|
},
|
|
161
167
|
|
|
162
168
|
async rename(from, to) {
|
package/src/fs/staged.ts
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { globToRegExp } from './glob'
|
|
3
|
+
import type { CmsFileSystem } from './types'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Compare-and-commit for CMS mutations.
|
|
7
|
+
*
|
|
8
|
+
* A mutation runs over a staged view of the filesystem: reads go to the real filesystem and
|
|
9
|
+
* record what they saw, writes and removals stay in memory. When the mutation is done, its
|
|
10
|
+
* changeset goes to a commit function that applies the changes only if every file the mutation
|
|
11
|
+
* looked at is still as it saw it. A host whose files can also change by other means (an agent
|
|
12
|
+
* editing the same checkout) implements that commit atomically, so a CMS write never overwrites
|
|
13
|
+
* a change it did not see.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** What a mutation saw of a path. */
|
|
17
|
+
export type CmsFileVersion =
|
|
18
|
+
| { kind: 'absent' }
|
|
19
|
+
/** It existed. Recorded by `exists`/`stat`, which do not read the content. */
|
|
20
|
+
| { kind: 'present' }
|
|
21
|
+
/** Its bytes, as {@link digestBytes} gives them. */
|
|
22
|
+
| { kind: 'content'; digest: string }
|
|
23
|
+
|
|
24
|
+
export type CmsStagedChange = { kind: 'write'; path: string; content: Uint8Array } | { kind: 'remove'; path: string }
|
|
25
|
+
|
|
26
|
+
export interface CmsChangeset {
|
|
27
|
+
/** Each path the mutation read, tested or changed, with the version it first saw. Paths are root-relative, without a leading slash. */
|
|
28
|
+
readonly reads: ReadonlyMap<string, CmsFileVersion>
|
|
29
|
+
/** The final state of each changed path, in the order the paths were first changed. A rename is a removal plus a write. */
|
|
30
|
+
readonly changes: readonly CmsStagedChange[]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Applies a changeset when every path in `reads` still has the recorded version, and applies
|
|
35
|
+
* nothing otherwise, rejecting with {@link CmsCommitConflictError}. The check and the writes must
|
|
36
|
+
* not interleave with other writes to the same files.
|
|
37
|
+
*/
|
|
38
|
+
export type CmsCommit = (changeset: CmsChangeset) => Promise<void>
|
|
39
|
+
|
|
40
|
+
export class CmsCommitConflictError extends Error {
|
|
41
|
+
constructor(readonly paths: readonly string[]) {
|
|
42
|
+
super(`Changed since the edit read them: ${paths.join(', ')}`)
|
|
43
|
+
this.name = 'CmsCommitConflictError'
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `sha256:<hex>` of the bytes; for UTF-8 text, the same value the sidecar reports as a source hash. */
|
|
48
|
+
export function digestBytes(content: Uint8Array): string {
|
|
49
|
+
return `sha256:${createHash('sha256').update(content).digest('hex')}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface StagedFileSystem extends CmsFileSystem {
|
|
53
|
+
changeset(): CmsChangeset
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Root-relative, no leading slash, no `.` segments: one spelling per file, so a staged write is found again. */
|
|
57
|
+
function normalize(path: string): string {
|
|
58
|
+
const segments: string[] = []
|
|
59
|
+
for (const segment of path.split('/')) {
|
|
60
|
+
if (segment === '' || segment === '.') continue
|
|
61
|
+
if (segment === '..' && segments.length > 0 && segments.at(-1) !== '..') segments.pop()
|
|
62
|
+
else segments.push(segment)
|
|
63
|
+
}
|
|
64
|
+
return segments.join('/')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isBelow(path: string, dir: string): boolean {
|
|
68
|
+
return dir === '' || path.startsWith(`${dir}/`)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function missing(path: string): Error {
|
|
72
|
+
return Object.assign(new Error(`ENOENT: no such file, '${path}'`), { code: 'ENOENT' })
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createStagedFileSystem(base: CmsFileSystem): StagedFileSystem {
|
|
76
|
+
const reads = new Map<string, CmsFileVersion>()
|
|
77
|
+
const staged = new Map<string, { content: Uint8Array; mtimeMs: number } | null>()
|
|
78
|
+
const encoder = new TextEncoder()
|
|
79
|
+
const decoder = new TextDecoder()
|
|
80
|
+
|
|
81
|
+
/** Keeps the first version seen, except that content read later sharpens a bare `present`. */
|
|
82
|
+
function observe(path: string, version: CmsFileVersion): void {
|
|
83
|
+
const recorded = reads.get(path)
|
|
84
|
+
if (recorded === undefined || (recorded.kind === 'present' && version.kind === 'content')) reads.set(path, version)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A path changed without its content read first is fenced on its content from the moment it is changed. */
|
|
88
|
+
async function observeBeforeChange(path: string): Promise<void> {
|
|
89
|
+
if (staged.has(path)) return
|
|
90
|
+
const recorded = reads.get(path)
|
|
91
|
+
if (recorded !== undefined && recorded.kind !== 'present') return
|
|
92
|
+
observe(path, await versionOf(base, path))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function readBytes(rawPath: string): Promise<Uint8Array> {
|
|
96
|
+
const path = normalize(rawPath)
|
|
97
|
+
const change = staged.get(path)
|
|
98
|
+
if (change === null) throw missing(path)
|
|
99
|
+
if (change !== undefined) return change.content.slice()
|
|
100
|
+
try {
|
|
101
|
+
const content = await base.readBytes(path)
|
|
102
|
+
observe(path, { kind: 'content', digest: digestBytes(content) })
|
|
103
|
+
return content
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (!(await base.exists(path))) observe(path, { kind: 'absent' })
|
|
106
|
+
throw error
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function write(rawPath: string, content: Uint8Array): Promise<void> {
|
|
111
|
+
const path = normalize(rawPath)
|
|
112
|
+
await observeBeforeChange(path)
|
|
113
|
+
staged.set(path, { content: content.slice(), mtimeMs: Date.now() })
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function remove(rawPath: string): Promise<void> {
|
|
117
|
+
const path = normalize(rawPath)
|
|
118
|
+
await observeBeforeChange(path)
|
|
119
|
+
staged.set(path, null)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function stagedBelow(dir: string): string[] {
|
|
123
|
+
return [...staged].filter(([path, change]) => change !== null && isBelow(path, dir)).map(([path]) => path)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
async readFile(path) {
|
|
128
|
+
return decoder.decode(await readBytes(path))
|
|
129
|
+
},
|
|
130
|
+
readBytes,
|
|
131
|
+
writeFile(path, content) {
|
|
132
|
+
return write(path, encoder.encode(content))
|
|
133
|
+
},
|
|
134
|
+
writeBytes: write,
|
|
135
|
+
async rename(from, to) {
|
|
136
|
+
const content = await readBytes(from)
|
|
137
|
+
await remove(from)
|
|
138
|
+
await write(to, content)
|
|
139
|
+
},
|
|
140
|
+
remove,
|
|
141
|
+
async exists(rawPath) {
|
|
142
|
+
const path = normalize(rawPath)
|
|
143
|
+
const change = staged.get(path)
|
|
144
|
+
if (change !== undefined) return change !== null
|
|
145
|
+
if (stagedBelow(path).length > 0) return true
|
|
146
|
+
const exists = await base.exists(path)
|
|
147
|
+
observe(path, exists ? { kind: 'present' } : { kind: 'absent' })
|
|
148
|
+
return exists
|
|
149
|
+
},
|
|
150
|
+
async list(rawDir) {
|
|
151
|
+
const dir = normalize(rawDir)
|
|
152
|
+
const entries = new Map((await base.list(dir)).map(entry => [entry.name, entry.isDirectory]))
|
|
153
|
+
for (const [path, change] of staged) {
|
|
154
|
+
if (!isBelow(path, dir)) continue
|
|
155
|
+
const rest = dir === '' ? path : path.slice(dir.length + 1)
|
|
156
|
+
const [name, ...deeper] = rest.split('/')
|
|
157
|
+
if (name === undefined) continue
|
|
158
|
+
if (deeper.length > 0) {
|
|
159
|
+
if (change !== null) entries.set(name, true)
|
|
160
|
+
} else if (change === null) {
|
|
161
|
+
entries.delete(name)
|
|
162
|
+
} else {
|
|
163
|
+
entries.set(name, false)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return [...entries].map(([name, isDirectory]) => ({ name, isDirectory }))
|
|
167
|
+
},
|
|
168
|
+
async glob(pattern, options) {
|
|
169
|
+
const matcher = globToRegExp(pattern)
|
|
170
|
+
const files = new Set(await base.glob(pattern, options))
|
|
171
|
+
for (const [path, change] of staged) {
|
|
172
|
+
if (change === null) files.delete(path)
|
|
173
|
+
else if (matcher.test(path)) files.add(path)
|
|
174
|
+
}
|
|
175
|
+
return [...files]
|
|
176
|
+
},
|
|
177
|
+
async stat(rawPath) {
|
|
178
|
+
const path = normalize(rawPath)
|
|
179
|
+
const change = staged.get(path)
|
|
180
|
+
if (change === null) throw missing(path)
|
|
181
|
+
if (change !== undefined) return { mtimeMs: change.mtimeMs, size: change.content.byteLength }
|
|
182
|
+
const stat = await base.stat(path)
|
|
183
|
+
observe(path, { kind: 'present' })
|
|
184
|
+
return stat
|
|
185
|
+
},
|
|
186
|
+
changeset() {
|
|
187
|
+
const changes: CmsStagedChange[] = [...staged].map(([path, change]) =>
|
|
188
|
+
change === null ? { kind: 'remove', path } : { kind: 'write', path, content: change.content }
|
|
189
|
+
)
|
|
190
|
+
return { reads: new Map(reads), changes }
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The version of `path` now, in the terms {@link CmsFileVersion} records. */
|
|
196
|
+
export async function versionOf(fs: CmsFileSystem, path: string): Promise<CmsFileVersion> {
|
|
197
|
+
if (!(await fs.exists(path))) return { kind: 'absent' }
|
|
198
|
+
try {
|
|
199
|
+
return { kind: 'content', digest: digestBytes(await fs.readBytes(path)) }
|
|
200
|
+
} catch {
|
|
201
|
+
// A directory exists without content.
|
|
202
|
+
return { kind: 'present' }
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Whether a path whose version was `recorded` may be overwritten now that it is `current`. */
|
|
207
|
+
export function versionMatches(recorded: CmsFileVersion, current: CmsFileVersion): boolean {
|
|
208
|
+
if (recorded.kind === 'absent') return current.kind === 'absent'
|
|
209
|
+
if (recorded.kind === 'present') return current.kind !== 'absent'
|
|
210
|
+
return current.kind === 'content' && current.digest === recorded.digest
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* A commit over `fs` that checks the recorded versions and then applies the changes. It is atomic
|
|
215
|
+
* only when nothing else writes to `fs` between its awaits; a host with concurrent writers does
|
|
216
|
+
* both steps inside its own critical section instead.
|
|
217
|
+
*/
|
|
218
|
+
export function commitChangeset(fs: CmsFileSystem): CmsCommit {
|
|
219
|
+
return async ({ reads, changes }) => {
|
|
220
|
+
const conflicts: string[] = []
|
|
221
|
+
for (const [path, recorded] of reads) {
|
|
222
|
+
if (!versionMatches(recorded, await versionOf(fs, path))) conflicts.push(path)
|
|
223
|
+
}
|
|
224
|
+
if (conflicts.length > 0) throw new CmsCommitConflictError(conflicts)
|
|
225
|
+
for (const change of changes) {
|
|
226
|
+
if (change.kind === 'write') await fs.writeBytes(change.path, change.content)
|
|
227
|
+
else await fs.remove(change.path)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
package/src/fs/types.ts
CHANGED
|
@@ -38,6 +38,8 @@ export interface CmsFileSystem {
|
|
|
38
38
|
readBytes(path: string): Promise<Uint8Array>
|
|
39
39
|
/** Write a UTF-8 text file atomically (write temp + rename). Creates parent dirs. */
|
|
40
40
|
writeFile(path: string, content: string): Promise<void>
|
|
41
|
+
/** Write raw bytes (images and other binary assets) atomically, like `writeFile`. Creates parent dirs. */
|
|
42
|
+
writeBytes(path: string, content: Uint8Array): Promise<void>
|
|
41
43
|
/** Rename/move a file. Creates the destination's parent dir. */
|
|
42
44
|
rename(from: string, to: string): Promise<void>
|
|
43
45
|
/** Remove a file. No-op when it does not exist. */
|
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
withRenamedEntrySlug,
|
|
17
17
|
} from '../editor-write-model'
|
|
18
18
|
import type { CmsFileSystem } from '../fs/types'
|
|
19
|
-
import { mimeFromExt } from '../media/
|
|
19
|
+
import { mimeFromExt } from '../media/mime'
|
|
20
20
|
import { computeDerivedFieldUpdates, isPlainRecord, relativeImportPath, slugify } from '../shared'
|
|
21
21
|
|
|
22
22
|
/** Frontmatter file extensions that hold markdown content (vs. pure data files). */
|
|
@@ -7,9 +7,10 @@ import type {
|
|
|
7
7
|
UpdateRedirectRequest,
|
|
8
8
|
} from '@nuasite/cms-types'
|
|
9
9
|
import type { CmsFileSystem } from '../fs/types'
|
|
10
|
+
import { CMS_REDIRECTS_FILE, parseRedirectRule } from '../redirects'
|
|
10
11
|
|
|
11
12
|
const DEFAULT_STATUS_CODE = 307
|
|
12
|
-
const REDIRECTS_FILE =
|
|
13
|
+
const REDIRECTS_FILE = CMS_REDIRECTS_FILE
|
|
13
14
|
|
|
14
15
|
export interface RedirectOpsDeps {
|
|
15
16
|
fs: CmsFileSystem
|
|
@@ -23,15 +24,8 @@ export async function listRedirects(deps: RedirectOpsDeps): Promise<GetRedirects
|
|
|
23
24
|
export async function addRedirect(deps: RedirectOpsDeps, request: AddRedirectRequest): Promise<RedirectOperationResponse> {
|
|
24
25
|
const { source, destination, statusCode = DEFAULT_STATUS_CODE } = request
|
|
25
26
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
if (!source.startsWith('/')) {
|
|
30
|
-
return { success: false, error: 'Source must start with /' }
|
|
31
|
-
}
|
|
32
|
-
if (!destination.startsWith('/') && !destination.startsWith('http')) {
|
|
33
|
-
return { success: false, error: 'Destination must start with / or http' }
|
|
34
|
-
}
|
|
27
|
+
const invalid = ruleError(source, destination, statusCode)
|
|
28
|
+
if (invalid) return { success: false, error: invalid }
|
|
35
29
|
|
|
36
30
|
const lines = await readRedirectsFile(deps)
|
|
37
31
|
const existing = parseRedirectLines(lines)
|
|
@@ -48,9 +42,9 @@ export async function addRedirect(deps: RedirectOpsDeps, request: AddRedirectReq
|
|
|
48
42
|
export async function updateRedirect(deps: RedirectOpsDeps, request: UpdateRedirectRequest): Promise<RedirectOperationResponse> {
|
|
49
43
|
const { lineIndex, source, destination, statusCode = DEFAULT_STATUS_CODE } = request
|
|
50
44
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
45
|
+
// The same rules as adding: a line the editor list cannot show is one the editor cannot fix.
|
|
46
|
+
const invalid = ruleError(source, destination, statusCode)
|
|
47
|
+
if (invalid) return { success: false, error: invalid }
|
|
54
48
|
|
|
55
49
|
const lines = await readRedirectsFile(deps)
|
|
56
50
|
|
|
@@ -58,6 +52,14 @@ export async function updateRedirect(deps: RedirectOpsDeps, request: UpdateRedir
|
|
|
58
52
|
if (!currentLine || currentLine.startsWith('#')) {
|
|
59
53
|
return { success: false, error: 'Line at index is no longer a redirect rule — please refresh and try again' }
|
|
60
54
|
}
|
|
55
|
+
// The build keeps the first rule for a source, so moving a rule onto a source another rule already
|
|
56
|
+
// has would save and never apply. Editing a rule in place is always allowed, so a repeat already in
|
|
57
|
+
// the file can still be fixed.
|
|
58
|
+
const rules = parseRedirectLines(lines)
|
|
59
|
+
const current = rules.find(r => r.lineIndex === lineIndex)
|
|
60
|
+
if (current?.source !== source && rules.some(r => r.source === source && r.lineIndex !== lineIndex)) {
|
|
61
|
+
return { success: false, error: `Redirect already exists for ${source}` }
|
|
62
|
+
}
|
|
61
63
|
|
|
62
64
|
lines[lineIndex] = formatRedirectLine(source, destination, statusCode)
|
|
63
65
|
await writeRedirectsFile(deps, lines)
|
|
@@ -85,6 +87,17 @@ export async function deleteRedirect(deps: RedirectOpsDeps, request: DeleteRedir
|
|
|
85
87
|
|
|
86
88
|
// --- Internal helpers ---
|
|
87
89
|
|
|
90
|
+
function ruleError(source: string, destination: string, statusCode: number): string | undefined {
|
|
91
|
+
if (!source || !destination) return 'Source and destination are required'
|
|
92
|
+
if (/\s/.test(source) || /\s/.test(destination)) return 'Source and destination must not contain spaces'
|
|
93
|
+
if (!source.startsWith('/')) return 'Source must start with /'
|
|
94
|
+
// Editors redirect; proxying (200) and 4xx stay with code, which the build enforces too.
|
|
95
|
+
if (![301, 302, 303, 307, 308].includes(statusCode)) return 'Status must be a redirect: 301, 302, 303, 307 or 308'
|
|
96
|
+
// Read back the way the build reads it, so the editor never saves a rule the build would not apply.
|
|
97
|
+
if (!parseRedirectRule(formatRedirectLine(source, destination, statusCode))) return 'Destination must start with / or http:// or https://'
|
|
98
|
+
return undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
88
101
|
function formatRedirectLine(source: string, destination: string, statusCode: number): string {
|
|
89
102
|
return statusCode === DEFAULT_STATUS_CODE
|
|
90
103
|
? `${source} ${destination}`
|
|
@@ -118,21 +131,12 @@ function parseRedirectLines(lines: string[]): RedirectRule[] {
|
|
|
118
131
|
const line = lines[i]!.trim()
|
|
119
132
|
if (!line || line.startsWith('#')) continue
|
|
120
133
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const source = parts[0]!
|
|
125
|
-
if (!source.startsWith('/')) continue
|
|
126
|
-
|
|
127
|
-
const destination = parts[1]!
|
|
128
|
-
const statusCode = parts[2] ? parseInt(parts[2], 10) : DEFAULT_STATUS_CODE
|
|
134
|
+
// The same reading as the build's merge. The editor only manages rules whose source is a path.
|
|
135
|
+
const rule = parseRedirectRule(line)
|
|
136
|
+
if (!rule || !rule.source.startsWith('/')) continue
|
|
129
137
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
destination,
|
|
133
|
-
statusCode: Number.isNaN(statusCode) ? DEFAULT_STATUS_CODE : statusCode,
|
|
134
|
-
lineIndex: i,
|
|
135
|
-
})
|
|
138
|
+
const statusCode = rule.status ? parseInt(rule.status, 10) : DEFAULT_STATUS_CODE
|
|
139
|
+
rules.push({ source: rule.source, destination: rule.destination, statusCode, lineIndex: i })
|
|
136
140
|
}
|
|
137
141
|
|
|
138
142
|
return rules
|
package/src/index.ts
CHANGED
|
@@ -1,116 +1,3 @@
|
|
|
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'
|
|
11
|
-
export { checkContent, type CheckContentOptions, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check'
|
|
12
|
-
export {
|
|
13
|
-
collectionKind,
|
|
14
|
-
entryStem,
|
|
15
|
-
loadCollections,
|
|
16
|
-
type LoadedCollection,
|
|
17
|
-
type LoadedCollections,
|
|
18
|
-
type LoadedEntry,
|
|
19
|
-
normalizeBase,
|
|
20
|
-
parseEntry,
|
|
21
|
-
} from './check-entries'
|
|
22
|
-
export { checkAgainstSchemas, type LiveCheckInput } from './check-live'
|
|
23
|
-
export { checkFieldShapes, type ShapeCheckInput } from './check-shape'
|
|
24
|
-
export { checkEditorWrites, type WriteCheckInput } from './check-write'
|
|
25
|
-
export { collectionScanReport, scanCollections } from './collection-scanner'
|
|
26
|
-
export { scanComponentDefinitions } from './component-registry'
|
|
27
|
-
export {
|
|
28
|
-
classifyEmptyContentConfig,
|
|
29
|
-
CONTENT_CONFIG_PATHS,
|
|
30
|
-
type ContentConfigRead,
|
|
31
|
-
type DeclaredCollection,
|
|
32
|
-
type EmptyContentConfigReason,
|
|
33
|
-
type ParseCache,
|
|
34
|
-
parseConfigSource,
|
|
35
|
-
parseContentConfig,
|
|
36
|
-
type ParsedCollection,
|
|
37
|
-
type ParsedConfig,
|
|
38
|
-
type ParsedField,
|
|
39
|
-
type ParsedReference,
|
|
40
|
-
readContentConfig,
|
|
41
|
-
UNREAD_CONTENT_CONFIG_PATHS,
|
|
42
|
-
} from './content-config-ast'
|
|
43
|
-
export { createCmsCore } from './core'
|
|
44
|
-
export type { CmsCore, CmsCoreOptions } from './core'
|
|
45
|
-
export {
|
|
46
|
-
applyCreateRouteFields,
|
|
47
|
-
blankFieldValue,
|
|
48
|
-
blankRequiredFields,
|
|
49
|
-
type CollectionKind,
|
|
50
|
-
type CreateWriteField,
|
|
51
|
-
isBlankFieldValue,
|
|
52
|
-
newEntryFrontmatter,
|
|
53
|
-
newRepeaterItem,
|
|
54
|
-
normalizeCreateWrite,
|
|
55
|
-
omitEmptyOnCreate,
|
|
56
|
-
type RepeaterItemField,
|
|
57
|
-
type RequiredGuardField,
|
|
58
|
-
seedValueForRequiredField,
|
|
59
|
-
withoutBlankArrayItems,
|
|
60
|
-
type WriteModelField,
|
|
61
|
-
} from './editor-write-model'
|
|
62
|
-
export { globMayMatchUnder, globToRegExp, UnreadableDirectoryError } from './fs/glob'
|
|
63
1
|
export { createNodeFs } from './fs/node-fs'
|
|
64
|
-
export
|
|
65
|
-
export
|
|
66
|
-
type AddArrayItemInput,
|
|
67
|
-
type CreateEntryInput,
|
|
68
|
-
ensureMdxImports,
|
|
69
|
-
type EntryAsset,
|
|
70
|
-
type EntryOpsDeps,
|
|
71
|
-
type GetEntryResult,
|
|
72
|
-
parseFrontmatter,
|
|
73
|
-
type RemoveArrayItemInput,
|
|
74
|
-
serializeFrontmatter,
|
|
75
|
-
type UpdateEntryInput,
|
|
76
|
-
} from './handlers/entry-ops'
|
|
77
|
-
export {
|
|
78
|
-
type ContemberStorageOptions,
|
|
79
|
-
createContemberStorageAdapter,
|
|
80
|
-
createLocalStorageAdapter,
|
|
81
|
-
createS3StorageAdapter,
|
|
82
|
-
decodeFilteredMediaCursor,
|
|
83
|
-
getFileExtension,
|
|
84
|
-
isUnsafeFolder,
|
|
85
|
-
listFilteredMedia,
|
|
86
|
-
listProjectImages,
|
|
87
|
-
type ListProjectImagesOptions,
|
|
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,
|
|
96
|
-
MIME_BY_EXT,
|
|
97
|
-
mimeFromExt,
|
|
98
|
-
parseMediaTypeFilter,
|
|
99
|
-
type S3StorageOptions,
|
|
100
|
-
uploadsDirRelativeToRoot,
|
|
101
|
-
} from './media/index'
|
|
102
|
-
export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast'
|
|
103
|
-
export { type RouteCollectionScan, scanRouteCollections } from './route-scan'
|
|
104
|
-
export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port'
|
|
105
|
-
export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe'
|
|
106
|
-
export {
|
|
107
|
-
applyDerivedTransform,
|
|
108
|
-
computeDerivedFieldUpdates,
|
|
109
|
-
computePathnameFromSpec,
|
|
110
|
-
type DerivedFieldSpec,
|
|
111
|
-
escapeHtml,
|
|
112
|
-
relativeImportPath,
|
|
113
|
-
resolvePathnameFromSpec,
|
|
114
|
-
slugify,
|
|
115
|
-
slugifyHref,
|
|
116
|
-
} from './shared'
|
|
2
|
+
export { createLocalStorageAdapter, type LocalStorageOptions } from './media/local'
|
|
3
|
+
export * from './portable'
|