@wervt/cms 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @wervt/cms
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Editable texts for Nuxt sites on [wervt](https://wervt.app). Pages read their texts with
4
+ `useCms`; the site's owner changes them on the live site, without a redeploy.
5
+
6
+ ```sh
7
+ pnpm add @wervt/cms @wervt/nuxt
8
+ ```
9
+
10
+ ```ts [nuxt.config.ts]
11
+ export default defineNuxtConfig({
12
+ modules: ['@wervt/cms'], // loads @wervt/nuxt with its database turned on
13
+ })
14
+ ```
15
+
16
+ ```vue [app/pages/index.vue]
17
+ <script setup lang="ts">
18
+ const home = useCms('home', { title: 'Welcome', hours: 'Mon–Fri 8–18' })
19
+ </script>
20
+
21
+ <template>
22
+ <h1>{{ home.title }}</h1>
23
+ <p>{{ home.hours }}</p>
24
+ </template>
25
+ ```
26
+
27
+ The defaults render until an entry is saved, so a page works before anyone edits it.
28
+
29
+ ## Where entries live
30
+
31
+ - **`nuxt dev`**: saving writes `cms/entries.json` in the app. Commit it; the deploy bundles it.
32
+ - **Deployed**: saving writes the app's database. The module turns the database on, so the app
33
+ needs no `drizzle/` folder for it; the table is created on first use.
34
+ - When both have an entry for a key, the newer one wins. Editing `cms/entries.json` and
35
+ deploying replaces a live edit; a later live edit wins again.
36
+
37
+ Keys are lowercase words joined by `-`, `_` or `/` (`home`, `menu/drinks`), up to 200
38
+ characters.
39
+
40
+ ## Editing
41
+
42
+ `/_cms?key=<key>` is a small editor for one entry. `GET` and `PUT /api/_cms/entries/<key>` are
43
+ the API behind it; reading is public, saving needs an editor.
44
+
45
+ The app's owner, members and wervt admins can edit. To let others edit, list their addresses
46
+ (only confirmed ones count):
47
+
48
+ ```ts [nuxt.config.ts]
49
+ export default defineNuxtConfig({
50
+ cms: { editors: 'anna@example.com,ben@example.com' },
51
+ })
52
+ ```
53
+
54
+ or set `NUXT_CMS_EDITORS` on the deployed app (`wervt env`), which needs no redeploy.
@@ -0,0 +1,9 @@
1
+ export interface ModuleOptions {
2
+ /**
3
+ * Signed-in people with a confirmed address who may edit besides the app's owner, members and
4
+ * admins. Set at runtime with `NUXT_CMS_EDITORS` (comma-separated), no redeploy needed.
5
+ */
6
+ editors?: string;
7
+ }
8
+ declare const _default: import("nuxt/schema").NuxtModule<ModuleOptions, ModuleOptions, false>;
9
+ export { _default as default };
package/dist/module.js ADDED
@@ -0,0 +1,56 @@
1
+ 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";
5
+ // src/module.ts
6
+ var module_default = defineNuxtModule({
7
+ meta: {
8
+ name: "@wervt/cms",
9
+ configKey: "cms"
10
+ },
11
+ moduleDependencies: { "@wervt/nuxt": { overrides: { database: true } } },
12
+ defaults: { editors: "" },
13
+ setup(options, nuxt) {
14
+ const resolver = createResolver(import.meta.url);
15
+ const config = nuxt.options.runtimeConfig;
16
+ config.cms = {
17
+ editors: options.editors ?? "",
18
+ ...config.cms
19
+ };
20
+ const file = join(nuxt.options.rootDir, "cms/entries.json");
21
+ addServerTemplate({
22
+ filename: "#wervt-cms/entries",
23
+ getContents: () => {
24
+ const entries = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
25
+ const stamped = stampEntries(entries, /* @__PURE__ */ new Date()).file;
26
+ return [
27
+ `export const entries = ${JSON.stringify(stamped)}`,
28
+ `export const file = ${nuxt.options.dev ? JSON.stringify(file) : "undefined"}`,
29
+ ""
30
+ ].join("\n");
31
+ }
32
+ });
33
+ addServerHandler({
34
+ route: "/api/_cms/entries/**:key",
35
+ method: "get",
36
+ handler: resolver.resolve("./runtime/server/entry.get")
37
+ });
38
+ addServerHandler({
39
+ route: "/api/_cms/entries/**:key",
40
+ method: "put",
41
+ handler: resolver.resolve("./runtime/server/entry.put")
42
+ });
43
+ addImports({
44
+ name: "useCms",
45
+ from: resolver.resolve("./runtime/app/useCms")
46
+ });
47
+ extendPages((pages) => {
48
+ pages.push({
49
+ name: "wervt-cms",
50
+ path: "/_cms",
51
+ file: resolver.resolve("./runtime/app/editor.vue")
52
+ });
53
+ });
54
+ }
55
+ });
56
+ export { module_default as default };
@@ -0,0 +1,32 @@
1
+ <script setup lang="ts">
2
+ import { ref, watch } from 'vue'
3
+ import { useFetch, useRoute } from '#app'
4
+
5
+ const key = String(useRoute().query.key ?? 'home')
6
+ const { data } = await useFetch<{ value: Record<string, unknown> } | null>(
7
+ `/api/_cms/entries/${key}`,
8
+ )
9
+ const text = ref('{}')
10
+ watch(data, (entry) => (text.value = JSON.stringify(entry?.value ?? {}, null, 2)), {
11
+ immediate: true,
12
+ })
13
+ const status = ref('')
14
+
15
+ async function save() {
16
+ try {
17
+ await $fetch(`/api/_cms/entries/${key}`, { method: 'PUT', body: JSON.parse(text.value) })
18
+ status.value = 'Saved'
19
+ } catch (e) {
20
+ status.value = (e as { data?: { message?: string } }).data?.message ?? String(e)
21
+ }
22
+ }
23
+ </script>
24
+
25
+ <template>
26
+ <main style="max-width: 40rem; margin: 2rem auto; font-family: system-ui">
27
+ <h1>Content: {{ key }}</h1>
28
+ <textarea v-model="text" rows="12" style="width: 100%; font-family: monospace" />
29
+ <button type="button" @click="save">Save</button>
30
+ <p data-testid="status">{{ status }}</p>
31
+ </main>
32
+ </template>
@@ -0,0 +1,2 @@
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>;
@@ -0,0 +1,12 @@
1
+ import { computed } from "vue";
2
+ import { useFetch } from "#app";
3
+ // src/runtime/app/useCms.ts
4
+ /** The entry's saved values over `defaults`, so a page renders fully before anything is saved. */
5
+ function useCms(key, defaults) {
6
+ const { data } = useFetch(`/api/_cms/entries/${key}`, { key: `wervt-cms:${key}` });
7
+ return computed(() => ({
8
+ ...defaults,
9
+ ...data.value?.value
10
+ }));
11
+ }
12
+ export { useCms };
@@ -0,0 +1,2 @@
1
+ import { RequestEvent } from "nuxt/server";
2
+ export declare function requireEditor(event: RequestEvent): import("@wervt/core").WervtUser;
@@ -0,0 +1,19 @@
1
+ import { useWervtUser } from "@wervt/nuxt/server";
2
+ import { createError, useRuntimeConfig } from "nuxt/server";
3
+ // src/runtime/server/access.ts
4
+ function requireEditor(event) {
5
+ const user = useWervtUser(event);
6
+ if (!user) throw createError({
7
+ status: 401,
8
+ message: "Sign in to edit"
9
+ });
10
+ if (user.role === "owner" || user.role === "member" || user.role === "admin" || user.admin) return user;
11
+ const config = useRuntimeConfig();
12
+ const editors = String(config.cms?.editors ?? "").split(",").map((email) => email.trim().toLowerCase()).filter(Boolean);
13
+ if (user.emailVerified && editors.includes(user.email.toLowerCase())) return user;
14
+ throw createError({
15
+ status: 403,
16
+ message: "Not allowed to edit"
17
+ });
18
+ }
19
+ export { requireEditor };
@@ -0,0 +1,27 @@
1
+ export interface CmsEntry {
2
+ key: string;
3
+ value: Record<string, unknown>;
4
+ /** ISO 8601. */
5
+ updatedAt: string;
6
+ }
7
+ /** `cms/entries.json`: entries by key. */
8
+ export type EntriesFile = Record<string, {
9
+ value: Record<string, unknown>;
10
+ updatedAt?: string;
11
+ }>;
12
+ /**
13
+ * The entry a page shows when both the app's `cms/entries.json` and its database have one: the
14
+ * one changed last. On a tie the database wins, since that is the edit made on the live site.
15
+ */
16
+ export declare function newerEntry(file: CmsEntry | undefined, db: CmsEntry | undefined): CmsEntry | undefined;
17
+ /**
18
+ * Gives entries without `updatedAt` the time `now`. An agent editing the file drops the field
19
+ * instead of keeping a clock, so a missing time means "just changed".
20
+ */
21
+ export declare function stampEntries(file: EntriesFile, now: Date): {
22
+ file: EntriesFile;
23
+ changed: boolean;
24
+ };
25
+ export declare function fileEntry(file: EntriesFile, key: string): CmsEntry | undefined;
26
+ /** Lowercase words joined by `-`, `_` or `/`, so a key is also safe as a property name. */
27
+ export declare function isEntryKey(key: string | undefined): key is string;
@@ -0,0 +1,44 @@
1
+ // src/runtime/server/entries.ts
2
+ /**
3
+ * The entry a page shows when both the app's `cms/entries.json` and its database have one: the
4
+ * one changed last. On a tie the database wins, since that is the edit made on the live site.
5
+ */
6
+ function newerEntry(file, db) {
7
+ if (!file || !db) return file ?? db;
8
+ return Date.parse(file.updatedAt) > Date.parse(db.updatedAt) ? file : db;
9
+ }
10
+ /**
11
+ * Gives entries without `updatedAt` the time `now`. An agent editing the file drops the field
12
+ * instead of keeping a clock, so a missing time means "just changed".
13
+ */
14
+ function stampEntries(file, now) {
15
+ let changed = false;
16
+ const stamped = {};
17
+ for (const [key, entry] of Object.entries(file)) if (entry.updatedAt) stamped[key] = entry;
18
+ else {
19
+ stamped[key] = {
20
+ ...entry,
21
+ updatedAt: now.toISOString()
22
+ };
23
+ changed = true;
24
+ }
25
+ return {
26
+ file: stamped,
27
+ changed
28
+ };
29
+ }
30
+ function fileEntry(file, key) {
31
+ const entry = Object.hasOwn(file, key) ? file[key] : void 0;
32
+ if (!entry?.updatedAt) return void 0;
33
+ return {
34
+ key,
35
+ value: entry.value,
36
+ updatedAt: entry.updatedAt
37
+ };
38
+ }
39
+ const KEY = /^[a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)*$/;
40
+ /** Lowercase words joined by `-`, `_` or `/`, so a key is also safe as a property name. */
41
+ function isEntryKey(key) {
42
+ return key !== void 0 && key.length <= 200 && KEY.test(key);
43
+ }
44
+ export { fileEntry, isEntryKey, newerEntry, stampEntries };
@@ -0,0 +1,3 @@
1
+ import { CmsEntry } from "./entries.js";
2
+ declare const _default: import("nuxt/server").EventHandler<Promise<CmsEntry | null>>;
3
+ export { _default as default };
@@ -0,0 +1,13 @@
1
+ import { isEntryKey } from "./entries.js";
2
+ import { readEntry } from "./store.js";
3
+ import { createError, defineEventHandler, getRouterParam } from "nuxt/server";
4
+ // src/runtime/server/entry.get.ts
5
+ var entry_get_default = defineEventHandler(async (event) => {
6
+ const key = getRouterParam(event, "key");
7
+ if (!isEntryKey(key)) throw createError({
8
+ status: 400,
9
+ message: "Invalid key"
10
+ });
11
+ return await readEntry(key) ?? null;
12
+ });
13
+ export { entry_get_default as default };
@@ -0,0 +1,4 @@
1
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
2
+ ok: boolean;
3
+ }>>;
4
+ export { _default as default };
@@ -0,0 +1,21 @@
1
+ import { isEntryKey } from "./entries.js";
2
+ import { requireEditor } from "./access.js";
3
+ import { writeEntry } from "./store.js";
4
+ import { createError, defineEventHandler, getRouterParam, readBody } from "nuxt/server";
5
+ // src/runtime/server/entry.put.ts
6
+ var entry_put_default = defineEventHandler(async (event) => {
7
+ requireEditor(event);
8
+ const key = getRouterParam(event, "key");
9
+ if (!isEntryKey(key)) throw createError({
10
+ status: 400,
11
+ message: "Invalid key"
12
+ });
13
+ const body = await readBody(event);
14
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw createError({
15
+ status: 400,
16
+ message: "Expected an object"
17
+ });
18
+ await writeEntry(key, body);
19
+ return { ok: true };
20
+ });
21
+ export { entry_put_default as default };
@@ -0,0 +1,3 @@
1
+ import { CmsEntry } from "./entries.js";
2
+ export declare function readFileEntry(path: string, key: string): Promise<CmsEntry | undefined>;
3
+ export declare function writeFileEntry(path: string, key: string, value: Record<string, unknown>): Promise<void>;
@@ -0,0 +1,43 @@
1
+ import { fileEntry, stampEntries } from "./entries.js";
2
+ import { dirname } from "node:path";
3
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
+ // src/runtime/server/file-store.ts
5
+ let queue = Promise.resolve();
6
+ function serialized(task) {
7
+ const run = queue.then(task, task);
8
+ queue = run.catch(() => {});
9
+ return run;
10
+ }
11
+ async function load(path) {
12
+ try {
13
+ return JSON.parse(await readFile(path, "utf8"));
14
+ } catch (error) {
15
+ if (error.code === "ENOENT") return {};
16
+ throw error;
17
+ }
18
+ }
19
+ async function save(path, file) {
20
+ const sorted = Object.fromEntries(Object.entries(file).sort(([a], [b]) => a.localeCompare(b)));
21
+ await mkdir(dirname(path), { recursive: true });
22
+ const temporary = `${path}.${process.pid}.tmp`;
23
+ await writeFile(temporary, `${JSON.stringify(sorted, null, 2)}\n`);
24
+ await rename(temporary, path);
25
+ }
26
+ function readFileEntry(path, key) {
27
+ return serialized(async () => {
28
+ const { file, changed } = stampEntries(await load(path), /* @__PURE__ */ new Date());
29
+ if (changed) await save(path, file);
30
+ return fileEntry(file, key);
31
+ });
32
+ }
33
+ function writeFileEntry(path, key, value) {
34
+ return serialized(async () => {
35
+ const file = await load(path);
36
+ file[key] = {
37
+ value,
38
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
39
+ };
40
+ await save(path, file);
41
+ });
42
+ }
43
+ export { readFileEntry, writeFileEntry };
@@ -0,0 +1,8 @@
1
+ import { CmsEntry } from "./entries.js";
2
+ /**
3
+ * Under `nuxt dev` the entry lives in the app's `cms/entries.json`, so edits made while
4
+ * building the app ship with it. Deployed, the file is what was built and the database holds
5
+ * the edits made on the live site; the one changed last wins.
6
+ */
7
+ export declare function readEntry(key: string): Promise<CmsEntry | undefined>;
8
+ export declare function writeEntry(key: string, value: Record<string, unknown>): Promise<void>;
@@ -0,0 +1,62 @@
1
+ import { fileEntry, newerEntry } from "./entries.js";
2
+ import { useDb } from "@wervt/nuxt/server";
3
+ import { eq, sql } from "drizzle-orm";
4
+ import { jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
5
+ import { entries, file } from "#wervt-cms/entries";
6
+ // src/runtime/server/store.ts
7
+ const entries$1 = pgTable("cms_entries", {
8
+ key: text().primaryKey(),
9
+ value: jsonb().$type().notNull(),
10
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
11
+ });
12
+ let ready;
13
+ function ensureTables() {
14
+ ready ??= useDb().execute(sql`create table if not exists cms_entries (
15
+ key text primary key,
16
+ value jsonb not null,
17
+ updated_at timestamptz not null default now()
18
+ )`).catch((e) => {
19
+ ready = void 0;
20
+ throw e;
21
+ });
22
+ return ready;
23
+ }
24
+ async function readDbEntry(key) {
25
+ await ensureTables();
26
+ const [row] = await useDb().select().from(entries$1).where(eq(entries$1.key, key));
27
+ return row && {
28
+ key: row.key,
29
+ value: row.value,
30
+ updatedAt: row.updatedAt.toISOString()
31
+ };
32
+ }
33
+ /**
34
+ * Under `nuxt dev` the entry lives in the app's `cms/entries.json`, so edits made while
35
+ * building the app ship with it. Deployed, the file is what was built and the database holds
36
+ * the edits made on the live site; the one changed last wins.
37
+ */
38
+ async function readEntry(key) {
39
+ if (import.meta.dev && file) {
40
+ const { readFileEntry } = await import("./file-store.js");
41
+ return readFileEntry(file, key);
42
+ }
43
+ return newerEntry(fileEntry(entries, key), await readDbEntry(key));
44
+ }
45
+ async function writeEntry(key, value) {
46
+ if (import.meta.dev && file) {
47
+ const { writeFileEntry } = await import("./file-store.js");
48
+ return writeFileEntry(file, key, value);
49
+ }
50
+ await ensureTables();
51
+ await useDb().insert(entries$1).values({
52
+ key,
53
+ value
54
+ }).onConflictDoUpdate({
55
+ target: entries$1.key,
56
+ set: {
57
+ value,
58
+ updatedAt: sql`now()`
59
+ }
60
+ });
61
+ }
62
+ export { readEntry, writeEntry };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@wervt/cms",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Editable texts for Nuxt sites on wervt: written to a file in dev, to the app's database once deployed.",
5
+ "keywords": [
6
+ "cms",
7
+ "nuxt",
8
+ "nuxt-module",
9
+ "wervt"
10
+ ],
11
+ "homepage": "https://wervt.app",
12
+ "license": "MIT",
13
+ "author": "Niki2k1",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/wervt-app/wervt.git",
17
+ "directory": "packages/cms"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/module.d.ts",
27
+ "default": "./dist/module.js"
28
+ }
29
+ },
30
+ "dependencies": {
31
+ "@wervt/nuxt": "^0.3.22"
32
+ },
33
+ "devDependencies": {
34
+ "drizzle-orm": "1.0.0-rc.5",
35
+ "nuxt": "npm:nuxt-nightly@5x",
36
+ "vue": "^3.5.45"
37
+ },
38
+ "peerDependencies": {
39
+ "drizzle-orm": ">=1.0.0-rc.5 <2",
40
+ "nuxt": ">=4.2"
41
+ },
42
+ "scripts": {
43
+ "build": "vp pack"
44
+ }
6
45
  }