@crombolo/server 0.27.0 → 0.29.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/package.json +12 -12
- package/src/bundle-build.ts +139 -0
- package/src/bundle-reload.ts +84 -0
- package/src/config.ts +17 -1
- package/src/database.ts +4 -4
- package/src/index.ts +4 -0
- package/src/marketplace.ts +14 -3
- package/src/media-folders.ts +32 -0
- package/src/schema.ts +0 -6
- package/src/seed/compile.ts +745 -0
- package/src/seed/export.ts +416 -0
- package/src/seed/index.ts +5 -0
- package/src/seed/keys.ts +35 -0
- package/src/seed/lines.ts +58 -0
- package/src/seed/read.ts +175 -0
- package/src/server.ts +23 -1
- package/src/settings.ts +13 -0
- package/src/webhook-files.ts +50 -13
- package/src/webhooks.ts +59 -6
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content already in a site, written out as seed files (stories 163, 164), so
|
|
3
|
+
* an existing site can move to seeds. Pages go to `seed/content/`, Library
|
|
4
|
+
* elements to `seed/library/`, and media, files and all, to `seed/media/`.
|
|
5
|
+
*
|
|
6
|
+
* Values are written in the shorthand `seed apply` reads back — rich text as
|
|
7
|
+
* `{ html }`, pickers and links as paths to what the export carries, blocks as
|
|
8
|
+
* `{ type, key, values }` — and in their editor's stored shape where there is
|
|
9
|
+
* none. A node keeps its key in its file wherever it is not the one its path
|
|
10
|
+
* would derive, so a round trip names the same nodes.
|
|
11
|
+
*/
|
|
12
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { mediaFileOf, normaliseUuid, ObjectTypes } from '@crombolo/core'
|
|
15
|
+
import {
|
|
16
|
+
ContentTypeRepository,
|
|
17
|
+
currentSchemaState,
|
|
18
|
+
DataTypeRepository,
|
|
19
|
+
type Db,
|
|
20
|
+
DocumentRepository,
|
|
21
|
+
NodeRepository,
|
|
22
|
+
type NodeRow,
|
|
23
|
+
} from '@crombolo/data'
|
|
24
|
+
import type { MediaFileStore } from '../media-files.ts'
|
|
25
|
+
import { pickKey, seedKey } from './keys.ts'
|
|
26
|
+
|
|
27
|
+
/** A URL segment from a name: `About us` → `about-us`. */
|
|
28
|
+
export const segmentOf = (name: string) =>
|
|
29
|
+
name
|
|
30
|
+
.normalize('NFKD')
|
|
31
|
+
.replace(/[̀-ͯ]/g, '')
|
|
32
|
+
.toLowerCase()
|
|
33
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
34
|
+
.replace(/^-+|-+$/g, '') || 'item'
|
|
35
|
+
|
|
36
|
+
/** A media file or folder name as it can sit on disk. */
|
|
37
|
+
const fileName = (name: string) => name.replace(/[/\\:*?"<>|]+/g, '-').trim() || 'item'
|
|
38
|
+
|
|
39
|
+
const bareKey = (key: string) => (/^[A-Za-z0-9_-]+$/.test(key) ? key : JSON.stringify(key))
|
|
40
|
+
|
|
41
|
+
/** A value as TOML, inline. Nulls are left out: TOML has none. */
|
|
42
|
+
export function tomlValue(value: unknown): string | undefined {
|
|
43
|
+
if (value === null || value === undefined) return undefined
|
|
44
|
+
if (typeof value === 'string') return JSON.stringify(value)
|
|
45
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
|
|
46
|
+
if (value instanceof Date) return value.toISOString()
|
|
47
|
+
if (Array.isArray(value))
|
|
48
|
+
return `[${value
|
|
49
|
+
.map(tomlValue)
|
|
50
|
+
.filter((v) => v !== undefined)
|
|
51
|
+
.join(', ')}]`
|
|
52
|
+
if (typeof value === 'object') {
|
|
53
|
+
const entries = Object.entries(value as Record<string, unknown>).flatMap(([k, v]) => {
|
|
54
|
+
const written = tomlValue(v)
|
|
55
|
+
return written === undefined ? [] : [`${bareKey(k)} = ${written}`]
|
|
56
|
+
})
|
|
57
|
+
return `{ ${entries.join(', ')} }`
|
|
58
|
+
}
|
|
59
|
+
return JSON.stringify(String(value))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
63
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
64
|
+
|
|
65
|
+
const PICKER = /^umb:\/\/document\/([0-9a-f]{32})$/i
|
|
66
|
+
const dashed = (hex: string) =>
|
|
67
|
+
`${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
|
68
|
+
|
|
69
|
+
/** What a media item's own properties are, which its file stands for in a seed. */
|
|
70
|
+
const FILE_PROPERTIES = new Set([
|
|
71
|
+
'umbracoFile',
|
|
72
|
+
'umbracoWidth',
|
|
73
|
+
'umbracoHeight',
|
|
74
|
+
'umbracoBytes',
|
|
75
|
+
'umbracoExtension',
|
|
76
|
+
])
|
|
77
|
+
|
|
78
|
+
export interface SeedExportOptions {
|
|
79
|
+
/** The pages to export, each with every page below it. */
|
|
80
|
+
pages: readonly NodeRow[]
|
|
81
|
+
/** Every Library element too. */
|
|
82
|
+
library?: boolean
|
|
83
|
+
/** Every media item too, with its file. */
|
|
84
|
+
media?: boolean
|
|
85
|
+
/** Where media files are read from; media is exported without files when absent. */
|
|
86
|
+
files?: MediaFileStore
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface SeedExportResult {
|
|
90
|
+
written: string[]
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function exportSeed(
|
|
94
|
+
db: Db,
|
|
95
|
+
siteDir: string,
|
|
96
|
+
options: SeedExportOptions,
|
|
97
|
+
): Promise<SeedExportResult> {
|
|
98
|
+
const state = await currentSchemaState(db)
|
|
99
|
+
const nodeState = { version: state.version, revision: state.revision }
|
|
100
|
+
const repos = {
|
|
101
|
+
content: new DocumentRepository(db, { nodeState }),
|
|
102
|
+
library: new DocumentRepository(db, { nodeState, kind: 'element' }),
|
|
103
|
+
media: new DocumentRepository(db, { nodeState, kind: 'media' }),
|
|
104
|
+
}
|
|
105
|
+
const nodes = new NodeRepository(db)
|
|
106
|
+
const documentTypes = new ContentTypeRepository(db)
|
|
107
|
+
const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
|
|
108
|
+
const dataTypes = new DataTypeRepository(db)
|
|
109
|
+
|
|
110
|
+
const typeAliases = new Map<string, string>()
|
|
111
|
+
const aliasOf = async (typeKey: string) => {
|
|
112
|
+
const key = normaliseUuid(typeKey)
|
|
113
|
+
if (!typeAliases.has(key)) {
|
|
114
|
+
const rows = await db.query<{ alias: string }>(
|
|
115
|
+
'SELECT ct.alias FROM node n JOIN content_type ct ON ct.node_id = n.id WHERE n.unique_id = ?',
|
|
116
|
+
[key],
|
|
117
|
+
)
|
|
118
|
+
typeAliases.set(key, rows[0] ? String(rows[0].alias) : typeKey)
|
|
119
|
+
}
|
|
120
|
+
return typeAliases.get(key) as string
|
|
121
|
+
}
|
|
122
|
+
const editorCache = new Map<string, Map<string, string>>()
|
|
123
|
+
const editorsOf = async (typeKey: string, media = false) => {
|
|
124
|
+
const key = normaliseUuid(typeKey)
|
|
125
|
+
const cached = editorCache.get(key)
|
|
126
|
+
if (cached) return cached
|
|
127
|
+
const properties = await (media ? mediaTypes : documentTypes).resolveProperties(key)
|
|
128
|
+
const byType = new Map(
|
|
129
|
+
(await dataTypes.byKeys(properties.map((p) => p.dataTypeKey))).map((d) => [
|
|
130
|
+
d.key,
|
|
131
|
+
d.editorAlias,
|
|
132
|
+
]),
|
|
133
|
+
)
|
|
134
|
+
const out = new Map<string, string>()
|
|
135
|
+
for (const property of properties) {
|
|
136
|
+
const editor = byType.get(property.dataTypeKey)
|
|
137
|
+
if (editor) out.set(property.alias, editor)
|
|
138
|
+
}
|
|
139
|
+
editorCache.set(key, out)
|
|
140
|
+
return out
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// --------------------------------------------------- every node's place
|
|
144
|
+
type Kind = 'content' | 'library' | 'media'
|
|
145
|
+
type Entry = { kind: Kind; node: NodeRow; path: string; order: number }
|
|
146
|
+
const entries: Entry[] = []
|
|
147
|
+
const pathOf = new Map<string, { kind: Kind; path: string }>()
|
|
148
|
+
const taken = new Set<string>()
|
|
149
|
+
const place = (kind: Kind, node: NodeRow, parent: string | null, order: number, base: string) => {
|
|
150
|
+
const dot = kind === 'media' ? base.lastIndexOf('.') : -1
|
|
151
|
+
let name = base
|
|
152
|
+
for (let n = 2; taken.has(`${kind}/${parent ? `${parent}/` : ''}${name}`); n++)
|
|
153
|
+
name = dot > 0 ? `${base.slice(0, dot)}-${n}${base.slice(dot)}` : `${base}-${n}`
|
|
154
|
+
const path = parent ? `${parent}/${name}` : name
|
|
155
|
+
taken.add(`${kind}/${path}`)
|
|
156
|
+
pathOf.set(normaliseUuid(node.key), { kind, path })
|
|
157
|
+
entries.push({ kind, node, path, order })
|
|
158
|
+
return path
|
|
159
|
+
}
|
|
160
|
+
const walkPages = async (node: NodeRow, parent: string | null, order: number) => {
|
|
161
|
+
const path = place('content', node, parent, order, segmentOf(node.text ?? node.key))
|
|
162
|
+
const children = await nodes.children(node.id, ObjectTypes.Document, 0, Number.MAX_SAFE_INTEGER)
|
|
163
|
+
for (const [index, child] of children.items.entries()) await walkPages(child, path, index)
|
|
164
|
+
}
|
|
165
|
+
for (const [index, root] of options.pages.entries()) await walkPages(root, null, index)
|
|
166
|
+
|
|
167
|
+
if (options.library) {
|
|
168
|
+
const roots = await nodes.children(-1, ObjectTypes.Element, 0, Number.MAX_SAFE_INTEGER)
|
|
169
|
+
for (const [index, element] of roots.items.entries())
|
|
170
|
+
place('library', element, null, index, segmentOf(element.text ?? element.key))
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const mediaFile = new Map<string, string>()
|
|
174
|
+
if (options.media) {
|
|
175
|
+
const walkMedia = async (parentId: number, parent: string | null) => {
|
|
176
|
+
const children = await nodes.children(parentId, ObjectTypes.Media, 0, Number.MAX_SAFE_INTEGER)
|
|
177
|
+
for (const [index, child] of children.items.entries()) {
|
|
178
|
+
const item = await repos.media.byKey(child.key)
|
|
179
|
+
const src = item ? mediaFileOf(item) : null
|
|
180
|
+
if (src) mediaFile.set(child.key, src)
|
|
181
|
+
const base = src
|
|
182
|
+
? fileName(src.split('/').at(-1) as string)
|
|
183
|
+
: fileName(child.text ?? child.key)
|
|
184
|
+
const path = place('media', child, parent, index, base)
|
|
185
|
+
if (!src) await walkMedia(child.id, path)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
await walkMedia(-1, null)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const where = (key: string, kind: Kind) => {
|
|
192
|
+
const found = pathOf.get(normaliseUuid(key))
|
|
193
|
+
return found && found.kind === kind ? found.path : undefined
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// -------------------------------------------------- values, as shorthand
|
|
197
|
+
const shorthand = async (editor: string, value: unknown): Promise<unknown> => {
|
|
198
|
+
switch (editor) {
|
|
199
|
+
case 'Umbraco.RichText':
|
|
200
|
+
case 'Umbraco.TinyMCE':
|
|
201
|
+
return isRecord(value) && typeof value.markup === 'string' && value.blocks == null
|
|
202
|
+
? { html: value.markup }
|
|
203
|
+
: value
|
|
204
|
+
case 'Umbraco.ContentPicker': {
|
|
205
|
+
const picked = typeof value === 'string' ? PICKER.exec(value) : null
|
|
206
|
+
if (!picked) return value
|
|
207
|
+
const key = dashed((picked[1] as string).toLowerCase())
|
|
208
|
+
const path = where(key, 'content')
|
|
209
|
+
return path ? `/${path}` : key
|
|
210
|
+
}
|
|
211
|
+
case 'Umbraco.MediaPicker3': {
|
|
212
|
+
if (!Array.isArray(value)) return value
|
|
213
|
+
const paths = value.map((pick) =>
|
|
214
|
+
isRecord(pick) &&
|
|
215
|
+
typeof pick.mediaKey === 'string' &&
|
|
216
|
+
pick.key === pickKey(pick.mediaKey) &&
|
|
217
|
+
Array.isArray(pick.crops) &&
|
|
218
|
+
pick.crops.length === 0 &&
|
|
219
|
+
pick.focalPoint == null
|
|
220
|
+
? where(pick.mediaKey, 'media')
|
|
221
|
+
: undefined,
|
|
222
|
+
)
|
|
223
|
+
if (paths.length === 0 || paths.some((p) => p === undefined)) return value
|
|
224
|
+
const full = paths.map((p) => `/${p}`)
|
|
225
|
+
return full.length === 1 ? full[0] : full
|
|
226
|
+
}
|
|
227
|
+
case 'Umbraco.ElementPicker': {
|
|
228
|
+
if (!Array.isArray(value)) return value
|
|
229
|
+
const paths = value.map((key) =>
|
|
230
|
+
typeof key === 'string' ? where(key, 'library') : undefined,
|
|
231
|
+
)
|
|
232
|
+
if (paths.length === 0 || paths.some((p) => p === undefined)) return value
|
|
233
|
+
return paths.length === 1 ? paths[0] : paths
|
|
234
|
+
}
|
|
235
|
+
case 'Umbraco.MultiUrlPicker': {
|
|
236
|
+
if (!Array.isArray(value)) return value
|
|
237
|
+
return value.map((link) => {
|
|
238
|
+
if (!isRecord(link)) return link
|
|
239
|
+
const target = link.target ?? null
|
|
240
|
+
if (
|
|
241
|
+
link.type === 'document' &&
|
|
242
|
+
typeof link.unique === 'string' &&
|
|
243
|
+
target === null &&
|
|
244
|
+
!link.url &&
|
|
245
|
+
!link.queryString
|
|
246
|
+
) {
|
|
247
|
+
const path = where(link.unique, 'content')
|
|
248
|
+
if (path && (link.name === '' || link.name == null)) return `/${path}`
|
|
249
|
+
if (path && typeof link.name === 'string') return { path: `/${path}`, name: link.name }
|
|
250
|
+
}
|
|
251
|
+
if (link.type === 'external' && typeof link.url === 'string' && target === null)
|
|
252
|
+
return { url: link.url, name: link.name ?? link.url }
|
|
253
|
+
return link
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
case 'Umbraco.BlockList':
|
|
257
|
+
case 'Umbraco.BlockGrid':
|
|
258
|
+
return blocks(editor, value)
|
|
259
|
+
default:
|
|
260
|
+
return value
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Blocks as `{ type, key, values, settings }`, when their layout is plain enough to say so. */
|
|
265
|
+
const blocks = async (editor: string, value: unknown): Promise<unknown> => {
|
|
266
|
+
if (!isRecord(value) || !isRecord(value.layout) || !Array.isArray(value.contentData))
|
|
267
|
+
return value
|
|
268
|
+
const layout = value.layout[editor]
|
|
269
|
+
if (!Array.isArray(layout)) return value
|
|
270
|
+
const content = new Map(
|
|
271
|
+
(value.contentData as unknown[]).filter(isRecord).map((d) => [String(d.key), d]),
|
|
272
|
+
)
|
|
273
|
+
const settings = new Map(
|
|
274
|
+
((value.settingsData as unknown[] | undefined) ?? [])
|
|
275
|
+
.filter(isRecord)
|
|
276
|
+
.map((d) => [String(d.key), d]),
|
|
277
|
+
)
|
|
278
|
+
const out: unknown[] = []
|
|
279
|
+
for (const item of layout) {
|
|
280
|
+
if (!isRecord(item)) return value
|
|
281
|
+
const data = content.get(String(item.contentKey))
|
|
282
|
+
if (!data || typeof data.contentTypeKey !== 'string') return value
|
|
283
|
+
if (editor === 'Umbraco.BlockGrid' && Array.isArray(item.areas) && item.areas.length > 0)
|
|
284
|
+
return value
|
|
285
|
+
const entry: Record<string, unknown> = {
|
|
286
|
+
type: await aliasOf(data.contentTypeKey),
|
|
287
|
+
key: item.contentKey,
|
|
288
|
+
values: await elementValues(data),
|
|
289
|
+
}
|
|
290
|
+
if (typeof item.settingsKey === 'string') {
|
|
291
|
+
const setting = settings.get(item.settingsKey)
|
|
292
|
+
if (!setting || typeof setting.contentTypeKey !== 'string') return value
|
|
293
|
+
entry.settings = {
|
|
294
|
+
type: await aliasOf(setting.contentTypeKey),
|
|
295
|
+
key: item.settingsKey,
|
|
296
|
+
values: await elementValues(setting),
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (editor === 'Umbraco.BlockGrid') {
|
|
300
|
+
entry.columns = item.columnSpan
|
|
301
|
+
entry.rows = item.rowSpan
|
|
302
|
+
}
|
|
303
|
+
out.push(entry)
|
|
304
|
+
}
|
|
305
|
+
return out
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const elementValues = async (data: Record<string, unknown>) => {
|
|
309
|
+
const editors = await editorsOf(String(data.contentTypeKey))
|
|
310
|
+
const out: Record<string, unknown> = {}
|
|
311
|
+
for (const v of (data.values as unknown[] | undefined) ?? []) {
|
|
312
|
+
if (!isRecord(v) || typeof v.alias !== 'string') continue
|
|
313
|
+
const editor = editors.get(v.alias)
|
|
314
|
+
out[v.alias] = editor ? await shorthand(editor, v.value) : v.value
|
|
315
|
+
}
|
|
316
|
+
return out
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// --------------------------------------------------------- the files
|
|
320
|
+
const written: string[] = []
|
|
321
|
+
const write = (relative: string, text: string) => {
|
|
322
|
+
const file = join(siteDir, 'seed', relative)
|
|
323
|
+
mkdirSync(join(file, '..'), { recursive: true })
|
|
324
|
+
writeFileSync(file, text)
|
|
325
|
+
written.push(`seed/${relative}`)
|
|
326
|
+
}
|
|
327
|
+
const valueLines = async (
|
|
328
|
+
values: ReadonlyArray<{
|
|
329
|
+
alias: string
|
|
330
|
+
culture: string | null
|
|
331
|
+
segment: string | null
|
|
332
|
+
value: unknown
|
|
333
|
+
}>,
|
|
334
|
+
editors: ReadonlyMap<string, string>,
|
|
335
|
+
) => {
|
|
336
|
+
const byCulture = new Map<string | null, string[]>()
|
|
337
|
+
for (const v of values) {
|
|
338
|
+
if (v.segment !== null) continue
|
|
339
|
+
const value = await shorthand(editors.get(v.alias) ?? '', v.value)
|
|
340
|
+
const text = tomlValue(value)
|
|
341
|
+
if (text === undefined) continue
|
|
342
|
+
const list = byCulture.get(v.culture) ?? []
|
|
343
|
+
// A long list reads better an item to a line; TOML allows that for arrays.
|
|
344
|
+
list.push(
|
|
345
|
+
Array.isArray(value) && text.length > 100
|
|
346
|
+
? `${bareKey(v.alias)} = [\n${value
|
|
347
|
+
.map(tomlValue)
|
|
348
|
+
.filter((item) => item !== undefined)
|
|
349
|
+
.map((item) => ` ${item},`)
|
|
350
|
+
.join('\n')}\n]`
|
|
351
|
+
: `${bareKey(v.alias)} = ${text}`,
|
|
352
|
+
)
|
|
353
|
+
byCulture.set(v.culture, list)
|
|
354
|
+
}
|
|
355
|
+
const lines: string[] = []
|
|
356
|
+
for (const [culture, list] of byCulture)
|
|
357
|
+
lines.push('', culture ? `[values.${bareKey(culture)}]` : '[values]', ...list)
|
|
358
|
+
return lines
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
for (const { kind, node, path, order } of entries) {
|
|
362
|
+
const doc = await repos[kind].byKey(node.key)
|
|
363
|
+
const derived = seedKey(`${kind}/${path}`)
|
|
364
|
+
const lines: string[] = []
|
|
365
|
+
if (kind === 'media') {
|
|
366
|
+
const src = mediaFile.get(node.key)
|
|
367
|
+
if (!src) {
|
|
368
|
+
// A folder: its directory says it, unless it has a name or key of its own.
|
|
369
|
+
mkdirSync(join(siteDir, 'seed', 'media', path), { recursive: true })
|
|
370
|
+
continue
|
|
371
|
+
}
|
|
372
|
+
const stored = options.files ? await options.files.open(src) : undefined
|
|
373
|
+
if (stored) {
|
|
374
|
+
const file = join(siteDir, 'seed', 'media', path)
|
|
375
|
+
mkdirSync(join(file, '..'), { recursive: true })
|
|
376
|
+
writeFileSync(file, await stored.bytes())
|
|
377
|
+
written.push(`seed/media/${path}`)
|
|
378
|
+
}
|
|
379
|
+
// A sidecar only for what the file cannot say.
|
|
380
|
+
if (normaliseUuid(node.key) !== derived) lines.push(`key = ${JSON.stringify(node.key)}`)
|
|
381
|
+
lines.push(`order = ${order}`)
|
|
382
|
+
const name = doc?.variants[0]?.name
|
|
383
|
+
if (name && name !== path.split('/').at(-1)) lines.push(`name = ${JSON.stringify(name)}`)
|
|
384
|
+
const file = doc?.values.find((v) => v.alias === 'umbracoFile')?.value
|
|
385
|
+
if (isRecord(file) && isRecord(file.focalPoint))
|
|
386
|
+
lines.push(`focalPoint = ${tomlValue(file.focalPoint)}`)
|
|
387
|
+
if (doc) {
|
|
388
|
+
const editors = await editorsOf(doc.contentTypeKey, true)
|
|
389
|
+
lines.push(
|
|
390
|
+
...(await valueLines(
|
|
391
|
+
doc.values.filter((v) => !FILE_PROPERTIES.has(v.alias)),
|
|
392
|
+
editors,
|
|
393
|
+
)),
|
|
394
|
+
)
|
|
395
|
+
}
|
|
396
|
+
if (lines.length > 0) write(`media/${path}.toml`, `${lines.join('\n')}\n`)
|
|
397
|
+
continue
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
if (!doc) continue
|
|
401
|
+
lines.push(`type = ${JSON.stringify(await aliasOf(doc.contentTypeKey))}`)
|
|
402
|
+
if (normaliseUuid(node.key) !== derived) lines.push(`key = ${JSON.stringify(node.key)}`)
|
|
403
|
+
const invariant = doc.variants.find((v) => v.culture === null)
|
|
404
|
+
if (invariant) lines.push(`name = ${JSON.stringify(invariant.name)}`)
|
|
405
|
+
else
|
|
406
|
+
lines.push(
|
|
407
|
+
`name = ${tomlValue(Object.fromEntries(doc.variants.map((v) => [v.culture as string, v.name])))}`,
|
|
408
|
+
)
|
|
409
|
+
lines.push(`order = ${order}`)
|
|
410
|
+
if (!doc.variants.some((v) => v.state === 'Published' || v.state === 'PublishedPendingChanges'))
|
|
411
|
+
lines.push('published = false')
|
|
412
|
+
lines.push(...(await valueLines(doc.values, await editorsOf(doc.contentTypeKey))))
|
|
413
|
+
write(`${kind}/${path}.toml`, `${lines.join('\n')}\n`)
|
|
414
|
+
}
|
|
415
|
+
return { written }
|
|
416
|
+
}
|
package/src/seed/keys.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keys for seed items (story 163): RFC 4122 version 5 uuids, named by kind and
|
|
3
|
+
* path under one fixed namespace, so a rebuild names the same node and two
|
|
4
|
+
* sites built from the same seed share keys.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto'
|
|
7
|
+
import { SEED_NAMESPACE, uuidV5 } from '@crombolo/core'
|
|
8
|
+
|
|
9
|
+
export { SEED_NAMESPACE, uuidV5 }
|
|
10
|
+
|
|
11
|
+
/** The key a seed item has when its file gives none: `content/about/team`, `media/logos/mark.png`. */
|
|
12
|
+
export const seedKey = (path: string) => uuidV5(path, SEED_NAMESPACE)
|
|
13
|
+
|
|
14
|
+
/** The key of a block inside an item's value: stable for the item, the property and the position. */
|
|
15
|
+
export const blockKey = (owner: string, where: string) =>
|
|
16
|
+
uuidV5(`${owner}#${where}`, SEED_NAMESPACE)
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A media picker item's own key: a uuid-shaped sha256 of the media key, the
|
|
20
|
+
* formula the demo sites' pickers have always used, so a seed reproduces them.
|
|
21
|
+
*/
|
|
22
|
+
export function pickKey(mediaKey: string): string {
|
|
23
|
+
const hex = createHash('sha256')
|
|
24
|
+
.update(`pick:${normaliseKey(mediaKey)}`)
|
|
25
|
+
.digest('hex')
|
|
26
|
+
return [
|
|
27
|
+
hex.slice(0, 8),
|
|
28
|
+
hex.slice(8, 12),
|
|
29
|
+
`4${hex.slice(13, 16)}`,
|
|
30
|
+
`8${hex.slice(17, 20)}`,
|
|
31
|
+
hex.slice(20, 32),
|
|
32
|
+
].join('-')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const normaliseKey = (key: string) => key.toLowerCase()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a key sits in a seed file (story 163). `Bun.TOML` parses without
|
|
3
|
+
* positions, so a finding's line is found by reading the file the way TOML is
|
|
4
|
+
* laid out: a `[table]` header, then `key = value` lines under it. Good enough
|
|
5
|
+
* for the shapes seeds use; anything it cannot place is line 1.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const unquote = (part: string) =>
|
|
9
|
+
part
|
|
10
|
+
.trim()
|
|
11
|
+
.replace(/^"(.*)"$/, '$1')
|
|
12
|
+
.replace(/^'(.*)'$/, '$1')
|
|
13
|
+
|
|
14
|
+
const splitDotted = (text: string): string[] => {
|
|
15
|
+
const parts: string[] = []
|
|
16
|
+
let current = ''
|
|
17
|
+
let quote: string | null = null
|
|
18
|
+
for (const char of text) {
|
|
19
|
+
if (quote) {
|
|
20
|
+
if (char === quote) quote = null
|
|
21
|
+
current += char
|
|
22
|
+
} else if (char === '"' || char === "'") {
|
|
23
|
+
quote = char
|
|
24
|
+
current += char
|
|
25
|
+
} else if (char === '.') {
|
|
26
|
+
parts.push(unquote(current))
|
|
27
|
+
current = ''
|
|
28
|
+
} else current += char
|
|
29
|
+
}
|
|
30
|
+
parts.push(unquote(current))
|
|
31
|
+
return parts.filter((part) => part.length > 0)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The 1-based line of a dotted path (`['values', 'en-US', 'title']`) in a TOML text. */
|
|
35
|
+
export function lineOf(text: string, path: readonly string[]): number {
|
|
36
|
+
if (path.length === 0) return 1
|
|
37
|
+
const lines = text.split('\n')
|
|
38
|
+
let table: string[] = []
|
|
39
|
+
let best = 0
|
|
40
|
+
for (const [index, raw] of lines.entries()) {
|
|
41
|
+
const line = raw.trim()
|
|
42
|
+
if (line.startsWith('#') || line === '') continue
|
|
43
|
+
const header = /^\[\[?\s*([^\]]+?)\s*\]\]?$/.exec(line)
|
|
44
|
+
if (header) {
|
|
45
|
+
table = splitDotted(header[1] as string)
|
|
46
|
+
if (table.length <= path.length && table.every((part, i) => part === path[i]))
|
|
47
|
+
if (table.length === path.length) return index + 1
|
|
48
|
+
else if (best === 0) best = index + 1
|
|
49
|
+
continue
|
|
50
|
+
}
|
|
51
|
+
const assignment = /^((?:"[^"]*"|'[^']*'|[^=])+?)\s*=/.exec(line)
|
|
52
|
+
if (!assignment) continue
|
|
53
|
+
const full = [...table, ...splitDotted(assignment[1] as string)]
|
|
54
|
+
if (full.length === path.length && full.every((part, i) => part === path[i])) return index + 1
|
|
55
|
+
if (full.length < path.length && full.every((part, i) => part === path[i])) return index + 1
|
|
56
|
+
}
|
|
57
|
+
return best || 1
|
|
58
|
+
}
|
package/src/seed/read.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a site's `seed/` directory (story 163) into items: the content tree
|
|
3
|
+
* from `seed/content/`, Library elements from `seed/library/`, and media files
|
|
4
|
+
* and their folders from `seed/media/`. A content item is a TOML file named for
|
|
5
|
+
* its URL segment, with its children in a folder of the same name; a media file
|
|
6
|
+
* may have a sidecar, `photo.jpg.toml`.
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
9
|
+
import { join, relative } from 'node:path'
|
|
10
|
+
|
|
11
|
+
export type SeedKind = 'content' | 'library' | 'media'
|
|
12
|
+
|
|
13
|
+
export interface SeedItem {
|
|
14
|
+
kind: SeedKind
|
|
15
|
+
/** Its path in the tree, by segment: `about/team`, `logos/mark.png`. */
|
|
16
|
+
path: string
|
|
17
|
+
/** The parent's path, or null at the top. */
|
|
18
|
+
parent: string | null
|
|
19
|
+
/** The TOML file that describes it, relative to the site; null for a media item with no sidecar. */
|
|
20
|
+
file: string | null
|
|
21
|
+
text: string
|
|
22
|
+
data: Record<string, unknown>
|
|
23
|
+
/** A media file's bytes. */
|
|
24
|
+
bytes?: Uint8Array
|
|
25
|
+
/** A media folder: a directory under `seed/media/`. */
|
|
26
|
+
folder?: boolean
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SeedFinding {
|
|
30
|
+
file: string
|
|
31
|
+
line: number
|
|
32
|
+
code: string
|
|
33
|
+
message: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface SeedTree {
|
|
37
|
+
items: SeedItem[]
|
|
38
|
+
findings: SeedFinding[]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const SKIPPED = (name: string) => name.startsWith('.')
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The line a TOML syntax error is on: the first prefix of the file that does
|
|
45
|
+
* not parse. The parser's own position is not always the file's.
|
|
46
|
+
*/
|
|
47
|
+
function syntaxLine(text: string): number {
|
|
48
|
+
const lines = text.split('\n')
|
|
49
|
+
for (let n = 1; n <= lines.length; n++) {
|
|
50
|
+
try {
|
|
51
|
+
Bun.TOML.parse(lines.slice(0, n).join('\n'))
|
|
52
|
+
} catch {
|
|
53
|
+
return n
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return 1
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function readSeed(siteDir: string): SeedTree {
|
|
60
|
+
const root = join(siteDir, 'seed')
|
|
61
|
+
const items: SeedItem[] = []
|
|
62
|
+
const findings: SeedFinding[] = []
|
|
63
|
+
const shown = (path: string) => relative(siteDir, path)
|
|
64
|
+
|
|
65
|
+
const parse = (path: string): { text: string; data: Record<string, unknown> } | undefined => {
|
|
66
|
+
const text = readFileSync(path, 'utf8')
|
|
67
|
+
try {
|
|
68
|
+
return { text, data: Bun.TOML.parse(text) as Record<string, unknown> }
|
|
69
|
+
} catch (error) {
|
|
70
|
+
const line = syntaxLine(text)
|
|
71
|
+
findings.push({
|
|
72
|
+
file: shown(path),
|
|
73
|
+
line,
|
|
74
|
+
code: 'syntax',
|
|
75
|
+
message: (error as Error).message,
|
|
76
|
+
})
|
|
77
|
+
return undefined
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const content = (kind: 'content' | 'library', dir: string, parent: string | null) => {
|
|
82
|
+
if (!existsSync(dir)) return
|
|
83
|
+
const names = readdirSync(dir)
|
|
84
|
+
.filter((name) => !SKIPPED(name))
|
|
85
|
+
.sort()
|
|
86
|
+
for (const name of names) {
|
|
87
|
+
const path = join(dir, name)
|
|
88
|
+
if (statSync(path).isDirectory()) {
|
|
89
|
+
if (kind === 'library') {
|
|
90
|
+
findings.push({
|
|
91
|
+
file: shown(path),
|
|
92
|
+
line: 1,
|
|
93
|
+
code: 'library-folder',
|
|
94
|
+
message: 'Library elements sit at the top of seed/library: folders are not read yet',
|
|
95
|
+
})
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
if (!names.includes(`${name}.toml`))
|
|
99
|
+
findings.push({
|
|
100
|
+
file: shown(path),
|
|
101
|
+
line: 1,
|
|
102
|
+
code: 'orphan-folder',
|
|
103
|
+
message: `the folder ${name}/ holds children, but there is no ${name}.toml for the page they sit under`,
|
|
104
|
+
})
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
if (!name.endsWith('.toml')) {
|
|
108
|
+
findings.push({
|
|
109
|
+
file: shown(path),
|
|
110
|
+
line: 1,
|
|
111
|
+
code: 'not-toml',
|
|
112
|
+
message: 'only .toml files describe content; this one is not read',
|
|
113
|
+
})
|
|
114
|
+
continue
|
|
115
|
+
}
|
|
116
|
+
const segment = name.slice(0, -'.toml'.length)
|
|
117
|
+
const itemPath = parent ? `${parent}/${segment}` : segment
|
|
118
|
+
const parsed = parse(path)
|
|
119
|
+
if (parsed) items.push({ kind, path: itemPath, parent, file: shown(path), ...parsed })
|
|
120
|
+
if (kind === 'content') content(kind, join(dir, segment), itemPath)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const media = (dir: string, parent: string | null) => {
|
|
125
|
+
if (!existsSync(dir)) return
|
|
126
|
+
const names = readdirSync(dir)
|
|
127
|
+
.filter((name) => !SKIPPED(name))
|
|
128
|
+
.sort()
|
|
129
|
+
for (const name of names) {
|
|
130
|
+
const path = join(dir, name)
|
|
131
|
+
const itemPath = parent ? `${parent}/${name}` : name
|
|
132
|
+
if (statSync(path).isDirectory()) {
|
|
133
|
+
items.push({
|
|
134
|
+
kind: 'media',
|
|
135
|
+
path: itemPath,
|
|
136
|
+
parent,
|
|
137
|
+
file: null,
|
|
138
|
+
text: '',
|
|
139
|
+
data: {},
|
|
140
|
+
folder: true,
|
|
141
|
+
})
|
|
142
|
+
media(path, itemPath)
|
|
143
|
+
continue
|
|
144
|
+
}
|
|
145
|
+
if (name.endsWith('.toml')) {
|
|
146
|
+
if (!names.includes(name.slice(0, -'.toml'.length)))
|
|
147
|
+
findings.push({
|
|
148
|
+
file: shown(path),
|
|
149
|
+
line: 1,
|
|
150
|
+
code: 'orphan-sidecar',
|
|
151
|
+
message: `there is no ${name.slice(0, -'.toml'.length)} beside this sidecar`,
|
|
152
|
+
})
|
|
153
|
+
continue
|
|
154
|
+
}
|
|
155
|
+
const sidecar = names.includes(`${name}.toml`) ? parse(join(dir, `${name}.toml`)) : undefined
|
|
156
|
+
items.push({
|
|
157
|
+
kind: 'media',
|
|
158
|
+
path: itemPath,
|
|
159
|
+
parent,
|
|
160
|
+
file: sidecar ? shown(join(dir, `${name}.toml`)) : null,
|
|
161
|
+
text: sidecar?.text ?? '',
|
|
162
|
+
data: sidecar?.data ?? {},
|
|
163
|
+
bytes: new Uint8Array(readFileSync(path)),
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
content('content', join(root, 'content'), null)
|
|
169
|
+
content('library', join(root, 'library'), null)
|
|
170
|
+
media(join(root, 'media'), null)
|
|
171
|
+
return { items, findings }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Whether a site has a seed at all. */
|
|
175
|
+
export const hasSeed = (siteDir: string) => existsSync(join(siteDir, 'seed'))
|