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
package/dist-cli/edge.mjs CHANGED
@@ -21,8 +21,26 @@ function getStyles() {
21
21
  return "";
22
22
  }
23
23
  }
24
- var BOOTSTRAP = esbuild.transformSync(`
25
- const __app = document.getElementById('app');
24
+ var BOOTSTRAP_SOURCE = `
25
+ // shell = false: the document's SSR content sits directly in <body> - no
26
+ // #app wrapper, no demo styles, so a real theme's CSS owns the document from
27
+ // the first byte (and a JS-less visitor never sees either). The bundle still
28
+ // runs, and it still needs its container: wrap the content once, here, before
29
+ // any theme script executes (module scripts run before DOMContentLoaded). The
30
+ // wrapper is a plain unstyled div, so the re-parent is visually inert; every
31
+ // later path - adoption, navigation, forms - is then the ordinary one.
32
+ let __app = document.getElementById('app');
33
+ if (!__app) {
34
+ __app = document.createElement('div');
35
+ __app.id = 'app';
36
+ // scripts stay outside the wrapper, exactly where the dressed document
37
+ // keeps them: the state element and the running module must survive a
38
+ // navigation's innerHTML swap (they are the document's, not the route's).
39
+ for (const node of Array.from(document.body.children)) {
40
+ if (node.tagName !== 'SCRIPT') __app.appendChild(node);
41
+ }
42
+ document.body.appendChild(__app);
43
+ }
26
44
  // Native View Transitions around client-side navigation (progressive:
27
45
  // browsers without the API navigate normally, no polyfill, no CSS required).
28
46
  function __navigate(pathname) {
@@ -85,13 +103,15 @@ document.addEventListener('submit', (e) => {
85
103
  e.preventDefault();
86
104
  postForm(new FormData(f));
87
105
  });
88
- // Dev seam: the live signal graph, readable as JSON. Two callers, one
106
+ // Dev seam: the live signal graph, readable as JSON. Three callers, one
89
107
  // implementation: the dev server's reload bridge snapshots it before a
90
108
  // 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() };
109
+ // and the devtools extension (devtools/) reads it the same way - the signal
110
+ // graph plus the prefetch counters, which is the whole observable state of a
111
+ // running page. Both are DIRECT references (no wrapper arrow): the names take
112
+ // no arguments, so the call is identical and every document that carries the
113
+ // bundle pays eleven bytes for the pair instead of forty.
114
+ window.__rosetack = { state: serializeState, prefetch: prefetchStats };
95
115
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
96
116
  // If the document was rendered for a DIFFERENT route (a static-file server's
97
117
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
@@ -110,23 +130,61 @@ if (__resumed) {
110
130
  __state = Object.assign(__state, __resumed);
111
131
  __state.__route = __route;
112
132
  }
113
- if (__resumed) {
133
+ // A NOT-FOUND document (the server stamps __notFound onto its state) boots
134
+ // into the app's own 404 route: the URL matches no route - or a catch-all
135
+ // whose resolver threw notFound(), whose key sits null in the resumed state
136
+ // and whose template would dereference it into a 500. startNotFound paints
137
+ // the not-found route from the resumed state instead (zero requests).
138
+ if (__state.__notFound) {
139
+ startNotFound(__app, window.location.pathname);
140
+ } else if (__resumed) {
114
141
  start(__app, window.location.pathname);
115
142
  } else if (__state.__route === window.location.pathname) {
116
143
  start(__app, window.location.pathname, true);
117
144
  } else {
118
145
  start(__app, window.location.pathname);
119
146
  }
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'`;
147
+ `;
148
+ var BOOTSTRAP_CACHE = null;
149
+ function bootstrap() {
150
+ if (BOOTSTRAP_CACHE === null) {
151
+ if (globalThis.__rosetack_SKIP_MINIFY) {
152
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
153
+ } else {
154
+ try {
155
+ BOOTSTRAP_CACHE = esbuild.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
156
+ } catch {
157
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
158
+ }
159
+ }
160
+ }
161
+ return BOOTSTRAP_CACHE;
162
+ }
163
+ var CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
122
164
  var cspCache = null;
123
- var EXTERNAL_BOOTSTRAP = `
124
- import { start, prefetch, postForm } from '/client.js';
125
- ${BOOTSTRAP}`;
165
+ var EXTERNAL_BOOTSTRAP_CACHE = null;
166
+ function externalBootstrap() {
167
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `
168
+ import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';
169
+ ${bootstrap()}`;
170
+ return EXTERNAL_BOOTSTRAP_CACHE;
171
+ }
126
172
  function inlineScript(client) {
173
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
174
+ let body = client;
175
+ let aliases = "";
176
+ if (m) {
177
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
178
+ aliases = m[1].split(",").map((pair) => {
179
+ const parts = pair.split(" as ").map((x) => x.trim());
180
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
181
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
182
+ }).join("");
183
+ }
127
184
  return `
128
- ${client}
129
- ${BOOTSTRAP}`;
185
+ ${body}
186
+ ${aliases}
187
+ ${bootstrap()}`;
130
188
  }
131
189
  function mintNonce() {
132
190
  const bytes = new Uint8Array(16);
@@ -138,7 +196,7 @@ function mintNonce() {
138
196
  function securityHeaders(client, nonce = "") {
139
197
  if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
140
198
  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")}'`;
199
+ const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(externalBootstrap(), "utf-8").digest("base64")}'`;
142
200
  cspCache = {
143
201
  for: client,
144
202
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`
@@ -203,73 +261,117 @@ function mergeHeadBlocks(blocks) {
203
261
  function clientScriptTag(client, nonce = "") {
204
262
  const n = nonce ? ` nonce="${nonce}"` : "";
205
263
  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>`;
264
+ <script type="module"${n}>${externalBootstrap()}</script>`;
207
265
  }
208
- function shellOpen(styles = getStyles(), lang = "en", dir = "") {
266
+ function shellOpen(styles = getStyles(), lang = "en", dir = "", shell = true) {
209
267
  const styleTag = styles ? `
210
268
  <style>${styles}</style>` : "";
269
+ const demoStyles = shell ? `
270
+ <style>${STYLES_MIN}</style>` : "";
271
+ const appOpen = shell ? `
272
+ <div id="app">` : "";
211
273
  return `<!DOCTYPE html>
212
274
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
213
275
  <head>
214
276
  <meta charset="UTF-8">
215
277
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
216
- <title>RoseTack</title>
217
- <style>${STYLES_MIN}</style>${styleTag}
278
+ <title>RoseTack</title>${demoStyles}${styleTag}
218
279
  ${FAVICON}
219
280
  </head>
220
- <body>
221
- <div id="app">`;
281
+ <body>${appOpen}`;
222
282
  }
223
- function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
283
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
224
284
  const clientTag = clientScriptTag(client, nonce);
225
285
  const mergedHead = mergeHeadBlocks(head);
286
+ const headStamped = nonce ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs) => /\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`) : mergedHead;
287
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ""}`;
288
+ let bodyAttrs = "";
289
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag, attrs) => {
290
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, "");
291
+ if (tag === "html") htmlAttrs = clean;
292
+ else bodyAttrs = clean;
293
+ return "";
294
+ });
226
295
  const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
227
296
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
228
297
  ${FAVICON}`;
229
- const headTags = mergedHead ? `
230
- ${mergedHead}` : "";
298
+ const headTags = headClean ? `
299
+ ${headClean}` : "";
231
300
  const styleTag = styles ? `
232
301
  <style>${styles}</style>` : "";
302
+ const stateSafe = stateJson.replace(/</g, "\\u003c");
233
303
  const jsTail = js ? `
234
- <script type="application/json" id="__rosetack_state">${stateJson}</script>
304
+ <script type="application/json" id="__rosetack_state">${stateSafe}</script>
235
305
  ${clientTag}` : "";
236
- const open = js ? '<div id="app">' : "";
237
- const close = js ? "</div>" : "";
238
- const shellStyles = js ? `
306
+ const open = js && shell ? '<div id="app">' : "";
307
+ const close = js && shell ? "</div>" : "";
308
+ const shellStyles = js && shell ? `
239
309
  <style>${STYLES_MIN}</style>` : "";
240
310
  return `<!DOCTYPE html>
241
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
311
+ <html${htmlAttrs}>
242
312
  <head>
243
313
  <meta charset="UTF-8">
244
314
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
245
315
  ${titleTag}${shellStyles}${styleTag}
246
316
  </head>
247
- <body>
317
+ <body${bodyAttrs}>
248
318
  ${open}${ssrHtml}${close}${jsTail}
249
319
  </body>
250
320
  </html>`;
251
321
  }
252
322
 
253
323
  // src/cli/edge.ts
254
- async function createEdgeHandler(outDir) {
255
- const mod = await import(pathToFileURL(join2(outDir, "server.js")).href);
324
+ function crossSiteWrite(request) {
325
+ const m = request.method;
326
+ if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
327
+ const origin = request.headers.get("origin");
328
+ if (origin) {
329
+ let host;
330
+ try {
331
+ host = new URL(origin).host;
332
+ } catch {
333
+ return new Response("Cross-site request blocked (unparsable Origin header)", { status: 403 });
334
+ }
335
+ return host === new URL(request.url).host ? null : new Response("Cross-site request blocked (Origin does not match Host)", { status: 403 });
336
+ }
337
+ const site = request.headers.get("sec-fetch-site");
338
+ if (site && site !== "same-origin" && site !== "same-site" && site !== "none") {
339
+ return new Response(`Cross-site request blocked (sec-fetch-site: ${site})`, { status: 403 });
340
+ }
341
+ return null;
342
+ }
343
+ async function createEdgeHandler(outDir, preloaded) {
344
+ const mod = preloaded?.server ?? await import(pathToFileURL(join2(outDir, "server.js")).href);
256
345
  let client = null;
257
346
  let styles = "";
258
- try {
259
- client = await (await import("fs/promises")).readFile(join2(outDir, "client.js"), "utf-8");
260
- } catch {
261
- client = null;
347
+ if (preloaded && "client" in preloaded) {
348
+ client = preloaded.client ?? null;
349
+ } else {
350
+ try {
351
+ client = await (await import("fs/promises")).readFile(join2(outDir, "client.js"), "utf-8");
352
+ } catch {
353
+ client = null;
354
+ }
262
355
  }
263
- try {
264
- styles = await (await import("fs/promises")).readFile(join2(outDir, "styles.css"), "utf-8");
265
- } catch {
266
- styles = "";
356
+ if (client && client.includes("chunks/")) client = null;
357
+ if (preloaded && "styles" in preloaded) {
358
+ styles = preloaded.styles ?? "";
359
+ } else {
360
+ try {
361
+ styles = await (await import("fs/promises")).readFile(join2(outDir, "styles.css"), "utf-8");
362
+ } catch {
363
+ styles = "";
364
+ }
267
365
  }
268
366
  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();
367
+ if (preloaded && "broken" in preloaded) {
368
+ broken = new Set(preloaded.broken);
369
+ } else {
370
+ try {
371
+ broken = new Set(JSON.parse(await (await import("fs/promises")).readFile(join2(outDir, "broken.json"), "utf-8")));
372
+ } catch {
373
+ broken = /* @__PURE__ */ new Set();
374
+ }
273
375
  }
274
376
  const pageHeaders = (pathname, nonce = "") => {
275
377
  const headers = {};
@@ -279,7 +381,13 @@ async function createEdgeHandler(outDir) {
279
381
  return headers;
280
382
  };
281
383
  return async function handle(request) {
384
+ const refused = crossSiteWrite(request);
385
+ if (refused) return refused;
282
386
  const { pathname, searchParams } = new URL(request.url);
387
+ const canonical = pathname.replace(/\/+$/, "") || "/";
388
+ if (canonical !== pathname) {
389
+ return new Response(null, { status: 308, headers: { location: canonical + new URL(request.url).search } });
390
+ }
283
391
  mod.setQuery?.(Object.fromEntries(searchParams));
284
392
  const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks ? { request, url: new URL(request.url), method: request.method, pathname, state: {} } : null;
285
393
  if (hookCtx) {
@@ -295,6 +403,7 @@ async function createEdgeHandler(outDir) {
295
403
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
296
404
  }
297
405
  const form = request.method === "POST" ? await request.formData() : void 0;
406
+ if (form) mod.invalidateRenderCache?.();
298
407
  if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
299
408
  const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
300
409
  const streamed = new Response(null, {
@@ -309,7 +418,7 @@ async function createEdgeHandler(outDir) {
309
418
  await mod.renderPageStream(
310
419
  pathname,
311
420
  (chunk) => controller.enqueue(encoder.encode(chunk)),
312
- shellOpen(styles, doc.lang, doc.dir),
421
+ shellOpen(styles, doc.lang, doc.dir, !mod.shellOff?.(pathname)),
313
422
  clientScriptTag(client, nonce2)
314
423
  );
315
424
  controller.close();
@@ -317,9 +426,11 @@ async function createEdgeHandler(outDir) {
317
426
  });
318
427
  return new Response(stream, { status: head.status, headers: head.headers });
319
428
  }
320
- const page = await mod.renderPage(pathname, form);
429
+ const cookieHeader = request.headers.get("cookie") || "";
430
+ const memoHit = !form && mod.isCachedRoute?.(pathname) ? mod.peekRenderCache?.(pathname, cookieHeader) : null;
431
+ const page = memoHit ?? (mod.renderPageCached && !form ? await mod.renderPageCached(pathname, cookieHeader) : await mod.renderPage(pathname, form));
321
432
  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);
433
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
323
434
  const buffered = new Response(html, {
324
435
  status: page.status ?? 200,
325
436
  headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders(pathname, nonce) }