@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 ADDED
@@ -0,0 +1,40 @@
1
+ # Changelog
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
+
9
+ ## 0.2.0
10
+
11
+ ### Upgrading from 0.1.x
12
+
13
+ - **Pictures are published by reference.** A page now names each picture by its media id, and publishing writes the picture itself to `content/media/<id>.json`. A site reading published content has to read those files (or resolve `picture: "<id>"` some other way). Data sources and previews still carry pictures copied in. Run `tela republish` once after upgrading, so content published before moves over in one commit.
14
+ - **`data` is reserved.** No collection may be named `data`, since data sources publish under `content/data/`.
15
+
16
+ ### Added
17
+
18
+ - **Link field** (`link()`): search pages and files, or paste any address. A field chooses what it accepts (pages, web addresses, files, email, phone), and `siteAliases` turns links pasted from the live site into pages.
19
+ - **Data sources:** a record of facts with no page, published to `content/data/<name>.json`, previewed as a page or as data. Each publish writes its shape beside it (`<name>.schema.json`) and refuses a change that would break what reads it.
20
+ - **Publish hooks** (`afterPublish`): called after each publish, such as to tell another service the content changed.
21
+ - **Toggle input** for yes-or-no fields.
22
+ - **Date fields can default to today.**
23
+ - **Fallbacks and blocks made for particular pages.**
24
+ - **Limits on many references** (`maxRows`), and an entry is kept out of its own picker.
25
+ - **`tela media-sync`:** checks every published picture against the media library and republishes what changed there (alt text, credit, a picture binned).
26
+ - **`tela republish [collection …]`:** writes every published entry again under the current rules, from the published versions, in one commit.
27
+ - A picture's words changing in the library republishes it straight away, with the data sources carrying it.
28
+
29
+ ### Fixed
30
+
31
+ - `defineConfig` keeps site aliases, the data address and publish hooks.
32
+ - Collection names are checked, and a data source's own slug is accepted.
33
+ - A markdown field's length is measured by what a reader sees, not by its link addresses.
34
+ - A save that leaves out a composite field is checked like any other.
35
+ - Keyboard shortcuts are labelled for the keyboard in use.
36
+ - Data preview text, and a page preview that can't be shown says why.
37
+
38
+ ## 0.1.3
39
+
40
+ The first release as `@nickpaustian/tela`.
package/bin/tela.ts CHANGED
@@ -35,6 +35,8 @@ const USAGE = `tela <command>
35
35
  create-user <email> [--editor]
36
36
  set-password <email>
37
37
  media-words [--apply] move words on media records into the library
38
+ media-sync republish pictures whose words changed in the library
39
+ republish [collection …] write every published entry again under the current rules
38
40
 
39
41
  Run from the folder holding tela.config.ts, or set TELA_CONFIG.`
40
42
 
@@ -134,6 +136,12 @@ switch (command) {
134
136
  if (code === 0) code = await vite("build")
135
137
  break
136
138
  }
139
+ case "republish":
140
+ code = await run(["bun", script("scripts/republish.ts"), ...rest])
141
+ break
142
+ case "media-sync":
143
+ code = await run(["bun", script("scripts/media-sync.ts")])
144
+ break
137
145
  case "check":
138
146
  code = await run(["bun", script("scripts/check-components.ts")])
139
147
  break
package/lib/index.js CHANGED
@@ -1,3 +1,39 @@
1
+ // src/content/link-address.ts
2
+ var LINK_KINDS = ["pages", "files", "web", "sections", "email", "phone"];
3
+ var DEFAULT_LINK_KINDS = ["pages", "web", "sections", "email", "phone"];
4
+ function acceptedKinds(accepts) {
5
+ const known = (accepts ?? DEFAULT_LINK_KINDS).filter((one) => LINK_KINDS.includes(one));
6
+ return known.length ? known : DEFAULT_LINK_KINDS;
7
+ }
8
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
9
+ var escapeName = (name) => name.replace(/[^\w-]/g, "");
10
+ function linkPattern(kinds, collections) {
11
+ const entries = collections?.length ? `(${collections.map(escapeName).join("|")})` : "(?!media/)[\\w-]+";
12
+ const parts = {
13
+ pages: [`tela:${entries}/${UUID}(#\\S*)?`, "/(?!/)\\S*"],
14
+ files: [`tela:media/${UUID}`],
15
+ web: ["https?://\\S+"],
16
+ sections: ["#\\S+"],
17
+ email: ["mailto:\\S+@\\S+"],
18
+ phone: ["tel:\\+?\\d+"]
19
+ };
20
+ return `^(${kinds.flatMap((kind) => parts[kind]).join("|")})$`;
21
+ }
22
+ var listed = (words) => words.length <= 1 ? words[0] ?? "" : `${words.slice(0, -1).join(", ")} or ${words[words.length - 1]}`;
23
+ function linkMessage(kinds) {
24
+ const choose = [kinds.includes("pages") ? "a page" : "", kinds.includes("files") ? "a file" : ""].filter(Boolean);
25
+ const paste = [
26
+ kinds.includes("web") ? "a full address" : "",
27
+ kinds.includes("email") ? "an email" : "",
28
+ kinds.includes("phone") ? "a phone number" : ""
29
+ ].filter(Boolean);
30
+ const said = [
31
+ choose.length ? `Choose ${choose.join(" or ")} from the list` : "",
32
+ paste.length ? `paste ${listed(paste)}` : ""
33
+ ].filter(Boolean).join(", or ");
34
+ return said.charAt(0).toUpperCase() + said.slice(1) + ".";
35
+ }
36
+
1
37
  // src/config/fields.ts
2
38
  function slugField({ from = "title", label = "Slug" } = {}) {
3
39
  return {
@@ -74,6 +110,56 @@ function person(name, label, options = {}) {
74
110
  ]
75
111
  };
76
112
  }
113
+ function link(name, label, options = {}) {
114
+ const { required, accepts, collections, ...rest } = options;
115
+ const kinds = acceptedKinds(accepts);
116
+ return {
117
+ name,
118
+ label,
119
+ type: "link",
120
+ ...required ? { required: true } : {},
121
+ patterns: [{ pattern: linkPattern(kinds, collections), message: linkMessage(kinds) }],
122
+ options: { ...rest, accepts: kinds, ...collections?.length ? { collections } : {} }
123
+ };
124
+ }
125
+ function customBlock(name, {
126
+ label,
127
+ description,
128
+ note,
129
+ for: pages,
130
+ uses,
131
+ once = true,
132
+ kept = true,
133
+ content = {},
134
+ editable = []
135
+ }) {
136
+ return {
137
+ name,
138
+ label,
139
+ description,
140
+ note,
141
+ for: pages,
142
+ ...uses?.length ? { uses } : {},
143
+ once,
144
+ kept,
145
+ content,
146
+ fields: editable.map((field) => field.fallback === undefined && content[field.name] !== undefined ? { ...field, fallback: content[field.name] } : field)
147
+ };
148
+ }
149
+ function dataSource(name, options) {
150
+ return { ...options, name, data: true };
151
+ }
152
+
153
+ // src/config/components.ts
154
+ function dataFields(fields) {
155
+ return fields.flatMap((field) => {
156
+ if (field.type === "note")
157
+ return [];
158
+ if (field.type === "group" && field.fields)
159
+ return dataFields(field.fields);
160
+ return [field];
161
+ });
162
+ }
77
163
 
78
164
  // src/config/seo.ts
79
165
  var SEO_FIELDS = {
@@ -89,8 +175,9 @@ function seoGroup(collection, siteName) {
89
175
  return null;
90
176
  const options = collection.seo === true ? {} : collection.seo;
91
177
  const at = `Collection "${collection.name}" seo`;
178
+ const stored = dataFields(collection.fields);
92
179
  const named = (name) => {
93
- const field = collection.fields.find((one) => one.name === name);
180
+ const field = stored.find((one) => one.name === name);
94
181
  if (!field)
95
182
  throw new Error(`${at}: falls back to "${name}", which is not one of its fields.`);
96
183
  return field;
@@ -111,7 +198,7 @@ function seoGroup(collection, siteName) {
111
198
  maxLength: 70,
112
199
  counter: { target: options.title?.target ?? 60, ...suffix ? { adds: suffix } : {} },
113
200
  options: {
114
- hint: options.title?.hint ?? `Leave empty to use the ${collection.fields.some((one) => one.name === titleField) ? labelOf(titleField) : "title"}.`
201
+ hint: options.title?.hint ?? `Leave empty to use the ${stored.some((one) => one.name === titleField) ? labelOf(titleField) : "title"}.`
115
202
  }
116
203
  },
117
204
  {
@@ -252,6 +339,7 @@ var STORAGE_TYPES = {
252
339
  number: (v) => typeof v === "number" && Number.isFinite(v),
253
340
  boolean: (v) => typeof v === "boolean",
254
341
  repeater: (v) => Array.isArray(v),
342
+ link: (v) => typeof v === "string",
255
343
  reference: (v) => typeof v === "string" || Array.isArray(v) && v.every((one) => typeof one === "string"),
256
344
  block: (v) => typeof v === "object" && v !== null && !Array.isArray(v)
257
345
  };
@@ -320,14 +408,14 @@ var USER_BASE_FIELDS = [
320
408
  ];
321
409
  var BLOCK_KEY = "block";
322
410
  var LABEL_KEY = "internalLabel";
323
- function checkFields(fields, path, known = new Set) {
411
+ function checkFields(fields, path, known = new Set, dataNames = new Set) {
324
412
  for (const field of fields) {
325
413
  const where = `${path}.${field.name}`;
326
414
  if (!STORAGE_TYPES[field.type] && !LAYOUT_TYPES[field.type]) {
327
415
  throw new Error(`${where}: "${field.type}" is not a storage type. ` + `Use one of ${Object.keys(STORAGE_TYPES).join(", ")}, and name the ` + `component with \`component\` if a custom one renders it.`);
328
416
  }
329
417
  if (field.fields)
330
- checkFields(field.fields, where, known);
418
+ checkFields(field.fields, where, known, dataNames);
331
419
  for (const tool of field.tools ?? []) {
332
420
  if (!TOOL_NAMES.includes(tool)) {
333
421
  throw new Error(`${where}: "${tool}" is not a formatting tool. ` + `Use one of ${TOOL_NAMES.join(", ")}.`);
@@ -357,18 +445,38 @@ function checkFields(fields, path, known = new Set) {
357
445
  }
358
446
  }
359
447
  if (field.of)
360
- checkFields(field.of, where, known);
448
+ checkFields(field.of, where, known, dataNames);
361
449
  const seen = new Set;
362
450
  for (const block of field.blocks ?? []) {
363
451
  if (seen.has(block.name)) {
364
452
  throw new Error(`${where}: two blocks are both named "${block.name}".`);
365
453
  }
454
+ if (block.content && BLOCK_KEY in block.content) {
455
+ throw new Error(`${where}: block "${block.name}" has "${BLOCK_KEY}" in its content, which is how a row records its shape.`);
456
+ }
457
+ for (const source of block.uses ?? []) {
458
+ if (!dataNames.has(source)) {
459
+ throw new Error(`${where}: block "${block.name}" uses "${source}", which is not a data source.`);
460
+ }
461
+ }
462
+ if (block.for?.some((page) => !page.startsWith("/"))) {
463
+ throw new Error(`${where}: block "${block.name}" is for pages by address, each starting with "/".`);
464
+ }
366
465
  seen.add(block.name);
367
- checkFields(block.fields, `${where}[${block.name}]`, known);
466
+ checkFields(block.fields, `${where}[${block.name}]`, known, dataNames);
368
467
  }
369
468
  }
370
469
  }
371
470
  var BUILT_IN = ["users", "groups", "media"];
471
+ var COLLECTION_NAME = /^[a-z][a-zA-Z0-9-]*$/;
472
+ function checkCollectionName(name) {
473
+ if (!COLLECTION_NAME.test(name)) {
474
+ throw new Error(`"${name}": a collection's name is a folder in the content repo and part of its rebuild keys, ` + `so start with a lowercase letter and use only letters, digits and hyphens.`);
475
+ }
476
+ if (name === "data") {
477
+ throw new Error(`"data" is reserved: data sources are published to content/data/ and rebuilt as cms:data:<name>, ` + `so a collection called data would overwrite them. Choose another name.`);
478
+ }
479
+ }
372
480
  function checkWorkflow(collection) {
373
481
  const workflow = collection.workflow;
374
482
  if (!workflow)
@@ -399,13 +507,61 @@ function checkWorkflow(collection) {
399
507
  }
400
508
  }
401
509
  }
510
+ function checkDataSource(collection) {
511
+ const where = collection.name;
512
+ if (collection.url)
513
+ throw new Error(`${where}: a data source has no page, so no \`url\`.`);
514
+ if (collection.publishable === false)
515
+ throw new Error(`${where}: a data source is published, so it cannot set \`publishable: false\`.`);
516
+ if (collection.version !== undefined && !(Number.isInteger(collection.version) && collection.version >= 1)) {
517
+ throw new Error(`${where}: \`version\` counts up from 1.`);
518
+ }
519
+ const flat = (fields) => fields.flatMap((field) => field.type === "group" ? flat(field.fields ?? []) : [field]);
520
+ if (flat(collection.fields).some((field) => field.name === "slug")) {
521
+ throw new Error(`${where}: a data source is named by its collection, so it has no "slug" field.`);
522
+ }
523
+ }
524
+ function checkHook(hook, known) {
525
+ let url;
526
+ try {
527
+ url = new URL(hook.url);
528
+ } catch {
529
+ throw new Error(`afterPublish: "${hook.url}" is not an address.`);
530
+ }
531
+ if (url.protocol !== "https:" && url.protocol !== "http:")
532
+ throw new Error(`afterPublish: ${hook.url} must be http or https.`);
533
+ const unknown = (hook.collections ?? []).filter((name) => !known.has(name));
534
+ if (unknown.length)
535
+ throw new Error(`afterPublish: ${hook.url} names ${unknown.join(", ")}, which no collection is called.`);
536
+ }
402
537
  function defineConfig(config) {
403
538
  const known = new Set([...config.collections.map((one) => one.name), ...BUILT_IN]);
404
539
  const declaredCollections = config.collections.map((one) => withSeo(one, config.siteName));
540
+ const dataNames = new Set(config.collections.filter((one) => one.data).map((one) => one.name));
405
541
  for (const collection of declaredCollections) {
406
- checkFields(collection.fields, collection.name, known);
542
+ checkCollectionName(collection.name);
543
+ checkFields(collection.fields, collection.name, known, dataNames);
407
544
  checkWorkflow(collection);
545
+ if (collection.data)
546
+ checkDataSource(collection);
547
+ else if (collection.version !== undefined)
548
+ throw new Error(`${collection.name}: only a data source has a \`version\`.`);
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);
408
562
  }
563
+ for (const hook of config.afterPublish ?? [])
564
+ checkHook(hook, new Set([...known, ...gatheredNames]));
409
565
  const declared = declaredCollections.find((c) => c.name === "users");
410
566
  const [address, ...access] = USER_BASE_FIELDS;
411
567
  const userFields = config.userNames ? [address, ...USER_NAME_FIELDS, ...access] : USER_BASE_FIELDS;
@@ -456,6 +612,10 @@ function defineConfig(config) {
456
612
  ...config.overrides ? { overrides: config.overrides } : {},
457
613
  ...config.components ? { components: config.components } : {},
458
614
  ...config.site ? { site: config.site } : {},
615
+ ...config.siteAliases?.length ? { siteAliases: config.siteAliases } : {},
616
+ ...config.dataAddress ? { dataAddress: config.dataAddress } : {},
617
+ ...config.afterPublish?.length ? { afterPublish: config.afterPublish } : {},
618
+ ...config.gathered?.length ? { gathered: config.gathered } : {},
459
619
  ...config.siteName ? { siteName: config.siteName } : {},
460
620
  ...config.userNames ? { userNames: true } : {}
461
621
  };
@@ -751,14 +911,18 @@ function iconFor(collection) {
751
911
  export {
752
912
  BUILT_IN,
753
913
  LAYOUT_TYPES,
914
+ LINK_KINDS,
754
915
  SEO_FIELDS,
755
916
  STORAGE_TYPES,
756
917
  TYPE_ICONS,
918
+ customBlock,
919
+ dataSource,
757
920
  dateRange,
758
921
  defineConfig,
759
922
  iconFor,
760
923
  imageUse,
761
924
  initialsOf,
925
+ link,
762
926
  person,
763
927
  personName,
764
928
  slugField,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nickpaustian/tela",
3
- "version": "0.1.3",
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",
@@ -34,8 +34,11 @@
34
34
  "scripts/create-user.ts",
35
35
  "scripts/set-password.ts",
36
36
  "scripts/media-words.ts",
37
+ "scripts/media-sync.ts",
38
+ "scripts/republish.ts",
37
39
  "LICENSE",
38
- "README.md"
40
+ "README.md",
41
+ "CHANGELOG.md"
39
42
  ],
40
43
  "scripts": {
41
44
  "dev": "bun bin/tela.ts dev",
@@ -1,9 +1,29 @@
1
1
  import { config } from "../src/config/load.ts"
2
2
  import { checkProject, reportCheck } from "../src/config/check.ts"
3
3
  import { componentRoots } from "../src/project.ts"
4
+ import { checkShapes } from "../src/content/shape.ts"
4
5
 
5
6
  /**
6
7
  * The pre-build check, runnable on its own. `tela check` is the same call.
7
8
  */
8
9
  const ok = reportCheck(checkProject(config.collections, componentRoots(config.components), config.overrides))
9
10
  if (!ok) process.exit(1)
11
+
12
+ const root = process.env.TELA_CONTENT_REPO
13
+ const sources = config.collections.filter((one) => one.data)
14
+ if (sources.length && !root) {
15
+ console.log("- data source shapes not checked: TELA_CONTENT_REPO is not set")
16
+ } else if (sources.length && root) {
17
+ const found = await checkShapes(config.collections, root)
18
+ if (found.length) {
19
+ console.error("\nA data source no longer matches the shape apps read:\n")
20
+ for (const problem of found) {
21
+ console.error(` ${problem.source}: ${problem.problems.join("; ")}`)
22
+ }
23
+ console.error(
24
+ "\nRaise its `version` if the break is meant, so readers can tell; otherwise put the field back.",
25
+ )
26
+ process.exit(1)
27
+ }
28
+ console.log(`✓ ${sources.length} data source shape(s) checked against ${root}`)
29
+ }
@@ -0,0 +1,41 @@
1
+ import { readdir } from "fs/promises"
2
+ import { join } from "path"
3
+ import { republishPictures } from "../src/content/export.ts"
4
+ import { commitContent } from "../src/content/git.ts"
5
+
6
+ /**
7
+ * Every published picture checked against the media library: a credit
8
+ * corrected or a picture replaced in the library itself, not through Tela,
9
+ * republished with the data sources carrying it, and committed so the site
10
+ * rebuilds what shows it. Nothing changed, nothing is written.
11
+ *
12
+ * tela media-sync
13
+ *
14
+ * Run on a timer beside the server for libraries edited directly.
15
+ */
16
+ const root = process.env.TELA_CONTENT_REPO
17
+ if (!root) {
18
+ console.error("Set TELA_CONTENT_REPO to the content repo checkout.")
19
+ process.exit(1)
20
+ }
21
+
22
+ const files = await readdir(join(root, "content", "media")).catch(() => [] as string[])
23
+ const ids = files.filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -".json".length))
24
+ if (!ids.length) {
25
+ console.log("No published pictures to check.")
26
+ process.exit(0)
27
+ }
28
+
29
+ const exported = await republishPictures(ids, { root })
30
+ if (!exported.files.length) {
31
+ console.log(`${ids.length} published picture(s) checked; none changed.`)
32
+ process.exit(0)
33
+ }
34
+
35
+ const commit = await commitContent(exported, {
36
+ root,
37
+ message: `Update pictures from the media library\n\nRebuild: ${exported.cells.join(" ")}\n`,
38
+ push: process.env.TELA_PUSH !== "false",
39
+ })
40
+ console.log(`${ids.length} checked; updated ${exported.files.join(", ")}${commit.sha ? ` in ${commit.sha.slice(0, 7)}` : ""}.`)
41
+ process.exit(0)
@@ -0,0 +1,24 @@
1
+ import { republishEntries } from "../src/content/export.ts"
2
+ import { commitContent } from "../src/content/git.ts"
3
+
4
+ /**
5
+ * Every published entry written again under the rules publishing follows now,
6
+ * committed as one change: after Tela changes how content is written, so the
7
+ * content repo matches without anyone republishing page by page.
8
+ *
9
+ * tela republish [collection …]
10
+ */
11
+ const root = process.env.TELA_CONTENT_REPO
12
+ if (!root) {
13
+ console.error("Set TELA_CONTENT_REPO to the content repo checkout.")
14
+ process.exit(1)
15
+ }
16
+ const only = process.argv.slice(2)
17
+ const exported = await republishEntries({ root, ...(only.length ? { collections: only } : {}) })
18
+ const commit = await commitContent(exported, {
19
+ root,
20
+ message: `Republish under the current rules\n\nRebuild: ${exported.cells.join(" ")}\n`,
21
+ push: process.env.TELA_PUSH !== "false",
22
+ })
23
+ console.log(commit.sha ? `Rewrote ${commit.files.length} file(s) in ${commit.sha.slice(0, 7)}.` : "Everything already matches.")
24
+ process.exit(0)
package/src/api.ts CHANGED
@@ -148,12 +148,12 @@ export const api = {
148
148
 
149
149
  if (response.status === 401) {
150
150
  window.location.href = "/login"
151
- return { ok: false as const, body: "" }
151
+ return { ok: false as const, body: "", status: 401, headers: new Headers() }
152
152
  }
153
153
 
154
- return { ok: response.ok, body: await response.text() }
154
+ return { ok: response.ok, body: await response.text(), status: response.status, headers: response.headers }
155
155
  } catch {
156
- return { ok: false as const, body: "Could not reach the server." }
156
+ return { ok: false as const, body: "Could not reach the server.", status: 0, headers: new Headers() }
157
157
  }
158
158
  },
159
159