@slim-lang/core 1.2.11 → 1.2.13

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 (48) hide show
  1. package/README.md +522 -14
  2. package/package.json +2 -6
  3. package/packages/slim/server/main.slim +433 -422
  4. package/run-dev-slim.js +10 -5
  5. package/run-slim.js +10 -20
  6. package/src/bin/api/github_get.js +7 -12
  7. package/src/bin/api/github_req.js +54 -241
  8. package/src/bin/api/lock.js +2 -1
  9. package/src/bin/api/spm.js +20 -91
  10. package/src/bin/cli.js +73 -102
  11. package/src/bin/config.default.json +11 -11
  12. package/src/bin/helpers.js +2 -7
  13. package/src/bin/spm.js +3 -7
  14. package/src/checker.js +1705 -388
  15. package/src/compile.js +131 -100
  16. package/src/external/classErrors.js +5 -6
  17. package/src/external/client.js +0 -2
  18. package/src/external/core.js +355 -237
  19. package/src/external/defaults.js +12 -4
  20. package/src/external/dom.js +663 -0
  21. package/src/external/helpers.js +87 -58
  22. package/src/external/reactive.js +601 -0
  23. package/src/external/router.js +117 -0
  24. package/src/external/slim-globals.d.ts +43 -4
  25. package/src/external/typeSyntax.js +258 -0
  26. package/src/external/types.js +1 -1
  27. package/src/format.js +183 -12
  28. package/src/handlers/errorHandler.js +9 -36
  29. package/src/jsdoc.js +36 -16
  30. package/src/modulePaths.js +15 -5
  31. package/src/reactivity.js +774 -0
  32. package/src/repl.js +1 -1
  33. package/src/suggest.js +60 -0
  34. package/src/syntax/babel.js +46 -0
  35. package/src/syntax/index.js +39 -0
  36. package/src/syntax/lower.js +666 -0
  37. package/src/syntax/markup.js +195 -0
  38. package/src/syntax/plugin.js +903 -0
  39. package/src/syntax/types.js +106 -0
  40. package/src/test-runner.js +5 -5
  41. package/src/transform.js +209 -244
  42. package/packages/slim/helpers/string.js +0 -43
  43. package/packages/slim/types/hash.js +0 -11
  44. package/src/handlers/parser/components.js +0 -295
  45. package/src/handlers/parserHandler.js +0 -789
  46. package/src/lexer.js +0 -174
  47. package/src/parser.js +0 -803
  48. package/src/sourcemap.js +0 -0
@@ -1,25 +1,5 @@
1
- import { parseHTML } from "linkedom";
2
1
  import { CLIENT_RUNTIME } from "./client.js";
3
-
4
- export function getFunctionBody(fn) {
5
- const str = fn.toString();
6
- return str.substring(str.indexOf('{') + 1, str.lastIndexOf('}')).trim();
7
- }
8
-
9
- export const idify = (text) => {
10
- if (!text) return '';
11
-
12
- return btoa(text + Math.random(100 * 9999) * 100)
13
- .toString()
14
- .trim()
15
- .toLowerCase()
16
- .normalize('NFD')
17
- .replace(/[\u0300-\u036f]/g, '')
18
- .replace(/[^a-z0-9\s-]/g, '')
19
- .replace(/[\s_-]+/g, '-')
20
- .replace(/^-+|-+$/g, '');
21
- };
22
-
2
+ import { Signal } from "./reactive.js";
23
3
 
24
4
  const VOID_ELEMENTS = new Set([
25
5
  "area", "base", "br", "col", "embed", "hr", "img", "input",
@@ -27,15 +7,46 @@ const VOID_ELEMENTS = new Set([
27
7
  ]);
28
8
 
29
9
  const RAW_TEXT_ELEMENTS = new Set(["script", "style", "textarea", "title"]);
10
+ const UNESCAPED_TEXT_ELEMENTS = new Set(["script", "style"]);
11
+
12
+ const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
13
+ const NAMED_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00a0" };
14
+
15
+ export function escapeHtml(value) {
16
+ return String(value).replace(/[&<>"']/g, ch => ESCAPES[ch]);
17
+ }
18
+
19
+ export function decodeEntities(text) {
20
+ if (!text.includes("&")) return text;
21
+ return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, entity) => {
22
+ if (entity[0] !== "#") return NAMED_ENTITIES[entity.toLowerCase()] ?? match;
23
+ const code = entity[1] === "x" || entity[1] === "X"
24
+ ? parseInt(entity.slice(2), 16)
25
+ : parseInt(entity.slice(1), 10);
26
+ return code <= 0x10ffff ? String.fromCodePoint(code) : match;
27
+ });
28
+ }
29
+
30
+ export class SafeHtml {
31
+ constructor(value) {
32
+ this.value = value;
33
+ }
34
+ toString() {
35
+ return this.value;
36
+ }
37
+ }
38
+
39
+ export function raw(html) {
40
+ return html instanceof SafeHtml ? html : new SafeHtml(html == null ? "" : String(html));
41
+ }
30
42
 
31
- // Use the platform DOM or detached linkedom nodes; static import supports bundler stubs.
32
43
  const hasNativeDom =
33
44
  typeof globalThis.document !== "undefined" &&
34
45
  typeof globalThis.HTMLElement !== "undefined";
35
46
 
36
47
  const { document: slimDocument, HTMLElement } = hasNativeDom
37
48
  ? globalThis
38
- : parseHTML("<!doctype html><html><head></head><body></body></html>");
49
+ : (await import("linkedom")).parseHTML("<!doctype html><html><head></head><body></body></html>");
39
50
 
40
51
  export { slimDocument, HTMLElement };
41
52
 
@@ -108,7 +119,7 @@ function parseAttributes(html, i) {
108
119
  while (i < len && !isSpace(html[i]) && html[i] !== ">" && !(html[i] === "/" && html[i + 1] === ">")) i++;
109
120
  value = html.slice(start, i);
110
121
  }
111
- attrs[name] = value;
122
+ attrs[name] = decodeEntities(value);
112
123
  } else {
113
124
  attrs[name] = true;
114
125
  }
@@ -117,6 +128,10 @@ function parseAttributes(html, i) {
117
128
  return { attrs, selfClosing, end: i };
118
129
  }
119
130
 
131
+ export function parseAttributeList(text) {
132
+ return parseAttributes(text + ">", 0).attrs;
133
+ }
134
+
120
135
  function findRawClose(html, lower, from, tag) {
121
136
  const needle = "</" + tag;
122
137
  let idx = from;
@@ -182,8 +197,8 @@ function parseNodes(html) {
182
197
  if (!selfClosing && !VOID_ELEMENTS.has(tag)) {
183
198
  if (RAW_TEXT_ELEMENTS.has(tag)) {
184
199
  const { contentEnd, next } = findRawClose(html, lower, i, tag);
185
- const raw = html.slice(i, contentEnd);
186
- if (raw) el.children.push(textNode(raw));
200
+ const content = html.slice(i, contentEnd);
201
+ if (content) el.children.push(textNode(UNESCAPED_TEXT_ELEMENTS.has(tag) ? content : decodeEntities(content)));
187
202
  i = next;
188
203
  } else {
189
204
  stack.push(el);
@@ -199,7 +214,7 @@ function parseNodes(html) {
199
214
 
200
215
  const nextLt = html.indexOf("<", i);
201
216
  const end = nextLt === -1 ? len : nextLt;
202
- top().children.push(textNode(html.slice(i, end)));
217
+ top().children.push(textNode(decodeEntities(html.slice(i, end))));
203
218
  i = end;
204
219
  }
205
220
 
@@ -207,7 +222,7 @@ function parseNodes(html) {
207
222
  }
208
223
 
209
224
  function escapeAttribute(value) {
210
- return String(value).replace(/"/g, "&quot;");
225
+ return String(value).replace(/[&"]/g, ch => ESCAPES[ch]);
211
226
  }
212
227
 
213
228
  function renderAttributes(attrs) {
@@ -221,7 +236,7 @@ function renderAttributes(attrs) {
221
236
  return out;
222
237
  }
223
238
 
224
- export function renderVNode(node) {
239
+ export function renderVNode(node, rawText = false) {
225
240
  if (node == null) return "";
226
241
  if (typeof node === "string") return node;
227
242
  if (Array.isArray(node)) return node.map(renderVNode).join("");
@@ -231,15 +246,16 @@ export function renderVNode(node) {
231
246
  case "node":
232
247
  return String(node.node);
233
248
  case "text":
234
- return node.value ?? "";
249
+ return rawText ? node.value ?? "" : escapeHtml(node.value ?? "").replace(/&quot;|&#39;/g, m => m === "&quot;" ? '"' : "'");
235
250
  case "comment":
236
251
  return `<!--${node.value ?? ""}-->`;
237
252
  case "fragment":
238
- return (node.children || []).map(renderVNode).join("");
253
+ return (node.children || []).map(child => renderVNode(child)).join("");
239
254
  case "element": {
240
255
  const open = `<${node.tag}${renderAttributes(node.attrs)}>`;
241
256
  if (VOID_ELEMENTS.has(node.tag)) return open;
242
- const inner = (node.children || []).map(renderVNode).join("");
257
+ const unescaped = UNESCAPED_TEXT_ELEMENTS.has(node.tag);
258
+ const inner = (node.children || []).map(child => renderVNode(child, unescaped)).join("");
243
259
  return `${open}${inner}</${node.tag}>`;
244
260
  }
245
261
  default:
@@ -288,7 +304,6 @@ function fragmentToHtml() {
288
304
  return out;
289
305
  }
290
306
 
291
- // Park live nodes while parsing templates to retain their listeners and methods.
292
307
  const NODE_MARKER = "slim-node:";
293
308
  let parkedNodes = [];
294
309
 
@@ -298,9 +313,15 @@ function isDomNode(value) {
298
313
 
299
314
  function stringifyChild(value) {
300
315
  if (value == null || value === false) return "";
316
+ if (value instanceof SafeHtml) return value.value;
317
+ if (value instanceof VNode) return renderVNode(value);
301
318
  if (Array.isArray(value)) return value.map(stringifyChild).join("");
302
319
  if (isDomNode(value)) return `<!--${NODE_MARKER}${parkedNodes.push(value) - 1}-->`;
303
- return String(value);
320
+ return escapeHtml(value);
321
+ }
322
+
323
+ function insideTag(html) {
324
+ return html.lastIndexOf("<") > html.lastIndexOf(">");
304
325
  }
305
326
 
306
327
  function reviveParked(node) {
@@ -314,8 +335,6 @@ function reviveParked(node) {
314
335
  return node;
315
336
  }
316
337
 
317
- // Delegated handlers serialize for SSR and retain live closures on the client.
318
-
319
338
  let eventHandlers = [];
320
339
 
321
340
  function registerEventHandler(event, fn) {
@@ -326,7 +345,6 @@ function registerEventHandler(event, fn) {
326
345
 
327
346
  const boundEvents = new Set();
328
347
 
329
- // Client dispatch keeps closures and binds once per event type.
330
348
  export function __bind_events__() {
331
349
  for (const { event } of eventHandlers) {
332
350
  if (boundEvents.has(event)) continue;
@@ -367,7 +385,6 @@ export function __flush_events__() {
367
385
  return script.replace(/<\/script/gi, "<\\/script");
368
386
  }
369
387
 
370
- // Run lifecycle hooks once; non-browser environments connect eagerly.
371
388
  const __lifecycleRecords__ = new Set();
372
389
  let __lifecycleObserver__ = null;
373
390
 
@@ -414,8 +431,6 @@ export function __lifecycle__(el, connectFns, unmountFns) {
414
431
  __lifecycleRecords__.add(r);
415
432
  }
416
433
 
417
- // Custom elements render into their host and use platform lifecycle callbacks.
418
-
419
434
  export function __create_host__(tag) {
420
435
  const doc = typeof document !== "undefined" ? document : slimDocument;
421
436
  return doc.createElement(tag);
@@ -423,15 +438,26 @@ export function __create_host__(tag) {
423
438
 
424
439
  export function __adopt_into__(host, el) {
425
440
  if (el.nodeType === 11) {
426
- for (const child of [...el.childNodes]) host.appendChild(child);
441
+ for (const child of [...el.childNodes]) if (child.parentNode !== host) host.appendChild(child);
427
442
  return;
428
443
  }
429
444
 
430
- host.appendChild(el);
445
+ if (el.parentNode !== host) host.appendChild(el);
446
+ }
447
+
448
+ function liveProps(signal) {
449
+ return new Proxy({}, {
450
+ get: (_, key) => signal.v[key],
451
+ has: (_, key) => key in signal.v,
452
+ ownKeys: () => Reflect.ownKeys(signal.v),
453
+ getOwnPropertyDescriptor(_, key) {
454
+ const value = signal.v;
455
+ return key in value ? { value: value[key], enumerable: true, configurable: true } : undefined;
456
+ }
457
+ });
431
458
  }
432
459
 
433
460
  export function __define_element__(tag, factory) {
434
- // linkedom cannot define custom elements.
435
461
  if (typeof customElements === "undefined" || !hasNativeDom) return;
436
462
  if (customElements.get(tag)) return;
437
463
 
@@ -440,8 +466,8 @@ export function __define_element__(tag, factory) {
440
466
  super();
441
467
  this.__slim__ = null;
442
468
  this.__props__ = null;
469
+ this.__slim_signal__ = null;
443
470
 
444
- // Restore properties assigned before custom-element upgrade.
445
471
  if (Object.prototype.hasOwnProperty.call(this, "props")) {
446
472
  const pending = this.props;
447
473
  delete this.props;
@@ -455,10 +481,9 @@ export function __define_element__(tag, factory) {
455
481
 
456
482
  set props(value) {
457
483
  this.__props__ = value ?? {};
458
- if (this.__slim__) this.__slim_render__();
484
+ if (this.__slim_signal__) this.__slim_signal__.v = this.__slim_props__();
459
485
  }
460
486
 
461
- // Convert attributes to component props, including camel-cased data attributes.
462
487
  __slim_props__() {
463
488
  const fromAttributes = {};
464
489
 
@@ -476,9 +501,18 @@ export function __define_element__(tag, factory) {
476
501
  }
477
502
 
478
503
  __slim_render__() {
479
- for (const fn of this.__slim__?.unmounts ?? []) fn(this);
480
- this.replaceChildren();
481
- this.__slim__ = factory(this.__slim_props__(), this);
504
+ const signal = this.__slim_signal__ = new Signal(this.__slim_props__());
505
+ if (this.hasAttribute("hydrate") && typeof globalThis.hydrate === "function") {
506
+ this.__slim__ = globalThis.hydrate(() => factory(liveProps(signal), this), this);
507
+ } else {
508
+ this.replaceChildren();
509
+ this.__slim__ = factory(liveProps(signal), this);
510
+ }
511
+
512
+ if (typeof MutationObserver !== "undefined") {
513
+ new MutationObserver(() => { signal.v = this.__slim_props__(); })
514
+ .observe(this, { attributes: true });
515
+ }
482
516
  }
483
517
 
484
518
  connectedCallback() {
@@ -493,8 +527,6 @@ export function __define_element__(tag, factory) {
493
527
  }
494
528
 
495
529
  export function __html__(strings, ...values) {
496
- parkedNodes = [];
497
-
498
530
  let out = strings[0];
499
531
 
500
532
  for (let i = 0; i < values.length; i++) {
@@ -508,6 +540,8 @@ export function __html__(strings, ...values) {
508
540
  const id = registerEventHandler(event, value);
509
541
  out += ` data-slim-on-${event}="${id}"`;
510
542
  }
543
+ } else if (insideTag(out) && /=\s*$/.test(out)) {
544
+ out += `"${escapeHtml(value instanceof SafeHtml ? value.value : value ?? "")}"`;
511
545
  } else {
512
546
  out += stringifyChild(value);
513
547
  }
@@ -515,11 +549,7 @@ export function __html__(strings, ...values) {
515
549
  out += strings[i + 1];
516
550
  }
517
551
 
518
- return out;
519
- }
520
-
521
- export function htmlToElement(input, doc = slimDocument) {
522
- return vnodeToElement(htmlToVdom(input), doc);
552
+ return new SafeHtml(out);
523
553
  }
524
554
 
525
555
  export function __resolve_bem__(vnode, scope = "") {
@@ -548,7 +578,7 @@ export function __resolve_bem__(vnode, scope = "") {
548
578
  export function htmlToVdom(input) {
549
579
  if (input instanceof VNode) return input;
550
580
 
551
- const html = input == null ? "" : String(input);
581
+ const html = input == null ? "" : input instanceof SafeHtml ? input.value : String(input);
552
582
  const nodes = parseNodes(html).map(reviveParked);
553
583
  parkedNodes = [];
554
584
 
@@ -557,7 +587,6 @@ export function htmlToVdom(input) {
557
587
  if (meaningful.length === 0) return fragmentNode([]);
558
588
  if (meaningful.length === 1) {
559
589
  const only = meaningful[0];
560
- // Wrap revived DOM nodes as VNodes.
561
590
  return isDomNode(only) ? new VNode({ type: "node", node: only }) : only;
562
591
  }
563
592
  return fragmentNode(meaningful);