@nickpaustian/tela 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -1
  3. package/bin/tela.ts +18 -2
  4. package/lib/index.js +172 -7
  5. package/package.json +5 -2
  6. package/scripts/check-components.ts +20 -0
  7. package/scripts/media-sync.ts +41 -0
  8. package/scripts/republish.ts +24 -0
  9. package/src/api.ts +3 -3
  10. package/src/components/EntryEditor.lsp +174 -11
  11. package/src/components/EntryList.lsp +8 -0
  12. package/src/components/Field.lsp +92 -2
  13. package/src/components/LinkField.lsp +477 -0
  14. package/src/components/MarkdownField.lsp +19 -24
  15. package/src/components/PersonField.lsp +255 -0
  16. package/src/components/ReferenceField.lsp +22 -1
  17. package/src/components/RepeaterField.lsp +141 -13
  18. package/src/components/ToggleField.lsp +63 -0
  19. package/src/config/fields.ts +134 -1
  20. package/src/config/seo.ts +4 -2
  21. package/src/config/types.ts +158 -7
  22. package/src/content/derive-values.ts +14 -3
  23. package/src/content/entries.ts +1 -1
  24. package/src/content/entry.ts +15 -1
  25. package/src/content/export.ts +173 -14
  26. package/src/content/git.ts +1 -1
  27. package/src/content/hooks.ts +75 -0
  28. package/src/content/link-address.ts +168 -0
  29. package/src/content/links.ts +13 -0
  30. package/src/content/person.ts +11 -0
  31. package/src/content/placement.ts +48 -0
  32. package/src/content/references.ts +48 -4
  33. package/src/content/rules.ts +24 -4
  34. package/src/content/shape.ts +192 -0
  35. package/src/content/store.ts +17 -0
  36. package/src/content/url.ts +15 -1
  37. package/src/content/users.ts +32 -0
  38. package/src/content/validate.ts +12 -2
  39. package/src/index.ts +4 -1
  40. package/src/keys.ts +47 -0
  41. package/src/media/index.ts +5 -0
  42. package/src/server/index.ts +168 -34
  43. package/src/server/library-routes.ts +11 -3
@@ -3,8 +3,9 @@ import type { Collection, Field } from "../config/types.ts"
3
3
  import { blockOf, blocksOf, dataFields, isSlot } from "../config/components.ts"
4
4
  import { findCollection } from "./collections.ts"
5
5
  import { summarise } from "./summary.ts"
6
- import { linkedEntries, withLinkSlugs } from "./links.ts"
6
+ import { linkedEntries, parseLink, publishedLink, withLinkSlugs } from "./links.ts"
7
7
  import { media } from "../media/index.ts"
8
+ import { publicName } from "./person.ts"
8
9
  import type { MediaStore, StoredInfo } from "../media/store.ts"
9
10
 
10
11
  /**
@@ -98,6 +99,11 @@ export function collectReferences(
98
99
  if (ids.length) found.push({ field, ids })
99
100
  return text
100
101
  },
102
+ (field, href) => {
103
+ const link = parseLink(href)
104
+ if (link) found.push({ field, ids: [link.id] })
105
+ return href
106
+ },
101
107
  )
102
108
 
103
109
  return found
@@ -121,7 +127,7 @@ export function withSlugs(
121
127
  }
122
128
 
123
129
  return slugs.get(String(value))
124
- }, (_field, text) => withLinkSlugs(text, slugs))
130
+ }, (_field, text) => withLinkSlugs(text, slugs), (_field, href) => publishedLink(href, slugs))
125
131
  }
126
132
 
127
133
  function idsOf(value: unknown): string[] {
@@ -143,6 +149,8 @@ function walk(
143
149
  visit: (field: Field, value: unknown) => unknown,
144
150
  /** Rich text, whose links to other entries are references too. */
145
151
  visitText?: (field: Field, text: string) => string,
152
+ /** A link field, which may name an entry or a file. */
153
+ visitLink?: (field: Field, href: string) => string | undefined,
146
154
  ): Record<string, unknown> {
147
155
  const out = { ...data }
148
156
 
@@ -155,6 +163,14 @@ function walk(
155
163
  continue
156
164
  }
157
165
 
166
+ if (field.type === "link") {
167
+ if (!visitLink || typeof value !== "string") continue
168
+ const next = visitLink(field, value)
169
+ if (next === undefined) delete out[field.name]
170
+ else out[field.name] = next
171
+ continue
172
+ }
173
+
158
174
  if (field.type === "reference") {
159
175
  const next = visit(field, value)
160
176
  if (next === undefined) delete out[field.name]
@@ -166,7 +182,7 @@ function walk(
166
182
  if (typeof value !== "object" || Array.isArray(value)) continue
167
183
  const inner = value as Record<string, unknown>
168
184
  const block = blockOf(field, inner)
169
- if (block) out[field.name] = walk(block.fields, inner, visit, visitText)
185
+ if (block) out[field.name] = walk(block.fields, inner, visit, visitText, visitLink)
170
186
  continue
171
187
  }
172
188
 
@@ -174,7 +190,7 @@ function walk(
174
190
  out[field.name] = value.map((row) => {
175
191
  if (!row || typeof row !== "object") return row
176
192
  const block = blockOf(field, row)
177
- return block ? walk(block.fields, row as Record<string, unknown>, visit, visitText) : row
193
+ return block ? walk(block.fields, row as Record<string, unknown>, visit, visitText, visitLink) : row
178
194
  })
179
195
  }
180
196
  }
@@ -196,6 +212,14 @@ function walk(
196
212
  */
197
213
  export async function publishedReferences(
198
214
  ids: string[],
215
+ /**
216
+ * What a picture becomes. `copied`: the picture itself, address, size and
217
+ * words, for what has to stand alone (a data source other apps read, a
218
+ * preview of a draft). `named`: its id, for an entry whose site reads the
219
+ * picture from its own file (`content/media/<id>.json`), so a corrected
220
+ * credit is one file and every page using it rebuilds.
221
+ */
222
+ { pictures = "copied" }: { pictures?: "copied" | "named" } = {},
199
223
  ): Promise<Map<string, unknown>> {
200
224
  if (!ids.length) return new Map()
201
225
 
@@ -247,6 +271,10 @@ export async function publishedReferences(
247
271
  console.warn(`[tela] ${file} is not in the media library, so it is left out of what is published.`)
248
272
  continue
249
273
  }
274
+ if (pictures === "named" && collection.uploads) {
275
+ resolved.set(String(row.id), String(row.id))
276
+ continue
277
+ }
250
278
  // Not a page, so being published is not the question - a media entry is
251
279
  // usable the moment it exists.
252
280
  resolved.set(
@@ -265,6 +293,22 @@ export async function publishedReferences(
265
293
  if (row.live && row.data?.slug) resolved.set(String(row.id), row.data.slug)
266
294
  }
267
295
 
296
+ // Accounts, which have their own table. One is somebody to name - a byline -
297
+ // so it publishes as its name and nothing else; one without a name is left
298
+ // out, like a reference to something unpublished.
299
+ const found = new Set(rows.map((row: any) => String(row.id)))
300
+ const rest = ids.filter((id) => !found.has(id))
301
+ if (rest.length) {
302
+ const people = await sql`
303
+ select id, data from users
304
+ where id = any(string_to_array(${rest.join(",")}, ',')::uuid[])
305
+ `
306
+ for (const person of people) {
307
+ const name = publicName(person.data)
308
+ if (name) resolved.set(String(person.id), { name })
309
+ }
310
+ }
311
+
268
312
  return resolved
269
313
  }
270
314
 
@@ -1,6 +1,8 @@
1
1
  import { BLOCK_KEY, type Collection, type Field, type PatternRule } from "../config/types.ts"
2
2
  import { blockOf, dataFields, isSlot, tagsRows } from "../config/components.ts"
3
3
  import { shown } from "./visibility.ts"
4
+ import { repeatedOnce } from "./placement.ts"
5
+ import { plainWords } from "./markdown.ts"
4
6
 
5
7
  /**
6
8
  * Declarative field rules, evaluated identically wherever they run.
@@ -71,7 +73,7 @@ export function checkField(
71
73
  // `required` is only judged when they try to save.
72
74
  if (mode === "live" && empty(value)) return issues
73
75
 
74
- if (field.required && empty(value)) {
76
+ if (field.required && empty(value) && field.fallback === undefined) {
75
77
  fail(`${nameOf(field)} is required.`)
76
78
  // Nothing else is worth saying about an empty field.
77
79
  return issues
@@ -79,6 +81,15 @@ export function checkField(
79
81
 
80
82
  if (empty(value)) return issues
81
83
 
84
+ if (field.type === "reference" && field.many && Array.isArray(value)) {
85
+ if (field.maxRows !== undefined && value.length > field.maxRows) {
86
+ fail(`${nameOf(field)} takes at most ${field.maxRows}.`)
87
+ }
88
+ if (mode === "save" && field.minRows !== undefined && value.length < field.minRows) {
89
+ fail(`${nameOf(field)} needs at least ${field.minRows}.`)
90
+ }
91
+ }
92
+
82
93
  if (field.choices && typeof value === "string") {
83
94
  // The same list the editor offers. A value from outside it usually means
84
95
  // content written before the list changed.
@@ -88,10 +99,13 @@ export function checkField(
88
99
  }
89
100
 
90
101
  if (typeof value === "string") {
91
- if (field.minLength !== undefined && value.length < field.minLength) {
102
+ // What a reader sees, as the editor's counter measures it: a link's address
103
+ // and the formatting marks are not characters of the caption.
104
+ const length = field.type === "markdown" ? plainWords(value).replace(/\s+/g, " ").trim().length : value.length
105
+ if (field.minLength !== undefined && length < field.minLength) {
92
106
  fail(`${nameOf(field)} must be at least ${field.minLength} characters.`)
93
107
  }
94
- if (field.maxLength !== undefined && value.length > field.maxLength) {
108
+ if (field.maxLength !== undefined && length > field.maxLength) {
95
109
  fail(`${nameOf(field)} must be at most ${field.maxLength} characters.`)
96
110
  }
97
111
  // Only the first failing pattern is reported. The rules are ordered
@@ -171,7 +185,8 @@ function checkNested(field: Field, data: Record<string, unknown>, mode: Mode): I
171
185
  * already said so - repeating it here would be two messages for one gap.
172
186
  */
173
187
  function checkSlot(field: Field, data: Record<string, unknown>, mode: Mode): Issue[] {
174
- const value = data[field.name]
188
+ const absent = data[field.name] === undefined || data[field.name] === null
189
+ const value = absent && mode === "save" && !tagsRows(field) ? {} : data[field.name]
175
190
  if (!value || typeof value !== "object" || Array.isArray(value)) return []
176
191
 
177
192
  const inner = value as Record<string, unknown>
@@ -229,6 +244,11 @@ function checkRows(field: Field, data: Record<string, unknown>, mode: Mode): Iss
229
244
  }
230
245
  }
231
246
 
247
+ const used = rows.map((row) => (row && typeof row === "object" ? (row as any)[BLOCK_KEY] : undefined)).filter(Boolean)
248
+ for (const block of repeatedOnce(field.blocks ?? [], used)) {
249
+ issues.push({ field: field.name, message: `${block.label ?? block.name} can only be added once.` })
250
+ }
251
+
232
252
  return issues.concat(rows.flatMap((row, index) => {
233
253
  if (!row || typeof row !== "object") return []
234
254
 
@@ -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
+ }
@@ -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
@@ -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
  }
@@ -3,6 +3,7 @@ import { narrowing } from "./filters.ts"
3
3
  import { sql } from "../db/client.ts"
4
4
  import type { Collection } from "../config/types.ts"
5
5
  import type { Entry, EntrySummary } from "./entries.ts"
6
+ import { publicName } from "./person.ts"
6
7
 
7
8
  /**
8
9
  * Users, stored where authentication needs them.
@@ -121,6 +122,37 @@ export async function listUsers(
121
122
  }
122
123
  }
123
124
 
125
+ /**
126
+ * Accounts as somebody to name: an id and a name, nothing else.
127
+ *
128
+ * For the person field, where an editor picks who wrote something. Editors
129
+ * may not read accounts - they are how permissions are held - so this answers
130
+ * any signed-in account but says only what a byline would. An account without
131
+ * a name is left out: there is nothing it could be called but its address.
132
+ */
133
+ export async function peopleNamed({
134
+ search = "",
135
+ ids = [],
136
+ limit = 20,
137
+ }: { search?: string; ids?: string[]; limit?: number } = {}): Promise<{ id: string; name: string }[]> {
138
+ // Every word typed somewhere in the name, so "nick pau" finds Nick Paustian.
139
+ const patterns = search.trim().split(/\s+/).filter(Boolean).map((word) => `%${word}%`).join("\n")
140
+ const wanted = ids.join(",")
141
+ const rows = await sql`
142
+ select id, data from users
143
+ where (${wanted} = '' or id = any(string_to_array(${wanted}, ',')::uuid[]))
144
+ and not exists (
145
+ select 1 from unnest(string_to_array(nullif(${patterns}, ''), E'\n')) as pattern
146
+ where concat_ws(' ', data ->> 'firstName', data ->> 'lastName', data ->> 'name') not ilike pattern
147
+ )
148
+ order by lower(concat_ws(' ', data ->> 'firstName', data ->> 'lastName', data ->> 'name'))
149
+ limit ${Math.min(Math.max(limit, 1), MAX_LIMIT)}
150
+ `
151
+ return rows
152
+ .map((row: any) => ({ id: String(row.id), name: publicName(row.data) }))
153
+ .filter((one: { name: string }) => one.name)
154
+ }
155
+
124
156
  export async function getUser(_: Collection, id: string): Promise<Entry | null> {
125
157
  const rows = await sql`
126
158
  select id, email, data, created_at, updated_at from users where id = ${id}
@@ -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
- if (!target.published) {
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, 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
+ }
@@ -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
  *