rosetack 0.1.0 → 0.1.2

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 (52) hide show
  1. package/deploy/k8s/rosetack.yaml +107 -0
  2. package/dist-cli/compiler.mjs +2783 -0
  3. package/dist-cli/edge.mjs +332 -0
  4. package/dist-cli/rosetack.mjs +4230 -0
  5. package/dist-cli/runtime.mjs +703 -0
  6. package/dist-cli/test.mjs +3202 -0
  7. package/pack.mjs +49 -0
  8. package/package.json +25 -7
  9. package/src/FRAMEWORK_VERSION +1 -1
  10. package/src/cli/edge.ts +67 -25
  11. package/src/cli/index.ts +858 -94
  12. package/src/cli/prompt.ts +127 -0
  13. package/src/cli/shell.ts +133 -30
  14. package/src/cli/test.ts +400 -0
  15. package/src/compiler/errors.ts +74 -0
  16. package/src/compiler/index.ts +1955 -264
  17. package/src/runtime/index.ts +465 -66
  18. package/src/types/rosetack.d.ts +151 -0
  19. package/.github/workflows/ci.yml +0 -72
  20. package/.github/workflows/release.yml +0 -122
  21. package/benchmark.ts +0 -227
  22. package/example/public/favicon.ico +0 -0
  23. package/example/public/logo.svg +0 -148
  24. package/example/public/rose-mark-black.png +0 -0
  25. package/example/public/rose-mark.png +0 -0
  26. package/example/public/rose-mono.png +0 -0
  27. package/example/rosetack.config.js +0 -10
  28. package/example/src/locales/en.json +0 -8
  29. package/example/src/locales/zh.json +0 -8
  30. package/example/src/pages/404.rose +0 -15
  31. package/example/src/pages/500.rose +0 -10
  32. package/example/src/pages/[lang]/about.rose +0 -40
  33. package/example/src/pages/_layout.rose +0 -33
  34. package/example/src/pages/_middleware.rose +0 -37
  35. package/example/src/pages/about.rose +0 -67
  36. package/example/src/pages/admin.rose +0 -27
  37. package/example/src/pages/api/hello.rose +0 -19
  38. package/example/src/pages/api/login.rose +0 -55
  39. package/example/src/pages/api/posts.rose +0 -80
  40. package/example/src/pages/api/secret.rose +0 -14
  41. package/example/src/pages/blog/[id].rose +0 -25
  42. package/example/src/pages/broken.rose +0 -16
  43. package/example/src/pages/fresh.rose +0 -22
  44. package/example/src/pages/garden.rose +0 -27
  45. package/example/src/pages/index.rose +0 -84
  46. package/example/src/pages/sign.rose +0 -45
  47. package/example/src/pages/thorn.rose +0 -23
  48. package/example/src/pages/vault.rose +0 -14
  49. package/go.mod +0 -3
  50. package/main.go +0 -470
  51. package/tools/release-notes.mjs +0 -113
  52. package/tsconfig.json +0 -17
@@ -0,0 +1,332 @@
1
+ // src/cli/edge.ts
2
+ import { pathToFileURL } from "url";
3
+ import { join as join2 } from "path";
4
+
5
+ // src/cli/shell.ts
6
+ import * as fs from "fs";
7
+ import * as path from "path";
8
+ import * as esbuild from "esbuild";
9
+ import { createHash } from "crypto";
10
+ var OUT_DIR = path.join(process.cwd(), "dist");
11
+ var styleCache = null;
12
+ function getStyles() {
13
+ const file = path.join(OUT_DIR, "styles.css");
14
+ try {
15
+ const st = fs.statSync(file);
16
+ if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
17
+ styleCache = { mtimeMs: st.mtimeMs, source: fs.readFileSync(file, "utf-8") };
18
+ }
19
+ return styleCache.source;
20
+ } catch {
21
+ return "";
22
+ }
23
+ }
24
+ var BOOTSTRAP = esbuild.transformSync(`
25
+ const __app = document.getElementById('app');
26
+ // Native View Transitions around client-side navigation (progressive:
27
+ // browsers without the API navigate normally, no polyfill, no CSS required).
28
+ function __navigate(pathname) {
29
+ const paint = () => start(__app, pathname);
30
+ if (document.startViewTransition) {
31
+ return document.startViewTransition(paint).updateCallbackDone;
32
+ }
33
+ return paint();
34
+ }
35
+ window.addEventListener('popstate', () => __navigate(window.location.pathname));
36
+ document.addEventListener('click', (e) => {
37
+ const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
38
+ if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
39
+ e.preventDefault();
40
+ history.pushState(null, '', a.getAttribute('href'));
41
+ __navigate(window.location.pathname);
42
+ }
43
+ });
44
+ // Prefetch the target route's full render (including $data) on hover, keyboard
45
+ // focus, or touch - the click that follows paints from cache: no await, no
46
+ // request. Other frameworks prefetch data only; rosetack prefetches the render
47
+ // because the inlined bundle already contains every route.
48
+ function __prefetchHandler(e) {
49
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
50
+ if (a && prefetch) prefetch(a.getAttribute('href'), 'hover');
51
+ }
52
+ document.addEventListener('mouseover', __prefetchHandler);
53
+ document.addEventListener('focusin', __prefetchHandler);
54
+ document.addEventListener('touchstart', __prefetchHandler, { passive: true });
55
+ // Viewport + idle prefetch (viewport-triggered): once a link scrolls into view and the
56
+ // browser is idle, its route renders ahead of any interaction. trade-off: both
57
+ // APIs are feature-detected; without them the hover/focus/touch path above
58
+ // still covers every link.
59
+ if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
60
+ const io = new IntersectionObserver((entries) => {
61
+ for (const e of entries) {
62
+ if (!e.isIntersecting) continue;
63
+ io.unobserve(e.target); // one-shot per element; fresh links re-observe after nav
64
+ requestIdleCallback(() => prefetch(e.target.getAttribute('href'), 'viewport'));
65
+ }
66
+ });
67
+ // observing an already-observed element is a no-op, so re-sweeping is cheap
68
+ const observeLinks = () => {
69
+ for (const a of document.querySelectorAll('a[href^="/"]')) io.observe(a);
70
+ };
71
+ observeLinks();
72
+ // navigation swaps the container's innerHTML: re-observe the fresh links
73
+ const __rawNav = __navigate;
74
+ __navigate = (p) => __rawNav(p).then(observeLinks, () => {});
75
+ }
76
+ // Progressive-enhancement forms: <form method="POST"> backed by a server
77
+ // action. With JS the submit is intercepted and handed to postForm (one
78
+ // request, in-place adopt). Without JS the browser performs the native POST
79
+ // and the server re-renders the page: the same form works with JavaScript
80
+ // disabled, which Server Actions in other frameworks do not.
81
+ document.addEventListener('submit', (e) => {
82
+ const f = e.target;
83
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
84
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
85
+ e.preventDefault();
86
+ postForm(new FormData(f));
87
+ });
88
+ // Dev seam: the live signal graph, readable as JSON. Two callers, one
89
+ // implementation: the dev server's reload bridge snapshots it before a
90
+ // rebuild-triggered reload so the edit lands on the state the developer had,
91
+ // and a devtools extension reads it the same way. It is the same
92
+ // serializeState the zero-hydration resume already ships, so the only new
93
+ // bytes are the assignment.
94
+ window.__rosetack = { state: () => serializeState() };
95
+ // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
96
+ // If the document was rendered for a DIFFERENT route (a static-file server's
97
+ // SPA fallback serves index.html for unknown paths), adopt nothing - let the
98
+ // client router render the requested route from scratch.
99
+ const __st = document.getElementById('__rosetack_state');
100
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
101
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
102
+ // the next document (window.__rosetack_resume). The resumed values win over the
103
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
104
+ // the route renders client-side from the bundle rather than adopting the SSR
105
+ // DOM, because a resumed list can be longer than the document's rows and
106
+ // adoption could not add them. Absent in every non-dev document.
107
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
108
+ if (__resumed) {
109
+ const __route = __state.__route;
110
+ __state = Object.assign(__state, __resumed);
111
+ __state.__route = __route;
112
+ }
113
+ if (__resumed) {
114
+ start(__app, window.location.pathname);
115
+ } else if (__state.__route === window.location.pathname) {
116
+ start(__app, window.location.pathname, true);
117
+ } else {
118
+ start(__app, window.location.pathname);
119
+ }
120
+ `, { minify: true }).code;
121
+ var CSP_TAIL = `style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
122
+ var cspCache = null;
123
+ var EXTERNAL_BOOTSTRAP = `
124
+ import { start, prefetch, postForm } from '/client.js';
125
+ ${BOOTSTRAP}`;
126
+ function inlineScript(client) {
127
+ return `
128
+ ${client}
129
+ ${BOOTSTRAP}`;
130
+ }
131
+ function mintNonce() {
132
+ const bytes = new Uint8Array(16);
133
+ crypto.getRandomValues(bytes);
134
+ let raw = "";
135
+ for (const b of bytes) raw += String.fromCharCode(b);
136
+ return btoa(raw);
137
+ }
138
+ function securityHeaders(client, nonce = "") {
139
+ if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
140
+ if (!cspCache || cspCache.for !== client) {
141
+ const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(EXTERNAL_BOOTSTRAP, "utf-8").digest("base64")}'`;
142
+ cspCache = {
143
+ for: client,
144
+ value: `script-src ${scriptSrc}; ${CSP_TAIL}`
145
+ };
146
+ }
147
+ return { "Content-Security-Policy": cspCache.value };
148
+ }
149
+ var FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
150
+ var STYLES = `
151
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
152
+ button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
153
+ a { color: #e91e63; text-decoration: none; font-weight: bold; }
154
+ a:hover { text-decoration: underline; }
155
+ nav a { margin-right: 1rem; }
156
+ .rh { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; border-bottom: 2px solid #e91e63; margin-bottom: 1.5rem; padding-bottom: 0.75rem; }
157
+ .rb { font-size: 1.6rem; }
158
+ .rbrand { display: inline-flex; align-items: center; gap: 0.5em; }
159
+ .rlogo { height: 1em; width: 1em; vertical-align: -0.08em; margin-right: 0.2em; }
160
+ @media (max-width: 640px) {
161
+ .rh { flex-direction: column; align-items: flex-start; gap: 0.75rem; }
162
+ nav a:last-child { margin-right: 0; }
163
+ }
164
+ .rn { display: inline-block; margin-left: 1.5rem; }
165
+ .rf { margin-top: 2rem; color: #888; font-size: 0.85rem; }
166
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
167
+ `;
168
+ var STYLES_MIN = STYLES.replace(
169
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
170
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
171
+ ).trim();
172
+ function mergeHeadBlocks(blocks) {
173
+ const byKey = /* @__PURE__ */ new Map();
174
+ const order = [];
175
+ const positional = /* @__PURE__ */ new Map();
176
+ const put = (key, html) => {
177
+ if (!byKey.has(key)) {
178
+ byKey.set(key, html);
179
+ order.push(key);
180
+ }
181
+ };
182
+ for (const block of blocks) {
183
+ for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
184
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
185
+ const tag = m[1].toLowerCase();
186
+ if (tag === "title") continue;
187
+ const attrs = m[2];
188
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
189
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
190
+ let key;
191
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
192
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
193
+ else {
194
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
195
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
196
+ }
197
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
198
+ put(key, marked);
199
+ }
200
+ }
201
+ return order.map((k) => byKey.get(k)).join("\n ");
202
+ }
203
+ function clientScriptTag(client, nonce = "") {
204
+ const n = nonce ? ` nonce="${nonce}"` : "";
205
+ return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
206
+ <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
207
+ }
208
+ function shellOpen(styles = getStyles(), lang = "en", dir = "") {
209
+ const styleTag = styles ? `
210
+ <style>${styles}</style>` : "";
211
+ return `<!DOCTYPE html>
212
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
213
+ <head>
214
+ <meta charset="UTF-8">
215
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
216
+ <title>RoseTack</title>
217
+ <style>${STYLES_MIN}</style>${styleTag}
218
+ ${FAVICON}
219
+ </head>
220
+ <body>
221
+ <div id="app">`;
222
+ }
223
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
224
+ const clientTag = clientScriptTag(client, nonce);
225
+ const mergedHead = mergeHeadBlocks(head);
226
+ const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
227
+ const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
228
+ ${FAVICON}`;
229
+ const headTags = mergedHead ? `
230
+ ${mergedHead}` : "";
231
+ const styleTag = styles ? `
232
+ <style>${styles}</style>` : "";
233
+ const jsTail = js ? `
234
+ <script type="application/json" id="__rosetack_state">${stateJson}</script>
235
+ ${clientTag}` : "";
236
+ const open = js ? '<div id="app">' : "";
237
+ const close = js ? "</div>" : "";
238
+ const shellStyles = js ? `
239
+ <style>${STYLES_MIN}</style>` : "";
240
+ return `<!DOCTYPE html>
241
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
242
+ <head>
243
+ <meta charset="UTF-8">
244
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
245
+ ${titleTag}${shellStyles}${styleTag}
246
+ </head>
247
+ <body>
248
+ ${open}${ssrHtml}${close}${jsTail}
249
+ </body>
250
+ </html>`;
251
+ }
252
+
253
+ // src/cli/edge.ts
254
+ async function createEdgeHandler(outDir) {
255
+ const mod = await import(pathToFileURL(join2(outDir, "server.js")).href);
256
+ let client = null;
257
+ let styles = "";
258
+ try {
259
+ client = await (await import("fs/promises")).readFile(join2(outDir, "client.js"), "utf-8");
260
+ } catch {
261
+ client = null;
262
+ }
263
+ try {
264
+ styles = await (await import("fs/promises")).readFile(join2(outDir, "styles.css"), "utf-8");
265
+ } catch {
266
+ styles = "";
267
+ }
268
+ let broken = /* @__PURE__ */ new Set();
269
+ try {
270
+ broken = new Set(JSON.parse(await (await import("fs/promises")).readFile(join2(outDir, "broken.json"), "utf-8")));
271
+ } catch {
272
+ broken = /* @__PURE__ */ new Set();
273
+ }
274
+ const pageHeaders = (pathname, nonce = "") => {
275
+ const headers = {};
276
+ if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
277
+ const own = mod.headersFor?.(pathname);
278
+ if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
279
+ return headers;
280
+ };
281
+ return async function handle(request) {
282
+ const { pathname, searchParams } = new URL(request.url);
283
+ mod.setQuery?.(Object.fromEntries(searchParams));
284
+ const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks ? { request, url: new URL(request.url), method: request.method, pathname, state: {} } : null;
285
+ if (hookCtx) {
286
+ const short = await mod.runRequestHooks(hookCtx);
287
+ if (short) return mod.runResponseHooks(hookCtx, short);
288
+ }
289
+ if (mod.middleware) {
290
+ const mw = await mod.runMiddleware(request);
291
+ if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
292
+ }
293
+ if (mod.isApi(pathname)) {
294
+ const apiRes = await mod.handleApi(request.method, pathname, request);
295
+ return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
296
+ }
297
+ const form = request.method === "POST" ? await request.formData() : void 0;
298
+ if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
299
+ const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
300
+ const streamed = new Response(null, {
301
+ status: 200,
302
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders(pathname, nonce2) }
303
+ });
304
+ const head = hookCtx ? await mod.runResponseHooks(hookCtx, streamed) : streamed;
305
+ const encoder = new TextEncoder();
306
+ const stream = new ReadableStream({
307
+ async start(controller) {
308
+ const doc = mod.docAttrs(pathname);
309
+ await mod.renderPageStream(
310
+ pathname,
311
+ (chunk) => controller.enqueue(encoder.encode(chunk)),
312
+ shellOpen(styles, doc.lang, doc.dir),
313
+ clientScriptTag(client, nonce2)
314
+ );
315
+ controller.close();
316
+ }
317
+ });
318
+ return new Response(stream, { status: head.status, headers: head.headers });
319
+ }
320
+ const page = await mod.renderPage(pathname, form);
321
+ const nonce = mod.cspNonce?.(pathname) ? mintNonce() : "";
322
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce);
323
+ const buffered = new Response(html, {
324
+ status: page.status ?? 200,
325
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders(pathname, nonce) }
326
+ });
327
+ return hookCtx ? mod.runResponseHooks(hookCtx, buffered) : buffered;
328
+ };
329
+ }
330
+ export {
331
+ createEdgeHandler
332
+ };