rosetack 0.0.0 → 0.1.1

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/pack.mjs ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * pack.mjs - build the PUBLISHED package: the CLI and its library entries as
3
+ * self-contained ESM bundles, so `npm i -g rosetack` needs nothing but Node.
4
+ *
5
+ * Why a script and not a shell one-liner: the bin needs a shebang, and '#'
6
+ * is a comment character in two of the three shells npm might run a script
7
+ * through. esbuild's JS API takes it as data instead of as shell text.
8
+ *
9
+ * esbuild stays EXTERNAL: the compiler drives it at build time (it bundles
10
+ * the app), and its platform binary resolves relative to its own package -
11
+ * bundling it here would break that. It is a runtime dependency for exactly
12
+ * this reason.
13
+ *
14
+ * The bundles resolve two things relative to themselves (src/runtime for the
15
+ * app's bundles, package.json for the version banner), so src/ ships in the
16
+ * tarball beside dist-cli/ - see "files" in package.json.
17
+ */
18
+ import { build } from 'esbuild';
19
+ import * as fs from 'node:fs';
20
+
21
+ const OUT = 'dist-cli';
22
+ fs.rmSync(OUT, { recursive: true, force: true });
23
+ fs.mkdirSync(OUT, { recursive: true });
24
+
25
+ const entries = [
26
+ // [source, output, is-the-bin]
27
+ ['src/cli/index.ts', `${OUT}/rosetack.mjs`, true],
28
+ ['src/cli/edge.ts', `${OUT}/edge.mjs`, false],
29
+ ['src/cli/test.ts', `${OUT}/test.mjs`, false],
30
+ ['src/runtime/index.ts', `${OUT}/runtime.mjs`, false],
31
+ ['src/compiler/index.ts', `${OUT}/compiler.mjs`, false],
32
+ ];
33
+
34
+ for (const [entry, outfile, isBin] of entries) {
35
+ await build({
36
+ entryPoints: [entry],
37
+ outfile,
38
+ bundle: true,
39
+ platform: 'node',
40
+ format: 'esm',
41
+ target: 'node22',
42
+ external: ['esbuild'],
43
+ banner: isBin ? { js: '#!/usr/bin/env node' } : {},
44
+ logLevel: 'warning',
45
+ });
46
+ const { size } = fs.statSync(outfile);
47
+ console.log(`packed ${outfile.padEnd(22)} ${(size / 1024).toFixed(1).padStart(6)} KB <- ${entry}`);
48
+ }
49
+ console.log(`\n${entries.length} bundles in ${OUT}/ - the tarball also ships src/ (the runtime source the compiler feeds esbuild), deploy/, and the docs`);
package/package.json CHANGED
@@ -1,20 +1,59 @@
1
1
  {
2
2
  "name": "rosetack",
3
- "version": "0.0.0",
4
- "description": "rosetack",
5
- "main": "index.js",
3
+ "version": "0.1.1",
4
+ "description": "Zero-hydration full-stack web framework with compile-time reactivity and zero-JS content routes.",
5
+ "type": "module",
6
6
  "scripts": {
7
- "test": "echo \"no test\" && exit 1"
7
+ "dev": "tsx src/cli/index.ts dev example",
8
+ "build": "tsx src/cli/index.ts build example",
9
+ "preview": "tsx src/cli/index.ts preview example",
10
+ "serve": "tsx src/cli/index.ts serve example",
11
+ "release:notes": "node tools/release-notes.mjs",
12
+ "pack": "node pack.mjs",
13
+ "prepublishOnly": "npm run pack",
14
+ "build:go": "go build -o rosetack-server ."
15
+ },
16
+ "bin": {
17
+ "rosetack": "dist-cli/rosetack.mjs"
18
+ },
19
+ "exports": {
20
+ "./edge": "./dist-cli/edge.mjs",
21
+ "./runtime": "./dist-cli/runtime.mjs",
22
+ "./compiler": "./dist-cli/compiler.mjs",
23
+ "./test": "./dist-cli/test.mjs"
24
+ },
25
+ "files": [
26
+ "dist-cli",
27
+ "src",
28
+ "deploy",
29
+ "pack.mjs",
30
+ "README.md",
31
+ "VERSIONING.md",
32
+ "LICENSE"
33
+ ],
34
+ "license": "MIT",
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "dependencies": {
39
+ "esbuild": "^0.24.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.0.0",
43
+ "jsdom": "^29.1.1",
44
+ "tsx": "^4.7.0",
45
+ "typescript": "^5.6.0"
46
+ },
47
+ "author": {
48
+ "name": "xdunli",
49
+ "url": "https://github.com/xdunli"
8
50
  },
9
51
  "repository": {
10
52
  "type": "git",
11
- "url": "git+https://github.com/neodunli/rosetack.git"
53
+ "url": "git+https://github.com/xdunli/rosetack.git"
12
54
  },
13
- "keywords": [],
14
- "author": "",
15
- "license": "MIT",
55
+ "homepage": "https://github.com/xdunli/rosetack#readme",
16
56
  "bugs": {
17
- "url": "https://github.com/neodunli/rosetack/issues"
18
- },
19
- "homepage": "https://github.com/neodunli/rosetack#readme"
57
+ "url": "https://github.com/xdunli/rosetack/issues"
58
+ }
20
59
  }
@@ -0,0 +1 @@
1
+ 0.1.1
@@ -0,0 +1,162 @@
1
+ /**
2
+ * rosetack Edge adapter - Web-standard fetch handler.
3
+ *
4
+ * Works on any edge runtime that supports the Fetch API standard
5
+ * (Cloudflare Workers, Deno Deploy, Vercel Edge, Bun, Node 18+):
6
+ *
7
+ * import { createEdgeHandler } from 'rosetack/edge';
8
+ * const handle = createEdgeHandler('./dist');
9
+ * export default { fetch: handle };
10
+ *
11
+ * The generated dist/server.js has zero Node built-in imports, so the same
12
+ * bundle that runs the Node server runs at the edge. Static routes can be
13
+ * served by the platform's asset layer; everything else renders on demand.
14
+ * GETs to known routes stream (the static shell flushes before the render
15
+ * completes, still one request); routes known-broken at build time
16
+ * (dist/broken.json) stay buffered so their real 500 status survives, and
17
+ * csr = false routes buffer so their document is complete without a client.
18
+ */
19
+
20
+ import { pathToFileURL } from 'url';
21
+ import { join } from 'path';
22
+ import { buildShell, shellOpen, clientScriptTag, securityHeaders, mintNonce } from './shell.js';
23
+
24
+ type ServerModule = {
25
+ renderPage(pathname: string, form?: FormData): Promise<{ html: string; state: string; head: string[]; status?: number; csr?: boolean; lang?: string; dir?: string }>;
26
+ renderPageStream(pathname: string, write: (chunk: string) => void, shellOpen: string, clientTag: string): Promise<number>;
27
+ canStream(pathname: string): boolean;
28
+ isNoJs(pathname: string): boolean;
29
+ isApi(pathname: string): boolean;
30
+ handleApi(method: string, pathname: string, request: Request): Promise<Response>;
31
+ /** The document's <html lang>/<dir> for a pathname (streaming needs them before the render) */
32
+ docAttrs(pathname: string): { lang: string; dir: string };
33
+ /** pages/_middleware.rose's handler, or null when the project has none */
34
+ middleware: ((request: Request) => Promise<Response | void | null>) | null;
35
+ /** run the middleware once per request; returns its short-circuit Response or null */
36
+ runMiddleware(rawReq: any, form?: FormData): Promise<Response | null>;
37
+ /** The runtime plugin hooks, and whether the project declares any */
38
+ runRequestHooks(ctx: {
39
+ request: Request; url: URL; method: string; pathname: string; state: Record<string, unknown>;
40
+ }): Promise<Response | null>;
41
+ runResponseHooks(ctx: {
42
+ request: Request; url: URL; method: string; pathname: string; state: Record<string, unknown>;
43
+ }, res: Response): Promise<Response>;
44
+ hasRequestHooks: boolean;
45
+ hasResponseHooks: boolean;
46
+ /** routes whose component reads getContext(): never prerendered, always live */
47
+ dynamicRoutes: string[];
48
+ /** per-route response headers [] when no route exports any */
49
+ routeHeaders: Array<{ pattern: string; headers: Record<string, string> }>;
50
+ /** the route's own exported headers for a pathname, or null */
51
+ headersFor(pathname: string): Record<string, string> | null;
52
+ /** Routes that exported `csp = { nonce: true }` - nonce policy, never baked */
53
+ cspNonce(pathname: string): boolean;
54
+ };
55
+
56
+ /**
57
+ * Create a fetch handler from a built rosetack project.
58
+ * @param outDir directory containing server.js and client.js
59
+ */
60
+ export async function createEdgeHandler(outDir: string): Promise<(request: Request) => Promise<Response>> {
61
+ const mod: ServerModule = await import(pathToFileURL(join(outDir, 'server.js')).href);
62
+ let client: string | null = null;
63
+ let styles = '';
64
+ try {
65
+ client = await (await import('fs/promises')).readFile(join(outDir, 'client.js'), 'utf-8');
66
+ } catch {
67
+ client = null; // no fs (Workers): platform should inline the bundle at deploy time
68
+ }
69
+ try {
70
+ styles = await (await import('fs/promises')).readFile(join(outDir, 'styles.css'), 'utf-8');
71
+ } catch {
72
+ styles = ''; // no component styles (or no fs): shell STYLES only
73
+ }
74
+ // routes whose render failed at build time: buffered, so the 500 survives
75
+ let broken = new Set<string>();
76
+ try {
77
+ broken = new Set(JSON.parse(await (await import('fs/promises')).readFile(join(outDir, 'broken.json'), 'utf-8')));
78
+ } catch {
79
+ broken = new Set(); // no manifest: nothing known-broken
80
+ }
81
+
82
+ // Response headers for a page document: the strict CSP hashed over the exact inlined bytes …
83
+ const pageHeaders = (pathname: string, nonce = ''): Record<string, string> => {
84
+ const headers: Record<string, string> = {};
85
+ if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
86
+ const own = mod.headersFor?.(pathname);
87
+ if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
88
+ return headers;
89
+ };
90
+
91
+ return async function handle(request: Request): Promise<Response> {
92
+ const { pathname } = new URL(request.url);
93
+ // Runtime hooks: onRequest runs before middleware and routing and may short-circuit with
94
+ // its own Response - an auth wall, a rate limit.
95
+ const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks
96
+ ? { request, url: new URL(request.url), method: request.method, pathname, state: {} as Record<string, unknown> }
97
+ : null;
98
+ if (hookCtx) {
99
+ const short = await mod.runRequestHooks(hookCtx);
100
+ if (short) return mod.runResponseHooks(hookCtx, short);
101
+ }
102
+ // Middleware (pages/_middleware.rose) runs exactly once per request, before anything
103
+ // else: a returned Response short-circuits the whole request (a redirect, an auth wall) …
104
+ if (mod.middleware) {
105
+ const mw = await mod.runMiddleware(request);
106
+ if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
107
+ }
108
+ // API routes (pages/api/*.rose): the /api namespace answers JSON, never the HTML shell …
109
+ if (mod.isApi(pathname)) {
110
+ const apiRes = await mod.handleApi(request.method, pathname, request);
111
+ return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
112
+ }
113
+ // POST: progressive-enhancement form - run the route's server action with
114
+ // the submitted FormData and re-render the page (works without JS).
115
+ const form = request.method === 'POST' ? await request.formData() : undefined;
116
+ // csr = false routes buffer too: a streamed no-JS document would carry the shell's default
117
+ // <title> - the route head is applied client-side at boot, and there is no client.
118
+ if (!form && !broken.has(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
119
+ // The nonce is minted before the Response exists, because its headers are fixed from then
120
+ // on - and the document's script tag is written into that same stream …
121
+ const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
122
+ // streaming GET: one chunked Response, still exactly one request. onResponse runs
123
+ // before the stream is created, while the status and headers can still change …
124
+ const streamed = new Response(null, {
125
+ status: 200,
126
+ headers: { 'content-type': 'text/html; charset=utf-8', ...pageHeaders(pathname, nonce) }
127
+ });
128
+ const head = hookCtx ? await mod.runResponseHooks(hookCtx, streamed) : streamed;
129
+ const encoder = new TextEncoder();
130
+ const stream = new ReadableStream<Uint8Array>({
131
+ async start(controller) {
132
+ // The shell opens before the render, so its <html lang>/<dir>
133
+ // come from the pathname (the server bundle's docAttrs)
134
+ const doc = mod.docAttrs(pathname);
135
+ await mod.renderPageStream(
136
+ pathname,
137
+ (chunk) => controller.enqueue(encoder.encode(chunk)),
138
+ shellOpen(styles, doc.lang, doc.dir),
139
+ clientScriptTag(client, nonce)
140
+ );
141
+ controller.close();
142
+ }
143
+ });
144
+ return new Response(stream, { status: head.status, headers: head.headers });
145
+ }
146
+ // buffered: POST actions, unmatched routes (404), known-broken routes (500).
147
+ // The middleware already ran at the top of this handler, so the render
148
+ // below sees its context.
149
+ const page = await mod.renderPage(pathname, form);
150
+ // '' for every hashed route, so the document is byte-identical to
151
+ // what it was before nonce mode existed.
152
+ const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
153
+ // js = page.csr !== false: a csr = false route ships no bundle, no state script - the
154
+ // document is HTML + CSS only .
155
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce);
156
+ const buffered = new Response(html, {
157
+ status: page.status ?? 200,
158
+ headers: { 'content-type': 'text/html; charset=utf-8', ...pageHeaders(pathname, nonce) }
159
+ });
160
+ return hookCtx ? mod.runResponseHooks(hookCtx, buffered) : buffered;
161
+ };
162
+ }