@nickpaustian/tela 0.1.3 → 0.3.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/CHANGELOG.md +40 -0
- package/bin/tela.ts +8 -0
- package/lib/index.js +171 -7
- package/package.json +5 -2
- package/scripts/check-components.ts +20 -0
- package/scripts/media-sync.ts +41 -0
- package/scripts/republish.ts +24 -0
- package/src/api.ts +3 -3
- package/src/components/EntryEditor.lsp +174 -11
- package/src/components/EntryList.lsp +8 -0
- package/src/components/Field.lsp +92 -2
- package/src/components/LinkField.lsp +477 -0
- package/src/components/MarkdownField.lsp +19 -24
- package/src/components/ReferenceField.lsp +22 -1
- package/src/components/RepeaterField.lsp +141 -13
- package/src/components/ToggleField.lsp +63 -0
- package/src/config/fields.ts +104 -1
- package/src/config/seo.ts +4 -2
- package/src/config/types.ts +187 -7
- package/src/content/derive-values.ts +14 -3
- package/src/content/entry.ts +15 -1
- package/src/content/export.ts +199 -14
- package/src/content/gathered.ts +103 -0
- package/src/content/git.ts +1 -1
- package/src/content/hooks.ts +75 -0
- package/src/content/link-address.ts +168 -0
- package/src/content/links.ts +13 -0
- package/src/content/placement.ts +48 -0
- package/src/content/references.ts +31 -4
- package/src/content/rules.ts +24 -4
- package/src/content/shape.ts +192 -0
- package/src/content/store.ts +17 -0
- package/src/content/url.ts +15 -1
- package/src/content/validate.ts +12 -2
- package/src/index.ts +4 -1
- package/src/keys.ts +47 -0
- package/src/media/index.ts +5 -0
- package/src/server/index.ts +145 -33
- package/src/server/library-routes.ts +11 -3
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { join } from "path"
|
|
2
|
+
import { BLOCK_KEY, type Block, type Collection, type Field } from "../config/types.ts"
|
|
3
|
+
import { blocksOf, dataFields, tagsRows } from "../config/components.ts"
|
|
4
|
+
import { findCollection } from "./collections.ts"
|
|
5
|
+
|
|
6
|
+
export interface ShapeNode {
|
|
7
|
+
type?: string | string[]
|
|
8
|
+
"x-tela-type"?: string
|
|
9
|
+
"x-tela-to"?: string
|
|
10
|
+
const?: string
|
|
11
|
+
properties?: Record<string, ShapeNode>
|
|
12
|
+
required?: string[]
|
|
13
|
+
items?: ShapeNode
|
|
14
|
+
oneOf?: ShapeNode[]
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface DataShape extends ShapeNode {
|
|
18
|
+
$schema: string
|
|
19
|
+
title: string
|
|
20
|
+
"x-tela": { source: string; version: number }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const JSON_TYPES: Record<string, string> = {
|
|
24
|
+
text: "string",
|
|
25
|
+
markdown: "string",
|
|
26
|
+
link: "string",
|
|
27
|
+
date: "string",
|
|
28
|
+
number: "number",
|
|
29
|
+
boolean: "boolean",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const shapePath = (name: string) => join("content", "data", `${name}.schema.json`)
|
|
33
|
+
|
|
34
|
+
export const versionOf = (collection: Collection) => collection.version ?? 1
|
|
35
|
+
|
|
36
|
+
export function dataShape(collection: Collection): DataShape {
|
|
37
|
+
return {
|
|
38
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
39
|
+
title: collection.label ?? collection.name,
|
|
40
|
+
"x-tela": { source: collection.name, version: versionOf(collection) },
|
|
41
|
+
...objectOf(collection.fields),
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const alwaysThere = (field: Field) => (field.required === true && !field.when) || field.fallback !== undefined
|
|
46
|
+
|
|
47
|
+
function objectOf(fields: Field[], extra: Record<string, ShapeNode> = {}, extraRequired: string[] = []): ShapeNode {
|
|
48
|
+
const properties: Record<string, ShapeNode> = { ...extra }
|
|
49
|
+
const required = [...extraRequired]
|
|
50
|
+
for (const field of dataFields(fields)) {
|
|
51
|
+
const there = alwaysThere(field)
|
|
52
|
+
properties[field.name] = fieldNode(field, there)
|
|
53
|
+
if (there && !required.includes(field.name)) required.push(field.name)
|
|
54
|
+
}
|
|
55
|
+
return { type: "object", properties, ...(required.length ? { required } : {}) }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function blockNode(block: Block, tagged: boolean): ShapeNode {
|
|
59
|
+
const content: Record<string, ShapeNode> = {}
|
|
60
|
+
for (const [key, value] of Object.entries(block.content ?? {})) {
|
|
61
|
+
content[key] = { type: Array.isArray(value) ? "array" : value === null ? "null" : typeof value, "x-tela-type": "content" }
|
|
62
|
+
}
|
|
63
|
+
const tag: Record<string, ShapeNode> = tagged ? { [BLOCK_KEY]: { const: block.name } } : {}
|
|
64
|
+
return objectOf(block.fields, { ...tag, ...content }, [...Object.keys(tag), ...Object.keys(content)])
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function withDerivedKeys(field: Field, node: ShapeNode): ShapeNode {
|
|
68
|
+
const keys = Object.keys(field.derive ?? {})
|
|
69
|
+
if (!keys.length) return node
|
|
70
|
+
const derived = Object.fromEntries(keys.map((key) => [key, { type: "string", "x-tela-type": "derived" }]))
|
|
71
|
+
const add = (one: ShapeNode): ShapeNode => ({ ...one, properties: { ...one.properties, ...derived } })
|
|
72
|
+
return node.oneOf ? { ...node, oneOf: node.oneOf.map(add) } : add(node)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function rowsOf(field: Field): ShapeNode {
|
|
76
|
+
const blocks = blocksOf(field)
|
|
77
|
+
if (tagsRows(field)) return { oneOf: blocks.map((block) => blockNode(block, true)) }
|
|
78
|
+
return blockNode(blocks[0]!, false)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function fieldNode(field: Field, there: boolean): ShapeNode {
|
|
82
|
+
const telaType = { "x-tela-type": field.type }
|
|
83
|
+
const maybe = (type: string) => (there ? type : [type, "null"])
|
|
84
|
+
|
|
85
|
+
if (field.type === "repeater" && blocksOf(field).length) {
|
|
86
|
+
return { type: maybe("array"), ...telaType, items: rowsOf(field) }
|
|
87
|
+
}
|
|
88
|
+
if (field.type === "block" && blocksOf(field).length) {
|
|
89
|
+
const rows = withDerivedKeys(field, rowsOf(field))
|
|
90
|
+
return { ...rows, type: maybe("object"), ...telaType }
|
|
91
|
+
}
|
|
92
|
+
if (field.type === "reference") {
|
|
93
|
+
const to = field.to ? { "x-tela-to": field.to } : {}
|
|
94
|
+
const one: ShapeNode = field.to && findCollection(field.to)?.referencedAs ? { type: "object" } : { type: "string" }
|
|
95
|
+
return field.many
|
|
96
|
+
? { type: maybe("array"), ...telaType, ...to, items: one }
|
|
97
|
+
: { type: maybe(String(one.type)), ...telaType, ...to }
|
|
98
|
+
}
|
|
99
|
+
const json = JSON_TYPES[field.type]
|
|
100
|
+
return json ? { type: maybe(json), ...telaType } : telaType
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const types = (node: ShapeNode) => (node.type === undefined ? [] : Array.isArray(node.type) ? node.type : [node.type])
|
|
104
|
+
const kind = (node: ShapeNode) =>
|
|
105
|
+
[node["x-tela-type"] ?? "", types(node).filter((type) => type !== "null").join("|"), node["x-tela-to"] ?? "", node.const ?? ""].join("/")
|
|
106
|
+
const nullable = (node: ShapeNode) => types(node).includes("null")
|
|
107
|
+
const describe = (node: ShapeNode) =>
|
|
108
|
+
node["x-tela-to"] ? `${node["x-tela-type"]} to ${node["x-tela-to"]}` : node["x-tela-type"] ?? types(node).join(" or ")
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* What an app written against `before` would trip over in `after`. Adding is
|
|
112
|
+
* never a break; taking away, retyping and no longer promising a value are.
|
|
113
|
+
*/
|
|
114
|
+
export function breaks(before: ShapeNode, after: ShapeNode, path = ""): string[] {
|
|
115
|
+
const here = path || "the record"
|
|
116
|
+
if (kind(before) !== kind(after)) {
|
|
117
|
+
const many = (node: ShapeNode) => types(node).includes("array") && node["x-tela-type"] === "reference"
|
|
118
|
+
const what = many(before) !== many(after) ? `${many(before) ? "a list" : "one"}, now ${many(after) ? "a list" : "one"}` : `${describe(before)}, now ${describe(after)}`
|
|
119
|
+
return [`${here} was ${what}`]
|
|
120
|
+
}
|
|
121
|
+
const out: string[] = []
|
|
122
|
+
if (!nullable(before) && nullable(after)) out.push(`${here} may now be empty`)
|
|
123
|
+
|
|
124
|
+
const at = (key: string) => (path ? `${path}.${key}` : key)
|
|
125
|
+
for (const [key, was] of Object.entries(before.properties ?? {})) {
|
|
126
|
+
const now = after.properties?.[key]
|
|
127
|
+
if (!now) {
|
|
128
|
+
out.push(`${at(key)} is gone`)
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
131
|
+
const inside = breaks(was, now, at(key))
|
|
132
|
+
if (before.required?.includes(key) && !after.required?.includes(key)) {
|
|
133
|
+
out.push(`${at(key)} may now be missing`, ...inside.filter((one) => one !== `${at(key)} may now be empty`))
|
|
134
|
+
} else out.push(...inside)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (before.items && after.items) out.push(...breaks(before.items, after.items, path))
|
|
138
|
+
|
|
139
|
+
if (before.oneOf || after.oneOf) {
|
|
140
|
+
if (!before.oneOf || !after.oneOf) return [...out, `${here} changed from one shape to a choice of shapes, or back`]
|
|
141
|
+
const named = (nodes: ShapeNode[]) => new Map(nodes.map((node) => [node.properties?.[BLOCK_KEY]?.const ?? "", node]))
|
|
142
|
+
const now = named(after.oneOf)
|
|
143
|
+
for (const [name, was] of named(before.oneOf)) {
|
|
144
|
+
const next = now.get(name)
|
|
145
|
+
if (next) out.push(...breaks(was, next, path ? `${path} (${name})` : name))
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return out
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export class ShapeBreaks extends Error {
|
|
153
|
+
constructor(
|
|
154
|
+
readonly source: string,
|
|
155
|
+
readonly label: string,
|
|
156
|
+
readonly problems: string[],
|
|
157
|
+
readonly went: "back" | "unraised",
|
|
158
|
+
) {
|
|
159
|
+
super(
|
|
160
|
+
went === "back"
|
|
161
|
+
? `${label} can't be published: its version in the config is lower than the one already published. A developer needs to fix the version first.`
|
|
162
|
+
: `${label} can't be published: its fields changed in a way that would break the apps reading it (${problems.join("; ")}). A developer needs to raise its version in the config first.`,
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Why `next` may not replace the published `before`, or null when it may. */
|
|
168
|
+
export function shapeProblem(before: DataShape | null, next: DataShape): ShapeBreaks | null {
|
|
169
|
+
if (!before) return null
|
|
170
|
+
const source = next["x-tela"].source
|
|
171
|
+
const was = before["x-tela"]?.version ?? 1
|
|
172
|
+
const now = next["x-tela"].version
|
|
173
|
+
if (now < was) return new ShapeBreaks(source, next.title, [`version ${was} is published, the config says ${now}`], "back")
|
|
174
|
+
if (now > was) return null
|
|
175
|
+
const problems = breaks(before, next)
|
|
176
|
+
return problems.length ? new ShapeBreaks(source, next.title, problems, "unraised") : null
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Every data source against the shape last published to `root`: what would
|
|
181
|
+
* refuse to publish, found before a deploy rather than by an editor.
|
|
182
|
+
*/
|
|
183
|
+
export async function checkShapes(collections: Collection[], root: string): Promise<ShapeBreaks[]> {
|
|
184
|
+
const found: ShapeBreaks[] = []
|
|
185
|
+
for (const collection of collections.filter((one) => one.data)) {
|
|
186
|
+
const file = Bun.file(join(root, shapePath(collection.name)))
|
|
187
|
+
const before = (await file.exists()) ? ((await file.json()) as DataShape) : null
|
|
188
|
+
const problem = shapeProblem(before, dataShape(collection))
|
|
189
|
+
if (problem) found.push(problem)
|
|
190
|
+
}
|
|
191
|
+
return found
|
|
192
|
+
}
|
package/src/content/store.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Collection } from "../config/types.ts"
|
|
2
2
|
import type { Entry, EntrySummary } from "./entries.ts"
|
|
3
3
|
import { saveDraft } from "./releases.ts"
|
|
4
|
+
import { sql } from "../db/client.ts"
|
|
4
5
|
import {
|
|
5
6
|
listEntries,
|
|
6
7
|
getEntry,
|
|
@@ -128,10 +129,26 @@ export function isPublishable(collection: Collection): boolean {
|
|
|
128
129
|
* Staging at birth makes the state honest instead: a new entry has unpublished
|
|
129
130
|
* changes, the badge says so, and Publish does what it says.
|
|
130
131
|
*/
|
|
132
|
+
/** A second record for a data source, which only ever has one. */
|
|
133
|
+
export class DataSourceExists extends Error {
|
|
134
|
+
constructor(readonly id: string, label: string) {
|
|
135
|
+
super(`${label} already exists.`)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
131
139
|
export async function createAndStage(
|
|
132
140
|
collection: Collection,
|
|
133
141
|
data: Record<string, unknown>,
|
|
134
142
|
): Promise<Entry> {
|
|
143
|
+
// A data source is one record, found by its collection's name.
|
|
144
|
+
if (collection.data) {
|
|
145
|
+
const [existing] = await sql`
|
|
146
|
+
select id from entries where collection = ${collection.name} and deleted_at is null limit 1
|
|
147
|
+
`
|
|
148
|
+
if (existing) throw new DataSourceExists(String(existing.id), collection.label ?? collection.name)
|
|
149
|
+
data = { ...data, slug: collection.name }
|
|
150
|
+
}
|
|
151
|
+
|
|
135
152
|
const created = await storeFor(collection).create(collection, data)
|
|
136
153
|
|
|
137
154
|
// Nothing to stage where nothing publishes: a user account takes effect when
|
package/src/content/url.ts
CHANGED
|
@@ -37,8 +37,22 @@ export function siteRoot(config: Pick<TelaConfig, "site">, env: Record<string, s
|
|
|
37
37
|
return (env.TELA_SITE_URL || config.site || "").trim().replace(/\/+$/, "")
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/** Where a data source can be read, from `dataAddress`, or null when the project has not said. */
|
|
41
|
+
export function dataAddressOf(
|
|
42
|
+
config: Pick<TelaConfig, "site" | "dataAddress">,
|
|
43
|
+
name: string,
|
|
44
|
+
env: Record<string, string | undefined> = {},
|
|
45
|
+
): string | null {
|
|
46
|
+
const template = config.dataAddress?.trim()
|
|
47
|
+
if (!template) return null
|
|
48
|
+
const filled = template.replaceAll("{name}", name)
|
|
49
|
+
if (/^https?:\/\//i.test(filled)) return filled
|
|
50
|
+
const root = siteRoot(config, env)
|
|
51
|
+
return root ? root + (filled.startsWith("/") ? filled : "/" + filled) : null
|
|
52
|
+
}
|
|
53
|
+
|
|
40
54
|
export function urlRule(collection: Collection): { path: string; under?: string } | null {
|
|
41
|
-
if (collection.url === false || collection.publishable === false) return null
|
|
55
|
+
if (collection.url === false || collection.publishable === false || collection.data) return null
|
|
42
56
|
if (collection.url === undefined) return { path: `/${collection.name}/{slug}` }
|
|
43
57
|
return typeof collection.url === "string" ? { path: collection.url } : collection.url
|
|
44
58
|
}
|
package/src/content/validate.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { STORAGE_TYPES, type Collection, type Field } from "../config/types.ts"
|
|
2
2
|
import { dataFields } from "../config/components.ts"
|
|
3
|
-
import { storeFor } from "./store.ts"
|
|
3
|
+
import { isPublishable, storeFor } from "./store.ts"
|
|
4
|
+
import { findCollection } from "./collections.ts"
|
|
4
5
|
import { collectReferences, targetsFor } from "./references.ts"
|
|
5
6
|
import { checkAll, type Mode } from "./rules.ts"
|
|
6
7
|
|
|
@@ -90,6 +91,12 @@ export function validate(
|
|
|
90
91
|
)
|
|
91
92
|
|
|
92
93
|
for (const key of Object.keys(data)) {
|
|
94
|
+
if (key === "slug" && collection.data) {
|
|
95
|
+
if (data.slug !== collection.name) {
|
|
96
|
+
errors.push({ field: key, message: `A data source's slug is always its name, "${collection.name}"` })
|
|
97
|
+
}
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
93
100
|
if (!known.has(key)) {
|
|
94
101
|
errors.push({
|
|
95
102
|
field: key,
|
|
@@ -258,7 +265,10 @@ export async function checkReferences(
|
|
|
258
265
|
continue
|
|
259
266
|
}
|
|
260
267
|
|
|
261
|
-
|
|
268
|
+
// A file or a category is never published itself; it travels inside
|
|
269
|
+
// whatever uses it.
|
|
270
|
+
const kind = findCollection(target.collection)
|
|
271
|
+
if (!target.published && (!kind || isPublishable(kind))) {
|
|
262
272
|
issues.push({
|
|
263
273
|
field: field.name,
|
|
264
274
|
warning: true,
|
package/src/index.ts
CHANGED
|
@@ -19,12 +19,15 @@ export type {
|
|
|
19
19
|
Workflow,
|
|
20
20
|
WorkflowStage,
|
|
21
21
|
NavSection,
|
|
22
|
+
PublishHook,
|
|
22
23
|
} from "./config/types.ts"
|
|
23
|
-
export { imageUse, person, slugField } from "./config/fields.ts"
|
|
24
|
+
export { customBlock, dataSource, imageUse, link, person, slugField } from "./config/fields.ts"
|
|
24
25
|
export type { UrlRule } from "./content/url.ts"
|
|
26
|
+
export { LINK_KINDS, type LinkKind } from "./content/link-address.ts"
|
|
25
27
|
export type { CounterSpec, Band, Tone } from "./content/counter.ts"
|
|
26
28
|
export type { SharingOptions } from "./content/sharing.ts"
|
|
27
29
|
export type { SeoOptions } from "./config/seo.ts"
|
|
30
|
+
export type { PublishNotice, PublishEvent } from "./content/hooks.ts"
|
|
28
31
|
export { SEO_FIELDS } from "./config/seo.ts"
|
|
29
32
|
export { personName, initialsOf } from "./content/person.ts"
|
|
30
33
|
export { TYPE_ICONS, iconFor, suggestIcon, type TypeIcon } from "./config/icons.ts"
|
package/src/keys.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keyboard shortcuts as the person's own keyboard labels them.
|
|
3
|
+
*
|
|
4
|
+
* Written once as a combination - `Mod+Shift+F`, `Alt+ArrowUp` - where `Mod`
|
|
5
|
+
* is the command key on a Mac and Ctrl elsewhere, the key the shortcut
|
|
6
|
+
* handlers already accept as either. A Mac shows its symbols run together
|
|
7
|
+
* (⌘⇧F); anything else names the keys joined by `+` (Ctrl+Shift+F).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const onMac = (platform: string = (globalThis.navigator && navigator.platform) || ""): boolean =>
|
|
11
|
+
/Mac|iPhone|iPad/.test(platform)
|
|
12
|
+
|
|
13
|
+
const MAC: Record<string, string> = {
|
|
14
|
+
Mod: "⌘",
|
|
15
|
+
Ctrl: "⌃",
|
|
16
|
+
Alt: "⌥",
|
|
17
|
+
Shift: "⇧",
|
|
18
|
+
Enter: "↩",
|
|
19
|
+
Backspace: "⌫",
|
|
20
|
+
Escape: "Esc",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const OTHER: Record<string, string> = {
|
|
24
|
+
Mod: "Ctrl",
|
|
25
|
+
Escape: "Esc",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const BOTH: Record<string, string> = {
|
|
29
|
+
ArrowUp: "↑",
|
|
30
|
+
ArrowDown: "↓",
|
|
31
|
+
ArrowLeft: "←",
|
|
32
|
+
ArrowRight: "→",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Each key in a combination as its own label, for a row of key caps. */
|
|
36
|
+
export function keyParts(combo: string, mac: boolean = onMac()): string[] {
|
|
37
|
+
return combo
|
|
38
|
+
.split("+")
|
|
39
|
+
.map((key) => key.trim())
|
|
40
|
+
.filter(Boolean)
|
|
41
|
+
.map((key) => BOTH[key] ?? (mac ? MAC : OTHER)[key] ?? (key.length === 1 ? key.toUpperCase() : key))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A combination as one label: ⌘⇧F on a Mac, Ctrl+Shift+F elsewhere. */
|
|
45
|
+
export function keyLabel(combo: string, mac: boolean = onMac()): string {
|
|
46
|
+
return keyParts(combo, mac).join(mac ? "" : "+")
|
|
47
|
+
}
|
package/src/media/index.ts
CHANGED
|
@@ -22,6 +22,11 @@ export function media(): MediaStore {
|
|
|
22
22
|
return (store ??= driverFor(config.media))
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/** A store to use instead of the configured one, or none to go back to it: for tests about publishing rather than a media service. */
|
|
26
|
+
export function setMediaStore(next: MediaStore | undefined) {
|
|
27
|
+
store = next
|
|
28
|
+
}
|
|
29
|
+
|
|
25
30
|
/**
|
|
26
31
|
* A name, a driver, or nothing.
|
|
27
32
|
*
|
package/src/server/index.ts
CHANGED
|
@@ -9,10 +9,14 @@ import {
|
|
|
9
9
|
draftReleaseFor,
|
|
10
10
|
discardDraft,
|
|
11
11
|
} from "../content/releases.ts"
|
|
12
|
+
import { ShapeBreaks } from "../content/shape.ts"
|
|
13
|
+
import { republishPictures } from "../content/export.ts"
|
|
14
|
+
import { noticeOf, notifyHooks } from "../content/hooks.ts"
|
|
12
15
|
import {
|
|
13
16
|
exportRelease,
|
|
14
17
|
exportRemoval,
|
|
15
18
|
entryCell,
|
|
19
|
+
entryPath,
|
|
16
20
|
indexCell,
|
|
17
21
|
} from "../content/export.ts"
|
|
18
22
|
import { commitContent, commitMessage } from "../content/git.ts"
|
|
@@ -30,9 +34,10 @@ import { config } from "../config/load.ts"
|
|
|
30
34
|
import { DIST } from "../project.ts"
|
|
31
35
|
import { navigationFor } from "../config/navigation.ts"
|
|
32
36
|
import { iconFor } from "../config/icons.ts"
|
|
33
|
-
import { entryUrl, linkSearch, siteRoot, urlRule, urlUses } from "../content/url.ts"
|
|
37
|
+
import { dataAddressOf, entryUrl, linkSearch, siteRoot, urlRule, urlUses } from "../content/url.ts"
|
|
34
38
|
import { libraryRoutes, writeGroupsOf } from "./library-routes.ts"
|
|
35
39
|
import { linkTo, parseLink } from "../content/links.ts"
|
|
40
|
+
import { hostsOf } from "../content/link-address.ts"
|
|
36
41
|
import { previewAssetPaths } from "../content/preview.ts"
|
|
37
42
|
import { governingChanges } from "../content/governing.ts"
|
|
38
43
|
import { personName } from "../content/person.ts"
|
|
@@ -53,7 +58,7 @@ import { accessCondition, explainScope, mayOn } from "../content/access.ts"
|
|
|
53
58
|
import { verifyCredentials } from "../auth/login.ts"
|
|
54
59
|
import { createFirstAdmin, needsSetup, MIN_PASSWORD_LENGTH } from "../auth/setup.ts"
|
|
55
60
|
import { findCollection } from "../content/collections.ts"
|
|
56
|
-
import { createAndStage, storeFor, isPublishable } from "../content/store.ts"
|
|
61
|
+
import { DataSourceExists, createAndStage, storeFor, isPublishable } from "../content/store.ts"
|
|
57
62
|
import { withDerived } from "../content/derive-values.ts"
|
|
58
63
|
import { withoutSecrets } from "../config/components.ts"
|
|
59
64
|
import { countUsers, peopleNamed } from "../content/users.ts"
|
|
@@ -285,6 +290,55 @@ const authed =
|
|
|
285
290
|
* Returns a Response on failure so handlers can return it directly - a route
|
|
286
291
|
* that forgets to check gets a type error rather than an unguarded query.
|
|
287
292
|
*/
|
|
293
|
+
/** What the editor sends to see its draft: the values on screen, and a saved draft to fall back on. */
|
|
294
|
+
interface PreviewBody {
|
|
295
|
+
entryId?: string
|
|
296
|
+
data?: Record<string, unknown>
|
|
297
|
+
exact?: boolean
|
|
298
|
+
/** For a data source: which page that shows it to draw. */
|
|
299
|
+
page?: string
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* The draft as publishing would write it.
|
|
304
|
+
*
|
|
305
|
+
* Sent values win; anything absent falls back to the saved draft, so a preview
|
|
306
|
+
* opened before any edit still shows something. A comparison asks for a
|
|
307
|
+
* version exactly as it was, with nothing borrowed from the draft. Derived
|
|
308
|
+
* and with references as slugs, the same way a publish writes them, or a
|
|
309
|
+
* preview would be missing what the live page has - the one drift a preview
|
|
310
|
+
* exists to prevent.
|
|
311
|
+
*/
|
|
312
|
+
/** The media records holding a stored file: usually one, since adopting finds before it creates. */
|
|
313
|
+
async function mediaIdsFor(key: string): Promise<string[]> {
|
|
314
|
+
const rows = await sql`select id from entries where collection = 'media' and data ->> 'file' = ${key} and deleted_at is null`
|
|
315
|
+
return rows.map((row: any) => String(row.id))
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Pictures whose words or file changed, published again where they already
|
|
320
|
+
* are: their own files, and the data sources carrying them. Committed like a
|
|
321
|
+
* publish, so the site rebuilds the pages showing them. A picture no page has
|
|
322
|
+
* published writes nothing.
|
|
323
|
+
*/
|
|
324
|
+
async function picturesChanged(ids: string[], user: SessionUser) {
|
|
325
|
+
if (!CONTENT_REPO || !ids.length) return
|
|
326
|
+
const exported = await republishPictures(ids, { root: CONTENT_REPO })
|
|
327
|
+
if (!exported.files.length) return
|
|
328
|
+
const commit = await commitContent(exported, {
|
|
329
|
+
root: CONTENT_REPO,
|
|
330
|
+
message: `Update ${exported.cells.filter((cell) => cell.startsWith("cms:media:")).length || "a"} picture(s)\n\nRebuild: ${exported.cells.join(" ")}\n`,
|
|
331
|
+
push: process.env.TELA_PUSH !== "false",
|
|
332
|
+
author: authorOf(user),
|
|
333
|
+
})
|
|
334
|
+
void notifyHooks(config.afterPublish, noticeOf("published", commit))
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function asPublished(collection: Collection, body: PreviewBody | null) {
|
|
338
|
+
const saved = body?.entryId && !body.exact ? await draftData(body.entryId) : {}
|
|
339
|
+
return withDerived(collection, await withResolvedReferences(collection, { ...saved, ...(body?.data ?? {}) }))
|
|
340
|
+
}
|
|
341
|
+
|
|
288
342
|
function resolveCollection(name: string) {
|
|
289
343
|
const collection = findCollection(name)
|
|
290
344
|
|
|
@@ -638,7 +692,13 @@ const server = Bun.serve({
|
|
|
638
692
|
const escalatingCreate = refuseEscalation(user, found.collection, "", body)
|
|
639
693
|
if (escalatingCreate) return escalatingCreate
|
|
640
694
|
|
|
641
|
-
|
|
695
|
+
let created
|
|
696
|
+
try {
|
|
697
|
+
created = await createAndStage(found.collection, body)
|
|
698
|
+
} catch (error) {
|
|
699
|
+
if (error instanceof DataSourceExists) return json({ error: error.message, id: error.id }, 409)
|
|
700
|
+
throw error
|
|
701
|
+
}
|
|
642
702
|
if (isPublishable(found.collection)) await recordSave(created.id, created.data, user.id)
|
|
643
703
|
return json({ entry: withoutSecrets(found.collection, created) }, 201)
|
|
644
704
|
}),
|
|
@@ -741,6 +801,8 @@ const server = Bun.serve({
|
|
|
741
801
|
if (!isPublishable(found.collection)) {
|
|
742
802
|
const saved = await store.update(found.collection, req.params.id, body)
|
|
743
803
|
if (!saved) return json({ error: "Not found" }, 404)
|
|
804
|
+
// A picture's own words, where the store keeps none: what publishes it follows.
|
|
805
|
+
if (found.collection.uploads) await picturesChanged([req.params.id], user)
|
|
744
806
|
return json({ entry: withoutSecrets(found.collection, saved), draft: false })
|
|
745
807
|
}
|
|
746
808
|
|
|
@@ -859,12 +921,13 @@ const server = Bun.serve({
|
|
|
859
921
|
root: CONTENT_REPO,
|
|
860
922
|
})
|
|
861
923
|
|
|
862
|
-
await commitContent(exported, {
|
|
924
|
+
const removed = await commitContent(exported, {
|
|
863
925
|
root: CONTENT_REPO,
|
|
864
926
|
message: `Remove ${found.collection.name}/${slug}`,
|
|
865
927
|
push: process.env.TELA_PUSH !== "false",
|
|
866
928
|
author: authorOf(user),
|
|
867
929
|
})
|
|
930
|
+
void notifyHooks(config.afterPublish, noticeOf("removed", removed))
|
|
868
931
|
}
|
|
869
932
|
|
|
870
933
|
const gone = await storeFor(found.collection).remove(
|
|
@@ -1021,6 +1084,7 @@ const server = Bun.serve({
|
|
|
1021
1084
|
push: process.env.TELA_PUSH !== "false",
|
|
1022
1085
|
author: authorOf(user),
|
|
1023
1086
|
})
|
|
1087
|
+
void notifyHooks(config.afterPublish, noticeOf("unpublished", commit))
|
|
1024
1088
|
|
|
1025
1089
|
// Stage what it holds, so there is something to publish again.
|
|
1026
1090
|
//
|
|
@@ -1218,7 +1282,10 @@ const server = Bun.serve({
|
|
|
1218
1282
|
const asked = parseLink(params.get("ref") ?? "")
|
|
1219
1283
|
// The entry being edited, which a link from itself would only reload.
|
|
1220
1284
|
const self = params.get("not") ?? ""
|
|
1285
|
+
// Only these collections, for a link field that takes only some.
|
|
1286
|
+
const only = (params.get("in") ?? "").split(",").filter(Boolean)
|
|
1221
1287
|
const site = siteRoot(config, process.env)
|
|
1288
|
+
if (params.has("hosts")) return json({ links: [], hosts: hostsOf([site, config.site, ...(config.siteAliases ?? [])]) })
|
|
1222
1289
|
const found: {
|
|
1223
1290
|
collection: string
|
|
1224
1291
|
collectionLabel: string
|
|
@@ -1232,6 +1299,7 @@ const server = Bun.serve({
|
|
|
1232
1299
|
for (const collection of config.collections) {
|
|
1233
1300
|
if (!urlRule(collection) || !isPublishable(collection) || !can(user, "read", collection.name)) continue
|
|
1234
1301
|
if (asked && asked.collection !== collection.name) continue
|
|
1302
|
+
if (only.length && !only.includes(collection.name)) continue
|
|
1235
1303
|
|
|
1236
1304
|
const { entries } = await storeFor(collection).list(collection, {
|
|
1237
1305
|
limit: 8,
|
|
@@ -1265,7 +1333,9 @@ const server = Bun.serve({
|
|
|
1265
1333
|
}
|
|
1266
1334
|
}
|
|
1267
1335
|
|
|
1268
|
-
|
|
1336
|
+
// The hosts this site's own addresses are written with, so a pasted
|
|
1337
|
+
// one can be read as the page it names.
|
|
1338
|
+
return json({ links: found.slice(0, 12), hosts: hostsOf([site, config.site, ...(config.siteAliases ?? [])]) })
|
|
1269
1339
|
}),
|
|
1270
1340
|
},
|
|
1271
1341
|
|
|
@@ -1344,6 +1414,27 @@ const server = Bun.serve({
|
|
|
1344
1414
|
* are sitting in the editor - so making the id optional is the whole
|
|
1345
1415
|
* difference between previewing a new entry and being told to save first.
|
|
1346
1416
|
*/
|
|
1417
|
+
/**
|
|
1418
|
+
* A data source as it would be published from what is on screen: the
|
|
1419
|
+
* file's contents, where in the content repo it goes, and where it can be
|
|
1420
|
+
* read if the project serves it somewhere.
|
|
1421
|
+
*/
|
|
1422
|
+
"/api/collections/:collection/published": {
|
|
1423
|
+
POST: authed(async (req: { params: { collection: string } } & Request, user) => {
|
|
1424
|
+
const found = resolveCollection(req.params.collection)
|
|
1425
|
+
if (found.error) return found.error
|
|
1426
|
+
if (!can(user, "read", found.collection.name)) return refuse("read", found.collection.name)
|
|
1427
|
+
if (!found.collection.data) return json({ error: `"${found.collection.name}" is not a data source.` }, 409)
|
|
1428
|
+
|
|
1429
|
+
const { slug: _slug, ...record } = await asPublished(found.collection, (await readBody(req)) as PreviewBody | null)
|
|
1430
|
+
return json({
|
|
1431
|
+
data: record,
|
|
1432
|
+
file: entryPath(found.collection.name, found.collection.name),
|
|
1433
|
+
address: dataAddressOf(config, found.collection.name, process.env),
|
|
1434
|
+
})
|
|
1435
|
+
}),
|
|
1436
|
+
},
|
|
1437
|
+
|
|
1347
1438
|
"/api/collections/:collection/preview": {
|
|
1348
1439
|
POST: authed(async (req: { params: { collection: string } } & Request, user) => {
|
|
1349
1440
|
if (!AGENT_URL) {
|
|
@@ -1360,33 +1451,39 @@ const server = Bun.serve({
|
|
|
1360
1451
|
return refuse("read", found.collection.name)
|
|
1361
1452
|
}
|
|
1362
1453
|
|
|
1363
|
-
const body = (await readBody(req)) as
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1454
|
+
const body = (await readBody(req)) as PreviewBody | null
|
|
1455
|
+
const data = await asPublished(found.collection, body)
|
|
1456
|
+
|
|
1457
|
+
// A data source is drawn on a page that shows it, chosen by path; the
|
|
1458
|
+
// site says which pages those are.
|
|
1459
|
+
if (found.collection.data) {
|
|
1460
|
+
const { slug: _slug, ...record } = data
|
|
1461
|
+
const response = await fetch(`${AGENT_URL}/preview`, {
|
|
1462
|
+
method: "POST",
|
|
1463
|
+
headers: { "content-type": "application/json", "x-lightspeed-secret": AGENT_SECRET },
|
|
1464
|
+
body: JSON.stringify({
|
|
1465
|
+
entryCell: entryCell(found.collection.name, found.collection.name),
|
|
1466
|
+
indexCell: indexCell(found.collection.name),
|
|
1467
|
+
slug: found.collection.name,
|
|
1468
|
+
data: record,
|
|
1469
|
+
page: typeof body?.page === "string" ? body.page : undefined,
|
|
1470
|
+
}),
|
|
1471
|
+
}).catch(() => null)
|
|
1472
|
+
if (!response) return json({ error: "The build agent is not reachable." }, 502)
|
|
1473
|
+
const pages = response.headers.get("x-preview-pages") ?? "[]"
|
|
1474
|
+
if (!response.ok) {
|
|
1475
|
+
return new Response(await response.text(), { status: response.status, headers: { "x-preview-pages": pages } })
|
|
1476
|
+
}
|
|
1477
|
+
return new Response(previewAssetPaths(await response.text()), {
|
|
1478
|
+
headers: {
|
|
1479
|
+
"content-type": "text/html; charset=utf-8",
|
|
1480
|
+
"cache-control": "no-store",
|
|
1481
|
+
"x-preview-pages": pages,
|
|
1482
|
+
"x-preview-page": response.headers.get("x-lightspeed-path") ?? "",
|
|
1483
|
+
},
|
|
1484
|
+
})
|
|
1485
|
+
}
|
|
1373
1486
|
|
|
1374
|
-
// Sent values win; anything absent falls back to the saved draft, so a
|
|
1375
|
-
// preview opened before any edit still shows something.
|
|
1376
|
-
//
|
|
1377
|
-
// Derived the same way a publish derives, or a preview would be
|
|
1378
|
-
// missing every `name.full` the live page has - the one drift a
|
|
1379
|
-
// preview exists to prevent.
|
|
1380
|
-
// References resolved to slugs as well, for the same reason: the site
|
|
1381
|
-
// reads a slug, and a preview handing it an id shows a page with its
|
|
1382
|
-
// venue and its artists missing.
|
|
1383
|
-
const data = withDerived(
|
|
1384
|
-
found.collection,
|
|
1385
|
-
await withResolvedReferences(found.collection, {
|
|
1386
|
-
...saved,
|
|
1387
|
-
...(body?.data ?? {}),
|
|
1388
|
-
}),
|
|
1389
|
-
)
|
|
1390
1487
|
const slug = String(data.slug ?? "")
|
|
1391
1488
|
if (!slug) {
|
|
1392
1489
|
// The one thing a preview genuinely cannot do without: the slug is
|
|
@@ -1496,12 +1593,14 @@ const server = Bun.serve({
|
|
|
1496
1593
|
author: authorOf(user),
|
|
1497
1594
|
})
|
|
1498
1595
|
await publishRelease(releaseId, { force: true, by: user.id })
|
|
1596
|
+
void notifyHooks(config.afterPublish, noticeOf("published", commit))
|
|
1499
1597
|
|
|
1500
1598
|
return json({ published: true, commit: commit.sha, rebuild: commit.cells })
|
|
1501
1599
|
} catch (error) {
|
|
1502
1600
|
if (error instanceof ReleaseConflict) {
|
|
1503
1601
|
return json({ error: error.message, conflicts: error.conflicts }, 409)
|
|
1504
1602
|
}
|
|
1603
|
+
if (error instanceof ShapeBreaks) return json({ error: error.message, breaks: error.problems }, 409)
|
|
1505
1604
|
throw error
|
|
1506
1605
|
}
|
|
1507
1606
|
}),
|
|
@@ -1538,7 +1637,11 @@ const server = Bun.serve({
|
|
|
1538
1637
|
}
|
|
1539
1638
|
}
|
|
1540
1639
|
|
|
1541
|
-
const exported = await exportRelease(req.params.id, { root: CONTENT_REPO })
|
|
1640
|
+
const exported = await exportRelease(req.params.id, { root: CONTENT_REPO }).catch((error) => {
|
|
1641
|
+
if (error instanceof ShapeBreaks) return error
|
|
1642
|
+
throw error
|
|
1643
|
+
})
|
|
1644
|
+
if (exported instanceof ShapeBreaks) return json({ error: exported.message, breaks: exported.problems }, 409)
|
|
1542
1645
|
const [release] = await sql`select label from releases where id = ${req.params.id}`
|
|
1543
1646
|
|
|
1544
1647
|
// Export and commit before the database advances. If either fails, the
|
|
@@ -1554,6 +1657,7 @@ const server = Bun.serve({
|
|
|
1554
1657
|
|
|
1555
1658
|
// Cheapest, most reliable step, done last.
|
|
1556
1659
|
await publishRelease(req.params.id, { force: true, by: user.id })
|
|
1660
|
+
void notifyHooks(config.afterPublish, noticeOf("published", commit))
|
|
1557
1661
|
|
|
1558
1662
|
return json({
|
|
1559
1663
|
published: true,
|
|
@@ -1714,7 +1818,15 @@ const server = Bun.serve({
|
|
|
1714
1818
|
authed,
|
|
1715
1819
|
can,
|
|
1716
1820
|
json,
|
|
1717
|
-
|
|
1821
|
+
changed: async (key, user) => picturesChanged(await mediaIdsFor(key), user),
|
|
1822
|
+
fallback: {
|
|
1823
|
+
list: plainList as never,
|
|
1824
|
+
describe: (async (req: { params: { key: string } } & Request, user: SessionUser) => {
|
|
1825
|
+
const answer = await plainDescribe(req as never, user)
|
|
1826
|
+
if (answer.ok) await picturesChanged(await mediaIdsFor(req.params.key), user)
|
|
1827
|
+
return answer
|
|
1828
|
+
}) as never,
|
|
1829
|
+
},
|
|
1718
1830
|
}),
|
|
1719
1831
|
|
|
1720
1832
|
/**
|