@wervt/cms 0.0.2 → 0.0.4

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 (50) hide show
  1. package/README.md +150 -13
  2. package/dist/editor/assets/Button-Dai6Ph2c.js +6 -0
  3. package/dist/editor/assets/RichTextInput-CdL9ZFoP.js +271 -0
  4. package/dist/editor/assets/Toast-BaUcosq6.js +13 -0
  5. package/dist/editor/assets/index-CP6dGIyl.css +2 -0
  6. package/dist/editor/assets/index-Du-lvx2V.js +16 -0
  7. package/dist/editor/assets/poppins-latin-400-normal-BOb3E3N0.woff +0 -0
  8. package/dist/editor/assets/poppins-latin-400-normal-cpxAROuN.woff2 +0 -0
  9. package/dist/editor/assets/poppins-latin-500-normal-C8OXljZJ.woff2 +0 -0
  10. package/dist/editor/assets/poppins-latin-500-normal-DGXqpDMm.woff +0 -0
  11. package/dist/editor/assets/poppins-latin-600-normal-BJdTmd5m.woff +0 -0
  12. package/dist/editor/assets/poppins-latin-600-normal-zEkxB9Mr.woff2 +0 -0
  13. package/dist/editor/index.html +15 -0
  14. package/dist/editor-theme.d.ts +28 -0
  15. package/dist/editor-theme.js +62 -0
  16. package/dist/module.d.ts +6 -1
  17. package/dist/module.js +101 -11
  18. package/dist/runtime/app/CmsRichText.d.ts +15 -0
  19. package/dist/runtime/app/CmsRichText.js +48 -0
  20. package/dist/runtime/app/drafts.d.ts +5 -0
  21. package/dist/runtime/app/drafts.js +8 -0
  22. package/dist/runtime/app/preview.client.d.ts +2 -0
  23. package/dist/runtime/app/preview.client.js +28 -0
  24. package/dist/runtime/app/useCms.d.ts +9 -2
  25. package/dist/runtime/app/useCms.js +12 -5
  26. package/dist/runtime/fields.d.ts +24 -0
  27. package/dist/runtime/fields.js +109 -0
  28. package/dist/runtime/pages.d.ts +3 -0
  29. package/dist/runtime/pages.js +14 -0
  30. package/dist/runtime/preview.d.ts +34 -0
  31. package/dist/runtime/preview.js +35 -0
  32. package/dist/runtime/schema.d.ts +108 -0
  33. package/dist/runtime/schema.js +74 -0
  34. package/dist/runtime/server/dev-images.d.ts +2 -0
  35. package/dist/runtime/server/dev-images.js +12 -0
  36. package/dist/runtime/server/editor.get.d.ts +2 -0
  37. package/dist/runtime/server/editor.get.js +9 -0
  38. package/dist/runtime/server/entry.get.d.ts +7 -2
  39. package/dist/runtime/server/entry.get.js +11 -1
  40. package/dist/runtime/server/entry.put.js +14 -1
  41. package/dist/runtime/server/images.d.ts +4 -0
  42. package/dist/runtime/server/images.js +30 -0
  43. package/dist/runtime/server/schema.get.d.ts +10 -0
  44. package/dist/runtime/server/schema.get.js +10 -0
  45. package/dist/runtime/server/sniff.d.ts +11 -0
  46. package/dist/runtime/server/sniff.js +53 -0
  47. package/dist/runtime/server/upload.post.d.ts +13 -0
  48. package/dist/runtime/server/upload.post.js +44 -0
  49. package/package.json +29 -5
  50. package/dist/runtime/app/editor.vue +0 -42
@@ -0,0 +1,15 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="robots" content="noindex" />
7
+ <title>Edit content</title>
8
+ <script type="module" crossorigin src="/_cms/assets/index-Du-lvx2V.js"></script>
9
+ <link rel="modulepreload" crossorigin href="/_cms/assets/Button-Dai6Ph2c.js">
10
+ <link rel="stylesheet" crossorigin href="/_cms/assets/index-CP6dGIyl.css">
11
+ </head>
12
+ <body>
13
+ <div id="app" class="isolate"></div>
14
+ </body>
15
+ </html>
@@ -0,0 +1,28 @@
1
+ declare const TOKENS: readonly ['bg', 'bg-muted', 'bg-elevated', 'bg-accented', 'bg-inverted', 'border', 'border-muted', 'border-accented', 'border-inverted', 'text', 'text-dimmed', 'text-muted', 'text-toned', 'text-highlighted', 'text-inverted'];
2
+ /** Nuxt UI's color tokens without `--ui-` (`bg`, `text-muted`, …), as CSS colors. */
3
+ export type EditorThemeColors = Partial<Record<(typeof TOKENS)[number], string>>;
4
+ /**
5
+ * The editor's look on this site, over wervt's. Every value is plain CSS.
6
+ *
7
+ * ```ts
8
+ * cms: { editor: { theme: { primary: '#1475bd', buttons: 'primary', font: "'Inter', sans-serif" } } }
9
+ * ```
10
+ */
11
+ export interface EditorTheme {
12
+ /** Links, focus rings, toggles: one color, or one per color mode. */
13
+ primary?: string | {
14
+ light: string;
15
+ dark: string;
16
+ };
17
+ /** The save button in black and white (`neutral`, wervt's) or in the primary color. */
18
+ buttons?: 'neutral' | 'primary';
19
+ /** A `font-family`. The font must come from the stylesheet or the device. */
20
+ font?: string;
21
+ /** The base radius; buttons and fields use 1.5× of it. */
22
+ radius?: string;
23
+ light?: EditorThemeColors;
24
+ dark?: EditorThemeColors;
25
+ /** A stylesheet the editor loads after its own, for `@font-face` or further rules: a path on the site or an https URL. */
26
+ stylesheet?: string;
27
+ }
28
+ export {};
@@ -0,0 +1,62 @@
1
+ // src/editor-theme.ts
2
+ const TOKENS = [
3
+ "bg",
4
+ "bg-muted",
5
+ "bg-elevated",
6
+ "bg-accented",
7
+ "bg-inverted",
8
+ "border",
9
+ "border-muted",
10
+ "border-accented",
11
+ "border-inverted",
12
+ "text",
13
+ "text-dimmed",
14
+ "text-muted",
15
+ "text-toned",
16
+ "text-highlighted",
17
+ "text-inverted"
18
+ ];
19
+ /** What the module adds to the editor's `<head>`; throws on values that would break out of CSS. */
20
+ function editorThemeHead(theme) {
21
+ if (!theme) return "";
22
+ const css = (where, value) => {
23
+ if (typeof value !== "string" || !value.trim() || /[<>{};\\]/.test(value)) throw new Error(`[@wervt/cms] cms.editor.theme.${where} must be a plain CSS value`);
24
+ return value.trim();
25
+ };
26
+ const colors = (mode) => Object.entries(theme[mode] ?? {}).map(([token, value]) => {
27
+ if (!TOKENS.includes(token)) throw new Error(`[@wervt/cms] cms.editor.theme.${mode}.${token} is not one of ${TOKENS.join(", ")}`);
28
+ return `--ui-${token}: ${css(`${mode}.${token}`, value)};`;
29
+ });
30
+ const primary = typeof theme.primary === "object" ? {
31
+ light: css("primary.light", theme.primary.light),
32
+ dark: css("primary.dark", theme.primary.dark)
33
+ } : theme.primary === void 0 ? void 0 : {
34
+ light: css("primary", theme.primary),
35
+ dark: css("primary", theme.primary)
36
+ };
37
+ const root = [
38
+ ...primary ? [`--ui-primary: ${primary.light};`] : [],
39
+ ...theme.radius === void 0 ? [] : [`--ui-radius: ${css("radius", theme.radius)};`],
40
+ ...theme.font === void 0 ? [] : [`--font-sans: ${css("font", theme.font)};`]
41
+ ];
42
+ const light = colors("light");
43
+ const dark = [...primary ? [`--ui-primary: ${primary.dark};`] : [], ...colors("dark")];
44
+ const tags = [];
45
+ const rules = [
46
+ ...root.length ? [`:root { ${root.join(" ")} }`] : [],
47
+ ...light.length ? [`:root:not(.dark) { ${light.join(" ")} }`] : [],
48
+ ...dark.length ? [`.dark { ${dark.join(" ")} }`] : []
49
+ ];
50
+ if (rules.length) tags.push(`<style>${rules.join("\n")}</style>`);
51
+ if (theme.stylesheet !== void 0) {
52
+ const href = theme.stylesheet;
53
+ if (!/^(\/(?!\/)|https:\/\/)[^\s"'<>\\]+$/.test(href)) throw new Error("[@wervt/cms] cms.editor.theme.stylesheet must be a path like /editor.css or an https URL");
54
+ tags.push(`<link rel="stylesheet" href="${href}">`);
55
+ }
56
+ if (theme.buttons !== void 0) {
57
+ if (theme.buttons !== "neutral" && theme.buttons !== "primary") throw new Error("[@wervt/cms] cms.editor.theme.buttons must be 'neutral' or 'primary'");
58
+ tags.push(`<meta name="cms-buttons" content="${theme.buttons}">`);
59
+ }
60
+ return tags.join("\n");
61
+ }
62
+ export { editorThemeHead };
package/dist/module.d.ts CHANGED
@@ -1,9 +1,14 @@
1
+ import { EditorTheme, EditorThemeColors } from "./editor-theme.js";
1
2
  export interface ModuleOptions {
2
3
  /**
3
4
  * Signed-in people with a confirmed address who may edit besides the app's owner, members and
4
5
  * admins. Set at runtime with `NUXT_CMS_EDITORS` (comma-separated), no redeploy needed.
5
6
  */
6
7
  editors?: string;
8
+ editor?: {
9
+ /** The editor's look on this site; wervt's when missing. */
10
+ theme?: EditorTheme;
11
+ };
7
12
  }
8
13
  declare const _default: import("nuxt/schema").NuxtModule<ModuleOptions, ModuleOptions, false>;
9
- export { _default as default };
14
+ export { type EditorTheme, type EditorThemeColors, _default as default };
package/dist/module.js CHANGED
@@ -1,14 +1,18 @@
1
+ import { editorThemeHead } from "./editor-theme.js";
1
2
  import { stampEntries } from "./runtime/server/entries.js";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { addImports, addServerHandler, addServerTemplate, createResolver, defineNuxtModule, extendPages } from "nuxt/kit";
3
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
4
+ import { join, relative, resolve } from "node:path";
5
+ import { addComponent, addImports, addPlugin, addServerHandler, addServerTemplate, addTemplate, addTypeTemplate, createResolver, defineNuxtModule, resolveFiles } from "nuxt/kit";
5
6
  // src/module.ts
6
7
  var module_default = defineNuxtModule({
7
8
  meta: {
8
9
  name: "@wervt/cms",
9
10
  configKey: "cms"
10
11
  },
11
- moduleDependencies: { "@wervt/nuxt": { overrides: { database: true } } },
12
+ moduleDependencies: {
13
+ ablage: { defaults: { image: false } },
14
+ "@wervt/nuxt": { overrides: { database: true } }
15
+ },
12
16
  defaults: { editors: "" },
13
17
  setup(options, nuxt) {
14
18
  const resolver = createResolver(import.meta.url);
@@ -17,7 +21,51 @@ var module_default = defineNuxtModule({
17
21
  editors: options.editors ?? "",
18
22
  ...config.cms
19
23
  };
20
- const file = join(nuxt.options.rootDir, "cms/entries.json");
24
+ const cmsDir = join(nuxt.options.rootDir, "cms");
25
+ const file = join(cmsDir, "entries.json");
26
+ const publicDir = resolve(nuxt.options.rootDir, nuxt.options.dir.public);
27
+ const schemaFiles = async () => (await resolveFiles(cmsDir, [
28
+ "**/*.{ts,js,mjs}",
29
+ "!**/*.d.ts",
30
+ "!**/*.test.*"
31
+ ])).sort();
32
+ const pagesTemplate = addTemplate({
33
+ filename: "wervt-cms/pages.mjs",
34
+ write: true,
35
+ getContents: async () => {
36
+ const files = await schemaFiles();
37
+ return [
38
+ ...files.map((path, i) => `import * as m${i} from ${JSON.stringify(path)}`),
39
+ `export const modules = [${files.map((_, i) => `m${i}`).join(", ")}]`,
40
+ ""
41
+ ].join("\n");
42
+ }
43
+ });
44
+ nuxt.options.alias["#wervt-cms/pages"] = pagesTemplate.dst;
45
+ addTypeTemplate({
46
+ filename: "types/wervt-cms.d.ts",
47
+ getContents: async () => {
48
+ const dir = join(nuxt.options.buildDir, "types");
49
+ const pages = (await schemaFiles()).map((path) => `PagesOf<typeof import(${JSON.stringify(relative(dir, path).replace(/\.[cm]?[jt]s$/, ""))})>`);
50
+ return [
51
+ `import type { PagesOf } from '@wervt/cms/schema'`,
52
+ `declare module '@wervt/cms/schema' {`,
53
+ ` interface CmsPages ${pages.length ? `extends ${pages.join(", ")} ` : ""}{}`,
54
+ `}`,
55
+ `export {}`,
56
+ ""
57
+ ].join("\n");
58
+ }
59
+ });
60
+ if (nuxt.options.dev && !nuxt.options._prepare) {
61
+ mkdirSync(cmsDir, { recursive: true });
62
+ if (!nuxt.options.watch.includes(cmsDir)) nuxt.options.watch.push(cmsDir);
63
+ }
64
+ nuxt.hook("builder:watch", async (event, path) => {
65
+ if (event !== "add" && event !== "unlink") return;
66
+ const absolute = resolve(nuxt.options.srcDir, path);
67
+ if (absolute.startsWith(`${cmsDir}/`) && /\.(?:ts|js|mjs)$/.test(absolute)) await nuxt.callHook("restart");
68
+ });
21
69
  addServerTemplate({
22
70
  filename: "#wervt-cms/entries",
23
71
  getContents: () => {
@@ -26,6 +74,7 @@ var module_default = defineNuxtModule({
26
74
  return [
27
75
  `export const entries = ${JSON.stringify(stamped)}`,
28
76
  `export const file = ${nuxt.options.dev ? JSON.stringify(file) : "undefined"}`,
77
+ `export const publicDir = ${nuxt.options.dev ? JSON.stringify(publicDir) : "undefined"}`,
29
78
  ""
30
79
  ].join("\n");
31
80
  }
@@ -40,17 +89,58 @@ var module_default = defineNuxtModule({
40
89
  method: "put",
41
90
  handler: resolver.resolve("./runtime/server/entry.put")
42
91
  });
92
+ addServerHandler({
93
+ route: "/api/_cms/schema",
94
+ method: "get",
95
+ handler: resolver.resolve("./runtime/server/schema.get")
96
+ });
97
+ addServerHandler({
98
+ route: "/api/_cms/images",
99
+ method: "post",
100
+ handler: resolver.resolve("./runtime/server/upload.post")
101
+ });
43
102
  addImports({
44
103
  name: "useCms",
45
104
  from: resolver.resolve("./runtime/app/useCms")
46
105
  });
47
- extendPages((pages) => {
48
- pages.push({
49
- name: "wervt-cms",
50
- path: "/_cms",
51
- file: resolver.resolve("./runtime/app/editor.vue")
52
- });
106
+ addComponent({
107
+ name: "CmsRichText",
108
+ filePath: resolver.resolve("./runtime/app/CmsRichText")
53
109
  });
110
+ addPlugin({
111
+ src: resolver.resolve("./runtime/app/preview.client"),
112
+ mode: "client"
113
+ });
114
+ setupEditor(resolver.resolve("../dist/editor"), editorThemeHead(options.editor?.theme), nuxt);
54
115
  }
55
116
  });
117
+ /**
118
+ * The editor at `/_cms` is a prebuilt app in the package (`editor/`), not a page of the site: its
119
+ * Tailwind and Nuxt UI stay out of the site's pages, and it works whatever the site is built with.
120
+ * `../dist/editor` is the same folder from `src/` and from `dist/`.
121
+ */
122
+ function setupEditor(dir, themeHead, nuxt) {
123
+ const html = join(dir, "index.html");
124
+ if (!existsSync(html)) {
125
+ console.warn(`[@wervt/cms] No editor build in ${dir}; run \`vp build editor\` in packages/cms.`);
126
+ return;
127
+ }
128
+ nuxt.hook("nitro:config", (config) => {
129
+ const nitro = config;
130
+ nitro.publicAssets = [...nitro.publicAssets ?? [], {
131
+ dir: join(dir, "assets"),
132
+ baseURL: "/_cms/assets",
133
+ maxAge: 31536e3
134
+ }];
135
+ });
136
+ addServerTemplate({
137
+ filename: "#wervt-cms/editor",
138
+ getContents: () => `export const html = ${JSON.stringify(readFileSync(html, "utf8").replace("</head>", `${themeHead}\n</head>`))}\n`
139
+ });
140
+ addServerHandler({
141
+ route: "/_cms",
142
+ method: "get",
143
+ handler: createResolver(import.meta.url).resolve("./runtime/server/editor.get")
144
+ });
145
+ }
56
146
  export { module_default as default };
@@ -0,0 +1,15 @@
1
+ /** Renders a `richText` field: `<CmsRichText :value="home.intro" />`. */
2
+ declare const _default: import("vue").DefineComponent<import("vue").ExtractPropTypes<{
3
+ value: {
4
+ type: StringConstructor;
5
+ required: true;
6
+ };
7
+ }>, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
8
+ [key: string]: any;
9
+ }>, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<{
10
+ value: {
11
+ type: StringConstructor;
12
+ required: true;
13
+ };
14
+ }>> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
15
+ export { _default as default };
@@ -0,0 +1,48 @@
1
+ import { Markdown } from "@comark/vue";
2
+ import security from "comark/plugins/security";
3
+ import { defineComponent, h } from "vue";
4
+ // src/runtime/app/CmsRichText.ts
5
+ const options = { registerDefaultPlugins: false };
6
+ const plugins = [security({ allowedTags: [
7
+ "p",
8
+ "br",
9
+ "strong",
10
+ "em",
11
+ "del",
12
+ "s",
13
+ "code",
14
+ "pre",
15
+ "blockquote",
16
+ "hr",
17
+ "a",
18
+ "img",
19
+ "ul",
20
+ "ol",
21
+ "li",
22
+ "h1",
23
+ "h2",
24
+ "h3",
25
+ "h4",
26
+ "h5",
27
+ "h6",
28
+ "table",
29
+ "thead",
30
+ "tbody",
31
+ "tr",
32
+ "th",
33
+ "td"
34
+ ] })];
35
+ /** Renders a `richText` field: `<CmsRichText :value="home.intro" />`. */
36
+ var CmsRichText_default = defineComponent({
37
+ name: "CmsRichText",
38
+ props: { value: {
39
+ type: String,
40
+ required: true
41
+ } },
42
+ setup: (props) => () => h(Markdown, {
43
+ value: props.value,
44
+ options,
45
+ plugins
46
+ })
47
+ });
48
+ export { CmsRichText_default as default };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Values the editor shows in its preview before they are saved, by page key. Only written in the
3
+ * browser inside the editor's iframe, so the server's copy, shared by all requests, stays empty.
4
+ */
5
+ export declare const drafts: import("vue").ShallowRef<Record<string, Record<string, unknown>>, Record<string, Record<string, unknown>>>;
@@ -0,0 +1,8 @@
1
+ import { shallowRef } from "vue";
2
+ // src/runtime/app/drafts.ts
3
+ /**
4
+ * Values the editor shows in its preview before they are saved, by page key. Only written in the
5
+ * browser inside the editor's iframe, so the server's copy, shared by all requests, stays empty.
6
+ */
7
+ const drafts = shallowRef({});
8
+ export { drafts };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("#app").Plugin<Record<string, unknown>> & import("#app").ObjectPlugin<Record<string, unknown>>;
2
+ export { _default as default };
@@ -0,0 +1,28 @@
1
+ import { readMessage, siteMessage } from "../preview.js";
2
+ import { drafts } from "./drafts.js";
3
+ import { defineNuxtPlugin, useRouter } from "#app";
4
+ // src/runtime/app/preview.client.ts
5
+ var preview_client_default = defineNuxtPlugin((nuxtApp) => {
6
+ const parent = window.parent;
7
+ if (parent === window) return;
8
+ try {
9
+ if (parent.location.origin !== location.origin || !parent.location.pathname.startsWith("/_cms")) return;
10
+ } catch {
11
+ return;
12
+ }
13
+ const router = useRouter();
14
+ const report = (path) => parent.postMessage(siteMessage(path), location.origin);
15
+ addEventListener("message", (event) => {
16
+ const message = readMessage(event, parent, location.origin, "draft");
17
+ if (message) drafts.value = {
18
+ ...drafts.value,
19
+ [message.key]: message.value
20
+ };
21
+ });
22
+ nuxtApp.hook("app:mounted", () => report(router.currentRoute.value.fullPath));
23
+ router.afterEach((to) => {
24
+ if (nuxtApp.isHydrating) return;
25
+ report(to.fullPath);
26
+ });
27
+ });
28
+ export { preview_client_default as default };
@@ -1,2 +1,9 @@
1
- /** The entry's saved values over `defaults`, so a page renders fully before anything is saved. */
2
- export declare function useCms<T extends Record<string, unknown>>(key: string, defaults: T): import("vue").ComputedRef<T>;
1
+ import { CmsFields, CmsPages, CmsValue } from "../schema.js";
2
+ import { ComputedRef } from "vue";
3
+ /**
4
+ * The content of a page defined in `cms/*.ts`, typed from its fields. Values nobody edited yet
5
+ * come from the defaults there.
6
+ */
7
+ export declare function useCms<K extends Extract<keyof CmsPages, string>>(key: K): ComputedRef<CmsPages[K] extends CmsFields ? CmsValue<CmsPages[K]> : never>;
8
+ /** Content without a schema: what was saved, over `defaults`. */
9
+ export declare function useCms<T extends Record<string, unknown>>(key: string, defaults: T): ComputedRef<T>;
@@ -1,12 +1,19 @@
1
+ import { resolveValue, staticImages } from "../fields.js";
2
+ import { pages } from "../pages.js";
3
+ import { drafts } from "./drafts.js";
1
4
  import { computed } from "vue";
2
5
  import { useFetch } from "#app";
3
6
  // src/runtime/app/useCms.ts
4
- /** The entry's saved values over `defaults`, so a page renders fully before anything is saved. */
5
7
  function useCms(key, defaults) {
6
8
  const { data } = useFetch(`/api/_cms/entries/${key}`, { key: `wervt-cms:${key}` });
7
- return computed(() => ({
8
- ...defaults,
9
- ...data.value?.value
10
- }));
9
+ const page = pages.get(key);
10
+ return computed(() => {
11
+ const stored = drafts.value[key] ?? data.value?.value;
12
+ if (defaults) return {
13
+ ...defaults,
14
+ ...stored
15
+ };
16
+ return stored ?? (page ? resolveValue(page.fields, void 0, staticImages) : {});
17
+ });
11
18
  }
12
19
  export { useCms };
@@ -0,0 +1,24 @@
1
+ import { CmsField, CmsFields, CmsImage, StoredImage } from "./schema.js";
2
+ export declare function isField(value: CmsField | CmsFields): value is CmsField;
3
+ type Plain = Record<string, unknown>;
4
+ /** Turns a stored image into what the page shows; `undefined` when it can't be shown. */
5
+ export type ImageResolver = (image: StoredImage) => CmsImage | undefined;
6
+ /** Shows paths and URLs as they are; uploaded files need the server's resolver. */
7
+ export declare const staticImages: ImageResolver;
8
+ /**
9
+ * The value a page shows: what was stored where it fits the field, the default everywhere else.
10
+ * Stored values that don't fit (the field changed type since) fall back to the default instead
11
+ * of breaking the page. Keys the schema doesn't know are kept, so nothing an edit sent is lost
12
+ * when a field is renamed back.
13
+ */
14
+ export declare function resolveValue(fields: CmsFields, stored: unknown, images: ImageResolver): Plain;
15
+ export declare class InvalidValue extends Error {}
16
+ /**
17
+ * Checks an edit against the schema and brings it into the form it's stored in. Takes what GET
18
+ * answered as well, so the editor can send a value back unchanged: an image the page got as a
19
+ * signed URL is stored as its file again.
20
+ */
21
+ export declare function normalizeValue(fields: CmsFields, input: unknown, path?: string): Plain;
22
+ /** An edited `href` is put on the live site as is, so only harmless schemes get through. */
23
+ export declare function isSafeHref(href: string): boolean;
24
+ export {};
@@ -0,0 +1,109 @@
1
+ // src/runtime/fields.ts
2
+ function isField(value) {
3
+ return typeof value.type === "string";
4
+ }
5
+ const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
+ /** Shows paths and URLs as they are; uploaded files need the server's resolver. */
7
+ const staticImages = (image) => "src" in image ? {
8
+ src: image.src,
9
+ alt: image.alt ?? ""
10
+ } : void 0;
11
+ /**
12
+ * The value a page shows: what was stored where it fits the field, the default everywhere else.
13
+ * Stored values that don't fit (the field changed type since) fall back to the default instead
14
+ * of breaking the page. Keys the schema doesn't know are kept, so nothing an edit sent is lost
15
+ * when a field is renamed back.
16
+ */
17
+ function resolveValue(fields, stored, images) {
18
+ const value = isPlain(stored) ? { ...stored } : {};
19
+ for (const [name, field] of Object.entries(fields)) value[name] = isField(field) ? resolveField(field, value[name], images) : resolveValue(field, value[name], images);
20
+ return value;
21
+ }
22
+ function resolveField(field, stored, images) {
23
+ switch (field.type) {
24
+ case "text":
25
+ case "richText": return typeof stored === "string" ? stored : field.default;
26
+ case "toggle": return typeof stored === "boolean" ? stored : field.default;
27
+ case "link": return toLink(stored) ?? field.default;
28
+ case "image": {
29
+ const image = stored === null ? null : toImage(stored);
30
+ if (image === null && !field.required) return null;
31
+ const shown = image && images(image);
32
+ if (shown) return shown;
33
+ return field.default && (images(field.default) ?? null);
34
+ }
35
+ case "list": return (Array.isArray(stored) ? stored : field.default).map((item) => resolveValue(field.item, item, images));
36
+ }
37
+ }
38
+ var InvalidValue = class extends Error {};
39
+ /**
40
+ * Checks an edit against the schema and brings it into the form it's stored in. Takes what GET
41
+ * answered as well, so the editor can send a value back unchanged: an image the page got as a
42
+ * signed URL is stored as its file again.
43
+ */
44
+ function normalizeValue(fields, input, path = "") {
45
+ if (!isPlain(input)) throw new InvalidValue(`${path || "value"}: expected an object`);
46
+ const value = { ...input };
47
+ for (const [name, field] of Object.entries(fields)) {
48
+ if (!(name in input) || input[name] === void 0) continue;
49
+ const at = path ? `${path}.${name}` : name;
50
+ value[name] = isField(field) ? normalizeField(field, input[name], at) : normalizeValue(field, input[name], at);
51
+ }
52
+ return value;
53
+ }
54
+ const MAX_ITEMS = 500;
55
+ function normalizeField(field, input, at) {
56
+ switch (field.type) {
57
+ case "text":
58
+ case "richText":
59
+ if (typeof input !== "string") throw new InvalidValue(`${at}: expected text`);
60
+ return input;
61
+ case "toggle":
62
+ if (typeof input !== "boolean") throw new InvalidValue(`${at}: expected true or false`);
63
+ return input;
64
+ case "link": {
65
+ const value = toLink(input);
66
+ if (!value) throw new InvalidValue(`${at}: expected { label, href } with a safe href`);
67
+ return value;
68
+ }
69
+ case "image": {
70
+ if (input === null && !field.required) return null;
71
+ const value = toImage(input);
72
+ if (!value) throw new InvalidValue(`${at}: expected an uploaded image or a path`);
73
+ return value;
74
+ }
75
+ case "list":
76
+ if (!Array.isArray(input)) throw new InvalidValue(`${at}: expected a list`);
77
+ if (input.length > MAX_ITEMS) throw new InvalidValue(`${at}: at most ${MAX_ITEMS} items`);
78
+ return input.map((item, i) => normalizeValue(field.item, item, `${at}[${i}]`));
79
+ }
80
+ }
81
+ const SAFE_HREF = /^(?:\/(?!\/)|#|\?|https?:\/\/|mailto:|tel:)/i;
82
+ const SAFE_SRC = /^(?:\/(?!\/)|https:\/\/)/i;
83
+ const FILE_ID = /^[A-Za-z0-9_-]{1,100}$/;
84
+ /** An edited `href` is put on the live site as is, so only harmless schemes get through. */
85
+ function isSafeHref(href) {
86
+ return href === "" || SAFE_HREF.test(href);
87
+ }
88
+ function toLink(input) {
89
+ if (!isPlain(input) || typeof input.label !== "string" || typeof input.href !== "string") return void 0;
90
+ if (!isSafeHref(input.href.trim())) return void 0;
91
+ return {
92
+ label: input.label,
93
+ href: input.href.trim()
94
+ };
95
+ }
96
+ function toImage(input) {
97
+ if (typeof input === "string") input = { src: input };
98
+ if (!isPlain(input)) return void 0;
99
+ const alt = typeof input.alt === "string" && input.alt ? { alt: input.alt } : {};
100
+ if (typeof input.id === "string") return FILE_ID.test(input.id) ? {
101
+ id: input.id,
102
+ ...alt
103
+ } : void 0;
104
+ if (typeof input.src === "string" && SAFE_SRC.test(input.src)) return {
105
+ src: input.src,
106
+ ...alt
107
+ };
108
+ }
109
+ export { InvalidValue, isField, isSafeHref, normalizeValue, resolveValue, staticImages };
@@ -0,0 +1,3 @@
1
+ import { CmsFields, CmsPage } from "./schema.js";
2
+ /** The pages the app defines in `cms/*.ts`, by key. */
3
+ export declare const pages: Map<string, CmsPage<string, CmsFields>>;
@@ -0,0 +1,14 @@
1
+ import { isCmsPage } from "./schema.js";
2
+ import { modules } from "#wervt-cms/pages";
3
+ // src/runtime/pages.ts
4
+ function collect(found) {
5
+ const pages = /* @__PURE__ */ new Map();
6
+ for (const module of found) for (const value of Object.values(module)) if (isCmsPage(value)) {
7
+ if (pages.has(value.key) && pages.get(value.key) !== value) console.warn(`[cms] page \`${value.key}\` is defined twice in cms/, the last one counts`);
8
+ pages.set(value.key, value);
9
+ }
10
+ return pages;
11
+ }
12
+ /** The pages the app defines in `cms/*.ts`, by key. */
13
+ const pages = collect(modules);
14
+ export { pages };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The editor at `/_cms` shows the site in an iframe and sends it the values nobody saved yet. Both
3
+ * sides share one origin; these are the messages between them.
4
+ */
5
+ declare const source = "wervt-cms";
6
+ /** From the site in the iframe: it loaded or moved to `path`. */
7
+ export interface SiteMessage {
8
+ source: typeof source;
9
+ type: 'page';
10
+ path: string;
11
+ }
12
+ /** From the editor: show `value` for `key` until the next one. */
13
+ export interface EditorMessage {
14
+ source: typeof source;
15
+ type: 'draft';
16
+ key: string;
17
+ value: Record<string, unknown>;
18
+ }
19
+ export declare const siteMessage: (path: string) => SiteMessage;
20
+ /** Values are copied as JSON: `postMessage` refuses Vue's reactive proxies. */
21
+ export declare const editorMessage: (key: string, value: unknown) => EditorMessage;
22
+ /**
23
+ * The message's data if it came from `from` on this origin and has the expected shape. Anything
24
+ * else (other frames, browser extensions, other origins) is ignored.
25
+ */
26
+ export declare function readMessage<T extends SiteMessage | EditorMessage>(event: Pick<MessageEvent, 'data' | 'origin' | 'source'>, from: unknown, origin: string, type: T['type']): T | undefined;
27
+ /** `/menu/` and `/menu?x#y` are `/menu`. */
28
+ export declare const normalizePath: (path: string) => string;
29
+ /** The page whose `path` is where the site is. */
30
+ export declare const pageAt: <P extends {
31
+ key: string;
32
+ path?: string;
33
+ }>(pages: P[], path: string) => P | undefined;
34
+ export {};