@lipsjs/lips 0.1.0 → 0.2.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 +119 -85
  2. package/dist/lips.js +3836 -0
  3. package/dist/lips.js.map +28 -0
  4. package/dist/lips.min.js +9 -2
  5. package/dist/lips.min.js.map +22 -43
  6. package/dist/precompile.min.js +20 -0
  7. package/dist/precompile.min.js.map +13 -0
  8. package/dist/runtime.min.js +4 -0
  9. package/dist/runtime.min.js.map +19 -0
  10. package/dist/types/events.d.ts +1 -1
  11. package/dist/types/ir/compiler.d.ts +153 -0
  12. package/dist/types/ir/expression.d.ts +120 -0
  13. package/dist/types/ir/facade.d.ts +94 -0
  14. package/dist/types/ir/index.d.ts +15 -0
  15. package/dist/types/ir/parser.d.ts +124 -0
  16. package/dist/types/ir/router.d.ts +47 -0
  17. package/dist/types/ir/runtime.d.ts +95 -0
  18. package/dist/types/ir/signal.d.ts +26 -0
  19. package/dist/types/ir/swap.d.ts +23 -0
  20. package/dist/types/lips.d.ts +16 -35
  21. package/dist/types/precompile.d.ts +60 -0
  22. package/dist/types/runtime.d.ts +16 -0
  23. package/dist/types/stylesheet.d.ts +24 -40
  24. package/dist/types/types.d.ts +49 -185
  25. package/package.json +29 -10
  26. package/dist/test.component.min.js +0 -283
  27. package/dist/test.component.min.js.map +0 -50
  28. package/dist/test.stress.min.js +0 -476
  29. package/dist/test.stress.min.js.map +0 -50
  30. package/dist/types/component.d.ts +0 -107
  31. package/dist/types/dws.d.ts +0 -14
  32. package/dist/types/iuc/index.d.ts +0 -25
  33. package/dist/types/iuc/tick.d.ts +0 -38
  34. package/dist/types/iuc.d.ts +0 -25
  35. package/dist/types/metrics.d.ts +0 -50
  36. package/dist/types/preprocess.d.ts +0 -2
  37. package/dist/types/signal.d.ts +0 -30
  38. package/dist/types/syntax/async.d.ts +0 -16
  39. package/dist/types/syntax/for.d.ts +0 -25
  40. package/dist/types/syntax/if.d.ts +0 -14
  41. package/dist/types/syntax/router.d.ts +0 -40
  42. package/dist/types/syntax/switch.d.ts +0 -16
  43. package/dist/types/tick.d.ts +0 -38
  44. package/dist/types/uqs.d.ts +0 -37
  45. package/dist/types/utils.d.ts +0 -45
package/dist/lips.js ADDED
@@ -0,0 +1,3836 @@
1
+ // node_modules/stylis/src/Enum.js
2
+ var COMMENT = "comm";
3
+ var RULESET = "rule";
4
+ var DECLARATION = "decl";
5
+ var IMPORT = "@import";
6
+ var NAMESPACE = "@namespace";
7
+ var KEYFRAMES = "@keyframes";
8
+ var LAYER = "@layer";
9
+
10
+ // node_modules/stylis/src/Utility.js
11
+ var abs = Math.abs;
12
+ var from = String.fromCharCode;
13
+ function trim(value) {
14
+ return value.trim();
15
+ }
16
+ function replace(value, pattern, replacement) {
17
+ return value.replace(pattern, replacement);
18
+ }
19
+ function indexof(value, search, position) {
20
+ return value.indexOf(search, position);
21
+ }
22
+ function charat(value, index) {
23
+ return value.charCodeAt(index) | 0;
24
+ }
25
+ function substr(value, begin, end) {
26
+ return value.slice(begin, end);
27
+ }
28
+ function strlen(value) {
29
+ return value.length;
30
+ }
31
+ function sizeof(value) {
32
+ return value.length;
33
+ }
34
+ function append(value, array) {
35
+ return array.push(value), value;
36
+ }
37
+
38
+ // node_modules/stylis/src/Tokenizer.js
39
+ var line = 1;
40
+ var column = 1;
41
+ var length = 0;
42
+ var position = 0;
43
+ var character = 0;
44
+ var characters = "";
45
+ function node(value, root, parent, type, props, children, length2, siblings) {
46
+ return { value, root, parent, type, props, children, line, column, length: length2, return: "", siblings };
47
+ }
48
+ function char() {
49
+ return character;
50
+ }
51
+ function prev() {
52
+ character = position > 0 ? charat(characters, --position) : 0;
53
+ if (column--, character === 10)
54
+ column = 1, line--;
55
+ return character;
56
+ }
57
+ function next() {
58
+ character = position < length ? charat(characters, position++) : 0;
59
+ if (column++, character === 10)
60
+ column = 1, line++;
61
+ return character;
62
+ }
63
+ function peek() {
64
+ return charat(characters, position);
65
+ }
66
+ function caret() {
67
+ return position;
68
+ }
69
+ function slice(begin, end) {
70
+ return substr(characters, begin, end);
71
+ }
72
+ function token(type) {
73
+ switch (type) {
74
+ case 0:
75
+ case 9:
76
+ case 10:
77
+ case 13:
78
+ case 32:
79
+ return 5;
80
+ case 33:
81
+ case 43:
82
+ case 44:
83
+ case 47:
84
+ case 62:
85
+ case 64:
86
+ case 126:
87
+ case 59:
88
+ case 123:
89
+ case 125:
90
+ return 4;
91
+ case 58:
92
+ return 3;
93
+ case 34:
94
+ case 39:
95
+ case 40:
96
+ case 91:
97
+ return 2;
98
+ case 41:
99
+ case 93:
100
+ return 1;
101
+ }
102
+ return 0;
103
+ }
104
+ function alloc(value) {
105
+ return line = column = 1, length = strlen(characters = value), position = 0, [];
106
+ }
107
+ function dealloc(value) {
108
+ return characters = "", value;
109
+ }
110
+ function delimit(type) {
111
+ return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)));
112
+ }
113
+ function whitespace(type) {
114
+ while (character = peek())
115
+ if (character < 33)
116
+ next();
117
+ else
118
+ break;
119
+ return token(type) > 2 || token(character) > 3 ? "" : " ";
120
+ }
121
+ function escaping(index, count) {
122
+ while (--count && next())
123
+ if (character < 48 || character > 102 || character > 57 && character < 65 || character > 70 && character < 97)
124
+ break;
125
+ return slice(index, caret() + (count < 6 && peek() == 32 && next() == 32));
126
+ }
127
+ function delimiter(type) {
128
+ while (next())
129
+ switch (character) {
130
+ case type:
131
+ return position;
132
+ case 34:
133
+ case 39:
134
+ if (type !== 34 && type !== 39)
135
+ delimiter(character);
136
+ break;
137
+ case 40:
138
+ if (type === 41)
139
+ delimiter(type);
140
+ break;
141
+ case 92:
142
+ next();
143
+ break;
144
+ }
145
+ return position;
146
+ }
147
+ function commenter(type, index) {
148
+ while (next())
149
+ if (type + character === 47 + 10)
150
+ break;
151
+ else if (type + character === 42 + 42 && peek() === 47)
152
+ break;
153
+ return "/*" + slice(index, position - 1) + "*" + from(type === 47 ? type : next());
154
+ }
155
+ function identifier(index) {
156
+ while (!token(peek()))
157
+ next();
158
+ return slice(index, position);
159
+ }
160
+
161
+ // node_modules/stylis/src/Parser.js
162
+ function compile(value) {
163
+ return dealloc(parse("", null, null, null, [""], value = alloc(value), 0, [0], value));
164
+ }
165
+ function parse(value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {
166
+ var index = 0;
167
+ var offset = 0;
168
+ var length2 = pseudo;
169
+ var atrule = 0;
170
+ var property = 0;
171
+ var previous = 0;
172
+ var variable = 1;
173
+ var scanning = 1;
174
+ var ampersand = 1;
175
+ var character2 = 0;
176
+ var type = "";
177
+ var props = rules;
178
+ var children = rulesets;
179
+ var reference = rule;
180
+ var characters2 = type;
181
+ while (scanning)
182
+ switch (previous = character2, character2 = next()) {
183
+ case 40:
184
+ if (previous != 108 && charat(characters2, length2 - 1) == 58) {
185
+ if (indexof(characters2 += replace(delimit(character2), "&", "&\f"), "&\f", abs(index ? points[index - 1] : 0)) != -1)
186
+ ampersand = -1;
187
+ break;
188
+ }
189
+ case 34:
190
+ case 39:
191
+ case 91:
192
+ characters2 += delimit(character2);
193
+ break;
194
+ case 9:
195
+ case 10:
196
+ case 13:
197
+ case 32:
198
+ characters2 += whitespace(previous);
199
+ break;
200
+ case 92:
201
+ characters2 += escaping(caret() - 1, 7);
202
+ continue;
203
+ case 47:
204
+ switch (peek()) {
205
+ case 42:
206
+ case 47:
207
+ append(comment(commenter(next(), caret()), root, parent, declarations), declarations);
208
+ if ((token(previous || 1) == 5 || token(peek() || 1) == 5) && strlen(characters2) && substr(characters2, -1, undefined) !== " ")
209
+ characters2 += " ";
210
+ break;
211
+ default:
212
+ characters2 += "/";
213
+ }
214
+ break;
215
+ case 123 * variable:
216
+ points[index++] = strlen(characters2) * ampersand;
217
+ case 125 * variable:
218
+ case 59:
219
+ case 0:
220
+ switch (character2) {
221
+ case 0:
222
+ case 125:
223
+ scanning = 0;
224
+ case 59 + offset:
225
+ if (ampersand == -1)
226
+ characters2 = replace(characters2, /\f/g, "");
227
+ if (property > 0 && (strlen(characters2) - length2 || variable === 0 && previous === 47))
228
+ append(property > 32 ? declaration(characters2 + ";", rule, parent, length2 - 1, declarations) : declaration(replace(characters2, " ", "") + ";", rule, parent, length2 - 2, declarations), declarations);
229
+ break;
230
+ case 59:
231
+ characters2 += ";";
232
+ default:
233
+ append(reference = ruleset(characters2, root, parent, index, offset, rules, points, type, props = [], children = [], length2, rulesets), rulesets);
234
+ if (character2 === 123)
235
+ if (offset === 0)
236
+ parse(characters2, root, reference, reference, props, rulesets, length2, points, children);
237
+ else {
238
+ switch (atrule) {
239
+ case 99:
240
+ if (charat(characters2, 3) === 110)
241
+ break;
242
+ case 108:
243
+ if (charat(characters2, 2) === 97)
244
+ break;
245
+ default:
246
+ offset = 0;
247
+ case 100:
248
+ case 109:
249
+ case 115:
250
+ }
251
+ if (offset)
252
+ parse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length2, children), children), rules, children, length2, points, rule ? props : children);
253
+ else
254
+ parse(characters2, reference, reference, reference, [""], children, 0, points, children);
255
+ }
256
+ }
257
+ index = offset = property = 0, variable = ampersand = 1, type = characters2 = "", length2 = pseudo;
258
+ break;
259
+ case 58:
260
+ length2 = 1 + strlen(characters2), property = previous;
261
+ default:
262
+ if (variable < 1) {
263
+ if (character2 == 123)
264
+ --variable;
265
+ else if (character2 == 125 && variable++ == 0 && prev() == 125)
266
+ continue;
267
+ }
268
+ switch (characters2 += from(character2), character2 * variable) {
269
+ case 38:
270
+ ampersand = offset > 0 ? 1 : (characters2 += "\f", -1);
271
+ break;
272
+ case 44:
273
+ points[index++] = (strlen(characters2) - 1) * ampersand, ampersand = 1;
274
+ break;
275
+ case 64:
276
+ if (peek() === 45)
277
+ characters2 += delimit(next());
278
+ atrule = peek(), offset = length2 = strlen(type = characters2 += identifier(caret())), character2++;
279
+ break;
280
+ case 45:
281
+ if (previous === 45 && strlen(characters2) == 2)
282
+ variable = 0;
283
+ }
284
+ }
285
+ return rulesets;
286
+ }
287
+ function ruleset(value, root, parent, index, offset, rules, points, type, props, children, length2, siblings) {
288
+ var post = offset - 1;
289
+ var rule = offset === 0 ? rules : [""];
290
+ var size = sizeof(rule);
291
+ for (var i = 0, j = 0, k = 0;i < index; ++i)
292
+ for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value;x < size; ++x)
293
+ if (z = trim(j > 0 ? rule[x] + " " + y : replace(y, /&\f/g, rule[x])))
294
+ props[k++] = z;
295
+ return node(value, root, parent, offset === 0 ? RULESET : type, props, children, length2, siblings);
296
+ }
297
+ function comment(value, root, parent, siblings) {
298
+ return node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0, siblings);
299
+ }
300
+ function declaration(value, root, parent, length2, siblings) {
301
+ return node(value, root, parent, DECLARATION, substr(value, 0, length2), substr(value, length2 + 1, -1), length2, siblings);
302
+ }
303
+
304
+ // node_modules/stylis/src/Serializer.js
305
+ function serialize(children, callback) {
306
+ var output = "";
307
+ for (var i = 0;i < children.length; i++)
308
+ output += callback(children[i], i, children, callback) || "";
309
+ return output;
310
+ }
311
+ function stringify(element, index, children, callback) {
312
+ switch (element.type) {
313
+ case LAYER:
314
+ if (element.children.length)
315
+ break;
316
+ case IMPORT:
317
+ case NAMESPACE:
318
+ case DECLARATION:
319
+ return element.return = element.return || element.value;
320
+ case COMMENT:
321
+ return "";
322
+ case KEYFRAMES:
323
+ return element.return = element.value + "{" + serialize(element.children, callback) + "}";
324
+ case RULESET:
325
+ if (!strlen(element.value = element.props.join(",")))
326
+ return "";
327
+ }
328
+ return strlen(children = serialize(element.children, callback)) ? element.return = element.value + "{" + children + "}" : "";
329
+ }
330
+
331
+ // node_modules/stylis/src/Middleware.js
332
+ function middleware(collection) {
333
+ var length2 = sizeof(collection);
334
+ return function(element, index, children, callback) {
335
+ var output = "";
336
+ for (var i = 0;i < length2; i++)
337
+ output += collection[i](element, index, children, callback) || "";
338
+ return output;
339
+ };
340
+ }
341
+
342
+ // src/ir/expression.ts
343
+ var PUNCTS = [
344
+ "===",
345
+ "!==",
346
+ "...",
347
+ "=>",
348
+ "==",
349
+ "!=",
350
+ "<=",
351
+ ">=",
352
+ "&&",
353
+ "||",
354
+ "??",
355
+ "?.",
356
+ "++",
357
+ "--",
358
+ "+=",
359
+ "-=",
360
+ "*=",
361
+ "/=",
362
+ "%=",
363
+ "+",
364
+ "-",
365
+ "*",
366
+ "/",
367
+ "%",
368
+ "<",
369
+ ">",
370
+ "!",
371
+ "?",
372
+ ":",
373
+ ".",
374
+ ",",
375
+ "(",
376
+ ")",
377
+ "[",
378
+ "]",
379
+ "{",
380
+ "}",
381
+ "="
382
+ ];
383
+ function tokenize(src, diagnostics) {
384
+ const tokens = [];
385
+ let i = 0;
386
+ const isIdStart = (c) => /[A-Za-z_$]/.test(c);
387
+ const isIdChar = (c) => /[A-Za-z0-9_$]/.test(c);
388
+ while (i < src.length) {
389
+ const c = src[i];
390
+ if (/\s/.test(c)) {
391
+ i++;
392
+ continue;
393
+ }
394
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(src[i + 1])) {
395
+ const start = i;
396
+ while (i < src.length && /[0-9]/.test(src[i]))
397
+ i++;
398
+ if (src[i] === ".") {
399
+ i++;
400
+ while (i < src.length && /[0-9]/.test(src[i]))
401
+ i++;
402
+ }
403
+ if (src[i] === "e" || src[i] === "E") {
404
+ i++;
405
+ if (src[i] === "+" || src[i] === "-")
406
+ i++;
407
+ while (i < src.length && /[0-9]/.test(src[i]))
408
+ i++;
409
+ }
410
+ tokens.push({ t: "num", value: src.slice(start, i), start, end: i });
411
+ continue;
412
+ }
413
+ if (c === "'" || c === '"') {
414
+ const start = i;
415
+ i++;
416
+ let value = "";
417
+ let closed = false;
418
+ while (i < src.length) {
419
+ const ch = src[i];
420
+ if (ch === "\\") {
421
+ const next2 = src[i + 1];
422
+ const escapes = { n: `
423
+ `, t: "\t", r: "\r", b: "\b", f: "\f", v: "\v", "0": "\x00" };
424
+ if (next2 === "u") {
425
+ const hex = src.slice(i + 2, i + 6);
426
+ value += String.fromCharCode(parseInt(hex, 16) || 0);
427
+ i += 6;
428
+ } else {
429
+ value += escapes[next2] ?? next2;
430
+ i += 2;
431
+ }
432
+ continue;
433
+ }
434
+ if (ch === c) {
435
+ closed = true;
436
+ i++;
437
+ break;
438
+ }
439
+ value += ch;
440
+ i++;
441
+ }
442
+ if (!closed)
443
+ diagnostics.push({ code: "LIPS-E001", message: "Unterminated string literal", loc: { offset: start, length: i - start } });
444
+ tokens.push({ t: "str", value, start, end: i });
445
+ continue;
446
+ }
447
+ if (isIdStart(c)) {
448
+ const start = i;
449
+ while (i < src.length && isIdChar(src[i]))
450
+ i++;
451
+ tokens.push({ t: "id", value: src.slice(start, i), start, end: i });
452
+ continue;
453
+ }
454
+ let punct = PUNCTS.find((p) => src.startsWith(p, i));
455
+ if (punct === "?." && /[0-9]/.test(src[i + 2] ?? ""))
456
+ punct = "?";
457
+ if (punct) {
458
+ tokens.push({ t: "punct", value: punct, start: i, end: i + punct.length });
459
+ i += punct.length;
460
+ continue;
461
+ }
462
+ diagnostics.push({ code: "LIPS-E002", message: `Unexpected character '${c}'`, loc: { offset: i, length: 1 } });
463
+ i++;
464
+ }
465
+ tokens.push({ t: "eof", value: "", start: src.length, end: src.length });
466
+ return tokens;
467
+ }
468
+
469
+ class Parser {
470
+ tokens;
471
+ diagnostics;
472
+ pos = 0;
473
+ constructor(tokens, diagnostics) {
474
+ this.tokens = tokens;
475
+ this.diagnostics = diagnostics;
476
+ }
477
+ peek(offset = 0) {
478
+ return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
479
+ }
480
+ next() {
481
+ return this.tokens[this.pos++] ?? this.tokens[this.tokens.length - 1];
482
+ }
483
+ at(value) {
484
+ const t = this.peek();
485
+ return t.t === "punct" && t.value === value;
486
+ }
487
+ eat(value) {
488
+ if (this.at(value)) {
489
+ this.pos++;
490
+ return true;
491
+ }
492
+ return false;
493
+ }
494
+ error(code, message, token2 = this.peek()) {
495
+ this.diagnostics.push({ code, message, loc: { offset: token2.start, length: Math.max(1, token2.end - token2.start) } });
496
+ return { t: "error" };
497
+ }
498
+ expect(value, code) {
499
+ if (!this.eat(value))
500
+ this.error(code, `Expected '${value}'`);
501
+ }
502
+ parse() {
503
+ const expr = this.assign();
504
+ if (this.peek().t !== "eof")
505
+ this.error("LIPS-E003", `Unexpected token '${this.peek().value}' after expression`);
506
+ return expr;
507
+ }
508
+ isArrowAhead() {
509
+ const t = this.peek();
510
+ if (t.t === "id") {
511
+ const n = this.peek(1);
512
+ return n.t === "punct" && n.value === "=>";
513
+ }
514
+ if (t.t === "punct" && t.value === "(") {
515
+ let depth = 0, k = 0;
516
+ while (true) {
517
+ const tok = this.peek(k);
518
+ if (tok.t === "eof")
519
+ return false;
520
+ if (tok.t === "punct" && tok.value === "(")
521
+ depth++;
522
+ if (tok.t === "punct" && tok.value === ")") {
523
+ depth--;
524
+ if (depth === 0) {
525
+ const after = this.peek(k + 1);
526
+ return after.t === "punct" && after.value === "=>";
527
+ }
528
+ }
529
+ k++;
530
+ }
531
+ }
532
+ return false;
533
+ }
534
+ assign() {
535
+ if (this.isArrowAhead()) {
536
+ const params = [];
537
+ if (this.peek().t === "id")
538
+ params.push(this.next().value);
539
+ else {
540
+ this.expect("(", "LIPS-E004");
541
+ while (!this.at(")") && this.peek().t !== "eof") {
542
+ const p = this.next();
543
+ if (p.t !== "id")
544
+ return this.error("LIPS-E005", "Invalid arrow parameter", p);
545
+ params.push(p.value);
546
+ if (!this.eat(","))
547
+ break;
548
+ }
549
+ this.expect(")", "LIPS-E004");
550
+ }
551
+ this.expect("=>", "LIPS-E004");
552
+ return { t: "arrow", params, body: this.assign() };
553
+ }
554
+ const target = this.conditional();
555
+ const op = this.peek();
556
+ if (op.t === "punct" && ["=", "+=", "-=", "*=", "/=", "%="].includes(op.value)) {
557
+ if (target.t !== "id" && target.t !== "member")
558
+ return this.error("LIPS-E006", "Invalid assignment target", op);
559
+ this.next();
560
+ return { t: "assign", op: op.value, target, value: this.assign() };
561
+ }
562
+ return target;
563
+ }
564
+ conditional() {
565
+ const test = this.nullish();
566
+ if (this.eat("?")) {
567
+ const cons = this.assign();
568
+ this.expect(":", "LIPS-E007");
569
+ return { t: "cond", test, cons, alt: this.assign() };
570
+ }
571
+ return test;
572
+ }
573
+ nullish() {
574
+ let l = this.or();
575
+ while (this.at("??")) {
576
+ this.next();
577
+ l = { t: "logic", op: "??", l, r: this.or() };
578
+ }
579
+ return l;
580
+ }
581
+ or() {
582
+ let l = this.and();
583
+ while (this.at("||")) {
584
+ this.next();
585
+ l = { t: "logic", op: "||", l, r: this.and() };
586
+ }
587
+ return l;
588
+ }
589
+ and() {
590
+ let l = this.equality();
591
+ while (this.at("&&")) {
592
+ this.next();
593
+ l = { t: "logic", op: "&&", l, r: this.equality() };
594
+ }
595
+ return l;
596
+ }
597
+ equality() {
598
+ let l = this.relational();
599
+ while (["===", "!==", "==", "!="].some((op) => this.at(op))) {
600
+ const op = this.next().value;
601
+ l = { t: "bin", op, l, r: this.relational() };
602
+ }
603
+ return l;
604
+ }
605
+ relational() {
606
+ let l = this.additive();
607
+ while (["<=", ">=", "<", ">"].some((op) => this.at(op))) {
608
+ const op = this.next().value;
609
+ l = { t: "bin", op, l, r: this.additive() };
610
+ }
611
+ return l;
612
+ }
613
+ additive() {
614
+ let l = this.multiplicative();
615
+ while (this.at("+") || this.at("-")) {
616
+ const op = this.next().value;
617
+ l = { t: "bin", op, l, r: this.multiplicative() };
618
+ }
619
+ return l;
620
+ }
621
+ multiplicative() {
622
+ let l = this.unary();
623
+ while (this.at("*") || this.at("/") || this.at("%")) {
624
+ const op = this.next().value;
625
+ l = { t: "bin", op, l, r: this.unary() };
626
+ }
627
+ return l;
628
+ }
629
+ unary() {
630
+ if (this.at("!") || this.at("-") || this.at("+")) {
631
+ const op = this.next().value;
632
+ return { t: "unary", op, arg: this.unary() };
633
+ }
634
+ if (this.at("++") || this.at("--")) {
635
+ const op = this.next().value;
636
+ const arg = this.unary();
637
+ if (arg.t !== "id" && arg.t !== "member")
638
+ return this.error("LIPS-E006", "Invalid update target");
639
+ return { t: "update", op, arg, prefix: true };
640
+ }
641
+ return this.postfix();
642
+ }
643
+ postfix() {
644
+ let expr = this.callMember();
645
+ if (this.at("++") || this.at("--")) {
646
+ const op = this.next().value;
647
+ if (expr.t !== "id" && expr.t !== "member")
648
+ return this.error("LIPS-E006", "Invalid update target");
649
+ expr = { t: "update", op, arg: expr, prefix: false };
650
+ }
651
+ return expr;
652
+ }
653
+ callMember() {
654
+ let expr = this.primary();
655
+ while (true) {
656
+ if (this.eat(".")) {
657
+ const prop = this.next();
658
+ if (prop.t !== "id")
659
+ return this.error("LIPS-E008", "Expected property name", prop);
660
+ expr = { t: "member", obj: expr, prop: prop.value, computed: false, optional: false };
661
+ } else if (this.eat("?.")) {
662
+ if (this.at("(")) {
663
+ expr = { t: "call", callee: expr, args: this.argList(), optional: true };
664
+ } else if (this.eat("[")) {
665
+ const idx = this.assign();
666
+ this.expect("]", "LIPS-E009");
667
+ expr = { t: "member", obj: expr, prop: idx, computed: true, optional: true };
668
+ } else {
669
+ const prop = this.next();
670
+ if (prop.t !== "id")
671
+ return this.error("LIPS-E008", "Expected property name", prop);
672
+ expr = { t: "member", obj: expr, prop: prop.value, computed: false, optional: true };
673
+ }
674
+ } else if (this.eat("[")) {
675
+ const idx = this.assign();
676
+ this.expect("]", "LIPS-E009");
677
+ expr = { t: "member", obj: expr, prop: idx, computed: true, optional: false };
678
+ } else if (this.at("(")) {
679
+ expr = { t: "call", callee: expr, args: this.argList(), optional: false };
680
+ } else
681
+ break;
682
+ }
683
+ return expr;
684
+ }
685
+ argList() {
686
+ this.expect("(", "LIPS-E010");
687
+ const args = [];
688
+ while (!this.at(")") && this.peek().t !== "eof") {
689
+ args.push(this.assign());
690
+ if (!this.eat(","))
691
+ break;
692
+ }
693
+ this.expect(")", "LIPS-E010");
694
+ return args;
695
+ }
696
+ primary() {
697
+ const t = this.peek();
698
+ if (t.t === "num") {
699
+ this.next();
700
+ return { t: "lit", v: parseFloat(t.value) };
701
+ }
702
+ if (t.t === "str") {
703
+ this.next();
704
+ return { t: "lit", v: t.value };
705
+ }
706
+ if (t.t === "id") {
707
+ this.next();
708
+ switch (t.value) {
709
+ case "true":
710
+ return { t: "lit", v: true };
711
+ case "false":
712
+ return { t: "lit", v: false };
713
+ case "null":
714
+ return { t: "lit", v: null };
715
+ case "undefined":
716
+ return { t: "lit", v: undefined };
717
+ case "NaN":
718
+ return { t: "lit", v: NaN };
719
+ case "Infinity":
720
+ return { t: "lit", v: Infinity };
721
+ default:
722
+ return { t: "id", name: t.value };
723
+ }
724
+ }
725
+ if (this.eat("(")) {
726
+ const expr = this.assign();
727
+ this.expect(")", "LIPS-E010");
728
+ return expr;
729
+ }
730
+ if (this.eat("[")) {
731
+ const items = [];
732
+ while (!this.at("]") && this.peek().t !== "eof") {
733
+ const spread = this.eat("...");
734
+ items.push({ spread: spread || undefined, value: this.assign() });
735
+ if (!this.eat(","))
736
+ break;
737
+ }
738
+ this.expect("]", "LIPS-E009");
739
+ return { t: "arr", items };
740
+ }
741
+ if (this.eat("{")) {
742
+ const props = [];
743
+ while (!this.at("}") && this.peek().t !== "eof") {
744
+ if (this.eat("...")) {
745
+ props.push({ spread: true, value: this.assign() });
746
+ } else {
747
+ const key = this.next();
748
+ if (key.t !== "id" && key.t !== "str" && key.t !== "num")
749
+ return this.error("LIPS-E011", "Invalid object key", key);
750
+ if (this.eat(":"))
751
+ props.push({ key: String(key.value), value: this.assign() });
752
+ else if (key.t === "id")
753
+ props.push({ key: key.value, value: { t: "id", name: key.value } });
754
+ else
755
+ return this.error("LIPS-E011", "Invalid shorthand property", key);
756
+ }
757
+ if (!this.eat(","))
758
+ break;
759
+ }
760
+ this.expect("}", "LIPS-E011");
761
+ return { t: "obj", props };
762
+ }
763
+ this.next();
764
+ return this.error("LIPS-E012", t.t === "eof" ? "Unexpected end of expression" : `Unexpected token '${t.value}'`, t);
765
+ }
766
+ }
767
+ function parseExpression(src) {
768
+ const diagnostics = [];
769
+ const tokens = tokenize(src, diagnostics);
770
+ const ast = new Parser(tokens, diagnostics).parse();
771
+ return { ast, diagnostics };
772
+ }
773
+ var METAVAR_ROOTS = new Set(["state", "input", "context", "self", "arguments"]);
774
+ var ID_RENAMES = { static: "__static", arguments: "__args__" };
775
+ function gen(node2) {
776
+ switch (node2.t) {
777
+ case "lit":
778
+ if (typeof node2.v === "string")
779
+ return JSON.stringify(node2.v);
780
+ if (node2.v === undefined)
781
+ return "undefined";
782
+ if (Number.isNaN(node2.v))
783
+ return "NaN";
784
+ return String(node2.v);
785
+ case "id":
786
+ return ID_RENAMES[node2.name] ?? node2.name;
787
+ case "member": {
788
+ const obj = gen(node2.obj);
789
+ if (node2.computed)
790
+ return `(${obj})${node2.optional ? "?." : ""}[${gen(node2.prop)}]`;
791
+ return `(${obj})${node2.optional ? "?." : "."}${node2.prop}`;
792
+ }
793
+ case "call":
794
+ return `(${gen(node2.callee)})${node2.optional ? "?." : ""}(${node2.args.map(gen).join(",")})`;
795
+ case "unary":
796
+ return `(${node2.op}(${gen(node2.arg)}))`;
797
+ case "update":
798
+ return node2.prefix ? `(${node2.op}${genTarget(node2.arg)})` : `(${genTarget(node2.arg)}${node2.op})`;
799
+ case "bin":
800
+ return `((${gen(node2.l)})${node2.op}(${gen(node2.r)}))`;
801
+ case "logic":
802
+ return `((${gen(node2.l)})${node2.op}(${gen(node2.r)}))`;
803
+ case "cond":
804
+ return `((${gen(node2.test)})?(${gen(node2.cons)}):(${gen(node2.alt)}))`;
805
+ case "assign":
806
+ return `(${genTarget(node2.target)}${node2.op}(${gen(node2.value)}))`;
807
+ case "arrow":
808
+ return `((${node2.params.join(",")})=>(${gen(node2.body)}))`;
809
+ case "arr":
810
+ return `[${node2.items.map((i) => (i.spread ? "..." : "") + gen(i.value)).join(",")}]`;
811
+ case "obj":
812
+ return `({${node2.props.map((p) => p.spread ? `...${gen(p.value)}` : `${JSON.stringify(p.key)}:${gen(p.value)}`).join(",")}})`;
813
+ case "error":
814
+ return "undefined";
815
+ }
816
+ }
817
+ function genTarget(node2) {
818
+ if (node2.t === "id")
819
+ return ID_RENAMES[node2.name] ?? node2.name;
820
+ if (node2.t === "member") {
821
+ const obj = gen(node2.obj);
822
+ return node2.computed ? `${obj}[${gen(node2.prop)}]` : `${obj}.${node2.prop}`;
823
+ }
824
+ return gen(node2);
825
+ }
826
+ var COMPILE_CACHE = new Map;
827
+ var ROOT_PARAMS = ["state", "input", "context", "__static", "self"];
828
+ function compileExpression(src, scopeNames = []) {
829
+ const key = `${scopeNames.join(",")}\x00${src}`;
830
+ const cached = COMPILE_CACHE.get(key);
831
+ if (cached)
832
+ return cached;
833
+ const { ast, diagnostics } = parseExpression(src);
834
+ if (diagnostics.length)
835
+ console.warn(`[lips-ir] expression diagnostics for "${src}":`, diagnostics);
836
+ const code = `return (${gen(ast)});`, params = [...ROOT_PARAMS, "__args__", ...scopeNames], fn = new Function(...params, code);
837
+ const compiled = {
838
+ source: src,
839
+ run(env) {
840
+ const scope = env.scope || {};
841
+ return fn(env.state, env.input, env.context, env.static, env.self, env.arguments, ...scopeNames.map((name) => scope[name]));
842
+ }
843
+ };
844
+ COMPILE_CACHE.set(key, compiled);
845
+ return compiled;
846
+ }
847
+ var SAFE_GLOBALS = {
848
+ Math,
849
+ JSON,
850
+ Object,
851
+ Array,
852
+ String,
853
+ Number,
854
+ Boolean,
855
+ Date,
856
+ parseInt,
857
+ parseFloat,
858
+ isNaN,
859
+ isFinite,
860
+ encodeURIComponent,
861
+ decodeURIComponent,
862
+ console
863
+ };
864
+ function interpretExpression(ast, env) {
865
+ const scope = env.scope || {};
866
+ const resolveId = (name, locals) => {
867
+ for (const frame of locals)
868
+ if (name in frame)
869
+ return frame[name];
870
+ if (name in scope)
871
+ return scope[name];
872
+ switch (name) {
873
+ case "state":
874
+ return env.state;
875
+ case "input":
876
+ return env.input;
877
+ case "context":
878
+ return env.context;
879
+ case "static":
880
+ return env.static;
881
+ case "self":
882
+ return env.self;
883
+ case "arguments":
884
+ return env.arguments;
885
+ }
886
+ if (name in SAFE_GLOBALS)
887
+ return SAFE_GLOBALS[name];
888
+ return;
889
+ };
890
+ const assignId = (name, value, locals) => {
891
+ for (const frame of locals)
892
+ if (name in frame) {
893
+ frame[name] = value;
894
+ return value;
895
+ }
896
+ scope[name] = value;
897
+ return value;
898
+ };
899
+ const ev = (node2, locals) => {
900
+ switch (node2.t) {
901
+ case "lit":
902
+ return node2.v;
903
+ case "id":
904
+ return resolveId(node2.name, locals);
905
+ case "member": {
906
+ const obj = ev(node2.obj, locals);
907
+ if (node2.optional && obj == null)
908
+ return;
909
+ const prop = node2.computed ? ev(node2.prop, locals) : node2.prop;
910
+ return obj?.[prop];
911
+ }
912
+ case "call": {
913
+ if (node2.callee.t === "member") {
914
+ const obj = ev(node2.callee.obj, locals);
915
+ if ((node2.callee.optional || node2.optional) && obj == null)
916
+ return;
917
+ const prop = node2.callee.computed ? ev(node2.callee.prop, locals) : node2.callee.prop;
918
+ const fn2 = obj?.[prop];
919
+ if (node2.optional && fn2 == null)
920
+ return;
921
+ return fn2.apply(obj, node2.args.map((a) => ev(a, locals)));
922
+ }
923
+ const fn = ev(node2.callee, locals);
924
+ if (node2.optional && fn == null)
925
+ return;
926
+ return fn(...node2.args.map((a) => ev(a, locals)));
927
+ }
928
+ case "unary": {
929
+ const v = ev(node2.arg, locals);
930
+ switch (node2.op) {
931
+ case "!":
932
+ return !v;
933
+ case "-":
934
+ return -v;
935
+ case "+":
936
+ return +v;
937
+ }
938
+ }
939
+ case "update": {
940
+ const cur = ev(node2.arg, locals);
941
+ const nextVal = node2.op === "++" ? cur + 1 : cur - 1;
942
+ setTarget(node2.arg, nextVal, locals);
943
+ return node2.prefix ? nextVal : cur;
944
+ }
945
+ case "bin": {
946
+ const l = ev(node2.l, locals), r = ev(node2.r, locals);
947
+ switch (node2.op) {
948
+ case "+":
949
+ return l + r;
950
+ case "-":
951
+ return l - r;
952
+ case "*":
953
+ return l * r;
954
+ case "/":
955
+ return l / r;
956
+ case "%":
957
+ return l % r;
958
+ case "<":
959
+ return l < r;
960
+ case ">":
961
+ return l > r;
962
+ case "<=":
963
+ return l <= r;
964
+ case ">=":
965
+ return l >= r;
966
+ case "==":
967
+ return l == r;
968
+ case "!=":
969
+ return l != r;
970
+ case "===":
971
+ return l === r;
972
+ case "!==":
973
+ return l !== r;
974
+ }
975
+ return;
976
+ }
977
+ case "logic": {
978
+ const l = ev(node2.l, locals);
979
+ switch (node2.op) {
980
+ case "&&":
981
+ return l ? ev(node2.r, locals) : l;
982
+ case "||":
983
+ return l ? l : ev(node2.r, locals);
984
+ case "??":
985
+ return l != null ? l : ev(node2.r, locals);
986
+ }
987
+ }
988
+ case "cond":
989
+ return ev(node2.test, locals) ? ev(node2.cons, locals) : ev(node2.alt, locals);
990
+ case "assign": {
991
+ let value = ev(node2.value, locals);
992
+ if (node2.op !== "=") {
993
+ const cur = ev(node2.target, locals);
994
+ switch (node2.op) {
995
+ case "+=":
996
+ value = cur + value;
997
+ break;
998
+ case "-=":
999
+ value = cur - value;
1000
+ break;
1001
+ case "*=":
1002
+ value = cur * value;
1003
+ break;
1004
+ case "/=":
1005
+ value = cur / value;
1006
+ break;
1007
+ case "%=":
1008
+ value = cur % value;
1009
+ break;
1010
+ }
1011
+ }
1012
+ return setTarget(node2.target, value, locals);
1013
+ }
1014
+ case "arrow":
1015
+ return (...args) => {
1016
+ const frame = {};
1017
+ node2.params.forEach((p, k) => frame[p] = args[k]);
1018
+ return ev(node2.body, [frame, ...locals]);
1019
+ };
1020
+ case "arr": {
1021
+ const out = [];
1022
+ for (const item of node2.items) {
1023
+ const v = ev(item.value, locals);
1024
+ item.spread ? out.push(...v) : out.push(v);
1025
+ }
1026
+ return out;
1027
+ }
1028
+ case "obj": {
1029
+ const out = {};
1030
+ for (const p of node2.props) {
1031
+ if (p.spread)
1032
+ Object.assign(out, ev(p.value, locals));
1033
+ else
1034
+ out[p.key] = ev(p.value, locals);
1035
+ }
1036
+ return out;
1037
+ }
1038
+ case "error":
1039
+ return;
1040
+ }
1041
+ };
1042
+ const setTarget = (target, value, locals) => {
1043
+ if (target.t === "id")
1044
+ return assignId(target.name, value, locals);
1045
+ if (target.t === "member") {
1046
+ const obj = ev(target.obj, locals);
1047
+ const prop = target.computed ? ev(target.prop, locals) : target.prop;
1048
+ if (obj != null)
1049
+ obj[prop] = value;
1050
+ return value;
1051
+ }
1052
+ return value;
1053
+ };
1054
+ return ev(ast, []);
1055
+ }
1056
+
1057
+ // src/ir/signal.ts
1058
+ var CURRENT = null;
1059
+ function signal(value) {
1060
+ const subs = new Set;
1061
+ const notify = () => {
1062
+ for (const e of [...subs])
1063
+ !e.disposed && e.run();
1064
+ };
1065
+ const read = () => {
1066
+ if (CURRENT && !CURRENT.disposed) {
1067
+ subs.add(CURRENT);
1068
+ CURRENT.deps.add(subs);
1069
+ }
1070
+ return value;
1071
+ };
1072
+ const write = (next2) => {
1073
+ if (Object.is(next2, value))
1074
+ return;
1075
+ value = next2;
1076
+ notify();
1077
+ };
1078
+ const touch = () => notify();
1079
+ return [read, write, touch];
1080
+ }
1081
+ function effect(fn) {
1082
+ const e = {
1083
+ deps: new Set,
1084
+ disposed: false,
1085
+ run() {
1086
+ if (e.disposed)
1087
+ return;
1088
+ for (const subs of e.deps)
1089
+ subs.delete(e);
1090
+ e.deps.clear();
1091
+ const prev2 = CURRENT;
1092
+ CURRENT = e;
1093
+ try {
1094
+ fn();
1095
+ } finally {
1096
+ CURRENT = prev2;
1097
+ }
1098
+ }
1099
+ };
1100
+ e.run();
1101
+ return {
1102
+ dispose() {
1103
+ e.disposed = true;
1104
+ for (const subs of e.deps)
1105
+ subs.delete(e);
1106
+ e.deps.clear();
1107
+ }
1108
+ };
1109
+ }
1110
+ function untrack(fn) {
1111
+ const prev2 = CURRENT;
1112
+ CURRENT = null;
1113
+ try {
1114
+ return fn();
1115
+ } finally {
1116
+ CURRENT = prev2;
1117
+ }
1118
+ }
1119
+ var IS_REACTIVE = Symbol("lips.reactive");
1120
+ function reactive(obj, deep = false) {
1121
+ if (obj[IS_REACTIVE])
1122
+ return obj;
1123
+ const sigs = new Map;
1124
+ const wrapped = deep ? new WeakMap : null;
1125
+ const sigFor = (key, initial) => {
1126
+ let s = sigs.get(key);
1127
+ if (!s) {
1128
+ s = signal(initial);
1129
+ sigs.set(key, s);
1130
+ }
1131
+ return s;
1132
+ };
1133
+ const isPlain = (v) => v !== null && typeof v === "object" && (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype);
1134
+ const ARRAY_MUTATORS = new Set(["push", "pop", "shift", "unshift", "splice", "sort", "reverse", "fill", "copyWithin"]);
1135
+ const deepWrap = (value, touch) => {
1136
+ if (!deep || !isPlain(value))
1137
+ return value;
1138
+ const hit = wrapped.get(value);
1139
+ if (hit)
1140
+ return hit;
1141
+ let muted = false;
1142
+ const proxy = new Proxy(value, {
1143
+ get(t, k) {
1144
+ const v = t[k];
1145
+ if (Array.isArray(t) && typeof k === "string" && ARRAY_MUTATORS.has(k) && typeof v === "function")
1146
+ return (...args) => {
1147
+ muted = true;
1148
+ try {
1149
+ return v.apply(t, args);
1150
+ } finally {
1151
+ muted = false;
1152
+ touch();
1153
+ }
1154
+ };
1155
+ return isPlain(v) ? deepWrap(v, touch) : v;
1156
+ },
1157
+ set(t, k, v) {
1158
+ t[k] = v;
1159
+ !muted && touch();
1160
+ return true;
1161
+ },
1162
+ deleteProperty(t, k) {
1163
+ delete t[k];
1164
+ !muted && touch();
1165
+ return true;
1166
+ }
1167
+ });
1168
+ wrapped.set(value, proxy);
1169
+ return proxy;
1170
+ };
1171
+ return new Proxy(obj, {
1172
+ get(target, key) {
1173
+ if (key === IS_REACTIVE)
1174
+ return true;
1175
+ if (typeof key === "string") {
1176
+ const s = sigFor(key, target[key]);
1177
+ return deepWrap(s[0](), s[2]);
1178
+ }
1179
+ return target[key];
1180
+ },
1181
+ set(target, key, value) {
1182
+ target[key] = value;
1183
+ typeof key === "string" && sigFor(key, value)[1](value);
1184
+ return true;
1185
+ },
1186
+ has(target, key) {
1187
+ return key in target;
1188
+ },
1189
+ deleteProperty(target, key) {
1190
+ delete target[key];
1191
+ typeof key === "string" && sigs.get(key)?.[1](undefined);
1192
+ return true;
1193
+ }
1194
+ });
1195
+ }
1196
+
1197
+ // src/ir/swap.ts
1198
+ var normInput = (ci, x) => ci == null ? ci : ("e" in ci) ? { $: x[ci.e] } : ci;
1199
+ var normBind = (b, x) => ({ ...b, e: x[b.e] });
1200
+ function normChild(c, x) {
1201
+ switch (c.t) {
1202
+ case "macro":
1203
+ return {
1204
+ t: c.t,
1205
+ name: c.name,
1206
+ args: c.args,
1207
+ vars: Object.fromEntries(Object.entries(c.vars).map(([k, v]) => [k, normInput(v, x)])),
1208
+ block: normBlock(c.block, x)
1209
+ };
1210
+ case "if":
1211
+ return { t: c.t, branches: c.branches.map((b) => ({
1212
+ when: b.when == null ? null : x[b.when],
1213
+ block: normBlock(b.block, x)
1214
+ })) };
1215
+ case "for":
1216
+ return {
1217
+ t: c.t,
1218
+ args: c.args,
1219
+ of: c.of === undefined ? undefined : x[c.of],
1220
+ from: normInput(c.from, x),
1221
+ to: normInput(c.to, x),
1222
+ by: normInput(c.by, x),
1223
+ block: normBlock(c.block, x)
1224
+ };
1225
+ case "switch":
1226
+ return { t: c.t, on: x[c.on], cases: c.cases.map((k) => ({
1227
+ is: k.is === null ? null : normInput(k.is, x),
1228
+ block: normBlock(k.block, x)
1229
+ })) };
1230
+ case "async":
1231
+ return {
1232
+ t: c.t,
1233
+ awaitE: x[c.awaitE],
1234
+ then: c.then && { args: c.then.args, block: normBlock(c.then.block, x) },
1235
+ catch: c.catch && { args: c.catch.args, block: normBlock(c.catch.block, x) },
1236
+ loading: c.loading && normBlock(c.loading, x)
1237
+ };
1238
+ case "let":
1239
+ return {
1240
+ t: c.t,
1241
+ const: c.const,
1242
+ vars: Object.fromEntries(Object.entries(c.vars).map(([k, v]) => [k, normInput(v, x)]))
1243
+ };
1244
+ case "log":
1245
+ return { t: c.t, e: x[c.e] };
1246
+ case "comp":
1247
+ case "dynamic":
1248
+ return {
1249
+ t: c.t,
1250
+ name: c.t === "comp" ? c.name : undefined,
1251
+ tag: c.t === "dynamic" ? x[c.tag] : undefined,
1252
+ inputs: Object.fromEntries(Object.entries(c.inputs).map(([k, v]) => [k, normInput(v, x)])),
1253
+ spreads: c.spreads.map((e) => x[e]),
1254
+ events: c.events.map((ev) => ({ name: ev.name, e: x[ev.e] })),
1255
+ contents: c.contents && { args: c.contents.args, block: normBlock(c.contents.block, x) }
1256
+ };
1257
+ }
1258
+ }
1259
+ var normBlock = (b, x) => ({
1260
+ html: b.html,
1261
+ scope: b.scope,
1262
+ binds: b.binds.map((bind) => normBind(bind, x)),
1263
+ blocks: b.blocks.map((c) => normChild(c, x))
1264
+ });
1265
+ var sameChild = (a, ax, b, bx) => a.t === b.t && JSON.stringify(normChild(a, ax)) === JSON.stringify(normChild(b, bx));
1266
+ var sameBinds = (a, ax, b, bx) => JSON.stringify(a.map((x) => normBind(x, ax))) === JSON.stringify(b.map((x) => normBind(x, bx)));
1267
+ var sameLets = (a, ax, b, bx) => {
1268
+ const lets = (blk, x) => JSON.stringify(blk.blocks.filter((c) => c.t === "let").map((c) => normChild(c, x)));
1269
+ return lets(a, ax) === lets(b, bx);
1270
+ };
1271
+
1272
+ // src/ir/runtime.ts
1273
+ var SLOT = Symbol("lips.slot");
1274
+ var isSlot = (v) => !!v && typeof v === "object" && v[SLOT] === true;
1275
+ function makeHooks(self) {
1276
+ let scheduled = false;
1277
+ let isReady = false;
1278
+ const onError = (error) => typeof self.onError === "function" ? self.onError(error) : console.error("[lips:ir]", error);
1279
+ return {
1280
+ onError,
1281
+ ready() {
1282
+ isReady = true;
1283
+ },
1284
+ notifyUpdate() {
1285
+ if (!isReady || scheduled)
1286
+ return;
1287
+ scheduled = true;
1288
+ queueMicrotask(() => {
1289
+ scheduled = false;
1290
+ try {
1291
+ typeof self.onUpdate === "function" && self.onUpdate();
1292
+ typeof self.onRender === "function" && self.onRender();
1293
+ } catch (error) {
1294
+ onError(error);
1295
+ }
1296
+ });
1297
+ }
1298
+ };
1299
+ }
1300
+ var PENDING_ATTACH = [];
1301
+ function flushAttach() {
1302
+ for (let i = PENDING_ATTACH.length - 1;i >= 0; i--) {
1303
+ const entry = PENDING_ATTACH[i];
1304
+ const node2 = entry.node();
1305
+ if (node2 && node2.isConnected) {
1306
+ PENDING_ATTACH.splice(i, 1);
1307
+ entry.fn();
1308
+ }
1309
+ }
1310
+ }
1311
+ var AST_CACHE = new Map;
1312
+ function astOf(src) {
1313
+ let ast = AST_CACHE.get(src);
1314
+ if (!ast) {
1315
+ ast = parseExpression(src).ast;
1316
+ AST_CACHE.set(src, ast);
1317
+ }
1318
+ return ast;
1319
+ }
1320
+ var SKELETONS = new WeakMap;
1321
+ function skeleton(block) {
1322
+ let tpl = SKELETONS.get(block);
1323
+ if (!tpl) {
1324
+ tpl = document.createElement("template");
1325
+ tpl.innerHTML = block.html;
1326
+ SKELETONS.set(block, tpl);
1327
+ }
1328
+ return tpl;
1329
+ }
1330
+ var pathKey = (p) => p.join(",");
1331
+ function resolvePath(root, p) {
1332
+ let node2 = root;
1333
+ for (const i of p)
1334
+ node2 = node2.childNodes[i];
1335
+ return node2;
1336
+ }
1337
+ function nodesOf(inst) {
1338
+ const out = [];
1339
+ let n = inst.start;
1340
+ while (n) {
1341
+ out.push(n);
1342
+ if (n === inst.end)
1343
+ break;
1344
+ n = n.nextSibling;
1345
+ }
1346
+ return out;
1347
+ }
1348
+ function insertAfter(ref, nodes) {
1349
+ const parent = ref.parentNode;
1350
+ if (!parent)
1351
+ return;
1352
+ let anchor = ref;
1353
+ for (const n of nodes) {
1354
+ parent.insertBefore(n, anchor.nextSibling);
1355
+ anchor = n;
1356
+ }
1357
+ }
1358
+ function applyScopedStyles(options, inst, nsp, css) {
1359
+ for (const n of nodesOf(inst))
1360
+ if (n.nodeType === 1 && !n.hasAttribute("rel"))
1361
+ n.setAttribute("rel", nsp);
1362
+ const sheet = options.createStylesheet?.(nsp, css);
1363
+ return sheet ? () => sheet.clear() : undefined;
1364
+ }
1365
+ function disposeInstance(inst) {
1366
+ for (const h of inst.bindHandles)
1367
+ h.dispose();
1368
+ for (const h of inst.childHandles)
1369
+ h.dispose();
1370
+ }
1371
+ function destroy(inst) {
1372
+ if (!inst)
1373
+ return;
1374
+ disposeInstance(inst);
1375
+ for (const n of nodesOf(inst))
1376
+ n.remove();
1377
+ }
1378
+ function splitTopLevel(src) {
1379
+ const out = [];
1380
+ let depth = 0, start = 0;
1381
+ for (let i = 0;i < src.length; i++) {
1382
+ const c = src[i];
1383
+ if (c === "'" || c === '"' || c === "`") {
1384
+ i++;
1385
+ while (i < src.length && src[i] !== c) {
1386
+ if (src[i] === "\\")
1387
+ i++;
1388
+ i++;
1389
+ }
1390
+ continue;
1391
+ }
1392
+ if (c === "(" || c === "[" || c === "{")
1393
+ depth++;
1394
+ else if (c === ")" || c === "]" || c === "}")
1395
+ depth--;
1396
+ else if (c === "," && depth === 0) {
1397
+ out.push(src.slice(start, i));
1398
+ start = i + 1;
1399
+ }
1400
+ }
1401
+ out.push(src.slice(start));
1402
+ return out.map((s) => s.trim()).filter(Boolean);
1403
+ }
1404
+ var applyAttr = (el, name, v) => {
1405
+ v === false || v == null ? el.removeAttribute(name) : el.setAttribute(name, v === true ? "" : String(v));
1406
+ };
1407
+ var defineGetter = (scope, name, get) => Object.defineProperty(scope, name, { get, enumerable: true, configurable: true });
1408
+
1409
+ class IRRenderer {
1410
+ ir;
1411
+ options;
1412
+ hooks;
1413
+ constructor(ir, options, hooks) {
1414
+ this.ir = ir;
1415
+ this.options = options;
1416
+ this.hooks = hooks;
1417
+ }
1418
+ guarded(fn) {
1419
+ let first = true;
1420
+ return effect(() => {
1421
+ try {
1422
+ fn();
1423
+ } catch (error) {
1424
+ this.hooks ? this.hooks.onError(error) : console.error("[lips:ir]", error);
1425
+ }
1426
+ first ? first = false : this.hooks?.notifyUpdate();
1427
+ });
1428
+ }
1429
+ runner(e, scopeNames) {
1430
+ return this.srcRunner(this.ir.exprs[e], scopeNames);
1431
+ }
1432
+ srcRunner(src, scopeNames) {
1433
+ if (this.options.mode === "interpreted") {
1434
+ const ast = astOf(src);
1435
+ return (env) => interpretExpression(ast, env);
1436
+ }
1437
+ const compiled = compileExpression(src, scopeNames);
1438
+ return (env) => compiled.run(env);
1439
+ }
1440
+ renderBlock(block, env) {
1441
+ const frag = skeleton(block).content.cloneNode(true);
1442
+ const pathNodes = new Map;
1443
+ const bindNodes = block.binds.map((b) => {
1444
+ const node2 = resolvePath(frag, b.p);
1445
+ pathNodes.set(pathKey(b.p), node2);
1446
+ return node2;
1447
+ });
1448
+ const anchorNodes = block.blocks.map((b) => {
1449
+ const node2 = resolvePath(frag, b.p);
1450
+ pathNodes.set(pathKey(b.p), node2);
1451
+ return node2;
1452
+ });
1453
+ const start = document.createComment("^");
1454
+ const end = document.createComment("$");
1455
+ frag.insertBefore(start, frag.firstChild);
1456
+ frag.appendChild(end);
1457
+ const scope = Object.create(env.scope ?? null);
1458
+ const benv = { ...env, scope };
1459
+ const inst = {
1460
+ start,
1461
+ end,
1462
+ block,
1463
+ exprs: this.ir.exprs,
1464
+ penv: env,
1465
+ benv,
1466
+ pathNodes,
1467
+ bindHandles: [],
1468
+ childHandles: []
1469
+ };
1470
+ block.blocks.forEach((child, i) => {
1471
+ if (child.t !== "let")
1472
+ return;
1473
+ const letDisposers = [];
1474
+ for (const [name, input] of Object.entries(child.vars)) {
1475
+ if ("lit" in input) {
1476
+ const [get] = signal(input.lit);
1477
+ defineGetter(scope, name, get);
1478
+ } else {
1479
+ const [get, set] = signal(undefined);
1480
+ defineGetter(scope, name, get);
1481
+ const run = this.runner(input.e, block.scope);
1482
+ letDisposers.push(effect(() => set(run(benv))).dispose);
1483
+ }
1484
+ }
1485
+ inst.childHandles[i] = {
1486
+ child,
1487
+ exprs: this.ir.exprs,
1488
+ anchor: anchorNodes[i],
1489
+ dispose: () => letDisposers.forEach((d) => d())
1490
+ };
1491
+ });
1492
+ inst.bindHandles = block.binds.map((bind, i) => this.bindOne(bind, bindNodes[i], benv, block.scope));
1493
+ block.blocks.forEach((child, i) => {
1494
+ if (child.t === "let")
1495
+ return;
1496
+ inst.childHandles[i] = {
1497
+ child,
1498
+ exprs: this.ir.exprs,
1499
+ anchor: anchorNodes[i],
1500
+ dispose: this.execBlock(child, anchorNodes[i], benv, block.scope)
1501
+ };
1502
+ });
1503
+ return inst;
1504
+ }
1505
+ bindOne(bind, node2, benv, scopeNames, reuseText) {
1506
+ switch (bind.t) {
1507
+ case "text": {
1508
+ const textNode = reuseText ?? document.createTextNode("");
1509
+ !reuseText && insertAfter(node2, [textNode]);
1510
+ const run = this.runner(bind.e, scopeNames);
1511
+ const i18n = bind.i18n ? this.options.i18n : undefined;
1512
+ const h = this.guarded(() => {
1513
+ const v = run(benv);
1514
+ const text = v == null ? "" : String(v);
1515
+ textNode.data = i18n ? i18n.translate(text) : text;
1516
+ });
1517
+ return { bind, node: node2, textNode, dispose: h.dispose };
1518
+ }
1519
+ case "attr": {
1520
+ const run = this.runner(bind.e, scopeNames);
1521
+ const i18n = bind.i18n ? this.options.i18n : undefined;
1522
+ const h = this.guarded(() => {
1523
+ const v = run(benv);
1524
+ applyAttr(node2, bind.name, i18n && v != null ? i18n.translate(String(v)) : v);
1525
+ });
1526
+ return { bind, node: node2, dispose: h.dispose };
1527
+ }
1528
+ case "prop": {
1529
+ const run = this.runner(bind.e, scopeNames);
1530
+ if (bind.name === "format") {
1531
+ const ref = bind.ref || "";
1532
+ const h2 = this.guarded(() => {
1533
+ const params = run(benv);
1534
+ const text = this.options.i18n?.format(ref, params);
1535
+ node2.textContent = text == null ? "" : String(text);
1536
+ });
1537
+ return { bind, node: node2, dispose: h2.dispose };
1538
+ }
1539
+ const h = this.guarded(() => {
1540
+ const v = run(benv);
1541
+ bind.name === "html" ? node2.innerHTML = v == null ? "" : String(v) : node2.textContent = v == null ? "" : String(v);
1542
+ });
1543
+ return { bind, node: node2, dispose: h.dispose };
1544
+ }
1545
+ case "event": {
1546
+ const handler = this.eventDispatcher(this.ir.exprs[bind.e], scopeNames, benv);
1547
+ node2.addEventListener(bind.name, handler);
1548
+ return { bind, node: node2, dispose: () => node2.removeEventListener(bind.name, handler) };
1549
+ }
1550
+ case "spread": {
1551
+ const run = this.runner(bind.e, scopeNames);
1552
+ let prev2 = new Set;
1553
+ const h = this.guarded(() => {
1554
+ const obj = run(benv) || {};
1555
+ const next2 = new Set(Object.keys(obj));
1556
+ for (const k of prev2)
1557
+ !next2.has(k) && node2.removeAttribute(k);
1558
+ for (const k of next2)
1559
+ applyAttr(node2, k, obj[k]);
1560
+ prev2 = next2;
1561
+ });
1562
+ return { bind, node: node2, dispose: h.dispose };
1563
+ }
1564
+ }
1565
+ }
1566
+ swapBlock(inst, newBlock, report, path) {
1567
+ if (inst.block.html !== newBlock.html || JSON.stringify(inst.block.scope) !== JSON.stringify(newBlock.scope) || !sameLets(inst.block, inst.exprs, newBlock, this.ir.exprs))
1568
+ return this.rebuild(inst, newBlock, report, path);
1569
+ if (!sameBinds(inst.block.binds, inst.exprs, newBlock.binds, this.ir.exprs)) {
1570
+ const nodes = newBlock.binds.map((b) => inst.pathNodes.get(pathKey(b.p)));
1571
+ if (nodes.some((n) => !n))
1572
+ return this.rebuild(inst, newBlock, report, path);
1573
+ const oldTexts = new Map;
1574
+ inst.bindHandles.forEach((h) => h.textNode && oldTexts.set(pathKey(h.bind.p), h.textNode));
1575
+ inst.bindHandles.forEach((h) => h.dispose());
1576
+ const reused = new Set;
1577
+ inst.bindHandles = newBlock.binds.map((b, i) => {
1578
+ const key = pathKey(b.p);
1579
+ const reuse = b.t === "text" ? oldTexts.get(key) : undefined;
1580
+ reuse && reused.add(key);
1581
+ return this.bindOne(b, nodes[i], inst.benv, newBlock.scope, reuse);
1582
+ });
1583
+ oldTexts.forEach((tn, key) => !reused.has(key) && tn.remove());
1584
+ report.push({ kind: "binds", path });
1585
+ }
1586
+ for (let i = 0;i < newBlock.blocks.length; i++) {
1587
+ const newChild = newBlock.blocks[i];
1588
+ const oldH = inst.childHandles[i];
1589
+ if (newChild.t === "let")
1590
+ continue;
1591
+ if (oldH && sameChild(oldH.child, oldH.exprs, newChild, this.ir.exprs))
1592
+ continue;
1593
+ oldH?.dispose();
1594
+ inst.childHandles[i] = {
1595
+ child: newChild,
1596
+ exprs: this.ir.exprs,
1597
+ anchor: oldH.anchor,
1598
+ dispose: this.execBlock(newChild, oldH.anchor, inst.benv, newBlock.scope)
1599
+ };
1600
+ report.push({ kind: "block", path: `${path}/${i}` });
1601
+ }
1602
+ inst.block = newBlock;
1603
+ inst.exprs = this.ir.exprs;
1604
+ return inst;
1605
+ }
1606
+ rebuild(inst, newBlock, report, path) {
1607
+ const fresh = this.renderBlock(newBlock, inst.penv);
1608
+ insertAfter(inst.end, nodesOf(fresh));
1609
+ destroy(inst);
1610
+ report.push({ kind: "skeleton", path });
1611
+ return fresh;
1612
+ }
1613
+ execBlock(child, anchor, benv, scopeNames) {
1614
+ const disposers = [];
1615
+ switch (child.t) {
1616
+ case "if": {
1617
+ const runs = child.branches.map((b) => b.when != null ? this.runner(b.when, scopeNames) : null);
1618
+ let current = null;
1619
+ let activeIdx = -2;
1620
+ const h = effect(() => {
1621
+ let idx = -1;
1622
+ for (let i = 0;i < child.branches.length; i++) {
1623
+ const run = runs[i];
1624
+ if (!run || run(benv)) {
1625
+ idx = i;
1626
+ break;
1627
+ }
1628
+ }
1629
+ if (idx === activeIdx)
1630
+ return;
1631
+ activeIdx = idx;
1632
+ untrack(() => {
1633
+ destroy(current);
1634
+ current = null;
1635
+ if (idx >= 0) {
1636
+ current = this.renderBlock(child.branches[idx].block, benv);
1637
+ insertAfter(anchor, nodesOf(current));
1638
+ }
1639
+ });
1640
+ });
1641
+ disposers.push(() => {
1642
+ h.dispose();
1643
+ destroy(current);
1644
+ });
1645
+ break;
1646
+ }
1647
+ case "switch": {
1648
+ const onRun = this.runner(child.on, scopeNames);
1649
+ const caseRuns = child.cases.map((c) => c.is && ("e" in c.is) ? this.runner(c.is.e, scopeNames) : null);
1650
+ let current = null;
1651
+ let activeIdx = -2;
1652
+ const h = effect(() => {
1653
+ const value = onRun(benv);
1654
+ let idx = -1, defaultIdx = -1;
1655
+ for (let i = 0;i < child.cases.length; i++) {
1656
+ const c = child.cases[i];
1657
+ if (c.is === null) {
1658
+ defaultIdx = i;
1659
+ continue;
1660
+ }
1661
+ const is = "lit" in c.is ? c.is.lit : caseRuns[i](benv);
1662
+ if (Array.isArray(is) ? is.includes(value) : is === value) {
1663
+ idx = i;
1664
+ break;
1665
+ }
1666
+ }
1667
+ if (idx === -1)
1668
+ idx = defaultIdx;
1669
+ if (idx === activeIdx)
1670
+ return;
1671
+ activeIdx = idx;
1672
+ untrack(() => {
1673
+ destroy(current);
1674
+ current = null;
1675
+ if (idx >= 0) {
1676
+ current = this.renderBlock(child.cases[idx].block, benv);
1677
+ insertAfter(anchor, nodesOf(current));
1678
+ }
1679
+ });
1680
+ });
1681
+ disposers.push(() => {
1682
+ h.dispose();
1683
+ destroy(current);
1684
+ });
1685
+ break;
1686
+ }
1687
+ case "macro": {
1688
+ const scope = Object.create(benv.scope ?? null);
1689
+ const args = reactive({});
1690
+ for (const [name, ci] of Object.entries(child.vars)) {
1691
+ if ("lit" in ci) {
1692
+ args[name] = ci.lit;
1693
+ if (child.args.includes(name)) {
1694
+ const [get2] = signal(ci.lit);
1695
+ defineGetter(scope, name, get2);
1696
+ }
1697
+ continue;
1698
+ }
1699
+ const run = this.runner(ci.e, scopeNames);
1700
+ const [get, set] = signal(undefined);
1701
+ if (child.args.includes(name))
1702
+ defineGetter(scope, name, get);
1703
+ disposers.push(effect(() => {
1704
+ const v = run(benv);
1705
+ set(v);
1706
+ args[name] = v;
1707
+ }).dispose);
1708
+ }
1709
+ const inst = this.renderBlock(child.block, { ...benv, arguments: args, scope });
1710
+ insertAfter(anchor, nodesOf(inst));
1711
+ disposers.push(() => destroy(inst));
1712
+ break;
1713
+ }
1714
+ case "for":
1715
+ this.execFor(child, anchor, benv, scopeNames, disposers);
1716
+ break;
1717
+ case "async": {
1718
+ const awaitRun = this.runner(child.awaitE, scopeNames);
1719
+ let current = null;
1720
+ let token2 = 0;
1721
+ const swapTo = (arm, value) => {
1722
+ destroy(current);
1723
+ current = null;
1724
+ if (!arm)
1725
+ return;
1726
+ const isArm = "block" in arm;
1727
+ const scope2 = Object.create(benv.scope ?? null);
1728
+ if (isArm && arm.args[0] !== undefined) {
1729
+ const [get] = signal(value);
1730
+ defineGetter(scope2, arm.args[0], get);
1731
+ }
1732
+ current = this.renderBlock(isArm ? arm.block : arm, { ...benv, scope: scope2 });
1733
+ insertAfter(anchor, nodesOf(current));
1734
+ };
1735
+ const h = effect(() => {
1736
+ const p = awaitRun(benv);
1737
+ const my = ++token2;
1738
+ untrack(() => {
1739
+ child.loading ? swapTo(child.loading) : swapTo(undefined);
1740
+ Promise.resolve(p).then((v) => my === token2 && untrack(() => swapTo(child.then, v)), (err) => my === token2 && untrack(() => swapTo(child.catch, err)));
1741
+ });
1742
+ });
1743
+ disposers.push(() => {
1744
+ token2++;
1745
+ h.dispose();
1746
+ destroy(current);
1747
+ });
1748
+ break;
1749
+ }
1750
+ case "log": {
1751
+ const segs = splitTopLevel(this.ir.exprs[child.e]).map((s) => this.srcRunner(s, scopeNames));
1752
+ disposers.push(effect(() => console.log(...segs.map((run) => run(benv)))).dispose);
1753
+ break;
1754
+ }
1755
+ case "comp": {
1756
+ const def = this.options.components?.[child.name];
1757
+ def ? this.execComponent(def, child, anchor, benv, scopeNames, disposers) : this.execElement(child, anchor, benv, scopeNames, disposers);
1758
+ break;
1759
+ }
1760
+ case "dynamic": {
1761
+ const tagRun = this.runner(child.tag, scopeNames);
1762
+ let inner = [];
1763
+ let activeVerb = Symbol("init");
1764
+ const h = effect(() => {
1765
+ const verb = tagRun(benv);
1766
+ if (verb === activeVerb)
1767
+ return;
1768
+ activeVerb = verb;
1769
+ untrack(() => {
1770
+ for (const d of inner)
1771
+ d();
1772
+ inner = [];
1773
+ if (verb == null)
1774
+ return;
1775
+ if (isSlot(verb)) {
1776
+ const argvalues = {};
1777
+ for (const [name, ci] of Object.entries(child.inputs))
1778
+ argvalues[name] = "lit" in ci ? ci.lit : this.runner(ci.e, scopeNames)(benv);
1779
+ const slotInst = verb.render(argvalues);
1780
+ insertAfter(anchor, nodesOf(slotInst));
1781
+ inner.push(() => destroy(slotInst));
1782
+ return;
1783
+ }
1784
+ const def = typeof verb === "string" ? this.options.components?.[verb] : verb && typeof verb === "object" ? verb.ir ? verb : this.options.resolveTemplate?.(verb) : undefined;
1785
+ if (def)
1786
+ this.execComponent(def, child, anchor, benv, scopeNames, inner);
1787
+ else if (typeof verb === "string")
1788
+ this.execElement({ ...child, name: verb }, anchor, benv, scopeNames, inner);
1789
+ });
1790
+ });
1791
+ disposers.push(() => {
1792
+ h.dispose();
1793
+ for (const d of inner)
1794
+ d();
1795
+ });
1796
+ break;
1797
+ }
1798
+ }
1799
+ return () => disposers.forEach((d) => d());
1800
+ }
1801
+ execFor(child, anchor, benv, scopeNames, disposers) {
1802
+ const ofRun = child.of !== undefined ? this.runner(child.of, scopeNames) : null, byRun = child.by && "e" in child.by ? this.runner(child.by.e, scopeNames) : null, byPath = child.by && "lit" in child.by ? String(child.by.lit).split(".") : null, inputVal = (ci, env) => ci === undefined ? undefined : ("lit" in ci) ? ci.lit : this.runner(ci.e, scopeNames)(env);
1803
+ let items = [];
1804
+ const byKey = new Map;
1805
+ const tuples = () => {
1806
+ if (ofRun === null) {
1807
+ const from2 = Number(inputVal(child.from, benv) ?? 0);
1808
+ const to = Number(inputVal(child.to, benv) ?? from2);
1809
+ const asc = from2 <= to;
1810
+ const out = [];
1811
+ for (let v = from2;asc ? v <= to : v >= to; asc ? v++ : v--)
1812
+ out.push({ key: v, values: [v] });
1813
+ return out;
1814
+ }
1815
+ const src = ofRun(benv);
1816
+ const keyFor = (item, fallback, index) => {
1817
+ if (byRun) {
1818
+ const fn = byRun(benv);
1819
+ return typeof fn === "function" ? fn(item, index) : fallback;
1820
+ }
1821
+ if (byPath)
1822
+ return byPath.reduce((v, k) => v?.[k], item);
1823
+ return fallback;
1824
+ };
1825
+ if (Array.isArray(src))
1826
+ return src.map((item, i) => ({ key: keyFor(item, i, i), values: [item, i] }));
1827
+ if (src instanceof Map)
1828
+ return [...src.entries()].map(([k, v], i) => ({ key: k, values: [k, v, i] }));
1829
+ if (src && typeof src === "object")
1830
+ return Object.entries(src).map(([k, v], i) => ({ key: k, values: [k, v, i] }));
1831
+ return [];
1832
+ };
1833
+ const h = effect(() => {
1834
+ const next2 = tuples();
1835
+ untrack(() => {
1836
+ const seen = new Set;
1837
+ const ordered = [];
1838
+ for (const t of next2) {
1839
+ let key = t.key;
1840
+ if (seen.has(key)) {
1841
+ console.warn(`<for> duplicate key '${String(key)}' — falling back to positional identity`);
1842
+ key = `#dup:${ordered.length}`;
1843
+ }
1844
+ seen.add(key);
1845
+ const existing = byKey.get(key);
1846
+ if (existing) {
1847
+ existing.sigs.forEach(([get, set, touch], j) => {
1848
+ const nv = t.values[j];
1849
+ Object.is(get(), nv) && typeof nv === "object" && nv !== null ? touch() : set(nv);
1850
+ });
1851
+ ordered.push(existing);
1852
+ } else {
1853
+ const scope2 = Object.create(benv.scope ?? null);
1854
+ const sigs = t.values.map((v) => signal(v));
1855
+ child.args.forEach((name, j) => sigs[j] && defineGetter(scope2, name, sigs[j][0]));
1856
+ const inst = this.renderBlock(child.block, { ...benv, scope: scope2 });
1857
+ const item = { key, sigs, inst };
1858
+ byKey.set(key, item);
1859
+ ordered.push(item);
1860
+ }
1861
+ }
1862
+ for (const item of items)
1863
+ if (!ordered.includes(item)) {
1864
+ byKey.delete(item.key);
1865
+ destroy(item.inst);
1866
+ }
1867
+ let pointer = anchor;
1868
+ for (const item of ordered) {
1869
+ if (pointer.nextSibling !== item.inst.start)
1870
+ insertAfter(pointer, nodesOf(item.inst));
1871
+ pointer = item.inst.end;
1872
+ }
1873
+ items = ordered;
1874
+ });
1875
+ });
1876
+ disposers.push(() => {
1877
+ h.dispose();
1878
+ for (const item of items)
1879
+ destroy(item.inst);
1880
+ items = [];
1881
+ byKey.clear();
1882
+ });
1883
+ }
1884
+ execComponent(def, child, anchor, benv, scopeNames, disposers) {
1885
+ const input = reactive({});
1886
+ for (const [name, ci] of Object.entries(child.inputs)) {
1887
+ if ("lit" in ci)
1888
+ input[name] = ci.lit;
1889
+ else {
1890
+ const run = this.runner(ci.e, scopeNames);
1891
+ disposers.push(effect(() => input[name] = run(benv)).dispose);
1892
+ }
1893
+ }
1894
+ for (const e of child.spreads) {
1895
+ const run = this.runner(e, scopeNames);
1896
+ disposers.push(effect(() => {
1897
+ const obj = run(benv) || {};
1898
+ untrack(() => Object.entries(obj).forEach(([k, v]) => input[k] = v));
1899
+ }).dispose);
1900
+ }
1901
+ if (child.contents) {
1902
+ const parent = this, contents = child.contents, penv = benv;
1903
+ input.renderer = {
1904
+ [SLOT]: true,
1905
+ args: contents.args,
1906
+ render(argvalues) {
1907
+ const scope = Object.create(penv.scope ?? null);
1908
+ contents.args.forEach((name) => {
1909
+ const [get] = signal(argvalues?.[name]);
1910
+ defineGetter(scope, name, get);
1911
+ });
1912
+ return parent.renderBlock(contents.block, { ...penv, scope });
1913
+ }
1914
+ };
1915
+ }
1916
+ const state = reactive({ ...def.state || {} }, def.deep ?? false);
1917
+ const listeners = new Map;
1918
+ const self = {
1919
+ ...this.options.expose || {},
1920
+ state,
1921
+ input,
1922
+ static: def.statics,
1923
+ context: benv.context,
1924
+ emit(event, ...args) {
1925
+ listeners.get(event)?.forEach((fn) => fn(...args));
1926
+ },
1927
+ on(event, fn) {
1928
+ listeners.set(event, [...listeners.get(event) || [], fn]);
1929
+ return self;
1930
+ },
1931
+ off(event) {
1932
+ listeners.delete(event);
1933
+ return self;
1934
+ }
1935
+ };
1936
+ def.handlers && Object.entries(def.handlers).forEach(([k, fn]) => self[k] = fn.bind(self));
1937
+ child.events?.forEach((ev) => {
1938
+ const dispatch = this.eventDispatcher(this.ir.exprs[ev.e], scopeNames, benv);
1939
+ self.on(ev.name, dispatch);
1940
+ });
1941
+ const hooks = makeHooks(self);
1942
+ try {
1943
+ typeof self.onCreate === "function" && self.onCreate();
1944
+ } catch (error) {
1945
+ hooks.onError(error);
1946
+ }
1947
+ try {
1948
+ Object.keys(input).length && typeof self.onInput === "function" && self.onInput();
1949
+ } catch (error) {
1950
+ hooks.onError(error);
1951
+ }
1952
+ const cenv = { state, input, context: benv.context, static: def.statics, self, scope: undefined };
1953
+ const renderer = new IRRenderer(def.ir, this.options, hooks);
1954
+ const inst = renderer.renderBlock(def.ir.root, cenv);
1955
+ const clearStyles = def.stylesheet ? applyScopedStyles(this.options, inst, def.nsp || "lips", def.stylesheet) : undefined;
1956
+ insertAfter(anchor, nodesOf(inst));
1957
+ hooks.ready();
1958
+ try {
1959
+ typeof self.onMount === "function" && self.onMount();
1960
+ typeof self.onRender === "function" && self.onRender();
1961
+ } catch (error) {
1962
+ hooks.onError(error);
1963
+ }
1964
+ let unwatchContext;
1965
+ if (def.context?.length && typeof self.onContext === "function" && this.options.watchContext)
1966
+ unwatchContext = this.options.watchContext(def.context, () => {
1967
+ try {
1968
+ self.onContext();
1969
+ } catch (error) {
1970
+ hooks.onError(error);
1971
+ }
1972
+ });
1973
+ let attached = false;
1974
+ if (typeof self.onAttach === "function" || typeof self.onDetach === "function") {
1975
+ PENDING_ATTACH.push({
1976
+ node: () => inst.start,
1977
+ fn: () => {
1978
+ attached = true;
1979
+ try {
1980
+ typeof self.onAttach === "function" && self.onAttach();
1981
+ } catch (error) {
1982
+ hooks.onError(error);
1983
+ }
1984
+ }
1985
+ });
1986
+ inst.start.isConnected && flushAttach();
1987
+ }
1988
+ disposers.push(() => {
1989
+ unwatchContext?.();
1990
+ clearStyles?.();
1991
+ destroy(inst);
1992
+ try {
1993
+ attached && typeof self.onDetach === "function" && self.onDetach();
1994
+ typeof self.onDestroy === "function" && self.onDestroy();
1995
+ } catch (error) {
1996
+ hooks.onError(error);
1997
+ }
1998
+ });
1999
+ }
2000
+ execElement(child, anchor, benv, scopeNames, disposers) {
2001
+ const el = document.createElement(child.name);
2002
+ for (const [name, ci] of Object.entries(child.inputs)) {
2003
+ if ("lit" in ci)
2004
+ applyAttr(el, name, ci.lit);
2005
+ else {
2006
+ const run = this.runner(ci.e, scopeNames);
2007
+ disposers.push(effect(() => applyAttr(el, name, run(benv))).dispose);
2008
+ }
2009
+ }
2010
+ for (const ev of child.events) {
2011
+ const handler = this.eventDispatcher(this.ir.exprs[ev.e], scopeNames, benv);
2012
+ el.addEventListener(ev.name, handler);
2013
+ disposers.push(() => el.removeEventListener(ev.name, handler));
2014
+ }
2015
+ if (child.contents) {
2016
+ const inst = this.renderBlock(child.contents.block, benv);
2017
+ el.append(...nodesOf(inst));
2018
+ disposers.push(() => destroy(inst));
2019
+ }
2020
+ insertAfter(anchor, [el]);
2021
+ disposers.push(() => el.remove());
2022
+ }
2023
+ eventDispatcher(instruction, scopeNames, benv) {
2024
+ const segs = splitTopLevel(instruction);
2025
+ return (...params) => untrack(() => {
2026
+ const resolveFn = (src) => {
2027
+ let v;
2028
+ try {
2029
+ v = this.srcRunner(src, scopeNames)(benv);
2030
+ } catch (e) {
2031
+ v = undefined;
2032
+ }
2033
+ if (typeof v !== "function" && benv.self && typeof benv.self[src] === "function")
2034
+ v = benv.self[src];
2035
+ return v;
2036
+ };
2037
+ if (!segs.length)
2038
+ return;
2039
+ const fn = resolveFn(segs[0]);
2040
+ if (typeof fn !== "function")
2041
+ return;
2042
+ const args = segs.slice(1).map((src) => this.srcRunner(src, scopeNames)(benv));
2043
+ fn(...args, ...params);
2044
+ });
2045
+ }
2046
+ }
2047
+ function renderIR(ir, setup = {}, options = {}) {
2048
+ const state = reactive(setup.state || {}, setup.deep ?? false), input = setup.input ? reactive(setup.input, setup.deep ?? false) : undefined, self = { state, input, static: setup.static, ...setup.expose || {} };
2049
+ setup.handlers && Object.entries(setup.handlers).forEach(([k, fn]) => self[k] = fn.bind(self));
2050
+ const env = {
2051
+ state,
2052
+ input,
2053
+ context: setup.context,
2054
+ static: setup.static,
2055
+ self,
2056
+ scope: undefined
2057
+ };
2058
+ const hooks = makeHooks(self);
2059
+ try {
2060
+ typeof self.onCreate === "function" && self.onCreate();
2061
+ } catch (error) {
2062
+ hooks.onError(error);
2063
+ }
2064
+ try {
2065
+ input && Object.keys(input).length && typeof self.onInput === "function" && self.onInput();
2066
+ } catch (error) {
2067
+ hooks.onError(error);
2068
+ }
2069
+ let renderer = new IRRenderer(ir, options, hooks);
2070
+ let current = renderer.renderBlock(ir.root, env);
2071
+ hooks.ready();
2072
+ const clearStyles = setup.stylesheet ? applyScopedStyles(options, current, setup.nsp || "lips", setup.stylesheet) : undefined;
2073
+ try {
2074
+ typeof self.onMount === "function" && self.onMount();
2075
+ typeof self.onRender === "function" && self.onRender();
2076
+ } catch (error) {
2077
+ hooks.onError(error);
2078
+ }
2079
+ let attached = false;
2080
+ const attachSelf = () => {
2081
+ if (attached)
2082
+ return;
2083
+ attached = true;
2084
+ try {
2085
+ typeof self.onAttach === "function" && self.onAttach();
2086
+ } catch (error) {
2087
+ hooks.onError(error);
2088
+ }
2089
+ };
2090
+ return {
2091
+ state,
2092
+ self,
2093
+ get nodes() {
2094
+ return nodesOf(current);
2095
+ },
2096
+ mount(container) {
2097
+ container.append(...nodesOf(current));
2098
+ if (current.start.isConnected) {
2099
+ attachSelf();
2100
+ flushAttach();
2101
+ }
2102
+ },
2103
+ swap(newIR) {
2104
+ const changes = [];
2105
+ renderer = new IRRenderer(newIR, options, hooks);
2106
+ current = renderer.swapBlock(current, newIR.root, changes, "root");
2107
+ return { changes };
2108
+ },
2109
+ dispose() {
2110
+ clearStyles?.();
2111
+ destroy(current);
2112
+ try {
2113
+ attached && typeof self.onDetach === "function" && self.onDetach();
2114
+ typeof self.onDestroy === "function" && self.onDestroy();
2115
+ } catch (error) {
2116
+ hooks.onError(error);
2117
+ }
2118
+ }
2119
+ };
2120
+ }
2121
+
2122
+ // src/events.ts
2123
+ class Events {
2124
+ options = {
2125
+ emit: true
2126
+ };
2127
+ __events = {};
2128
+ __once_events = {};
2129
+ constructor(options) {
2130
+ if (options)
2131
+ this.options = options;
2132
+ }
2133
+ on(_event, fn) {
2134
+ if (!Array.isArray(this.__events[_event]))
2135
+ this.__events[_event] = [];
2136
+ this.__events[_event].push(fn);
2137
+ return this;
2138
+ }
2139
+ once(_event, fn) {
2140
+ if (!Array.isArray(this.__once_events[_event]))
2141
+ this.__once_events[_event] = [];
2142
+ this.__once_events[_event].push(fn);
2143
+ return this;
2144
+ }
2145
+ off(_event, fn) {
2146
+ if (fn) {
2147
+ if (Array.isArray(this.__events[_event])) {
2148
+ this.__events[_event] = this.__events[_event].filter((each) => each !== fn);
2149
+ !this.__events[_event].length && delete this.__events[_event];
2150
+ }
2151
+ if (Array.isArray(this.__once_events[_event])) {
2152
+ this.__once_events[_event] = this.__once_events[_event].filter((each) => each !== fn);
2153
+ !this.__once_events[_event].length && delete this.__once_events[_event];
2154
+ }
2155
+ } else {
2156
+ delete this.__events[_event];
2157
+ delete this.__once_events[_event];
2158
+ }
2159
+ return this;
2160
+ }
2161
+ emit(_event, ...params) {
2162
+ if (!this.options.emit)
2163
+ return;
2164
+ const deepclean = (each) => {
2165
+ if (!each || typeof each !== "object")
2166
+ return each;
2167
+ if (typeof each.toJSON === "function")
2168
+ return each.toJSON();
2169
+ if (Array.isArray(each))
2170
+ return each.map(deepclean);
2171
+ if (each.constructor === Object || each.constructor === undefined) {
2172
+ const clone = {};
2173
+ for (const key in each)
2174
+ clone[key] = deepclean(each[key]);
2175
+ return clone;
2176
+ }
2177
+ return each;
2178
+ }, serialized = params.map(deepclean);
2179
+ this.__events[_event]?.forEach((fn) => fn(...serialized));
2180
+ this.__once_events[_event]?.forEach((fn) => fn(...serialized));
2181
+ delete this.__once_events[_event];
2182
+ }
2183
+ }
2184
+
2185
+ // src/stylesheet.ts
2186
+ var STYLE_COMPILER = null;
2187
+ function setStyleCompiler(fn) {
2188
+ STYLE_COMPILER = fn;
2189
+ }
2190
+
2191
+ class Stylesheet {
2192
+ nsp;
2193
+ settings;
2194
+ constructor(nsp, settings) {
2195
+ if (typeof nsp !== "string" || !nsp)
2196
+ throw new Error("Undefined or invalid stylesheet namespace");
2197
+ this.nsp = nsp;
2198
+ this.settings = settings || {};
2199
+ this.settings.sheet && this.load(this.settings);
2200
+ }
2201
+ get rel() {
2202
+ return `${this.settings.meta ? "@" : ""}${this.nsp}`;
2203
+ }
2204
+ get styleElement() {
2205
+ return document.head.querySelector(`style[rel="${this.rel}"]`);
2206
+ }
2207
+ load(settings) {
2208
+ this.settings = settings;
2209
+ if (!settings.sheet)
2210
+ return;
2211
+ if (!STYLE_COMPILER) {
2212
+ console.warn(`[lips] <${this.nsp}> stylesheet skipped — this build has no CSS preprocessor. ` + 'Use "@lipsjs/lips" (not "@lipsjs/lips/runtime") for source stylesheets.');
2213
+ return;
2214
+ }
2215
+ const existing = this.styleElement;
2216
+ if (existing) {
2217
+ existing.setAttribute("dindex", String(Number(existing.getAttribute("dindex") || 0) + 1));
2218
+ return existing;
2219
+ }
2220
+ const source = settings.meta ? settings.sheet : `[rel="${this.nsp}"] { ${settings.sheet} }`;
2221
+ let sheet;
2222
+ try {
2223
+ sheet = STYLE_COMPILER(source);
2224
+ } catch (error) {
2225
+ throw new Error(`Style compilation failed: ${error.message}`);
2226
+ }
2227
+ if (!sheet)
2228
+ throw new Error(`<${this.nsp}> stylesheet compilation produced no output`);
2229
+ const element = document.createElement("style");
2230
+ element.setAttribute("rel", this.rel);
2231
+ element.setAttribute("dindex", "0");
2232
+ element.textContent = sheet;
2233
+ settings.meta ? document.head.prepend(element) : document.head.appendChild(element);
2234
+ return element;
2235
+ }
2236
+ clear() {
2237
+ const element = this.styleElement;
2238
+ if (!element)
2239
+ return;
2240
+ const dindex = Number(element.getAttribute("dindex") || 0);
2241
+ dindex <= 0 ? element.remove() : element.setAttribute("dindex", String(dindex - 1));
2242
+ }
2243
+ }
2244
+
2245
+ // src/i18n/formatters.ts
2246
+ function injectParams(text, params) {
2247
+ if (typeof text !== "string")
2248
+ return "";
2249
+ if (!params)
2250
+ return text;
2251
+ return text.replace(/{(\w+)}/g, (_, key) => {
2252
+ return params[key] !== undefined ? params[key].toString() : `{${key}}`;
2253
+ });
2254
+ }
2255
+ var formatters_default = (type, reference, value, params, variant) => {
2256
+ switch (type) {
2257
+ case "plural": {
2258
+ if (typeof value === "string") {
2259
+ console.warn(`Plural format value cannot be a string`);
2260
+ return;
2261
+ }
2262
+ if (params.count === undefined) {
2263
+ console.warn(`Plural format requires <count> parameter or use * by default.`);
2264
+ let formText2 = value["*"];
2265
+ if (typeof formText2 === "object")
2266
+ formText2 = formText2[variant || "*"];
2267
+ return injectParams(formText2, params);
2268
+ }
2269
+ if (typeof params.count === "string")
2270
+ params.count = Number(params.count);
2271
+ let form = "*";
2272
+ if (params.count.toString() in value)
2273
+ form = params.count.toString();
2274
+ let formText = value[form] || value["*"];
2275
+ if (typeof formText === "object")
2276
+ formText = formText[variant || "*"];
2277
+ return injectParams(formText, params);
2278
+ }
2279
+ case "condition": {
2280
+ if (typeof value === "string") {
2281
+ console.warn(`Condition format value cannot be a string`);
2282
+ return;
2283
+ }
2284
+ let text;
2285
+ for (const expr in value)
2286
+ try {
2287
+ const fn = new Function("params", `with( params ){ return ${expr}; }`);
2288
+ if (fn(params || {})) {
2289
+ text = value[expr];
2290
+ break;
2291
+ }
2292
+ } catch (error) {
2293
+ console.warn(`Invalid <${reference}(${expr})> condition expression`);
2294
+ }
2295
+ if (text === undefined)
2296
+ return;
2297
+ if (typeof text === "object")
2298
+ text = text[variant || "*"];
2299
+ return injectParams(text, params);
2300
+ }
2301
+ case "variable":
2302
+ default: {
2303
+ const text = typeof value === "object" ? value[variant || "*"] : value;
2304
+ if (typeof text === "object") {
2305
+ console.warn(`Invalid <${reference}> variable variant definition`);
2306
+ return;
2307
+ }
2308
+ return injectParams(text, params);
2309
+ }
2310
+ }
2311
+ };
2312
+
2313
+ // src/i18n/index.ts
2314
+ class I18N {
2315
+ currentLang = window.navigator.language;
2316
+ DICTIONARIES = {};
2317
+ set lang(value) {
2318
+ if (this.currentLang === value)
2319
+ return;
2320
+ this.currentLang = value;
2321
+ }
2322
+ get lang() {
2323
+ return this.currentLang;
2324
+ }
2325
+ setDictionary(id, dico) {
2326
+ this.DICTIONARIES[id] = dico;
2327
+ }
2328
+ translate(text, lang) {
2329
+ if (lang && this.currentLang === lang)
2330
+ return { text, lang: this.currentLang };
2331
+ lang = lang || this.currentLang;
2332
+ const [id, variant] = lang.split("-");
2333
+ if (this.DICTIONARIES[id] && text in this.DICTIONARIES[id]) {
2334
+ if (typeof this.DICTIONARIES[id][text] === "object") {
2335
+ const variants = this.DICTIONARIES[id][text];
2336
+ text = variants[variant || "*"] || variants["*"];
2337
+ } else if (typeof this.DICTIONARIES[id][text] === "string")
2338
+ text = this.DICTIONARIES[id][text];
2339
+ }
2340
+ return { text, lang };
2341
+ }
2342
+ format(reference, params, local) {
2343
+ local = local || this.currentLang;
2344
+ const [id, variant] = local.split("-");
2345
+ if (!this.DICTIONARIES[id]) {
2346
+ console.warn(`Undefined <${local}> format dictionary`);
2347
+ return;
2348
+ }
2349
+ if (!this.DICTIONARIES[id][reference]) {
2350
+ console.warn(`Undefined <${local}[${reference}]> format reference`);
2351
+ return;
2352
+ }
2353
+ const format = this.DICTIONARIES[id][reference];
2354
+ if (typeof format === "string") {
2355
+ console.warn(`Invalid <${local}[${reference}]> format reference. Expected object`);
2356
+ return;
2357
+ }
2358
+ if (typeof format !== "object" || format === null || Array.isArray(format)) {
2359
+ console.warn(`Invalid <${local}[${reference}]> format value`);
2360
+ return;
2361
+ }
2362
+ return formatters_default(format.type, reference, format.value, params, variant);
2363
+ }
2364
+ }
2365
+
2366
+ // src/ir/facade.ts
2367
+ var COMPILER = null;
2368
+ function setCompiler(fn) {
2369
+ COMPILER = fn;
2370
+ }
2371
+ var BUILTINS = {};
2372
+ function registerBuiltin(name, template) {
2373
+ BUILTINS[name] = template;
2374
+ }
2375
+ var RESERVED_MEMBERS = new Set([
2376
+ "state",
2377
+ "input",
2378
+ "static",
2379
+ "context",
2380
+ "emit",
2381
+ "on",
2382
+ "once",
2383
+ "off",
2384
+ "node",
2385
+ "destroy",
2386
+ "appendTo",
2387
+ "prependTo",
2388
+ "replaceWith",
2389
+ "render",
2390
+ "swap"
2391
+ ]);
2392
+ function guardHandlers(handler) {
2393
+ if (!handler)
2394
+ return;
2395
+ for (const name of Object.keys(handler))
2396
+ if (RESERVED_MEMBERS.has(name))
2397
+ throw new Error(`Handler <${name}> is a reserved component member name`);
2398
+ return handler;
2399
+ }
2400
+
2401
+ class IRFacadeComponent extends Events {
2402
+ lips;
2403
+ template;
2404
+ state;
2405
+ instance;
2406
+ contextWatcher;
2407
+ destroyed = false;
2408
+ constructor(lips, name, template, input, ir, options) {
2409
+ super();
2410
+ this.lips = lips;
2411
+ this.template = template;
2412
+ const handlers = guardHandlers(template.handler);
2413
+ this.state = reactive({ ...template.state || {} }, true);
2414
+ const inputR = input ? reactive({ ...input }, true) : undefined;
2415
+ this.instance = renderIR(ir, {
2416
+ state: this.state,
2417
+ input: inputR,
2418
+ context: lips.getContext(),
2419
+ static: template._static,
2420
+ handlers,
2421
+ deep: true,
2422
+ stylesheet: template.stylesheet,
2423
+ nsp: name,
2424
+ expose: {
2425
+ emit: (event, ...args) => this.emit(event, ...args),
2426
+ context: lips.getContext()
2427
+ }
2428
+ }, options);
2429
+ if (template.context?.length && typeof handlers?.onContext === "function")
2430
+ this.contextWatcher = lips.watchContext(template.context, () => {
2431
+ try {
2432
+ handlers.onContext.call(this.instance.self);
2433
+ } catch (error) {
2434
+ console.error("[lips:ir]", error);
2435
+ }
2436
+ });
2437
+ this.emit("component:mount");
2438
+ }
2439
+ get node() {
2440
+ return this.instance.nodes;
2441
+ }
2442
+ appendTo(selector) {
2443
+ const target = typeof selector === "string" ? document.querySelector(selector) : selector;
2444
+ target && this.instance.mount(target);
2445
+ return this;
2446
+ }
2447
+ swap(newIR) {
2448
+ return this.instance.swap(newIR);
2449
+ }
2450
+ destroy() {
2451
+ if (this.destroyed)
2452
+ return;
2453
+ this.destroyed = true;
2454
+ this.contextWatcher?.();
2455
+ this.instance.dispose();
2456
+ this.emit("component:destroy");
2457
+ }
2458
+ }
2459
+
2460
+ class IRLips {
2461
+ config;
2462
+ debug;
2463
+ store = new Map;
2464
+ irCache = new WeakMap;
2465
+ defCache = new WeakMap;
2466
+ context;
2467
+ __root;
2468
+ i18n = new I18N;
2469
+ getLang;
2470
+ setLang;
2471
+ componentsProxy;
2472
+ constructor(config) {
2473
+ this.config = config;
2474
+ this.debug = !!config?.debug;
2475
+ this.context = reactive({ ...config?.context || {} }, true);
2476
+ const [getLang, setLang] = signal(this.i18n.lang);
2477
+ this.getLang = getLang;
2478
+ this.setLang = setLang;
2479
+ COMPILER && Object.entries(BUILTINS).forEach(([name, template]) => this.register(name, template));
2480
+ const self = this;
2481
+ this.componentsProxy = new Proxy({}, {
2482
+ get(_, name) {
2483
+ const template = self.store.get(name);
2484
+ return template ? self.defFor(name, template) : undefined;
2485
+ },
2486
+ has(_, name) {
2487
+ return self.store.has(name);
2488
+ }
2489
+ });
2490
+ }
2491
+ register(name, template) {
2492
+ this.store.set(name, template);
2493
+ return this;
2494
+ }
2495
+ unregister(name) {
2496
+ this.store.delete(name);
2497
+ return this;
2498
+ }
2499
+ has(name) {
2500
+ return this.store.has(name);
2501
+ }
2502
+ compile(template) {
2503
+ if (template.ir)
2504
+ return template.ir;
2505
+ let ir = this.irCache.get(template);
2506
+ if (!ir) {
2507
+ if (!COMPILER)
2508
+ throw new Error("This build has no template compiler — templates must be precompiled to `ir` " + '(import from "@lipsjs/lips" instead of "@lipsjs/lips/runtime")');
2509
+ const result = COMPILER(template.default || "", { macros: template.macros });
2510
+ result.diagnostics.length && console.warn("[lips:ir] template diagnostics —", result.diagnostics);
2511
+ ir = result.ir;
2512
+ this.irCache.set(template, ir);
2513
+ }
2514
+ return ir;
2515
+ }
2516
+ defFor(name, template) {
2517
+ let def = this.defCache.get(template);
2518
+ if (!def) {
2519
+ def = {
2520
+ ir: this.compile(template),
2521
+ state: template.state,
2522
+ statics: template._static,
2523
+ context: template.context,
2524
+ stylesheet: template.stylesheet,
2525
+ nsp: name,
2526
+ handlers: guardHandlers(template.handler),
2527
+ deep: true
2528
+ };
2529
+ this.defCache.set(template, def);
2530
+ }
2531
+ return def;
2532
+ }
2533
+ render(name, template, input) {
2534
+ return new IRFacadeComponent(this, name, template, input, this.compile(template), {
2535
+ mode: this.config?.mode,
2536
+ components: this.componentsProxy,
2537
+ watchContext: (fields, fn) => this.watchContext(fields, fn),
2538
+ resolveTemplate: (value) => value && (typeof value.default === "string" || value.ir) ? this.defFor(value.name || "dynamic", value) : undefined,
2539
+ expose: {
2540
+ setContext: (arg, value) => this.setContext(arg, value)
2541
+ },
2542
+ createStylesheet: (nsp, css) => {
2543
+ const sheet = new Stylesheet(nsp, { sheet: css });
2544
+ return { clear: () => sheet.clear() };
2545
+ },
2546
+ i18n: {
2547
+ translate: (text) => {
2548
+ this.getLang();
2549
+ return this.i18n.translate(text).text;
2550
+ },
2551
+ format: (reference, params) => {
2552
+ this.getLang();
2553
+ return this.i18n.format(reference, params) ?? "";
2554
+ }
2555
+ }
2556
+ });
2557
+ }
2558
+ root(template, selector) {
2559
+ this.__root = this.render("__ROOT__", template);
2560
+ this.__root.appendTo(selector);
2561
+ return this.__root;
2562
+ }
2563
+ setLanguage(lang) {
2564
+ this.i18n.lang = lang;
2565
+ this.setLang(lang);
2566
+ }
2567
+ getLanguage() {
2568
+ return this.getLang();
2569
+ }
2570
+ useTranslator(support, fn) {
2571
+ let first = true;
2572
+ const { dispose } = effect(() => {
2573
+ const lang = this.getLang();
2574
+ if (first) {
2575
+ first = false;
2576
+ return;
2577
+ }
2578
+ (support === "*" || Array.isArray(support) && support.includes(lang)) && fn(lang);
2579
+ });
2580
+ return dispose;
2581
+ }
2582
+ getContext() {
2583
+ return this.context;
2584
+ }
2585
+ setContext(arg, value) {
2586
+ typeof arg === "string" ? this.context[arg] = value : Object.entries(arg).forEach(([k, v]) => this.context[k] = v);
2587
+ }
2588
+ watchContext(fields, fn) {
2589
+ let first = true;
2590
+ const { dispose } = effect(() => {
2591
+ fields.forEach((f) => this.context[f]);
2592
+ first ? first = false : fn();
2593
+ });
2594
+ return dispose;
2595
+ }
2596
+ useContext(fields, fn) {
2597
+ return this.watchContext(fields, () => fn(Object.fromEntries(fields.map((f) => [f, this.context[f]]))));
2598
+ }
2599
+ dispose() {
2600
+ this.__root?.destroy();
2601
+ }
2602
+ }
2603
+
2604
+ // src/ir/parser.ts
2605
+ var VOID_ELEMENTS = new Set([
2606
+ "area",
2607
+ "base",
2608
+ "br",
2609
+ "col",
2610
+ "embed",
2611
+ "hr",
2612
+ "img",
2613
+ "input",
2614
+ "link",
2615
+ "meta",
2616
+ "param",
2617
+ "source",
2618
+ "track",
2619
+ "wbr"
2620
+ ]);
2621
+ var RAW_WHITESPACE_TAGS = new Set(["pre", "textarea"]);
2622
+ var HEAD_SUGAR_TAGS = new Set(["if", "else-if", "switch", "log"]);
2623
+ var NAMED_ENTITIES = {
2624
+ "&amp;": "&",
2625
+ "&lt;": "<",
2626
+ "&gt;": ">",
2627
+ "&quot;": '"',
2628
+ "&#39;": "'",
2629
+ "&nbsp;": " "
2630
+ };
2631
+ function decodeEntities(text) {
2632
+ return text.replace(/&(?:amp|lt|gt|quot|#39|nbsp);/g, (m) => NAMED_ENTITIES[m]);
2633
+ }
2634
+
2635
+ class TemplateParser {
2636
+ src;
2637
+ pos = 0;
2638
+ lineStarts = null;
2639
+ diagnostics = [];
2640
+ constructor(src) {
2641
+ this.src = src;
2642
+ }
2643
+ locate(offset) {
2644
+ if (!this.lineStarts) {
2645
+ this.lineStarts = [0];
2646
+ for (let i = 0;i < this.src.length; i++)
2647
+ if (this.src[i] === `
2648
+ `)
2649
+ this.lineStarts.push(i + 1);
2650
+ }
2651
+ let lo = 0, hi = this.lineStarts.length - 1;
2652
+ while (lo < hi) {
2653
+ const mid = lo + hi + 1 >> 1;
2654
+ this.lineStarts[mid] <= offset ? lo = mid : hi = mid - 1;
2655
+ }
2656
+ return { line: lo + 1, col: offset - this.lineStarts[lo] + 1 };
2657
+ }
2658
+ report(code, severity, message, offset, length2 = 1, hint) {
2659
+ const { line: line2, col } = this.locate(offset);
2660
+ this.diagnostics.push({ code, severity, message, hint, loc: { line: line2, col, offset, length: length2 } });
2661
+ }
2662
+ eof() {
2663
+ return this.pos >= this.src.length;
2664
+ }
2665
+ peek(offset = 0) {
2666
+ return this.src[this.pos + offset];
2667
+ }
2668
+ startsWith(str) {
2669
+ return this.src.startsWith(str, this.pos);
2670
+ }
2671
+ skipSpace() {
2672
+ while (!this.eof() && /\s/.test(this.src[this.pos]))
2673
+ this.pos++;
2674
+ }
2675
+ scanBalanced(closer, code) {
2676
+ const start = this.pos;
2677
+ let depth = 0;
2678
+ while (!this.eof()) {
2679
+ const c = this.src[this.pos];
2680
+ if (c === "'" || c === '"' || c === "`") {
2681
+ this.pos++;
2682
+ while (!this.eof() && this.src[this.pos] !== c) {
2683
+ if (this.src[this.pos] === "\\")
2684
+ this.pos++;
2685
+ this.pos++;
2686
+ }
2687
+ this.pos++;
2688
+ continue;
2689
+ }
2690
+ if (depth === 0 && c === closer) {
2691
+ const content = this.src.slice(start, this.pos);
2692
+ this.pos++;
2693
+ return { content, loc: { offset: start, length: content.length } };
2694
+ }
2695
+ if (c === "(" || c === "[" || c === "{")
2696
+ depth++;
2697
+ else if (c === ")" || c === "]" || c === "}") {
2698
+ if (depth === 0 && c !== closer) {
2699
+ this.report(code, "error", `Unbalanced '${c}'`, this.pos);
2700
+ this.pos++;
2701
+ continue;
2702
+ }
2703
+ depth--;
2704
+ }
2705
+ this.pos++;
2706
+ }
2707
+ this.report(code, "error", `Unterminated — expected '${closer}'`, start, this.pos - start);
2708
+ return null;
2709
+ }
2710
+ parse() {
2711
+ const children = [];
2712
+ while (!this.eof()) {
2713
+ children.push(...this.parseNodes([]));
2714
+ if (this.startsWith("</")) {
2715
+ const closeStart = this.pos;
2716
+ this.pos += 2;
2717
+ while (!this.eof() && this.peek() !== ">")
2718
+ this.pos++;
2719
+ !this.eof() && this.pos++;
2720
+ this.report("LIPS-P005", "error", `Stray closing tag ${this.src.slice(closeStart, this.pos)}`, closeStart, this.pos - closeStart);
2721
+ }
2722
+ }
2723
+ return {
2724
+ root: { t: "fragment", children, loc: { offset: 0, length: this.src.length } },
2725
+ diagnostics: this.diagnostics
2726
+ };
2727
+ }
2728
+ parseNodes(stack) {
2729
+ const nodes = [];
2730
+ while (!this.eof()) {
2731
+ if (this.startsWith("</"))
2732
+ break;
2733
+ const before = this.pos;
2734
+ if (this.peek() === "<" && this.peek(1) !== undefined) {
2735
+ const node2 = this.parseTag(stack);
2736
+ node2 && nodes.push(node2);
2737
+ } else {
2738
+ const text = this.parseText(stack);
2739
+ text && nodes.push(text);
2740
+ }
2741
+ if (this.pos === before)
2742
+ this.pos++;
2743
+ }
2744
+ return nodes;
2745
+ }
2746
+ parseText(stack) {
2747
+ const start = this.pos;
2748
+ const parts = [];
2749
+ let buffer = "";
2750
+ while (!this.eof() && this.peek() !== "<") {
2751
+ if (this.peek() === "{") {
2752
+ this.pos++;
2753
+ const region = this.scanBalanced("}", "LIPS-P007");
2754
+ if (region) {
2755
+ buffer && parts.push(buffer);
2756
+ buffer = "";
2757
+ parts.push({ expr: region.content.trim(), loc: region.loc });
2758
+ }
2759
+ continue;
2760
+ }
2761
+ buffer += this.peek();
2762
+ this.pos++;
2763
+ }
2764
+ buffer && parts.push(buffer);
2765
+ const loc = { offset: start, length: this.pos - start };
2766
+ if (parts.some((p) => typeof p !== "string"))
2767
+ return {
2768
+ t: "interp",
2769
+ parts: parts.map((p) => typeof p === "string" ? decodeEntities(p) : p),
2770
+ loc
2771
+ };
2772
+ const raw = parts.length ? parts[0] : "";
2773
+ const inRaw = stack.some((tag) => RAW_WHITESPACE_TAGS.has(tag));
2774
+ if (!raw || !inRaw && !raw.trim())
2775
+ return null;
2776
+ return { t: "text", value: decodeEntities(raw), loc };
2777
+ }
2778
+ parseTag(stack) {
2779
+ const start = this.pos;
2780
+ if (this.startsWith("<!--")) {
2781
+ const end = this.src.indexOf("-->", this.pos + 4);
2782
+ if (end === -1) {
2783
+ this.report("LIPS-P003", "error", "Unterminated comment", start, this.src.length - start);
2784
+ this.pos = this.src.length;
2785
+ return null;
2786
+ }
2787
+ const value = this.src.slice(this.pos + 4, end);
2788
+ this.pos = end + 3;
2789
+ return { t: "comment", value, loc: { offset: start, length: this.pos - start } };
2790
+ }
2791
+ if (this.startsWith("<>")) {
2792
+ this.pos += 2;
2793
+ const children = [];
2794
+ while (true) {
2795
+ children.push(...this.parseNodes([...stack, "#fragment"]));
2796
+ if (this.closeStatus("#fragment", start, stack) !== "stray")
2797
+ break;
2798
+ }
2799
+ return { t: "fragment", children, loc: { offset: start, length: this.pos - start } };
2800
+ }
2801
+ if (this.startsWith("<{")) {
2802
+ this.pos += 2;
2803
+ const region = this.scanBalanced("}", "LIPS-P008");
2804
+ if (!region)
2805
+ return null;
2806
+ const el2 = {
2807
+ t: "element",
2808
+ tag: "#dynamic",
2809
+ dynamicTag: { expr: region.content.trim(), loc: region.loc },
2810
+ attrs: [],
2811
+ children: [],
2812
+ selfClosed: false,
2813
+ loc: { offset: start, length: 0 }
2814
+ };
2815
+ this.finishTag(el2, stack, start);
2816
+ return el2;
2817
+ }
2818
+ this.pos++;
2819
+ const nameStart = this.pos;
2820
+ while (!this.eof() && /[A-Za-z0-9_-]/.test(this.peek()))
2821
+ this.pos++;
2822
+ const tag = this.src.slice(nameStart, this.pos);
2823
+ if (!tag || !/^[A-Za-z]/.test(tag)) {
2824
+ this.report("LIPS-P002", "error", "Invalid tag name", start, this.pos - start + 1);
2825
+ return { t: "text", value: "<", loc: { offset: start, length: 1 } };
2826
+ }
2827
+ const el = {
2828
+ t: "element",
2829
+ tag: tag.toLowerCase(),
2830
+ attrs: [],
2831
+ children: [],
2832
+ selfClosed: false,
2833
+ loc: { offset: start, length: 0 }
2834
+ };
2835
+ if (this.peek() === "(") {
2836
+ if (HEAD_SUGAR_TAGS.has(el.tag)) {
2837
+ this.pos++;
2838
+ const region = this.scanBalanced(")", "LIPS-P012");
2839
+ region && (el.head = { expr: region.content.trim(), loc: region.loc });
2840
+ } else
2841
+ this.report("LIPS-P011", "error", `Head expression is not allowed on <${el.tag}>`, this.pos, 1, `Only ${[...HEAD_SUGAR_TAGS].map((t) => `<${t}(…)>`).join(", ")} take a head`);
2842
+ }
2843
+ this.finishTag(el, stack, start);
2844
+ return el;
2845
+ }
2846
+ finishTag(el, stack, start) {
2847
+ this.parseAttrs(el);
2848
+ if (el.selfClosed || VOID_ELEMENTS.has(el.tag)) {
2849
+ el.selfClosed = true;
2850
+ el.loc = { offset: start, length: this.pos - start };
2851
+ return;
2852
+ }
2853
+ const stackName = el.tag === "#dynamic" ? "#dynamic" : el.tag;
2854
+ el.children = [];
2855
+ while (true) {
2856
+ el.children.push(...this.parseNodes([...stack, stackName]));
2857
+ if (this.closeStatus(stackName, start, stack) !== "stray")
2858
+ break;
2859
+ }
2860
+ el.loc = { offset: start, length: this.pos - start };
2861
+ }
2862
+ closeStatus(tag, openOffset, stack) {
2863
+ if (this.eof()) {
2864
+ this.report("LIPS-P006", "error", `Unclosed <${tag === "#fragment" ? "" : tag}> — reached end of template`, openOffset, 1, `Add </${tag === "#fragment" || tag === "#dynamic" ? "" : tag}>`);
2865
+ return "eof";
2866
+ }
2867
+ if (!this.startsWith("</"))
2868
+ return "closed";
2869
+ const closeStart = this.pos;
2870
+ this.pos += 2;
2871
+ if (this.peek() === ">") {
2872
+ this.pos++;
2873
+ if (tag !== "#fragment" && tag !== "#dynamic")
2874
+ this.report("LIPS-P004", "warning", `Generic '</>' closes <${tag}>`, closeStart, 3, `Prefer </${tag}>`);
2875
+ return "closed";
2876
+ }
2877
+ const nameStart = this.pos;
2878
+ while (!this.eof() && /[A-Za-z0-9_-]/.test(this.peek()))
2879
+ this.pos++;
2880
+ const closeTag = this.src.slice(nameStart, this.pos).toLowerCase();
2881
+ this.skipSpace();
2882
+ this.peek() === ">" ? this.pos++ : this.report("LIPS-P001", "error", `Malformed closing tag`, closeStart, this.pos - closeStart);
2883
+ if (closeTag === tag)
2884
+ return "closed";
2885
+ if (stack.includes(closeTag)) {
2886
+ this.report("LIPS-P004", "warning", `</${closeTag}> auto-closes <${tag}>`, closeStart, this.pos - closeStart, `Add the missing </${tag}> before </${closeTag}>`);
2887
+ this.pos = closeStart;
2888
+ return "ancestor";
2889
+ }
2890
+ this.report("LIPS-P005", "error", `Stray closing tag </${closeTag}> — <${tag}> is open`, closeStart, this.pos - closeStart);
2891
+ return "stray";
2892
+ }
2893
+ parseAttrs(el) {
2894
+ while (true) {
2895
+ this.skipSpace();
2896
+ if (this.eof()) {
2897
+ this.report("LIPS-P001", "error", "Unexpected end of template inside tag", el.loc.offset);
2898
+ return;
2899
+ }
2900
+ if (this.startsWith("/>")) {
2901
+ this.pos += 2;
2902
+ el.selfClosed = true;
2903
+ return;
2904
+ }
2905
+ if (this.peek() === ">") {
2906
+ this.pos++;
2907
+ return;
2908
+ }
2909
+ const attrStart = this.pos;
2910
+ if (this.startsWith("...")) {
2911
+ this.pos += 3;
2912
+ const source = this.readUnquotedValue();
2913
+ el.attrs.push({ k: "spread", source, loc: { offset: attrStart, length: this.pos - attrStart } });
2914
+ continue;
2915
+ }
2916
+ if (this.peek() === "[") {
2917
+ this.pos++;
2918
+ const region = this.scanBalanced("]", "LIPS-P009");
2919
+ if (region) {
2920
+ const names = region.content.split(",").map((s) => s.trim()).filter(Boolean);
2921
+ el.attrs.push({ k: "args", names, loc: { offset: attrStart, length: this.pos - attrStart } });
2922
+ }
2923
+ continue;
2924
+ }
2925
+ let negated = false;
2926
+ if (this.peek() === "!") {
2927
+ negated = true;
2928
+ this.pos++;
2929
+ }
2930
+ const nameStart = this.pos;
2931
+ while (!this.eof() && /[^\s=/>()]/.test(this.peek()))
2932
+ this.pos++;
2933
+ const name = this.src.slice(nameStart, this.pos);
2934
+ if (!name) {
2935
+ this.report("LIPS-P009", "error", `Invalid attribute syntax at '${this.peek()}'`, this.pos);
2936
+ this.pos++;
2937
+ continue;
2938
+ }
2939
+ if (this.peek() === "(") {
2940
+ this.pos++;
2941
+ const region = this.scanBalanced(")", "LIPS-P010");
2942
+ const source = region ? region.content.trim() : "";
2943
+ const loc = { offset: attrStart, length: this.pos - attrStart };
2944
+ name.startsWith("on-") ? el.attrs.push({ k: "event", name: name.slice(3), source, loc }) : el.attrs.push({ k: "fn", name, source, loc });
2945
+ continue;
2946
+ }
2947
+ if (this.peek() === "=") {
2948
+ this.pos++;
2949
+ this.parseAttrValue(el, name, attrStart);
2950
+ continue;
2951
+ }
2952
+ el.attrs.push({ k: "bool", name, value: !negated, loc: { offset: attrStart, length: this.pos - attrStart } });
2953
+ }
2954
+ }
2955
+ parseAttrValue(el, name, attrStart) {
2956
+ const q = this.peek();
2957
+ if (q === '"' || q === "'") {
2958
+ this.pos++;
2959
+ const valueStart = this.pos;
2960
+ const parts = [];
2961
+ let buffer = "";
2962
+ while (!this.eof() && this.peek() !== q) {
2963
+ if (this.peek() === "{") {
2964
+ this.pos++;
2965
+ const region = this.scanBalanced("}", "LIPS-P007");
2966
+ if (region) {
2967
+ buffer && parts.push(buffer);
2968
+ buffer = "";
2969
+ parts.push({ expr: region.content.trim(), loc: region.loc });
2970
+ }
2971
+ continue;
2972
+ }
2973
+ buffer += this.peek();
2974
+ this.pos++;
2975
+ }
2976
+ buffer && parts.push(buffer);
2977
+ this.eof() ? this.report("LIPS-P010", "error", `Unterminated value for '${name}'`, valueStart, this.pos - valueStart) : this.pos++;
2978
+ const loc = { offset: attrStart, length: this.pos - attrStart };
2979
+ parts.some((p) => typeof p !== "string") ? el.attrs.push({ k: "interp", name, parts: parts.map((p) => typeof p === "string" ? decodeEntities(p) : p), loc }) : el.attrs.push({ k: "literal", name, value: decodeEntities(parts[0] ?? ""), loc });
2980
+ return;
2981
+ }
2982
+ if (q === "{") {
2983
+ this.pos++;
2984
+ const region = this.scanBalanced("}", "LIPS-P007");
2985
+ el.attrs.push({
2986
+ k: "expr",
2987
+ name,
2988
+ source: region ? region.content.trim() : "",
2989
+ loc: { offset: attrStart, length: this.pos - attrStart }
2990
+ });
2991
+ return;
2992
+ }
2993
+ const source = this.readUnquotedValue();
2994
+ source ? el.attrs.push({ k: "expr", name, source, loc: { offset: attrStart, length: this.pos - attrStart } }) : this.report("LIPS-P010", "error", `Missing value for attribute '${name}'`, attrStart);
2995
+ }
2996
+ readUnquotedValue() {
2997
+ const start = this.pos;
2998
+ let depth = 0;
2999
+ while (!this.eof()) {
3000
+ const c = this.peek();
3001
+ if (c === "'" || c === '"' || c === "`") {
3002
+ this.pos++;
3003
+ while (!this.eof() && this.peek() !== c) {
3004
+ if (this.peek() === "\\")
3005
+ this.pos++;
3006
+ this.pos++;
3007
+ }
3008
+ this.pos++;
3009
+ continue;
3010
+ }
3011
+ if (depth === 0) {
3012
+ if (/\s/.test(c) || c === ">")
3013
+ break;
3014
+ if (c === "/" && this.peek(1) === ">")
3015
+ break;
3016
+ }
3017
+ if (c === "(" || c === "[" || c === "{")
3018
+ depth++;
3019
+ else if (c === ")" || c === "]" || c === "}")
3020
+ depth--;
3021
+ this.pos++;
3022
+ }
3023
+ return this.src.slice(start, this.pos).trim();
3024
+ }
3025
+ }
3026
+ function parseTemplate(src) {
3027
+ return new TemplateParser(src || "").parse();
3028
+ }
3029
+ function parseSFC(src) {
3030
+ const splitAt = findTemplateStart(src || "");
3031
+ const script = (src || "").slice(0, splitAt).trimEnd();
3032
+ const templateSrc = (src || "").slice(splitAt);
3033
+ const result = new TemplateParser(templateSrc).parse();
3034
+ const lineOffset = script ? script.split(`
3035
+ `).length + (/\n\s*\n$/.test(src.slice(0, splitAt)) ? 1 : 0) : 0;
3036
+ result.diagnostics.forEach((d) => {
3037
+ d.loc.line += script ? src.slice(0, splitAt).split(`
3038
+ `).length - 1 : 0;
3039
+ d.loc.offset += splitAt;
3040
+ });
3041
+ return { script, ...result };
3042
+ }
3043
+ function findTemplateStart(src) {
3044
+ let depth = 0, lineStart = true;
3045
+ for (let i = 0;i < src.length; i++) {
3046
+ const c = src[i];
3047
+ if (c === "'" || c === '"' || c === "`") {
3048
+ const quote = c;
3049
+ i++;
3050
+ while (i < src.length && src[i] !== quote) {
3051
+ if (src[i] === "\\")
3052
+ i++;
3053
+ i++;
3054
+ }
3055
+ lineStart = false;
3056
+ continue;
3057
+ }
3058
+ if (c === "/" && src[i + 1] === "/") {
3059
+ while (i < src.length && src[i] !== `
3060
+ `)
3061
+ i++;
3062
+ lineStart = true;
3063
+ continue;
3064
+ }
3065
+ if (c === "/" && src[i + 1] === "*") {
3066
+ const end = src.indexOf("*/", i + 2);
3067
+ i = end === -1 ? src.length : end + 1;
3068
+ continue;
3069
+ }
3070
+ if (c === `
3071
+ `) {
3072
+ lineStart = true;
3073
+ continue;
3074
+ }
3075
+ if (lineStart && depth === 0 && c === "<" && /[A-Za-z{>!]/.test(src[i + 1] || ""))
3076
+ return i;
3077
+ if (c === "(" || c === "[" || c === "{")
3078
+ depth++;
3079
+ else if (c === ")" || c === "]" || c === "}")
3080
+ depth = Math.max(0, depth - 1);
3081
+ if (!/\s/.test(c))
3082
+ lineStart = false;
3083
+ }
3084
+ return 0;
3085
+ }
3086
+
3087
+ // src/ir/compiler.ts
3088
+ var ANCHOR = "<!--$-->";
3089
+ var CONTROL_TAGS = new Set(["if", "else-if", "else", "for", "switch", "async", "let", "const", "log"]);
3090
+ var ARM_TAGS = new Set(["case", "default", "then", "catch", "loading"]);
3091
+ var HTML_TAGS = new Set([
3092
+ "a",
3093
+ "abbr",
3094
+ "address",
3095
+ "area",
3096
+ "article",
3097
+ "aside",
3098
+ "audio",
3099
+ "b",
3100
+ "base",
3101
+ "bdi",
3102
+ "bdo",
3103
+ "blockquote",
3104
+ "body",
3105
+ "br",
3106
+ "button",
3107
+ "canvas",
3108
+ "caption",
3109
+ "cite",
3110
+ "code",
3111
+ "col",
3112
+ "colgroup",
3113
+ "data",
3114
+ "datalist",
3115
+ "dd",
3116
+ "del",
3117
+ "details",
3118
+ "dfn",
3119
+ "dialog",
3120
+ "div",
3121
+ "dl",
3122
+ "dt",
3123
+ "em",
3124
+ "embed",
3125
+ "fieldset",
3126
+ "figcaption",
3127
+ "figure",
3128
+ "footer",
3129
+ "form",
3130
+ "h1",
3131
+ "h2",
3132
+ "h3",
3133
+ "h4",
3134
+ "h5",
3135
+ "h6",
3136
+ "head",
3137
+ "header",
3138
+ "hgroup",
3139
+ "hr",
3140
+ "html",
3141
+ "i",
3142
+ "iframe",
3143
+ "img",
3144
+ "input",
3145
+ "ins",
3146
+ "kbd",
3147
+ "label",
3148
+ "legend",
3149
+ "li",
3150
+ "link",
3151
+ "main",
3152
+ "map",
3153
+ "mark",
3154
+ "menu",
3155
+ "meta",
3156
+ "meter",
3157
+ "nav",
3158
+ "noscript",
3159
+ "object",
3160
+ "ol",
3161
+ "optgroup",
3162
+ "option",
3163
+ "output",
3164
+ "p",
3165
+ "picture",
3166
+ "pre",
3167
+ "progress",
3168
+ "q",
3169
+ "rp",
3170
+ "rt",
3171
+ "ruby",
3172
+ "s",
3173
+ "samp",
3174
+ "script",
3175
+ "section",
3176
+ "select",
3177
+ "slot",
3178
+ "small",
3179
+ "source",
3180
+ "span",
3181
+ "strong",
3182
+ "style",
3183
+ "sub",
3184
+ "summary",
3185
+ "sup",
3186
+ "table",
3187
+ "tbody",
3188
+ "td",
3189
+ "template",
3190
+ "textarea",
3191
+ "tfoot",
3192
+ "th",
3193
+ "thead",
3194
+ "time",
3195
+ "title",
3196
+ "tr",
3197
+ "track",
3198
+ "u",
3199
+ "ul",
3200
+ "var",
3201
+ "video",
3202
+ "wbr",
3203
+ "svg",
3204
+ "circle",
3205
+ "clippath",
3206
+ "defs",
3207
+ "ellipse",
3208
+ "foreignobject",
3209
+ "g",
3210
+ "image",
3211
+ "line",
3212
+ "lineargradient",
3213
+ "marker",
3214
+ "mask",
3215
+ "path",
3216
+ "pattern",
3217
+ "polygon",
3218
+ "polyline",
3219
+ "radialgradient",
3220
+ "rect",
3221
+ "stop",
3222
+ "symbol",
3223
+ "text",
3224
+ "tspan",
3225
+ "use"
3226
+ ]);
3227
+ var VOID_ELEMENTS2 = new Set([
3228
+ "area",
3229
+ "base",
3230
+ "br",
3231
+ "col",
3232
+ "embed",
3233
+ "hr",
3234
+ "img",
3235
+ "input",
3236
+ "link",
3237
+ "meta",
3238
+ "param",
3239
+ "source",
3240
+ "track",
3241
+ "wbr"
3242
+ ]);
3243
+ var escText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3244
+ var escAttr = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
3245
+ var isNumeric = (s) => s !== "" && !isNaN(Number(s));
3246
+
3247
+ class Compiler {
3248
+ src;
3249
+ macros;
3250
+ exprs = [];
3251
+ exprIndex = new Map;
3252
+ lineStarts = null;
3253
+ macroStack = [];
3254
+ diagnostics = [];
3255
+ constructor(src, macros = new Map) {
3256
+ this.src = src;
3257
+ this.macros = macros;
3258
+ }
3259
+ locate(offset) {
3260
+ if (!this.lineStarts) {
3261
+ this.lineStarts = [0];
3262
+ for (let i = 0;i < this.src.length; i++)
3263
+ if (this.src[i] === `
3264
+ `)
3265
+ this.lineStarts.push(i + 1);
3266
+ }
3267
+ let lo = 0, hi = this.lineStarts.length - 1;
3268
+ while (lo < hi) {
3269
+ const mid = lo + hi + 1 >> 1;
3270
+ this.lineStarts[mid] <= offset ? lo = mid : hi = mid - 1;
3271
+ }
3272
+ return { line: lo + 1, col: offset - this.lineStarts[lo] + 1 };
3273
+ }
3274
+ report(code, severity, message, offset, length2 = 1, hint) {
3275
+ const { line: line2, col } = this.locate(offset);
3276
+ this.diagnostics.push({ code, severity, message, hint, loc: { line: line2, col, offset, length: length2 } });
3277
+ }
3278
+ expr(source, at) {
3279
+ const cached = this.exprIndex.get(source);
3280
+ if (cached !== undefined)
3281
+ return cached;
3282
+ const { diagnostics } = parseExpression(source);
3283
+ for (const d of diagnostics) {
3284
+ const offset = (at?.offset ?? 0) + d.loc.offset;
3285
+ this.report(d.code, "error", d.message, offset, d.loc.length);
3286
+ }
3287
+ const idx = this.exprs.length;
3288
+ this.exprs.push(source);
3289
+ this.exprIndex.set(source, idx);
3290
+ return idx;
3291
+ }
3292
+ synth(source) {
3293
+ const cached = this.exprIndex.get(source);
3294
+ if (cached !== undefined)
3295
+ return cached;
3296
+ const idx = this.exprs.length;
3297
+ this.exprs.push(source);
3298
+ this.exprIndex.set(source, idx);
3299
+ return idx;
3300
+ }
3301
+ concat(parts) {
3302
+ parts.filter((p) => typeof p !== "string").forEach((p) => {
3303
+ const { diagnostics } = parseExpression(p.expr);
3304
+ for (const d of diagnostics)
3305
+ this.report(d.code, "error", d.message, p.loc.offset + d.loc.offset, d.loc.length);
3306
+ });
3307
+ const source = parts.map((p) => typeof p === "string" ? JSON.stringify(p) : `((${p.expr})??"")`).join("+");
3308
+ return this.synth(source);
3309
+ }
3310
+ compInput(attr) {
3311
+ switch (attr.k) {
3312
+ case "literal":
3313
+ return { lit: attr.value };
3314
+ case "bool":
3315
+ return { lit: attr.value };
3316
+ case "expr":
3317
+ return { e: this.expr(attr.source, attr.loc) };
3318
+ case "interp":
3319
+ return { e: this.concat(attr.parts) };
3320
+ }
3321
+ }
3322
+ compile(children) {
3323
+ return { v: 1, exprs: this.exprs, root: this.block(children, []) };
3324
+ }
3325
+ block(children, scope) {
3326
+ const block = { html: "", scope: [...scope], binds: [], blocks: [] };
3327
+ const html = [];
3328
+ const emitSiblings = (nodes, path, i18nParent = false) => {
3329
+ let index = 0;
3330
+ let lastWasText = false;
3331
+ const anchor = () => {
3332
+ html.push(ANCHOR);
3333
+ lastWasText = false;
3334
+ return [...path, index++];
3335
+ };
3336
+ for (let i = 0;i < nodes.length; i++) {
3337
+ const node2 = nodes[i];
3338
+ switch (node2.t) {
3339
+ case "text": {
3340
+ if (i18nParent) {
3341
+ block.binds.push({ t: "text", p: anchor(), e: this.synth(JSON.stringify(node2.value)), i18n: 1 });
3342
+ break;
3343
+ }
3344
+ html.push(escText(node2.value));
3345
+ if (!lastWasText)
3346
+ index++;
3347
+ lastWasText = true;
3348
+ break;
3349
+ }
3350
+ case "comment": {
3351
+ html.push(`<!--${node2.value.replace(/--/g, "- -")}-->`);
3352
+ lastWasText = false;
3353
+ index++;
3354
+ break;
3355
+ }
3356
+ case "interp": {
3357
+ const bind = { t: "text", p: anchor(), e: this.concat(node2.parts) };
3358
+ if (i18nParent)
3359
+ bind.i18n = 1;
3360
+ block.binds.push(bind);
3361
+ break;
3362
+ }
3363
+ case "fragment": {
3364
+ nodes = [...nodes.slice(0, i), ...node2.children, ...nodes.slice(i + 1)];
3365
+ i--;
3366
+ break;
3367
+ }
3368
+ case "element": {
3369
+ if (CONTROL_TAGS.has(node2.tag)) {
3370
+ this.controlBlock(node2, nodes, i, anchor(), block, scope);
3371
+ if (node2.tag === "if") {
3372
+ let j = i + 1;
3373
+ while (j < nodes.length) {
3374
+ const sib = nodes[j];
3375
+ if (sib.t === "element" && (sib.tag === "else-if" || sib.tag === "else"))
3376
+ j++;
3377
+ else
3378
+ break;
3379
+ }
3380
+ nodes = [...nodes.slice(0, i + 1), ...nodes.slice(j)];
3381
+ }
3382
+ break;
3383
+ }
3384
+ if (ARM_TAGS.has(node2.tag)) {
3385
+ this.report("LIPS-C002", "error", `<${node2.tag}> is only valid inside its parent construct`, node2.loc.offset, node2.loc.length);
3386
+ break;
3387
+ }
3388
+ if (node2.tag === "#dynamic") {
3389
+ block.blocks.push(this.compLike(node2, anchor(), scope, "dynamic"));
3390
+ break;
3391
+ }
3392
+ if (this.macros.has(node2.tag)) {
3393
+ const macroBlock = this.macroCall(node2, anchor(), scope);
3394
+ macroBlock && block.blocks.push(macroBlock);
3395
+ break;
3396
+ }
3397
+ if (!HTML_TAGS.has(node2.tag)) {
3398
+ block.blocks.push(this.compLike(node2, anchor(), scope, "comp"));
3399
+ break;
3400
+ }
3401
+ this.emitElement(node2, path, index++, html, block, emitSiblings);
3402
+ lastWasText = false;
3403
+ break;
3404
+ }
3405
+ }
3406
+ }
3407
+ };
3408
+ emitSiblings(children, []);
3409
+ block.html = html.join("");
3410
+ return block;
3411
+ }
3412
+ emitElement(node2, path, index, html, block, emitSiblings) {
3413
+ const p = [...path, index];
3414
+ let open = `<${node2.tag}`;
3415
+ const i18n = node2.attrs.some((a) => a.k === "bool" && a.name === "i18n" && a.value);
3416
+ const translatableAttr = (name) => i18n && (name === "title" || name === "placeholder");
3417
+ for (const attr of node2.attrs) {
3418
+ switch (attr.k) {
3419
+ case "literal":
3420
+ if (attr.name === "@format") {
3421
+ block.binds.push(this.formatBind(p, attr));
3422
+ break;
3423
+ }
3424
+ if (attr.name.startsWith("@")) {
3425
+ block.binds.push({ t: "prop", p, name: attr.name.slice(1), e: this.synth(JSON.stringify(attr.value)) });
3426
+ break;
3427
+ }
3428
+ if (translatableAttr(attr.name)) {
3429
+ block.binds.push({ t: "attr", p, name: attr.name, e: this.synth(JSON.stringify(attr.value)), i18n: 1 });
3430
+ break;
3431
+ }
3432
+ open += ` ${attr.name}="${escAttr(attr.value)}"`;
3433
+ break;
3434
+ case "bool":
3435
+ attr.name !== "i18n" && attr.value && (open += ` ${attr.name}`);
3436
+ break;
3437
+ case "expr": {
3438
+ if (attr.name === "@format") {
3439
+ block.binds.push(this.formatBind(p, attr));
3440
+ break;
3441
+ }
3442
+ if (attr.name.startsWith("@")) {
3443
+ block.binds.push({ t: "prop", p, name: attr.name.slice(1), e: this.expr(attr.source, attr.loc) });
3444
+ break;
3445
+ }
3446
+ const bind = { t: "attr", p, name: attr.name, e: this.expr(attr.source, attr.loc) };
3447
+ if (translatableAttr(attr.name))
3448
+ bind.i18n = 1;
3449
+ block.binds.push(bind);
3450
+ break;
3451
+ }
3452
+ case "interp": {
3453
+ if (attr.name === "@format") {
3454
+ block.binds.push(this.formatBind(p, attr));
3455
+ break;
3456
+ }
3457
+ const bind = { t: "attr", p, name: attr.name, e: this.concat(attr.parts) };
3458
+ if (translatableAttr(attr.name))
3459
+ bind.i18n = 1;
3460
+ block.binds.push(bind);
3461
+ break;
3462
+ }
3463
+ case "event":
3464
+ block.binds.push({ t: "event", p, name: attr.name, e: this.synth(attr.source) });
3465
+ break;
3466
+ case "spread":
3467
+ block.binds.push({ t: "spread", p, e: this.expr(attr.source, attr.loc) });
3468
+ break;
3469
+ case "fn":
3470
+ this.report("LIPS-C007", "warning", `Callable attribute '${attr.name}(…)' has no meaning on <${node2.tag}>`, attr.loc.offset, attr.loc.length);
3471
+ break;
3472
+ case "args":
3473
+ this.report("LIPS-C008", "warning", `Iterator arguments are not applicable to <${node2.tag}>`, attr.loc.offset, attr.loc.length);
3474
+ break;
3475
+ }
3476
+ }
3477
+ if (VOID_ELEMENTS2.has(node2.tag)) {
3478
+ html.push(open + ">");
3479
+ return;
3480
+ }
3481
+ html.push(open + ">");
3482
+ node2.children.length && emitSiblings(node2.children, p, i18n);
3483
+ html.push(`</${node2.tag}>`);
3484
+ }
3485
+ formatBind(p, attr) {
3486
+ const raw = attr.k === "literal" ? attr.value : attr.k === "expr" ? attr.source : attr.parts.map((part) => typeof part === "string" ? part : `{${part.expr}}`).join("");
3487
+ const comma = raw.indexOf(",");
3488
+ if (comma === -1) {
3489
+ this.report("LIPS-C012", "error", `@format expects "reference, { params }"`, attr.loc.offset, attr.loc.length);
3490
+ return { t: "prop", p, name: "format", e: this.synth("({})"), ref: raw.trim() };
3491
+ }
3492
+ const ref = raw.slice(0, comma).trim(), params = raw.slice(comma + 1).trim();
3493
+ return { t: "prop", p, name: "format", e: this.expr(params, attr.loc), ref };
3494
+ }
3495
+ attrsOf(node2) {
3496
+ const byName = new Map, args = [];
3497
+ for (const attr of node2.attrs) {
3498
+ if (attr.k === "args")
3499
+ args.push(...attr.names);
3500
+ else if ("name" in attr)
3501
+ byName.set(attr.name, attr);
3502
+ }
3503
+ return { byName, args };
3504
+ }
3505
+ controlBlock(node2, siblings, i, p, block, scope) {
3506
+ switch (node2.tag) {
3507
+ case "if": {
3508
+ const branches = [{
3509
+ when: node2.head ? this.expr(node2.head.expr, node2.head.loc) : this.missingHead(node2),
3510
+ block: this.block(node2.children, scope)
3511
+ }];
3512
+ for (let j = i + 1;j < siblings.length; j++) {
3513
+ const sib = siblings[j];
3514
+ if (sib.t !== "element")
3515
+ break;
3516
+ if (sib.tag === "else-if")
3517
+ branches.push({
3518
+ when: sib.head ? this.expr(sib.head.expr, sib.head.loc) : this.missingHead(sib),
3519
+ block: this.block(sib.children, scope)
3520
+ });
3521
+ else if (sib.tag === "else") {
3522
+ branches.push({ when: null, block: this.block(sib.children, scope) });
3523
+ break;
3524
+ } else
3525
+ break;
3526
+ }
3527
+ block.blocks.push({ t: "if", p, branches });
3528
+ break;
3529
+ }
3530
+ case "else-if":
3531
+ case "else":
3532
+ this.report("LIPS-C001", "error", `<${node2.tag}> without a preceding <if>`, node2.loc.offset, node2.loc.length);
3533
+ break;
3534
+ case "for": {
3535
+ const { byName, args } = this.attrsOf(node2);
3536
+ const inAttr = byName.get("in"), fromAttr = byName.get("from"), toAttr = byName.get("to"), byAttr = byName.get("by");
3537
+ if (!inAttr && !fromAttr) {
3538
+ this.report("LIPS-C004", "error", `<for> requires 'in' or 'from'/'to'`, node2.loc.offset, node2.loc.length);
3539
+ break;
3540
+ }
3541
+ const child = {
3542
+ t: "for",
3543
+ p,
3544
+ args,
3545
+ block: this.block(node2.children, [...scope, ...args])
3546
+ };
3547
+ if (inAttr && inAttr.k === "expr")
3548
+ child.of = this.expr(inAttr.source, inAttr.loc);
3549
+ if (fromAttr)
3550
+ child.from = this.numInput(fromAttr);
3551
+ if (toAttr)
3552
+ child.to = this.numInput(toAttr);
3553
+ if (byAttr && (byAttr.k === "literal" || byAttr.k === "expr"))
3554
+ child.by = byAttr.k === "literal" ? { lit: byAttr.value } : { e: this.expr(byAttr.source, byAttr.loc) };
3555
+ block.blocks.push(child);
3556
+ break;
3557
+ }
3558
+ case "switch": {
3559
+ const on = node2.head ? this.expr(node2.head.expr, node2.head.loc) : this.missingHead(node2);
3560
+ const cases = [];
3561
+ for (const child of node2.children) {
3562
+ if (child.t !== "element")
3563
+ continue;
3564
+ if (child.tag === "case") {
3565
+ const { byName } = this.attrsOf(child);
3566
+ const isAttr = byName.get("is");
3567
+ if (!isAttr || isAttr.k !== "literal" && isAttr.k !== "expr") {
3568
+ this.report("LIPS-C004", "error", `<case> requires an 'is' attribute`, child.loc.offset, child.loc.length);
3569
+ continue;
3570
+ }
3571
+ cases.push({
3572
+ is: isAttr.k === "literal" ? { lit: isAttr.value } : { e: this.expr(isAttr.source, isAttr.loc) },
3573
+ block: this.block(child.children, scope)
3574
+ });
3575
+ } else if (child.tag === "default")
3576
+ cases.push({ is: null, block: this.block(child.children, scope) });
3577
+ else
3578
+ this.report("LIPS-C003", "error", `Only <case>/<default> are valid inside <switch>`, child.loc.offset, child.loc.length);
3579
+ }
3580
+ block.blocks.push({ t: "switch", p, on, cases });
3581
+ break;
3582
+ }
3583
+ case "async": {
3584
+ const awaitAttr = node2.attrs.find((a) => a.k === "fn" && a.name === "await");
3585
+ if (!awaitAttr) {
3586
+ this.report("LIPS-C004", "error", `<async> requires await(…)`, node2.loc.offset, node2.loc.length);
3587
+ break;
3588
+ }
3589
+ const child = { t: "async", p, awaitE: this.expr(awaitAttr.source, awaitAttr.loc) };
3590
+ for (const arm of node2.children) {
3591
+ if (arm.t !== "element")
3592
+ continue;
3593
+ const { args } = this.attrsOf(arm);
3594
+ if (arm.tag === "then")
3595
+ child.then = { args, block: this.block(arm.children, [...scope, ...args]) };
3596
+ else if (arm.tag === "catch")
3597
+ child.catch = { args, block: this.block(arm.children, [...scope, ...args]) };
3598
+ else if (arm.tag === "loading")
3599
+ child.loading = this.block(arm.children, scope);
3600
+ else
3601
+ this.report("LIPS-C003", "error", `Only <then>/<catch>/<loading> are valid inside <async>`, arm.loc.offset, arm.loc.length);
3602
+ }
3603
+ block.blocks.push(child);
3604
+ break;
3605
+ }
3606
+ case "let":
3607
+ case "const": {
3608
+ const vars = {};
3609
+ for (const attr of node2.attrs)
3610
+ if (attr.k === "literal" || attr.k === "expr" || attr.k === "interp" || attr.k === "bool") {
3611
+ vars[attr.name] = this.compInput(attr);
3612
+ !block.scope.includes(attr.name) && block.scope.push(attr.name);
3613
+ !scope.includes(attr.name) && scope.push(attr.name);
3614
+ }
3615
+ block.blocks.push({ t: "let", p, const: node2.tag === "const", vars });
3616
+ break;
3617
+ }
3618
+ case "log":
3619
+ block.blocks.push({ t: "log", p, e: node2.head ? this.synth(node2.head.expr) : this.missingHead(node2) });
3620
+ break;
3621
+ }
3622
+ }
3623
+ missingHead(node2) {
3624
+ this.report("LIPS-C004", "error", `<${node2.tag}> requires a head expression: <${node2.tag}( … )>`, node2.loc.offset, node2.loc.length);
3625
+ return this.synth("undefined");
3626
+ }
3627
+ numInput(attr) {
3628
+ if (attr.k === "literal")
3629
+ return { lit: isNumeric(attr.value) ? Number(attr.value) : attr.value };
3630
+ if (attr.k === "expr")
3631
+ return isNumeric(attr.source) ? { lit: Number(attr.source) } : { e: this.expr(attr.source, attr.loc) };
3632
+ return { lit: undefined };
3633
+ }
3634
+ macroCall(node2, p, scope) {
3635
+ const macro = this.macros.get(node2.tag);
3636
+ if (this.macroStack.includes(macro.name)) {
3637
+ this.report("LIPS-C009", "error", `Recursive macro <${macro.name}> (${[...this.macroStack, macro.name].join(" → ")})`, node2.loc.offset, node2.loc.length);
3638
+ return null;
3639
+ }
3640
+ const vars = {};
3641
+ for (const attr of node2.attrs)
3642
+ if (attr.k === "literal" || attr.k === "expr" || attr.k === "interp" || attr.k === "bool")
3643
+ vars[attr.name] = this.compInput(attr);
3644
+ for (const name of macro.argv)
3645
+ if (!(name in vars))
3646
+ vars[name] = { lit: undefined };
3647
+ this.macroStack.push(macro.name);
3648
+ const block = this.block(macro.children, [...scope, ...macro.argv]);
3649
+ this.macroStack.pop();
3650
+ return { t: "macro", p, name: macro.name, vars, args: macro.argv, block };
3651
+ }
3652
+ compLike(node2, p, scope, kind) {
3653
+ const inputs = {}, spreads = [], events = [];
3654
+ let args = [];
3655
+ for (const attr of node2.attrs) {
3656
+ switch (attr.k) {
3657
+ case "literal":
3658
+ case "bool":
3659
+ case "expr":
3660
+ case "interp":
3661
+ inputs[attr.name] = this.compInput(attr);
3662
+ break;
3663
+ case "event":
3664
+ events.push({ name: attr.name, e: this.synth(attr.source) });
3665
+ break;
3666
+ case "spread":
3667
+ spreads.push(this.expr(attr.source, attr.loc));
3668
+ break;
3669
+ case "args":
3670
+ args = [...args, ...attr.names];
3671
+ break;
3672
+ case "fn":
3673
+ inputs[attr.name] = { e: this.expr(attr.source, attr.loc) };
3674
+ break;
3675
+ }
3676
+ }
3677
+ const contents = node2.children.length ? { args, block: this.block(node2.children, [...scope, ...args]) } : undefined;
3678
+ return kind === "comp" ? { t: "comp", p, name: node2.tag, inputs, spreads, events, contents } : { t: "dynamic", p, tag: this.expr(node2.dynamicTag.expr, node2.dynamicTag.loc), inputs, spreads, events, contents };
3679
+ }
3680
+ }
3681
+ function parseMacros(src, diagnostics) {
3682
+ const macros = new Map;
3683
+ if (!src?.trim())
3684
+ return macros;
3685
+ const parsed = parseTemplate(src);
3686
+ diagnostics.push(...parsed.diagnostics);
3687
+ for (const node2 of parsed.root.children) {
3688
+ if (node2.t !== "element")
3689
+ continue;
3690
+ if (node2.tag !== "macro") {
3691
+ diagnostics.push({
3692
+ code: "LIPS-C010",
3693
+ severity: "warning",
3694
+ message: `Only <macro> definitions are allowed in the macros source — ignoring <${node2.tag}>`,
3695
+ loc: { line: 1, col: 1, offset: node2.loc.offset, length: node2.loc.length }
3696
+ });
3697
+ continue;
3698
+ }
3699
+ let name = "";
3700
+ const argv = [];
3701
+ for (const attr of node2.attrs) {
3702
+ if (attr.k === "args")
3703
+ argv.push(...attr.names);
3704
+ else if (attr.k === "literal" && attr.name === "name")
3705
+ name = attr.value;
3706
+ }
3707
+ if (!name) {
3708
+ diagnostics.push({
3709
+ code: "LIPS-C011",
3710
+ severity: "error",
3711
+ message: `<macro> requires a name attribute`,
3712
+ loc: { line: 1, col: 1, offset: node2.loc.offset, length: node2.loc.length }
3713
+ });
3714
+ continue;
3715
+ }
3716
+ macros.set(name.toLowerCase(), { name, argv, children: node2.children });
3717
+ }
3718
+ return macros;
3719
+ }
3720
+ function compileTemplate(src, options) {
3721
+ const diagnostics = [];
3722
+ const macros = parseMacros(options?.macros || "", diagnostics);
3723
+ const parsed = parseTemplate(src);
3724
+ const compiler = new Compiler(src, macros);
3725
+ const ir = compiler.compile(parsed.root.children);
3726
+ return { ir, diagnostics: [...diagnostics, ...parsed.diagnostics, ...compiler.diagnostics] };
3727
+ }
3728
+
3729
+ // src/ir/router.ts
3730
+ function safeDecode(value) {
3731
+ try {
3732
+ return decodeURIComponent(value);
3733
+ } catch (e) {
3734
+ return value;
3735
+ }
3736
+ }
3737
+ var parseQuery = (str) => Object.fromEntries(new URLSearchParams(str));
3738
+ var routerTemplate = {
3739
+ state: {
3740
+ page: null,
3741
+ params: {},
3742
+ query: {}
3743
+ },
3744
+ handler: {
3745
+ onCreate() {
3746
+ this.__routes = [];
3747
+ this.__defaultPath = null;
3748
+ this.__currentRoute = null;
3749
+ this.__global = false;
3750
+ },
3751
+ onInput() {
3752
+ this.processor(this.input);
3753
+ },
3754
+ processor(options) {
3755
+ if (!options?.routes)
3756
+ return;
3757
+ if (options.global)
3758
+ this.__global = true;
3759
+ this.__routes = options.routes.map(({ path, template, default: _default }) => {
3760
+ if (_default)
3761
+ this.__defaultPath = path;
3762
+ const pathVars = path.match(/:[^\/]*(\/|$)/gi) || [], pathRegex = path.replaceAll("/", "\\/").replaceAll(/:[^\/]*(\/|$)/gi, "([^\\/]+)(?:\\/|$)");
3763
+ return { path, template, default: _default, pathVars, pathRegex: new RegExp(`${pathRegex}$`, "i") };
3764
+ });
3765
+ if (options.global) {
3766
+ const cpathname = window.location.pathname;
3767
+ this.__defaultPath = this.__defaultPath && cpathname === "/" && cpathname !== this.__defaultPath ? this.__defaultPath : cpathname ? cpathname + window.location.search : this.__routes[0]?.path;
3768
+ }
3769
+ },
3770
+ onAttach() {
3771
+ if (this.input?.global) {
3772
+ window.navigate = this.navigate.bind(this);
3773
+ window.addEventListener("popstate", (e) => e.state && this.navigate(e.state.path, true));
3774
+ }
3775
+ typeof this.setContext === "function" && this.setContext("navigate", this.navigate.bind(this));
3776
+ this.__defaultPath && this.navigate(this.__defaultPath);
3777
+ },
3778
+ navigate(path, back) {
3779
+ !back && this.__global && history.pushState({ path }, "", path);
3780
+ const parts = String(path).split("?");
3781
+ path = parts[0];
3782
+ const query = parts[1] ? parseQuery(parts[1]) : {};
3783
+ let fromState = null;
3784
+ if (this.__currentRoute) {
3785
+ fromState = { path: this.__currentRoute.path, params: this.state.params };
3786
+ this.emit("before", { fromState, toState: { path, query } });
3787
+ }
3788
+ const result = this.match(path);
3789
+ if (!result) {
3790
+ this.__currentRoute = null;
3791
+ this.state.params = {};
3792
+ this.state.query = {};
3793
+ this.state.page = null;
3794
+ this.emit("not-found", path);
3795
+ return;
3796
+ }
3797
+ const { route, params } = result;
3798
+ this.emit("after", { fromState, toState: { path: route.path, params, query } });
3799
+ this.__currentRoute = route;
3800
+ this.state.params = params;
3801
+ this.state.query = query;
3802
+ this.state.page = route.template;
3803
+ },
3804
+ match(path) {
3805
+ const params = {};
3806
+ for (const route of this.__routes) {
3807
+ const matches = path.match(route.pathRegex);
3808
+ if (matches === null || matches.index !== 0)
3809
+ continue;
3810
+ for (let x = 0;x + 1 < matches.length && x < route.pathVars.length; x++)
3811
+ params[route.pathVars[x].replaceAll(/[\/:]/g, "")] = safeDecode(matches[x + 1]);
3812
+ return { route, params };
3813
+ }
3814
+ return false;
3815
+ }
3816
+ },
3817
+ default: `<{state.page} params=state.params query=state.query/>`
3818
+ };
3819
+ // src/lips.ts
3820
+ setCompiler(compileTemplate);
3821
+ setStyleCompiler((css) => serialize(compile(css), middleware([stringify])));
3822
+ registerBuiltin("router", routerTemplate);
3823
+ var lips_default = IRLips;
3824
+ export {
3825
+ untrack,
3826
+ signal,
3827
+ renderIR,
3828
+ reactive,
3829
+ parseTemplate,
3830
+ parseSFC,
3831
+ effect,
3832
+ lips_default as default,
3833
+ compileTemplate
3834
+ };
3835
+
3836
+ //# debugId=F41B6717B2FD658E64756E2164756E21