rosetack 0.1.2 → 0.1.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 (57) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/netlify/functions/rosetack.ts +38 -0
  4. package/deploy/netlify.toml +17 -0
  5. package/devtools/devtools.html +7 -0
  6. package/devtools/devtools.js +1 -0
  7. package/devtools/manifest.json +8 -0
  8. package/devtools/panel.html +28 -0
  9. package/devtools/panel.js +54 -0
  10. package/dist-cli/compiler.mjs +2194 -561
  11. package/dist-cli/edge.mjs +159 -48
  12. package/dist-cli/rosetack.mjs +2899 -739
  13. package/dist-cli/runtime.mjs +305 -43
  14. package/dist-cli/test.mjs +2332 -630
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/content.ts +186 -0
  18. package/src/cli/edge.ts +78 -62
  19. package/src/cli/image-size.ts +83 -0
  20. package/src/cli/index.ts +391 -334
  21. package/src/cli/prod-server.ts +324 -0
  22. package/src/cli/prompt.ts +51 -20
  23. package/src/cli/shell.ts +105 -74
  24. package/src/cli/test.ts +9 -70
  25. package/src/compiler/index.ts +2107 -913
  26. package/src/runtime/index.ts +367 -168
  27. package/src/types/rosetack.d.ts +16 -66
  28. package/templates/admin/package.json +14 -0
  29. package/templates/admin/rosetack.config.js +1 -0
  30. package/templates/admin/src/pages/_middleware.rose +33 -0
  31. package/templates/admin/src/pages/api/items.rose +37 -0
  32. package/templates/admin/src/pages/api/login.rose +25 -0
  33. package/templates/admin/src/pages/index.rose +79 -0
  34. package/templates/api/package.json +14 -0
  35. package/templates/api/rosetack.config.js +1 -0
  36. package/templates/api/src/pages/api/health.rose +7 -0
  37. package/templates/api/src/pages/api/items.rose +46 -0
  38. package/templates/api/src/pages/api/login.rose +24 -0
  39. package/templates/api/src/pages/index.rose +25 -0
  40. package/templates/blog/package.json +14 -0
  41. package/templates/blog/rosetack.config.js +1 -0
  42. package/templates/blog/src/pages/404.rose +2 -0
  43. package/templates/blog/src/pages/_layout.rose +42 -0
  44. package/templates/blog/src/pages/_middleware.rose +74 -0
  45. package/templates/blog/src/pages/admin.rose +85 -0
  46. package/templates/blog/src/pages/api/login.rose +46 -0
  47. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  48. package/templates/blog/src/pages/api/posts.rose +72 -0
  49. package/templates/blog/src/pages/index.rose +31 -0
  50. package/templates/blog/src/pages/post/[id].rose +36 -0
  51. package/templates/site/package.json +14 -0
  52. package/templates/site/rosetack.config.js +1 -0
  53. package/templates/site/src/pages/404.rose +2 -0
  54. package/templates/site/src/pages/_layout.rose +40 -0
  55. package/templates/site/src/pages/about.rose +6 -0
  56. package/templates/site/src/pages/index.rose +13 -0
  57. package/templates/site/src/pages/pricing.rose +8 -0
@@ -1,26 +1,6 @@
1
- /**
2
- * rosetack - the globals a `.rose` <script> block can call.
3
- *
4
- * This file is the framework's public script surface, declared once so an
5
- * editor and `rosetack check` (which runs the project's own TypeScript over
6
- * every extracted script block) both see the same truth the runtime
7
- * implements. The signatures mirror src/runtime/index.ts exactly - when one
8
- * changes, this file changes with it.
9
- *
10
- * It ships with the package. A project picks it up with a `rosetack-env.d.ts`
11
- * holding `/// <reference types="rosetack" />` (what `rosetack new` writes for
12
- * you); `rosetack check` references it by path, so it works in a source
13
- * checkout too. No imports, no exports: every declaration here is global,
14
- * because that is exactly how a `.rose` script sees them.
15
- */
16
- /// <reference lib="dom" />
17
-
18
- /**
19
- * A reactive getter. The compiler turns `let count = $state(0)` into a
20
- * getter/setter pair named after your declaration, so in a `.rose` script
21
- * the name you wrote IS this function - `count()` reads it, and
22
- * `$setState('count', v)` (or the generated setter) writes it.
23
- */
1
+ // rosetack - the globals a `.rose` <script> block can call.
2
+
3
+ // A reactive getter.
24
4
  type Getter<T> = () => T;
25
5
 
26
6
  /** A store shared by every request in this process (and, with a transport, every worker). */
@@ -36,45 +16,22 @@ declare function $state<T>(initial: T): Getter<T>;
36
16
  /** Write reactive state by key - the same write the generated setter performs. */
37
17
  declare function $setState<T>(key: string, value: T): void;
38
18
 
39
- /**
40
- * Server data. The body runs on the server per request (and ships to the
41
- * client, where it re-runs on a client-side navigation), the result lands in
42
- * the same state map as `$state` - so `post()` is a getter like any other.
43
- * The await is the compiler's, not yours.
44
- */
19
+
45
20
  declare function $data<T>(fn: () => T | Promise<T>): Getter<T>;
46
21
 
47
22
  /** The per-request bag filled by `pages/_middleware.rose` (auth, db, cache). */
48
23
  declare function getContext<T = Record<string, unknown>>(): T;
49
24
 
50
- /**
51
- * The parsed query string of the request being rendered (`?page=2&q=x` ->
52
- * `{ page: '2', q: 'x' }`). Read it in a `$data` body or in the render:
53
- * routing matches the pathname, so `/search?q=cats` renders the `/search`
54
- * route with `$query().q === 'cats'`. On a client-side navigation it is the
55
- * URL the browser is on. A repeated key keeps its first value.
56
- */
25
+ // The parsed query string of the request being rendered (`?page=2&q=x` -> `{ page: '2', q: 'x' }`).
57
26
  declare function $query(): Record<string, string>;
58
27
 
59
- /**
60
- * Translate a key from src/locales/<lang>.json.
61
- *
62
- * Values are either plain strings with `{name}` holes or ICU MessageFormat:
63
- * `{count, plural, one {# item} other {# items}}`, `{n, selectordinal, ...}`,
64
- * `{who, select, ...}` - so `vars` carries numbers for counts and strings for
65
- * names and select arms. A missing key renders the key itself.
66
- */
28
+
67
29
  declare function $t(key: string, vars?: Record<string, string | number>): string;
68
30
 
69
31
  /** 'rtl' for a right-to-left locale (ar, he, fa, ur, ...), 'ltr' otherwise. */
70
32
  declare function localeDir(lang: string): string;
71
33
 
72
- /**
73
- * Resolve once a locale's dictionary is present: immediately for a baked one,
74
- * after one fetch of /locales/<lang>.json for a runtime pack (a locale the
75
- * build left out of the bundle via i18n.preload). The client router awaits
76
- * this on every navigation, so a page rarely needs to call it directly.
77
- */
34
+
78
35
  declare function ensureLocale(lang: string): Promise<void>;
79
36
 
80
37
  /** Merge a dictionary that arrived at runtime (a fetched pack, or your own import()). */
@@ -108,12 +65,7 @@ declare function esc(v: unknown): string;
108
65
  /** Call a server action by name; the response is adopted in place. */
109
66
  declare function $action(name: string, e?: Event): Promise<void>;
110
67
 
111
- /**
112
- * The standardized failure a server action throws for a BUSINESS error (bad
113
- * input, not signed in, a duplicate) - as opposed to a bug, which still goes
114
- * to the 500 page. `code` becomes the response status; `field` names the
115
- * offending form input.
116
- */
68
+
117
69
  declare class ActionError extends Error {
118
70
  code: number;
119
71
  field?: string;
@@ -128,18 +80,10 @@ interface ActionErrorInfo {
128
80
  field?: string;
129
81
  }
130
82
 
131
- /**
132
- * The failure of the action that produced the response being rendered, or
133
- * null. Render it (`{#if $actionError()}<p>{$actionError().message}</p>{/if}`)
134
- * or contain it with a `{#boundary}` around the action's widget.
135
- */
83
+ // The failure of the action that produced the response being rendered, or null.
136
84
  declare function $actionError(): ActionErrorInfo | null;
137
85
 
138
- /**
139
- * An incremental patch: an action's return value may map a state key to an
140
- * OPERATION instead of a whole replacement, so growing a large list costs one
141
- * row rather than a second copy of the list.
142
- */
86
+ // An incremental patch: an action's return value may map a state key to an OPERATION instead of a whole replacement.
143
87
  declare function $append(value: unknown): unknown;
144
88
  declare function $prepend(value: unknown): unknown;
145
89
  declare function $merge(value: Record<string, unknown>): unknown;
@@ -149,3 +93,9 @@ declare function hasState(key: string): boolean;
149
93
 
150
94
  /** The best dictionary for an Accept-Language header (null when none matches). */
151
95
  declare function bestLocale(header: string | null | undefined): string | null;
96
+
97
+
98
+ declare function redirect(path: string, status?: 301 | 302 | 303 | 307 | 308): never;
99
+
100
+
101
+ declare function notFound(): never;
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "rosetack-admin",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "dev": "rosetack dev",
7
+ "build": "rosetack build",
8
+ "preview": "rosetack preview",
9
+ "serve": "rosetack serve"
10
+ },
11
+ "dependencies": {
12
+ "rosetack": "latest"
13
+ }
14
+ }
@@ -0,0 +1 @@
1
+ export default [];
@@ -0,0 +1,33 @@
1
+ <script>
2
+ // The middleware runs before every request and does two jobs here:
3
+ //
4
+ // 1. own the store - $store's box is shared by every request in the
5
+ // process and broadcast to the other cluster workers on a write,
6
+ // and the middleware is the one module the compiler never ships,
7
+ // 2. read the session cookie and put the user (and, for a signed-in
8
+ // visitor, the rows) in the request context.
9
+ //
10
+ // The api routes borrow the store from the context instead of opening
11
+ // their own: one box, one owner, no module global to drift.
12
+ //
13
+ // The wall is DATA ABSENCE, not a redirect: with no session the context
14
+ // carries no user, so the dashboard renders its login form and the
15
+ // manager never exists in the response - the same document a static
16
+ // deploy would serve. A context-reading route is dynamic by
17
+ // construction, so nothing gated can leak into a prerendered file.
18
+ interface Item { id: number; label: string }
19
+
20
+ // Not exported: nothing imports this module - the api routes borrow the
21
+ // store from the request context below, which is the whole point.
22
+ const store = $store<Item[]>('items', [
23
+ { id: 1, label: 'first' },
24
+ { id: 2, label: 'second' },
25
+ ]);
26
+
27
+ export async function handle(request: Request) {
28
+ const signedIn = $cookies(request).session === '1';
29
+ getContext().store = store;
30
+ getContext().user = signedIn ? { name: 'admin' } : null;
31
+ if (signedIn) getContext().items = store.get();
32
+ }
33
+ </script>
@@ -0,0 +1,37 @@
1
+ <script>
2
+ // The resource. The store itself lives in the middleware (one owner per
3
+ // app); this route borrows it from the request context, exactly like the
4
+ // blog-pg example borrows its pool. Writes are session-walled; reads are
5
+ // public so the landing page and a health check can share the shape.
6
+ const json = (obj: unknown, status = 200) =>
7
+ new Response(JSON.stringify(obj), { status, headers: { 'content-type': 'application/json' } });
8
+
9
+ const signedIn = (req: Request) => $cookies(req).session === '1';
10
+
11
+ export function GET() {
12
+ return { items: getContext().store.get() };
13
+ }
14
+
15
+ // Create: 401 without a session, 400 without a label, 201 with the row.
16
+ export async function POST(req: Request) {
17
+ if (!signedIn(req)) return json({ error: 'sign in first' }, 401);
18
+ const form = await req.formData();
19
+ const label = String(form.get('label') ?? '').trim();
20
+ if (!label) return json({ error: 'label is required' }, 400);
21
+ const store = getContext().store;
22
+ const items = store.get();
23
+ const id = items.reduce((max, it) => Math.max(max, it.id), 0) + 1;
24
+ store.set([...items, { id, label }]);
25
+ return json({ id, label }, 201);
26
+ }
27
+
28
+ // Delete by ?id=. Same wall as POST.
29
+ export async function DELETE(req: Request) {
30
+ if (!signedIn(req)) return json({ error: 'sign in first' }, 401);
31
+ const id = Number(new URL(req.url).searchParams.get('id'));
32
+ if (!id) return json({ error: 'id is required' }, 400);
33
+ const store = getContext().store;
34
+ store.set(store.get().filter((it) => it.id !== id));
35
+ return json({ deleted: id });
36
+ }
37
+ </script>
@@ -0,0 +1,25 @@
1
+ <script>
2
+ // Login for the template's one demo account. trade-off: plaintext, one
3
+ // seeded account - a demo, not a vault. A real backoffice hashes with
4
+ // node:crypto scrypt and compares in constant time; the cookie and the
5
+ // wall around it stay exactly as they are.
6
+ const json = (obj: unknown, status = 200, headers: Record<string, string> = {}) =>
7
+ new Response(JSON.stringify(obj), { status, headers: { 'content-type': 'application/json', ...headers } });
8
+
9
+ export async function POST(req: Request) {
10
+ const form = await req.formData();
11
+ const user = String(form.get('user') ?? '').trim();
12
+ const pass = String(form.get('pass') ?? '').trim();
13
+ // Validation before the credential check: a malformed request is a 400
14
+ // whether or not the account exists.
15
+ if (!user || !pass) return json({ error: 'user and pass are required' }, 400);
16
+ if (user !== 'admin' || pass !== 'admin') return json({ error: 'bad credentials' }, 401);
17
+ return json({ ok: true }, 200, { 'set-cookie': $sessionCookie('session', '1') });
18
+ }
19
+
20
+ // Logout: expire the cookie (Max-Age=0). The dashboard's Sign out button
21
+ // calls this with fetch - a native form cannot send DELETE.
22
+ export function DELETE() {
23
+ return json({ ok: true }, 200, { 'set-cookie': $sessionCookie('session', '', { maxAge: 0 }) });
24
+ }
25
+ </script>
@@ -0,0 +1,79 @@
1
+ <script>
2
+ // The dashboard - the whole gated half of the app in one page. Two
3
+ // forms, both progressive-enhancement honest:
4
+ //
5
+ // with JS - the handlers fetch-POST to the api routes and
6
+ // refresh() the page in place: one request, no reload
7
+ // without JS - the login form posts natively (the cookie is set, the
8
+ // next visit shows the manager); the write forms are the
9
+ // JS path, which is the honest split for a backoffice
10
+ //
11
+ // The wall is NOT here: without a session the middleware loads no user,
12
+ // so this page renders the login form and nothing else. `signedIn` is UX
13
+ // only - it remembers in this tab that the login fetch succeeded, because
14
+ // an HttpOnly cookie is deliberately unreadable from JavaScript.
15
+ interface Item { id: number; label: string }
16
+
17
+ let signedIn = $state(false);
18
+ let error = $state('');
19
+
20
+ let user = $data(async () => getContext().user ?? null);
21
+ let items = $data(async (): Promise<Item[] | null> =>
22
+ getContext().items ?? (signedIn() && typeof location !== 'undefined' ? (await (await fetch('/api/items')).json()).items : null));
23
+
24
+ async function login(e: SubmitEvent) {
25
+ e.preventDefault();
26
+ const form = e.target as HTMLFormElement;
27
+ const res = await fetch('/api/login', { method: 'POST', body: new FormData(form) });
28
+ if (res.ok) { signedIn(true); error(''); } else { error('wrong user or password'); }
29
+ }
30
+
31
+ async function create(e: SubmitEvent) {
32
+ e.preventDefault();
33
+ const form = e.target as HTMLFormElement;
34
+ const res = await fetch('/api/items', { method: 'POST', body: new FormData(form) });
35
+ if (res.ok) { error(''); form.reset(); await refresh(); } else { error(await res.text()); }
36
+ }
37
+
38
+ async function remove(id: number) {
39
+ const res = await fetch('/api/items?id=' + id, { method: 'DELETE' });
40
+ if (res.ok) await refresh(); else { error(await res.text()); }
41
+ }
42
+
43
+ // Sign out is a DELETE, which a native form cannot send - so it is the
44
+ // one action that needs the client. The cookie expires in 7 days anyway,
45
+ // and the README says so plainly.
46
+ async function logout() {
47
+ await fetch('/api/login', { method: 'DELETE' });
48
+ signedIn(false);
49
+ await refresh();
50
+ }
51
+ </script>
52
+
53
+ <h1>Dashboard</h1>
54
+
55
+ {#if signedIn() || user()}
56
+ <p>Signed in as <strong>admin</strong>. <button on:click={logout}>Sign out</button></p>
57
+ {#if error()}<p><strong>{error()}</strong></p>{/if}
58
+
59
+ <form on:submit={create}>
60
+ <input name="label" placeholder="New item" aria-label="New item" required>
61
+ <button type="submit">Add</button>
62
+ </form>
63
+
64
+ <ul>
65
+ {#each items() ?? [] as it}
66
+ <li>{it.label} <button on:click={() => remove(it.id)}>delete</button></li>
67
+ {/each}
68
+ </ul>
69
+ {/if}
70
+
71
+ {#if !signedIn() && !user()}
72
+ <p>Sign in to manage. The demo account is <code>admin</code> / <code>admin</code>.</p>
73
+ {#if error()}<p><strong>{error()}</strong></p>{/if}
74
+ <form method="POST" action="/api/login" on:submit={login}>
75
+ <input name="user" placeholder="User" aria-label="User" required>
76
+ <input name="pass" type="password" placeholder="Password" aria-label="Password" required>
77
+ <button type="submit">Sign in</button>
78
+ </form>
79
+ {/if}
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "rosetack-api",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "dev": "rosetack dev",
7
+ "build": "rosetack build",
8
+ "preview": "rosetack preview",
9
+ "serve": "rosetack serve"
10
+ },
11
+ "dependencies": {
12
+ "rosetack": "latest"
13
+ }
14
+ }
@@ -0,0 +1 @@
1
+ export default [];
@@ -0,0 +1,7 @@
1
+ <script>
2
+ // Liveness. The one endpoint that must never need a database, a session
3
+ // or a config value: if this answers, the process is up.
4
+ export function GET() {
5
+ return { ok: true, uptime: Math.round(process.uptime()) };
6
+ }
7
+ </script>
@@ -0,0 +1,46 @@
1
+ <script>
2
+ // The resource. $store is the right shape for an API template: one box
3
+ // per name, shared by every request in the process, and broadcast to the
4
+ // other cluster workers on a write (a plain module object would live in
5
+ // exactly one worker - items would appear and vanish by which core
6
+ // answered). A real service swaps the store body for a database; the
7
+ // handlers below do not change.
8
+ export const store = $store('items', [
9
+ { id: 1, label: 'first' },
10
+ { id: 2, label: 'second' },
11
+ ]);
12
+
13
+ const json = (obj: unknown, status = 200) =>
14
+ new Response(JSON.stringify(obj), { status, headers: { 'content-type': 'application/json' } });
15
+
16
+ const signedIn = (req: Request) => $cookies(req).session === '1';
17
+
18
+ // Public read. The CSRF guard on `rosetack serve` only refuses cross-site
19
+ // WRITES, so a GET needs no token of its own.
20
+ export function GET() {
21
+ return { items: store.get() };
22
+ }
23
+
24
+ // Create: 401 without a session, 400 without a label, 201 with the new
25
+ // row. The response is the row, not the whole list - the client already
26
+ // has the list, and a real service would return even less.
27
+ export async function POST(req: Request) {
28
+ if (!signedIn(req)) return json({ error: 'sign in first' }, 401);
29
+ const form = await req.formData();
30
+ const label = String(form.get('label') ?? '').trim();
31
+ if (!label) return json({ error: 'label is required' }, 400);
32
+ const items = store.get();
33
+ const id = items.reduce((max, it) => Math.max(max, it.id), 0) + 1;
34
+ store.set([...items, { id, label }]);
35
+ return json({ id, label }, 201);
36
+ }
37
+
38
+ // Delete by ?id=. Same wall as POST.
39
+ export async function DELETE(req: Request) {
40
+ if (!signedIn(req)) return json({ error: 'sign in first' }, 401);
41
+ const id = Number(new URL(req.url).searchParams.get('id'));
42
+ if (!id) return json({ error: 'id is required' }, 400);
43
+ store.set(store.get().filter((it) => it.id !== id));
44
+ return json({ deleted: id });
45
+ }
46
+ </script>
@@ -0,0 +1,24 @@
1
+ <script>
2
+ // Login for the template's one demo account. trade-off: plaintext, one
3
+ // seeded row - a demo, not a vault. A real service hashes with
4
+ // node:crypto scrypt and compares in constant time; the cookie and the
5
+ // wall around it stay exactly as they are.
6
+ const json = (obj: unknown, status = 200, headers: Record<string, string> = {}) =>
7
+ new Response(JSON.stringify(obj), { status, headers: { 'content-type': 'application/json', ...headers } });
8
+
9
+ export async function POST(req: Request) {
10
+ const form = await req.formData();
11
+ const user = String(form.get('user') ?? '').trim();
12
+ const pass = String(form.get('pass') ?? '').trim();
13
+ // Validation before the credential check: a malformed request is a 400
14
+ // whether or not the account exists.
15
+ if (!user || !pass) return json({ error: 'user and pass are required' }, 400);
16
+ if (user !== 'admin' || pass !== 'admin') return json({ error: 'bad credentials' }, 401);
17
+ return json({ ok: true }, 200, { 'set-cookie': $sessionCookie('session', '1') });
18
+ }
19
+
20
+ // Logout: expire the cookie (Max-Age=0).
21
+ export function DELETE() {
22
+ return json({ ok: true }, 200, { 'set-cookie': $sessionCookie('session', '', { maxAge: 0 }) });
23
+ }
24
+ </script>
@@ -0,0 +1,25 @@
1
+ <script>
2
+ // The landing page. It exists so `rosetack dev` has something to open, and
3
+ // it doubles as the endpoint list. No events, no forms, no lifecycle: the
4
+ // compiler ships it as pure HTML - zero JavaScript, zero requests beyond
5
+ // the document.
6
+ let endpoints = $state([
7
+ { method: 'GET', path: '/api/health', note: 'liveness - always public' },
8
+ { method: 'GET', path: '/api/items', note: 'the list - public read' },
9
+ { method: 'POST', path: '/api/login', note: 'admin / admin -> the session cookie' },
10
+ { method: 'POST', path: '/api/items', note: 'create - needs the session' },
11
+ { method: 'DELETE', path: '/api/items?id=1', note: 'delete - needs the session' },
12
+ ]);
13
+ </script>
14
+
15
+ <h1>🌹 rosetack API service</h1>
16
+ <p>A JSON backend: five endpoints, one in-memory store, no database to set up.</p>
17
+ <ul>
18
+ {#each endpoints() as e}
19
+ <li><code>{e.method} {e.path}</code> — {e.note}</li>
20
+ {/each}
21
+ </ul>
22
+ <p>
23
+ Try it: <code>curl localhost:3000/api/items</code>, then
24
+ <code>curl -X POST localhost:3000/api/login -d 'user=admin&amp;pass=admin'</code>.
25
+ </p>
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "rosetack-blog",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "dev": "rosetack dev",
7
+ "build": "rosetack build",
8
+ "preview": "rosetack preview",
9
+ "serve": "rosetack serve"
10
+ },
11
+ "dependencies": {
12
+ "rosetack": "latest"
13
+ }
14
+ }
@@ -0,0 +1 @@
1
+ export default [];
@@ -0,0 +1,2 @@
1
+ <h1>404</h1>
2
+ <p>That page is not in the garden. <a href="/">Back to the posts</a>.</p>
@@ -0,0 +1,42 @@
1
+ <script>
2
+ // The layout wraps every page of the blog. `links` is ordinary state:
3
+ // the nav is one {#each} over it, so adding a page means adding a line
4
+ // here and a file under src/pages/.
5
+ let links = $state([
6
+ { href: '/', label: 'Posts' },
7
+ { href: '/admin', label: 'Write' }
8
+ ]);
9
+ </script>
10
+
11
+ <style>
12
+ /* Scoped to this file: the build rewrites every selector with this
13
+ component's scope key, so `.shell` below cannot leak into a page's
14
+ own `.shell`. Zero stylesheet requests - the CSS is inlined into
15
+ the document. */
16
+ .shell { max-width: 42rem; margin: 0 auto; padding: 1.5rem 1rem 3rem; font-family: system-ui, sans-serif; }
17
+ .rb { font-size: 1.25rem; }
18
+ .rn a { margin-right: 1rem; }
19
+ .rf { margin-top: 3rem; color: #888; font-size: 0.85rem; }
20
+ </style>
21
+
22
+ <head>
23
+ <title>Rosevine</title>
24
+ <meta name="description" content="A blog built with rosetack: one request, zero hydration, a real database.">
25
+ </head>
26
+
27
+ <div class="shell">
28
+ <header>
29
+ <strong class="rb">🌹 Rosevine</strong>
30
+ <nav class="rn">
31
+ {#each links() as link}
32
+ <a href={link.href}>{link.label}</a>
33
+ {/each}
34
+ </nav>
35
+ </header>
36
+ <main>
37
+ <slot />
38
+ </main>
39
+ <footer class="rf">
40
+ Built with rosetack — the list page ships zero JavaScript.
41
+ </footer>
42
+ </div>
@@ -0,0 +1,74 @@
1
+ <script>
2
+ import { $cookies } from './runtime.js';
3
+ import type { DatabaseSync } from 'node:sqlite';
4
+
5
+ // The middleware runs before every request - pages, POSTs and api calls
6
+ // alike. In this blog it does three jobs:
7
+ //
8
+ // 1. open the database once per process (lazily - never at module
9
+ // load, and never as a build side effect),
10
+ // 2. load the rows each route needs into the request context,
11
+ // 3. decide who is signed in.
12
+ //
13
+ // Why the data loads HERE and not in the page: a page's $data body ships
14
+ // to the browser (it re-runs on client-side navigation), so a database
15
+ // import inside a page would land in the client bundle and break the
16
+ // build. The middleware module is the one the compiler never ships.
17
+
18
+ // The connection. node:sqlite is inside Node 22+ - zero dependencies,
19
+ // zero native modules. A Postgres deploy swaps this block for a pg.Pool
20
+ // (same shape: prepare/run/all) and nothing else in the app moves.
21
+ // The file path is relative to the directory you started the server
22
+ // from - never inside dist/, which is a build artifact.
23
+ let conn: DatabaseSync | undefined;
24
+ const getDb = async () => {
25
+ if (!conn) {
26
+ const { DatabaseSync } = await import('node:sqlite');
27
+ conn = new DatabaseSync('blog.db');
28
+ conn.exec(`
29
+ CREATE TABLE IF NOT EXISTS posts (
30
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
31
+ title TEXT NOT NULL,
32
+ body TEXT NOT NULL,
33
+ author TEXT NOT NULL DEFAULT 'anonymous'
34
+ );
35
+ INSERT OR IGNORE INTO posts (id, title, body, author) VALUES
36
+ (1, 'One request, zero hydration', 'The whole page - data included - arrives in the first response. No runtime boots to show it.', 'ada'),
37
+ (2, 'The database is not the hard part', 'node:sqlite ships inside Node. The hard part is keeping the single-request contract while the data changes per request.', 'grace');
38
+ `);
39
+ }
40
+ return conn;
41
+ };
42
+
43
+ interface PostRow { id: number; title: string; body: string; author: string }
44
+
45
+ export async function handle(request: Request) {
46
+ const { pathname } = new URL(request.url);
47
+ const session = $cookies(request).session;
48
+
49
+ // The write page is walled by ABSENCE of data, not by a redirect: with
50
+ // no session the middleware loads no posts, so the page renders its
51
+ // login form and the manager never exists in the response. A static
52
+ // deploy (the Go binary) shows exactly the same login form.
53
+ if (pathname === '/admin' && session) {
54
+ const db = await getDb();
55
+ getContext().posts = db.prepare('SELECT id, title, body, author FROM posts ORDER BY id DESC').all() as unknown as PostRow[];
56
+ }
57
+
58
+ // The list page reads the same rows.
59
+ if (pathname === '/') {
60
+ const db = await getDb();
61
+ getContext().posts = db.prepare('SELECT id, title, body, author FROM posts ORDER BY id DESC').all() as unknown as PostRow[];
62
+ }
63
+
64
+ // A single post: /post/<id>. The id is the last path segment.
65
+ const postMatch = pathname.match(/^\/post\/(\d+)$/);
66
+ if (postMatch) {
67
+ const db = await getDb();
68
+ getContext().post = db.prepare('SELECT id, title, body, author FROM posts WHERE id = ?').get(Number(postMatch[1])) as PostRow | undefined;
69
+ }
70
+
71
+ // Everything downstream can ask who is calling.
72
+ getContext().user = session ? { id: Number(session) } : null;
73
+ }
74
+ </script>