brumate 0.3.0 → 0.4.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 (122) hide show
  1. package/README.md +2 -2
  2. package/check.d.ts +49 -0
  3. package/dist/{boot-C25Sa6vq.d.ts → boot-DLlRmD9z.d.ts} +8 -10
  4. package/dist/cli.js +275 -15
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-BvDsC6Qr.js +3463 -0
  7. package/dist/client-BvDsC6Qr.js.map +1 -0
  8. package/dist/{client-D0CqSxoO.d.ts → client-DBwL2wKQ.d.ts} +390 -181
  9. package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
  10. package/dist/client-routes-BtGpYCef.js.map +1 -0
  11. package/dist/{cookies-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
  12. package/dist/cookies-Cnbf4w-S.js.map +1 -0
  13. package/dist/{defer-BbD7JQhj.js → defer-CKWZLv2K.js} +4 -4
  14. package/dist/defer-CKWZLv2K.js.map +1 -0
  15. package/dist/{devtools-CQgD7NPB.js → devtools-4uTPwR_v.js} +56 -82
  16. package/dist/devtools-4uTPwR_v.js.map +1 -0
  17. package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-Be9pxYgv.js} +397 -333
  18. package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
  19. package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
  20. package/dist/events-LgLdp1R7.js.map +1 -0
  21. package/dist/features-CHY5Ekku.js +30 -0
  22. package/dist/features-CHY5Ekku.js.map +1 -0
  23. package/dist/files-WW4RlajL.js +506 -0
  24. package/dist/files-WW4RlajL.js.map +1 -0
  25. package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
  26. package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
  27. package/dist/forms-nXK7-Lv_.js.map +1 -0
  28. package/dist/highlight.js +31 -22
  29. package/dist/highlight.js.map +1 -1
  30. package/dist/{html-mNTKzaDD.js → html-BtKRyi7g.js} +86 -22
  31. package/dist/html-BtKRyi7g.js.map +1 -0
  32. package/dist/{html-Bq1rFxX_.d.ts → html-Bw9Qwu6F.d.ts} +20 -5
  33. package/dist/index.d.ts +96 -10
  34. package/dist/index.js +639 -104
  35. package/dist/index.js.map +1 -1
  36. package/dist/{inspect-BHpOw1LF.js → inspect-Y6y4uNZp.js} +3751 -676
  37. package/dist/inspect-Y6y4uNZp.js.map +1 -0
  38. package/dist/{loader-Dos_3NP0.js → loader-BjKGJzLN.js} +20 -14
  39. package/dist/loader-BjKGJzLN.js.map +1 -0
  40. package/dist/logo-DQ_OYhBi.js +10 -0
  41. package/dist/logo-DQ_OYhBi.js.map +1 -0
  42. package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
  43. package/dist/navigate-CfOr-TRF.js.map +1 -0
  44. package/dist/nesting-DA5vJw9X.js +265 -0
  45. package/dist/nesting-DA5vJw9X.js.map +1 -0
  46. package/dist/{produce-Doc91GkX.js → produce-B7X9ori9.js} +137 -9
  47. package/dist/produce-B7X9ori9.js.map +1 -0
  48. package/dist/{produce-D0V0ICkz.d.ts → produce-DIgHBVwL.d.ts} +39 -5
  49. package/dist/{rpc-ygMRPmN4.js → rpc-Q-XkLwFh.js} +11 -6
  50. package/dist/rpc-Q-XkLwFh.js.map +1 -0
  51. package/dist/runtime/batch.js +9 -7
  52. package/dist/runtime/batch.js.map +1 -1
  53. package/dist/runtime/client.d.ts +4 -4
  54. package/dist/runtime/client.js +4 -4
  55. package/dist/runtime/devtools.d.ts +11 -29
  56. package/dist/runtime/devtools.js +3 -1
  57. package/dist/runtime/env.js +14 -2
  58. package/dist/runtime/env.js.map +1 -1
  59. package/dist/runtime/events.d.ts +23 -1
  60. package/dist/runtime/events.js +1 -1
  61. package/dist/runtime/forms.d.ts +2 -2
  62. package/dist/runtime/forms.js +1 -1
  63. package/dist/runtime/hot.d.ts +1 -1
  64. package/dist/runtime/hot.js +5 -2
  65. package/dist/runtime/hot.js.map +1 -1
  66. package/dist/runtime/html.d.ts +2 -2
  67. package/dist/runtime/html.js +1 -1
  68. package/dist/runtime/loader.d.ts +2 -2
  69. package/dist/runtime/loader.js +2 -2
  70. package/dist/runtime/routes.js +4 -1
  71. package/dist/runtime/routes.js.map +1 -1
  72. package/dist/runtime/server.d.ts +5 -5
  73. package/dist/runtime/server.js +5 -5
  74. package/dist/runtime/signals.d.ts +38 -1
  75. package/dist/runtime/signals.js +33 -1
  76. package/dist/runtime/signals.js.map +1 -1
  77. package/dist/runtime/static-loader.d.ts +2 -2
  78. package/dist/runtime/static-loader.js +1 -1
  79. package/dist/runtime/testing.d.ts +18 -3
  80. package/dist/runtime/testing.js +150 -33
  81. package/dist/runtime/testing.js.map +1 -1
  82. package/dist/{server-DuFYRXrd.d.ts → server-BvPIg9pT.d.ts} +84 -22
  83. package/dist/{server-CxVDYE_V.js → server-DjyOVJtJ.js} +598 -164
  84. package/dist/server-DjyOVJtJ.js.map +1 -0
  85. package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
  86. package/dist/{static-loader-nZssh66R.js → static-loader-BZR17hSw.js} +78 -99
  87. package/dist/static-loader-BZR17hSw.js.map +1 -0
  88. package/dist/{stream-DCYZO4IF.js → stream-BP5AVmg5.js} +102 -16
  89. package/dist/stream-BP5AVmg5.js.map +1 -0
  90. package/dist/vite.d.ts +13 -20
  91. package/dist/vite.js +1890 -548
  92. package/dist/vite.js.map +1 -1
  93. package/elements.d.ts +951 -0
  94. package/forms/forms.brm.ts +3 -3
  95. package/package.json +12 -3
  96. package/skills/brumate/SKILL.md +58 -0
  97. package/skills/brumate/references/errors.md +2078 -0
  98. package/skills/brumate/references/events.md +117 -0
  99. package/skills/brumate/references/signals.md +61 -0
  100. package/skills/brumate/references/state.md +235 -0
  101. package/skills/brumate/references/syntax.md +250 -0
  102. package/types.d.ts +4 -4
  103. package/dist/client-BD6XT-s5.js +0 -1968
  104. package/dist/client-BD6XT-s5.js.map +0 -1
  105. package/dist/client-routes-JTbGtukf.js.map +0 -1
  106. package/dist/cookies-BzllthiF.js.map +0 -1
  107. package/dist/defer-BbD7JQhj.js.map +0 -1
  108. package/dist/devtools-CQgD7NPB.js.map +0 -1
  109. package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
  110. package/dist/events-CSs7OwIC.js.map +0 -1
  111. package/dist/files-BXSSrQgc.js +0 -205
  112. package/dist/files-BXSSrQgc.js.map +0 -1
  113. package/dist/forms-Bg-CwGqX.js.map +0 -1
  114. package/dist/html-mNTKzaDD.js.map +0 -1
  115. package/dist/inspect-BHpOw1LF.js.map +0 -1
  116. package/dist/loader-Dos_3NP0.js.map +0 -1
  117. package/dist/navigate-O78d_zGN.js.map +0 -1
  118. package/dist/produce-Doc91GkX.js.map +0 -1
  119. package/dist/rpc-ygMRPmN4.js.map +0 -1
  120. package/dist/server-CxVDYE_V.js.map +0 -1
  121. package/dist/static-loader-nZssh66R.js.map +0 -1
  122. package/dist/stream-DCYZO4IF.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as analyzeProject, B as isWithin, D as unmarked, F as parse, I as buildGraph, L as BrumateError, N as resolveRelative, P as summarize, R as getLocation, S as sharedSites, V as lookup, b as SHARED_QUERY, d as generateServer$1, g as createPlan, h as clientState, i as report, j as analyzeProjectProps, l as generateClient$1, m as blockBodies, n as formatReport, o as CompileError, r as inspect, s as compile, u as generateRender$1, v as getComponentName, x as generateShared, z as analyze } from "./inspect-BHpOw1LF.js";
1
+ import { A as analyzeProject, B as getLocation, D as unmarked, F as resolveRelative, G as isWithin, H as findError, I as summarize, K as lookup, L as parse, R as buildGraph, S as sharedSites, U as analyze, V as errorLink, W as getPatternNames, b as SHARED_QUERY, d as generateServer$1, g as createPlan, h as clientState, i as report, j as analyzeProjectProps, l as generateClient$1, m as blockBodies, n as formatReport, o as CompileError, r as inspect, s as compile, u as generateRender$1, v as getComponentName, x as generateShared, z as BrumateError } from "./inspect-Y6y4uNZp.js";
2
2
  //#region src/print.ts
3
3
  function at(source, range) {
4
4
  const { line, column } = getLocation(source, range.start);
@@ -7,13 +7,22 @@ function at(source, range) {
7
7
  function quote(text) {
8
8
  return JSON.stringify(text);
9
9
  }
10
+ function printAttributes(items) {
11
+ let text = "";
12
+ for (const item of items) text += ` ${printAttribute(item)}`;
13
+ return text;
14
+ }
15
+ function printModifiers(modifiers) {
16
+ let text = "";
17
+ for (const modifier of modifiers) text += `:${modifier}`;
18
+ return text;
19
+ }
10
20
  function printAttribute(item) {
11
21
  switch (item.kind) {
12
22
  case "static": return item.value === true ? item.name : `${item.name}=${quote(item.value)}`;
13
23
  case "value": return `${item.name}=(${item.value.code})`;
14
- case "event": return `${item.name}${item.modifiers.map((modifier) => `:${modifier}`).join("")}=(${item.handler.code})`;
15
- case "ref": return `ref=${item.target}`;
16
- case "prefetch": return `prefetch=${quote(item.strategy)}`;
24
+ case "event": return `${item.name}${printModifiers(item.modifiers)}=(${item.handler.code})`;
25
+ case "ref": return `ref=$bind(${item.target})`;
17
26
  case "spread": return `{...${item.value.code}}`;
18
27
  case "computed": return `[${item.name.code}]${item.value === true ? "" : `=(${item.value.code})`}`;
19
28
  }
@@ -21,10 +30,10 @@ function printAttribute(item) {
21
30
  /** Prints the syntax tree, one node per line. */
22
31
  function printAST(file) {
23
32
  const lines = [];
24
- const write = (depth, text) => {
33
+ function write(depth, text) {
25
34
  lines.push(`${" ".repeat(depth)}${text}`);
26
- };
27
- const body = (item, depth, label) => {
35
+ }
36
+ function body(item, depth, label) {
28
37
  write(depth, label);
29
38
  if (item.script) write(depth + 1, "script");
30
39
  for (const template of item.templates) {
@@ -32,8 +41,8 @@ function printAST(file) {
32
41
  body(template.body, depth + 2, "body");
33
42
  }
34
43
  nodes(item.children, depth + 1);
35
- };
36
- const block = (item, depth) => {
44
+ }
45
+ function block(item, depth) {
37
46
  switch (item.kind) {
38
47
  case "if":
39
48
  write(depth, "if");
@@ -43,8 +52,7 @@ function printAST(file) {
43
52
  case "for": {
44
53
  const key = item.key === void 0 ? "" : ` by ${item.key === "index" ? "index" : item.key.code}`;
45
54
  const index = item.index ? `, ${item.index.name}` : "";
46
- const itemCode = file.source.slice(item.item.start, item.item.end);
47
- write(depth, `for (${itemCode}${index} of ${item.list.code.trim()}${key})`);
55
+ write(depth, `for (${file.source.slice(item.item.start, item.item.end)}${index} of ${item.list.code.trim()}${key})`);
48
56
  body(item.body, depth + 1, "body");
49
57
  if (item.fallback) body(item.fallback, depth + 1, "else");
50
58
  break;
@@ -70,7 +78,10 @@ function printAST(file) {
70
78
  case "try": {
71
79
  write(depth, "try");
72
80
  body(item.body, depth + 1, "body");
73
- const names = [item.error?.name, item.reset?.name].filter(Boolean).join(", ");
81
+ const found = [];
82
+ if (item.error?.name) found.push(item.error.name);
83
+ if (item.reset?.name) found.push(item.reset.name);
84
+ const names = found.join(", ");
74
85
  body(item.fallback, depth + 1, names ? `catch (${names})` : "catch");
75
86
  break;
76
87
  }
@@ -93,19 +104,19 @@ function printAST(file) {
93
104
  body(item.body, depth + 1, "body");
94
105
  if (item.fallback) body(item.fallback, depth + 1, "else");
95
106
  }
96
- };
97
- const node = (item, depth) => {
107
+ }
108
+ function node(item, depth) {
98
109
  switch (item.kind) {
99
110
  case "element":
100
111
  case "component": {
101
112
  const name = item.kind === "element" ? item.tag : item.name;
102
- const attributes = item.attributes.map((value) => ` ${printAttribute(value)}`).join("");
113
+ const attributes = printAttributes(item.attributes);
103
114
  write(depth, `${item.kind} <${name}${attributes}>`);
104
115
  nodes(item.children, depth + 1);
105
116
  break;
106
117
  }
107
118
  case "dynamic":
108
- write(depth, `dynamic <{${item.tag.code}}${item.attributes.map((value) => ` ${printAttribute(value)}`).join("")}>`);
119
+ write(depth, `dynamic <{${item.tag.code}}${printAttributes(item.attributes)}>`);
109
120
  nodes(item.children, depth + 1);
110
121
  break;
111
122
  case "fragment":
@@ -113,7 +124,7 @@ function printAST(file) {
113
124
  nodes(item.children, depth + 1);
114
125
  break;
115
126
  case "listener":
116
- write(depth, `listener <${item.target}${item.attributes.map((value) => ` ${printAttribute(value)}`).join("")}>`);
127
+ write(depth, `listener <${item.target}${printAttributes(item.attributes)}>`);
117
128
  break;
118
129
  case "text":
119
130
  write(depth, `text ${quote(item.value)}`);
@@ -123,10 +134,10 @@ function printAST(file) {
123
134
  break;
124
135
  default: block(item, depth);
125
136
  }
126
- };
127
- const nodes = (items, depth) => {
137
+ }
138
+ function nodes(items, depth) {
128
139
  for (const item of items) node(item, depth);
129
- };
140
+ }
130
141
  if (file.moduleScript) write(0, "script module");
131
142
  if (file.instanceScript) write(0, file.generics ? `script generics=${quote(file.generics)}` : "script");
132
143
  for (const style of file.styles) {
@@ -163,9 +174,14 @@ function printModel(source, model) {
163
174
  lines.push("sites");
164
175
  for (const site of model.sites) {
165
176
  const parts = [siteLabel(source, site)];
166
- const reads = [...new Set(site.reads.map((read) => (read.tracked ? "" : "~") + read.declaration.name))];
167
- const writes = [...new Set(site.writes.map((write) => write.declaration.name))];
168
- const calls = [...site.calls].map((declaration) => declaration.name);
177
+ const readSet = /* @__PURE__ */ new Set();
178
+ for (const read of site.reads) readSet.add((read.tracked ? "" : "~") + read.declaration.name);
179
+ const reads = [...readSet];
180
+ const writeSet = /* @__PURE__ */ new Set();
181
+ for (const write of site.writes) writeSet.add(write.declaration.name);
182
+ const writes = [...writeSet];
183
+ const calls = [];
184
+ for (const declaration of site.calls) calls.push(declaration.name);
169
185
  if (reads.length > 0) parts.push(`reads ${reads.join(", ")}`);
170
186
  if (writes.length > 0) parts.push(`writes ${writes.join(", ")}`);
171
187
  if (calls.length > 0) parts.push(`calls ${calls.join(", ")}`);
@@ -185,13 +201,15 @@ function nodeLabel(source, node) {
185
201
  function printGraph(source, graph) {
186
202
  const lines = ["nodes"];
187
203
  for (const node of graph.nodes) {
188
- const from = graph.edges.filter((edge) => edge.to === node).map((edge) => nodeLabel(source, edge.from));
204
+ const from = [];
205
+ for (const edge of graph.edges) if (edge.to === node) from.push(nodeLabel(source, edge.from));
189
206
  const state = graph.live.has(node) ? "live" : "static";
190
207
  lines.push(` ${nodeLabel(source, node)} ${state}${from.length > 0 ? ` <- ${from.join(", ")}` : ""}`);
191
208
  }
192
209
  lines.push("client");
193
210
  for (const site of graph.model.sites) if (graph.reached.has(site)) lines.push(` ${siteLabel(source, site)}${site.kind === "server-function" ? " (stub)" : ""}`);
194
- const created = graph.model.scopes.filter((scope) => graph.created.has(scope));
211
+ const created = [];
212
+ for (const scope of graph.model.scopes) if (graph.created.has(scope)) created.push(scope);
195
213
  if (created.length > 0) {
196
214
  lines.push("created");
197
215
  for (const scope of created) lines.push(` ${scopeLabel(source, scope)}`);
@@ -212,10 +230,12 @@ function generateRender(file, plan) {
212
230
  /** Generates the client entry and its parts. */
213
231
  function generateClient(file, plan, merge) {
214
232
  const result = generateClient$1(file, plan, merge);
233
+ const parts = {};
234
+ for (const [name, code] of Object.entries(result.parts)) parts[name] = unmarked(code);
215
235
  return {
216
236
  ...result,
217
237
  code: unmarked(result.code),
218
- parts: Object.fromEntries(Object.entries(result.parts).map(([name, code]) => [name, unmarked(code)]))
238
+ parts
219
239
  };
220
240
  }
221
241
  //#endregion
@@ -231,18 +251,57 @@ const COMPONENT = "$$Component";
231
251
  */
232
252
  const HELPERS = `/// <reference types="brumate/types" />
233
253
  type $$Component<P> = (props: P, ...rest: any[]) => unknown;
234
- declare function $$component<P>(component: $$Component<P>, props: P): void;
235
- declare function $$dynamic(tag: string | $$Component<any>, props: Record<string, unknown>): void;
236
- type $$Event<K, M> = K extends keyof M ? M[K] : Event;
254
+ type $$Markup = import('brumate/elements').Markup;
255
+ declare const $$markup: $$Markup;
256
+ /** \`Omit\` that keeps the index signatures, for the rest of a \`$props\` call. */
257
+ type $$Omit<T, K> = { [P in keyof T as P extends K ? never : P]: T[P] };
258
+ type $$Elements = import('brumate/elements').Elements;
259
+ /** The values that a spread can get and that spread nothing. */
260
+ type $$Falsy = false | 0 | '' | 0n | null | undefined;
261
+ // The helpers of elements are curried and constrained by \`keyof Elements\`, with a second overload
262
+ // for other tags. A parameter typed from a generic \`T extends string\` made TypeScript resolve the
263
+ // attributes of every tag, in the call and in the declaration of each file, which tripled the time.
264
+ /** Checks the attributes of a plain element against its type. A tag that \`Elements\` lacks takes any. */
265
+ declare function $$element<T extends keyof $$Elements>(tag: T): (attributes: $$Elements[T]) => void;
266
+ declare function $$element(tag: string): (attributes: Record<string, unknown>) => void;
267
+ /** Checks the names of a spread onto a plain element, which has no excess check. \`$$element\` checks its values. */
268
+ declare function $$spread<T extends keyof $$Elements>(tag: T): <S>(value: (S & { [K in Exclude<keyof S, keyof $$Elements[T]>]: { [M in \`\${K & string} is not an attribute of <\${T}>\`]: never } }) | $$Falsy) => void;
269
+ declare function $$spread(tag: string): (value: object | $$Falsy) => void;
270
+ /** A spread value without its falsy part, which spreads nothing, such as \`false\` of \`cond && { ... }\`. Its object part is checked. */
271
+ declare function $$present<T>(value: T): Exclude<T, $$Falsy>;
272
+ /** \`$bind\` of a \`ref\`, which needs no import in markup. */
273
+ declare function $$bind<T>(signal: T): import('brumate/signals').BoundSignal<T>;
274
+ // A dynamic tag. The helpers are curried, as those of elements: an element name checks the
275
+ // attributes of its element, a component its props, and a tag that can be either, such as a
276
+ // generic \`T extends AsTarget\`, the global attributes of an HTML or SVG element. A handler is
277
+ // typed by \`$$handler\`, since a union of element names gives a union of handlers, which types
278
+ // no parameter. The first overload takes any string, not \`keyof Elements\`: a tag such as
279
+ // \`AsTarget\` fails it at once, where a failed \`keyof Elements\` cost about 50 ms for each call.
280
+ // The types live in \`brumate/check\`, so TypeScript resolves them once, not in each file.
281
+ type $$AnyTag = keyof $$Elements | import('brumate/elements').Component;
282
+ declare function $$dynamic<T extends string>(tag: T): (attributes: import('brumate/check').DynamicAttributes<T> & { children?: $$Markup }, ...spreads: import('brumate/check').DynamicAttributes<T>[]) => void;
283
+ declare function $$dynamic<P>(tag: $$Component<P>): import('brumate/check').DynamicProps<P>;
284
+ // The spreads of a tag that can be either are not checked: a part spreads its rest, whose type
285
+ // depends on the tag, and attributes of a context, typed as any.
286
+ declare function $$dynamic(tag: $$AnyTag): (attributes: import('brumate/check').AnyTagAttributes, ...spreads: object[]) => void;
287
+ declare function $$handler<T extends string>(tag: T): import('brumate/check').DynamicHandle<$$Element<T>>;
288
+ declare function $$handler(tag: $$Component<never>): <H>(event: string, handler: H) => H;
289
+ declare function $$handler(tag: $$AnyTag): import('brumate/check').DynamicHandle<HTMLElement | SVGElement>;
290
+ type $$Events = import('brumate/elements').ElementEvents;
237
291
  type $$Element<T> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement;
238
- declare function $$on<T extends string, K extends string>(tag: T, event: K, handler: (event: $$Event<K, HTMLElementEventMap> & { currentTarget: $$Element<T> }) => unknown): void;
239
- declare function $$onWindow<K extends string>(event: K, handler: (event: $$Event<K, WindowEventMap> & { currentTarget: Window }) => unknown): void;
240
- declare function $$onDocument<K extends string>(event: K, handler: (event: $$Event<K, DocumentEventMap> & { currentTarget: Document }) => unknown): void;
292
+ declare function $$on<T extends string, K extends keyof $$Events & string>(tag: T, event: K, handler: (event: $$Events[K] & { currentTarget: $$Element<T> }) => unknown): void;
293
+ declare function $$onWindow<K extends keyof WindowEventMap & string>(event: K, handler: (event: WindowEventMap[K] & { currentTarget: Window }) => unknown): void;
294
+ declare function $$onDocument<K extends keyof DocumentEventMap & string>(event: K, handler: (event: DocumentEventMap[K] & { currentTarget: Document }) => unknown): void;
241
295
  declare function $$use(...values: unknown[]): void;
296
+ /** The type of the name of a template that is written at each use. Only its name is read. */
297
+ declare const $$template: (...args: any[]) => Promise<$$Markup>;
242
298
  type $$Plain = string | number | boolean | bigint | null | undefined | Date | Error | URL | URLSearchParams | ArrayBuffer | ArrayBufferView | Headers | FormData | Request | Response | ReadableStream<any> | AbortSignal | Event | DOMException | ImageData;
243
299
  type $$Sendable<T> = T extends $$Plain | import('brumate/serial').AppValue ? T : T extends { brumateId: string } ? T : T extends RegExp ? { 'A regular expression cannot be sent to the client. Send its source and flags': never } : T extends (...args: any[]) => any ? { 'A function cannot be sent to the client. Keep it out of the signal or memo': never } : T extends Promise<infer U> ? Promise<$$Sendable<U>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<$$Sendable<K>, $$Sendable<V>> : T extends ReadonlySet<infer V> ? ReadonlySet<$$Sendable<V>> : T extends object ? { [K in keyof T]: $$Sendable<T[K]> } : T;
244
300
  /** Checks a value that the page state sends to the client. */
245
301
  declare function $$sendable<T>(value: T & $$Sendable<T>): void;
302
+ /** Checks a signal that only a ref binds: the browser fills it with an element, and anything else is sent. */
303
+ type $$SendableRef<T> = T extends Element | null | undefined ? T : $$Sendable<T>;
304
+ declare function $$sendableRef<T>(value: T & $$SendableRef<T>): void;
246
305
  `;
247
306
  var Writer = class {
248
307
  code = "";
@@ -251,6 +310,11 @@ var Writer = class {
251
310
  constructor(source) {
252
311
  this.source = source;
253
312
  }
313
+ /** Starts the code again, to write the file another way. */
314
+ reset() {
315
+ this.code = "";
316
+ this.mappings = [];
317
+ }
254
318
  text(value) {
255
319
  this.code += value;
256
320
  }
@@ -272,6 +336,39 @@ var Writer = class {
272
336
  });
273
337
  this.code += text;
274
338
  }
339
+ /**
340
+ * Writes the name of an event as a string. It stands in place of the attribute name, which has
341
+ * the same length, so that the error of an unknown event is at the attribute.
342
+ */
343
+ event(attribute) {
344
+ const start = this.source[attribute.start] === "{" ? attribute.handler.start : attribute.start;
345
+ this.stand({
346
+ start,
347
+ end: start + attribute.name.length
348
+ }, JSON.stringify(attribute.event));
349
+ }
350
+ /**
351
+ * Writes a property name that stands for a range of the file. A name that is not an identifier
352
+ * is quoted, and its quotes are mapped to the first and last characters of the range, so an
353
+ * error at the name spans the range. So is a name whose length differs from the range, such as
354
+ * `children` for the children of a component.
355
+ */
356
+ key(range, name) {
357
+ if (/^[A-Za-z_$][\w$]*$/.test(name) && this.source.slice(range.start, range.end) === name) {
358
+ this.copy(range);
359
+ return;
360
+ }
361
+ const text = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
362
+ this.stand({
363
+ start: range.start,
364
+ end: range.start + 1
365
+ }, text[0]);
366
+ this.text(text.slice(1, -1));
367
+ this.stand({
368
+ start: range.end - 1,
369
+ end: range.end
370
+ }, text.at(-1));
371
+ }
275
372
  /** Copies an expression in parentheses. */
276
373
  expression(expression) {
277
374
  this.text("(");
@@ -282,57 +379,235 @@ var Writer = class {
282
379
  function isTopLevel(statement) {
283
380
  return statement.type === "ImportDeclaration" || statement.type === "TSTypeAliasDeclaration" || statement.type === "TSInterfaceDeclaration" || statement.type === "ExportNamedDeclaration" && (statement.exportKind === "type" || statement.declaration?.type === "TSTypeAliasDeclaration" || statement.declaration?.type === "TSInterfaceDeclaration");
284
381
  }
285
- /** Finds the type argument of `$props<T>()`, as a range of the file. */
286
- function propsType(program) {
287
- let found;
288
- const visit = (node) => {
289
- if (found || typeof node !== "object" || node === null) return;
382
+ /**
383
+ * Finds the type arguments of the calls of `$props<T>()`, as ranges of the file. A component can
384
+ * call it more than once, such as once with `const` and once with `let` for its bindable props.
385
+ */
386
+ function propsTypes(program) {
387
+ const found = [];
388
+ function visit(node) {
389
+ if (typeof node !== "object" || node === null) return;
290
390
  const value = node;
291
391
  if (value.type === "CallExpression" && value.callee?.type === "Identifier" && value.callee.name === "$props" && value.typeArguments?.params[0]) {
292
- found = value.typeArguments.params[0];
392
+ found.push(value.typeArguments.params[0]);
293
393
  return;
294
394
  }
295
- for (const child of Object.values(value)) if (Array.isArray(child)) child.forEach(visit);
395
+ for (const child of Object.values(value)) if (Array.isArray(child)) for (const item of child) visit(item);
296
396
  else if (typeof child === "object") visit(child);
297
- };
397
+ }
298
398
  visit(program);
299
399
  return found;
300
400
  }
301
401
  /**
402
+ * Finds the `$props<T>()` calls whose pattern has a rest element, and the names that the other
403
+ * calls destructure. At runtime the rest leaves those names out, so the type of the call leaves
404
+ * them out too: a rest that is spread onto an element must not carry a prop of another call.
405
+ * Returns the names by the range of the type argument.
406
+ */
407
+ function restOmits(program) {
408
+ const names = /* @__PURE__ */ new Map();
409
+ const types = /* @__PURE__ */ new Map();
410
+ const rests = /* @__PURE__ */ new Set();
411
+ for (const statement of program?.body ?? []) {
412
+ if (statement.type !== "VariableDeclaration") continue;
413
+ for (const declarator of statement.declarations) {
414
+ const init = declarator.init;
415
+ if (init?.type !== "CallExpression" || init.callee.type !== "Identifier" || init.callee.name !== "$props" || declarator.id.type !== "ObjectPattern") continue;
416
+ const own = [];
417
+ for (const property of declarator.id.properties) if (property.type === "RestElement") rests.add(init);
418
+ else if (!property.computed && property.key.type === "Identifier") own.push(property.key.name);
419
+ else if (!property.computed && property.key.type === "Literal") own.push(String(property.key.value));
420
+ names.set(init, own);
421
+ const type = init.typeArguments?.params[0];
422
+ if (type) types.set(init, type);
423
+ }
424
+ }
425
+ const omits = /* @__PURE__ */ new Map();
426
+ for (const call of rests) {
427
+ const type = types.get(call);
428
+ const own = new Set(names.get(call));
429
+ const others = /* @__PURE__ */ new Set();
430
+ for (const [other, list] of names) if (other !== call) {
431
+ for (const name of list) if (!own.has(name)) others.add(name);
432
+ }
433
+ if (type && others.size > 0) omits.set(type, [...others]);
434
+ }
435
+ return omits;
436
+ }
437
+ /**
302
438
  * Returns the signals and memos whose values the page state sends to the
303
439
  * client, because client code reads them. Element refs are sent as
304
440
  * references, so they are left out.
305
441
  */
306
442
  function sentDeclarations(file) {
307
443
  try {
308
- const { slots } = clientState(buildGraph(analyze(file)));
309
- return [...slots.values()].flat().filter((declaration) => (declaration.kind === "signal" || declaration.kind === "memo" || declaration.kind === "async-memo") && declaration.refs.length === 0);
444
+ const { slots } = clientState(buildGraph(analyze(file)), file);
445
+ const sent = [];
446
+ for (const declaration of [...slots.values()].flat()) if ((declaration.kind === "signal" || declaration.kind === "memo" || declaration.kind === "async-memo") && declaration.refs.length === 0) sent.push(declaration);
447
+ return sent;
310
448
  } catch {
311
449
  return [];
312
450
  }
313
451
  }
452
+ /**
453
+ * Visits the nodes of the file and of the oxc trees in it. `visit` returns false to skip the
454
+ * children of a node.
455
+ */
456
+ function walk(node, visit) {
457
+ if (typeof node !== "object" || node === null) return;
458
+ if (Array.isArray(node)) {
459
+ for (const item of node) walk(item, visit);
460
+ return;
461
+ }
462
+ const value = node;
463
+ if (visit(value) === false) return;
464
+ for (const key in value) if (key !== "parent") walk(value[key], visit);
465
+ }
466
+ /** The names that a node reads or declares, as identifiers and component tags. */
467
+ function namesIn(node) {
468
+ const found = /* @__PURE__ */ new Set();
469
+ walk(node, (value) => {
470
+ if (value.type === "Identifier" && typeof value.name === "string") found.add(value.name);
471
+ else if (value.kind === "component" && typeof value.name === "string") found.add(value.name.split(".")[0]);
472
+ return true;
473
+ });
474
+ return found;
475
+ }
476
+ /** The names that the parameters of a template declare. */
477
+ function paramNames(template) {
478
+ const found = [];
479
+ for (const param of template.params) {
480
+ const pattern = param.type === "TSParameterProperty" ? param.parameter : param;
481
+ for (const name of getPatternNames(pattern.type === "RestElement" ? pattern.argument : pattern)) found.push(name.name);
482
+ }
483
+ return found;
484
+ }
485
+ /** Whether a parameter of a template has no type, so it can only get one from where it is passed. */
486
+ function untyped(template) {
487
+ for (const param of template.params) if (!(param.type === "AssignmentPattern" ? param.left : param).typeAnnotation) return true;
488
+ return false;
489
+ }
490
+ /** The name of a template that an attribute value passes as it is, such as `item=row`. */
491
+ function passedName(value) {
492
+ return passedIdentifier(value)?.name;
493
+ }
494
+ /** The identifier of `passedName`, with its range in the file. */
495
+ function passedIdentifier(value) {
496
+ let node = value.ast;
497
+ while (node.type === "ParenthesizedExpression") node = node.expression;
498
+ return node.type === "Identifier" ? node : void 0;
499
+ }
500
+ /**
501
+ * Finds the templates with an untyped parameter whose every use passes it to a prop of a component,
502
+ * such as `item=row`. They are written at each use, so the prop types the parameter. A template
503
+ * that the code reads in another way, or passes to an element, keeps its function declaration.
504
+ */
505
+ function inlineTemplates(file) {
506
+ const found = /* @__PURE__ */ new Set();
507
+ function scope(root, templates) {
508
+ for (const template of templates) {
509
+ if (template.params.length === 0 || !untyped(template)) continue;
510
+ let reads = 0;
511
+ let passed = 0;
512
+ walk(root, (value) => {
513
+ if (value !== root && Array.isArray(value.templates)) {
514
+ for (const other of value.templates) if (other !== template && other.name === template.name) return false;
515
+ }
516
+ if (value.kind === "template" && paramNames(value).includes(template.name)) return false;
517
+ if (value.type === "Identifier" && value.name === template.name) reads++;
518
+ else if (value.kind === "component" && value.name === template.name) reads++;
519
+ if (value.kind === "component" || value.kind === "dynamic") {
520
+ for (const attribute of value.attributes) if (attribute.kind === "value" && passedName(attribute.value) === template.name) passed++;
521
+ }
522
+ return true;
523
+ });
524
+ if (passed > 0 && reads === passed) found.add(template);
525
+ }
526
+ }
527
+ scope(file, file.templates);
528
+ walk(file.children, (value) => {
529
+ if (Array.isArray(value.templates) && Array.isArray(value.children)) scope(value, value.templates);
530
+ return true;
531
+ });
532
+ for (const template of file.templates) walk(template.body, (value) => {
533
+ if (Array.isArray(value.templates) && Array.isArray(value.children)) scope(value, value.templates);
534
+ return true;
535
+ });
536
+ return found;
537
+ }
538
+ /** Thrown when a template cannot be written at a use. It is then written as a declaration. */
539
+ var Hoist = class {
540
+ template;
541
+ constructor(template) {
542
+ this.template = template;
543
+ }
544
+ };
545
+ function namespaced(attribute) {
546
+ return (attribute.kind === "static" || attribute.kind === "value") && attribute.name.includes(":");
547
+ }
314
548
  var Generator = class {
315
549
  file;
316
550
  out;
317
551
  hoisted = [];
318
552
  sent;
553
+ omits;
554
+ /** The templates that are written at each use. See `inlineTemplates`. */
555
+ inline;
556
+ /** The names that each block of the generated code declares, outermost first. */
557
+ scopes = [];
558
+ /** The templates in scope, with the number of blocks at their declaration. */
559
+ visible = [];
560
+ /** The templates being written at a use, to find one that passes itself. */
561
+ writing = /* @__PURE__ */ new Set();
319
562
  constructor(file, out) {
320
563
  this.file = file;
321
564
  this.out = out;
322
565
  this.sent = sentDeclarations(file);
566
+ this.omits = restOmits(file.instanceScript?.program);
567
+ this.inline = inlineTemplates(file);
323
568
  }
324
569
  /** Copies a statement, and checks the values it declares that the client receives. */
325
570
  statement(statement) {
326
571
  const { out } = this;
327
- out.copy(statement);
572
+ let start = statement.start;
573
+ for (const [type, names] of this.omits) if (type.start >= statement.start && type.end <= statement.end) {
574
+ out.copy({
575
+ start,
576
+ end: type.start
577
+ });
578
+ out.text("$$Omit<");
579
+ out.copy(type);
580
+ const quoted = [];
581
+ for (const name of names) quoted.push(JSON.stringify(name));
582
+ out.text(`, ${quoted.join(" | ")}>`);
583
+ start = type.end;
584
+ }
585
+ out.copy({
586
+ start,
587
+ end: statement.end
588
+ });
328
589
  out.text("\n");
329
590
  for (const declaration of this.sent) if (declaration.range.start >= statement.start && declaration.range.end <= statement.end) {
330
- out.text("$$sendable(");
591
+ const refOnly = declaration.boundAs?.size === 1 && declaration.boundAs.has("ref");
592
+ out.text(refOnly ? "$$sendableRef(" : "$$sendable(");
331
593
  out.copy(declaration.range);
332
594
  out.text(");\n");
333
595
  }
334
596
  }
335
597
  generate() {
598
+ for (;;) try {
599
+ this.write();
600
+ return;
601
+ } catch (error) {
602
+ if (!(error instanceof Hoist)) throw error;
603
+ this.inline.delete(error.template);
604
+ this.out.reset();
605
+ this.scopes = [];
606
+ this.visible = [];
607
+ this.writing = /* @__PURE__ */ new Set();
608
+ }
609
+ }
610
+ write() {
336
611
  const { file, out } = this;
337
612
  out.text(HELPERS);
338
613
  for (const statement of file.moduleScript?.program.body ?? []) {
@@ -349,13 +624,17 @@ var Generator = class {
349
624
  out.copy(statement);
350
625
  out.text("\n");
351
626
  }
352
- const type = propsType(file.instanceScript?.program);
627
+ const types = propsTypes(file.instanceScript?.program);
353
628
  out.text(`\nexport default ${COMPONENT};\nasync function ${COMPONENT}`);
354
629
  if (file.generics) out.text(`<${file.generics}>`);
355
630
  out.text("($$props: ");
356
- if (type) out.copy(type);
631
+ if (types.length > 0) for (const [index, type] of types.entries()) {
632
+ out.text(index > 0 ? " & (" : "(");
633
+ out.copy(type);
634
+ out.text(")");
635
+ }
357
636
  else out.text("Record<string, any>");
358
- out.text(", $$ctx?: import('brumate/server').Context): Promise<string> {\n");
637
+ out.text(", $$ctx?: import('brumate/server').Context): Promise<$$Markup> {\n");
359
638
  out.text("$$use($$props, $$ctx);\n");
360
639
  for (const statement of body) if (!isTopLevel(statement)) this.statement(statement);
361
640
  for (const style of file.styles) for (const variable of style.variables) {
@@ -363,9 +642,11 @@ var Generator = class {
363
642
  out.expression(variable);
364
643
  out.text(");\n");
365
644
  }
645
+ this.enter(/* @__PURE__ */ new Set(), file.templates);
366
646
  this.templates(file.templates);
367
647
  this.nodes(file.children);
368
- out.text("return '';\n}\n");
648
+ this.leave();
649
+ out.text("return $$markup;\n}\n");
369
650
  out.text(`${COMPONENT}.brumateId = '';\n`);
370
651
  }
371
652
  collectBodyImports(nodes) {
@@ -379,25 +660,80 @@ var Generator = class {
379
660
  }
380
661
  for (const template of this.file.templates) if (nodes === this.file.children) this.collectBodyImports(template.body.children);
381
662
  }
663
+ /** Opens a block of the generated code that declares names and templates. */
664
+ enter(declared, templates = []) {
665
+ for (const template of templates) declared.add(template.name);
666
+ this.scopes.push(declared);
667
+ for (const template of templates) this.visible.push({
668
+ template,
669
+ depth: this.scopes.length
670
+ });
671
+ }
672
+ leave() {
673
+ const depth = this.scopes.length;
674
+ this.scopes.pop();
675
+ while (this.visible.at(-1) && this.visible.at(-1).depth >= depth) this.visible.pop();
676
+ }
382
677
  templates(templates) {
383
678
  const { out } = this;
384
679
  for (const template of templates) {
680
+ if (this.inline.has(template)) {
681
+ out.text("const ");
682
+ out.copy(template.nameRange);
683
+ out.text(" = $$template;\n");
684
+ continue;
685
+ }
385
686
  out.text("async function ");
386
687
  out.copy(template.nameRange);
387
- out.text("(");
388
- if (template.params.length > 0) out.copy({
389
- start: template.params[0].start,
390
- end: template.params.at(-1).end
391
- });
392
- out.text(") {\n");
393
- this.body(template.body);
394
- out.text("}\n");
688
+ this.template(template);
689
+ out.text("\n");
395
690
  }
396
691
  }
397
- body(body) {
692
+ /** Writes the parameters and the body of a template, after its name or `async`. */
693
+ template(template) {
694
+ const { out } = this;
695
+ out.text("(");
696
+ if (template.params.length > 0) out.copy({
697
+ start: template.params[0].start,
698
+ end: template.params.at(-1).end
699
+ });
700
+ out.text("): Promise<$$Markup> ");
701
+ out.text(this.inline.has(template) ? "=> {\n" : "{\n");
702
+ this.enter(new Set(paramNames(template)));
703
+ this.body(template.body);
704
+ this.leave();
705
+ out.text("return $$markup;\n}");
706
+ }
707
+ /**
708
+ * Finds the template that a prop value passes, if it is written at each use. An unannotated
709
+ * parameter of a function declaration has no type, and one of an arrow function in a prop takes
710
+ * the type of the prop, so the template is written there as `async (a) => { ... }`. The body is
711
+ * copied, with its mappings, at each use. Throws `Hoist` if a name declared between the
712
+ * template and the use would hide a name that the template reads, or if the template passes
713
+ * itself.
714
+ */
715
+ passed(value) {
716
+ const name = passedName(value);
717
+ if (name === void 0) return;
718
+ for (let index = this.visible.length - 1; index >= 0; index--) {
719
+ const { template, depth } = this.visible[index];
720
+ if (template.name !== name) continue;
721
+ if (!this.inline.has(template)) return;
722
+ if (this.writing.has(template)) throw new Hoist(template);
723
+ const read = namesIn([template.params, template.body]);
724
+ for (const param of paramNames(template)) read.delete(param);
725
+ for (const scope of this.scopes.slice(depth)) for (const declared of scope) if (declared === name || read.has(declared)) throw new Hoist(template);
726
+ return template;
727
+ }
728
+ }
729
+ body(body, declared = /* @__PURE__ */ new Set()) {
730
+ for (const statement of body.script?.program.body ?? []) if (statement.type === "VariableDeclaration") for (const declarator of statement.declarations) for (const name of getPatternNames(declarator.id)) declared.add(name.name);
731
+ else if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && statement.id) declared.add(statement.id.name);
732
+ this.enter(declared, body.templates);
398
733
  for (const statement of body.script?.program.body ?? []) if (statement.type !== "ImportDeclaration") this.statement(statement);
399
734
  this.templates(body.templates);
400
735
  this.nodes(body.children);
736
+ this.leave();
401
737
  }
402
738
  nodes(nodes) {
403
739
  for (const node of nodes) this.node(node);
@@ -412,7 +748,7 @@ var Generator = class {
412
748
  out.text(");\n");
413
749
  return;
414
750
  case "element":
415
- this.elementAttributes(node.tag, node.attributes);
751
+ this.element(node);
416
752
  this.nodes(node.children);
417
753
  return;
418
754
  case "component":
@@ -420,11 +756,7 @@ var Generator = class {
420
756
  this.nodes(node.children);
421
757
  return;
422
758
  case "dynamic":
423
- out.text("$$dynamic(");
424
- out.expression(node.tag);
425
- out.text(", {");
426
- this.props(node.attributes);
427
- out.text("});\n");
759
+ this.dynamic(node);
428
760
  this.nodes(node.children);
429
761
  return;
430
762
  case "fragment":
@@ -433,7 +765,9 @@ var Generator = class {
433
765
  case "listener": {
434
766
  const helper = node.target === "window" ? "$$onWindow" : "$$onDocument";
435
767
  for (const attribute of node.attributes) {
436
- out.text(`${helper}(${JSON.stringify(attribute.event)}, `);
768
+ out.text(`${helper}(`);
769
+ out.event(attribute);
770
+ out.text(", ");
437
771
  out.expression(attribute.handler);
438
772
  out.text(");\n");
439
773
  }
@@ -442,48 +776,223 @@ var Generator = class {
442
776
  default: this.block(node);
443
777
  }
444
778
  }
445
- elementAttributes(tag, attributes) {
779
+ /**
780
+ * Checks the attributes of a plain element as one object against the type of its tag, so an
781
+ * unknown attribute and a wrong value are errors at the attribute. Handlers are checked apart,
782
+ * by `$$on`, which also checks the name of the event.
783
+ */
784
+ element(node) {
446
785
  const { out } = this;
447
- for (const attribute of attributes) switch (attribute.kind) {
786
+ for (const attribute of node.attributes) if (attribute.kind === "event") {
787
+ out.text(`$$on(${JSON.stringify(node.tag)}, `);
788
+ out.event(attribute);
789
+ out.text(", ");
790
+ out.expression(attribute.handler);
791
+ out.text(");\n");
792
+ }
793
+ for (const attribute of node.attributes) if (attribute.kind === "spread") {
794
+ out.text(`$$spread(${JSON.stringify(node.tag)})(`);
795
+ out.copy(attribute.value);
796
+ out.text(");\n");
797
+ out.text(`$$element(${JSON.stringify(node.tag)})(`);
798
+ out.stand({
799
+ start: attribute.start,
800
+ end: attribute.start + 1
801
+ }, "{");
802
+ out.text("...$$present(");
803
+ out.copy(attribute.value);
804
+ out.text(") ");
805
+ out.stand({
806
+ start: attribute.end - 1,
807
+ end: attribute.end
808
+ }, "}");
809
+ out.text(");\n");
810
+ }
811
+ for (const attribute of node.attributes) if (namespaced(attribute) && attribute.kind === "value") {
812
+ out.text("$$use(");
813
+ out.expression(attribute.value);
814
+ out.text(");\n");
815
+ }
816
+ let checked = false;
817
+ for (const attribute of node.attributes) if (attribute.kind !== "event" && attribute.kind !== "spread" && !namespaced(attribute)) {
818
+ checked = true;
819
+ break;
820
+ }
821
+ if (!checked) return;
822
+ out.text(`$$element(${JSON.stringify(node.tag)})(`);
823
+ out.stand({
824
+ start: node.start,
825
+ end: node.start + 1
826
+ }, "{");
827
+ for (const attribute of node.attributes) switch (attribute.kind) {
828
+ case "static":
448
829
  case "value":
449
- case "spread":
450
- out.text("$$use(");
451
- out.expression(attribute.value);
452
- out.text(");\n");
830
+ if (namespaced(attribute)) break;
831
+ this.propName(attribute);
832
+ if (attribute.kind === "value") out.expression(attribute.value);
833
+ else out.text(attribute.value === true ? "true" : JSON.stringify(attribute.value));
834
+ out.text(",");
835
+ break;
836
+ case "ref":
837
+ out.text(" ");
838
+ out.stand({
839
+ start: attribute.start,
840
+ end: attribute.start + 3
841
+ }, "ref");
842
+ out.text(": $$bind(");
843
+ out.copy(attribute.targetRange);
844
+ out.text("),");
845
+ break;
846
+ case "computed": {
847
+ const close = this.file.source.indexOf("]", attribute.name.end);
848
+ out.text(" ");
849
+ out.stand({
850
+ start: attribute.start,
851
+ end: attribute.start + 1
852
+ }, "[");
853
+ out.copy(attribute.name);
854
+ out.stand({
855
+ start: close,
856
+ end: close + 1
857
+ }, "]");
858
+ out.text(": ");
859
+ if (attribute.value === true) out.text("true");
860
+ else out.expression(attribute.value);
861
+ out.text(",");
862
+ break;
863
+ }
864
+ }
865
+ out.text(" ");
866
+ const end = this.openTagEnd(node);
867
+ out.stand({
868
+ start: end - 1,
869
+ end
870
+ }, "}");
871
+ out.text(");\n");
872
+ }
873
+ /**
874
+ * Checks the attributes of a dynamic tag as one object against the type of its tag: the
875
+ * attributes of an element name, or the props of a component. The tag is read once into a
876
+ * constant, so an error in it is reported once. Handlers are typed by `$$handler`. The values
877
+ * of each spread are checked as an argument after the object, but not its names: a check of the
878
+ * names, as `$$spread` does on an element, cost TypeScript ten times the time of the whole check.
879
+ */
880
+ dynamic(node) {
881
+ const { out } = this;
882
+ this.passedNames(node.attributes);
883
+ out.text("{\nconst $$tag = ");
884
+ out.expression(node.tag);
885
+ out.text(";\n");
886
+ out.text("$$dynamic($$tag)(");
887
+ out.stand({
888
+ start: node.start,
889
+ end: node.start + 1
890
+ }, "{");
891
+ for (const attribute of node.attributes) switch (attribute.kind) {
892
+ case "static":
893
+ this.propName(attribute);
894
+ out.text(`${attribute.value === true ? "true" : JSON.stringify(attribute.value)},`);
895
+ break;
896
+ case "value":
897
+ this.propName(attribute);
898
+ this.propValue(attribute.value);
899
+ out.text(",");
453
900
  break;
454
901
  case "event":
455
- out.text(`$$on(${JSON.stringify(tag)}, ${JSON.stringify(attribute.event)}, `);
902
+ this.propName(attribute);
903
+ out.text("$$handler($$tag)(");
904
+ out.event(attribute);
905
+ out.text(", ");
456
906
  out.expression(attribute.handler);
457
- out.text(");\n");
907
+ out.text("),");
458
908
  break;
459
909
  case "ref":
460
- out.text("$$use(");
910
+ out.text(" ");
911
+ out.stand({
912
+ start: attribute.start,
913
+ end: attribute.start + 3
914
+ }, "ref");
915
+ out.text(": $$bind(");
461
916
  out.copy(attribute.targetRange);
462
- out.text(");\n");
917
+ out.text("),");
463
918
  break;
464
- case "computed":
465
- out.text("$$use(");
466
- out.expression(attribute.name);
467
- if (attribute.value !== true) {
468
- out.text(", ");
469
- out.expression(attribute.value);
470
- }
471
- out.text(");\n");
919
+ case "computed": {
920
+ const close = this.file.source.indexOf("]", attribute.name.end);
921
+ out.text(" ");
922
+ out.stand({
923
+ start: attribute.start,
924
+ end: attribute.start + 1
925
+ }, "[");
926
+ out.copy(attribute.name);
927
+ out.stand({
928
+ start: close,
929
+ end: close + 1
930
+ }, "]");
931
+ out.text(": ");
932
+ if (attribute.value === true) out.text("true");
933
+ else out.expression(attribute.value);
934
+ out.text(",");
935
+ break;
936
+ }
472
937
  }
938
+ if (node.children.length > 0) {
939
+ out.text(" ");
940
+ out.key({
941
+ start: node.children[0].start,
942
+ end: node.children.at(-1).end
943
+ }, "children");
944
+ out.text(": $$markup,");
945
+ }
946
+ out.text(" ");
947
+ const end = this.openTagEnd(node);
948
+ out.stand({
949
+ start: end - 1,
950
+ end
951
+ }, "}");
952
+ for (const attribute of node.attributes) if (attribute.kind === "spread") {
953
+ out.text(", ");
954
+ out.stand({
955
+ start: attribute.start,
956
+ end: attribute.start + 1
957
+ }, "{");
958
+ out.text("...$$present(");
959
+ out.copy(attribute.value);
960
+ out.text(") ");
961
+ out.stand({
962
+ start: attribute.end - 1,
963
+ end: attribute.end
964
+ }, "}");
965
+ }
966
+ out.text(");\n}\n");
473
967
  }
474
968
  /** Writes a prop name, mapped to the attribute, so errors about the prop point at it. */
475
969
  propName(attribute) {
476
970
  const { out } = this;
477
971
  out.text(" ");
478
- if (/^[A-Za-z_$][\w$]*$/.test(attribute.name)) out.copy({
479
- start: attribute.start,
480
- end: attribute.start + attribute.name.length
481
- });
482
- else out.text(JSON.stringify(attribute.name));
972
+ const start = this.file.source[attribute.start] === "{" ? this.file.source.indexOf(attribute.name, attribute.start) : attribute.start;
973
+ out.key({
974
+ start,
975
+ end: start + attribute.name.length
976
+ }, attribute.name);
483
977
  out.text(": ");
484
978
  }
485
- /** Writes the attributes of a component or a dynamic tag as the properties of an object. */
486
- props(attributes, children = false) {
979
+ /**
980
+ * Writes the value of a prop. A template passed by name is written in its place, so the type of
981
+ * the prop types its parameters.
982
+ */
983
+ propValue(value) {
984
+ const { out } = this;
985
+ const template = this.passed(value);
986
+ if (template) {
987
+ this.writing.add(template);
988
+ out.text("(async ");
989
+ this.template(template);
990
+ out.text(")");
991
+ this.writing.delete(template);
992
+ } else out.expression(value);
993
+ }
994
+ /** Writes the attributes of a component as the properties of an object. */
995
+ props(attributes, children) {
487
996
  const { out } = this;
488
997
  for (const attribute of attributes) switch (attribute.kind) {
489
998
  case "static":
@@ -492,7 +1001,7 @@ var Generator = class {
492
1001
  break;
493
1002
  case "value":
494
1003
  this.propName(attribute);
495
- out.expression(attribute.value);
1004
+ this.propValue(attribute.value);
496
1005
  out.text(",");
497
1006
  break;
498
1007
  case "event":
@@ -505,22 +1014,43 @@ var Generator = class {
505
1014
  out.expression(attribute.value);
506
1015
  out.text(",");
507
1016
  }
508
- if (children) out.text(" children: undefined as any,");
1017
+ if (children) {
1018
+ out.text(" ");
1019
+ out.key(children, "children");
1020
+ out.text(": $$markup,");
1021
+ }
1022
+ }
1023
+ /**
1024
+ * Reads the name of each template that a prop passes and that is written at the use, mapped to
1025
+ * the name at the use, so the use reaches the template in an editor. It is a statement of its own
1026
+ * before the call: in the prop, next to the arrow function, it would change how the call infers
1027
+ * its type parameters.
1028
+ */
1029
+ passedNames(attributes) {
1030
+ for (const attribute of attributes) if (attribute.kind === "value" && this.passed(attribute.value)) {
1031
+ const name = passedIdentifier(attribute.value);
1032
+ this.out.text("$$use(");
1033
+ this.out.copy(name);
1034
+ this.out.text(");\n");
1035
+ }
509
1036
  }
510
1037
  component(node) {
511
1038
  const { out } = this;
1039
+ this.passedNames(node.attributes);
512
1040
  const nameStart = node.start + 1;
513
- out.text("$$component(");
514
1041
  out.copy({
515
1042
  start: nameStart,
516
1043
  end: nameStart + node.name.length
517
1044
  });
518
- out.text(", ");
1045
+ out.text("(");
519
1046
  out.stand({
520
1047
  start: node.start,
521
1048
  end: node.start + 1
522
1049
  }, "{");
523
- this.props(node.attributes, node.children.length > 0);
1050
+ this.props(node.attributes, node.children.length > 0 ? {
1051
+ start: node.children[0].start,
1052
+ end: node.children.at(-1).end
1053
+ } : void 0);
524
1054
  out.text(" ");
525
1055
  out.stand({
526
1056
  start: this.openTagEnd(node) - 1,
@@ -528,23 +1058,27 @@ var Generator = class {
528
1058
  }, "}");
529
1059
  out.text(");\n");
530
1060
  }
531
- /** The offset after the `>` that ends the opening tag of a component. */
1061
+ /** The offset after the `>` that ends the opening tag of an element or a component. */
532
1062
  openTagEnd(node) {
533
- const last = node.attributes.at(-1)?.end ?? node.start + 1 + node.name.length;
1063
+ let tagEnd;
1064
+ if (node.kind === "dynamic") tagEnd = this.file.source.indexOf("}", node.tag.end) + 1;
1065
+ else tagEnd = node.start + 1 + (node.kind === "component" ? node.name : node.tag).length;
1066
+ const last = node.attributes.at(-1)?.end ?? tagEnd;
534
1067
  return this.file.source.indexOf(">", last) + 1;
535
1068
  }
536
1069
  block(block) {
537
1070
  const { out } = this;
538
1071
  switch (block.kind) {
539
1072
  case "if":
540
- case "switch":
541
- (block.kind === "if" ? block.branches : block.cases).forEach((branch, index) => {
1073
+ case "switch": {
1074
+ const branches = block.kind === "if" ? block.branches : block.cases;
1075
+ for (const [index, branch] of branches.entries()) {
542
1076
  out.text(index === 0 ? "if " : " else if ");
543
1077
  out.expression(branch.condition);
544
1078
  out.text(" {\n");
545
1079
  this.body(branch.body);
546
1080
  out.text("}");
547
- });
1081
+ }
548
1082
  if (block.fallback) {
549
1083
  out.text(" else {\n");
550
1084
  this.body(block.fallback);
@@ -552,6 +1086,7 @@ var Generator = class {
552
1086
  }
553
1087
  out.text("\n");
554
1088
  return;
1089
+ }
555
1090
  case "for":
556
1091
  out.text("for (const ");
557
1092
  out.copy(block.item);
@@ -568,7 +1103,7 @@ var Generator = class {
568
1103
  out.expression(block.key);
569
1104
  out.text(");\n");
570
1105
  }
571
- this.body(block.body);
1106
+ this.body(block.body, namesIn([block.item, block.index]));
572
1107
  out.text("}\n");
573
1108
  this.fallback(block.fallback);
574
1109
  return;
@@ -581,7 +1116,7 @@ var Generator = class {
581
1116
  out.copy(block.index);
582
1117
  out.text(" = $$i;\n");
583
1118
  }
584
- this.body(block.body);
1119
+ this.body(block.body, namesIn(block.index));
585
1120
  out.text("}\n");
586
1121
  this.fallback(block.fallback);
587
1122
  return;
@@ -611,7 +1146,7 @@ var Generator = class {
611
1146
  out.copy(block.reset);
612
1147
  out.text(" = (): void => {};\n");
613
1148
  }
614
- this.body(block.fallback);
1149
+ this.body(block.fallback, namesIn([block.error, block.reset]));
615
1150
  out.text("}\n");
616
1151
  return;
617
1152
  case "loading":
@@ -696,7 +1231,7 @@ function toTypeScript(source, filename = "Component.brm") {
696
1231
  out.copy(range);
697
1232
  out.text("\n");
698
1233
  }
699
- out.text(`export default async function ${COMPONENT}(..._: any[]): Promise<string> {\n return '';\n}\n`);
1234
+ out.text(`export default async function ${COMPONENT}(..._: any[]): Promise<$$Markup> {\n return $$markup;\n}\n`);
700
1235
  return {
701
1236
  code: out.code,
702
1237
  mappings: out.mappings,
@@ -710,6 +1245,6 @@ function toTypeScript(source, filename = "Component.brm") {
710
1245
  };
711
1246
  }
712
1247
  //#endregion
713
- export { BrumateError, CompileError, SHARED_QUERY, analyze, analyzeProject, analyzeProjectProps, buildGraph, compile, createPlan, formatReport, generateClient, generateRender, generateServer, generateShared, getComponentName, getLocation, inspect, isWithin, lookup, parse, printAST, printGraph, printModel, report, resolveRelative, sharedSites, summarize, toTypeScript };
1248
+ export { BrumateError, CompileError, SHARED_QUERY, analyze, analyzeProject, analyzeProjectProps, buildGraph, compile, createPlan, errorLink, findError, formatReport, generateClient, generateRender, generateServer, generateShared, getComponentName, getLocation, inspect, isWithin, lookup, parse, printAST, printGraph, printModel, report, resolveRelative, sharedSites, summarize, toTypeScript };
714
1249
 
715
1250
  //# sourceMappingURL=index.js.map