rosetack 0.1.1 → 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.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The canonical .rose authoring contract, printed by `rosetack prompt`.
3
+ *
4
+ * Why a command and not a doc page: the audience is as often an AI agent as
5
+ * a human, and the agent needs the contract at the moment it writes code,
6
+ * not a URL to go read. One command, stdout, no network - the same shape as
7
+ * every other tool an agent already shells out to.
8
+ *
9
+ * The content is the compiler's actual rules, in the order a page meets
10
+ * them: file layout, the script block, the template, head and styles,
11
+ * events and actions, the exports, the npm boundary, and the error
12
+ * contract. Anything the compiler REFUSES is listed as a rule here, so a
13
+ * correct page compiles on the first try.
14
+ */
15
+ export const AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
16
+
17
+ rosetack is a zero-hydration web framework: a .rose file compiles to a server
18
+ render plus a client resume bundle, one request per page, no hydration. Write
19
+ the smallest thing that works - the compiler decides what ships.
20
+
21
+ ## File layout (all paths relative to the project root)
22
+
23
+ - src/pages/index.rose -> route /
24
+ - src/pages/about.rose -> route /about
25
+ - src/pages/blog/[id].rose -> route /blog/:id (the param is readable as state \`id()\`)
26
+ - src/pages/[lang]/about.rose -> localized route (see i18n below)
27
+ - src/pages/_layout.rose -> root layout wrapping every route (app-global exports live here)
28
+ - src/pages/_middleware.rose -> server-only request middleware (handle(request), getContext())
29
+ - src/pages/404.rose, 500.rose -> error pages
30
+ - src/pages/api/posts.rose -> JSON API route (export async function GET/POST/...)
31
+ - src/components/Card.rose -> reusable component, imported by relative path
32
+ - src/locales/en.json -> i18n dictionaries (one file per language)
33
+
34
+ ## A page
35
+
36
+ \`\`\`rose
37
+ <script>
38
+ let count = $state(0); // reactive state: read it as count()
39
+ let posts = $data(async () => db.query()); // server data: awaited on the server,
40
+ // resumed on the client - never re-fetched
41
+ const total = count() + 1; // a top-level read AFTER the declaration is fine
42
+ async function like() { // a server action (progressive enhancement)
43
+ return $merge({ likes: 1 });
44
+ }
45
+ </script>
46
+
47
+ <h1>Posts</h1>
48
+ <p>Total: {total}</p>
49
+ <button on:click={() => $setState('count', count() + 1)}>+1</button>
50
+ <form method="POST"><button formaction="?__action=like">Like</button></form>
51
+ \`\`\`
52
+
53
+ Rules the compiler enforces (breaking one fails the build):
54
+
55
+ - The script block is TypeScript. Types, interfaces, \`import type\`, \`as\` casts and
56
+ type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
57
+ - $state / $data declarations are top-level statements. The declared name IS the
58
+ getter: write count() in the template and the script, never bare count.
59
+ - A route param (pages/blog/[id].rose) is read as state too: declare it
60
+ (\`let id = $state('1')\`) and read id() - the server overwrites the default
61
+ with the URL's value, and export const params = { id: [...] } bakes those
62
+ values at build time.
63
+ - $data() is banned in components (src/components/**) - a component renders
64
+ synchronously inside its parent. Fetch in the page or the middleware and pass
65
+ the value down as a prop.
66
+ - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
67
+ trusted-HTML escape hatch - use it only for content you control.
68
+ - Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
69
+ {#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
70
+ - A <slot> with attributes is a named slot and must declare its name:
71
+ <slot name="row" item={post} />. A named slot must be a DIRECT child of the
72
+ component tag - never inside another element or an {#if}/{#each} block.
73
+ - Every component tag needs its matching close tag (or self-closes with />).
74
+ - In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
75
+ through. A <style> inside <head> is document CSS; a <style> in the body is
76
+ the component's scoped stylesheet.
77
+ - Node-only modules (node:fs, better-sqlite3, pg, redis, ...) are REFUSED in
78
+ pages and components: their script ships to the browser. Import them in
79
+ src/pages/_middleware.rose or a pages/api/*.rose handler instead, and pass
80
+ the rows to the page through getContext().
81
+
82
+ ## Events and server actions
83
+
84
+ - on:click={handler} wires a client event. The handler is a named function from
85
+ the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
86
+ - A server action is an exported async function. Call it from a native form
87
+ (method="POST", no JS needed - progressive enhancement) or from any event
88
+ (on:click={like} - one POST, in-place adopt). Its return value is an
89
+ incremental patch: $append(row) / $prepend(row) / $merge({...}).
90
+ - Business failures: throw new ActionError('message', 422, 'field'). It lands
91
+ in ordinary state - $actionError() reads it back, a {#boundary} contains it.
92
+ - beforeAction(name, form) is the per-page guard that vetoes an action.
93
+
94
+ ## Route exports (in the script block, validated at build time)
95
+
96
+ - export const csr = false | true force/assert zero-JS (absent = the compiler decides)
97
+ - export const buffer = true keep this route off the streaming path
98
+ - export const headers = { ... } flat string map, merged over the strict CSP default
99
+ - export const csp = { nonce: true } per-response nonce instead of the hash (route becomes dynamic)
100
+ - export const prefetch = 'off' | 'hover' | 'viewport' | 'all' app-global, root layout only
101
+ - export const bundle = 'inline' | 'split' app-global; 'split' = mode B for large apps
102
+ - export const vitals = true opt into the web-vitals hook
103
+ - export const revalidate = N stale-while-revalidate ISR window, seconds
104
+ - export const params = { id: ['1'] } prerender these param values at build time
105
+ - export const prerender = true (api routes) bake the GET body for static deploys
106
+
107
+ ## i18n
108
+
109
+ src/locales/<lang>.json is a dictionary; a [lang] route segment selects one;
110
+ $t('key', { name }) translates reactively; unknown locales answer 404.
111
+
112
+ ## When a build fails
113
+
114
+ Every compiler failure is structured: { code, file, line, message, hint }.
115
+ Run \`rosetack build --json\` to read it as JSON, fix the named file at the named
116
+ line, and build again. Codes: E-IMPORT (unresolvable .rose import), E-PLUGIN
117
+ (transform threw), E-NODE-ONLY (server-only import in a page/component),
118
+ E-EXPORT (invalid export const value), E-TEMPLATE (unclosed tag / slot
119
+ placement), E-ROUTE (no pages found), E-INTERNAL (installation problem).
120
+
121
+ ## The one invariant worth protecting
122
+
123
+ A route ships ONE request with ZERO hydration: the whole client bundle is
124
+ inlined in the document. Keep it that way - browser-only code (document.,
125
+ window., timers) belongs in onMount, and anything the predicate cannot see
126
+ (inline on* attributes, javascript: URLs, eval) is reported by the build.
127
+ `;
package/src/cli/shell.ts CHANGED
@@ -124,13 +124,34 @@ document.addEventListener('submit', (e) => {
124
124
  e.preventDefault();
125
125
  postForm(new FormData(f));
126
126
  });
127
+ // Dev seam: the live signal graph, readable as JSON. Two callers, one
128
+ // implementation: the dev server's reload bridge snapshots it before a
129
+ // rebuild-triggered reload so the edit lands on the state the developer had,
130
+ // and a devtools extension reads it the same way. It is the same
131
+ // serializeState the zero-hydration resume already ships, so the only new
132
+ // bytes are the assignment.
133
+ window.__rosetack = { state: () => serializeState() };
127
134
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
128
135
  // If the document was rendered for a DIFFERENT route (a static-file server's
129
136
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
130
137
  // client router render the requested route from scratch.
131
138
  const __st = document.getElementById('__rosetack_state');
132
- const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
133
- if (__state.__route === window.location.pathname) {
139
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
140
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
141
+ // the next document (window.__rosetack_resume). The resumed values win over the
142
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
143
+ // the route renders client-side from the bundle rather than adopting the SSR
144
+ // DOM, because a resumed list can be longer than the document's rows and
145
+ // adoption could not add them. Absent in every non-dev document.
146
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
147
+ if (__resumed) {
148
+ const __route = __state.__route;
149
+ __state = Object.assign(__state, __resumed);
150
+ __state.__route = __route;
151
+ }
152
+ if (__resumed) {
153
+ start(__app, window.location.pathname);
154
+ } else if (__state.__route === window.location.pathname) {
134
155
  start(__app, window.location.pathname, true);
135
156
  } else {
136
157
  start(__app, window.location.pathname);
@@ -232,10 +253,26 @@ const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
232
253
  * Merge the route chain's <head> blocks (document order: page first, then its
233
254
  * layouts) into one clean <head> fragment. First occurrence wins per key, so a
234
255
  * page overrides its layouts - matching the client's reverse-order applyHead.
256
+ *
257
+ * Bug report 2026.9.22 11:46: the keyed whitelist used to be title plus
258
+ * meta/link/base and NOTHING else, so a `<style>` block, a
259
+ * `<script type="application/ld+json">` data block and a `<noscript>`
260
+ * fallback were dropped here in silence - the compiler collected them, the
261
+ * merge threw them away, and a CMS theme system had no way to ship its
262
+ * per-request CSS. Every head element now passes through: the keyed
263
+ * singletons keep their name/property/rel/charset identity, and everything
264
+ * else is keyed by id when it has one and by tag+position when it does not,
265
+ * so two layouts' <style> blocks coexist and a page still overrides its
266
+ * layout's. Passthrough elements carry HEAD_ATTR too (the attribute the
267
+ * runtime manages) so a client-side navigation replaces or drops them like
268
+ * any other managed element instead of leaking the previous route's CSS
269
+ * into every route visited after it.
235
270
  */
236
271
  function mergeHeadBlocks(blocks: string[]): string {
237
272
  const byKey = new Map<string, string>();
238
273
  const order: string[] = [];
274
+ // positional keys: tag -> how many unkeyed elements of that tag came before
275
+ const positional = new Map<string, number>();
239
276
  // first occurrence wins: blocks arrive page-first (a page renders inside its
240
277
  // layouts' <slot/>), so the page's title/meta override the layouts'
241
278
  const put = (key: string, html: string) => {
@@ -247,13 +284,24 @@ function mergeHeadBlocks(blocks: string[]): string {
247
284
  for (const block of blocks) {
248
285
  // title carries content, so it needs its own pattern
249
286
  for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put('title', m[0]);
250
- for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
287
+ // One pass over every other head element: a void tag (meta/link/base), a paired one
288
+ // (style/script/noscript, and any tag a route writes), or a self-closed one.
289
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
251
290
  const tag = m[1].toLowerCase();
252
- const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
253
- const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
291
+ if (tag === 'title') continue; // handled above, with its own key
292
+ const attrs = m[2];
293
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
294
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
295
+ let key: string;
296
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
297
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
298
+ else {
299
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
300
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
301
+ }
254
302
  // keyed tags carry their key (must match HEAD_ATTR in the runtime) so the client
255
303
  // adopts these SSR-injected elements in place on the first navigation instead of …
256
- const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
304
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
257
305
  put(key, marked);
258
306
  }
259
307
  }
@@ -316,17 +364,19 @@ export function buildShell(ssrHtml: string, stateJson: string, client: string |
316
364
  const jsTail = js
317
365
  ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
318
366
  : '';
367
+ const open = js ? '<div id="app">' : '';
368
+ const close = js ? '</div>' : '';
369
+ const shellStyles = js ? `\n <style>${STYLES_MIN}</style>` : '';
319
370
 
320
371
  return `<!DOCTYPE html>
321
372
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
322
373
  <head>
323
374
  <meta charset="UTF-8">
324
375
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
325
- ${titleTag}
326
- <style>${STYLES_MIN}</style>${styleTag}
376
+ ${titleTag}${shellStyles}${styleTag}
327
377
  </head>
328
378
  <body>
329
- <div id="app">${ssrHtml}</div>${jsTail}
379
+ ${open}${ssrHtml}${close}${jsTail}
330
380
  </body>
331
381
  </html>`;
332
382
  }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * A compiler error shaped for its reader - who is as often an AI agent as a
3
+ * human. Every failure the compiler throws on purpose carries:
4
+ *
5
+ * code a stable identifier (E-EXPORT, E-TEMPLATE, ...) an agent can
6
+ * branch on and a human can grep across a build log
7
+ * file the .rose file (or directory) at fault
8
+ * line the line inside it, when the compiler knows the position
9
+ * hint the fix, in one sentence
10
+ *
11
+ * `rosetack build --json` prints these as a JSON envelope on stdout, so an
12
+ * agent can parse the failure and patch the file without scraping prose.
13
+ * The human output prints the message and the hint. Errors that are NOT
14
+ * RoseErrors (a crash inside a plugin's own code, a framework bug) keep
15
+ * their stack: those are not the developer's to fix from a code alone.
16
+ */
17
+
18
+ export interface RoseErrorInfo {
19
+ code: string;
20
+ file?: string;
21
+ line?: number;
22
+ message: string;
23
+ hint?: string;
24
+ }
25
+
26
+ export class RoseError extends Error {
27
+ readonly code: string;
28
+ readonly file?: string;
29
+ readonly line?: number;
30
+ readonly hint?: string;
31
+
32
+ constructor(code: string, message: string, opts: { file?: string; line?: number; hint?: string } = {}) {
33
+ super(message);
34
+ this.name = 'RoseError';
35
+ this.code = code;
36
+ this.file = opts.file;
37
+ this.line = opts.line;
38
+ this.hint = opts.hint;
39
+ }
40
+
41
+ info(): RoseErrorInfo {
42
+ // code -> file -> line -> message -> hint: the order the prompt doc
43
+ // documents, so a reader parsing the envelope finds the location first
44
+ const info = { code: this.code } as RoseErrorInfo;
45
+ if (this.file !== undefined) info.file = this.file;
46
+ if (this.line !== undefined) info.line = this.line;
47
+ info.message = this.message;
48
+ if (this.hint !== undefined) info.hint = this.hint;
49
+ return info;
50
+ }
51
+ }
52
+
53
+ /** The 1-based line of `index` inside `src`. */
54
+ export function lineOf(src: string, index: number): number {
55
+ let line = 1;
56
+ const end = Math.min(index, src.length);
57
+ for (let i = 0; i < end; i++) {
58
+ if (src[i] === '\n') line++;
59
+ }
60
+ return line;
61
+ }
62
+
63
+ /** The line of a regex match inside `src` - undefined when there is no match
64
+ * (the position is optional on a match array, and the call sites that have
65
+ * one always matched). */
66
+ export function lineAt(src: string, match?: RegExpMatchArray | null): number | undefined {
67
+ return match && match.index !== undefined ? lineOf(src, match.index) : undefined;
68
+ }
69
+
70
+ /** Shape any thrown value into the info object the --json envelope prints. */
71
+ export function errorInfo(err: unknown): RoseErrorInfo {
72
+ if (err instanceof RoseError) return err.info();
73
+ return { code: 'E-UNKNOWN', message: err instanceof Error ? err.message : String(err) };
74
+ }