inlaycms 0.2.0 → 0.4.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 (122) hide show
  1. package/README.md +334 -1
  2. package/assets/admin/admin.css +1 -1
  3. package/assets/admin/admin.js +1 -1
  4. package/assets/admin/editor.js +59 -44
  5. package/dist/adapters/admin/screens/redirects.js +12 -3
  6. package/dist/adapters/admin/views/layout.js +27 -7
  7. package/dist/adapters/cli/remote.js +9 -1
  8. package/dist/adapters/mcp/tools/redirects.js +16 -2
  9. package/dist/adapters/site/assets.d.ts +11 -0
  10. package/dist/adapters/site/assets.js +71 -0
  11. package/dist/adapters/site/cache.d.ts +2 -1
  12. package/dist/adapters/site/cache.js +6 -1
  13. package/dist/adapters/site/context.d.ts +6 -0
  14. package/dist/adapters/site/context.js +38 -13
  15. package/dist/adapters/site/head.d.ts +30 -7
  16. package/dist/adapters/site/head.js +145 -20
  17. package/dist/adapters/site/headers.d.ts +5 -0
  18. package/dist/adapters/site/headers.js +31 -0
  19. package/dist/adapters/site/plugin.d.ts +2 -0
  20. package/dist/adapters/site/plugin.js +32 -9
  21. package/dist/adapters/site/public.js +7 -24
  22. package/dist/adapters/site/render.d.ts +5 -0
  23. package/dist/adapters/site/render.js +23 -8
  24. package/dist/adapters/site/routes.d.ts +6 -0
  25. package/dist/adapters/site/routes.js +8 -3
  26. package/dist/adapters/site/seo.d.ts +20 -0
  27. package/dist/adapters/site/seo.js +45 -0
  28. package/dist/adapters/site/sitemap.d.ts +1 -1
  29. package/dist/adapters/site/sitemap.js +1 -1
  30. package/dist/config.js +3 -2
  31. package/dist/core/agent/format.js +1 -1
  32. package/dist/core/agent/schema.js +3 -0
  33. package/dist/core/boot.js +7 -0
  34. package/dist/core/check.js +6 -1
  35. package/dist/core/content/dry-run.d.ts +7 -6
  36. package/dist/core/content/dry-run.js +8 -8
  37. package/dist/core/content/publish.d.ts +1 -1
  38. package/dist/core/content/publish.js +5 -3
  39. package/dist/core/content/read.d.ts +3 -0
  40. package/dist/core/content/reader.js +3 -2
  41. package/dist/core/content/refs.js +1 -1
  42. package/dist/core/content/search.js +2 -2
  43. package/dist/core/content/shipped-images.d.ts +32 -0
  44. package/dist/core/content/shipped-images.js +62 -0
  45. package/dist/core/content/shipped-input.d.ts +9 -3
  46. package/dist/core/content/shipped-input.js +165 -28
  47. package/dist/core/content/shipped.js +8 -3
  48. package/dist/core/content/validate.js +7 -1
  49. package/dist/core/core.d.ts +5 -1
  50. package/dist/core/core.js +5 -4
  51. package/dist/core/db/connection.d.ts +6 -0
  52. package/dist/core/db/connection.js +13 -1
  53. package/dist/core/db/migrate.js +2 -0
  54. package/dist/core/db/migrations/0007_published_at.d.ts +3 -0
  55. package/dist/core/db/migrations/0007_published_at.js +16 -0
  56. package/dist/core/db/schema.d.ts +1 -0
  57. package/dist/core/export/export.js +3 -1
  58. package/dist/core/export/format.d.ts +8 -1
  59. package/dist/core/export/format.js +3 -2
  60. package/dist/core/export/read.js +7 -0
  61. package/dist/core/export/stage.d.ts +1 -1
  62. package/dist/core/export/stage.js +24 -1
  63. package/dist/core/fields/builtins.d.ts +28 -0
  64. package/dist/core/fields/builtins.js +103 -11
  65. package/dist/core/fields/define.d.ts +6 -0
  66. package/dist/core/fields/widgets.d.ts +7 -0
  67. package/dist/core/fields/widgets.js +77 -28
  68. package/dist/core/media/library.js +2 -2
  69. package/dist/core/messages/en.d.ts +72 -6
  70. package/dist/core/messages/en.js +72 -6
  71. package/dist/core/redirects/collapse.d.ts +17 -1
  72. package/dist/core/redirects/collapse.js +19 -3
  73. package/dist/core/redirects/redirects.d.ts +13 -12
  74. package/dist/core/redirects/redirects.js +141 -53
  75. package/dist/core/redirects/rule.d.ts +25 -0
  76. package/dist/core/redirects/rule.js +55 -0
  77. package/dist/core/registry/define.d.ts +40 -0
  78. package/dist/core/registry/define.js +3 -0
  79. package/dist/core/registry/registry.d.ts +21 -0
  80. package/dist/core/registry/registry.js +114 -6
  81. package/dist/core/registry/render.d.ts +37 -1
  82. package/dist/core/registry/route.d.ts +4 -0
  83. package/dist/core/release/bundle.js +30 -5
  84. package/dist/core/release/manifest.d.ts +14 -0
  85. package/dist/core/release/manifest.js +42 -17
  86. package/dist/core/release/markdown-file.d.ts +21 -0
  87. package/dist/core/release/markdown-file.js +172 -0
  88. package/dist/core/release/pack.js +2 -2
  89. package/dist/core/release/read.js +4 -1
  90. package/dist/core/release/site-dir.d.ts +4 -0
  91. package/dist/core/release/site-dir.js +8 -0
  92. package/dist/core/report.d.ts +8 -2
  93. package/dist/core/richtext/html.d.ts +3 -1
  94. package/dist/core/richtext/html.js +18 -4
  95. package/dist/core/richtext/inline.d.ts +22 -0
  96. package/dist/core/richtext/inline.js +33 -0
  97. package/dist/core/richtext/markdown.d.ts +19 -1
  98. package/dist/core/richtext/markdown.js +187 -22
  99. package/dist/core/richtext/schema.d.ts +22 -5
  100. package/dist/core/richtext/schema.js +81 -4
  101. package/dist/core/site/live.d.ts +1 -0
  102. package/dist/core/site/live.js +1 -0
  103. package/dist/core/site/paths.d.ts +6 -0
  104. package/dist/core/site/paths.js +13 -0
  105. package/dist/core/site/resolve.d.ts +1 -1
  106. package/dist/core/site/resolve.js +119 -30
  107. package/dist/core/site/sitemap.d.ts +1 -1
  108. package/dist/core/site/sitemap.js +4 -0
  109. package/dist/core/types.d.ts +28 -3
  110. package/dist/host/app.d.ts +5 -0
  111. package/dist/host/app.js +10 -1
  112. package/dist/host/dev.js +3 -7
  113. package/dist/host/diff.d.ts +19 -1
  114. package/dist/host/diff.js +32 -2
  115. package/dist/index.d.ts +2 -2
  116. package/dist/markdown-modules.d.ts +8 -0
  117. package/dist/markdown-modules.js +1 -0
  118. package/dist/site.d.ts +8 -3
  119. package/dist/site.js +6 -0
  120. package/dist/testing.d.ts +22 -0
  121. package/dist/testing.js +155 -0
  122. package/package.json +7 -1
@@ -1,14 +1,17 @@
1
- import { readFile } from 'node:fs/promises';
1
+ import { readFile, stat } from 'node:fs/promises';
2
2
  import { basename, isAbsolute } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { InlayError } from '../errors.js';
5
5
  import { fieldValues } from '../fields/walk.js';
6
6
  import { isRecord } from '../fields/zod-internals.js';
7
7
  import { inspectUpload } from '../media/library.js';
8
- import { markdownToRichText } from '../richtext/markdown.js';
8
+ import { markdownToInlineText } from '../richtext/inline.js';
9
+ import { markdownImages, markdownToRichText } from '../richtext/markdown.js';
10
+ import { DEFAULT_RICH_TEXT } from '../richtext/schema.js';
9
11
  import { docLabels } from './schema.js';
12
+ import { imageTarget, realInside, realInsideSync } from './shipped-images.js';
10
13
  import { contentIssue } from './validate.js';
11
- const KINDS = new Set(['image', 'file', 'richText', 'ref', 'link']);
14
+ const KINDS = new Set(['image', 'file', 'richText', 'inlineText', 'ref', 'link']);
12
15
  /** The start of a Markdown link target `](inlay:key/<type>` or `](inlay:key/<type>/<key>`; text elsewhere is left alone. */
13
16
  const KEY_HREF = /\]\(inlay:key\/([\w-]+)(?:\/([\w-]+))?(?=[\s)])/g;
14
17
  /** `root` with the value at `path` replaced, copying only the containers along the path. */
@@ -52,13 +55,11 @@ function localPath(file, shipped) {
52
55
  return null;
53
56
  }
54
57
  }
55
- /** Shipped content can't contain images in rich text: there is no way to name their files. */
56
- function withoutImages(opts) {
57
- return opts && { ...opts, features: opts.features.filter((f) => f !== 'image') };
58
- }
58
+ /** Stands in for an image that couldn't be read, so the Markdown is still checked for everything else. */
59
+ const NO_IMAGE = '0'.repeat(64);
59
60
  /**
60
61
  * Turns shipped content as a developer writes it into the stored shape:
61
- * Markdown strings in rich text fields become rich text, and `{ file, alt? }`
62
+ * Markdown strings in rich text and inline text fields become rich text, and `{ file, alt? }`
62
63
  * in image and file fields is read from disk, checked like an upload, and
63
64
  * replaced by `{ media, alt? }`. References to other shipped documents by key
64
65
  * become their group ids: `{ key }` in `ref` fields, `{ document: { type, key? } }`
@@ -86,6 +87,95 @@ export async function resolveShippedInput(deps, type, input, resolveKey) {
86
87
  return value;
87
88
  return groupOf(path, { type: target, key: value.key }) ?? value;
88
89
  };
90
+ /** `markdown` with its `inlay:key` link targets as `inlay:document` ones, or null after reporting an unknown key. */
91
+ const withDocumentLinks = (path, markdown) => {
92
+ let unknownKey = false;
93
+ const out = markdown.replace(KEY_HREF, (href, refType, key) => {
94
+ const id = groupOf(path, key === undefined ? { type: refType } : { type: refType, key });
95
+ if (id === null)
96
+ unknownKey = true;
97
+ return id === null ? href : `](inlay:document/${id}`;
98
+ });
99
+ return unknownKey ? null : out;
100
+ };
101
+ /** Image files named in rich text, by `file:` URL, each read once. */
102
+ const imageReads = new Map();
103
+ const readImage = async (url, path) => {
104
+ let file = path;
105
+ if (deps.shippedFiles) {
106
+ const shipped = deps.shippedFiles.get(url);
107
+ if (shipped === undefined)
108
+ return { code: 'not_found', messageId: 'issue.shippedImageUnknown' };
109
+ file = shipped;
110
+ }
111
+ else {
112
+ const siteDir = deps.registry.siteDir;
113
+ if (siteDir === null)
114
+ return { code: 'invalid', messageId: 'issue.shippedImageOutside' };
115
+ const exists = await stat(path).then(() => true, () => false);
116
+ if (!exists)
117
+ return { code: 'not_found', messageId: 'issue.shippedImageMissing' };
118
+ const real = await realInside(path, siteDir);
119
+ if (real === null)
120
+ return { code: 'invalid', messageId: 'issue.shippedImageOutside' };
121
+ file = real;
122
+ }
123
+ let bytes;
124
+ try {
125
+ bytes = await readFile(file);
126
+ }
127
+ catch {
128
+ return { code: 'not_found', messageId: 'issue.shippedImageMissing' };
129
+ }
130
+ try {
131
+ const info = await inspectUpload(deps, bytes, basename(path));
132
+ if (!info.mime.startsWith('image/'))
133
+ return { code: 'wrong_media_type', messageId: 'issue.shippedImageNotImage' };
134
+ files.set(info.id, { bytes, ...info });
135
+ return { id: info.id };
136
+ }
137
+ catch (e) {
138
+ if (!(e instanceof InlayError) || e.code !== 'validation')
139
+ throw e;
140
+ return { code: 'invalid', messageId: 'issue.shippedImageInvalid', problem: e.message };
141
+ }
142
+ };
143
+ /**
144
+ * The library image each image target in `markdown` names, by target as written. Targets naming a file are read;
145
+ * those that can't be used are reported at `path` and map to `NO_IMAGE`. Returns `ok: false` if any was reported.
146
+ */
147
+ const shippedImages = async (path, markdown) => {
148
+ const images = new Map();
149
+ let ok = true;
150
+ for (const { src, line } of markdownImages(markdown)) {
151
+ const fail = (code, messageId, problem) => {
152
+ const params = { line: String(line), src };
153
+ issue(path, code, messageId, problem === undefined ? params : { ...params, problem });
154
+ images.set(src, NO_IMAGE);
155
+ ok = false;
156
+ };
157
+ const target = imageTarget(src, deps.registry.siteDir);
158
+ if (target.kind === 'remote')
159
+ fail('invalid', 'issue.shippedImageRemote');
160
+ else if (target.kind === 'rooted')
161
+ fail('invalid', 'issue.shippedImageRooted');
162
+ else if (target.kind === 'outside')
163
+ fail('invalid', 'issue.shippedImageOutside');
164
+ else if (target.kind === 'file') {
165
+ let read = imageReads.get(target.url);
166
+ if (read === undefined) {
167
+ read = readImage(target.url, target.path);
168
+ imageReads.set(target.url, read);
169
+ }
170
+ const result = await read;
171
+ if ('id' in result)
172
+ images.set(src, result.id);
173
+ else
174
+ fail(result.code, result.messageId, result.problem);
175
+ }
176
+ }
177
+ return { ok, images };
178
+ };
89
179
  /** The stored value for one found value, or `undefined` to leave it as it is. */
90
180
  const resolve = async (path, meta, value) => {
91
181
  if (meta.kind === 'ref') {
@@ -103,29 +193,33 @@ export async function resolveShippedInput(deps, type, input, resolveKey) {
103
193
  const id = groupOf(path, ref);
104
194
  return id === null ? undefined : { ...value, document: id };
105
195
  }
196
+ if (meta.kind === 'inlineText') {
197
+ if (typeof value !== 'string')
198
+ return undefined;
199
+ const markdown = withDocumentLinks(path, value);
200
+ if (markdown === null)
201
+ return undefined;
202
+ const result = markdownToInlineText(markdown);
203
+ for (const problem of result.ok ? [] : result.problems) {
204
+ issue(path, 'invalid', 'issue.richText', { problem: problem.message });
205
+ }
206
+ return result.ok ? result.doc : undefined;
207
+ }
106
208
  if (meta.kind === 'richText') {
107
209
  if (typeof value !== 'string')
108
210
  return undefined;
109
- let unknownKey = false;
110
- const markdown = value.replace(KEY_HREF, (href, refType, key) => {
111
- const id = groupOf(path, key === undefined ? { type: refType } : { type: refType, key });
112
- if (id === null)
113
- unknownKey = true;
114
- return id === null ? href : `](inlay:document/${id}`;
115
- });
116
- if (unknownKey)
211
+ const markdown = withDocumentLinks(path, value);
212
+ if (markdown === null)
117
213
  return undefined;
118
- const result = markdownToRichText(markdown, meta.richText);
214
+ // A field that allows no images reports them itself, without any file being read.
215
+ const named = (meta.richText ?? DEFAULT_RICH_TEXT).features.includes('image')
216
+ ? await shippedImages(path, markdown)
217
+ : { ok: true, images: new Map() };
218
+ const result = markdownToRichText(markdown, meta.richText, { images: named.images });
119
219
  for (const problem of result.ok ? [] : result.problems) {
120
220
  issue(path, 'invalid', 'issue.richText', { problem: problem.message });
121
221
  }
122
- // What only the image-free reading finds are images the field allows but shipped content can't name.
123
- const bare = markdownToRichText(markdown, withoutImages(meta.richText));
124
- const known = new Set(result.ok ? [] : result.problems.map((p) => p.message));
125
- const images = bare.ok ? [] : bare.problems.filter((p) => !known.has(p.message));
126
- for (const image of images)
127
- issue(path, 'invalid', 'issue.shippedRichTextImage', { line: String(image.line) });
128
- return result.ok && images.length === 0 ? result.doc : undefined;
222
+ return result.ok && named.ok ? result.doc : undefined;
129
223
  }
130
224
  if (!isRecord(value) || !Object.hasOwn(value, 'file'))
131
225
  return undefined;
@@ -186,13 +280,42 @@ export async function resolveShippedInput(deps, type, input, resolveKey) {
186
280
  return { input: out, files, issues };
187
281
  }
188
282
  const FILE_KINDS = new Set(['image', 'file']);
283
+ const RICH_TEXT_KINDS = new Set(['richText']);
284
+ /** `input`, shipped content of `type`, with each rich-text Markdown string in its fields and slots replaced by `map`'s. */
285
+ export function mapRichText(registry, type, input, map) {
286
+ const { template } = registry.getType(type);
287
+ const mapAll = (schema, value) => {
288
+ let out = value;
289
+ for (const found of fieldValues(schema, value, RICH_TEXT_KINDS)) {
290
+ if (typeof found.value === 'string')
291
+ out = setAt(out, found.path, map(found.value));
292
+ }
293
+ return out;
294
+ };
295
+ const out = { ...input };
296
+ if (input.fields !== undefined)
297
+ out.fields = mapAll(template.fields, input.fields);
298
+ if (input.slots !== undefined) {
299
+ const slots = {};
300
+ for (const [key, given] of Object.entries(input.slots)) {
301
+ const slot = template.slots[key];
302
+ slots[key] = given === false || !slot ? given : mapAll(slot.block.schema, given);
303
+ }
304
+ out.slots = slots;
305
+ }
306
+ return out;
307
+ }
189
308
  /**
190
309
  * Every `{ file }` named in the registry's shipped content (template fields and slots), once per source: the
191
- * source as written (a file: URL's href or an absolute path) and the local path it names. Values that don't name
192
- * a local file are left out; applying the content reports them.
310
+ * source as written (a file: URL's href or an absolute path), the local path it names, and the path to `read` it
311
+ * by. Images named by a file in rich-text Markdown are listed too, by their `file:` URL's href, so one file named
312
+ * several ways is listed once; such an image is read by its real path, the one checked to be inside the site's
313
+ * folder. Values that don't name a local file, and images outside the site's folder or missing, are left out;
314
+ * applying the content reports them.
193
315
  */
194
316
  export function shippedFiles(registry) {
195
317
  const found = new Map();
318
+ const { siteDir } = registry;
196
319
  const collect = (schema, value) => {
197
320
  for (const { value: v } of fieldValues(schema, value, FILE_KINDS)) {
198
321
  if (!isRecord(v) || !Object.hasOwn(v, 'file'))
@@ -200,7 +323,21 @@ export function shippedFiles(registry) {
200
323
  const source = fileSource(v.file);
201
324
  const path = localPath(v.file);
202
325
  if (source !== null && path !== null)
203
- found.set(source, path);
326
+ found.set(source, { path, read: path });
327
+ }
328
+ if (siteDir === null)
329
+ return;
330
+ for (const { value: v } of fieldValues(schema, value, RICH_TEXT_KINDS)) {
331
+ if (typeof v !== 'string')
332
+ continue;
333
+ for (const { src } of markdownImages(v)) {
334
+ const target = imageTarget(src, siteDir);
335
+ if (target.kind !== 'file' || found.has(target.url))
336
+ continue;
337
+ const real = realInsideSync(target.path, siteDir);
338
+ if (real !== null)
339
+ found.set(target.url, { path: target.path, read: real });
340
+ }
204
341
  }
205
342
  };
206
343
  for (const [type, documents] of registry.content) {
@@ -217,5 +354,5 @@ export function shippedFiles(registry) {
217
354
  }
218
355
  }
219
356
  }
220
- return [...found].map(([source, path]) => ({ source, path }));
357
+ return [...found].map(([source, { path, read }]) => ({ source, path, read }));
221
358
  }
@@ -71,7 +71,7 @@ function withoutRefsTo(deps, type, data, gone) {
71
71
  const last = r.path.at(-1);
72
72
  const parentPath = r.path.slice(0, -1);
73
73
  const parent = getAt(out, parentPath);
74
- if (r.meta.kind === 'richText') {
74
+ if (r.meta.kind === 'richText' || r.meta.kind === 'inlineText') {
75
75
  const fixed = (doc) => {
76
76
  const walked = withoutLinks(doc, gone);
77
77
  const parsed = parseRichText(walked, r.meta.richText ?? DEFAULT_RICH_TEXT);
@@ -416,14 +416,19 @@ export async function writeShippedContent(deps, plan, opts = {}) {
416
416
  await autoRedirect(deps, ctx, { ...before, head_slug: slug, head_path: path });
417
417
  await trx
418
418
  .updateTable('documents')
419
- .set({ published_rev: revId, published_slug: slug, published_path: path })
419
+ .set((eb) => ({
420
+ published_rev: revId,
421
+ published_slug: slug,
422
+ published_path: path,
423
+ first_published_at: eb.fn.coalesce('first_published_at', eb.val(at)),
424
+ }))
420
425
  .where('id', '=', documentId)
421
426
  .execute();
422
427
  items.push({ documentId, revisionId: revId, action: 'publish' });
423
428
  }
424
429
  for (const a of actions)
425
430
  await syncRefs(deps, a.item.documentId);
426
- await recordEvent(deps, ctx, null, items);
431
+ await recordEvent(deps, ctx, null, items, at);
427
432
  return report;
428
433
  }
429
434
  /**
@@ -1,4 +1,4 @@
1
- import { DATE_CHECK, DATETIME_CHECK, NON_BLANK } from '../fields/builtins.js';
1
+ import { DATE_CHECK, DATETIME_CHECK, INLINE_TEXT_MAX, NON_BLANK, TITLE_TEMPLATE_CHECK } from '../fields/builtins.js';
2
2
  import { isRecord } from '../fields/zod-internals.js';
3
3
  import { t } from '../messages/index.js';
4
4
  import { docLabels, documentSchema } from './schema.js';
@@ -62,6 +62,9 @@ function mapIssue(issue, value) {
62
62
  return { code: 'out_of_range', messageId: 'issue.tooHigh', params: { max } };
63
63
  }
64
64
  }
65
+ if (issue.code === 'custom' && issue.params?.check === INLINE_TEXT_MAX) {
66
+ return { code: 'too_long', messageId: 'issue.tooLong', params: { max: bound(issue.params.max) } };
67
+ }
65
68
  if (isRequired(issue, value))
66
69
  return { code: 'required', messageId: 'issue.required', params: {} };
67
70
  if (issue.code === 'too_small') {
@@ -80,6 +83,9 @@ function mapIssue(issue, value) {
80
83
  if (issue.code === 'custom' && issue.params?.check === DATETIME_CHECK) {
81
84
  return { code: 'invalid', messageId: 'issue.datetime', params: {} };
82
85
  }
86
+ if (issue.code === 'custom' && issue.params?.check === TITLE_TEMPLATE_CHECK) {
87
+ return { code: 'invalid', messageId: 'issue.titleTemplate', params: {} };
88
+ }
83
89
  if (issue.code === 'invalid_type') {
84
90
  const messageId = EXPECTED[issue.expected];
85
91
  if (messageId)
@@ -16,7 +16,7 @@ import type { ReleaseMigration } from './registry/migration.js';
16
16
  import { type Registry } from './registry/registry.js';
17
17
  import { type SiteLockStatus } from './site-lock/site-lock.js';
18
18
  import { type SitemapEntry } from './site/sitemap.js';
19
- import type { Activity, ContentInput, Ctx, DocumentData, DocumentSummary, DocumentView, ContentRef, Usage, DiffEntry, RevisionMeta, UploadLimits, MediaInfo, MediaStatus, LiveDocument, LiveState, RouteMatch, Redirect, RedirectInput } from './types.js';
19
+ import type { Activity, ContentInput, Ctx, DocumentData, DocumentSummary, DocumentView, ContentRef, Usage, DiffEntry, RevisionMeta, UploadLimits, MediaInfo, MediaStatus, LiveDocument, LiveState, RouteMatch, Redirect, RedirectInput, CodeRedirect } from './types.js';
20
20
  export type { PatchOp, PublishResult, SaveResult, ShippedItem, ShippedReport };
21
21
  export interface Core {
22
22
  registry: Registry;
@@ -184,6 +184,10 @@ export interface Core {
184
184
  created: number;
185
185
  updated: number;
186
186
  }>;
187
+ /** The site's code redirect rules, in definition order, each marked when an admin rule or a page answers first. */
188
+ listCodeRedirects(): Promise<CodeRedirect[]>;
189
+ /** The `from` of each code rule that, with the stored rules, sends visitors round a loop with no stop. */
190
+ codeRedirectLoops(): Promise<string[]>;
187
191
  /** The backups on disk, newest first. Owners only. */
188
192
  listBackups(ctx: Ctx): Promise<BackupInfo[]>;
189
193
  /** Makes a manual backup of the database and media. Owners only. */
package/dist/core/core.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { findSingleton, findTranslation, getDocument, listEntries } from './content/read.js';
2
2
  import { findEntry, searchEntries } from './content/search.js';
3
3
  import { recentActivity } from './content/activity.js';
4
+ import { withTransaction } from './content/dry-run.js';
4
5
  import { describeChanges, listPendingChanges, publish, unpublish } from './content/publish.js';
5
6
  import { applyShippedContent, } from './content/shipped.js';
6
7
  import { patchDraft } from './content/patch.js';
@@ -29,7 +30,7 @@ import { mediaVariant } from './media/variants.js';
29
30
  import { fileMediaStore } from './media/store.js';
30
31
  import { buildRegistry } from './registry/registry.js';
31
32
  import { checkSitePassword, readSiteLock, setSiteLock, setSitePassword } from './site-lock/site-lock.js';
32
- import { createRedirect, deleteRedirect, importRedirects, listRedirects } from './redirects/redirects.js';
33
+ import { codeRedirectLoops, createRedirect, deleteRedirect, importRedirects, listCodeRedirects, listRedirects } from './redirects/redirects.js';
33
34
  import { liveAlternates, liveDocuments, liveEntries, liveSingleton } from './site/live.js';
34
35
  import { resolvePath } from './site/resolve.js';
35
36
  import { sitemapEntries } from './site/sitemap.js';
@@ -88,9 +89,7 @@ export function createCore(opts) {
88
89
  listPendingChanges: () => listPendingChanges(deps),
89
90
  recentActivity: (o) => recentActivity(deps, o),
90
91
  applyShippedContent: live((o) => applyShippedContent(deps, o), (r, o) => !o?.dryRun && (r.created.length > 0 || r.replaced.length > 0)),
91
- runReleaseMigrations: live((releaseId, migrations) => deps.db
92
- .transaction()
93
- .execute((trx) => runReleaseMigrations({ ...deps, db: trx }, releaseId, migrations, systemCtx('release'))), (ran) => ran.length > 0),
92
+ runReleaseMigrations: live((releaseId, migrations) => withTransaction(deps, (tx) => runReleaseMigrations(tx, releaseId, migrations, systemCtx('release'))), (ran) => ran.length > 0),
94
93
  createTranslation: (groupId, locale, ctx) => createTranslation(deps, groupId, locale, ctx),
95
94
  findUsages: (target) => findUsages(deps, target),
96
95
  countEntries: (o) => countEntries(deps, o),
@@ -196,6 +195,8 @@ export function createCore(opts) {
196
195
  createRedirect: live((input, ctx) => createRedirect(deps, input, ctx)),
197
196
  deleteRedirect: live((id, ctx) => deleteRedirect(deps, id, ctx)),
198
197
  importRedirects: live((csv, ctx) => importRedirects(deps, csv, ctx)),
198
+ listCodeRedirects: () => listCodeRedirects(deps),
199
+ codeRedirectLoops: () => codeRedirectLoops(deps),
199
200
  onLiveChange: (listener) => {
200
201
  listeners.add(listener);
201
202
  return () => {
@@ -4,3 +4,9 @@ export declare function openDatabase(path: string, opts?: {
4
4
  readonly?: boolean;
5
5
  busyTimeoutMs?: number;
6
6
  }): Kysely<Database>;
7
+ /**
8
+ * SQLite's `data_version` for a connection `openDatabase` made: it changes when another connection (another process,
9
+ * say) commits to the database, and not for the connection's own writes. Read straight from the connection, so it
10
+ * never waits behind a transaction Kysely has open on it. Null for a connection made elsewhere.
11
+ */
12
+ export declare function dataVersion(db: Kysely<Database>): number | null;
@@ -1,5 +1,6 @@
1
1
  import BetterSqlite3 from 'better-sqlite3';
2
2
  import { Kysely, SqliteDialect } from 'kysely';
3
+ const handles = new WeakMap();
3
4
  export function openDatabase(path, opts = {}) {
4
5
  const sqlite = opts.readonly
5
6
  ? new BetterSqlite3(path, { readonly: true, fileMustExist: true })
@@ -8,5 +9,16 @@ export function openDatabase(path, opts = {}) {
8
9
  sqlite.pragma(`busy_timeout = ${opts.busyTimeoutMs ?? 5000}`);
9
10
  if (path !== ':memory:' && !opts.readonly)
10
11
  sqlite.pragma('journal_mode = WAL');
11
- return new Kysely({ dialect: new SqliteDialect({ database: sqlite }) });
12
+ const db = new Kysely({ dialect: new SqliteDialect({ database: sqlite }) });
13
+ handles.set(db, sqlite);
14
+ return db;
15
+ }
16
+ /**
17
+ * SQLite's `data_version` for a connection `openDatabase` made: it changes when another connection (another process,
18
+ * say) commits to the database, and not for the connection's own writes. Read straight from the connection, so it
19
+ * never waits behind a transaction Kysely has open on it. Null for a connection made elsewhere.
20
+ */
21
+ export function dataVersion(db) {
22
+ const sqlite = handles.get(db);
23
+ return sqlite === undefined ? null : sqlite.pragma('data_version', { simple: true });
12
24
  }
@@ -5,6 +5,7 @@ import * as m0003 from './migrations/0003_redirects.js';
5
5
  import * as m0004 from './migrations/0004_token_cutoffs.js';
6
6
  import * as m0005 from './migrations/0005_site_lock.js';
7
7
  import * as m0006 from './migrations/0006_releases.js';
8
+ import * as m0007 from './migrations/0007_published_at.js';
8
9
  const systemMigrations = {
9
10
  '0001_content': m0001,
10
11
  '0002_media': m0002,
@@ -12,6 +13,7 @@ const systemMigrations = {
12
13
  '0004_token_cutoffs': m0004,
13
14
  '0005_site_lock': m0005,
14
15
  '0006_releases': m0006,
16
+ '0007_published_at': m0007,
15
17
  };
16
18
  function systemMigrator(db) {
17
19
  return new Migrator({
@@ -0,0 +1,3 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** The first time each document was published, filled from the publish history. */
3
+ export declare function up(db: Kysely<any>): Promise<void>;
@@ -0,0 +1,16 @@
1
+ import { sql } from 'kysely';
2
+ /** The first time each document was published, filled from the publish history. */
3
+ export async function up(db) {
4
+ await db.schema.alterTable('documents').addColumn('first_published_at', 'text').execute();
5
+ await sql `
6
+ UPDATE documents SET first_published_at = (
7
+ SELECT min(e.at) FROM publish_events e, json_each(e.items) i
8
+ WHERE json_extract(i.value, '$.documentId') = documents.id
9
+ AND json_extract(i.value, '$.action') = 'publish'
10
+ ) WHERE first_published_at IS NULL
11
+ `.execute(db);
12
+ await sql `
13
+ UPDATE documents SET first_published_at = (SELECT created_at FROM revisions WHERE id = documents.published_rev)
14
+ WHERE first_published_at IS NULL AND published_rev IS NOT NULL
15
+ `.execute(db);
16
+ }
@@ -15,6 +15,7 @@ export interface DocumentsTable {
15
15
  created_at: string;
16
16
  key: string | null;
17
17
  edition: number | null;
18
+ first_published_at: string | null;
18
19
  }
19
20
  export interface RevisionsTable {
20
21
  id: Generated<number>;
@@ -9,6 +9,7 @@ import { InlayError } from '../errors.js';
9
9
  import { fileMediaStore } from '../media/store.js';
10
10
  import { t } from '../messages/index.js';
11
11
  import { readSiteLock } from '../site-lock/site-lock.js';
12
+ import { targetOf } from '../redirects/rule.js';
12
13
  import { inlayVersion } from '../version.js';
13
14
  import { EXPORT_FORMAT, EXPORT_FORMAT_VERSION, } from './format.js';
14
15
  import { storedTypeSchema } from './schema.js';
@@ -119,6 +120,7 @@ async function readContent(db) {
119
120
  createdAt: d.created_at,
120
121
  key: d.key,
121
122
  edition: d.edition,
123
+ firstPublishedAt: d.first_published_at,
122
124
  })),
123
125
  ...revs.map((r) => ({
124
126
  record: 'revision',
@@ -149,7 +151,7 @@ async function readRedirects(db) {
149
151
  return rows.map((r) => ({
150
152
  id: r.id,
151
153
  from: r.from_path,
152
- to: r.to_group_id !== null ? { group: r.to_group_id } : { path: r.to_path ?? '' },
154
+ to: r.to_group_id !== null ? { group: r.to_group_id } : targetOf(r.to_path ?? ''),
153
155
  status: r.status,
154
156
  source: r.source,
155
157
  note: r.note,
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import type { DocumentData, DocumentKind, RedirectSource, RevisionSource } from '../types.js';
3
3
  export declare const EXPORT_FORMAT = "inlay-export";
4
- export declare const EXPORT_FORMAT_VERSION = 1;
4
+ export declare const EXPORT_FORMAT_VERSION = 2;
5
5
  export interface Manifest {
6
6
  format: typeof EXPORT_FORMAT;
7
7
  formatVersion: number;
@@ -42,6 +42,8 @@ export interface DocumentRecord {
42
42
  createdAt: string;
43
43
  key: string | null;
44
44
  edition: number | null;
45
+ /** Absent: not recorded, filled from the publish events on import. Null: never published. */
46
+ firstPublishedAt?: string | null;
45
47
  }
46
48
  export interface RevisionRecord {
47
49
  record: 'revision';
@@ -77,6 +79,8 @@ export interface RedirectRecord {
77
79
  path: string;
78
80
  } | {
79
81
  group: string;
82
+ } | {
83
+ url: string;
80
84
  };
81
85
  status: 301 | 302;
82
86
  source: RedirectSource;
@@ -155,6 +159,7 @@ export declare const contentRecordSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
155
159
  createdAt: z.ZodString;
156
160
  key: z.ZodDefault<z.ZodNullable<z.ZodString>>;
157
161
  edition: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
162
+ firstPublishedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
158
163
  }, z.core.$strip>, z.ZodObject<{
159
164
  record: z.ZodLiteral<"revision">;
160
165
  id: z.ZodNumber;
@@ -204,6 +209,8 @@ export declare const redirectsSchema: z.ZodArray<z.ZodObject<{
204
209
  path: z.ZodString;
205
210
  }, z.core.$strip>, z.ZodObject<{
206
211
  group: z.ZodString;
212
+ }, z.core.$strip>, z.ZodObject<{
213
+ url: z.ZodString;
207
214
  }, z.core.$strip>]>;
208
215
  status: z.ZodUnion<readonly [z.ZodLiteral<301>, z.ZodLiteral<302>]>;
209
216
  source: z.ZodEnum<{
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  export const EXPORT_FORMAT = 'inlay-export';
3
- export const EXPORT_FORMAT_VERSION = 1;
3
+ export const EXPORT_FORMAT_VERSION = 2;
4
4
  /** Exports made before shipped content had editions say `initial` for what is now `release`. */
5
5
  const source = z.preprocess((v) => (v === 'initial' ? 'release' : v), z.enum(['admin', 'mcp', 'restore', 'import', 'release', 'system']));
6
6
  const nullableString = z.string().nullable();
@@ -44,6 +44,7 @@ const documentRecord = z.object({
44
44
  createdAt: z.string(),
45
45
  key: nullableString.default(null),
46
46
  edition: nullableInt.default(null),
47
+ firstPublishedAt: nullableString.optional(),
47
48
  });
48
49
  const revisionRecord = z.object({
49
50
  record: z.literal('revision'),
@@ -71,7 +72,7 @@ export const contentRecordSchema = z.discriminatedUnion('record', [documentRecor
71
72
  export const redirectsSchema = z.array(z.object({
72
73
  id: z.number().int(),
73
74
  from: z.string(),
74
- to: z.union([z.object({ path: z.string() }), z.object({ group: z.string() })]),
75
+ to: z.union([z.object({ path: z.string() }), z.object({ group: z.string() }), z.object({ url: z.string() })]),
75
76
  status: z.union([z.literal(301), z.literal(302)]),
76
77
  source: z.enum(['manual', 'auto', 'import']),
77
78
  note: nullableString,
@@ -8,6 +8,7 @@ import { InlayError } from '../errors.js';
8
8
  import { t } from '../messages/index.js';
9
9
  import { paramNames } from '../redirects/collapse.js';
10
10
  import { cleanPath, redirectFrom } from '../redirects/redirects.js';
11
+ import { externalTarget } from '../redirects/rule.js';
11
12
  import { EXPORT_FORMAT, EXPORT_FORMAT_VERSION, contentRecordSchema, manifestSchema, mediaIndexSchema, redirectsSchema, } from './format.js';
12
13
  const FIXED = ['manifest.json', 'content.ndjson', 'redirects.json', 'media.json'];
13
14
  const MEDIA_ID = /^[0-9a-f]{64}$/;
@@ -209,6 +210,12 @@ function checkRedirects(redirects, documents, manifest) {
209
210
  fail(t('export.unknownGroup', { id: r.to.group }));
210
211
  return;
211
212
  }
213
+ if ('url' in r.to) {
214
+ if (externalTarget(r.to.url) !== r.to.url || (paramNames(r.from).length > 0 && paramNames(r.to.url).length > 0)) {
215
+ fail(t('export.redirectTo', { path: r.to.url }));
216
+ }
217
+ return;
218
+ }
212
219
  const to = r.to.path;
213
220
  const params = paramNames(r.from);
214
221
  if (storedPath(to, cleanPath) !== to || to.split('/')[1] === manifest.defaultLocale || paramNames(to).some((n) => !params.includes(n))) {
@@ -1,4 +1,4 @@
1
- import type { Kysely } from 'kysely';
1
+ import { type Kysely } from 'kysely';
2
2
  import { type Core } from '../core.js';
3
3
  import type { Database } from '../db/schema.js';
4
4
  import type { SiteDefinition } from '../registry/define.js';
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { rm } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
+ import { sql } from 'kysely';
4
5
  import { upgradeDatabase } from '../boot.js';
5
6
  import { syncRefs } from '../content/refs.js';
6
7
  import { createCore } from '../core.js';
@@ -20,6 +21,24 @@ const derived = (data) => ({
20
21
  slug: typeof data?.slug === 'string' ? data.slug : null,
21
22
  path: typeof data?.path === 'string' ? data.path : null,
22
23
  });
24
+ /** Fills `first_published_at` for documents whose record doesn't carry it (or says null of a published one), as migration 0007 does. */
25
+ async function backfillPublishedAt(trx, ids) {
26
+ for (let i = 0; i < ids.length; i += 500)
27
+ await backfillChunk(trx, ids.slice(i, i + 500));
28
+ }
29
+ async function backfillChunk(trx, ids) {
30
+ await sql `
31
+ UPDATE documents SET first_published_at = (
32
+ SELECT min(e.at) FROM publish_events e, json_each(e.items) i
33
+ WHERE json_extract(i.value, '$.documentId') = documents.id
34
+ AND json_extract(i.value, '$.action') = 'publish'
35
+ ) WHERE first_published_at IS NULL AND id IN (${sql.join(ids)})
36
+ `.execute(trx);
37
+ await sql `
38
+ UPDATE documents SET first_published_at = (SELECT created_at FROM revisions WHERE id = documents.published_rev)
39
+ WHERE first_published_at IS NULL AND published_rev IS NOT NULL AND id IN (${sql.join(ids)})
40
+ `.execute(trx);
41
+ }
23
42
  /**
24
43
  * Loads `bundle` (minus `exclude`) into a new scratch database in `bundle.dir`
25
44
  * and brings it up to date with `site` the way boot does. Problems go into
@@ -61,6 +80,7 @@ export async function stageBundle(site, bundle, exclude, now) {
61
80
  created_at: d.createdAt,
62
81
  key: d.key,
63
82
  edition: d.edition,
83
+ first_published_at: d.firstPublishedAt ?? null,
64
84
  })
65
85
  .execute();
66
86
  }
@@ -103,13 +123,16 @@ export async function stageBundle(site, bundle, exclude, now) {
103
123
  })
104
124
  .execute();
105
125
  }
126
+ await backfillPublishedAt(trx, documents
127
+ .filter((d) => d.firstPublishedAt === undefined || (d.firstPublishedAt === null && d.publishedRevision !== null))
128
+ .map((d) => d.id));
106
129
  for (const r of redirects) {
107
130
  await trx
108
131
  .insertInto('redirects')
109
132
  .values({
110
133
  id: r.id,
111
134
  from_path: r.from,
112
- to_path: 'path' in r.to ? r.to.path : null,
135
+ to_path: 'path' in r.to ? r.to.path : 'url' in r.to ? r.to.url : null,
113
136
  to_group_id: 'group' in r.to ? r.to.group : null,
114
137
  status: r.status,
115
138
  source: r.source,