create-spillway 0.1.21 → 0.1.23

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 (88) hide show
  1. package/README.md +11 -7
  2. package/dist/cli.d.ts +5 -1
  3. package/dist/cli.js +47 -4
  4. package/dist/cli.js.map +1 -1
  5. package/dist/index.d.ts +44 -5
  6. package/dist/index.js +109 -11
  7. package/dist/index.js.map +1 -1
  8. package/package.json +11 -7
  9. package/templates/astro/README.md +16 -3
  10. package/templates/astro/public/spillway-suggest.js +133 -0
  11. package/templates/astro/src/layouts/Layout.astro +21 -6
  12. package/templates/astro/src/lib/spillway.ts +88 -15
  13. package/templates/astro/src/pages/[...path].astro +58 -6
  14. package/templates/astro/src/pages/api/search/suggest.ts +16 -0
  15. package/templates/astro/src/styles/site.css +121 -0
  16. package/templates/next/README.md +19 -3
  17. package/templates/next/app/[[...slug]]/page.tsx +7 -4
  18. package/templates/next/app/api/search/suggest/route.ts +18 -0
  19. package/templates/next/app/globals.css +121 -0
  20. package/templates/next/app/layout.tsx +11 -21
  21. package/templates/next/app/not-found.tsx +11 -6
  22. package/templates/next/app/search/page.tsx +29 -0
  23. package/templates/next/components/LanguageSwitcher.tsx +19 -0
  24. package/templates/next/components/SearchPage.tsx +67 -0
  25. package/templates/next/components/SiteShell.tsx +38 -0
  26. package/templates/next/lib/spillway.ts +49 -1
  27. package/templates/next/next.config.ts +2 -1
  28. package/templates/next/public/spillway-suggest.js +133 -0
  29. package/templates/nuxt/.env.example +27 -0
  30. package/templates/nuxt/README.md +75 -0
  31. package/templates/nuxt/_gitignore +15 -0
  32. package/templates/nuxt/app/app.vue +3 -0
  33. package/templates/nuxt/app/assets/site.css +217 -0
  34. package/templates/nuxt/app/assets/spillway-brand.css +1 -0
  35. package/templates/nuxt/app/assets/spillway-brand.json +3 -0
  36. package/templates/nuxt/app/components/SearchPage.vue +36 -0
  37. package/templates/nuxt/app/components/SiteShell.vue +30 -0
  38. package/templates/nuxt/app/components/SpillwayMenu.vue +15 -0
  39. package/templates/nuxt/app/pages/[...slug].vue +54 -0
  40. package/templates/nuxt/nuxt.config.ts +18 -0
  41. package/templates/nuxt/package.json +32 -0
  42. package/templates/nuxt/public/spillway-suggest.js +133 -0
  43. package/templates/nuxt/scripts/brand.mjs +40 -0
  44. package/templates/nuxt/server/api/_spillway/view.get.ts +14 -0
  45. package/templates/nuxt/server/api/preview/exit.ts +13 -0
  46. package/templates/nuxt/server/api/preview/index.get.ts +31 -0
  47. package/templates/nuxt/server/api/revalidate.post.ts +45 -0
  48. package/templates/nuxt/server/api/search/suggest.get.ts +17 -0
  49. package/templates/nuxt/server/middleware/redirects.ts +17 -0
  50. package/templates/nuxt/server/routes/robots.txt.ts +7 -0
  51. package/templates/nuxt/server/routes/sitemap.xml.ts +18 -0
  52. package/templates/nuxt/server/utils/cache.ts +52 -0
  53. package/templates/nuxt/server/utils/preview.ts +6 -0
  54. package/templates/nuxt/server/utils/spillway.ts +211 -0
  55. package/templates/nuxt/shared/spillway.ts +60 -0
  56. package/templates/nuxt/tsconfig.json +9 -0
  57. package/templates/sveltekit/.env.example +27 -0
  58. package/templates/sveltekit/README.md +75 -0
  59. package/templates/sveltekit/_gitignore +11 -0
  60. package/templates/sveltekit/package.json +34 -0
  61. package/templates/sveltekit/scripts/brand.mjs +40 -0
  62. package/templates/sveltekit/src/app.d.ts +14 -0
  63. package/templates/sveltekit/src/app.html +11 -0
  64. package/templates/sveltekit/src/env.ts +20 -0
  65. package/templates/sveltekit/src/hooks.server.ts +26 -0
  66. package/templates/sveltekit/src/lib/components/SearchPage.svelte +41 -0
  67. package/templates/sveltekit/src/lib/components/SiteShell.svelte +36 -0
  68. package/templates/sveltekit/src/lib/components/SpillwayMenu.svelte +18 -0
  69. package/templates/sveltekit/src/lib/server/cache.ts +54 -0
  70. package/templates/sveltekit/src/lib/server/preview.ts +6 -0
  71. package/templates/sveltekit/src/lib/server/spillway.ts +203 -0
  72. package/templates/sveltekit/src/lib/site.css +204 -0
  73. package/templates/sveltekit/src/lib/spillway-brand.css +1 -0
  74. package/templates/sveltekit/src/lib/spillway-brand.json +3 -0
  75. package/templates/sveltekit/src/lib/view.ts +60 -0
  76. package/templates/sveltekit/src/routes/+layout.server.ts +4 -0
  77. package/templates/sveltekit/src/routes/+layout.svelte +8 -0
  78. package/templates/sveltekit/src/routes/[...path]/+page.server.ts +15 -0
  79. package/templates/sveltekit/src/routes/[...path]/+page.svelte +54 -0
  80. package/templates/sveltekit/src/routes/api/preview/+server.ts +30 -0
  81. package/templates/sveltekit/src/routes/api/preview/exit/+server.ts +10 -0
  82. package/templates/sveltekit/src/routes/api/revalidate/+server.ts +45 -0
  83. package/templates/sveltekit/src/routes/api/search/suggest/+server.ts +16 -0
  84. package/templates/sveltekit/src/routes/robots.txt/+server.ts +6 -0
  85. package/templates/sveltekit/src/routes/sitemap.xml/+server.ts +19 -0
  86. package/templates/sveltekit/static/spillway-suggest.js +133 -0
  87. package/templates/sveltekit/tsconfig.json +8 -0
  88. package/templates/sveltekit/vite.config.ts +17 -0
@@ -0,0 +1,40 @@
1
+ // Writes the Spillway site's published brand (GET /api/public/brand) into the project with @spillway-cms/brand: the
2
+ // stylesheet with the --sw-* variables and fonts, and its version (the layout compares it with the live brand).
3
+ // Runs before every build (prebuild) and by hand with `npm run brand`. When Spillway cannot be reached it keeps the files
4
+ // it has, so a build never fails for it.
5
+ //
6
+ // Using Tailwind v4? Write brandStylesheet(brand, { tailwind: 'v4' }) below and import this file after
7
+ // @import "tailwindcss"; then bg-primary, text-primary-700, font-heading and rounded-brand follow the brand.
8
+ import fs from 'node:fs';
9
+ import { brandStylesheet, fetchBrand } from '@spillway-cms/brand';
10
+
11
+ const CSS = 'app/assets/spillway-brand.css';
12
+ const JSON_FILE = 'app/assets/spillway-brand.json';
13
+
14
+ for (const file of ['.env']) {
15
+ try {
16
+ process.loadEnvFile(file); // never overrides a variable that is already set
17
+ } catch {
18
+ // no such file
19
+ }
20
+ }
21
+
22
+ const url = process.env.SPILLWAY_URL;
23
+ if (!url) {
24
+ console.warn(`[brand] SPILLWAY_URL is not set; keeping ${CSS}`);
25
+ } else {
26
+ try {
27
+ const site = process.env.SPILLWAY_SITE ? { site: process.env.SPILLWAY_SITE, token: process.env.SPILLWAY_TOKEN } : {};
28
+ const brand = await fetchBrand(url, { ...site, requestInit: { signal: AbortSignal.timeout(15_000) } });
29
+ const css = brandStylesheet(brand);
30
+ if (fs.existsSync(CSS) && fs.readFileSync(CSS, 'utf8') === css) {
31
+ console.log(`[brand] version ${brand.version} unchanged`);
32
+ } else {
33
+ fs.writeFileSync(CSS, css);
34
+ fs.writeFileSync(JSON_FILE, JSON.stringify({ version: brand.version }, null, 2) + '\n');
35
+ console.log(`[brand] version ${brand.version} written to ${CSS}`);
36
+ }
37
+ } catch (err) {
38
+ console.warn(`[brand] could not fetch the brand from ${url} (${err instanceof Error ? err.message : err}); keeping ${CSS}`);
39
+ }
40
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * GET /api/_spillway/view?_path=/about&...: what the page at `_path` shows (server/utils/spillway.ts, `resolveView`).
3
+ * app/pages/[...slug].vue reads it while it renders on the server; the preview cookie comes along with the request.
4
+ */
5
+ import { resolveView } from '../../utils/spillway';
6
+
7
+ export default defineEventHandler(async (event) => {
8
+ const { _path, ...rest } = getQuery(event);
9
+ const query: Record<string, string> = {};
10
+ for (const [key, value] of Object.entries(rest)) if (typeof value === 'string') query[key] = value;
11
+ const path = typeof _path === 'string' && _path.startsWith('/') ? _path : '/';
12
+ setResponseHeader(event, 'cache-control', 'private, no-store');
13
+ return resolveView(path, query, toWebRequest(event));
14
+ });
@@ -0,0 +1,13 @@
1
+ import { safeRedirectUrl } from '@spillway-cms/client';
2
+ import { previewCookie } from '../../utils/preview';
3
+
4
+ /**
5
+ * /api/preview/exit: ends the preview and goes back to the live home page. The preview bar posts to it: Nuxt lets
6
+ * browsers prerender links on hover (speculation rules), and a link here would end the preview before anyone clicked.
7
+ */
8
+ export default defineEventHandler((event) => {
9
+ const url = getRequestURL(event);
10
+ const headers = new Headers({ location: safeRedirectUrl('/', url.origin).href, 'cache-control': 'no-store' });
11
+ headers.append('set-cookie', previewCookie('', url.protocol === 'https:', 0));
12
+ return new Response(null, { status: 303, headers });
13
+ });
@@ -0,0 +1,31 @@
1
+ /**
2
+ * GET /api/preview: starts a preview and shows a page as it will be.
3
+ *
4
+ * - A release share link: /api/preview?path=/about&release=<release id>&token=<share token>. Spillway checks the token;
5
+ * the editor shares the link from the release in the admin.
6
+ * - The latest drafts through this front end's token: /api/preview?path=/about&preview=1&secret=<SPILLWAY_PREVIEW_SECRET>.
7
+ * Needs SPILLWAY_TOKEN with content.view_drafts.
8
+ *
9
+ * It sets the preview cookie (a draft preview's is signed with SPILLWAY_PREVIEW_SECRET and lasts an hour, so a cookie
10
+ * written by hand opens nothing) and opens the page on this site, never another one; /api/preview/exit removes it.
11
+ */
12
+ import { PREVIEW_MAX_AGE, SpillwayError, checkPreviewRequest, previewCookieValue, safeRedirectUrl } from '@spillway-cms/client';
13
+ import { previewCookie } from '../../utils/preview';
14
+ import { spillway } from '../../utils/spillway';
15
+
16
+ export default defineEventHandler(async (event) => {
17
+ const request = toWebRequest(event);
18
+ const url = new URL(request.url);
19
+ const secret = spillway.options.previewSecret;
20
+ const check = checkPreviewRequest(request, { secret });
21
+ if (!check.ok) return Response.json({ error: check.error }, { status: check.status });
22
+ try {
23
+ await spillway.withPreview(check.state).render(check.path);
24
+ } catch (err) {
25
+ if (err instanceof SpillwayError && (err.status === 401 || err.status === 403)) return Response.json({ error: 'Preview credential refused' }, { status: 401 });
26
+ if (!(err instanceof SpillwayError && err.status === 404)) throw err; // a missing page still opens the preview
27
+ }
28
+ const headers = new Headers({ location: safeRedirectUrl(check.path, url.origin).href, 'cache-control': 'no-store' });
29
+ headers.append('set-cookie', previewCookie(previewCookieValue(check.state, { secret }), url.protocol === 'https:', secret ? PREVIEW_MAX_AGE : undefined));
30
+ return new Response(null, { status: 307, headers });
31
+ });
@@ -0,0 +1,45 @@
1
+ /**
2
+ * POST /api/revalidate: the target of the webhook rules in Spillway (Site settings → Notifications). Point one rule per
3
+ * event at it (entity.published, entity.unpublished, entity.deleted, menu.updated, redirects.updated, site.updated,
4
+ * brand.published) with the secret SPILLWAY_WEBHOOK_SECRET; create-spillway adds them when you give it a token.
5
+ *
6
+ * readWebhook checks the X-Spillway-Signature HMAC over the raw body (401 when it does not match); a test send is
7
+ * acknowledged and changes nothing. affectedByWebhook finds what the event touched (the page's path and Spillway's cache
8
+ * tags), and those pages leave the cache, with the site settings, brand, menus and redirects.
9
+ */
10
+ import { WebhookError, affectedByWebhook, readWebhook, type WebhookPayload } from '@spillway-cms/client/webhook';
11
+ import { purge } from '../utils/cache';
12
+ import { SHELL_TAG } from '../utils/spillway';
13
+
14
+ export default defineEventHandler(async (event) => {
15
+ const secret = process.env.SPILLWAY_WEBHOOK_SECRET;
16
+ if (!secret) return Response.json({ error: 'SPILLWAY_WEBHOOK_SECRET is not set' }, { status: 503 });
17
+ let payload: WebhookPayload;
18
+ try {
19
+ payload = await readWebhook(toWebRequest(event), secret);
20
+ } catch (err) {
21
+ if (err instanceof WebhookError) return Response.json({ error: err.message }, { status: err.status });
22
+ throw err;
23
+ }
24
+ const affected = affectedByWebhook(payload);
25
+ if (affected.test) return { ok: true, test: true };
26
+ const dropped = purge([...affected.tags, SHELL_TAG], affected.paths);
27
+ console.log(`[spillway] ${payload.event}: purged ${dropped} cached entries (paths ${affected.paths.join(', ') || '-'})`);
28
+ if (payload.event === 'brand.published') await rebuildForBrand(payload);
29
+ return { ok: true, event: payload.event, paths: affected.paths, tags: affected.tags };
30
+ });
31
+
32
+ /**
33
+ * Pages show a newly published brand at once (the view inlines it); a deploy hook makes the next build write it into
34
+ * app/assets/spillway-brand.css as well. Optional: set DEPLOY_HOOK_URL to your host's deploy hook.
35
+ */
36
+ async function rebuildForBrand(payload: WebhookPayload): Promise<void> {
37
+ const hook = process.env.DEPLOY_HOOK_URL;
38
+ if (!hook) return;
39
+ try {
40
+ const res = await fetch(hook, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ source: 'spillway', event: payload.event, at: payload.at }) });
41
+ if (!res.ok) console.warn(`[spillway] the deploy hook answered ${res.status}`);
42
+ } catch (err) {
43
+ console.warn(`[spillway] the deploy hook failed: ${err instanceof Error ? err.message : String(err)}`);
44
+ }
45
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * GET /api/search/suggest?q=&locale=: up to six published pages for what a visitor has typed, for the suggestions under
3
+ * search fields (public/spillway-suggest.js). Read as a visitor, so drafts never show.
4
+ */
5
+ import { visitor } from '../../utils/spillway';
6
+
7
+ export default defineEventHandler(async (event) => {
8
+ const { q, locale } = getQuery(event);
9
+ const text = typeof q === 'string' ? q.slice(0, 100) : '';
10
+ try {
11
+ const found = await visitor.suggest(text, typeof locale === 'string' && locale ? { locale } : {});
12
+ setResponseHeader(event, 'cache-control', 'public, max-age=60');
13
+ return found;
14
+ } catch {
15
+ return { q: text, items: [] };
16
+ }
17
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Spillway's redirects (Marketing → Redirects) answered before any page, as on a Spillway-rendered site: 301 or 302 to
3
+ * the target, with the query string kept. The list is cached and purged by the redirects.updated webhook.
4
+ */
5
+ import { redirectFor } from '../utils/spillway';
6
+
7
+ const SKIP = ['/api/', '/_nuxt/', '/__nuxt', '/_ipx/'];
8
+
9
+ export default defineEventHandler(async (event) => {
10
+ if (event.method !== 'GET' && event.method !== 'HEAD') return;
11
+ const { pathname, search } = getRequestURL(event);
12
+ if (SKIP.some((p) => pathname.startsWith(p))) return;
13
+ const hit = await redirectFor(pathname);
14
+ if (!hit) return;
15
+ setResponseHeader(event, 'cache-control', 'no-store');
16
+ return sendRedirect(event, search && !hit.to.includes('?') ? `${hit.to}${search}` : hit.to, hit.status);
17
+ });
@@ -0,0 +1,7 @@
1
+ import { SITE_URL } from '../utils/spillway';
2
+
3
+ /** /robots.txt: everything may be crawled except the API routes; the sitemap is on this front end's address. */
4
+ export default defineEventHandler((event) => {
5
+ setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8');
6
+ return `User-agent: *\nAllow: /\nDisallow: /api/\n\nSitemap: ${SITE_URL}/sitemap.xml\n`;
7
+ });
@@ -0,0 +1,18 @@
1
+ import type { PublicPath } from '@spillway-cms/client';
2
+ import { cached } from '../utils/cache';
3
+ import { SHELL_TAG, SITE_URL, spillway } from '../utils/spillway';
4
+
5
+ const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
6
+
7
+ /** /sitemap.xml from every published path in Spillway, on this front end's address. */
8
+ export default defineEventHandler(async (event) => {
9
+ let paths: PublicPath[] = [];
10
+ try {
11
+ paths = await cached('paths', async () => ({ value: await spillway.paths(), tags: [SHELL_TAG] }));
12
+ } catch {
13
+ // Spillway is not reachable: an empty sitemap rather than an error
14
+ }
15
+ const urls = paths.map((p) => ` <url><loc>${esc(`${SITE_URL}${p.path === '/' ? '' : p.path}`)}</loc><lastmod>${esc(p.updatedAt)}</lastmod></url>`);
16
+ setResponseHeader(event, 'content-type', 'application/xml; charset=utf-8');
17
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('\n')}\n</urlset>\n`;
18
+ });
@@ -0,0 +1,52 @@
1
+ /**
2
+ * A small in-memory cache for what the site reads from Spillway, keyed by name and tagged with Spillway's cache tags
3
+ * (`entity:<id>`, `type:page`, `site:<id>`, `menu:main`, ...) and the page's path. src/pages/api/revalidate.ts purges it
4
+ * when a webhook says something changed; entries also expire after SPILLWAY_CACHE_SECONDS (300 by default, 0 turns the
5
+ * cache off) so a missed webhook heals itself.
6
+ *
7
+ * It lives in this server process. With more than one instance, or a CDN in front, purge those from the webhook too
8
+ * (`affected.tags` carries the tags Spillway sends in its Cache-Tag header).
9
+ */
10
+ interface Entry {
11
+ value: unknown;
12
+ tags: Set<string>;
13
+ expires: number;
14
+ }
15
+
16
+ const store = new Map<string, Entry>();
17
+
18
+ function ttlMs(): number {
19
+ const raw = Number(process.env.SPILLWAY_CACHE_SECONDS ?? 300);
20
+ return Number.isFinite(raw) && raw > 0 ? raw * 1000 : 0;
21
+ }
22
+
23
+ /**
24
+ * The cached value under `key`, or what `load` answers, stored with its tags unless `keep` is false. Errors are never
25
+ * cached.
26
+ */
27
+ export async function cached<T>(key: string, load: () => Promise<{ value: T; tags: string[]; keep?: boolean }>): Promise<T> {
28
+ const ttl = ttlMs();
29
+ const hit = store.get(key);
30
+ if (hit && hit.expires > Date.now()) return hit.value as T;
31
+ const { value, tags, keep = true } = await load();
32
+ if (ttl > 0 && keep) store.set(key, { value, tags: new Set(tags), expires: Date.now() + ttl });
33
+ return value;
34
+ }
35
+
36
+ /** Drops every entry carrying one of `tags` or tagged with one of `paths` (as `path:<path>`). Returns how many went. */
37
+ export function purge(tags: string[], paths: string[] = []): number {
38
+ const wanted = new Set([...tags, ...paths.map((p) => `path:${p}`)]);
39
+ let dropped = 0;
40
+ for (const [key, entry] of store) {
41
+ if ([...entry.tags].some((t) => wanted.has(t))) {
42
+ store.delete(key);
43
+ dropped += 1;
44
+ }
45
+ }
46
+ return dropped;
47
+ }
48
+
49
+ /** Empties the cache. */
50
+ export function purgeAll(): void {
51
+ store.clear();
52
+ }
@@ -0,0 +1,6 @@
1
+ import { PREVIEW_COOKIE } from '@spillway-cms/client';
2
+
3
+ /** The Set-Cookie value for the preview cookie: this site only, never readable by scripts. */
4
+ export function previewCookie(value: string, secure: boolean, maxAge?: number): string {
5
+ return [`${PREVIEW_COOKIE}=${encodeURIComponent(value)}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', ...(secure ? ['Secure'] : []), ...(maxAge !== undefined ? [`Max-Age=${maxAge}`] : [])].join('; ');
6
+ }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Everything this front end reads from Spillway, on the server only: the client (with SPILLWAY_TOKEN, which never reaches a
3
+ * browser), the in-memory cache in ./cache.ts, and `resolveView`, which turns a request into what a page shows: a
4
+ * Spillway page with its block area rendered by Spillway (the HTML render), the search page, or a 404, with the shell
5
+ * around it (the site name, menus, language switcher, brand and preview bar). The Vue pages only lay that out.
6
+ */
7
+ import {
8
+ SpillwayError,
9
+ createClient,
10
+ languageLinks,
11
+ localizedPath,
12
+ previewFromRequest,
13
+ splitLocalePath,
14
+ type PreviewState,
15
+ type PublicRedirect,
16
+ type PublicRender,
17
+ type PublicSite,
18
+ } from '@spillway-cms/client';
19
+ import type { HeadData, SearchHit, SearchView, Shell, View } from '../../shared/spillway';
20
+ // The brand as the last build wrote it (scripts/brand.mjs); a newer published brand is inlined until the next build.
21
+ import builtBrand from '../../app/assets/spillway-brand.json';
22
+ import { cached } from './cache';
23
+
24
+ /** The Spillway site (SPILLWAY_URL in .env). */
25
+ export const SPILLWAY_URL = (process.env.SPILLWAY_URL || 'http://localhost:3000').replace(/\/+$/, '');
26
+
27
+ /** This front end's own address, for canonical links, the sitemap and robots.txt. */
28
+ export const SITE_URL = (process.env.SITE_URL || 'http://localhost:3002').replace(/\/+$/, '');
29
+
30
+ /** Tag of the entries every webhook purges: the site settings, the brand, the menus, the redirects and the path list. */
31
+ export const SHELL_TAG = 'shell';
32
+
33
+ /** The server-side client. The preview secret checks /api/preview and signs the draft preview cookie. */
34
+ export const spillway = createClient({
35
+ baseUrl: SPILLWAY_URL,
36
+ token: process.env.SPILLWAY_TOKEN || undefined,
37
+ site: process.env.SPILLWAY_SITE || undefined,
38
+ previewSecret: process.env.SPILLWAY_PREVIEW_SECRET || undefined,
39
+ });
40
+
41
+ /** Search and suggestions read as a visitor: without the token, which would also find drafts. */
42
+ export const visitor = spillway.with({ token: undefined, site: undefined });
43
+
44
+ /** The preview this request is in, from the cookie /api/preview set; null for a visitor. */
45
+ export function readPreview(request: Request): PreviewState | null {
46
+ return previewFromRequest(request, { secret: spillway.options.previewSecret });
47
+ }
48
+
49
+ // ---------- What a page shows (the types are in shared/spillway.ts) ----------
50
+
51
+ /** A page with its block area rendered by Spillway (`client.renderHtml`). */
52
+ export type HtmlPage = PublicRender & { html: NonNullable<PublicRender['html']> };
53
+
54
+ /** Query parameters that open a preview rather than reach the page's blocks. */
55
+ const PREVIEW_PARAMS = new Set(['release', 'workstream', 'token', 'preview', 'secret']);
56
+
57
+ /** The site settings (name, locales, search), cached; null when Spillway does not answer. */
58
+ export function loadSite(preview: PreviewState | null = null): Promise<PublicSite | null> {
59
+ const load = () => spillway.withPreview(preview).site();
60
+ return (preview ? load() : cached('site', async () => ({ value: await load(), tags: [SHELL_TAG] }))).catch(() => null);
61
+ }
62
+
63
+ /** The page at `path`, or null when Spillway has none. A preview skips the cache; so does a page whose blocks read the query. */
64
+ export async function loadPage(path: string, query: Record<string, string>, preview: PreviewState | null): Promise<HtmlPage | null> {
65
+ const fetchPage = async (params: Record<string, string>) => {
66
+ try {
67
+ return await spillway.renderHtml(path, { previewState: preview, params });
68
+ } catch (err) {
69
+ // Not found, or members-only (signing members in on this front end is still to come; see README.md, Members).
70
+ if (err instanceof SpillwayError && (err.status === 404 || err.code === 'members_only')) return null;
71
+ throw err;
72
+ }
73
+ };
74
+ if (preview) return fetchPage(query);
75
+ const page = await cached(`render:${path}`, async () => {
76
+ const value = await fetchPage({});
77
+ // A 404 is not kept: the page may be published any moment.
78
+ return { value, tags: value ? [...value.cacheTags, `path:${path}`] : [], keep: value !== null };
79
+ });
80
+ // Exposed filters, a pager or a calendar read the query string: render this request on its own (Spillway caches it briefly).
81
+ return page?.queryDependent && Object.keys(query).length ? fetchPage(query) : page;
82
+ }
83
+
84
+ async function loadShellParts(locale: string, preview: PreviewState | null) {
85
+ const c = spillway.withPreview(preview);
86
+ const read = <T>(key: string, load: () => Promise<T>): Promise<T | null> =>
87
+ (preview ? load() : cached(key, async () => ({ value: await load(), tags: [SHELL_TAG] }))).catch(() => null);
88
+ const [brand, main, footer] = await Promise.all([
89
+ read('brand', () => c.brand()),
90
+ read(`menu:main:${locale}`, () => c.menu('main', { locale })),
91
+ read(`menu:footer:${locale}`, () => c.menu('footer', { locale })),
92
+ ]);
93
+ return { brand, main: main?.items ?? [], footer: footer?.items ?? [] };
94
+ }
95
+
96
+ /** A URL on the Spillway site rewritten onto this front end (canonical links and alternates name Spillway's pages). */
97
+ export function onSite(href: string | undefined, origin: string): string | undefined {
98
+ if (!href || !origin) return href;
99
+ return href === origin || href.startsWith(`${origin}/`) ? SITE_URL + href.slice(origin.length) : href;
100
+ }
101
+
102
+ /** Spillway marks the matched words in a search snippet «like this»; the parts, for a <mark> around each match. */
103
+ export function snippetParts(snippet: string): SearchHit['snippet'] {
104
+ const parts: SearchHit['snippet'] = [];
105
+ for (const [i, text] of snippet.split(/[«»]/).entries()) if (text) parts.push({ text, hit: i % 2 === 1 });
106
+ return parts;
107
+ }
108
+
109
+ const jsonLd = (value: unknown) => JSON.stringify(value).replace(/</g, '\\u003c');
110
+
111
+ /**
112
+ * Spillway's HTML with the form posts and downloads pointed at Spillway itself: the Form block posts to
113
+ * /api/forms/<key>/submit and the Collection block links its downloads under /api/collections/, which live on Spillway
114
+ * (the form endpoint accepts posts from other origins). Media URLs are already absolute.
115
+ */
116
+ export function pointApiAtSpillway(html: string, origin: string): string {
117
+ return origin ? html.replace(/ action="\/api\/forms\//g, ` action="${origin}/api/forms/`).replace(/ href="\/api\/collections\//g, ` href="${origin}/api/collections/`) : html;
118
+ }
119
+
120
+ /** What the request at `path` (with its query string) shows. */
121
+ export async function resolveView(path: string, query: Record<string, string>, request: Request): Promise<View> {
122
+ const preview = readPreview(request);
123
+ const params = Object.fromEntries(Object.entries(query).filter(([k]) => !PREVIEW_PARAMS.has(k)));
124
+ const site = await loadSite(preview);
125
+ const local = site ? splitLocalePath(site, path) : { locale: 'en', path, prefixed: false };
126
+ const isSearch = local.path === '/search';
127
+ const page = isSearch ? null : await loadPage(path, params, preview);
128
+ const locale = page?.locale ?? local.locale;
129
+ const parts = await loadShellParts(locale, preview);
130
+ const siteName = site?.name ?? page?.site.name ?? 'Spillway site';
131
+ const searchPath = site ? localizedPath(site, locale, '/search') : '/search';
132
+ const shell: Shell = {
133
+ siteName,
134
+ footerNote: site?.footerNote?.split('\n').filter(Boolean) ?? [],
135
+ lang: locale,
136
+ main: page?.menus.main ?? parts.main,
137
+ footer: page?.menus.footer ?? parts.footer,
138
+ languages: [],
139
+ brandCss: parts.brand && parts.brand.version !== builtBrand.version ? parts.brand.css : null,
140
+ suggestions: site?.searchSuggestions ?? true,
141
+ searchPath,
142
+ preview: Boolean(preview),
143
+ };
144
+
145
+ if (page) {
146
+ const origin = page.site.origin;
147
+ shell.languages = site ? languageLinks(site, { locale: page.locale, path: page.path, alternates: page.seo.alternates }) : [];
148
+ const head: HeadData = {
149
+ title: page.seo.title,
150
+ ...(page.seo.description ? { description: page.seo.description } : {}),
151
+ ...(page.seo.canonical ? { canonical: onSite(page.seo.canonical, origin) } : {}),
152
+ alternates: page.seo.alternates.map((a) => ({ hreflang: a.hreflang, href: onSite(a.href, origin) ?? a.href })),
153
+ ...(page.seo.ogImage ? { ogImage: page.seo.ogImage } : {}),
154
+ noindex: page.seo.noindex,
155
+ jsonLd: page.seo.jsonLd.map(jsonLd),
156
+ css: [page.html.css.theme, page.html.css.blocks, page.html.css.styles].filter(Boolean),
157
+ motion: page.html.motion,
158
+ };
159
+ return { kind: 'page', shell, head, body: pointApiAtSpillway(page.html.body, origin), scripts: page.html.scripts };
160
+ }
161
+
162
+ const head: HeadData = { title: siteName, alternates: [], noindex: true, jsonLd: [], css: site?.themeCss ? [site.themeCss] : [], motion: null };
163
+ if (isSearch) {
164
+ const q = (query.q ?? '').trim().slice(0, 200);
165
+ const pageNo = Math.max(1, Math.min(100, Number.parseInt(query.page ?? '1', 10) || 1));
166
+ shell.languages = site ? languageLinks(site, { locale, alternates: [] }).map((l) => ({ ...l, href: `${localizedPath(site, l.locale, '/search')}${q ? `?q=${encodeURIComponent(q)}` : ''}`, translated: true })) : [];
167
+ const search: SearchView = { q, page: pageNo, pages: 0, total: 0, results: [] };
168
+ if (q) {
169
+ try {
170
+ const found = await visitor.search(q, { locale, page: pageNo, limit: 10 });
171
+ search.results = found.items.filter((r) => r.path).map((r) => ({ id: r.id, title: r.title, href: r.path!, snippet: snippetParts(r.snippet) }));
172
+ search.total = found.total;
173
+ search.pages = Math.ceil(found.total / (found.limit || 10));
174
+ } catch (err) {
175
+ search.error = err instanceof Error ? err.message : String(err);
176
+ }
177
+ }
178
+ return { kind: 'search', shell, head: { ...head, title: q ? `Search: ${q} | ${siteName}` : `Search | ${siteName}` }, search };
179
+ }
180
+ shell.languages = site ? languageLinks(site, { locale, alternates: [] }) : [];
181
+ return { kind: 'not-found', shell, head: { ...head, title: `Page not found | ${siteName}` } };
182
+ }
183
+
184
+ // ---------- Redirects ----------
185
+
186
+ /** Redirect matching as Spillway does it: case-insensitive, without a trailing slash or a query. */
187
+ export function normalizePath(raw: string): string {
188
+ let p = raw;
189
+ try {
190
+ p = decodeURIComponent(p);
191
+ } catch {
192
+ // keep it as it is; a malformed escape never matches a stored path
193
+ }
194
+ const q = p.indexOf('?');
195
+ if (q >= 0) p = p.slice(0, q);
196
+ p = p.replace(/\/{2,}/g, '/').toLowerCase();
197
+ if (!p.startsWith('/')) p = `/${p}`;
198
+ if (p.length > 1) p = p.replace(/\/+$/, '');
199
+ return p;
200
+ }
201
+
202
+ /** The redirect from `path` in Spillway's list (Marketing → Redirects), if there is one. */
203
+ export async function redirectFor(path: string): Promise<PublicRedirect | undefined> {
204
+ try {
205
+ const list = await cached('redirects', async () => ({ value: await spillway.redirects(), tags: [SHELL_TAG, 'redirects'] }));
206
+ const want = normalizePath(path);
207
+ return list.find((r) => normalizePath(r.from) === want);
208
+ } catch {
209
+ return undefined; // an older Spillway without the list, or Spillway is down: serve the page
210
+ }
211
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * What the server answers for a request (server/utils/spillway.ts, `resolveView`) and the Vue pages lay out. Types only,
3
+ * shared by the app and the server (`#shared/spillway`).
4
+ */
5
+ import type { LanguageLink, PublicMenuItem } from '@spillway-cms/client';
6
+
7
+ export interface HeadData {
8
+ title: string;
9
+ description?: string;
10
+ canonical?: string;
11
+ alternates: { hreflang: string; href: string }[];
12
+ ogImage?: string;
13
+ noindex: boolean;
14
+ /** JSON-LD, already escaped for a <script> element. */
15
+ jsonLd: string[];
16
+ /** Spillway's CSS for the page, in order: the theme variables, the block styles and the page's block-style rules. */
17
+ css: string[];
18
+ /** The site's motion level when the page animates, for data-sw-motion on <html>. */
19
+ motion: 'subtle' | 'expressive' | null;
20
+ }
21
+
22
+ export interface Shell {
23
+ siteName: string;
24
+ footerNote: string[];
25
+ lang: string;
26
+ main: PublicMenuItem[];
27
+ footer: PublicMenuItem[];
28
+ /** One link per site locale; empty for a site with one locale. */
29
+ languages: LanguageLink[];
30
+ /** The published brand's stylesheet when it is newer than the one the last build wrote (use that one), else null. */
31
+ brandCss: string | null;
32
+ /** Whether search fields suggest pages while visitors type (Site settings → Search). */
33
+ suggestions: boolean;
34
+ /** The search page in the current locale (/search, /es/search). */
35
+ searchPath: string;
36
+ preview: boolean;
37
+ }
38
+
39
+ /** One search result: the page and the passage that matched, with the matched words marked. */
40
+ export interface SearchHit {
41
+ id: string;
42
+ title: string;
43
+ href: string;
44
+ snippet: { text: string; hit: boolean }[];
45
+ }
46
+
47
+ export interface SearchView {
48
+ q: string;
49
+ page: number;
50
+ pages: number;
51
+ total: number;
52
+ results: SearchHit[];
53
+ /** Set when Spillway could not answer the search. */
54
+ error?: string;
55
+ }
56
+
57
+ export type View =
58
+ | { kind: 'page'; shell: Shell; head: HeadData; body: string; scripts: string[] }
59
+ | { kind: 'search'; shell: Shell; head: HeadData; search: SearchView }
60
+ | { kind: 'not-found'; shell: Shell; head: HeadData };
@@ -0,0 +1,9 @@
1
+ {
2
+ "files": [],
3
+ "references": [
4
+ { "path": "./.nuxt/tsconfig.app.json" },
5
+ { "path": "./.nuxt/tsconfig.server.json" },
6
+ { "path": "./.nuxt/tsconfig.shared.json" },
7
+ { "path": "./.nuxt/tsconfig.node.json" }
8
+ ]
9
+ }
@@ -0,0 +1,27 @@
1
+ # Copy to .env (create-spillway wrote one for you) and fill in. Never commit .env.
2
+
3
+ # The Spillway site this front end reads, its public address.
4
+ SPILLWAY_URL=https://cms.example.org
5
+
6
+ # Optional. An API token (spw_..., made under the account menu → API tokens) with content.view_drafts, for draft
7
+ # previews through /api/preview?preview=1, and to read one site of a multisite instance with SPILLWAY_SITE. Server only.
8
+ SPILLWAY_TOKEN=
9
+ # Optional. The site's key on a multisite instance, when SPILLWAY_URL is not the site's own domain (needs SPILLWAY_TOKEN).
10
+ SPILLWAY_SITE=
11
+
12
+ # The secret of the webhook rule in Spillway (Site settings → Notifications) that posts to /api/revalidate.
13
+ SPILLWAY_WEBHOOK_SECRET=
14
+
15
+ # Guards /api/preview?preview=1 (latest drafts through SPILLWAY_TOKEN) and signs its cookie. Without it, only release
16
+ # share links open a preview.
17
+ SPILLWAY_PREVIEW_SECRET=
18
+
19
+ # Optional. A deploy hook (Vercel, Netlify, ...) the revalidation route calls on brand.published, so the next build
20
+ # refreshes the brand stylesheet. Pages already pick up a new brand without it.
21
+ DEPLOY_HOOK_URL=
22
+
23
+ # This front end's own address: canonical links, the sitemap and robots.txt use it.
24
+ SITE_URL=http://localhost:5173
25
+
26
+ # How long a page read from Spillway stays in the in-memory cache when no webhook purges it, in seconds; 0 turns it off.
27
+ SPILLWAY_CACHE_SECONDS=300