clarusjs 0.1.0 → 0.3.0

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.
@@ -1,25 +1,34 @@
1
1
  // Syntax tree → IR: static HTML chunks, holes (reactive or not), child components, events. Build-time checks live here.
2
2
  import { ClarusError } from './errors.js';
3
- import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames } from './script.js';
3
+ import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
4
+ const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
4
5
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
5
6
  export function lower(parsed, file, source) {
6
7
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
7
8
  const stateful = !!parsed.script;
8
- const signals = parsed.script ? analyzeScript(parsed.script.code, file, source, parsed.script.start) : new Map();
9
+ const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
10
+ const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
9
11
  // A hole is reactive if it reads anything the script declares: a signal directly, or a function/value that may read one.
10
12
  // text()'s effect tracks the real dependencies, so over-marking only costs a pair of comment markers.
11
13
  const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
12
14
  const components = new Set(parsed.imports.map((i) => i.name));
13
15
  const nodes = [];
16
+ let out = nodes; // where lowering writes; switched while lowering a component's children
14
17
  const events = [];
15
18
  let holeCount = 0;
16
19
  let eventElementCount = 0;
20
+ let attrElementCount = 0;
21
+ let blockCount = 0;
22
+ let forCount = 0;
23
+ let regionCount = 0;
24
+ let loopNames = new Set(); // @for item and $index names in scope: they make holes inside rows reactive
25
+ let scopeKey; // the @if branch being lowered, for events
17
26
  const emitStatic = (html) => {
18
- const last = nodes[nodes.length - 1];
27
+ const last = out[out.length - 1];
19
28
  if (last?.kind === 'static')
20
29
  last.html += html;
21
30
  else
22
- nodes.push({ kind: 'static', html });
31
+ out.push({ kind: 'static', html });
23
32
  };
24
33
  for (const input of parsed.inputs)
25
34
  if (input.default !== undefined)
@@ -29,50 +38,170 @@ export function lower(parsed, file, source) {
29
38
  function visit(node, rawText) {
30
39
  if (node.type === 'text')
31
40
  return emitStatic(node.value);
41
+ if (node.type === 'fill')
42
+ return fail('@slot only works directly inside a component tag', node.start);
43
+ if (node.type === 'if') {
44
+ const block = stateful ? blockCount++ : -1;
45
+ const parent = out;
46
+ const parentScope = scopeKey;
47
+ const branches = node.branches.map((b, i) => {
48
+ if (b.cond !== null)
49
+ checkExpr(b.cond, file, source, b.condStart);
50
+ const branchNodes = [];
51
+ out = branchNodes;
52
+ if (stateful)
53
+ scopeKey = `${block}.${i}`;
54
+ b.children.forEach((child) => visit(child, rawText));
55
+ return { cond: b.cond, nodes: branchNodes };
56
+ });
57
+ out = parent;
58
+ scopeKey = parentScope;
59
+ out.push({ kind: 'if', branches, block });
60
+ return;
61
+ }
62
+ if (node.type === 'for') {
63
+ checkExpr(node.list, file, source, node.headStart);
64
+ if (node.track !== null)
65
+ checkExpr(node.track, file, source, node.headStart);
66
+ const block = stateful ? forCount++ : -1;
67
+ const parent = out;
68
+ const parentScope = scopeKey;
69
+ const parentLoop = loopNames;
70
+ const lowerInto = (children, key, names) => {
71
+ const list = [];
72
+ out = list;
73
+ loopNames = names;
74
+ if (stateful)
75
+ scopeKey = key;
76
+ children.forEach((child) => visit(child, rawText));
77
+ return list;
78
+ };
79
+ const nodes = lowerInto(node.children, `f${block}`, new Set([...parentLoop, node.item, '$index']));
80
+ const empty = node.empty ? lowerInto(node.empty, `f${block}e`, parentLoop) : null;
81
+ out = parent;
82
+ scopeKey = parentScope;
83
+ loopNames = parentLoop;
84
+ out.push({ kind: 'for', item: node.item, list: node.list, track: node.track, nodes, empty, block });
85
+ return;
86
+ }
87
+ if (node.type === 'raw')
88
+ return emitStatic(node.value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'));
32
89
  if (node.type === 'expr') {
33
90
  checkExpr(node.expr, file, source, node.start);
34
- const reactive = referencesNames(node.expr, scriptScope);
91
+ const reactive = stateful && (referencesNames(node.expr, scriptScope) || referencesNames(node.expr, loopNames));
35
92
  if (reactive && rawText)
36
93
  fail(`reactive {{ }} inside <${rawText}> is not supported yet (it cannot hold update markers)`, node.start);
37
- nodes.push({ kind: 'hole', expr: node.expr, reactive, index: reactive ? holeCount++ : -1 });
94
+ out.push({ kind: 'hole', expr: node.expr, reactive, index: reactive ? holeCount++ : -1 });
38
95
  return;
39
96
  }
40
97
  if (components.has(node.tag)) {
41
- if (stateful)
42
- fail('components inside a stateful component are not supported yet', node.start);
43
- if (node.children.length)
44
- fail('slots are not supported yet', node.start);
45
98
  const props = [];
99
+ let attach;
46
100
  for (const a of node.attrs) {
47
101
  if (a.kind === 'prop') {
48
102
  checkExpr(a.expr, file, source, a.start);
49
103
  props.push({ name: a.name, expr: a.expr });
50
104
  }
105
+ else if (a.kind === 'static' && a.name === 'attach') {
106
+ // When the island's code loads in the browser (see runtime/loader.ts).
107
+ if (typeof a.value !== 'string' || !ATTACH_MODES.includes(a.value))
108
+ fail(`attach must be one of ${ATTACH_MODES.join(', ')}`, a.start);
109
+ attach = a.value;
110
+ }
111
+ else
112
+ fail(`component <${node.tag}> only takes [prop] bindings and attach="…"`, a.start);
113
+ }
114
+ // Content is rendered here, in this component's scope, and handed to the child for its slots.
115
+ const hasContent = node.children.some((c) => c.type !== 'text' || c.value.trim());
116
+ const readsState = props.some((p) => referencesNames(p.expr, scriptScope) || referencesNames(p.expr, loopNames));
117
+ const region = stateful && (hasContent || readsState) ? regionCount++ : -1;
118
+ const parentScope = scopeKey;
119
+ if (region >= 0)
120
+ scopeKey = `c${region}`;
121
+ const lowerList = (list) => {
122
+ const nodes_ = [];
123
+ const parent = out;
124
+ out = nodes_;
125
+ list.forEach((child) => visit(child, rawText));
126
+ out = parent;
127
+ return nodes_;
128
+ };
129
+ const fills = [];
130
+ for (const child of node.children) {
131
+ if (child.type !== 'fill')
132
+ continue;
133
+ if (fills.some((f) => f.name === child.name))
134
+ fail(`slot "${child.name}" is filled twice`, child.start);
135
+ fills.push({ name: child.name, nodes: lowerList(child.children) });
136
+ }
137
+ const rest = node.children.filter((c) => c.type !== 'fill');
138
+ // Whitespace around @slot blocks is not content for the default slot.
139
+ const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
140
+ scopeKey = parentScope;
141
+ out.push({ kind: 'component', name: node.tag, props, children, fills, region, ...(attach ? { attach } : {}) });
142
+ return;
143
+ }
144
+ if (node.tag === 'slot') {
145
+ if (stateful)
146
+ fail('<slot /> is only supported in components without <script>', node.start);
147
+ let name = 'default';
148
+ for (const a of node.attrs) {
149
+ if (a.kind === 'static' && a.name === 'name' && typeof a.value === 'string' && a.value)
150
+ name = a.value;
51
151
  else
52
- fail(`component <${node.tag}> only takes [prop] bindings`, a.start);
152
+ fail('<slot> only takes name="…"', a.start);
53
153
  }
54
- nodes.push({ kind: 'component', name: node.tag, props });
154
+ // Fallback content belongs to this component: its holes read this component's inputs.
155
+ const fallback = [];
156
+ const parent = out;
157
+ out = fallback;
158
+ node.children.forEach((child) => visit(child, rawText));
159
+ out = parent;
160
+ out.push({ kind: 'slot', name, fallback });
55
161
  return;
56
162
  }
57
- let open = `<${node.tag}`;
163
+ emitStatic(`<${node.tag}`);
58
164
  const elementEvents = node.attrs.filter((a) => a.kind === 'event');
165
+ const dynamic = [];
59
166
  for (const a of node.attrs) {
60
167
  if (a.kind === 'static')
61
- open += a.value === true ? ` ${a.name}` : ` ${a.name}="${a.value}"`;
62
- else if (a.kind === 'prop')
63
- fail('[prop] bindings on HTML elements are not supported yet', a.start);
64
- else if (!stateful)
65
- fail('event bindings need a <script> with state; this component is static', a.start);
66
- else
168
+ emitStatic(a.value === true ? ` ${a.name}` : ` ${a.name}="${a.value}"`);
169
+ else if (a.kind === 'event') {
170
+ if (!stateful)
171
+ fail('event bindings need a <script> with state; this component is static', a.start);
67
172
  checkHandler(a.expr, file, source, a.start);
173
+ }
174
+ else {
175
+ if (/^on/i.test(a.name))
176
+ fail(`use (${a.name.slice(2).toLowerCase()}) for events, not an ${a.name} attribute`, a.start);
177
+ // srcdoc is a whole HTML document: binding data into it is HTML injection, so it stays static.
178
+ if (a.name.toLowerCase() === 'srcdoc')
179
+ fail('srcdoc cannot be bound; write it as a static attribute', a.start);
180
+ const exprs = a.kind === 'prop' ? [{ expr: a.expr, start: a.start }] : a.parts.filter((p) => typeof p !== 'string');
181
+ for (const e of exprs)
182
+ checkExpr(e.expr, file, source, e.start);
183
+ const reactive = stateful && exprs.some((e) => referencesNames(e.expr, scriptScope) || referencesNames(e.expr, loopNames));
184
+ const value = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
185
+ const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag };
186
+ if (reactive)
187
+ dynamic.push(node_);
188
+ out.push(node_);
189
+ }
190
+ }
191
+ // One marker per element for its reactive attributes, one for its events.
192
+ if (dynamic.length) {
193
+ const index = attrElementCount++;
194
+ for (const d of dynamic)
195
+ d.index = index;
196
+ emitStatic(` data-cl-a="${index}"`);
68
197
  }
69
198
  if (elementEvents.length) {
70
199
  const index = eventElementCount++;
71
- open += ` data-cl-e="${index}"`;
200
+ emitStatic(` data-cl-e="${index}"`);
72
201
  for (const a of elementEvents)
73
- events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '' });
202
+ events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey });
74
203
  }
75
- emitStatic(open + '>');
204
+ emitStatic('>');
76
205
  node.children.forEach((child) => visit(child, RAW_TEXT.has(node.tag) ? node.tag : rawText));
77
206
  if (!VOID.has(node.tag))
78
207
  emitStatic(`</${node.tag}>`);
@@ -83,7 +212,8 @@ export function lower(parsed, file, source) {
83
212
  name: file.split('/').pop().replace(/\.clarus$/, ''),
84
213
  inputs: parsed.inputs,
85
214
  imports: parsed.imports,
86
- script: parsed.script?.code,
215
+ script: parsed.script ? split.body : undefined,
216
+ scriptImports: split.imports,
87
217
  signals,
88
218
  stateful,
89
219
  nodes,
@@ -13,6 +13,14 @@ export type Attr = {
13
13
  name: string;
14
14
  expr: string;
15
15
  start: number;
16
+ } | {
17
+ kind: 'interp';
18
+ name: string;
19
+ parts: (string | {
20
+ expr: string;
21
+ start: number;
22
+ })[];
23
+ start: number;
16
24
  };
17
25
  export type TemplateNode = {
18
26
  type: 'element';
@@ -28,6 +36,32 @@ export type TemplateNode = {
28
36
  type: 'expr';
29
37
  expr: string;
30
38
  start: number;
39
+ } | {
40
+ type: 'raw';
41
+ value: string;
42
+ start: number;
43
+ } | {
44
+ type: 'if';
45
+ branches: {
46
+ cond: string | null;
47
+ condStart: number;
48
+ children: TemplateNode[];
49
+ }[];
50
+ start: number;
51
+ } | {
52
+ type: 'fill';
53
+ name: string;
54
+ children: TemplateNode[];
55
+ start: number;
56
+ } | {
57
+ type: 'for';
58
+ item: string;
59
+ list: string;
60
+ track: string | null;
61
+ headStart: number;
62
+ children: TemplateNode[];
63
+ empty: TemplateNode[] | null;
64
+ start: number;
31
65
  };
32
66
  export type InputDecl = {
33
67
  name: string;
@@ -53,9 +53,30 @@ export function parse(source, file) {
53
53
  list.push({ kind: 'prop', name: name.slice(1, -1), expr: value.trim(), start });
54
54
  }
55
55
  else {
56
- if (typeof value === 'string' && value.includes('{{'))
57
- fail('interpolation in attributes is not supported yet; use a literal value', start);
58
- list.push({ kind: 'static', name, value, start });
56
+ if (typeof value === 'string' && value.includes('{{')) {
57
+ // Split into literal text and {{ expr }} parts; valueStart is the offset of the value's first character.
58
+ const valueStart = start + name.length + 2;
59
+ const parts = [];
60
+ let at = 0;
61
+ while (at < value.length) {
62
+ const open = value.indexOf('{{', at);
63
+ if (open === -1) {
64
+ parts.push(value.slice(at));
65
+ break;
66
+ }
67
+ if (open > at)
68
+ parts.push(value.slice(at, open));
69
+ const close = value.indexOf('}}', open + 2);
70
+ if (close === -1)
71
+ fail('unclosed {{ in attribute value', valueStart + open);
72
+ parts.push({ expr: value.slice(open + 2, close).trim(), start: valueStart + open });
73
+ at = close + 2;
74
+ }
75
+ list.push({ kind: 'interp', name, parts, start });
76
+ }
77
+ else {
78
+ list.push({ kind: 'static', name, value, start });
79
+ }
59
80
  }
60
81
  }
61
82
  }
@@ -97,6 +118,143 @@ export function parse(source, file) {
97
118
  return -1;
98
119
  }
99
120
  // Parse children until `</parent>` (or end of input at top level).
121
+ // A parenthesised JS condition after `@if` / `@else if`, skipping strings and nested parentheses.
122
+ function condition(keyword) {
123
+ while (/\s/.test(source[i] ?? ''))
124
+ i++;
125
+ if (source[i] !== '(')
126
+ fail(`expected ( after ${keyword}`, i);
127
+ const open = i;
128
+ let depth = 0;
129
+ for (; i < source.length; i++) {
130
+ const c = source[i];
131
+ if (c === '"' || c === "'" || c === '`') {
132
+ for (i++; i < source.length && source[i] !== c; i++)
133
+ if (source[i] === '\\')
134
+ i++;
135
+ }
136
+ else if (c === '(')
137
+ depth++;
138
+ else if (c === ')' && --depth === 0) {
139
+ i++;
140
+ return { cond: source.slice(open + 1, i - 1).trim(), condStart: open + 1 };
141
+ }
142
+ }
143
+ return fail(`unclosed ( after ${keyword}`, open);
144
+ }
145
+ // @if (a) { … } @else if (b) { … } @else { … }
146
+ function ifBlock() {
147
+ const start = i;
148
+ i += 3;
149
+ const branches = [];
150
+ let next = condition('@if');
151
+ while (next) {
152
+ while (/\s/.test(source[i] ?? ''))
153
+ i++;
154
+ if (source[i] !== '{')
155
+ fail('expected { to open the block', i);
156
+ i++;
157
+ branches.push({ ...next, children: children({ tag: '@if', start, block: true }) });
158
+ if (next.cond === null)
159
+ break; // @else is last
160
+ const save = i;
161
+ while (/\s/.test(source[i] ?? ''))
162
+ i++;
163
+ if (!source.startsWith('@else', i)) {
164
+ i = save;
165
+ break;
166
+ }
167
+ i += 5;
168
+ while (/\s/.test(source[i] ?? ''))
169
+ i++;
170
+ if (/^if[\s(]/.test(source.slice(i, i + 3))) {
171
+ i += 2;
172
+ next = condition('@else if');
173
+ }
174
+ else
175
+ next = { cond: null, condStart: i };
176
+ }
177
+ return { type: 'if', branches, start };
178
+ }
179
+ // Split at top-level ';' (outside strings and brackets).
180
+ function splitClauses(text) {
181
+ const parts = [];
182
+ let depth = 0;
183
+ let from = 0;
184
+ for (let j = 0; j < text.length; j++) {
185
+ const c = text[j];
186
+ if (c === '"' || c === "'" || c === '`') {
187
+ for (j++; j < text.length && text[j] !== c; j++)
188
+ if (text[j] === '\\')
189
+ j++;
190
+ }
191
+ else if ('([{'.includes(c))
192
+ depth++;
193
+ else if (')]}'.includes(c))
194
+ depth--;
195
+ else if (c === ';' && depth === 0) {
196
+ parts.push(text.slice(from, j));
197
+ from = j + 1;
198
+ }
199
+ }
200
+ return [...parts, text.slice(from)].map((p) => p.trim()).filter(Boolean);
201
+ }
202
+ // @for (item of list; track key) { … } @empty { … }
203
+ function forBlock() {
204
+ const start = i;
205
+ i += 4;
206
+ const { cond: head, condStart: headStart } = condition('@for');
207
+ const [first = '', ...rest] = splitClauses(head);
208
+ const m = /^([\s\S]+?)\s+of\s+([\s\S]+)$/.exec(first);
209
+ if (!m)
210
+ fail('expected "item of list" in @for', headStart);
211
+ if (!/^[A-Za-z_$][\w$]*$/.test(m[1].trim()))
212
+ fail('the @for item must be a simple name', headStart);
213
+ let track = null;
214
+ for (const clause of rest) {
215
+ const t = /^track\s+([\s\S]+)$/.exec(clause);
216
+ if (!t)
217
+ fail(`unknown @for clause "${clause}"`, headStart);
218
+ track = t[1].trim();
219
+ }
220
+ while (/\s/.test(source[i] ?? ''))
221
+ i++;
222
+ if (source[i] !== '{')
223
+ fail('expected { to open the block', i);
224
+ i++;
225
+ const body = children({ tag: '@for', start, block: true });
226
+ let empty = null;
227
+ const save = i;
228
+ while (/\s/.test(source[i] ?? ''))
229
+ i++;
230
+ if (/^@empty[\s{]/.test(source.slice(i, i + 7))) {
231
+ i += 6;
232
+ while (/\s/.test(source[i] ?? ''))
233
+ i++;
234
+ if (source[i] !== '{')
235
+ fail('expected { to open the block', i);
236
+ i++;
237
+ empty = children({ tag: '@empty', start, block: true });
238
+ }
239
+ else
240
+ i = save;
241
+ return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, children: body, empty, start };
242
+ }
243
+ // @slot('name') { … }: content for a component's named slot.
244
+ function fillBlock() {
245
+ const start = i;
246
+ i += 5;
247
+ const { cond } = condition('@slot');
248
+ const m = /^(['"])([\w-]+)\1$/.exec(cond);
249
+ if (!m)
250
+ fail(`@slot needs a quoted name, like @slot('aside')`, start);
251
+ while (/\s/.test(source[i] ?? ''))
252
+ i++;
253
+ if (source[i] !== '{')
254
+ fail('expected { to open the block', i);
255
+ i++;
256
+ return { type: 'fill', name: m[2], children: children({ tag: '@slot', start, block: true }), start };
257
+ }
100
258
  function children(parent) {
101
259
  const nodes = [];
102
260
  let text = '';
@@ -122,6 +280,26 @@ export function parse(source, file) {
122
280
  text += source.slice(i, end + 3); // kept verbatim as static text: no tags, no holes inside
123
281
  i = end + 3;
124
282
  }
283
+ else if (/^@if[\s(]/.test(source.slice(i, i + 4))) {
284
+ flush();
285
+ nodes.push(ifBlock());
286
+ textStart = i;
287
+ }
288
+ else if (/^@for[\s(]/.test(source.slice(i, i + 5))) {
289
+ flush();
290
+ nodes.push(forBlock());
291
+ textStart = i;
292
+ }
293
+ else if (/^@slot[\s(]/.test(source.slice(i, i + 6))) {
294
+ flush();
295
+ nodes.push(fillBlock());
296
+ textStart = i;
297
+ }
298
+ else if (parent?.block && source[i] === '}') {
299
+ flush();
300
+ i++;
301
+ return nodes;
302
+ }
125
303
  else if (!parent && source[i] === '@' && atLineStart(i)) {
126
304
  flush();
127
305
  directive();
@@ -169,6 +347,23 @@ export function parse(source, file) {
169
347
  out.script = { code: source.slice(i, end), start: i };
170
348
  i = end + '</script>'.length;
171
349
  }
350
+ else if (list.some((a) => a.name === 'verbatim')) {
351
+ // Everything up to </tag> is text: no holes, tags or directives.
352
+ const attr = list.find((a) => a.name === 'verbatim');
353
+ if (attr.kind !== 'static' || attr.value !== true)
354
+ fail('verbatim takes no value', attr.start);
355
+ if (out.imports.some((imp) => imp.name === tag))
356
+ fail('verbatim only works on HTML elements, not components', attr.start);
357
+ let kids = [];
358
+ if (!selfClosing && !VOID.has(tag)) {
359
+ const close = source.indexOf(`</${tag}>`, i);
360
+ if (close === -1)
361
+ fail(`unclosed <${tag} verbatim>`, start);
362
+ kids = [{ type: 'raw', value: source.slice(i, close), start: i }];
363
+ i = close + `</${tag}>`.length;
364
+ }
365
+ nodes.push({ type: 'element', tag, attrs: list.filter((a) => a !== attr), children: kids, start });
366
+ }
172
367
  else {
173
368
  const kids = selfClosing || VOID.has(tag) ? [] : children({ tag, start });
174
369
  nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
@@ -180,7 +375,7 @@ export function parse(source, file) {
180
375
  }
181
376
  }
182
377
  if (parent)
183
- fail(`unclosed <${parent.tag}>`, parent.start);
378
+ fail(parent.block ? `unclosed ${parent.tag} block` : `unclosed <${parent.tag}>`, parent.start);
184
379
  flush();
185
380
  return nodes;
186
381
  }
@@ -1,4 +1,4 @@
1
- export type Signals = Map<string, 'state' | 'derived'>;
1
+ export type Signals = Map<string, 'state' | 'derived' | 'shared'>;
2
2
  /** Throw a located ClarusError unless `expr` is exactly one JS expression. */
3
3
  export declare function checkExpr(expr: string, file: string, source: string, offset: number): void;
4
4
  /** Throw a located ClarusError unless `code` parses as statements (event handlers may hold several). */
@@ -9,8 +9,23 @@ export declare function templateRanges(code: string): [number, number][];
9
9
  export declare function wrapExpr(expr: string): string;
10
10
  /** Names declared at the top level of <script>: variables, functions, classes. */
11
11
  export declare function scriptNames(code: string): Set<string>;
12
+ /**
13
+ * Take the `import` statements out of a <script> so they can go at the top of the compiled modules. Their text is
14
+ * blanked in the body (same length, newlines kept), so positions in the rest of the script don't move.
15
+ * Island scripts are bundled for the browser, so `node:` imports are a build error.
16
+ */
17
+ export declare function splitImports(code: string, file: string, source: string, offset: number): {
18
+ imports: string[];
19
+ body: string;
20
+ };
12
21
  export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
13
- export declare function rewriteClient(code: string, signals: Signals): string;
22
+ /**
23
+ * Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
24
+ * starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
25
+ */
26
+ export declare function rewriteClient(code: string, signals: Signals, options?: {
27
+ stateFromServer?: boolean;
28
+ }): string;
14
29
  export declare function rewriteClientExpr(expr: string, signals: Signals): string;
15
30
  export declare function rewriteServer(code: string): string;
16
31
  export declare function referencesSignal(expr: string, signals: Signals): boolean;
@@ -181,19 +181,55 @@ export function scriptNames(code) {
181
181
  else if ((stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration') && stmt.id) {
182
182
  names.add(stmt.id.name);
183
183
  }
184
+ else if (stmt.type === 'ImportDeclaration') {
185
+ for (const spec of stmt.specifiers)
186
+ names.add(spec.local.name);
187
+ }
184
188
  }
185
189
  return names;
186
190
  }
187
191
  function signalCall(init) {
188
192
  if (init?.type !== 'CallExpression' || init.callee.type !== 'Identifier')
189
193
  return undefined;
190
- return init.callee.name === 'state' || init.callee.name === 'derived' ? init.callee.name : undefined;
194
+ const name = init.callee.name;
195
+ return name === 'state' || name === 'derived' || name === 'shared' ? name : undefined;
191
196
  }
197
+ /**
198
+ * Take the `import` statements out of a <script> so they can go at the top of the compiled modules. Their text is
199
+ * blanked in the body (same length, newlines kept), so positions in the rest of the script don't move.
200
+ * Island scripts are bundled for the browser, so `node:` imports are a build error.
201
+ */
202
+ export function splitImports(code, file, source, offset) {
203
+ const imports = [];
204
+ let body = code;
205
+ for (const stmt of parseScript(code, file, source, offset).body) {
206
+ if (stmt.type !== 'ImportDeclaration')
207
+ continue;
208
+ const from = String(stmt.source.value);
209
+ if (from.startsWith('node:')) {
210
+ throw new ClarusError(`\`${from}\` can't be imported in an island script: the script is bundled for the browser`, file, source, offset + stmt.start);
211
+ }
212
+ imports.push(code.slice(stmt.start, stmt.end));
213
+ body = body.slice(0, stmt.start) + code.slice(stmt.start, stmt.end).replace(/[^\n]/g, ' ') + body.slice(stmt.end);
214
+ }
215
+ return { imports, body };
216
+ }
217
+ // Globals that only exist on a server runtime. An island's script also runs in the browser and its state() values
218
+ // are written into the page, so reading these would leak server data (or simply fail in the browser).
219
+ const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
192
220
  export function analyzeScript(code, file, source, offset) {
193
221
  const signals = new Map();
194
- for (const stmt of parseScript(code, file, source, offset).body) {
195
- if (stmt.type === 'ImportDeclaration' || stmt.type.startsWith('Export')) {
196
- throw new ClarusError('imports in <script> are not supported yet', file, source, offset + stmt.start);
222
+ const ast = parseScript(code, file, source, offset);
223
+ const declared = scriptNames(code);
224
+ print(ast, code, (node, parent, key) => {
225
+ if (node.type === 'Identifier' && SERVER_GLOBALS.has(node.name) && !declared.has(node.name) && !isBinding(parent, key)) {
226
+ throw new ClarusError(`\`${node.name}\` is server-only: an island's script also runs in the browser, and its state and props are sent to the browser in the page`, file, source, offset + node.start);
227
+ }
228
+ return undefined;
229
+ });
230
+ for (const stmt of ast.body) {
231
+ if (stmt.type.startsWith('Export')) {
232
+ throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
197
233
  }
198
234
  if (stmt.type !== 'VariableDeclaration')
199
235
  continue;
@@ -247,9 +283,29 @@ function clientHook(code, signals, entered = new WeakSet()) {
247
283
  };
248
284
  return hook;
249
285
  }
250
- export function rewriteClient(code, signals) {
286
+ /**
287
+ * Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
288
+ * starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
289
+ */
290
+ export function rewriteClient(code, signals, options = {}) {
251
291
  const ast = parseScript(code);
252
- return code.slice(0, ast.start) + print(ast, code, clientHook(code, signals)) + code.slice(ast.end);
292
+ const hook = clientHook(code, signals);
293
+ if (!options.stateFromServer)
294
+ return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
295
+ const topLevel = new Set(ast.body.filter((n) => n.type === 'VariableDeclaration').flatMap((n) => n.declarations));
296
+ const withState = (node, parent, key) => {
297
+ // `let x = state()` becomes `const x = …`; re-print with this hook so the declarators below still see it.
298
+ if (node.type === 'VariableDeclaration' && node.kind === 'let' && node.declarations.every((d) => signalCall(d.init))) {
299
+ return 'const' + print({ ...node, kind: 'const', start: node.start + 3 }, code, withState, parent, key);
300
+ }
301
+ if (topLevel.has(node) && node.id.type === 'Identifier' && signals.get(node.id.name) === 'state' && node.init?.arguments?.length) {
302
+ const name = node.id.name;
303
+ const init = print(node.init.arguments[0], code, hook);
304
+ return `${name} = state(__cl_state && ${JSON.stringify(name)} in __cl_state ? __cl_state.${name} : ${init})`;
305
+ }
306
+ return hook(node, parent, key);
307
+ };
308
+ return code.slice(0, ast.start) + print(ast, code, withState) + code.slice(ast.end);
253
309
  }
254
310
  export function rewriteClientExpr(expr, signals) {
255
311
  const ast = parseExpr(expr);
@@ -266,6 +322,10 @@ export function rewriteServer(code) {
266
322
  return `(${inner})`;
267
323
  if (node.callee.name === 'derived')
268
324
  return `(${inner})()`;
325
+ // A store's current value lives across requests on the server; render from its initial value instead, and from
326
+ // a copy, so a render that mutates it can't change what the next request sees.
327
+ if (node.callee.name === 'shared')
328
+ return `structuredClone((${inner}).initial)`;
269
329
  return undefined;
270
330
  };
271
331
  return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
@@ -0,0 +1,5 @@
1
+ export declare const UNSAFE_URL = "about:invalid#unsafe";
2
+ /**
3
+ * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
4
+ */
5
+ export declare function attrValue(name: string, value: unknown, tag?: string): string | true | null;