rosetack 0.1.4 → 0.1.5

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/src/cli/prompt.ts CHANGED
@@ -46,6 +46,9 @@ Rules the compiler enforces (breaking one fails the build):
46
46
  $persist is $state backed by localStorage: let theme = $persist('light') —
47
47
  the value survives reloads (SSR renders the initial; the client re-seeds
48
48
  from storage at boot).
49
+ $derived is computed state: let sq = $derived(n * n) — a read-only getter
50
+ that recomputes from the signals its expression reads; $setState on it is a
51
+ build error. Top-level only (in a function body, use a plain const arrow).
49
52
  - A route param (pages/blog/[id].rose) is read as state too: declare it
50
53
  (\`let id = $state('1')\`) and read id() - the server overwrites the default
51
54
  with the URL's value, and export const params = { id: [...] } bakes those
@@ -54,7 +57,9 @@ Rules the compiler enforces (breaking one fails the build):
54
57
  synchronously inside its parent. Fetch in the page or the middleware and pass
55
58
  the value down as a prop.
56
59
  - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
57
- trusted-HTML escape hatch - use it only for content you control. {@const name
60
+ trusted-HTML escape hatch - use it only for content you control.
61
+ {@debug a, b} logs those values (as they are AT that point in the render);
62
+ bare {@debug} also breaks into the debugger. Neither emits HTML. {@const name
58
63
  = expr} is a template-level binding: it evaluates once and is visible to every
59
64
  expression that follows in the same scope (use it to name a computed value
60
65
  inside {#each} without re-evaluating, or to shorten a long expression).
@@ -66,9 +71,50 @@ Rules the compiler enforces (breaking one fails the build):
66
71
  {#key expr}...{/key} (re-creates the
67
72
  body whenever expr changes), {#boundary}...{:fallback}...{/boundary} (the
68
73
  fallback renders on a throw; {$boundaryError()?.message} reads the caught
69
- error), {#island name="x"}...{/island} (partial hydration) and
74
+ error), {#island name="x"}...{/island} (partial hydration) and
70
75
  {#defer}...{/defer} (progressive render; hold=N keeps the skeleton up at
71
- least N ms). {:else} / {:else if} must sit inside an {#if} block.
76
+ least N ms), and {#await promise}...{:then value}...{:catch error}...{/await}
77
+ (the server renders the pending branch, the client flips to the resolved
78
+ value once the promise settles, or to the caught error if it rejects; the
79
+ {:then} / {:catch} names are in scope only inside their branch, and {:catch}
80
+ is optional). There is NO {:else} branch of its own: a bare {:else} with no
81
+ block around it is a build error - inside {#each} it means "the list is
82
+ empty", inside {#if} it is the final else.
83
+ - Keyed each: {#each todos() as t (t.id)} — the key makes wire() reconcile:
84
+ rows whose key and rendered html are unchanged KEEP their DOM nodes (focus,
85
+ unbound input text, loaded images survive; reorders become moves). Rows
86
+ with handlers/actions/refs/transitions/components rebuild fresh. The key
87
+ needs a named item — {#each xs as x (x.id)}, not a destructuring pattern.
88
+ - Snippets: {#snippet name(a, b)}...{/snippet} defines a parameterized
89
+ fragment; {@render name(x, y)} calls it and inlines the markup. Define the
90
+ snippet BEFORE the render call (top-down execution order — the compiler
91
+ rejects the reverse). Reactive content inside works per call.
92
+ - Transitions: transition:fade (both directions), in:fade (enter only),
93
+ out:fade (mounts at rest, leave only). Built-ins: fade, slide, fly, zoom,
94
+ slide-up/down/left/right, scale, spin, blur, stagger; params via
95
+ transition:fade={300} or transition:fade={duration: 300} (the trailing
96
+ number wins), or the bare name (300 ms default). Custom: register
97
+ globalThis.__rosetackTransitions.NAME = (el, duration, phase) => cleanup? —
98
+ a transition:NAME that is not a built-in falls through to it (phase
99
+ 'both'/'in'/'out'; built-ins always win).
100
+ - $actionPending() is true while a server action is in flight: use it to
101
+ disable the submit button reactively ({#if $actionPending()}).
102
+ - $setState('k', (x) => x + 1) supports a FUNCTIONAL UPDATER: when the new
103
+ value is a function it receives the current value and returns the next one.
104
+ (State that must literally store a function cannot use this form.)
105
+ - <input type="number" bind:value={n}>: clearing the field stores 'null'
106
+ (NOT 'NaN') so bound math (n() + 1) stays clean instead of going NaN. The
107
+ empty field renders as '' on write-back.
108
+ - Scroll listeners are passive by default (they cannot preventDefault), which
109
+ keeps the constant scroll event off the main-thread critical path.
110
+ - Scoped CSS: component <style> rules scope under the component. Use
111
+ :global(X) to unscope one compound (.card :global(.md)); a selector made
112
+ only of :global(...) groups emits fully unscoped (:global(body){...}).
113
+ - animate:flip={duration: 300} (or animate:flip={300}) passes a DURATION
114
+ param to the FLIP animation; the trailing number is parsed even though object
115
+ params carry their own colons. Registered animation names work the same way.
116
+ - <select multiple bind:value={arr}> binds an ARRAY of selected values
117
+ (declare $state([])); state changes drive option.selected properties.
72
118
  - Two-way binding: <input bind:value={q}> / <input type="checkbox"
73
119
  bind:checked={on}> / <select bind:value={s}>. Numeric inputs coerce through
74
120
  valueAsNumber. Radio groups: <input type="radio" value="free"
@@ -86,7 +132,10 @@ Rules the compiler enforces (breaking one fails the build):
86
132
  update half re-runs when text changes; the param arrives JSON-parsed.
87
133
  - A <slot> with attributes is a named slot and must declare its name:
88
134
  <slot name="row" item={post} />. A named slot must be a DIRECT child of the
89
- component tag - never inside another element or an {#if}/{#each} block.
135
+ component tag, OR wrapped by a single {#if}/{#each}/{#boundary} block (F21:
136
+ the block is reconstructed around the slot and the lifted content reads the
137
+ parent scope, so a gated slot still projects). A named slot inside a plain
138
+ wrapper element (a <div>, not a block) is still a build error.
90
139
  - Every component tag needs its matching close tag (or self-closes with />).
91
140
  - In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
92
141
  through. A <style> inside <head> is document CSS; a <style> in the body is
package/src/cli/shell.ts CHANGED
@@ -67,18 +67,39 @@ if (!__app) {
67
67
  }
68
68
  // Native View Transitions around client-side navigation (progressive:
69
69
  // browsers without the API navigate normally, no polyfill, no CSS required).
70
- function __navigate(pathname) {
71
- const paint = () => start(__app, pathname);
70
+ // F35: stash the CURRENT entry's scroll position into its history state
71
+ // before a new push - the browser only restores scroll on full page loads; a
72
+ // pjax swap would land wherever the swap left it.
73
+ function __saveScroll() {
74
+ try {
75
+ const s = history.state || {};
76
+ history.replaceState(Object.assign({}, s, { __rosetackScroll: window.scrollY }), '');
77
+ } catch (e) { /* history state unavailable (file:// edge): best effort */ }
78
+ }
79
+ function __navigate(pathname, restore) {
80
+ const paint = () => {
81
+ const p = start(__app, pathname);
82
+ if (restore) {
83
+ // back/forward: restore the entry's scroll (top when it has none)
84
+ const s = history.state || {};
85
+ const y = typeof s.__rosetackScroll === 'number' ? s.__rosetackScroll : 0;
86
+ return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
87
+ }
88
+ // a fresh navigation starts at the top, like a full page load
89
+ window.scrollTo(0, 0);
90
+ return p;
91
+ };
72
92
  if (document.startViewTransition) {
73
93
  return document.startViewTransition(paint).updateCallbackDone;
74
94
  }
75
95
  return paint();
76
96
  }
77
- window.addEventListener('popstate', () => __navigate(window.location.pathname));
97
+ window.addEventListener('popstate', () => __navigate(window.location.pathname, true));
78
98
  document.addEventListener('click', (e) => {
79
99
  const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
80
100
  if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
81
101
  e.preventDefault();
102
+ __saveScroll();
82
103
  history.pushState(null, '', a.getAttribute('href'));
83
104
  __navigate(window.location.pathname);
84
105
  }
@@ -186,6 +207,15 @@ function bootstrap(): string {
186
207
  }
187
208
 
188
209
  const 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'`;
210
+
211
+
212
+ const BASELINE_SECURITY_HEADERS: Record<string, string> = {
213
+ 'x-content-type-options': 'nosniff',
214
+ 'x-frame-options': 'DENY',
215
+ 'referrer-policy': 'strict-origin-when-cross-origin',
216
+ 'permissions-policy': 'accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), fullscreen=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), serial=(), usb=(), xr-spatial-tracking=()',
217
+ };
218
+
189
219
  let cspCache: { for: string | null; value: string } | null = null;
190
220
  let EXTERNAL_BOOTSTRAP_CACHE: string | null = null;
191
221
  function externalBootstrap(): string {
@@ -242,7 +272,11 @@ export function mintNonce(): string {
242
272
  * the route opts into, per route, not a framework default.
243
273
  */
244
274
  export function securityHeaders(client: string | null, nonce = ''): Record<string, string> {
245
- if (nonce) return { 'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
275
+ const headers: Record<string, string> = { ...BASELINE_SECURITY_HEADERS };
276
+ if (nonce) {
277
+ headers['Content-Security-Policy'] = `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}`;
278
+ return headers;
279
+ }
246
280
  if (!cspCache || cspCache.for !== client) {
247
281
  const scriptSrc = client
248
282
  ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
@@ -252,7 +286,8 @@ export function securityHeaders(client: string | null, nonce = ''): Record<strin
252
286
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`,
253
287
  };
254
288
  }
255
- return { 'Content-Security-Policy': cspCache.value };
289
+ headers['Content-Security-Policy'] = cspCache.value;
290
+ return headers;
256
291
  }
257
292
 
258
293
  const 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==">';
@@ -0,0 +1,54 @@
1
+
2
+
3
+ type ShutdownHook = {
4
+ name: string;
5
+ fn: () => void | Promise<void>;
6
+ };
7
+
8
+ type HookResult = { name: string; ok: boolean; error?: string };
9
+
10
+ const shutdownHooks: ShutdownHook[] = [];
11
+
12
+
13
+ let draining: Promise<HookResult[]> | null = null;
14
+
15
+ (globalThis as unknown as { __rosetackOnShutdown?: typeof onShutdown }).__rosetackOnShutdown =
16
+ onShutdown;
17
+ (globalThis as unknown as { __rosetackRunShutdownHooks?: typeof runShutdownHooks }).__rosetackRunShutdownHooks =
18
+ runShutdownHooks;
19
+
20
+ /** Returns an unregister function - a hot-swapped client must drop its old hook. */
21
+ export function onShutdown(name: string, fn: () => void | Promise<void>): () => void {
22
+ const hook: ShutdownHook = { name, fn };
23
+ shutdownHooks.push(hook);
24
+ return () => {
25
+ const at = shutdownHooks.indexOf(hook);
26
+ if (at !== -1) shutdownHooks.splice(at, 1);
27
+ };
28
+ }
29
+
30
+ /** Never rejects; a throwing hook is reported and the rest still run. */
31
+ export function runShutdownHooks(reason: string): Promise<HookResult[]> {
32
+ if (draining) return draining;
33
+ draining = (async () => {
34
+ const results: HookResult[] = [];
35
+ for (const hook of shutdownHooks.slice()) {
36
+ try {
37
+ await hook.fn();
38
+ results.push({ name: hook.name, ok: true });
39
+ } catch (err) {
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ results.push({ name: hook.name, ok: false, error: message });
42
+ console.error(`[rosetack] shutdown hook ${hook.name} failed (${reason}):`, message);
43
+ }
44
+ }
45
+ return results;
46
+ })().finally(() => {
47
+ draining = null;
48
+ });
49
+ return draining;
50
+ }
51
+
52
+ export function shutdownHookCount(): number {
53
+ return shutdownHooks.length;
54
+ }