clarusjs 0.12.0 → 0.14.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.
Files changed (45) hide show
  1. package/README.md +2 -0
  2. package/dist/check/generate.js +54 -11
  3. package/dist/cli/check.js +15 -4
  4. package/dist/compiler/class-style.d.ts +2 -0
  5. package/dist/compiler/class-style.js +53 -0
  6. package/dist/compiler/emit-client.js +24 -4
  7. package/dist/compiler/emit-server.js +15 -5
  8. package/dist/compiler/html-expr.d.ts +10 -2
  9. package/dist/compiler/html-expr.js +31 -17
  10. package/dist/compiler/icon.d.ts +24 -0
  11. package/dist/compiler/icon.js +83 -0
  12. package/dist/compiler/index.d.ts +4 -0
  13. package/dist/compiler/index.js +53 -9
  14. package/dist/compiler/ir.d.ts +23 -0
  15. package/dist/compiler/ir.js +69 -2
  16. package/dist/compiler/lint.js +12 -1
  17. package/dist/compiler/parse.d.ts +24 -0
  18. package/dist/compiler/parse.js +66 -0
  19. package/dist/compiler/script.d.ts +10 -1
  20. package/dist/compiler/script.js +17 -3
  21. package/dist/fetch/index.d.ts +157 -3
  22. package/dist/fetch/index.js +135 -14
  23. package/dist/icons.d.ts +59 -0
  24. package/dist/icons.js +112 -0
  25. package/dist/runtime/attrs.d.ts +27 -0
  26. package/dist/runtime/attrs.js +66 -0
  27. package/dist/runtime/dom.d.ts +15 -0
  28. package/dist/runtime/dom.js +50 -1
  29. package/dist/runtime/html.d.ts +6 -0
  30. package/dist/runtime/html.js +19 -1
  31. package/dist/runtime/index.d.ts +3 -2
  32. package/dist/runtime/index.js +3 -2
  33. package/dist/runtime/server.d.ts +14 -1
  34. package/dist/runtime/server.js +36 -2
  35. package/dist/server/handler.d.ts +1 -1
  36. package/dist/server/handler.js +5 -2
  37. package/dist/server/views.d.ts +1 -1
  38. package/dist/server/views.js +1 -1
  39. package/dist/vite/node.d.ts +2 -0
  40. package/dist/vite/node.js +13 -0
  41. package/dist/vite/plugin.d.ts +6 -1
  42. package/dist/vite/plugin.js +114 -17
  43. package/dist/vite/sitemap.d.ts +20 -1
  44. package/dist/vite/sitemap.js +27 -3
  45. package/package.json +5 -1
@@ -2,15 +2,18 @@ import { emitClient } from './emit-client.js';
2
2
  import { ClarusError } from './errors.js';
3
3
  import { emitServer } from './emit-server.js';
4
4
  import { lower } from './ir.js';
5
- import { parse } from './parse.js';
5
+ import { awaitLists, parse } from './parse.js';
6
6
  export { ClarusError } from './errors.js';
7
7
  export { parse } from './parse.js';
8
+ import { foldClass } from './class-style.js';
9
+ export { checkIcons } from './icon.js';
8
10
  export { lint, lintRules } from './lint.js';
9
11
  export function compile(source, options) {
10
12
  const parsed = parse(source, options.file);
11
13
  const warnings = [];
12
14
  const id = options.scope ?? scopeId(options.file);
13
- markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)));
15
+ foldClass(parsed.nodes, new Set(parsed.imports.map((imp) => imp.name)));
16
+ markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)), parsed.styles.some((st) => st.mode === 'scoped'));
14
17
  let css = '';
15
18
  for (const s of parsed.styles) {
16
19
  if (s.mode === 'plain') {
@@ -24,7 +27,9 @@ export function compile(source, options) {
24
27
  const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
25
28
  css += `${statements}@scope (.cl-c-${id}) to ([class*="cl-c-"]:not(.cl-c-${id}) > *) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
26
29
  }
27
- const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace });
30
+ if (options.renderImports && parsed.serverScript)
31
+ throw new ClarusError('<script server> runs on the server only, and this component renders in the browser (a client route, or a child of an island, which re-renders it): make the route static or server, or render the component outside the island', options.file, source, parsed.serverScript.tag);
32
+ const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon });
28
33
  warnings.push(...ir.warnings);
29
34
  if (options.target === 'client')
30
35
  return { code: emitClient(ir, options.hot), stateful: ir.stateful, css, warnings };
@@ -40,10 +45,41 @@ export function scopeId(file) {
40
45
  return `${name}-${(h >>> 0).toString(36)}`;
41
46
  }
42
47
  const UNMARKED = new Set(['slot', 'cl-head', 'script', 'style', 'html', 'title', 'meta', 'link', 'base']);
43
- function markRoots(nodes, cls, components) {
48
+ function markSlotContent(nodes, cls, components) {
49
+ for (const node of nodes) {
50
+ if (node.type === 'fill')
51
+ markSlotContent(node.children, cls, components);
52
+ else if (node.type === 'if')
53
+ for (const b of node.branches)
54
+ markSlotContent(b.children, cls, components);
55
+ else if (node.type === 'for') {
56
+ markSlotContent(node.children, cls, components);
57
+ if (node.empty)
58
+ markSlotContent(node.empty, cls, components);
59
+ }
60
+ else if (node.type === 'await')
61
+ for (const kids of awaitLists(node))
62
+ markSlotContent(kids, cls, components);
63
+ else if (node.type === 'element' && components.has(node.tag))
64
+ markSlotContent(node.children, cls, components);
65
+ else if (node.type === 'element' && !UNMARKED.has(node.tag)) {
66
+ const at = node.attrs.findIndex((a) => a.name === 'class' && a.kind !== 'event');
67
+ const own = node.attrs[at];
68
+ if (!own)
69
+ node.attrs.push({ kind: 'static', name: 'class', value: cls, start: node.start });
70
+ else if (own.kind === 'static')
71
+ node.attrs[at] = { ...own, value: own.value === true || !own.value ? cls : `${own.value} ${cls}` };
72
+ else if (own.kind === 'interp')
73
+ own.parts.push(` ${cls}`);
74
+ else if (own.kind === 'prop')
75
+ node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr.startsWith('__cl_classValue(') ? own.expr : `__cl_classValue((${own.expr}))`, start: own.start }, ` ${cls}`], start: own.start };
76
+ }
77
+ }
78
+ }
79
+ function markRoots(nodes, cls, components, slots = false) {
44
80
  for (const node of nodes) {
45
81
  if (node.type === 'element' && !components.has(node.tag) && !UNMARKED.has(node.tag)) {
46
- const at = node.attrs.findIndex((a) => a.name === 'class');
82
+ const at = node.attrs.findIndex((a) => a.name === 'class' && a.kind !== 'event');
47
83
  const own = node.attrs[at];
48
84
  const passed = { expr: '__cl_class', start: node.start };
49
85
  if (!own)
@@ -53,16 +89,24 @@ function markRoots(nodes, cls, components) {
53
89
  else if (own.kind === 'interp')
54
90
  own.parts.push(` ${cls}`, passed);
55
91
  else if (own.kind === 'prop')
56
- node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr, start: own.start }, ` ${cls}`, passed], start: own.start };
92
+ node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr.startsWith('__cl_classValue(') ? own.expr : `__cl_classValue((${own.expr}))`, start: own.start }, ` ${cls}`, passed], start: own.start };
93
+ }
94
+ else if (node.type === 'element' && components.has(node.tag)) {
95
+ if (slots)
96
+ markSlotContent(node.children, cls, components);
57
97
  }
58
98
  else if (node.type === 'if') {
59
99
  for (const b of node.branches)
60
- markRoots(b.children, cls, components);
100
+ markRoots(b.children, cls, components, slots);
61
101
  }
62
102
  else if (node.type === 'for') {
63
- markRoots(node.children, cls, components);
103
+ markRoots(node.children, cls, components, slots);
64
104
  if (node.empty)
65
- markRoots(node.empty, cls, components);
105
+ markRoots(node.empty, cls, components, slots);
106
+ }
107
+ else if (node.type === 'await') {
108
+ for (const kids of awaitLists(node))
109
+ markRoots(kids, cls, components, slots);
66
110
  }
67
111
  }
68
112
  }
@@ -1,3 +1,4 @@
1
+ import { type IconResolver } from './icon.ts';
1
2
  import { ClarusError } from './errors.ts';
2
3
  import { type DataImport, type ImportDecl, type InputDecl, type ParsedFile } from './parse.ts';
3
4
  import { type Signals } from './script.ts';
@@ -50,6 +51,8 @@ export type IRNode = {
50
51
  reactive: boolean;
51
52
  index: number;
52
53
  tag: string;
54
+ skip?: string[];
55
+ where?: string;
53
56
  } | {
54
57
  kind: 'connect';
55
58
  expr: string;
@@ -61,6 +64,19 @@ export type IRNode = {
61
64
  nodes: IRNode[];
62
65
  }[];
63
66
  block: number;
67
+ } | {
68
+ kind: 'await';
69
+ expr: string;
70
+ pending: IRNode[];
71
+ then: {
72
+ name: string;
73
+ nodes: IRNode[];
74
+ } | null;
75
+ catch: {
76
+ name: string;
77
+ nodes: IRNode[];
78
+ } | null;
79
+ block: number;
64
80
  } | {
65
81
  kind: 'for';
66
82
  item: string;
@@ -83,6 +99,12 @@ export type ComponentIR = {
83
99
  imports: ImportDecl[];
84
100
  script?: string;
85
101
  scriptImports: string[];
102
+ /** <script server> (#430): its hoisted imports, its body (run at the top of render), and whether it awaits. */
103
+ server?: {
104
+ imports: string[];
105
+ body: string;
106
+ awaits: boolean;
107
+ };
86
108
  dataImports: DataImport[];
87
109
  signals: Signals;
88
110
  stateful: boolean;
@@ -93,4 +115,5 @@ export type ComponentIR = {
93
115
  };
94
116
  export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
95
117
  collapseWhitespace?: boolean;
118
+ icon?: IconResolver;
96
119
  }): ComponentIR;
@@ -1,13 +1,20 @@
1
1
  import { parseExpressionAt } from 'acorn';
2
+ import { iconElement } from './icon.js';
2
3
  import { ClarusError } from './errors.js';
3
4
  import { FOR_IMPLICIT, importNames } from './parse.js';
4
- import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
5
+ import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
5
6
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
7
+ const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
6
8
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
9
+ const iconBodies = new WeakMap();
7
10
  export function lower(parsed, file, source, options = {}) {
8
11
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
9
12
  const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
10
13
  const warnings = [];
14
+ const ss = parsed.serverScript;
15
+ if (ss && stateful)
16
+ fail('<script server> runs on the server only, and this component is an island (it has a <script> or a @model input): load the data in a parent, or in a page\'s <script server>, and pass it to the island as props', ss.tag);
17
+ const server = ss ? serverScriptParts(ss.code, file, source, ss.start) : undefined;
11
18
  const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
12
19
  const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
13
20
  const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
@@ -122,6 +129,27 @@ export function lower(parsed, file, source, options = {}) {
122
129
  out.push({ kind: 'if', branches, block });
123
130
  return;
124
131
  }
132
+ if (node.type === 'await') {
133
+ checkExpr(node.expr, file, source, node.exprStart);
134
+ const block = stateful ? blockCount++ : -1;
135
+ const parent = out;
136
+ const parentScope = scopeKey;
137
+ const lowerBranch = (children, k) => {
138
+ const list = [];
139
+ out = list;
140
+ if (stateful)
141
+ scopeKey = `${block}.${k}`;
142
+ children.forEach((child) => visit(child, rawText));
143
+ return list;
144
+ };
145
+ const pending = lowerBranch(node.pending, 0);
146
+ const then = node.then ? { name: node.then.name, nodes: lowerBranch(node.then.children, 1) } : null;
147
+ const caught = node.catch ? { name: node.catch.name, nodes: lowerBranch(node.catch.children, 2) } : null;
148
+ out = parent;
149
+ scopeKey = parentScope;
150
+ out.push({ kind: 'await', expr: node.expr, pending, then, catch: caught, block });
151
+ return;
152
+ }
125
153
  if (node.type === 'for') {
126
154
  checkExpr(node.list, file, source, node.listStart);
127
155
  if (node.track !== null)
@@ -167,13 +195,27 @@ export function lower(parsed, file, source, options = {}) {
167
195
  out.push({ kind: 'hole', expr: node.expr, reactive, index: reactive ? holeCount++ : -1 });
168
196
  return;
169
197
  }
170
- if (components.has(node.tag)) {
198
+ if (node.tag === 'icon' && !components.has('icon')) {
199
+ const { svg, body } = iconElement(node, file, source, options.icon);
200
+ iconBodies.set(svg, body);
201
+ return visit(svg, rawText);
202
+ }
203
+ if (components.has(node.tag) && !iconBodies.has(node)) {
171
204
  const props = [];
172
205
  const models = [];
173
206
  let attach;
174
207
  let cls;
175
208
  const paths = [];
176
209
  for (const a of node.attrs) {
210
+ if (/^(class|style)\./.test(a.name))
211
+ fail(`a component takes a static class="…" only: [${a.name}] is for elements`, a.start);
212
+ if (a.kind === 'prop' && a.name === '...') {
213
+ if (props.some((p) => p.name === '...'))
214
+ fail('one [...] per element', a.start);
215
+ checkExpr(a.expr, file, source, a.start);
216
+ props.unshift({ name: '...', expr: a.expr });
217
+ continue;
218
+ }
177
219
  if (a.name === 'class') {
178
220
  if (a.kind !== 'static' || typeof a.value !== 'string')
179
221
  fail('a component takes a static class="…" only ([class] and {{ }} in it aren\'t supported on a component yet)', a.start);
@@ -319,6 +361,17 @@ export function lower(parsed, file, source, options = {}) {
319
361
  attrs.push({ kind: 'prop', name: 'selected', expr: `((__cl_s, __cl_v) => (Array.isArray(__cl_s) ? __cl_s.map(String).includes(String(__cl_v)) : String(__cl_s) === String(__cl_v)))(${selectModel}, ${mine})`, start: own.start });
320
362
  }
321
363
  }
364
+ for (const a of node.attrs) {
365
+ if (a.name.startsWith('{'))
366
+ fail(`${a.name} isn't a binding: spread with [...]="${a.name.replace(/^\{\.*|\}$/g, '')}"`, a.start);
367
+ if (a.kind === 'prop' && a.name.includes('.') && a.name !== '...' && !/^(class|style)\./.test(a.name))
368
+ fail(`[${a.name}]: only class. and style. take a . ([class.name], [style.prop])`, a.start);
369
+ }
370
+ const spreads = node.attrs.filter((a) => a.kind === 'prop' && a.name === '...');
371
+ if (spreads.length > 1)
372
+ fail('one [...] per element', spreads[1].start);
373
+ if (spreads.length && SPREAD_REFUSED.has(node.tag.toLowerCase()))
374
+ fail(`[...] can't spread onto <${node.tag}>: it could set what the element loads (write its attributes one by one)`, spreads[0].start);
322
375
  emitStatic(`<${node.tag}`);
323
376
  const elementEvents = attrs.filter((a) => a.kind === 'event');
324
377
  const dynamic = [];
@@ -339,6 +392,16 @@ export function lower(parsed, file, source, options = {}) {
339
392
  for (const m of mutationsOf(a.expr, stateNames))
340
393
  warnings.push(new ClarusError(m.message, file, source, exprStart + m.start));
341
394
  }
395
+ else if (a.kind === 'prop' && a.name === '...') {
396
+ checkExpr(a.expr, file, source, a.start);
397
+ const reactive = stateful && (referencesNames(a.expr, scriptScope) || referencesNames(a.expr, loopNames));
398
+ const skip = [...new Set(attrs.filter((x) => x !== a && x.kind !== 'event').map((x) => x.name.toLowerCase()))];
399
+ const at = new ClarusError('', file, source, a.start);
400
+ const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, where: `${file}:${at.line}:${at.column}` };
401
+ if (reactive)
402
+ dynamic.push(node_);
403
+ out.push(node_);
404
+ }
342
405
  else if (a.kind === 'prop' && a.name === 'engine') {
343
406
  if (!stateful)
344
407
  fail('[engine] needs a <script> (an island): the forms engine runs in the browser', a.start);
@@ -380,6 +443,9 @@ export function lower(parsed, file, source, options = {}) {
380
443
  events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey });
381
444
  }
382
445
  emitStatic('>');
446
+ const iconBody = iconBodies.get(node);
447
+ if (iconBody !== undefined)
448
+ emitStatic(iconBody);
383
449
  const outer = engineScope;
384
450
  if (engine)
385
451
  engineScope = { root: null };
@@ -404,6 +470,7 @@ export function lower(parsed, file, source, options = {}) {
404
470
  imports: parsed.imports,
405
471
  script: parsed.script ? split.body : undefined,
406
472
  scriptImports: split.imports.map((imp) => imp.text),
473
+ ...(server ? { server } : {}),
407
474
  dataImports: parsed.dataImports,
408
475
  signals,
409
476
  stateful,
@@ -1,5 +1,5 @@
1
1
  import { ClarusError } from './errors.js';
2
- import { importNames, parse } from './parse.js';
2
+ import { awaitLists, importNames, parse } from './parse.js';
3
3
  const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
4
4
  const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
5
5
  function* elements(nodes) {
@@ -18,6 +18,9 @@ function* elements(nodes) {
18
18
  }
19
19
  else if (n.type === 'fill')
20
20
  yield* elements(n.children);
21
+ else if (n.type === 'await')
22
+ for (const kids of awaitLists(n))
23
+ yield* elements(kids);
21
24
  }
22
25
  }
23
26
  function* expressions(nodes) {
@@ -52,6 +55,11 @@ function* expressions(nodes) {
52
55
  }
53
56
  else if (n.type === 'fill')
54
57
  yield* expressions(n.children);
58
+ else if (n.type === 'await') {
59
+ yield n.expr;
60
+ for (const kids of awaitLists(n))
61
+ yield* expressions(kids);
62
+ }
55
63
  }
56
64
  }
57
65
  const has = (el, name) => el.attrs.some((a) => a.name === name);
@@ -66,6 +74,8 @@ function named(nodes, components) {
66
74
  return n.branches.some((b) => named(b.children, components));
67
75
  if (n.type === 'for')
68
76
  return named(n.children, components);
77
+ if (n.type === 'await')
78
+ return awaitLists(n).some((kids) => named(kids, components));
69
79
  if (n.type !== 'element')
70
80
  return false;
71
81
  if (components.has(n.tag) || n.tag === 'slot' || n.tag === 'title' || labelled(n))
@@ -135,6 +145,7 @@ export function lint(source, file, config = {}, extra = []) {
135
145
  const corpus = [
136
146
  ...expressions(parsed.nodes),
137
147
  parsed.script?.code ?? '',
148
+ parsed.serverScript?.code ?? '',
138
149
  ...parsed.inputs.flatMap((i) => [i.type, i.default ?? '']),
139
150
  ...parsed.types.map((t) => t.type),
140
151
  ].join('\n');
@@ -32,6 +32,16 @@ export type Attr = {
32
32
  })[];
33
33
  start: number;
34
34
  };
35
+ /** An @await's lists of children: pending, then @then's and @catch's (those it has). */
36
+ export declare const awaitLists: (n: Extract<TemplateNode, {
37
+ type: 'await';
38
+ }>) => TemplateNode[][];
39
+ /** An @await's @then or @catch: the name it binds, and its content. */
40
+ export type AwaitBranch = {
41
+ name: string;
42
+ nameStart: number;
43
+ children: TemplateNode[];
44
+ };
35
45
  /**
36
46
  * A node of a template's syntax tree: an element, text, a `{{ }}` hole, an `@if`, an `@for`, a slot fill…
37
47
  * @see https://clarusjs.com/reference/compiler#parse
@@ -63,6 +73,14 @@ export type TemplateNode = {
63
73
  children: TemplateNode[];
64
74
  }[];
65
75
  start: number;
76
+ } | {
77
+ type: 'await';
78
+ expr: string;
79
+ exprStart: number;
80
+ pending: TemplateNode[];
81
+ then: AwaitBranch | null;
82
+ catch: AwaitBranch | null;
83
+ start: number;
66
84
  } | {
67
85
  type: 'fill';
68
86
  name: string;
@@ -139,6 +157,12 @@ export type ParsedFile = {
139
157
  code: string;
140
158
  start: number;
141
159
  };
160
+ /** <script server> (#430): runs at render on the server only. `tag` = offset of `<script`. */
161
+ serverScript?: {
162
+ code: string;
163
+ start: number;
164
+ tag: number;
165
+ };
142
166
  styles: {
143
167
  css: string;
144
168
  mode: 'scoped' | 'global' | 'plain';
@@ -1,4 +1,5 @@
1
1
  import { ClarusError } from './errors.js';
2
+ export const awaitLists = (n) => [n.pending, ...(n.then ? [n.then.children] : []), ...(n.catch ? [n.catch.children] : [])];
2
3
  export const FOR_IMPLICIT = ['$index', '$count', '$first', '$last', '$even', '$odd'];
3
4
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
4
5
  const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
@@ -285,6 +286,49 @@ export function parse(source, file) {
285
286
  }
286
287
  return fail(`unclosed ( after ${keyword}`, open);
287
288
  }
289
+ function awaitBlock() {
290
+ const start = i;
291
+ i += 6;
292
+ const { cond: expr, condStart: exprStart } = condition('@await');
293
+ const open = () => {
294
+ while (/\s/.test(source[i] ?? ''))
295
+ i++;
296
+ if (source[i] !== '{')
297
+ fail('expected { to open the block', i);
298
+ i++;
299
+ };
300
+ open();
301
+ const pending = children({ tag: '@await', start, block: true });
302
+ let then = null;
303
+ let caught = null;
304
+ for (;;) {
305
+ const save = i;
306
+ while (/\s/.test(source[i] ?? ''))
307
+ i++;
308
+ const kw = /^@(then|catch)[\s(]/.exec(source.slice(i, i + 7))?.[1];
309
+ if (!kw) {
310
+ i = save;
311
+ break;
312
+ }
313
+ const at = i;
314
+ if (kw === 'then' && caught)
315
+ fail('@then comes before @catch', at);
316
+ if ((kw === 'then' && then) || (kw === 'catch' && caught))
317
+ fail(`only one @${kw} per @await`, at);
318
+ i += kw.length + 1;
319
+ const { cond: name, condStart: nameStart } = condition(`@${kw}`);
320
+ const what = kw === 'then' ? 'value' : 'error';
321
+ if (!/^[A-Za-z_$][\w$]*$/.test(name))
322
+ fail(`@${kw} takes a name for the ${what}: @${kw} (${what})`, nameStart);
323
+ open();
324
+ const branch = { name, nameStart, children: children({ tag: `@${kw}`, start: at, block: true }) };
325
+ if (kw === 'then')
326
+ then = branch;
327
+ else
328
+ caught = branch;
329
+ }
330
+ return { type: 'await', expr, exprStart, pending, then, catch: caught, start };
331
+ }
288
332
  function ifBlock() {
289
333
  const start = i;
290
334
  i += 3;
@@ -447,6 +491,14 @@ export function parse(source, file) {
447
491
  nodes.push(ifBlock());
448
492
  textStart = i;
449
493
  }
494
+ else if (/^@await[\s(]/.test(source.slice(i, i + 7))) {
495
+ flush();
496
+ nodes.push(awaitBlock());
497
+ textStart = i;
498
+ }
499
+ else if (/^@(then|catch)[\s(]/.test(source.slice(i, i + 7))) {
500
+ fail(`${/^@\w+/.exec(source.slice(i))[0]} without @await before it`, i);
501
+ }
450
502
  else if (/^@for[\s(]/.test(source.slice(i, i + 5))) {
451
503
  flush();
452
504
  nodes.push(forBlock());
@@ -525,6 +577,20 @@ export function parse(source, file) {
525
577
  nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
526
578
  i = selfClosing ? i : end + '</script>'.length;
527
579
  }
580
+ else if (tag === 'script' && list.some((a) => a.name === 'server')) {
581
+ if (parent)
582
+ fail('<script server> must be at the top level (it runs once per render, before the template)', start);
583
+ if (out.serverScript)
584
+ fail('only one <script server> block is allowed', start);
585
+ const other = list.find((a) => a.name !== 'server');
586
+ if (other)
587
+ fail('<script server> takes no other attributes', other.start);
588
+ const end = source.indexOf('</script>', i);
589
+ if (end === -1)
590
+ fail('unclosed <script server>', start);
591
+ out.serverScript = { code: source.slice(i, end), start: i, tag: start };
592
+ i = end + '</script>'.length;
593
+ }
528
594
  else if (tag === 'script') {
529
595
  if (parent)
530
596
  fail('<script> must be at the top level (a component script); add `inline` for a script that runs where it stands', start);
@@ -15,13 +15,22 @@ export declare function scriptNames(code: string): Set<string>;
15
15
  * Island scripts are bundled for the browser, so `node:` imports are a build error.
16
16
  */
17
17
  /** Import statements (text and offset in `code`), and the body with them blanked out. */
18
- export declare function splitImports(code: string, file: string, source: string, offset: number): {
18
+ export declare function splitImports(code: string, file: string, source: string, offset: number, server?: boolean): {
19
19
  imports: {
20
20
  text: string;
21
21
  start: number;
22
22
  }[];
23
23
  body: string;
24
24
  };
25
+ /**
26
+ * A `<script server>` (#430): its imports (hoisted to the server module, `node:` allowed: it never reaches a browser),
27
+ * the rest (run at the top of render), and whether it awaits at the top level (then render is async).
28
+ */
29
+ export declare function serverScriptParts(code: string, file: string, source: string, offset: number): {
30
+ imports: string[];
31
+ body: string;
32
+ awaits: boolean;
33
+ };
25
34
  /**
26
35
  * Where type annotations go for type checking: `: any` after the untyped parameters of the script's own functions
27
36
  * (declarations, `const f = (x) => …`, class methods) and of callbacks passed straight to them (`record((p) => …)`).
@@ -184,14 +184,14 @@ function signalCall(init) {
184
184
  const name = init.callee.name;
185
185
  return name === 'state' || name === 'derived' || name === 'shared' ? name : undefined;
186
186
  }
187
- export function splitImports(code, file, source, offset) {
187
+ export function splitImports(code, file, source, offset, server = false) {
188
188
  const imports = [];
189
189
  let body = code;
190
190
  for (const stmt of parseScript(code, file, source, offset).body) {
191
191
  if (stmt.type !== 'ImportDeclaration')
192
192
  continue;
193
193
  const from = String(stmt.source.value);
194
- if (from.startsWith('node:')) {
194
+ if (!server && from.startsWith('node:')) {
195
195
  throw new ClarusError(`\`${from}\` can't be imported in an island script: the script is bundled for the browser`, file, source, offset + stmt.start);
196
196
  }
197
197
  imports.push({ text: code.slice(stmt.start, stmt.end), start: stmt.start });
@@ -199,6 +199,20 @@ export function splitImports(code, file, source, offset) {
199
199
  }
200
200
  return { imports, body };
201
201
  }
202
+ export function serverScriptParts(code, file, source, offset) {
203
+ const ast = parseScript(code, file, source, offset);
204
+ const imports = [];
205
+ let body = code;
206
+ for (const stmt of ast.body) {
207
+ if (stmt.type.startsWith('Export'))
208
+ throw new ClarusError('a <script server> cannot export anything: its names are for the template', file, source, offset + stmt.start);
209
+ if (stmt.type !== 'ImportDeclaration')
210
+ continue;
211
+ imports.push(code.slice(stmt.start, stmt.end));
212
+ body = body.slice(0, stmt.start) + code.slice(stmt.start, stmt.end).replace(/[^\n]/g, ' ') + body.slice(stmt.end);
213
+ }
214
+ return { imports, body, awaits: !!topLevelAwait(ast) };
215
+ }
202
216
  export function untypedParams(code) {
203
217
  const ast = parseScript(code);
204
218
  const isFn = (n) => !!n && (n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression');
@@ -254,7 +268,7 @@ export function analyzeScript(code, file, source, offset) {
254
268
  }
255
269
  const tla = topLevelAwait(ast);
256
270
  if (tla)
257
- throw new ClarusError("top-level await isn't supported in a <script> (rendering is synchronous): await inside a function, such as a resource's fetcher or an event handler", file, source, offset + tla.start);
271
+ throw new ClarusError("an island's <script> can't await at the top level (the browser attaches it without waiting): await data on the server in a <script server>, or in the browser inside a function, such as a resource()'s fetcher or an event handler", file, source, offset + tla.start);
258
272
  for (const stmt of ast.body) {
259
273
  if (stmt.type.startsWith('Export')) {
260
274
  throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);