inlaycms 0.4.1 → 0.6.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 (151) hide show
  1. package/README.md +18 -709
  2. package/assets/admin/admin.css +1 -1
  3. package/assets/admin/admin.js +1 -1
  4. package/assets/admin/editor.js +63 -46
  5. package/assets/site/consent.js +1 -0
  6. package/dist/adapters/admin/context.d.ts +1 -1
  7. package/dist/adapters/admin/context.js +1 -0
  8. package/dist/adapters/admin/publish.js +2 -2
  9. package/dist/adapters/admin/routes.d.ts +2 -0
  10. package/dist/adapters/admin/routes.js +2 -0
  11. package/dist/adapters/admin/screens/backups.js +2 -2
  12. package/dist/adapters/admin/screens/editor.js +5 -2
  13. package/dist/adapters/admin/screens/integrations.d.ts +4 -0
  14. package/dist/adapters/admin/screens/integrations.js +140 -0
  15. package/dist/adapters/admin/screens/lists.js +2 -1
  16. package/dist/adapters/admin/screens/releases.js +9 -4
  17. package/dist/adapters/admin/views/data-table.js +1 -1
  18. package/dist/adapters/admin/views/layout.d.ts +1 -1
  19. package/dist/adapters/admin/views/layout.js +15 -2
  20. package/dist/adapters/cli/bin.js +8 -3
  21. package/dist/adapters/cli/main.js +12 -2
  22. package/dist/adapters/mcp/agent-refs.d.ts +2 -1
  23. package/dist/adapters/mcp/agent-refs.js +4 -4
  24. package/dist/adapters/mcp/tools/publish.js +1 -1
  25. package/dist/adapters/mcp/tools/read.js +19 -4
  26. package/dist/adapters/mcp/tools/write.js +5 -1
  27. package/dist/adapters/site/cache.d.ts +8 -2
  28. package/dist/adapters/site/cache.js +13 -4
  29. package/dist/adapters/site/code-files.d.ts +44 -0
  30. package/dist/adapters/site/code-files.js +212 -0
  31. package/dist/adapters/site/consent.d.ts +9 -0
  32. package/dist/adapters/site/consent.js +26 -0
  33. package/dist/adapters/site/context.d.ts +9 -1
  34. package/dist/adapters/site/context.js +106 -27
  35. package/dist/adapters/site/csp.d.ts +11 -0
  36. package/dist/adapters/site/csp.js +36 -0
  37. package/dist/adapters/site/head.d.ts +2 -0
  38. package/dist/adapters/site/head.js +7 -20
  39. package/dist/adapters/site/headers.d.ts +5 -2
  40. package/dist/adapters/site/headers.js +13 -6
  41. package/dist/adapters/site/integrations.d.ts +48 -0
  42. package/dist/adapters/site/integrations.js +118 -0
  43. package/dist/adapters/site/media-routes.d.ts +2 -0
  44. package/dist/adapters/site/media-routes.js +2 -1
  45. package/dist/adapters/site/plugin.d.ts +2 -0
  46. package/dist/adapters/site/plugin.js +78 -40
  47. package/dist/adapters/site/preview.d.ts +2 -0
  48. package/dist/adapters/site/preview.js +10 -5
  49. package/dist/adapters/site/render.d.ts +31 -14
  50. package/dist/adapters/site/render.js +33 -7
  51. package/dist/adapters/site/routes.d.ts +3 -0
  52. package/dist/adapters/site/routes.js +11 -6
  53. package/dist/adapters/site/scripts.d.ts +6 -0
  54. package/dist/adapters/site/scripts.js +27 -0
  55. package/dist/adapters/site/sitemap.d.ts +2 -1
  56. package/dist/adapters/site/sitemap.js +3 -3
  57. package/dist/core/auth/roles.d.ts +1 -1
  58. package/dist/core/auth/roles.js +1 -0
  59. package/dist/core/boot.d.ts +2 -0
  60. package/dist/core/boot.js +3 -0
  61. package/dist/core/content/shipped-input.js +1 -2
  62. package/dist/core/content/validate.d.ts +7 -0
  63. package/dist/core/content/validate.js +24 -1
  64. package/dist/core/core.d.ts +29 -0
  65. package/dist/core/core.js +10 -2
  66. package/dist/core/db/migrate.js +2 -0
  67. package/dist/core/db/migrations/0008_integrations.d.ts +3 -0
  68. package/dist/core/db/migrations/0008_integrations.js +11 -0
  69. package/dist/core/db/schema.d.ts +11 -0
  70. package/dist/core/export/export.js +4 -0
  71. package/dist/core/export/format.d.ts +11 -0
  72. package/dist/core/export/format.js +4 -0
  73. package/dist/core/export/import.js +2 -1
  74. package/dist/core/export/replace.d.ts +6 -1
  75. package/dist/core/export/replace.js +4 -1
  76. package/dist/core/export/report.d.ts +6 -0
  77. package/dist/core/export/report.js +7 -0
  78. package/dist/core/fields/builtins.d.ts +4 -0
  79. package/dist/core/fields/builtins.js +11 -1
  80. package/dist/core/fields/widgets.js +5 -1
  81. package/dist/core/integrations/integrations.d.ts +32 -0
  82. package/dist/core/integrations/integrations.js +80 -0
  83. package/dist/core/integrations/warnings.d.ts +4 -0
  84. package/dist/core/integrations/warnings.js +29 -0
  85. package/dist/core/media/store.d.ts +2 -0
  86. package/dist/core/media/store.js +17 -1
  87. package/dist/core/media/variants.d.ts +14 -0
  88. package/dist/core/media/variants.js +54 -0
  89. package/dist/core/messages/en.d.ts +83 -2
  90. package/dist/core/messages/en.js +83 -2
  91. package/dist/core/registry/code-image.d.ts +16 -0
  92. package/dist/core/registry/code-image.js +13 -0
  93. package/dist/core/registry/define.d.ts +12 -0
  94. package/dist/core/registry/define.js +3 -0
  95. package/dist/core/registry/designed.d.ts +6 -0
  96. package/dist/core/registry/designed.js +8 -0
  97. package/dist/core/registry/integration.d.ts +48 -0
  98. package/dist/core/registry/integration.js +29 -0
  99. package/dist/core/registry/js.d.ts +9 -0
  100. package/dist/core/registry/js.js +39 -0
  101. package/dist/core/registry/registry.js +46 -0
  102. package/dist/core/registry/render.d.ts +45 -5
  103. package/dist/core/release/bundle.d.ts +3 -1
  104. package/dist/core/release/bundle.js +169 -11
  105. package/dist/core/release/manifest.d.ts +29 -6
  106. package/dist/core/release/manifest.js +26 -25
  107. package/dist/core/release/pack.js +13 -2
  108. package/dist/core/release/pointer.js +14 -3
  109. package/dist/core/release/read.d.ts +4 -2
  110. package/dist/core/release/read.js +12 -12
  111. package/dist/core/release/window.d.ts +11 -0
  112. package/dist/core/release/window.js +34 -0
  113. package/dist/core/report.d.ts +3 -0
  114. package/dist/core/richtext/headings.d.ts +10 -0
  115. package/dist/core/richtext/headings.js +37 -0
  116. package/dist/core/richtext/html.d.ts +10 -1
  117. package/dist/core/richtext/html.js +17 -6
  118. package/dist/core/richtext/markdown-text.d.ts +24 -0
  119. package/dist/core/richtext/markdown-text.js +38 -0
  120. package/dist/core/richtext/markdown.js +44 -3
  121. package/dist/core/richtext/schema.d.ts +12 -3
  122. package/dist/core/richtext/schema.js +34 -0
  123. package/dist/core/site/live.d.ts +6 -0
  124. package/dist/core/site/live.js +25 -0
  125. package/dist/core/site/paths.d.ts +5 -0
  126. package/dist/core/site/paths.js +32 -0
  127. package/dist/core/site/resolve.js +17 -6
  128. package/dist/core/version.d.ts +4 -0
  129. package/dist/core/version.js +4 -0
  130. package/dist/host/activate.js +2 -1
  131. package/dist/host/app.d.ts +2 -0
  132. package/dist/host/app.js +1 -0
  133. package/dist/host/diff.d.ts +11 -0
  134. package/dist/host/diff.js +40 -0
  135. package/dist/host/ipc.d.ts +2 -0
  136. package/dist/host/ipc.js +5 -1
  137. package/dist/host/preview-worker.js +2 -2
  138. package/dist/host/primary.js +15 -4
  139. package/dist/host/push.d.ts +5 -1
  140. package/dist/host/push.js +18 -6
  141. package/dist/host/serve.js +1 -1
  142. package/dist/host/store.d.ts +1 -2
  143. package/dist/host/store.js +32 -6
  144. package/dist/host/worker.js +9 -3
  145. package/dist/image-modules.d.ts +29 -0
  146. package/dist/image-modules.js +1 -0
  147. package/dist/index.d.ts +7 -1
  148. package/dist/index.js +4 -0
  149. package/dist/site.d.ts +9 -2
  150. package/dist/site.js +5 -0
  151. package/package.json +5 -1
@@ -9,8 +9,9 @@ import { InlayError } from '../errors.js';
9
9
  import { buildRegistry } from '../registry/registry.js';
10
10
  import { inlayVersion as currentVersion } from '../version.js';
11
11
  import { fingerprint, verify } from './keys.js';
12
- import { manifestSchema, satisfies, sha256Hex } from './manifest.js';
12
+ import { manifestSchema, sha256Hex } from './manifest.js';
13
13
  import { SITE_DIR_EXPORT } from './site-dir.js';
14
+ import { releaseFit, runningWindow } from './window.js';
14
15
  const SIGNED = new Set(['manifest.json', 'manifest.sig']);
15
16
  /** `.ts` when running from `src/` (tsx, vitest), `.js` from `dist/`. */
16
17
  const EXT = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
@@ -84,16 +85,14 @@ function invalid() {
84
85
  function releasePath(path) {
85
86
  return path === 'site.js' || path.startsWith('content/') || path.startsWith('public/');
86
87
  }
87
- /** `1.x` or, before 1.0, `0.3.x`: the versions a caret range accepts. */
88
- function series(range) {
89
- const need = range.replace(/^\^/, '');
90
- const [major = '', minor = ''] = need.split('.');
91
- return { need, series: major === '0' ? `0.${minor}.x` : `${major}.x` };
92
- }
93
- /** Throws `error.releaseVersion` when Inlay `version` (default: the running one) isn't in a release's `range`. */
94
- export function checkInlayVersion(range, version = currentVersion()) {
95
- if (!satisfies(version, range))
96
- throw new InlayError('release', 'error.releaseVersion', { range, version, ...series(range) });
88
+ /** Throws `error.releaseTooOld` or `error.releaseTooNew` when a release packed with Inlay `packed` doesn't run on Inlay `version` (default: the running one). */
89
+ export function checkInlayVersion(packed, version = currentVersion()) {
90
+ const window = { ...runningWindow(), version };
91
+ const fit = releaseFit(packed, window);
92
+ if (fit === 'tooOld')
93
+ throw new InlayError('release', 'error.releaseTooOld', { packed, version, oldest: window.oldest });
94
+ if (fit === 'tooNew')
95
+ throw new InlayError('release', 'error.releaseTooNew', { packed, version });
97
96
  }
98
97
  /** The manifest and signature are small; anything bigger is refused before the signature is checked. */
99
98
  const SIGNED_MAX_BYTES = 1024 ** 2;
@@ -183,7 +182,7 @@ async function checkRelease(file, dir, opts) {
183
182
  catch {
184
183
  throw invalid();
185
184
  }
186
- checkInlayVersion(manifest.inlay.range, opts.inlayVersion);
185
+ checkInlayVersion(manifest.inlay.version, opts.inlayVersion);
187
186
  const listed = Object.keys(manifest.files);
188
187
  if (!Object.hasOwn(manifest.files, 'site.js') || !listed.every(releasePath))
189
188
  throw invalid();
@@ -249,6 +248,7 @@ export async function loadRelease(dir, opts = {}) {
249
248
  site,
250
249
  dir,
251
250
  shippedFiles: new Map(manifest.content.map((c) => [c.source, join(dir, c.path)])),
251
+ codeFiles: new Map(manifest.content.filter((c) => c.code === true).map((c) => [c.source, join(dir, c.path)])),
252
252
  publicDir: existsSync(join(dir, 'public')) ? join(dir, 'public') : null,
253
253
  };
254
254
  }
@@ -0,0 +1,11 @@
1
+ export interface ReleaseWindow {
2
+ version: string;
3
+ oldest: string;
4
+ nextOldest: string | null;
5
+ }
6
+ export type ReleaseFit = 'ok' | 'warn' | 'tooOld' | 'tooNew';
7
+ export declare function runningWindow(): ReleaseWindow;
8
+ /** Whether a release packed with `packed` runs in `window`: packed with the oldest version or later, and not a newer minor than the host. */
9
+ export declare function releaseFit(packed: string, window?: ReleaseWindow): ReleaseFit;
10
+ /** A stored release's `inlay_range` without its leading caret. */
11
+ export declare function packedVersion(range: string): string;
@@ -0,0 +1,34 @@
1
+ import { inlayVersion, NEXT_OLDEST_RELEASE, OLDEST_RELEASE } from '../version.js';
2
+ const VERSION = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/;
3
+ function parts(version) {
4
+ const m = VERSION.exec(version);
5
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
6
+ }
7
+ function compare(a, b) {
8
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
9
+ }
10
+ export function runningWindow() {
11
+ return { version: inlayVersion(), oldest: OLDEST_RELEASE, nextOldest: NEXT_OLDEST_RELEASE };
12
+ }
13
+ /** Whether a release packed with `packed` runs in `window`: packed with the oldest version or later, and not a newer minor than the host. */
14
+ export function releaseFit(packed, window = runningWindow()) {
15
+ const have = parts(packed);
16
+ if (!have)
17
+ return 'tooOld';
18
+ const host = parts(window.version);
19
+ const oldest = parts(window.oldest);
20
+ if (!host || !oldest)
21
+ return 'tooOld';
22
+ if (have[0] > host[0] || (have[0] === host[0] && have[1] > host[1]))
23
+ return 'tooNew';
24
+ if (compare(have, oldest) < 0)
25
+ return 'tooOld';
26
+ const next = window.nextOldest === null ? null : parts(window.nextOldest);
27
+ if (next && compare(have, next) < 0)
28
+ return 'warn';
29
+ return 'ok';
30
+ }
31
+ /** A stored release's `inlay_range` without its leading caret. */
32
+ export function packedVersion(range) {
33
+ return range.startsWith('^') ? range.slice(1) : range;
34
+ }
@@ -23,6 +23,9 @@ export type CheckWarning = {
23
23
  redirect: {
24
24
  from: string;
25
25
  };
26
+ } | {
27
+ code: 'csp_unsafe_inline' | 'csp_unsafe_eval' | 'csp_script_scheme' | 'csp_overridden';
28
+ message: string;
26
29
  };
27
30
  /** What boot or `inlaycms check` did (or would do) to a database. */
28
31
  export interface CheckReport {
@@ -0,0 +1,10 @@
1
+ import type { RichTextDoc } from './schema.js';
2
+ export interface RichTextHeading {
3
+ level: number;
4
+ text: string;
5
+ id: string;
6
+ }
7
+ /** The doc's headings in document order, with the ids `ctx.richText(doc, { headingIds })` gives them. */
8
+ export declare function richTextHeadings(doc: RichTextDoc | null | undefined, opts?: {
9
+ prefix?: string;
10
+ }): RichTextHeading[];
@@ -0,0 +1,37 @@
1
+ function slug(text) {
2
+ const s = text
3
+ .normalize('NFC')
4
+ .toLowerCase()
5
+ .trim()
6
+ .replace(/\s+/g, '-')
7
+ .replace(/[^\p{L}\p{M}\p{N}-]/gu, '')
8
+ .replace(/-+/g, '-')
9
+ .replace(/^-|-$/g, '');
10
+ return s === '' ? 'section' : s;
11
+ }
12
+ /** The doc's headings in document order, with the ids `ctx.richText(doc, { headingIds })` gives them. */
13
+ export function richTextHeadings(doc, opts = {}) {
14
+ const out = [];
15
+ if (!doc)
16
+ return out;
17
+ const prefix = opts.prefix ?? '';
18
+ const used = new Set();
19
+ const walk = (nodes) => {
20
+ for (const node of nodes ?? []) {
21
+ if (node.type === 'heading') {
22
+ const text = (node.content ?? []).map((n) => (n.type === 'text' ? n.text : '')).join('');
23
+ const base = prefix + slug(text);
24
+ let id = base;
25
+ for (let n = 2; used.has(id); n++)
26
+ id = `${base}-${n}`;
27
+ used.add(id);
28
+ out.push({ level: node.attrs.level, text, id });
29
+ }
30
+ else if (node.type === 'blockquote' || node.type === 'bulletList' || node.type === 'orderedList' || node.type === 'listItem') {
31
+ walk(node.content);
32
+ }
33
+ }
34
+ };
35
+ walk(doc.content);
36
+ return out;
37
+ }
@@ -1,3 +1,4 @@
1
+ import { SafeHtml } from '../../jsx/html.js';
1
2
  import { type RichTextDoc, type RichTextInline } from './schema.js';
2
3
  export interface RichTextImageHtml {
3
4
  src: string;
@@ -11,7 +12,15 @@ export interface RichTextResolver {
11
12
  link(groupId: string): string | null;
12
13
  image(id: string, alt: string | undefined): RichTextImageHtml | null;
13
14
  }
15
+ /** Highlights code: the inside of `<code>` as `SafeHtml`, or `null` to leave it plain. */
16
+ export type CodeHighlighter = (code: string, language: string | undefined) => SafeHtml | null;
17
+ export interface RichTextRenderOptions {
18
+ highlight?: CodeHighlighter;
19
+ headingIds?: boolean | {
20
+ prefix: string;
21
+ };
22
+ }
14
23
  /** Inline content, keeping a mark open across neighbors that share it. */
15
24
  export declare function richTextInlineHtml(nodes: RichTextInline[], resolve: RichTextResolver): string;
16
25
  /** The doc as HTML. Every text and attribute is escaped; only Inlay's own tags are emitted. */
17
- export declare function richTextToHtml(doc: RichTextDoc, resolve: RichTextResolver): string;
26
+ export declare function richTextToHtml(doc: RichTextDoc, resolve: RichTextResolver, opts?: RichTextRenderOptions): string;
@@ -1,4 +1,5 @@
1
- import { escapeHtml } from '../../jsx/html.js';
1
+ import { escapeHtml, SafeHtml } from '../../jsx/html.js';
2
+ import { richTextHeadings } from './headings.js';
2
3
  import { isRichTextHref } from './schema.js';
3
4
  function attr(name, value) {
4
5
  return value === null || value === '' ? '' : ` ${name}="${escapeHtml(String(value))}"`;
@@ -53,15 +54,16 @@ export function richTextInlineHtml(nodes, resolve) {
53
54
  out += open[i].close;
54
55
  return out;
55
56
  }
56
- function block(node, resolve) {
57
- const children = (nodes) => (nodes ?? []).map((n) => block(n, resolve)).join('');
57
+ function block(node, resolve, opts, headings) {
58
+ const children = (nodes) => (nodes ?? []).map((n) => block(n, resolve, opts, headings)).join('');
58
59
  switch (node.type) {
59
60
  case 'paragraph':
60
61
  return `<p>${richTextInlineHtml(node.content ?? [], resolve)}</p>`;
61
62
  case 'heading': {
62
63
  const level = node.attrs.level;
63
64
  const tag = Number.isInteger(level) && level >= 1 && level <= 6 ? `h${level}` : 'p';
64
- return `<${tag}>${richTextInlineHtml(node.content ?? [], resolve)}</${tag}>`;
65
+ const id = headings ? headings.ids[headings.next++] ?? null : null;
66
+ return `<${tag}${attr('id', id)}>${richTextInlineHtml(node.content ?? [], resolve)}</${tag}>`;
65
67
  }
66
68
  case 'bulletList':
67
69
  return `<ul>${children(node.content)}</ul>`;
@@ -81,6 +83,13 @@ function block(node, resolve) {
81
83
  (body.length > 0 ? `<tbody>${body.map((r) => cells(r, 'td')).join('')}</tbody>` : '') +
82
84
  '</table>');
83
85
  }
86
+ case 'codeBlock': {
87
+ const code = node.content?.[0]?.text ?? '';
88
+ const language = node.attrs?.language;
89
+ const out = opts.highlight?.(code, language);
90
+ const inside = out instanceof SafeHtml ? out.value : escapeHtml(out === null || out === undefined ? code : String(out));
91
+ return `<pre><code${attr('class', language ? `language-${language}` : null)}>${inside}</code></pre>`;
92
+ }
84
93
  case 'tableRow':
85
94
  case 'tableHeader':
86
95
  case 'tableCell':
@@ -90,6 +99,8 @@ function block(node, resolve) {
90
99
  }
91
100
  }
92
101
  /** The doc as HTML. Every text and attribute is escaped; only Inlay's own tags are emitted. */
93
- export function richTextToHtml(doc, resolve) {
94
- return doc.content.map((node) => block(node, resolve)).join('');
102
+ export function richTextToHtml(doc, resolve, opts = {}) {
103
+ const ids = opts.headingIds;
104
+ const headings = ids ? { ids: richTextHeadings(doc, { prefix: typeof ids === 'object' ? ids.prefix : '' }).map((h) => h.id), next: 0 } : null;
105
+ return doc.content.map((node) => block(node, resolve, opts, headings)).join('');
95
106
  }
@@ -0,0 +1,24 @@
1
+ import { type RichTextHeading } from './headings.js';
2
+ import { type RichTextProblem } from './markdown.js';
3
+ import { type RichTextDoc, type RichTextOptions } from './schema.js';
4
+ export declare const MARKDOWN_TEXT_OPTIONS: RichTextOptions;
5
+ /** The start of a Markdown link target `](inlay:key/<type>` or `](inlay:key/<type>/<key>`; text elsewhere is left alone. */
6
+ export declare const KEY_HREF: RegExp;
7
+ /** A document that never resolves: a link to it shows as plain text. */
8
+ export declare const NO_DOCUMENT = "00000000-0000-0000-0000-000000000000";
9
+ /** The picture files Markdown in templates may name, by extension, with the type each must hold. No SVG. */
10
+ export declare const MARKDOWN_IMAGE_TYPES: Readonly<Record<string, string>>;
11
+ /** True if `src` names a media library image (`inlay:media/<id>`). */
12
+ export declare function isMediaTarget(src: string): boolean;
13
+ /** Reads a template's Markdown text with every rich text feature and heading levels 1 to 6. */
14
+ export declare function parseMarkdownText(text: string, images?: ReadonlyMap<string, string>): {
15
+ ok: true;
16
+ doc: RichTextDoc;
17
+ } | {
18
+ ok: false;
19
+ problems: RichTextProblem[];
20
+ };
21
+ /** The headings of Markdown text, with the ids `ctx.markdown` gives them, or none when it doesn't read. */
22
+ export declare function markdownHeadings(text: string, opts?: {
23
+ prefix?: string;
24
+ }): RichTextHeading[];
@@ -0,0 +1,38 @@
1
+ import { richTextHeadings } from './headings.js';
2
+ import { markdownImages, markdownToRichText } from './markdown.js';
3
+ import { RICH_TEXT_FEATURES } from './schema.js';
4
+ export const MARKDOWN_TEXT_OPTIONS = { features: RICH_TEXT_FEATURES, headings: [1, 2, 3, 4, 5, 6] };
5
+ /** Stands in for an image whose source isn't known, so parsing never fails on it. */
6
+ const PLACEHOLDER_IMAGE = '0'.repeat(64);
7
+ /** The start of a Markdown link target `](inlay:key/<type>` or `](inlay:key/<type>/<key>`; text elsewhere is left alone. */
8
+ export const KEY_HREF = /\]\(inlay:key\/([\w-]+)(?:\/([\w-]+))?(?=[\s)])/g;
9
+ /** A document that never resolves: a link to it shows as plain text. */
10
+ export const NO_DOCUMENT = '00000000-0000-0000-0000-000000000000';
11
+ const MEDIA_TARGET = /^inlay:media\/[0-9a-f]{64}$/;
12
+ /** The picture files Markdown in templates may name, by extension, with the type each must hold. No SVG. */
13
+ export const MARKDOWN_IMAGE_TYPES = {
14
+ '.png': 'image/png',
15
+ '.jpg': 'image/jpeg',
16
+ '.jpeg': 'image/jpeg',
17
+ '.gif': 'image/gif',
18
+ '.webp': 'image/webp',
19
+ '.avif': 'image/avif',
20
+ };
21
+ /** True if `src` names a media library image (`inlay:media/<id>`). */
22
+ export function isMediaTarget(src) {
23
+ return MEDIA_TARGET.test(src);
24
+ }
25
+ /** Reads a template's Markdown text with every rich text feature and heading levels 1 to 6. */
26
+ export function parseMarkdownText(text, images = new Map()) {
27
+ const mapped = new Map(images);
28
+ for (const { src } of markdownImages(text)) {
29
+ if (!mapped.has(src) && !isMediaTarget(src))
30
+ mapped.set(src, PLACEHOLDER_IMAGE);
31
+ }
32
+ return markdownToRichText(text.replace(KEY_HREF, `](inlay:document/${NO_DOCUMENT}`), MARKDOWN_TEXT_OPTIONS, { images: mapped });
33
+ }
34
+ /** The headings of Markdown text, with the ids `ctx.markdown` gives them, or none when it doesn't read. */
35
+ export function markdownHeadings(text, opts = {}) {
36
+ const parsed = parseMarkdownText(text);
37
+ return parsed.ok ? richTextHeadings(parsed.doc, opts) : [];
38
+ }
@@ -3,7 +3,7 @@ import { Fragment, Mark } from 'prosemirror-model';
3
3
  import { MarkdownParser, MarkdownSerializerState } from 'prosemirror-markdown';
4
4
  import { z } from 'zod';
5
5
  import { t } from '../messages/index.js';
6
- import { DEFAULT_RICH_TEXT, isRichTextHref, parseRichText, richTextSchema, } from './schema.js';
6
+ import { CODE_LANGUAGE, DEFAULT_RICH_TEXT, isRichTextHref, parseRichText, richTextSchema, } from './schema.js';
7
7
  const DOCUMENT_PREFIX = 'inlay:document/';
8
8
  const MEDIA_PREFIX = 'inlay:media/';
9
9
  const HEX64 = /^[0-9a-f]{64}$/;
@@ -637,6 +637,24 @@ const nodes = {
637
637
  renderTextblock(state, node, true);
638
638
  state.closeBlock(node);
639
639
  },
640
+ codeBlock(state, node) {
641
+ // Written line by line as it is: escaping, or the stand-ins `renderTextblock` places, would change the code.
642
+ const code = node.textContent;
643
+ let longest = 0;
644
+ for (const run of code.match(/`+/g) ?? [])
645
+ longest = Math.max(longest, run.length);
646
+ const fence = '`'.repeat(Math.max(3, longest + 1));
647
+ const language = node.attrs.language;
648
+ state.write(fence + (typeof language === 'string' ? language : ''));
649
+ state.ensureNewLine();
650
+ for (const line of code.split('\n')) {
651
+ state.write();
652
+ state.append(line);
653
+ state.append('\n');
654
+ }
655
+ state.write(fence);
656
+ state.closeBlock(node);
657
+ },
640
658
  image(state, node) {
641
659
  const alt = typeof node.attrs.alt === 'string' ? oneLine(node.attrs.alt) : '';
642
660
  state.write('![');
@@ -821,6 +839,7 @@ const parser = new MarkdownParser(richTextSchema, tokenizer, {
821
839
  bullet_list: { block: 'bulletList' },
822
840
  ordered_list: { block: 'orderedList', getAttrs: (tok) => ({ start: Number(tok.attrGet('start') ?? 1) }) },
823
841
  heading: { block: 'heading', getAttrs: (tok) => ({ level: Number(tok.tag.slice(1)) }) },
842
+ fence: { block: 'codeBlock', noCloseToken: true, getAttrs: (tok) => ({ language: tok.info.trim() || null }) },
824
843
  image: {
825
844
  node: 'image',
826
845
  getAttrs: (tok) => ({
@@ -878,8 +897,6 @@ const TOKEN_FEATURE = {
878
897
  table_open: 'table',
879
898
  };
880
899
  const TOKEN_UNSUPPORTED = {
881
- code_block: 'codeBlock',
882
- fence: 'codeBlock',
883
900
  hr: 'rule',
884
901
  };
885
902
  /** Token types the parser turns into rich text without any check. */
@@ -947,6 +964,18 @@ function literalSyntaxProblems(markdown) {
947
964
  }
948
965
  const isSafeHref = (href) => href.startsWith(DOCUMENT_PREFIX) ? UUID.safeParse(href.slice(DOCUMENT_PREFIX.length)).success : isRichTextHref(href);
949
966
  const isLibraryImage = (src) => src.startsWith(MEDIA_PREFIX) && HEX64.test(src.slice(MEDIA_PREFIX.length));
967
+ /**
968
+ * True if a fence token ends with a closing fence. A closed fence spans its content lines plus the opening and
969
+ * closing lines; one left open runs to the end of the document or its container and spans one line fewer.
970
+ * The content's last line lacks its `\n` only at the end of the input.
971
+ */
972
+ function fenceClosed(tok) {
973
+ if (!tok.map)
974
+ return true;
975
+ const content = tok.content;
976
+ const lines = content === '' ? 0 : (content.match(/\n/g) ?? []).length + (content.endsWith('\n') ? 0 : 1);
977
+ return tok.map[1] - tok.map[0] === lines + 2;
978
+ }
950
979
  /** Every problem in the token stream and `env`, in line order, before anything is built. */
951
980
  function findProblems(tokens, opts, env) {
952
981
  const problems = [];
@@ -956,6 +985,18 @@ function findProblems(tokens, opts, env) {
956
985
  };
957
986
  const allowed = (f) => opts.features.includes(f);
958
987
  const check = (tok, line, inHeading, inCell) => {
988
+ if (tok.type === 'code_block')
989
+ return add('unsupported', line, 'richtext.indentedCode', {});
990
+ if (tok.type === 'fence') {
991
+ if (!allowed('codeBlock'))
992
+ return add('not_allowed', line, 'richtext.notAllowed', { feature: feature('codeBlock') });
993
+ const language = tok.info.trim();
994
+ if (language !== '' && !CODE_LANGUAGE.test(language))
995
+ add('unsupported', line, 'richtext.codeLanguage', { language });
996
+ if (!fenceClosed(tok))
997
+ add('unsupported', line, 'richtext.unclosedCode', {});
998
+ return;
999
+ }
959
1000
  const unsupported = TOKEN_UNSUPPORTED[tok.type];
960
1001
  if (unsupported)
961
1002
  return add('unsupported', line, 'richtext.unsupported', { feature: feature(unsupported) });
@@ -1,6 +1,8 @@
1
1
  import { Schema } from 'prosemirror-model';
2
2
  import type { ContentRef } from '../types.js';
3
- export declare const RICH_TEXT_FEATURES: readonly ['heading', 'bold', 'italic', 'code', 'link', 'bulletList', 'orderedList', 'blockquote', 'image', 'hardBreak', 'table'];
3
+ export declare const RICH_TEXT_FEATURES: readonly ['heading', 'bold', 'italic', 'code', 'link', 'bulletList', 'orderedList', 'blockquote', 'codeBlock', 'image', 'hardBreak', 'table'];
4
+ /** A code block's language: one short word, kept as written. */
5
+ export declare const CODE_LANGUAGE: RegExp;
4
6
  export type RichTextFeature = (typeof RICH_TEXT_FEATURES)[number];
5
7
  export interface RichTextOptions {
6
8
  features: readonly RichTextFeature[];
@@ -69,6 +71,13 @@ export type RichTextBlockquote = {
69
71
  type: 'blockquote';
70
72
  content: RichTextBlock[];
71
73
  };
74
+ export type RichTextCodeBlock = {
75
+ type: 'codeBlock';
76
+ attrs?: {
77
+ language: string;
78
+ };
79
+ content?: [RichTextText];
80
+ };
72
81
  export type RichTextTableCell = {
73
82
  type: 'tableHeader' | 'tableCell';
74
83
  content: [RichTextParagraph];
@@ -81,7 +90,7 @@ export type RichTextTable = {
81
90
  type: 'table';
82
91
  content: RichTextTableRow[];
83
92
  };
84
- export type RichTextBlock = RichTextParagraph | RichTextHeading | RichTextBulletList | RichTextOrderedList | RichTextBlockquote | RichTextTable;
93
+ export type RichTextBlock = RichTextParagraph | RichTextHeading | RichTextBulletList | RichTextOrderedList | RichTextBlockquote | RichTextCodeBlock | RichTextTable;
85
94
  export type RichTextNode = RichTextBlock | RichTextListItem | RichTextTableRow | RichTextTableCell | RichTextInline;
86
95
  export type RichTextDoc = {
87
96
  type: 'doc';
@@ -91,7 +100,7 @@ export type RichTextDoc = {
91
100
  * Tiptap's node and mark names. The mark order is the canonical order of marks on a node. Code comes last, inside a
92
101
  * link, and never with bold or italic: Markdown can't put either inside a code span.
93
102
  */
94
- export declare const richTextSchema: Schema<"blockquote" | "bulletList" | "doc" | "hardBreak" | "heading" | "image" | "listItem" | "orderedList" | "paragraph" | "table" | "tableCell" | "tableHeader" | "tableRow" | "text", "bold" | "code" | "italic" | "link">;
103
+ export declare const richTextSchema: Schema<"blockquote" | "bulletList" | "codeBlock" | "doc" | "hardBreak" | "heading" | "image" | "listItem" | "orderedList" | "paragraph" | "table" | "tableCell" | "tableHeader" | "tableRow" | "text", "bold" | "code" | "italic" | "link">;
95
104
  /**
96
105
  * A link address rich text can hold: a safe URL without control characters, which
97
106
  * Markdown can't carry and so wouldn't read back.
@@ -11,10 +11,13 @@ export const RICH_TEXT_FEATURES = [
11
11
  'bulletList',
12
12
  'orderedList',
13
13
  'blockquote',
14
+ 'codeBlock',
14
15
  'image',
15
16
  'hardBreak',
16
17
  'table',
17
18
  ];
19
+ /** A code block's language: one short word, kept as written. */
20
+ export const CODE_LANGUAGE = /^[A-Za-z0-9_+#.-]{1,32}$/;
18
21
  export const DEFAULT_RICH_TEXT = { features: RICH_TEXT_FEATURES, headings: [2, 3, 4] };
19
22
  /**
20
23
  * Tiptap's node and mark names. The mark order is the canonical order of marks on a node. Code comes last, inside a
@@ -29,6 +32,7 @@ export const richTextSchema = new Schema({
29
32
  orderedList: { group: 'block', content: 'listItem+', attrs: { start: { default: 1 } } },
30
33
  listItem: { content: 'paragraph block*' },
31
34
  blockquote: { group: 'block', content: 'block+' },
35
+ codeBlock: { group: 'block', content: 'text*', marks: '', code: true, attrs: { language: { default: null } } },
32
36
  table: { group: 'block', content: 'tableRow+' },
33
37
  tableRow: { content: '(tableHeader | tableCell)+' },
34
38
  tableHeader: { content: 'paragraph' },
@@ -49,6 +53,7 @@ const NODE_FEATURE = {
49
53
  bulletList: 'bulletList',
50
54
  orderedList: 'orderedList',
51
55
  blockquote: 'blockquote',
56
+ codeBlock: 'codeBlock',
52
57
  image: 'image',
53
58
  hardBreak: 'hardBreak',
54
59
  table: 'table',
@@ -110,6 +115,14 @@ function cleanAttrs(type, raw, opts) {
110
115
  reject();
111
116
  return start === 1 ? undefined : { start };
112
117
  }
118
+ if (type === 'codeBlock') {
119
+ const { language } = attrs;
120
+ if (absent(language) || language === '')
121
+ return undefined;
122
+ if (typeof language !== 'string' || !CODE_LANGUAGE.test(language))
123
+ reject();
124
+ return { language };
125
+ }
113
126
  if (type === 'image') {
114
127
  const { media, alt } = attrs;
115
128
  if (typeof media !== 'string' || !HEX64.test(media))
@@ -142,6 +155,25 @@ function cleanNode(raw, opts) {
142
155
  if (marks.length > 0)
143
156
  out.marks = marks;
144
157
  }
158
+ if (type === 'codeBlock') {
159
+ if (!absent(raw.marks))
160
+ reject();
161
+ if (!absent(raw.content) && !Array.isArray(raw.content))
162
+ reject();
163
+ let code = '';
164
+ for (const child of raw.content ?? []) {
165
+ if (!isRecord(child) || child.type !== 'text' || typeof child.text !== 'string')
166
+ reject();
167
+ if (!absent(child.marks) && !(Array.isArray(child.marks) && child.marks.length === 0))
168
+ reject();
169
+ code += child.text;
170
+ }
171
+ code = code.replace(/\r\n?/g, '\n');
172
+ if (code === '')
173
+ return null;
174
+ out.content = [{ type: 'text', text: code }];
175
+ return out;
176
+ }
145
177
  if (type === 'text') {
146
178
  if (typeof raw.text !== 'string')
147
179
  reject();
@@ -309,6 +341,8 @@ function blockTexts(node, out) {
309
341
  continue;
310
342
  if (child.type === 'paragraph' || child.type === 'heading')
311
343
  out.push(inlineText(child));
344
+ else if (child.type === 'codeBlock')
345
+ out.push(inlineText(child));
312
346
  else if (child.type === 'tableRow')
313
347
  out.push(childrenOf(child).map(inlineCell).join('\t'));
314
348
  else
@@ -8,6 +8,7 @@ export type LiveOpts = {
8
8
  /** Visible, non-deleted documents, each with its live revision (`rev_*` are `null` when it has none). */
9
9
  export declare function liveQuery(deps: CoreDeps, state: LiveState): import("kysely").SelectQueryBuilder<{
10
10
  documents: DocumentsTable;
11
+ integrations: import("../db/schema.js").IntegrationsTable;
11
12
  media: import("../db/schema.js").MediaTable;
12
13
  media_deletions: import("../db/schema.js").MediaDeletionsTable;
13
14
  oauthClient: import("../db/schema.js").OAuthClientTable;
@@ -55,3 +56,8 @@ export declare function liveAlternates(deps: CoreDeps, groupId: string, opts?: L
55
56
  path: string;
56
57
  fallback: boolean;
57
58
  }>>;
59
+ /** The group id of each keyed document (or singleton or global, whose key is its type), by `type/key`. */
60
+ export declare function groupIdsByKey(deps: CoreDeps, refs: Array<{
61
+ type: string;
62
+ key: string | null;
63
+ }>): Promise<Map<string, string>>;
@@ -144,3 +144,28 @@ export async function liveAlternates(deps, groupId, opts = {}) {
144
144
  }
145
145
  return out;
146
146
  }
147
+ /** The group id of each keyed document (or singleton or global, whose key is its type), by `type/key`. */
148
+ export async function groupIdsByKey(deps, refs) {
149
+ const out = new Map();
150
+ if (refs.length === 0)
151
+ return out;
152
+ const wanted = new Map(refs.map((r) => [`${r.type}/${r.key ?? r.type}`, { type: r.type, key: r.key ?? r.type }]));
153
+ const rows = await deps.db
154
+ .selectFrom('documents')
155
+ .select(['group_id', 'type', 'key'])
156
+ .where('deleted_at', 'is', null)
157
+ .where((eb) => eb.or([...wanted.values()].map(({ type, key }) => {
158
+ const keyed = eb.and([eb('type', '=', type), eb('key', '=', key)]);
159
+ if (key !== type)
160
+ return keyed;
161
+ const unkeyed = eb.and([eb('type', '=', type), eb('key', 'is', null), eb('kind', 'in', ['singleton', 'global'])]);
162
+ return eb.or([keyed, unkeyed]);
163
+ })))
164
+ .execute();
165
+ for (const row of rows) {
166
+ const id = `${row.type}/${row.key ?? row.type}`;
167
+ if (wanted.has(id))
168
+ out.set(id, row.group_id);
169
+ }
170
+ return out;
171
+ }
@@ -19,3 +19,8 @@ export declare function withLocale(registry: Registry, locale: string, path: str
19
19
  export declare function singletonPath(def: SingletonDef, locale: string, defaultLocale: string): string | null;
20
20
  export declare function routeRegExp(route: string): RegExp;
21
21
  export declare function routePath(route: string, slug: string): string;
22
+ export type TrailingSlash = 'always' | 'never';
23
+ /** A decoded, normalized path (optionally with a `?query`) in the form the site presents. */
24
+ export declare function presentPath(path: string, mode: TrailingSlash): string;
25
+ /** The same for an encoded site-relative href; other hrefs come back unchanged. */
26
+ export declare function presentHref(href: string, mode: TrailingSlash): string;
@@ -75,3 +75,35 @@ export function routeRegExp(route) {
75
75
  export function routePath(route, slug) {
76
76
  return route.replace(':slug', slug);
77
77
  }
78
+ function slashable(path) {
79
+ if (path === '/' || path.endsWith('/') || isReserved(path))
80
+ return false;
81
+ return !(path.split('/').at(-1) ?? '').includes('.');
82
+ }
83
+ /** A decoded, normalized path (optionally with a `?query`) in the form the site presents. */
84
+ export function presentPath(path, mode) {
85
+ if (mode !== 'always')
86
+ return path;
87
+ const q = path.indexOf('?');
88
+ const bare = q === -1 ? path : path.slice(0, q);
89
+ if (!slashable(bare))
90
+ return path;
91
+ return `${bare}/${q === -1 ? '' : path.slice(q)}`;
92
+ }
93
+ /** The same for an encoded site-relative href; other hrefs come back unchanged. */
94
+ export function presentHref(href, mode) {
95
+ if (mode !== 'always' || !href.startsWith('/') || href.startsWith('//'))
96
+ return href;
97
+ const q = href.indexOf('?');
98
+ const bare = q === -1 ? href : href.slice(0, q);
99
+ let decoded;
100
+ try {
101
+ decoded = decodeURIComponent(bare);
102
+ }
103
+ catch {
104
+ return href;
105
+ }
106
+ if (!slashable(decoded))
107
+ return href;
108
+ return `${bare}/${q === -1 ? '' : href.slice(q)}`;
109
+ }
@@ -158,14 +158,14 @@ function lookupLocales(deps, locale) {
158
158
  export async function resolvePath(deps, rawPath, opts = {}) {
159
159
  const res = await resolveSite(deps, rawPath, opts);
160
160
  if (res.kind === 'canonical') {
161
- // A mixed-case path that would 404 once canonical goes where the lowercase fallback lands, in one 301.
162
161
  const { canonical } = res;
162
+ const at = await atCanonical(deps, canonical, opts);
163
+ if (at?.kind === 'redirect')
164
+ return at;
165
+ // A mixed-case path that would 404 once canonical goes where the lowercase fallback lands, in one 301.
163
166
  const lower = lowercaseFallback(canonical);
164
- if (lower !== null &&
165
- !deps.registry.getRoutePaths.has(canonical) &&
166
- (await resolveRules(deps, encodePath(canonical), opts)).kind === 'not_found') {
167
+ if (lower !== null && at?.kind === 'not_found')
167
168
  return (await landing(deps, lower, opts)) ?? redirect(canonical);
168
- }
169
169
  return redirect(canonical);
170
170
  }
171
171
  if (res.kind !== 'rules')
@@ -191,6 +191,13 @@ async function resolveRules(deps, rawPath, opts) {
191
191
  return res;
192
192
  return (await matchRedirect(deps, res, opts)) ?? notFound(res.locale);
193
193
  }
194
+ /**
195
+ * What steps 1–7b answer at the target of a step 2–3 redirect, so a rule there is reached in the
196
+ * same 301; `null` at a GET code route, which no rule can shadow.
197
+ */
198
+ async function atCanonical(deps, canonical, opts) {
199
+ return deps.registry.getRoutePaths.has(canonical) ? null : resolveRules(deps, encodePath(canonical), opts);
200
+ }
194
201
  /**
195
202
  * Where the lowercase fallback for a request lands, given its lowercase form `lower`: a GET code
196
203
  * route or a page there, a redirect that steps 2–6 or a rule would give, or `null` when nothing
@@ -202,8 +209,12 @@ async function landing(deps, lower, opts) {
202
209
  const res = await resolveSite(deps, encodePath(lower), opts);
203
210
  if (res.kind === 'page')
204
211
  return redirect(lower);
205
- if (res.kind === 'canonical')
212
+ if (res.kind === 'canonical') {
213
+ const at = await atCanonical(deps, res.canonical, opts);
214
+ if (at?.kind === 'redirect')
215
+ return at;
206
216
  return (await answers(deps, res.canonical, opts)) ? redirect(res.canonical) : null;
217
+ }
207
218
  if (res.kind === 'redirect')
208
219
  return res;
209
220
  if (res.kind !== 'rules')