@nickpaustian/tela 0.2.0 → 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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Added
6
+
7
+ - **Gathered lists** (`gathered`): a list drawn from everything published, such as every video on the site, written to `content/data/<name>.json` as `{ values: [...] }` and kept up to date by each publish and takedown. Tela keeps a ledger of what each entry adds (`.tela/gathered/<name>.json`, outside `content/`), so a publish updates one entry's line rather than reading the site again. Run `tela republish` after adding a list or changing what it gathers.
8
+
3
9
  ## 0.2.0
4
10
 
5
11
  ### Upgrading from 0.1.x
package/lib/index.js CHANGED
@@ -547,8 +547,21 @@ function defineConfig(config) {
547
547
  else if (collection.version !== undefined)
548
548
  throw new Error(`${collection.name}: only a data source has a \`version\`.`);
549
549
  }
550
+ const gatheredNames = new Set;
551
+ for (const list of config.gathered ?? []) {
552
+ if (!/^[a-z][a-z0-9-]*$/.test(list.name))
553
+ throw new Error(`gathered: "${list.name}" must start lowercase and use letters, digits and hyphens.`);
554
+ if (known.has(list.name))
555
+ throw new Error(`gathered: "${list.name}" is a collection's name, and would be written over its data.`);
556
+ if (gatheredNames.has(list.name))
557
+ throw new Error(`gathered: "${list.name}" is declared twice.`);
558
+ const unknown = (list.collections ?? []).filter((name) => !known.has(name));
559
+ if (unknown.length)
560
+ throw new Error(`gathered: ${list.name} names ${unknown.join(", ")}, which no collection is called.`);
561
+ gatheredNames.add(list.name);
562
+ }
550
563
  for (const hook of config.afterPublish ?? [])
551
- checkHook(hook, known);
564
+ checkHook(hook, new Set([...known, ...gatheredNames]));
552
565
  const declared = declaredCollections.find((c) => c.name === "users");
553
566
  const [address, ...access] = USER_BASE_FIELDS;
554
567
  const userFields = config.userNames ? [address, ...USER_NAME_FIELDS, ...access] : USER_BASE_FIELDS;
@@ -602,6 +615,7 @@ function defineConfig(config) {
602
615
  ...config.siteAliases?.length ? { siteAliases: config.siteAliases } : {},
603
616
  ...config.dataAddress ? { dataAddress: config.dataAddress } : {},
604
617
  ...config.afterPublish?.length ? { afterPublish: config.afterPublish } : {},
618
+ ...config.gathered?.length ? { gathered: config.gathered } : {},
605
619
  ...config.siteName ? { siteName: config.siteName } : {},
606
620
  ...config.userNames ? { userNames: true } : {}
607
621
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nickpaustian/tela",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "A Git-backed headless CMS: collections of fields in TypeScript, edited in a Lightspeed admin, published as JSON commits to a content repo.",
5
5
  "license": "MIT",
6
6
  "author": "Nick Paustian",
@@ -673,6 +673,14 @@ export interface TelaConfig {
673
673
  * logged and never fails the publish.
674
674
  */
675
675
  afterPublish?: PublishHook[]
676
+ /**
677
+ * Lists gathered from everything published, each written to
678
+ * `content/data/<name>.json` as `{ values: [...] }` and kept up to date by
679
+ * every publish and takedown: the videos on the site, for a server that
680
+ * will only stream those. Run `tela republish` after adding one or changing
681
+ * what it gathers, since a list only learns of an entry when it is published.
682
+ */
683
+ gathered?: GatheredList[]
676
684
  /**
677
685
  * The site's name, as search results and link cards give it. Collections
678
686
  * with `seo` add it to titles in search results unless they say otherwise.
@@ -738,6 +746,15 @@ export interface TelaConfig {
738
746
  components?: string[]
739
747
  }
740
748
 
749
+ export interface GatheredList {
750
+ /** The file's name, and the `cms:data:<name>` cell. Not a collection's name. */
751
+ name: string
752
+ /** What one published entry adds to the list. Text or numbers; anything else is left out. */
753
+ from: (data: Record<string, unknown>, entry: { collection: string }) => Iterable<unknown> | null | undefined
754
+ /** Only entries of these collections. All of them when left out. */
755
+ collections?: string[]
756
+ }
757
+
741
758
  export interface PublishHook {
742
759
  /** POSTed `{ event, commit, files, cells, collections }`. */
743
760
  url: string
@@ -1114,7 +1131,18 @@ export function defineConfig(config: TelaConfig): TelaConfig {
1114
1131
  else if (collection.version !== undefined) throw new Error(`${collection.name}: only a data source has a \`version\`.`)
1115
1132
  }
1116
1133
 
1117
- for (const hook of config.afterPublish ?? []) checkHook(hook, known)
1134
+ const gatheredNames = new Set<string>()
1135
+ for (const list of config.gathered ?? []) {
1136
+ if (!/^[a-z][a-z0-9-]*$/.test(list.name)) throw new Error(`gathered: "${list.name}" must start lowercase and use letters, digits and hyphens.`)
1137
+ if (known.has(list.name)) throw new Error(`gathered: "${list.name}" is a collection's name, and would be written over its data.`)
1138
+ if (gatheredNames.has(list.name)) throw new Error(`gathered: "${list.name}" is declared twice.`)
1139
+ const unknown = (list.collections ?? []).filter((name) => !known.has(name))
1140
+ if (unknown.length) throw new Error(`gathered: ${list.name} names ${unknown.join(", ")}, which no collection is called.`)
1141
+ gatheredNames.add(list.name)
1142
+ }
1143
+
1144
+ // A hook may wait on a gathered list as it would a data source.
1145
+ for (const hook of config.afterPublish ?? []) checkHook(hook, new Set([...known, ...gatheredNames]))
1118
1146
 
1119
1147
  const declared = declaredCollections.find((c) => c.name === "users")
1120
1148
 
@@ -1202,6 +1230,7 @@ export function defineConfig(config: TelaConfig): TelaConfig {
1202
1230
  ...(config.siteAliases?.length ? { siteAliases: config.siteAliases } : {}),
1203
1231
  ...(config.dataAddress ? { dataAddress: config.dataAddress } : {}),
1204
1232
  ...(config.afterPublish?.length ? { afterPublish: config.afterPublish } : {}),
1233
+ ...(config.gathered?.length ? { gathered: config.gathered } : {}),
1205
1234
  ...(config.siteName ? { siteName: config.siteName } : {}),
1206
1235
  ...(config.userNames ? { userNames: true } : {}),
1207
1236
  }
@@ -2,7 +2,9 @@ import { mkdir, writeFile, readFile, rm } from "fs/promises"
2
2
  import { existsSync } from "fs"
3
3
  import { dirname, join } from "path"
4
4
  import { sql } from "../db/client.ts"
5
+ import { config } from "../config/load.ts"
5
6
  import { findCollection } from "./collections.ts"
7
+ import { writeGathered } from "./gathered.ts"
6
8
  import { DIALECT } from "./richtext.ts"
7
9
  import { withDerived } from "./derive-values.ts"
8
10
  import type { Collection } from "../config/types.ts"
@@ -288,6 +290,14 @@ export async function exportRelease(
288
290
  cells.push(indexCell(collection))
289
291
  }
290
292
 
293
+ const gathered = await writeGathered(
294
+ config.gathered ?? [],
295
+ published.map((row: any) => ({ id: String(row.id), collection: String(row.collection), data: row.data ?? {} })),
296
+ options,
297
+ )
298
+ files.push(...gathered.files)
299
+ cells.push(...gathered.cells)
300
+
291
301
  return { files, cells }
292
302
  }
293
303
 
@@ -330,6 +340,12 @@ export async function exportRemoval(
330
340
  const files = [path]
331
341
  const cells = [entryCell(collection, slug)]
332
342
 
343
+ if (row) {
344
+ const gathered = await writeGathered(config.gathered ?? [], [{ id: String(row.id), collection, data: null }], options)
345
+ files.push(...gathered.files)
346
+ cells.push(...gathered.cells)
347
+ }
348
+
333
349
  if (isDataSource(collection)) return { files, cells }
334
350
 
335
351
  // The index always changes: the entry has left it.
@@ -663,5 +679,15 @@ export async function republishEntries(options: { root: string; collections?: st
663
679
  }),
664
680
  options.root,
665
681
  )
666
- return { files: [...rewritten.files, ...pictures.files], cells: [...rewritten.cells, ...pictures.cells] }
682
+ // Every published entry is here unless the caller narrowed it, and then the
683
+ // ledger only hears about the ones it was given.
684
+ const gathered = await writeGathered(
685
+ config.gathered ?? [],
686
+ rows.map((row: any) => ({ id: String(row.id), collection: String(row.collection), data: row.data ?? {} })),
687
+ { root: options.root, complete: !options.collections },
688
+ )
689
+ return {
690
+ files: [...rewritten.files, ...pictures.files, ...gathered.files],
691
+ cells: [...rewritten.cells, ...pictures.cells, ...gathered.cells],
692
+ }
667
693
  }
@@ -0,0 +1,103 @@
1
+ import { mkdir, readFile, writeFile } from "fs/promises"
2
+ import { dirname, join } from "path"
3
+ import type { GatheredList } from "../config/types.ts"
4
+
5
+ /**
6
+ * Lists gathered from what is published: every Vimeo video on the site, say,
7
+ * for a server that will only stream those.
8
+ *
9
+ * Kept as a ledger of what each published entry adds, so a publish touches one
10
+ * line of it rather than reading the whole site again. The ledger lives in the
11
+ * content repo with the list it explains: the list is then only ever a
12
+ * function of the ledger, and the repo's history shows which entry brought a
13
+ * value in.
14
+ */
15
+
16
+ /** Published like a data source, so whatever serves those serves this. */
17
+ export const gatheredPath = (name: string) => join("content", "data", `${name}.json`)
18
+ /** Outside `content/`: the ledger is Tela's bookkeeping, and a site rebuilds nothing when it moves. */
19
+ export const ledgerPath = (name: string) => join(".tela", "gathered", `${name}.json`)
20
+ export const gatheredCell = (name: string) => `cms:data:${name}`
21
+
22
+ /** An entry as it is now published, or `data: null` for one taken off the site. */
23
+ export interface GatherChange {
24
+ id: string
25
+ collection: string
26
+ data: Record<string, unknown> | null
27
+ }
28
+
29
+ type Ledger = Record<string, string[]>
30
+
31
+ async function read(root: string, path: string): Promise<unknown> {
32
+ try {
33
+ return JSON.parse(await readFile(join(root, path), "utf-8"))
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+
39
+ async function write(root: string, path: string, data: unknown) {
40
+ const file = join(root, path)
41
+ await mkdir(dirname(file), { recursive: true })
42
+ await writeFile(file, JSON.stringify(data, null, 2) + "\n")
43
+ }
44
+
45
+ function ledgerFrom(file: unknown): Ledger {
46
+ if (!file || typeof file !== "object" || Array.isArray(file)) return {}
47
+ return Object.fromEntries(
48
+ Object.entries(file).filter(([, values]) => Array.isArray(values) && values.every((one) => typeof one === "string")),
49
+ ) as Ledger
50
+ }
51
+
52
+ /** What one entry adds: text, once each, in a steady order. */
53
+ export function valuesFrom(list: GatheredList, change: GatherChange): string[] {
54
+ if (!change.data) return []
55
+ if (list.collections && !list.collections.includes(change.collection)) return []
56
+ const found = list.from(change.data, { collection: change.collection }) ?? []
57
+ const values = [...found].filter((one) => typeof one === "string" || typeof one === "number").map(String).filter(Boolean)
58
+ return [...new Set(values)].sort()
59
+ }
60
+
61
+ const sorted = (ledger: Ledger): Ledger => Object.fromEntries(Object.keys(ledger).sort().map((id) => [id, ledger[id]!]))
62
+
63
+ /**
64
+ * Bring each list up to date with entries that were just published or taken
65
+ * down. `complete` says the changes are everything published, so entries the
66
+ * ledger remembers and the changes don't name are gone.
67
+ *
68
+ * Returns the files written. A list's cell is reported only when the list
69
+ * itself changed; the ledger moving alone rebuilds nothing.
70
+ */
71
+ export async function writeGathered(
72
+ lists: GatheredList[],
73
+ changes: GatherChange[],
74
+ options: { root: string; complete?: boolean },
75
+ ): Promise<{ files: string[]; cells: string[] }> {
76
+ const files: string[] = []
77
+ const cells: string[] = []
78
+
79
+ for (const list of lists) {
80
+ const was = ledgerFrom(await read(options.root, ledgerPath(list.name)))
81
+ const next: Ledger = options.complete ? {} : { ...was }
82
+
83
+ for (const change of changes) {
84
+ const values = valuesFrom(list, change)
85
+ if (values.length) next[change.id] = values
86
+ else delete next[change.id]
87
+ }
88
+
89
+ const ledger = sorted(next)
90
+ if (JSON.stringify(ledger) !== JSON.stringify(sorted(was))) {
91
+ await write(options.root, ledgerPath(list.name), ledger)
92
+ files.push(ledgerPath(list.name))
93
+ }
94
+
95
+ const published = { values: [...new Set(Object.values(ledger).flat())].sort() }
96
+ if (JSON.stringify(await read(options.root, gatheredPath(list.name))) === JSON.stringify(published)) continue
97
+ await write(options.root, gatheredPath(list.name), published)
98
+ files.push(gatheredPath(list.name))
99
+ cells.push(gatheredCell(list.name))
100
+ }
101
+
102
+ return { files, cells }
103
+ }