@glw907/cairn-cms 0.56.2 → 0.57.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 (173) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/dist/components/AdminLayout.svelte +3 -0
  3. package/dist/components/CairnAdmin.svelte +8 -1
  4. package/dist/components/CairnAdmin.svelte.d.ts +2 -0
  5. package/dist/components/CairnMediaLibrary.svelte +929 -0
  6. package/dist/components/CairnMediaLibrary.svelte.d.ts +37 -0
  7. package/dist/components/EditPage.svelte +347 -7
  8. package/dist/components/EditPage.svelte.d.ts +2 -0
  9. package/dist/components/MarkdownEditor.svelte +283 -1
  10. package/dist/components/MarkdownEditor.svelte.d.ts +37 -1
  11. package/dist/components/MediaCaptureCard.svelte +135 -0
  12. package/dist/components/MediaCaptureCard.svelte.d.ts +40 -0
  13. package/dist/components/MediaFigureControl.svelte +247 -0
  14. package/dist/components/MediaFigureControl.svelte.d.ts +40 -0
  15. package/dist/components/MediaHeroField.svelte +569 -0
  16. package/dist/components/MediaHeroField.svelte.d.ts +67 -0
  17. package/dist/components/MediaInsertPopover.svelte +449 -0
  18. package/dist/components/MediaInsertPopover.svelte.d.ts +58 -0
  19. package/dist/components/MediaPicker.svelte +257 -0
  20. package/dist/components/MediaPicker.svelte.d.ts +41 -0
  21. package/dist/components/admin-icons.d.ts +12 -0
  22. package/dist/components/admin-icons.js +12 -0
  23. package/dist/components/cairn-admin.css +901 -9
  24. package/dist/components/client-ingest.d.ts +142 -0
  25. package/dist/components/client-ingest.js +297 -0
  26. package/dist/components/editor-media.d.ts +11 -0
  27. package/dist/components/editor-media.js +206 -0
  28. package/dist/components/editor-placeholder.d.ts +26 -0
  29. package/dist/components/editor-placeholder.js +166 -0
  30. package/dist/components/index.d.ts +1 -0
  31. package/dist/components/index.js +1 -0
  32. package/dist/components/markdown-directives.d.ts +12 -0
  33. package/dist/components/markdown-directives.js +42 -0
  34. package/dist/components/markdown-format.d.ts +89 -0
  35. package/dist/components/markdown-format.js +255 -0
  36. package/dist/components/media-upload-outcome.d.ts +52 -0
  37. package/dist/components/media-upload-outcome.js +48 -0
  38. package/dist/content/compose.js +3 -0
  39. package/dist/content/frontmatter.js +17 -0
  40. package/dist/content/manifest.d.ts +4 -0
  41. package/dist/content/manifest.js +41 -1
  42. package/dist/content/media-refs.d.ts +7 -0
  43. package/dist/content/media-refs.js +52 -0
  44. package/dist/content/schema.d.ts +5 -2
  45. package/dist/content/schema.js +17 -0
  46. package/dist/content/types.d.ts +62 -11
  47. package/dist/content/validate.js +27 -0
  48. package/dist/delivery/public-routes.d.ts +16 -0
  49. package/dist/delivery/public-routes.js +46 -3
  50. package/dist/delivery/seo-fields.js +7 -1
  51. package/dist/delivery/seo.d.ts +2 -0
  52. package/dist/delivery/seo.js +3 -0
  53. package/dist/doctor/checks-local.d.ts +1 -0
  54. package/dist/doctor/checks-local.js +21 -0
  55. package/dist/doctor/index.d.ts +3 -1
  56. package/dist/doctor/index.js +11 -2
  57. package/dist/doctor/types.d.ts +3 -0
  58. package/dist/doctor/wrangler-config.d.ts +3 -0
  59. package/dist/doctor/wrangler-config.js +20 -0
  60. package/dist/env.d.ts +19 -0
  61. package/dist/env.js +26 -0
  62. package/dist/index.d.ts +1 -1
  63. package/dist/log/events.d.ts +1 -1
  64. package/dist/media/config.d.ts +24 -0
  65. package/dist/media/config.js +69 -0
  66. package/dist/media/delivery-bucket.d.ts +34 -0
  67. package/dist/media/delivery-bucket.js +10 -0
  68. package/dist/media/index.d.ts +6 -0
  69. package/dist/media/index.js +13 -0
  70. package/dist/media/library-entry.d.ts +30 -0
  71. package/dist/media/library-entry.js +17 -0
  72. package/dist/media/manifest.d.ts +44 -0
  73. package/dist/media/manifest.js +105 -0
  74. package/dist/media/naming.d.ts +18 -0
  75. package/dist/media/naming.js +112 -0
  76. package/dist/media/reconcile.d.ts +36 -0
  77. package/dist/media/reconcile.js +45 -0
  78. package/dist/media/reference.d.ts +12 -0
  79. package/dist/media/reference.js +33 -0
  80. package/dist/media/sniff.d.ts +18 -0
  81. package/dist/media/sniff.js +106 -0
  82. package/dist/media/store.d.ts +25 -0
  83. package/dist/media/store.js +16 -0
  84. package/dist/media/transform-url.d.ts +26 -0
  85. package/dist/media/transform-url.js +38 -0
  86. package/dist/media/usage.d.ts +48 -0
  87. package/dist/media/usage.js +90 -0
  88. package/dist/render/pipeline.d.ts +2 -0
  89. package/dist/render/pipeline.js +13 -2
  90. package/dist/render/registry.js +3 -0
  91. package/dist/render/remark-figure.d.ts +4 -0
  92. package/dist/render/remark-figure.js +103 -0
  93. package/dist/render/resolve-media.d.ts +34 -0
  94. package/dist/render/resolve-media.js +78 -0
  95. package/dist/render/sanitize-schema.d.ts +4 -2
  96. package/dist/render/sanitize-schema.js +5 -3
  97. package/dist/sveltekit/admin-dispatch.d.ts +2 -0
  98. package/dist/sveltekit/admin-dispatch.js +5 -0
  99. package/dist/sveltekit/cairn-admin.d.ts +8 -1
  100. package/dist/sveltekit/cairn-admin.js +10 -2
  101. package/dist/sveltekit/content-routes.d.ts +68 -2
  102. package/dist/sveltekit/content-routes.js +461 -10
  103. package/dist/sveltekit/csrf.d.ts +16 -0
  104. package/dist/sveltekit/csrf.js +18 -0
  105. package/dist/sveltekit/guard.js +10 -3
  106. package/dist/sveltekit/index.d.ts +2 -1
  107. package/dist/sveltekit/index.js +1 -0
  108. package/dist/sveltekit/media-route.d.ts +12 -0
  109. package/dist/sveltekit/media-route.js +137 -0
  110. package/dist/vite/index.d.ts +3 -0
  111. package/dist/vite/index.js +7 -2
  112. package/package.json +7 -1
  113. package/src/lib/components/AdminLayout.svelte +3 -0
  114. package/src/lib/components/CairnAdmin.svelte +8 -1
  115. package/src/lib/components/CairnMediaLibrary.svelte +929 -0
  116. package/src/lib/components/EditPage.svelte +347 -7
  117. package/src/lib/components/MarkdownEditor.svelte +283 -1
  118. package/src/lib/components/MediaCaptureCard.svelte +135 -0
  119. package/src/lib/components/MediaFigureControl.svelte +247 -0
  120. package/src/lib/components/MediaHeroField.svelte +569 -0
  121. package/src/lib/components/MediaInsertPopover.svelte +449 -0
  122. package/src/lib/components/MediaPicker.svelte +257 -0
  123. package/src/lib/components/admin-icons.ts +12 -0
  124. package/src/lib/components/cairn-admin.css +37 -0
  125. package/src/lib/components/client-ingest.ts +380 -0
  126. package/src/lib/components/editor-media.ts +248 -0
  127. package/src/lib/components/editor-placeholder.ts +213 -0
  128. package/src/lib/components/index.ts +1 -0
  129. package/src/lib/components/markdown-directives.ts +46 -0
  130. package/src/lib/components/markdown-format.ts +307 -1
  131. package/src/lib/components/media-upload-outcome.ts +83 -0
  132. package/src/lib/content/compose.ts +3 -0
  133. package/src/lib/content/frontmatter.ts +16 -1
  134. package/src/lib/content/manifest.ts +44 -1
  135. package/src/lib/content/media-refs.ts +58 -0
  136. package/src/lib/content/schema.ts +31 -7
  137. package/src/lib/content/types.ts +78 -13
  138. package/src/lib/content/validate.ts +26 -1
  139. package/src/lib/delivery/public-routes.ts +52 -3
  140. package/src/lib/delivery/seo-fields.ts +6 -1
  141. package/src/lib/delivery/seo.ts +5 -0
  142. package/src/lib/doctor/checks-local.ts +22 -0
  143. package/src/lib/doctor/index.ts +21 -3
  144. package/src/lib/doctor/types.ts +3 -0
  145. package/src/lib/doctor/wrangler-config.ts +23 -0
  146. package/src/lib/env.ts +28 -0
  147. package/src/lib/index.ts +2 -0
  148. package/src/lib/log/events.ts +8 -1
  149. package/src/lib/media/config.ts +103 -0
  150. package/src/lib/media/delivery-bucket.ts +41 -0
  151. package/src/lib/media/index.ts +22 -0
  152. package/src/lib/media/library-entry.ts +58 -0
  153. package/src/lib/media/manifest.ts +122 -0
  154. package/src/lib/media/naming.ts +130 -0
  155. package/src/lib/media/reconcile.ts +79 -0
  156. package/src/lib/media/reference.ts +40 -0
  157. package/src/lib/media/sniff.ts +114 -0
  158. package/src/lib/media/store.ts +57 -0
  159. package/src/lib/media/transform-url.ts +58 -0
  160. package/src/lib/media/usage.ts +152 -0
  161. package/src/lib/render/pipeline.ts +17 -3
  162. package/src/lib/render/registry.ts +5 -0
  163. package/src/lib/render/remark-figure.ts +132 -0
  164. package/src/lib/render/resolve-media.ts +96 -0
  165. package/src/lib/render/sanitize-schema.ts +5 -3
  166. package/src/lib/sveltekit/admin-dispatch.ts +6 -1
  167. package/src/lib/sveltekit/cairn-admin.ts +13 -3
  168. package/src/lib/sveltekit/content-routes.ts +573 -12
  169. package/src/lib/sveltekit/csrf.ts +18 -0
  170. package/src/lib/sveltekit/guard.ts +12 -3
  171. package/src/lib/sveltekit/index.ts +6 -0
  172. package/src/lib/sveltekit/media-route.ts +158 -0
  173. package/src/lib/vite/index.ts +9 -2
@@ -12,6 +12,8 @@ export interface SeoInput {
12
12
  json?: string;
13
13
  };
14
14
  image?: string;
15
+ /** The social image's alt text, emitted as twitter:image:alt. Used only when image is also set. */
16
+ imageAlt?: string;
15
17
  /** A robots meta directive, e.g. "noindex, nofollow". Omitted from the head when absent. */
16
18
  robots?: string;
17
19
  /** Author name, emitted as article:author for the article type. */
@@ -16,6 +16,9 @@ export function buildSeoMeta(input) {
16
16
  if (input.image) {
17
17
  meta.push({ property: 'og:image', content: input.image });
18
18
  meta.push({ name: 'twitter:image', content: input.image });
19
+ if (input.imageAlt) {
20
+ meta.push({ name: 'twitter:image:alt', content: input.imageAlt });
21
+ }
19
22
  }
20
23
  if (input.robots) {
21
24
  meta.push({ name: 'robots', content: input.robots });
@@ -1,5 +1,6 @@
1
1
  import type { DoctorCheck } from './types.js';
2
2
  export declare const configBindings: DoctorCheck;
3
+ export declare const configMediaBucket: DoctorCheck;
3
4
  export declare const configObservability: DoctorCheck;
4
5
  export declare const configCsrfDisable: DoctorCheck;
5
6
  export declare const configPublicOrigin: DoctorCheck;
@@ -26,6 +26,27 @@ export const configBindings = {
26
26
  return pass('EMAIL and AUTH_DB are declared');
27
27
  },
28
28
  };
29
+ // The R2 media bucket is never added to the hard config.bindings check, so a no-media site never
30
+ // fails on a missing media binding (decision 9). This conditional runs only when the adapter
31
+ // declares assets, matching the adapter's bucketBinding against wrangler's r2_buckets. It reuses the
32
+ // config.bindings-missing condition rather than registering a new one, so the readiness count holds.
33
+ export const configMediaBucket = {
34
+ id: 'config.media-bucket',
35
+ conditionId: 'config.bindings-missing',
36
+ title: 'Media bucket binding',
37
+ async run(ctx) {
38
+ const binding = ctx.mediaBucketBinding;
39
+ if (binding === undefined)
40
+ return skip('no media assets configured');
41
+ const facts = await readWranglerConfig(ctx.readFile);
42
+ if (facts === null)
43
+ return NO_WRANGLER;
44
+ if (!facts.r2Buckets.includes(binding)) {
45
+ return fail(`adapter declares media bucket ${binding} but no matching r2_buckets binding is in wrangler`);
46
+ }
47
+ return pass(`media bucket ${binding} is declared`);
48
+ },
49
+ };
29
50
  export const configObservability = {
30
51
  id: 'config.observability',
31
52
  conditionId: 'config.observability-off',
@@ -22,11 +22,13 @@ export declare function contextFromEnv(env: Record<string, string | undefined>,
22
22
  * Vite resolution and the wrangler config's account_id. Each runs only when an input it feeds
23
23
  * is still missing, so a doctor run with full flags touches neither. */
24
24
  export interface DerivationSources {
25
- /** Returns { owner, repo, from } off the adapter, or null when nothing is derivable. */
25
+ /** Returns { owner, repo, from, mediaBucketBinding } off the adapter, or null when nothing is
26
+ * derivable. */
26
27
  adapterFacts: () => Promise<{
27
28
  owner?: string;
28
29
  repo?: string;
29
30
  from?: string;
31
+ mediaBucketBinding?: string;
30
32
  } | null>;
31
33
  /** Returns the wrangler config's account_id, or undefined when none is declared. */
32
34
  wranglerAccountId: () => Promise<string | undefined>;
@@ -1,4 +1,4 @@
1
- import { configBindings, configObservability, configCsrfDisable, configSiteConfig, configPublicOrigin, } from './checks-local.js';
1
+ import { configBindings, configMediaBucket, configObservability, configCsrfDisable, configSiteConfig, configPublicOrigin, } from './checks-local.js';
2
2
  import { configDependencyFloors } from './check-floors.js';
3
3
  import { emailSenderOnboarded, edgeHttpsForced, edgeHsts, authStore } from './checks-cloudflare.js';
4
4
  import { githubApp } from './checks-github.js';
@@ -69,7 +69,12 @@ export function contextFromEnv(env, args, cwd) {
69
69
  */
70
70
  export async function deriveMissingInputs(ctx, sources) {
71
71
  const out = { ...ctx };
72
- if (out.from === undefined || out.repo === undefined) {
72
+ // The adapter read also carries the media bucket binding, which has no env source, so it runs
73
+ // when from, repo, or the media binding is still missing. A failure leaves each input absent so
74
+ // its check skips with the usual remediation rather than the doctor crashing.
75
+ if (out.from === undefined ||
76
+ out.repo === undefined ||
77
+ out.mediaBucketBinding === undefined) {
73
78
  const facts = await sources.adapterFacts().catch(() => null);
74
79
  if (out.from === undefined && typeof facts?.from === 'string') {
75
80
  out.from = facts.from;
@@ -79,6 +84,9 @@ export async function deriveMissingInputs(ctx, sources) {
79
84
  typeof facts?.repo === 'string') {
80
85
  out.repo = `${facts.owner}/${facts.repo}`;
81
86
  }
87
+ if (out.mediaBucketBinding === undefined && typeof facts?.mediaBucketBinding === 'string') {
88
+ out.mediaBucketBinding = facts.mediaBucketBinding;
89
+ }
82
90
  }
83
91
  if (out.cfAccountId === undefined) {
84
92
  const accountId = await sources.wranglerAccountId().catch(() => undefined);
@@ -95,6 +103,7 @@ export async function deriveMissingInputs(ctx, sources) {
95
103
  export function defaultChecks() {
96
104
  return [
97
105
  configBindings,
106
+ configMediaBucket,
98
107
  configObservability,
99
108
  configCsrfDisable,
100
109
  configSiteConfig,
@@ -30,6 +30,9 @@ export interface DoctorContext {
30
30
  cfAccountId?: string;
31
31
  /** PUBLIC_ORIGIN, the env fallback when the wrangler vars carry none. */
32
32
  publicOrigin?: string;
33
+ /** The adapter's media bucket binding (cairn.assets.bucketBinding), derived off the adapter.
34
+ * Undefined when the site declares no media assets; the media-bucket check skips in that case. */
35
+ mediaBucketBinding?: string;
33
36
  /** GITHUB_APP_ID / GITHUB_APP_INSTALLATION_ID / GITHUB_APP_PRIVATE_KEY_B64. */
34
37
  github?: {
35
38
  appId: string;
@@ -12,5 +12,8 @@ export interface WranglerFacts {
12
12
  publicOrigin?: string;
13
13
  /** The top-level account_id, when declared; a fallback for CLOUDFLARE_ACCOUNT_ID. */
14
14
  accountId?: string;
15
+ /** The declared r2_buckets binding names; the conditional media check matches the adapter's
16
+ * bucketBinding against this. Not part of the hard config.bindings check (decision 9). */
17
+ r2Buckets: string[];
15
18
  }
16
19
  export declare function readWranglerConfig(readFile: DoctorContext['readFile']): Promise<WranglerFacts | null>;
@@ -64,10 +64,17 @@ function factsFromJsonc(text) {
64
64
  const databases = Array.isArray(config.d1_databases) ? config.d1_databases : [];
65
65
  const authDb = databases.find((entry) => typeof entry === 'object' && entry !== null && entry.binding === 'AUTH_DB');
66
66
  const observability = config.observability;
67
+ const r2 = Array.isArray(config.r2_buckets) ? config.r2_buckets : [];
68
+ const r2Buckets = r2
69
+ .map((entry) => typeof entry === 'object' && entry !== null && typeof entry.binding === 'string'
70
+ ? entry.binding
71
+ : undefined)
72
+ .filter((binding) => binding !== undefined);
67
73
  const facts = {
68
74
  hasEmailBinding,
69
75
  hasAuthDb: authDb !== undefined,
70
76
  observabilityEnabled: observability?.enabled === true,
77
+ r2Buckets,
71
78
  };
72
79
  if (typeof authDb?.database_id === 'string')
73
80
  facts.authDbId = authDb.database_id;
@@ -87,10 +94,12 @@ function factsFromToml(text) {
87
94
  hasEmailBinding: false,
88
95
  hasAuthDb: false,
89
96
  observabilityEnabled: false,
97
+ r2Buckets: [],
90
98
  };
91
99
  let section = '';
92
100
  let d1Binding;
93
101
  let d1Id;
102
+ let r2Binding;
94
103
  const flushD1 = () => {
95
104
  if (d1Binding === 'AUTH_DB') {
96
105
  facts.hasAuthDb = true;
@@ -100,10 +109,16 @@ function factsFromToml(text) {
100
109
  d1Binding = undefined;
101
110
  d1Id = undefined;
102
111
  };
112
+ const flushR2 = () => {
113
+ if (r2Binding !== undefined)
114
+ facts.r2Buckets.push(r2Binding);
115
+ r2Binding = undefined;
116
+ };
103
117
  for (const line of text.split('\n')) {
104
118
  const header = line.match(/^\s*(\[\[?[\w.]+\]?\])\s*(?:#.*)?$/);
105
119
  if (header) {
106
120
  flushD1();
121
+ flushR2();
107
122
  section = header[1];
108
123
  continue;
109
124
  }
@@ -121,6 +136,10 @@ function factsFromToml(text) {
121
136
  if (key === 'database_id')
122
137
  d1Id = str;
123
138
  }
139
+ else if (section === '[[r2_buckets]]') {
140
+ if (key === 'binding' && str !== undefined)
141
+ r2Binding = str;
142
+ }
124
143
  else if (section === '[observability]' && key === 'enabled' && value.startsWith('true')) {
125
144
  facts.observabilityEnabled = true;
126
145
  }
@@ -132,5 +151,6 @@ function factsFromToml(text) {
132
151
  }
133
152
  }
134
153
  flushD1();
154
+ flushR2();
135
155
  return facts;
136
156
  }
package/dist/env.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { D1Database } from '@cloudflare/workers-types';
2
+ import type { DeliveryBucket } from './media/delivery-bucket.js';
2
3
  /**
3
4
  * Returns the site's public origin from configuration.
4
5
  *
@@ -22,3 +23,21 @@ export declare function requireOrigin(env: {
22
23
  export declare function requireDb(env: {
23
24
  AUTH_DB?: D1Database;
24
25
  }): D1Database;
26
+ /**
27
+ * Returns the media R2 bucket named by `bindingName`, or throws a clear error when a site has not
28
+ * wired it. The binding name is config-derived (the adapter's `bucketBinding`), so it is read off
29
+ * `env` dynamically rather than as a fixed key.
30
+ *
31
+ * The return type is the narrow structural `DeliveryBucket` seam, never the `@cloudflare/workers-types`
32
+ * `R2Bucket`, so no workers-types name reaches the public `.d.ts` (the delivery route is a public
33
+ * export and that package is only a devDependency). The cast through `unknown` is sound because the
34
+ * seam models a subset of the real R2 bucket API.
35
+ *
36
+ * The guard rejects a value wired to the wrong kind of binding too (a KV namespace, a string var),
37
+ * which is truthy but carries no callable `get`. Without that check the cast would succeed and the
38
+ * first `bucket.get(...)` would throw an uncaught 500 rather than the drained 503 a missing binding
39
+ * earns.
40
+ *
41
+ * @throws CairnError (`config.bindings-missing`) when the named binding is absent or not an R2 bucket.
42
+ */
43
+ export declare function requireBucket(env: Record<string, unknown>, bindingName: string): DeliveryBucket;
package/dist/env.js CHANGED
@@ -47,3 +47,29 @@ export function requireDb(env) {
47
47
  }
48
48
  return env.AUTH_DB;
49
49
  }
50
+ /**
51
+ * Returns the media R2 bucket named by `bindingName`, or throws a clear error when a site has not
52
+ * wired it. The binding name is config-derived (the adapter's `bucketBinding`), so it is read off
53
+ * `env` dynamically rather than as a fixed key.
54
+ *
55
+ * The return type is the narrow structural `DeliveryBucket` seam, never the `@cloudflare/workers-types`
56
+ * `R2Bucket`, so no workers-types name reaches the public `.d.ts` (the delivery route is a public
57
+ * export and that package is only a devDependency). The cast through `unknown` is sound because the
58
+ * seam models a subset of the real R2 bucket API.
59
+ *
60
+ * The guard rejects a value wired to the wrong kind of binding too (a KV namespace, a string var),
61
+ * which is truthy but carries no callable `get`. Without that check the cast would succeed and the
62
+ * first `bucket.get(...)` would throw an uncaught 500 rather than the drained 503 a missing binding
63
+ * earns.
64
+ *
65
+ * @throws CairnError (`config.bindings-missing`) when the named binding is absent or not an R2 bucket.
66
+ */
67
+ export function requireBucket(env, bindingName) {
68
+ const bucket = env[bindingName];
69
+ if (!bucket || typeof bucket.get !== 'function') {
70
+ throw new CairnError('config.bindings-missing', {
71
+ message: `${bindingName} binding is not configured`,
72
+ });
73
+ }
74
+ return bucket;
75
+ }
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { requireOrigin } from './env.js';
2
2
  export type { Role, Editor, AuthEnv } from './auth/types.js';
3
3
  export type { AuthBranding, MagicLinkMessage, SendMagicLink } from './email.js';
4
4
  export { buildMagicLinkMessage, cloudflareSend } from './email.js';
5
- export type { CairnAdapter, ConceptConfig, FrontmatterField, TextField, TextareaField, DateField, BooleanField, TagsField, FreeTagsField, ValidationResult, BackendConfig, SenderConfig, NavMenuConfig, PreviewConfig, ResolvedPreview, AssetConfig, RoutingRule, ConceptDescriptor, ConceptUrlPolicy, CairnExtension, CairnRuntime, AdminPanel, FieldTypeDef, } from './content/types.js';
5
+ export type { CairnAdapter, ConceptConfig, FrontmatterField, TextField, TextareaField, DateField, BooleanField, TagsField, FreeTagsField, ImageField, ImageValue, ValidationResult, BackendConfig, SenderConfig, NavMenuConfig, PreviewConfig, ResolvedPreview, AssetConfig, RoutingRule, ConceptDescriptor, ConceptUrlPolicy, CairnExtension, CairnRuntime, AdminPanel, FieldTypeDef, } from './content/types.js';
6
6
  export { CONCEPT_ROUTING, normalizeConcepts, findConcept } from './content/concepts.js';
7
7
  export { composeRuntime } from './content/compose.js';
8
8
  export type { ComposeInput } from './content/compose.js';
@@ -1 +1 @@
1
- export type CairnLogEvent = 'auth.link.requested' | 'auth.link.send_failed' | 'auth.token.minted' | 'auth.token.confirmed' | 'auth.session.created' | 'auth.session.destroyed' | 'commit.succeeded' | 'commit.failed' | 'config.invalid' | 'entry.published' | 'entry.discarded' | 'publish.failed' | 'github.unreachable' | 'guard.rejected';
1
+ export type CairnLogEvent = 'auth.link.requested' | 'auth.link.send_failed' | 'auth.token.minted' | 'auth.token.confirmed' | 'auth.session.created' | 'auth.session.destroyed' | 'commit.succeeded' | 'commit.failed' | 'config.invalid' | 'entry.published' | 'entry.discarded' | 'publish.failed' | 'github.unreachable' | 'guard.rejected' | 'media.uploaded' | 'media.upload_failed' | 'media.delivery_failed' | 'media.orphan_reconcile' | 'media.resolve_missing' | 'media.deleted' | 'media.delete_blocked';
@@ -0,0 +1,24 @@
1
+ import type { AssetConfig } from '../content/types.js';
2
+ import type { VariantSpec } from './transform-url.js';
3
+ /** The resolved media config the engine serves from. When a site declares no assets block, media is
4
+ * off and the value is `{ enabled: false }`; otherwise every field is filled from the AssetConfig
5
+ * or its default. */
6
+ export type ResolvedAssetConfig = {
7
+ enabled: false;
8
+ } | {
9
+ enabled: true;
10
+ bucketBinding: string;
11
+ publicBase: string;
12
+ urlForm: 'slug' | 'opaque';
13
+ maxUploadBytes: number;
14
+ allowedTypes: string[];
15
+ variants: Record<string, VariantSpec>;
16
+ /** Whether Cloudflare Image Transformations are enabled for the zone. With it false, the media
17
+ * resolver serves the bare full-size delivery path and ignores any preset. */
18
+ transformations: boolean;
19
+ };
20
+ /** Validate a site's AssetConfig and resolve it into a ResolvedAssetConfig. An undefined block leaves
21
+ * media off and returns `{ enabled: false }` rather than throwing. A declared block must name its R2
22
+ * bucket and carry a known urlForm and valid variant fit and gravity values; each failure throws a
23
+ * cairn:-prefixed error. The named variants merge over the built-in presets. */
24
+ export declare function normalizeAssets(assets: AssetConfig | undefined): ResolvedAssetConfig;
@@ -0,0 +1,69 @@
1
+ /** The default delivery base path when the AssetConfig omits one. */
2
+ const DEFAULT_PUBLIC_BASE = '/media';
3
+ /** The default maximum upload size, 25 MB. */
4
+ const DEFAULT_MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
5
+ /** The default accepted upload MIME types: the common web image formats. */
6
+ const DEFAULT_ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif'];
7
+ /** The built-in named transform presets. A site's `variants` merge over these, so a caller preset of
8
+ * the same name overrides the built-in. */
9
+ const BUILT_IN_PRESETS = {
10
+ thumb: { width: 320, height: 320, fit: 'cover' },
11
+ inline: { width: 800 },
12
+ card: { width: 640, height: 400, fit: 'cover' },
13
+ hero: { width: 1600, height: 900, fit: 'cover' },
14
+ };
15
+ /** The fit values Cloudflare Images accepts. A variant whose fit is set to anything else is rejected. */
16
+ const FIT_VALUES = new Set(['scale-down', 'contain', 'cover', 'crop', 'pad']);
17
+ /** The named gravity keywords Cloudflare Images accepts. A gravity is also valid as a coordinate
18
+ * string; everything else is rejected. */
19
+ const GRAVITY_KEYWORDS = new Set([
20
+ 'auto',
21
+ 'face',
22
+ 'left',
23
+ 'right',
24
+ 'top',
25
+ 'bottom',
26
+ 'center',
27
+ ]);
28
+ /** A gravity coordinate string, e.g. "0.5x0.5". */
29
+ const GRAVITY_COORD_RE = /^\d+(\.\d+)?x\d+(\.\d+)?$/;
30
+ /** Validate one variant's fit and gravity, throwing a cairn:-prefixed error naming the offending
31
+ * preset and value. The type system collapses VariantSpec.gravity to string, so the gravity check
32
+ * is the only guard against a bogus value reaching the transform URL. */
33
+ function validateVariant(name, spec) {
34
+ if (spec.fit !== undefined && !FIT_VALUES.has(spec.fit)) {
35
+ throw new Error(`cairn: media variant "${name}" has an unknown fit "${spec.fit}"`);
36
+ }
37
+ if (spec.gravity !== undefined &&
38
+ !GRAVITY_KEYWORDS.has(spec.gravity) &&
39
+ !GRAVITY_COORD_RE.test(spec.gravity)) {
40
+ throw new Error(`cairn: media variant "${name}" has an unknown gravity "${spec.gravity}"`);
41
+ }
42
+ }
43
+ /** Validate a site's AssetConfig and resolve it into a ResolvedAssetConfig. An undefined block leaves
44
+ * media off and returns `{ enabled: false }` rather than throwing. A declared block must name its R2
45
+ * bucket and carry a known urlForm and valid variant fit and gravity values; each failure throws a
46
+ * cairn:-prefixed error. The named variants merge over the built-in presets. */
47
+ export function normalizeAssets(assets) {
48
+ if (assets === undefined)
49
+ return { enabled: false };
50
+ if (!assets.bucketBinding) {
51
+ throw new Error('cairn: a media assets block must name its R2 bucket binding');
52
+ }
53
+ if (assets.urlForm !== undefined && assets.urlForm !== 'slug' && assets.urlForm !== 'opaque') {
54
+ throw new Error(`cairn: media urlForm must be "slug" or "opaque", got "${assets.urlForm}"`);
55
+ }
56
+ for (const [name, spec] of Object.entries(assets.variants ?? {})) {
57
+ validateVariant(name, spec);
58
+ }
59
+ return {
60
+ enabled: true,
61
+ bucketBinding: assets.bucketBinding,
62
+ publicBase: assets.publicBase ?? DEFAULT_PUBLIC_BASE,
63
+ urlForm: assets.urlForm ?? 'slug',
64
+ maxUploadBytes: assets.maxUploadBytes ?? DEFAULT_MAX_UPLOAD_BYTES,
65
+ allowedTypes: assets.allowedTypes ?? DEFAULT_ALLOWED_TYPES,
66
+ variants: { ...BUILT_IN_PRESETS, ...(assets.variants ?? {}) },
67
+ transformations: assets.transformations ?? false,
68
+ };
69
+ }
@@ -0,0 +1,34 @@
1
+ /** A stored object without its body: the shape an `If-None-Match` hit or a metadata read returns. */
2
+ export interface DeliveryObject {
3
+ /** Writes the stored HTTP metadata (Content-Type, Cache-Control, and so on) onto `headers`. */
4
+ writeHttpMetadata(headers: Headers): void;
5
+ /** The strong validator R2 stored for the bytes, set as the response `ETag`. */
6
+ httpEtag: string;
7
+ /** The full object size in bytes, the denominator of a `Content-Range`. */
8
+ size: number;
9
+ /** Present only on a ranged read: the served window, used to build the `Content-Range`. R2 fills
10
+ * both fields for a `bytes=start-end` request; each is typed optional so the route derives the
11
+ * range bounds defensively against `size`. */
12
+ range?: {
13
+ offset?: number;
14
+ length?: number;
15
+ };
16
+ }
17
+ /** A stored object with its readable body, the shape a full or ranged read returns. */
18
+ export interface DeliveryObjectBody extends DeliveryObject {
19
+ body: ReadableStream;
20
+ }
21
+ /** The bucket surface the delivery route reads: a single conditional, optionally ranged, get. */
22
+ export interface DeliveryBucket {
23
+ get(key: string, opts?: {
24
+ /** R2 reads `If-None-Match`/`If-Match` from a passed `Headers`; the route forwards the request's. */
25
+ onlyIf?: {
26
+ etagDoesNotMatch?: string;
27
+ } | Headers;
28
+ /** The byte window to serve; the route parses it from the request `Range` header. */
29
+ range?: {
30
+ offset?: number;
31
+ length?: number;
32
+ } | Headers;
33
+ }): Promise<DeliveryObjectBody | DeliveryObject | null>;
34
+ }
@@ -0,0 +1,10 @@
1
+ // A narrow structural seam over the R2 bucket, modelling only what the delivery route reads.
2
+ //
3
+ // The route needs conditional and ranged gets, which the narrow MediaStore seam cannot express, so
4
+ // it talks to the raw bucket. It must not name any `@cloudflare/workers-types` type (`R2Bucket`,
5
+ // `R2Object`, `R2ObjectBody`, `R2HTTPMetadata`): that package is a devDependency the engine builds
6
+ // against but a consumer does not have, so any such name in a public `.d.ts` would break a consumer
7
+ // build that lacks `skipLibCheck`. `Headers`, `ReadableStream`, and `Response` are web globals, not
8
+ // workers-types, so they are safe on the public surface. `requireBucket` casts the real R2 binding
9
+ // to `DeliveryBucket` through `unknown`; the shapes below are a structural subset of the real R2 API.
10
+ export {};
@@ -0,0 +1,6 @@
1
+ export { normalizeAssets, type ResolvedAssetConfig } from './config.js';
2
+ export { parseMediaManifest, findByHash, upsertMediaEntry, removeMediaEntry, serializeMediaManifest, parseMediaEntries, type MediaEntry, type MediaManifest, } from './manifest.js';
3
+ export { hashBytes, shortHash, slugifyFilename, r2Key, publicPath } from './naming.js';
4
+ export { presetUrl, variantUrl, type VariantSpec } from './transform-url.js';
5
+ export { parseMediaToken, mediaToken, type MediaRef } from './reference.js';
6
+ export { makeMediaResolver, manifestMediaResolver, type MediaResolve } from '../render/resolve-media.js';
@@ -0,0 +1,13 @@
1
+ // cairn-cms: the node-safe `/media` public barrel. It re-exports only the pure media surface a site
2
+ // reaches outside the SvelteKit runtime: the config normalizer, the manifest functions, the naming
3
+ // and transform-URL helpers, the reference codec, and the render resolver. Nothing here pulls
4
+ // `@sveltejs/kit` or `@cloudflare/workers-types` into the module graph, so a plain-Node tool or a
5
+ // build step can import it. The R2-touching pieces (`store.ts`, `delivery-bucket.ts`) and the
6
+ // delivery-route factory and `requireBucket` stay on `/sveltekit`, off this surface, so the public
7
+ // `.d.ts` for `/media` names no kit or workers-types type.
8
+ export { normalizeAssets } from './config.js';
9
+ export { parseMediaManifest, findByHash, upsertMediaEntry, removeMediaEntry, serializeMediaManifest, parseMediaEntries, } from './manifest.js';
10
+ export { hashBytes, shortHash, slugifyFilename, r2Key, publicPath } from './naming.js';
11
+ export { presetUrl, variantUrl } from './transform-url.js';
12
+ export { parseMediaToken, mediaToken } from './reference.js';
13
+ export { makeMediaResolver, manifestMediaResolver } from '../render/resolve-media.js';
@@ -0,0 +1,30 @@
1
+ import type { MediaEntry } from './manifest.js';
2
+ /** One stored asset in the picker's projected library, keyed elsewhere by the 16-hex content hash. */
3
+ export interface MediaLibraryEntry {
4
+ /** The 16-hex content-hash prefix that names the bytes. */
5
+ hash: string;
6
+ /** The cosmetic display slug in the media: token and the delivery path. */
7
+ slug: string;
8
+ /** The bare file extension (no dot), for example `webp`. */
9
+ ext: string;
10
+ /** The stored MIME type, for example `image/webp`; its top-level part drives the type facet. */
11
+ contentType: string;
12
+ /** The editable human name shown on the row. */
13
+ displayName: string;
14
+ /** The manifest alt, prefilled into a new placement; empty is the needs-alt signal. */
15
+ alt: string;
16
+ /** The pixel width, or null when the manifest carries none. */
17
+ width: number | null;
18
+ /** The pixel height, or null when the manifest carries none. */
19
+ height: number | null;
20
+ /** The stored byte size. */
21
+ bytes: number;
22
+ /** The ISO timestamp the bytes were first stored, the Library's sortable "Added" column. */
23
+ createdAt: string;
24
+ }
25
+ /** The projected library keyed by the 16-hex content hash, exactly EditData's `mediaLibrary`. */
26
+ export type MediaLibrary = Record<string, MediaLibraryEntry>;
27
+ /** Project a stored MediaEntry to the picker's MediaLibraryEntry, copying every display field and
28
+ * dropping the source-only sha256 and original filename. The single projection editLoad and
29
+ * mediaLibraryLoad both call, so the popover and the Library never diverge on the shared shape. */
30
+ export declare function mediaLibraryEntry(entry: MediaEntry): MediaLibraryEntry;
@@ -0,0 +1,17 @@
1
+ /** Project a stored MediaEntry to the picker's MediaLibraryEntry, copying every display field and
2
+ * dropping the source-only sha256 and original filename. The single projection editLoad and
3
+ * mediaLibraryLoad both call, so the popover and the Library never diverge on the shared shape. */
4
+ export function mediaLibraryEntry(entry) {
5
+ return {
6
+ hash: entry.hash,
7
+ slug: entry.slug,
8
+ ext: entry.ext,
9
+ contentType: entry.contentType,
10
+ displayName: entry.displayName,
11
+ alt: entry.alt,
12
+ width: entry.width,
13
+ height: entry.height,
14
+ bytes: entry.bytes,
15
+ createdAt: entry.createdAt,
16
+ };
17
+ }
@@ -0,0 +1,44 @@
1
+ /** One stored asset's row: its content hash, its human layer, and its byte and pixel facts. The
2
+ * `contentType` is the stored MIME type, so the delivery route serves it verbatim rather than
3
+ * guessing from the extension. `width` and `height` are null when no dimensions are known (the
4
+ * client is the only dimension source and a Worker cannot re-derive them). */
5
+ export interface MediaEntry {
6
+ hash: string;
7
+ sha256: string;
8
+ slug: string;
9
+ displayName: string;
10
+ originalFilename: string;
11
+ alt: string;
12
+ ext: string;
13
+ contentType: string;
14
+ bytes: number;
15
+ width: number | null;
16
+ height: number | null;
17
+ createdAt: string;
18
+ }
19
+ /** The whole stored-asset record, keyed by the 16-hex content-hash prefix. */
20
+ export type MediaManifest = Record<string, MediaEntry>;
21
+ /** Parse a committed media manifest. Tolerant: an empty, missing, null, or non-object input yields
22
+ * an empty manifest, so a first ingest into a site with no manifest file reads a clean {}. A valid
23
+ * object is returned as the manifest. */
24
+ export declare function parseMediaManifest(json: unknown): MediaManifest;
25
+ /** Parse the posted `media` field into a validated list of MediaEntry rows. The field arrives as a
26
+ * JSON string (the usual form-post shape), an already-parsed array, or junk. A string is JSON-parsed
27
+ * inside a try/catch that yields `[]` on a parse failure; a non-string array is taken directly;
28
+ * anything else yields `[]`. Each element is validated and a failing element is dropped, so a partly
29
+ * malformed post still lands its good rows. This is the trust boundary for the client's optimistic
30
+ * records. */
31
+ export declare function parseMediaEntries(value: unknown): MediaEntry[];
32
+ /** The dedup lookup: the entry stored under the content-hash prefix, or undefined when no bytes with
33
+ * that hash are stored yet. */
34
+ export declare function findByHash(manifest: MediaManifest, hash: string): MediaEntry | undefined;
35
+ /** Set the entry under its own hash, replacing any same-hash row. Returns a new manifest and leaves
36
+ * the input untouched, so a caller's prior manifest reference stays valid. The ingest path's patch. */
37
+ export declare function upsertMediaEntry(manifest: MediaManifest, entry: MediaEntry): MediaManifest;
38
+ /** Drop the entry under the given hash, returning a new manifest and leaving the input untouched.
39
+ * Removing an absent hash is a no-op that still returns an equivalent new manifest. The safe-delete
40
+ * path's patch. */
41
+ export declare function removeMediaEntry(manifest: MediaManifest, hash: string): MediaManifest;
42
+ /** Serialize canonically: the top-level hash keys sorted ascending, two-space pretty, and a trailing
43
+ * newline, so the committed file diffs cleanly in a PR and a re-serialization is byte-identical. */
44
+ export declare function serializeMediaManifest(manifest: MediaManifest): string;
@@ -0,0 +1,105 @@
1
+ // cairn-cms: the media manifest, a small git-committed record with one row per stored asset. It
2
+ // carries the human layer that the bytes cannot (display name, alt text, original filename) and is
3
+ // the dedup lookup: an ingest checks the content-hash prefix here before storing, so the same bytes
4
+ // are never stored twice. It mirrors the content manifest in ../content/manifest.ts, keyed by the
5
+ // 16-hex content-hash prefix rather than concept and id.
6
+ /** Parse a committed media manifest. Tolerant: an empty, missing, null, or non-object input yields
7
+ * an empty manifest, so a first ingest into a site with no manifest file reads a clean {}. A valid
8
+ * object is returned as the manifest. */
9
+ export function parseMediaManifest(json) {
10
+ if (!json || typeof json !== 'object' || Array.isArray(json))
11
+ return {};
12
+ return json;
13
+ }
14
+ /** Validate one posted value as a MediaEntry, returning it narrowed or undefined. The trust boundary
15
+ * for an optimistic record the client re-posts: the upload action server-owned each field at
16
+ * creation, but a re-post is untrusted, so every field is re-checked. A `hash` must be the 16-hex
17
+ * content-hash prefix; the string fields must be strings; `bytes` must be finite; `width`/`height`
18
+ * must each be a number or null; `createdAt` must be a string. */
19
+ function validateMediaEntry(value) {
20
+ if (!value || typeof value !== 'object')
21
+ return undefined;
22
+ const e = value;
23
+ const isString = (v) => typeof v === 'string';
24
+ const isNumOrNull = (v) => v === null || typeof v === 'number';
25
+ if (typeof e.hash !== 'string' || !/^[0-9a-f]{16}$/.test(e.hash))
26
+ return undefined;
27
+ if (!isString(e.sha256))
28
+ return undefined;
29
+ if (!isString(e.slug) || !isString(e.displayName) || !isString(e.originalFilename))
30
+ return undefined;
31
+ if (!isString(e.alt) || !isString(e.ext) || !isString(e.contentType))
32
+ return undefined;
33
+ if (typeof e.bytes !== 'number' || !Number.isFinite(e.bytes))
34
+ return undefined;
35
+ if (!isNumOrNull(e.width) || !isNumOrNull(e.height))
36
+ return undefined;
37
+ if (!isString(e.createdAt))
38
+ return undefined;
39
+ return {
40
+ hash: e.hash,
41
+ sha256: e.sha256,
42
+ slug: e.slug,
43
+ displayName: e.displayName,
44
+ originalFilename: e.originalFilename,
45
+ alt: e.alt,
46
+ ext: e.ext,
47
+ contentType: e.contentType,
48
+ bytes: e.bytes,
49
+ width: e.width,
50
+ height: e.height,
51
+ createdAt: e.createdAt,
52
+ };
53
+ }
54
+ /** Parse the posted `media` field into a validated list of MediaEntry rows. The field arrives as a
55
+ * JSON string (the usual form-post shape), an already-parsed array, or junk. A string is JSON-parsed
56
+ * inside a try/catch that yields `[]` on a parse failure; a non-string array is taken directly;
57
+ * anything else yields `[]`. Each element is validated and a failing element is dropped, so a partly
58
+ * malformed post still lands its good rows. This is the trust boundary for the client's optimistic
59
+ * records. */
60
+ export function parseMediaEntries(value) {
61
+ let raw = value;
62
+ if (typeof value === 'string') {
63
+ try {
64
+ raw = JSON.parse(value);
65
+ }
66
+ catch {
67
+ return [];
68
+ }
69
+ }
70
+ if (!Array.isArray(raw))
71
+ return [];
72
+ const entries = [];
73
+ for (const item of raw) {
74
+ const entry = validateMediaEntry(item);
75
+ if (entry)
76
+ entries.push(entry);
77
+ }
78
+ return entries;
79
+ }
80
+ /** The dedup lookup: the entry stored under the content-hash prefix, or undefined when no bytes with
81
+ * that hash are stored yet. */
82
+ export function findByHash(manifest, hash) {
83
+ return manifest[hash];
84
+ }
85
+ /** Set the entry under its own hash, replacing any same-hash row. Returns a new manifest and leaves
86
+ * the input untouched, so a caller's prior manifest reference stays valid. The ingest path's patch. */
87
+ export function upsertMediaEntry(manifest, entry) {
88
+ return { ...manifest, [entry.hash]: entry };
89
+ }
90
+ /** Drop the entry under the given hash, returning a new manifest and leaving the input untouched.
91
+ * Removing an absent hash is a no-op that still returns an equivalent new manifest. The safe-delete
92
+ * path's patch. */
93
+ export function removeMediaEntry(manifest, hash) {
94
+ const { [hash]: _removed, ...rest } = manifest;
95
+ return rest;
96
+ }
97
+ /** Serialize canonically: the top-level hash keys sorted ascending, two-space pretty, and a trailing
98
+ * newline, so the committed file diffs cleanly in a PR and a re-serialization is byte-identical. */
99
+ export function serializeMediaManifest(manifest) {
100
+ const sorted = {};
101
+ for (const hash of Object.keys(manifest).sort()) {
102
+ sorted[hash] = manifest[hash];
103
+ }
104
+ return `${JSON.stringify(sorted, null, 2)}\n`;
105
+ }