olum-compiler 1.1.0 → 1.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.
@@ -3,7 +3,9 @@
3
3
  "allow": [
4
4
  "Bash(npm run *)",
5
5
  "Bash(cd *)",
6
- "Bash(echo \"exit: $?\")"
6
+ "Bash(echo \"exit: $?\")",
7
+ "Bash(git add *)",
8
+ "Bash(git commit *)"
7
9
  ]
8
10
  }
9
11
  }
package/bin/copySrc.js CHANGED
@@ -2,6 +2,7 @@
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
4
  const { copy, remove, compileRoutes } = require("../lib/helpers");
5
+ const importMap = require("../lib/importMap");
5
6
  const entryPoint = path.resolve(process.cwd(), "src").replace(/\/module/, "");
6
7
  const entryPoint2 = path.resolve(process.cwd(), "public").replace(/\/module/, "");
7
8
 
@@ -21,8 +22,9 @@ module.exports = function copySrc() {
21
22
  copy(entryPoint2, path.resolve(__dirname, "../public"), () => {
22
23
  const indexHtmlPath = path.resolve(__dirname, "../public/index.html");
23
24
  let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
24
- // auto bind div#app placeholder and mainjs script to index.html
25
- indexHtmlContent = indexHtmlContent.replace(/<\/body>/, `\n<div id="app"></div>\n<script defer type="module" src="../src/main.js"></script>\n</body>`);
25
+ // auto bind div#app placeholder, import map and mainjs script to index.html
26
+ // (import map must precede the module script so bare imports resolve)
27
+ indexHtmlContent = indexHtmlContent.replace(/<\/body>/, `\n<div id="app"></div>\n${importMap(entryPoint)}\n<script defer type="module" src="../src/main.js"></script>\n</body>`);
26
28
  fs.writeFileSync(indexHtmlPath, indexHtmlContent);
27
29
  });
28
30
  resolve();
package/bin/server.js CHANGED
@@ -23,6 +23,7 @@ function getPath(entry, url) {
23
23
  path.resolve(entry, candidate),
24
24
  path.resolve(entry, "../", candidate),
25
25
  path.resolve(process.cwd(), candidate),
26
+ path.resolve(entry, "../../", candidate), // project root — app deps (/node_modules/*) install there
26
27
  ].find(p => fs.existsSync(p) && fs.statSync(p).isFile()) || null;
27
28
 
28
29
  // Exact match first (preserves the original behaviour).
@@ -73,7 +74,7 @@ function serve(entry, port) {
73
74
  const html = dom.querySelector("html");
74
75
  const wsContent = handleWsFile();
75
76
  dom.body.insertAdjacentHTML("beforeend", wsContent);
76
- res.writeHead(200, { "content-type": "text/html" });
77
+ res.writeHead(200, { "content-type": "text/html", "cache-control": "no-cache" });
77
78
  res.end("<!DOCTYPE html>" + html.outerHTML);
78
79
  });
79
80
  }
@@ -85,7 +86,9 @@ function serve(entry, port) {
85
86
  if (finalPath && fs.statSync(finalPath).isFile()) {
86
87
  const ext = path.extname(finalPath).toLowerCase();
87
88
  const obj = mimes.find(item => ext === item.ext.toLowerCase());
88
- res.writeHead(200, { "Content-Type": obj ? obj.mime : "application/octet-stream" });
89
+ // no-cache: without it browsers heuristically cache served JS (no headers at all),
90
+ // so a framework/runtime edit keeps running stale code until a hard refresh
91
+ res.writeHead(200, { "Content-Type": obj ? obj.mime : "application/octet-stream", "Cache-Control": "no-cache" });
89
92
  fs.createReadStream(finalPath).pipe(res);
90
93
  return;
91
94
  }
@@ -0,0 +1,27 @@
1
+ const { RAW_OPEN, RAW_CLOSE } = require("./tokens");
2
+
3
+ // Boolean attributes are truthy by PRESENCE: the browser treats checked="false" as checked and
4
+ // disabled="false" as disabled. So value interpolation (checked="${olum.esc(expr)}") can never
5
+ // turn them off. For these attributes, attr="{expr}" compiles to a conditional that emits the
6
+ // bare attribute name or nothing at all: ${(expr) ? "checked" : ""}.
7
+ //
8
+ // Runs on the serialized markup string, BEFORE the generic {expr} escape pass (which would
9
+ // otherwise claim these braces) and emitted with RAW sentinels so the code is not esc-wrapped.
10
+ // Only fires when the ENTIRE value is a single {expr}; mixed values (checked="a {b}") are
11
+ // meaningless for boolean attributes and fall through to the generic pass. Component props are
12
+ // already packed into data-o-props by placeholder() and can't match here.
13
+ const BOOL_ATTRS = [
14
+ "checked", "disabled", "selected", "readonly", "required", "hidden",
15
+ "autofocus", "multiple", "open", "loop", "muted", "controls", "autoplay",
16
+ "novalidate", "default", "defer", "ismap", "reversed",
17
+ ];
18
+
19
+ const boolAttrRegex = new RegExp("(\\s)(" + BOOL_ATTRS.join("|") + ")=([\"'])\\{([^{}]+)\\}\\3", "gi");
20
+
21
+ function handleBoolAttrs(content) {
22
+ return content.replace(boolAttrRegex, (match, ws, name, quote, expr) => {
23
+ return ws + RAW_OPEN + "(" + expr.trim() + ') ? "' + name.toLowerCase() + '" : ""' + RAW_CLOSE;
24
+ });
25
+ }
26
+
27
+ module.exports = handleBoolAttrs;
@@ -0,0 +1,14 @@
1
+ // single switch for where the framework runtime loads from:
2
+ // true -> the local copies in module/core, served at /core by the dev server (framework development)
3
+ // false -> the published npm packages ("olum", "olum-router") installed at the project root
4
+ // both the generated main.js (helpers.js compileRoutes) and the import map (importMap.js)
5
+ // read this flag — they must agree, otherwise two runtime copies load and fight over window.olum
6
+ const useLocalCore = process?.env?.LOCAL_CORE == 'true';
7
+
8
+ // import-map entries for the local mode
9
+ const localLibs = {
10
+ olum: "/core/olum.js",
11
+ "olum-router": "/core/router.js",
12
+ };
13
+
14
+ module.exports = { useLocalCore, localLibs };
package/lib/cssParser.js CHANGED
@@ -49,7 +49,26 @@ function scopeCSS(css, scopeAttr, compName) {
49
49
  s = s.trim();
50
50
  if (!s) return "";
51
51
  if (/^(:root|html|body)\b/.test(s)) return s;
52
- return scope + " " + s; // descendant combinator — root is now stamped so this covers all cases
52
+ // attach the scope attr to the selector's last compound (p:hover -> p[data-o-x]:hover),
53
+ // not as a descendant combinator — a descendant rule would also match nested components'
54
+ // elements, which sit inside this component's DOM but carry their own scope attr
55
+ let depth = 0, start = 0;
56
+ for (let j = 0; j < s.length; j++) {
57
+ const c = s[j];
58
+ if (c === "(" || c === "[") depth++;
59
+ else if (c === ")" || c === "]") depth--;
60
+ else if (depth === 0 && (c === " " || c === ">" || c === "+" || c === "~")) start = j + 1;
61
+ }
62
+ const compound = s.slice(start);
63
+ let k = 0;
64
+ depth = 0;
65
+ for (; k < compound.length; k++) {
66
+ const c = compound[k];
67
+ if (c === "(" || c === "[") depth++;
68
+ else if (c === ")" || c === "]") depth--;
69
+ else if (c === ":" && depth === 0) break;
70
+ }
71
+ return s.slice(0, start) + compound.slice(0, k) + scope + compound.slice(k);
53
72
  }).filter(Boolean).join(", ");
54
73
  }
55
74
 
package/lib/events.js CHANGED
@@ -27,7 +27,64 @@ function isSimpleCallList(str) {
27
27
  }
28
28
  }
29
29
 
30
- function handleEvents(body, counter, filePath, anonHandlers) {
30
+ // True when the expression references a name destructured from props() — e.g.
31
+ // `const { onclick } = props()` + onclick="onclick()". Such a call CAN'T go through the
32
+ // data-o-event chain (the runtime resolves chain names against methodsRef, and a destructured
33
+ // prop isn't a method), so the caller wraps it in an anon handler whose closure holds the prop.
34
+ function referencesPropsAlias(str, propsAliases) {
35
+ const names = propsAliases ? Object.keys(propsAliases) : [];
36
+ if (!names.length) return false;
37
+ try {
38
+ const acorn = require("acorn");
39
+ const node = acorn.parseExpressionAt(str, 0, { ecmaVersion: "latest" });
40
+ let found = false;
41
+ (function walk(n, parent, key) {
42
+ if (found || !n || typeof n.type !== "string") return;
43
+ if (n.type === "Identifier" && names.includes(n.name)) {
44
+ // skip non-value positions: obj.onclick (member property) / { onclick: x } (literal key)
45
+ const isStaticProp =
46
+ parent && !parent.computed && ((parent.type === "MemberExpression" && key === "property") || (parent.type === "Property" && key === "key"));
47
+ if (!isStaticProp) found = true;
48
+ return;
49
+ }
50
+ for (const k of Object.keys(n)) {
51
+ const v = n[k];
52
+ if (Array.isArray(v)) v.forEach((item) => item && typeof item === "object" && walk(item, n, k));
53
+ else if (v && typeof v === "object") walk(v, n, k);
54
+ }
55
+ })(node, null, null);
56
+ return found;
57
+ } catch (e) {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ // Loop variables in scope for an element: params of every ancestor <for each="..."> —
63
+ // "flavour of state.menu" / "(x, i) of ..." / "(key, i, value) in ...". handleEvents runs
64
+ // BEFORE handleForStatement, so the <for> ancestors still exist in the DOM.
65
+ function loopVarNames(item) {
66
+ const vars = [];
67
+ let cur = item;
68
+ while ((cur = cur.parentElement)) {
69
+ if (cur.tagName.toLowerCase() === "for" && cur.hasAttribute("each")) {
70
+ const m = cur.getAttribute("each").trim().match(/(.*)( of | in )/);
71
+ if (m) m[1].replace(/\(|\)/g, "").split(",").forEach((p) => {
72
+ p = p.trim();
73
+ if (p && !vars.includes(p)) vars.push(p);
74
+ });
75
+ }
76
+ }
77
+ return vars;
78
+ }
79
+
80
+ // Which loop variables the handler expression actually references (bare identifier,
81
+ // not a property access like obj.flavour). Over-matching is harmless — it only adds
82
+ // an unused parameter — so a word-boundary test is enough.
83
+ function usedLoopVars(str, item) {
84
+ return loopVarNames(item).filter((v) => new RegExp("(?<![.\\w$])" + v + "\\b").test(str));
85
+ }
86
+
87
+ function handleEvents(body, counter, filePath, anonHandlers, propsAliases) {
31
88
  let name = path.basename(filePath).replace(/\.html/i, "");
32
89
  name = name.slice(0, 1).toLowerCase() + name.slice(1); // make compName camel case
33
90
 
@@ -37,18 +94,30 @@ function handleEvents(body, counter, filePath, anonHandlers) {
37
94
  if (item.hasAttribute(e)) {
38
95
  let attrValue = item.getAttribute(e).trim();
39
96
 
97
+ // Anon handlers are hoisted to component scope, where <for> loop variables don't
98
+ // exist — so any loop variable the expression references becomes an extra PARAMETER
99
+ // of the anon handler. The call site (rendered inside the loop's map callback)
100
+ // serializes the per-item value into data-o-event args, and the runtime passes it
101
+ // back on dispatch — same mechanism simple calls like onclick="remove(flavour)" use.
102
+ const loopArgs = usedLoopVars(attrValue, item);
103
+ const params = ["$event"].concat(loopArgs).join(", ");
104
+
40
105
  // inline arrow/function handler -> extract to a named method, then parse the call below
41
106
  if (looksLikeFunction(attrValue)) {
42
107
  const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
43
- if (anonHandlers) anonHandlers.push(`const ${handlerName} = ${attrValue};`);
44
- attrValue = handlerName + "($event)";
45
- } else if (!isSimpleCallList(attrValue)) {
108
+ if (anonHandlers) {
109
+ if (loopArgs.length) anonHandlers.push(`const ${handlerName} = (${params}) => (${attrValue})($event);`);
110
+ else anonHandlers.push(`const ${handlerName} = ${attrValue};`);
111
+ }
112
+ attrValue = handlerName + "(" + params + ")";
113
+ } else if (!isSimpleCallList(attrValue) || referencesPropsAlias(attrValue, propsAliases)) {
46
114
  // not a plain `name(args)` call list — e.g. a function prop call props().toggle(id)
47
- // or a statement like state.count++ — wrap the whole expression in an anon handler
115
+ // or a statement like state.count++ — OR a call touching a destructured prop
116
+ // (onclick="onclick()") — wrap the whole expression in an anon handler
48
117
  // so it executes as-is in component scope ($event = the DOM event)
49
118
  const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
50
- if (anonHandlers) anonHandlers.push(`const ${handlerName} = ($event) => { ${attrValue} };`);
51
- attrValue = handlerName + "($event)";
119
+ if (anonHandlers) anonHandlers.push(`const ${handlerName} = (${params}) => { ${attrValue} };`);
120
+ attrValue = handlerName + "(" + params + ")";
52
121
  }
53
122
 
54
123
  let methods = attrValue.split("),");
package/lib/helpers.js CHANGED
@@ -27,8 +27,13 @@ const cleanParentheses = (filePath, type="name") => {
27
27
  return filePath;
28
28
  }
29
29
 
30
- const cleanNumbersPrefix = (name) => {
31
- return name.replace(/\d+-?/g, "")
30
+ const cleanNumbersPrefix = (name, type = "name") => {
31
+ if (type === "url") {
32
+ // only the NN- ordering prefix at a segment start — a blanket digit strip would
33
+ // corrupt legit digit segments ("/404" -> "/", "/7guis" -> "/guis")
34
+ return name.replace(/(^|\/)\d+-/g, "$1");
35
+ }
36
+ return name.replace(/\d+-?/g, "");
32
37
  }
33
38
 
34
39
  function isUpper(char) {
@@ -406,6 +411,33 @@ function getGlobalMethods(str) {
406
411
  .filter((item) => item);
407
412
  }
408
413
 
414
+ // top-level bindings destructured from props(): const { onMessage, onSave: save } = props()
415
+ // returns a localName -> propKey map so placeholder.js can flag bare-identifier prop forwards
416
+ // (onMessage="{onMessage}") as kind "props" src entries — functions can't cross the JSON channel
417
+ function getPropsAliases(str) {
418
+ const aliases = {};
419
+ acorn.parse(str, { ecmaVersion: "latest", sourceType: "module" }).body.forEach((obj) => {
420
+ if (obj.type !== "VariableDeclaration" || !Array.isArray(obj.declarations)) return;
421
+ obj.declarations.forEach((decl) => {
422
+ if (
423
+ decl.id &&
424
+ decl.id.type === "ObjectPattern" &&
425
+ decl.init &&
426
+ decl.init.type === "CallExpression" &&
427
+ decl.init.callee &&
428
+ decl.init.callee.name === "props"
429
+ ) {
430
+ decl.id.properties.forEach((prop) => {
431
+ if (prop.type === "Property" && prop.key && prop.key.name && prop.value && prop.value.type === "Identifier") {
432
+ aliases[prop.value.name] = prop.key.name; // localName -> original prop key (handles renames)
433
+ }
434
+ });
435
+ }
436
+ });
437
+ });
438
+ return aliases;
439
+ }
440
+
409
441
  // get props names
410
442
  function getGlobalProps(str) {
411
443
  return acorn
@@ -499,64 +531,6 @@ function minifyJS(src) {
499
531
  return out;
500
532
  }
501
533
 
502
- function resolvePackage(pkgName) {
503
- const pkgJsonPath = path.join(
504
- process.cwd(),
505
- "node_modules",
506
- pkgName,
507
- "package.json"
508
- );
509
-
510
- if (!fs.existsSync(pkgJsonPath)) {
511
- throw new Error(`Package "${pkgName}" not found`);
512
- }
513
-
514
- const pkg = JSON.parse(
515
- fs.readFileSync(pkgJsonPath, "utf8")
516
- );
517
-
518
- let entry;
519
-
520
- if (typeof pkg.exports === "string") {
521
- entry = pkg.exports;
522
- } else if (pkg.exports?.["."]?.import) {
523
- entry = pkg.exports["."].import;
524
- } else if (pkg.exports?.["."]?.default) {
525
- entry = pkg.exports["."].default;
526
- } else if (typeof pkg.exports?.["."] === "string") {
527
- entry = pkg.exports["."];
528
- } else {
529
- entry = pkg.module || pkg.main || "index.js";
530
- }
531
-
532
- entry = entry.replace(/^\.?\//, "");
533
-
534
- return `/node_modules/${pkgName}/${entry}`;
535
- }
536
-
537
- function rewriteImports(code) {
538
- return code.replace(
539
- /from\s+["']([^"']+)["']/g,
540
- (match, specifier) => {
541
- if (
542
- specifier.startsWith(".") ||
543
- specifier.startsWith("/") ||
544
- specifier.startsWith("http:")
545
- || specifier.startsWith("https:")
546
- ) {
547
- return match;
548
- }
549
-
550
- try {
551
- return `from "${resolvePackage(specifier)}"`;
552
- } catch (err) {
553
- console.warn(err.message);
554
- return match;
555
- }
556
- }
557
- );
558
- }
559
-
560
534
  // handle routing based on files
561
535
  function generateRouteManifest(paths, rootDir) {
562
536
  const routes = {};
@@ -673,36 +647,26 @@ function generateRoutes(manifest) {
673
647
 
674
648
  return `export const routes = [
675
649
  ${routes
676
- .map(({ path, comp }) => ` { path: "${cleanNumbersPrefix(path)}", comp: ${cleanNumbersPrefix(comp)} }`)
650
+ .map(({ path, comp }) => ` { path: "${cleanNumbersPrefix(path, "url")}", comp: ${cleanNumbersPrefix(comp)} }`)
677
651
  .join(",\n")}
678
652
  ];`;
679
653
  }
680
654
 
681
- const libsMap = {
682
- development: {
683
- olum: "/node_modules/olum/dist/olum.js",
684
- router: "/node_modules/olum-router/dist/router.js"
685
- },
686
- production: {
687
- olum: "olum",
688
- router: "olum-router"
689
- }
690
- }
691
-
692
655
  const compileRoutes = (entryPoint) => {
693
656
  let routes = ls(entryPoint, { absolute: true });
694
657
  routes = routes.filter((item) => {
695
658
  const extension = path.extname(item);
696
659
  const isDir = fs.lstatSync(item).isDirectory();
697
660
  const isHtml = fs.lstatSync(item).isFile() && extension == ".html";
698
- if (isDir || isHtml && !item.includes("components")) return item;
661
+ const segments = path.relative(entryPoint, item).split(path.sep);
662
+ const inExcludedDir = segments.some((seg) => ["components", "utils"].includes(seg) || seg.startsWith("_"));
663
+ if (isDir || (isHtml && !inExcludedDir)) return item;
699
664
  });
700
665
  // generate routes manifest
701
666
  const manifest = generateRouteManifest(routes, entryPoint);
702
667
  let has404Page = false;
703
668
  if (manifest['not-found']) has404Page = true;
704
- const libImports = `import Olum from "/node_modules/olum/dist/olum.js";\nimport Router from "/node_modules/olum-router/dist/router.js";`;
705
- // const libImports = `import Olum from "../core/olum.js";\nimport Router from "../core/router.js";`; // for testing
669
+ const libImports = `import Olum from "olum";\nimport Router from "olum-router";`;
706
670
  const imports = generateImports(manifest)
707
671
  const config = `const config = { mode: "history", root: "/", ${has404Page? `err: "/404",` : "" } routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
708
672
  routes = generateRoutes(manifest);
@@ -732,11 +696,10 @@ module.exports.stringToBase64 = stringToBase64;
732
696
  module.exports.base64ToString = base64ToString;
733
697
  module.exports.createScopeHandler = createScopeHandler;
734
698
  module.exports.getGlobalMethods = getGlobalMethods;
699
+ module.exports.getPropsAliases = getPropsAliases;
735
700
  module.exports.getGlobalProps = getGlobalProps;
736
701
  module.exports.minifyJS = minifyJS;
737
- module.exports.rewriteImports = rewriteImports;
738
702
  module.exports.generateRouteManifest = generateRouteManifest;
739
703
  module.exports.generateImports = generateImports;
740
704
  module.exports.generateRoutes = generateRoutes;
741
- module.exports.libsMap = libsMap;
742
705
  module.exports.compileRoutes = compileRoutes;
package/lib/htmlParser.js CHANGED
@@ -11,22 +11,26 @@ const handleEvents = require("./events");
11
11
  // const handleAttr = require("./attr");
12
12
  const handleCompPlaceholder = require("./compPlaceholder");
13
13
  const handleHtml = require("./html");
14
- const { RAW_OPEN, RAW_CLOSE, LT, GT } = require("./tokens");
14
+ const handleBoolAttrs = require("./boolAttr");
15
+ const handleTextarea = require("./textarea");
16
+ const { RAW_OPEN, RAW_CLOSE, LT, GT, shieldTags, unshieldTags } = require("./tokens");
15
17
 
16
- function htmlparser(str, counter, filePath, parentMethods) {
18
+ function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
17
19
  let content = str.replace(script, "").replace(style, "");
18
20
  content = clean(content); // clean html comments to avoid runtime errors
19
- content = placeholder(content, selfClosingTag, "self", parentMethods);
20
- content = placeholder(content, normalTag, "normal", parentMethods);
21
+ content = placeholder(content, selfClosingTag, "self", parentMethods, propsAliases);
22
+ content = placeholder(content, normalTag, "normal", parentMethods, propsAliases);
21
23
 
22
24
  // Inline arrow/function event handlers (oninput="(e)=> expr") are extracted into named
23
25
  // __olumAnon_ methods inside handleEvents (collected here, injected into the component JS later).
24
26
  const anonHandlers = [];
25
27
 
26
- // using dom parser
27
- const body = new jsdom.JSDOM(content).window.document.body;
28
+ // using dom parser — shieldTags renames parser-restricted containers (select/table/tr/…) to
29
+ // unknown elements so a <for>/<if>/<show> inside them survives the parse; restored after serialize
30
+ const body = new jsdom.JSDOM(shieldTags(content)).window.document.body;
28
31
  handleHtml(body); // html="expr" -> unescaped ${expr} content (before control-flow dissolves elements)
29
- handleEvents(body, counter, filePath, anonHandlers);
32
+ handleTextarea(body); // textarea value="..." -> text content (no value attribute exists on textarea)
33
+ handleEvents(body, counter, filePath, anonHandlers, propsAliases);
30
34
  // DISABLED — :style object binding. Colon attributes are gone; use a string style with
31
35
  // {expr} interpolation instead, e.g. style="color:{state.color}". Uncomment to re-enable.
32
36
  // handleStyles(body, counter, filePath);
@@ -39,7 +43,12 @@ function htmlparser(str, counter, filePath, parentMethods) {
39
43
  handleShowStatement(body, counter, filePath);
40
44
  const comps = handleCompPlaceholder(body, counter, filePath);
41
45
 
42
- content = body.innerHTML;
46
+ content = unshieldTags(body.innerHTML);
47
+
48
+ // presence-based boolean attributes: checked="{expr}" -> ${(expr) ? "checked" : ""}.
49
+ // Must run before the {expr} escape pass below, which would otherwise interpolate the VALUE
50
+ // (checked="false" is still checked — the browser only checks attribute presence).
51
+ content = handleBoolAttrs(content);
43
52
 
44
53
  // #2 (escape-by-default): at this point every literal `{expr}` left in the markup is a USER value
45
54
  // interpolation (text like `{props.todo.text}` or a simple attribute like `id="todo-{x.id}"`).
@@ -54,7 +63,10 @@ function htmlparser(str, counter, filePath, parentMethods) {
54
63
  const raw = expr.trim();
55
64
  if (raw === "children") return "${children}";
56
65
  if (/^props\(\s*\)\.children$/.test(raw)) return "${" + raw + "}";
57
- return "${olum.esc(" + expr + ")}";
66
+ // the captured expr is JS, but if it sat in a TEXT node jsdom entity-encoded its <,>,& on
67
+ // serialize — decode them back so comparisons like {width > 380 ? a : b} stay valid JS
68
+ const js = expr.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
69
+ return "${olum.esc(" + js + ")}";
58
70
  });
59
71
 
60
72
  content = content.replace(/&amp;/g, "&"); // fix entity
@@ -0,0 +1,116 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const colors = require("./colors");
4
+ const { ls, isFile } = require("./helpers");
5
+
6
+ const { useLocalCore, localLibs } = require("./coreLibs"); // shared flag — keeps main.js and the import map on the same runtime copy
7
+
8
+ // pick the browser-usable file from a package.json "exports" condition tree
9
+ function pickEntry(exp) {
10
+ if (typeof exp === "string") return exp;
11
+ if (Array.isArray(exp)) {
12
+ for (const item of exp) {
13
+ const found = pickEntry(item);
14
+ if (found) return found;
15
+ }
16
+ return null;
17
+ }
18
+ if (exp && typeof exp === "object") {
19
+ for (const key of ["browser", "import", "module", "default"]) {
20
+ if (exp[key]) {
21
+ const found = pickEntry(exp[key]);
22
+ if (found) return found;
23
+ }
24
+ }
25
+ }
26
+ return null;
27
+ }
28
+
29
+ function resolvePackage(rootDir, pkgName) {
30
+ const pkgJsonPath = path.join(rootDir, "node_modules", pkgName, "package.json");
31
+ if (!fs.existsSync(pkgJsonPath)) return null;
32
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8"));
33
+ let exp = pkg.exports;
34
+ // subpath map ("." keys) vs plain condition object — take the root subpath
35
+ if (exp && typeof exp === "object" && !Array.isArray(exp)) {
36
+ const keys = Object.keys(exp);
37
+ if (keys.some((k) => k.startsWith("."))) exp = exp["."];
38
+ }
39
+ let entry = pickEntry(exp) || pkg.module || pkg.main || "index.js";
40
+ entry = entry.replace(/^\.?\//, "");
41
+ return "/node_modules/" + pkgName + "/" + entry;
42
+ }
43
+
44
+ // collect bare specifiers used in src: from "pkg" | import "pkg" | import("pkg")
45
+ function getBareSpecifiers(srcDir) {
46
+ const specifiers = new Set();
47
+ const files = ls(srcDir, { absolute: true }).filter((p) => isFile(p) && /\.(html|js)$/i.test(p));
48
+ const regex = /(?:from\s+|import\s+|import\s*\(\s*)["']([^"'\n]+)["']/g;
49
+ files.forEach((file) => {
50
+ const content = fs.readFileSync(file, "utf8");
51
+ let match;
52
+ while ((match = regex.exec(content))) {
53
+ const spec = match[1];
54
+ if (spec.startsWith(".") || spec.startsWith("/") || /^https?:/.test(spec)) continue;
55
+ specifiers.add(spec);
56
+ }
57
+ });
58
+ return [...specifiers];
59
+ }
60
+
61
+ function toPkgName(specifier) {
62
+ const segments = specifier.split("/");
63
+ return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
64
+ }
65
+
66
+ // map a package AND its transitive deps — a package's own ESM files import their deps as bare
67
+ // specifiers too (d3-scale imports "d3-array"), and the browser resolves those via the import map
68
+ function addPackage(rootDir, pkgName, imports) {
69
+ if (imports[pkgName]) return;
70
+ const entry = resolvePackage(rootDir, pkgName);
71
+ if (!entry) {
72
+ console.warn(colors("yellow", 'Can\'t resolve "' + pkgName + '" — install it at the project root: npm i ' + pkgName));
73
+ return;
74
+ }
75
+ imports[pkgName] = entry;
76
+ imports[pkgName + "/"] = "/node_modules/" + pkgName + "/"; // subpath imports e.g. "pkg/x.js"
77
+ const pkgJsonPath = path.join(rootDir, "node_modules", pkgName, "package.json");
78
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8"));
79
+ Object.keys(pkg.dependencies || {}).forEach((dep) => addPackage(rootDir, dep, imports));
80
+ }
81
+
82
+ /**
83
+ * Build the <script type="importmap"> tag injected into index.html so bare imports
84
+ * (e.g. import { marked } from "marked") resolve in the browser without a bundler.
85
+ * App deps install at the project root (rootDir = srcDir/..); framework libs map to /core.
86
+ * @param {*} srcDir absolute path of the project's src directory
87
+ */
88
+ function importMap(srcDir) {
89
+ const rootDir = path.resolve(srcDir, "..");
90
+ const imports = {};
91
+
92
+ // handle internal libs
93
+ if (useLocalCore) {
94
+ Object.assign(imports, localLibs);
95
+ } else {
96
+ // npm mode: the framework resolves like any other root dependency
97
+ Object.keys(localLibs).forEach((pkgName) => {
98
+ const entry = resolvePackage(rootDir, pkgName);
99
+ if (!entry) {
100
+ console.warn(colors("yellow", 'Can\'t resolve "' + pkgName + '" — install it at the project root: npm i ' + pkgName));
101
+ return;
102
+ }
103
+ imports[pkgName] = entry;
104
+ imports[pkgName + "/"] = "/node_modules/" + pkgName + "/";
105
+ });
106
+ }
107
+
108
+ getBareSpecifiers(srcDir).forEach((spec) => {
109
+ const pkgName = toPkgName(spec);
110
+ if (pkgName in localLibs) return;
111
+ addPackage(rootDir, pkgName, imports);
112
+ });
113
+ return '<script type="importmap">' + JSON.stringify({ imports }, null, 2) + "</script>";
114
+ }
115
+
116
+ module.exports = importMap;
package/lib/parser.js CHANGED
@@ -5,7 +5,7 @@ const jsParser = require("./jsParser");
5
5
  const getImports = require("./getImports");
6
6
  const toJs = require("./toJs");
7
7
  const path = require("path");
8
- const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps, libsMap } = require("./helpers");
8
+ const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps, getPropsAliases } = require("./helpers");
9
9
  const createSourceMap = require("./sourcemap");
10
10
 
11
11
  const parser = (str, counter, filePath) => {
@@ -22,8 +22,12 @@ const parser = (str, counter, filePath) => {
22
22
  // can't cross the JSON data-o-props channel, so they travel via data-o-props-src kind "method"
23
23
  let parentMethods = [];
24
24
  try { parentMethods = getGlobalMethods(js); } catch (e) {}
25
+ // names destructured from props() — forwarding them (onMessage="{onMessage}") must travel via
26
+ // data-o-props-src kind "props" so function props survive intermediate components at any depth
27
+ let propsAliases = {};
28
+ try { propsAliases = getPropsAliases(js); } catch (e) {}
25
29
 
26
- let {html, comps, anonHandlers} = htmlParser(str, counter, filePath, parentMethods); // html content and all components tags <olum></olum>
30
+ let {html, comps, anonHandlers} = htmlParser(str, counter, filePath, parentMethods, propsAliases); // html content and all components tags <olum></olum>
27
31
  html = html.replace(/\"\-\[\[\-/g, "'").replace(/\-\]\]\-\"/g, "'"); // fix json in attribute issue
28
32
 
29
33
  // Inject anonymous handler declarations so getGlobalMethods picks them up as regular methods
@@ -34,14 +38,6 @@ const parser = (str, counter, filePath) => {
34
38
  if (imports) {
35
39
  const importRegex = /(import)(\s+)?(?!from)/g;
36
40
  imports.forEach((item) => {
37
- // resolve imported libs: olum, olum-router
38
- if (/from\s+(['"])olum\1/.test(item.statement)) {
39
- item.statement = item.statement.replace(new RegExp(item.regex, ""), `from "${libsMap[process.env.NODE_ENV].olum}"`)
40
- }
41
- if (/from\s+(['"])olum-router\1/.test(item.statement)) {
42
- item.statement = item.statement.replace(new RegExp(item.regex, ""), `from "${libsMap[process.env.NODE_ENV].olum}"`)
43
- }
44
-
45
41
  if (item.type && item.type == "noFrom") js = js.replace(new RegExp(item.regex, "gm"), "");
46
42
  if (!item.type) js = js.replace(new RegExp(item.regex, "g"), "*/");
47
43
  });
@@ -16,7 +16,7 @@ function literalExpr(raw) {
16
16
  return "'" + raw.replace(/'/g, "\\'") + "'";
17
17
  }
18
18
 
19
- function parseProps(attrsStr, parentMethods) {
19
+ function parseProps(attrsStr, parentMethods, propsAliases) {
20
20
  const entries = [];
21
21
  const srcEntries = []; // prop-name:state-key pairs for setter write-back
22
22
  // six alternatives in priority order (groups kept intact for easy toggling):
@@ -57,6 +57,16 @@ function parseProps(attrsStr, parentMethods) {
57
57
  srcEntries.push(propName + ':method:' + bare);
58
58
  continue;
59
59
  }
60
+ // PROP FORWARD: a bare identifier destructured from props() in THIS (parent) component,
61
+ // e.g. `const { onMessage } = props()` + onMessage="{onMessage}". Emit both the JSON entry
62
+ // (carries serializable values) and a kind "props" src entry keyed by the ORIGINAL prop name
63
+ // — buildTree falls back to the parent's own incomingProps when JSON dropped the value
64
+ // (it was a function), so function props survive any nesting depth.
65
+ if (propsAliases && Object.prototype.hasOwnProperty.call(propsAliases, bare) && /^[A-Za-z_$][\w$]*$/.test(bare)) {
66
+ entries.push(propName + ': ' + bare);
67
+ srcEntries.push(propName + ':props:' + propsAliases[bare]);
68
+ continue;
69
+ }
60
70
  // object literal: restore {} wrappers, escaping { so htmlParser won't turn it into ${
61
71
  const entryExpr = /^\s*\w+\s*:/.test(expr) ? ESC + expr + '}' : expr;
62
72
  entries.push(propName + ': ' + entryExpr);
@@ -75,8 +85,8 @@ function parseProps(attrsStr, parentMethods) {
75
85
  return { entries, srcEntries };
76
86
  }
77
87
 
78
- function buildPropsAttr(attrsStr, parentMethods) {
79
- const { entries, srcEntries } = parseProps(attrsStr, parentMethods);
88
+ function buildPropsAttr(attrsStr, parentMethods, propsAliases) {
89
+ const { entries, srcEntries } = parseProps(attrsStr, parentMethods, propsAliases);
80
90
 
81
91
  // emit the two attributes independently: a component may receive only function props
82
92
  // (src entries, no JSON payload) or only data props (JSON payload, no src entries)
@@ -90,14 +100,14 @@ function buildPropsAttr(attrsStr, parentMethods) {
90
100
  }
91
101
 
92
102
  // handle components placeholders with olum tag <olum></olum>
93
- function placeholder(content, regex, type, parentMethods) {
103
+ function placeholder(content, regex, type, parentMethods, propsAliases) {
94
104
  return content.replace(regex, (str, $1, $2) => {
95
105
  let data = $1.split(" ");
96
106
  if (isFullArr(data)) {
97
107
  let name = data[0].trim();
98
108
  if (isUpper(name[0])) {
99
109
  name = "name='" + name + "'";
100
- const propsAttr = data.length > 1 ? buildPropsAttr(data.slice(1).join(" "), parentMethods) : "";
110
+ const propsAttr = data.length > 1 ? buildPropsAttr(data.slice(1).join(" "), parentMethods, propsAliases) : "";
101
111
  const slot = type === "normal" ? $2 : "";
102
112
  return "<olum " + name + propsAttr + ">" + slot + "</olum>";
103
113
  }
@@ -0,0 +1,14 @@
1
+ // <textarea value="..."> — HTML has no `value` attribute on textarea (its value is its text
2
+ // content), so a serialized value="..." would be silently ignored by the browser's parser.
3
+ // Move the attribute into the element's content, where the later {expr} escape pass
4
+ // interpolates it exactly like regular text. If the textarea also has authored content,
5
+ // the value attribute wins (they'd be two sources of truth otherwise).
6
+ function handleTextarea(body) {
7
+ const elms = Array.prototype.slice.call(body.querySelectorAll("textarea[value]"));
8
+ elms.forEach((item) => {
9
+ item.textContent = item.getAttribute("value");
10
+ item.removeAttribute("value");
11
+ });
12
+ }
13
+
14
+ module.exports = handleTextarea;
package/lib/toJs.js CHANGED
@@ -3,6 +3,8 @@ const path = require("path");
3
3
  function toJs(statement) {
4
4
  return statement.replace(/(from)(\s+)?.*/g, (str) => {
5
5
  let _path = str.replace(/from|'|"/g, "").trim();
6
+ // bare specifiers (npm pkgs, olum) resolve via the import map in index.html — don't touch them
7
+ if (!/^\.{0,2}\//.test(_path)) return 'from "' + _path + '";';
6
8
  const extname = path.extname(_path);
7
9
  const newPath = extname ? _path.replace(extname, "") : _path;
8
10
  return 'from "' + newPath + '.js";';
package/lib/tokens.js CHANGED
@@ -15,10 +15,21 @@
15
15
  const LT = "OLUM_LT";
16
16
  const GT = "OLUM_GT";
17
17
 
18
+ // Tag shield: the HTML5 parser restricts what these containers may hold — unknown tags are DROPPED
19
+ // inside <select> and foster-parented out of <table>/<tr> — so a <for>/<if>/<show> placed there is
20
+ // destroyed before the directive passes run. Renaming the containers to unknown elements
21
+ // (olum-select, olum-tr, …) makes the parser treat them as generic containers that keep any child;
22
+ // htmlParser restores the real names after serialization.
23
+ const restrictedTags = "select|table|caption|colgroup|col|thead|tbody|tfoot|tr|td|th";
24
+ const shieldRe = new RegExp("<(\\/?)(" + restrictedTags + ")(?=[\\s/>])", "gi");
25
+ const unshieldRe = new RegExp("<(\\/?)olum-(" + restrictedTags + ")(?=[\\s/>])", "gi");
26
+
18
27
  module.exports = {
19
28
  RAW_OPEN: "OLUM_RAW_OPEN",
20
29
  RAW_CLOSE: "OLUM_RAW_CLOSE",
21
30
  LT,
22
31
  GT,
23
32
  shieldOps: (s) => String(s).split("<").join(LT).split(">").join(GT),
33
+ shieldTags: (s) => s.replace(shieldRe, "<$1olum-$2"),
34
+ unshieldTags: (s) => s.replace(unshieldRe, "<$1$2"),
24
35
  };
package/lib/websocket.js CHANGED
@@ -81,7 +81,9 @@ class WebSocket extends EventEmitter {
81
81
  socket.end();
82
82
  });
83
83
  socket.on("error", err => {
84
- this.emit("error", err);
84
+ // only forward if someone listens — an unhandled 'error' on an EventEmitter
85
+ // would throw and take down the whole process on any abrupt disconnect
86
+ if (this.listenerCount("error") > 0) this.emit("error", err);
85
87
  socket.destroy();
86
88
  });
87
89
  socket.on("close", () => {
@@ -141,7 +143,7 @@ class WebSocket extends EventEmitter {
141
143
  payload.writeUInt16BE(code, 0);
142
144
  reason.copy(payload, 2);
143
145
  }
144
- this._socket.write(encodeFrame(0x8, payload));
146
+ if (this._socket.writable && !this._socket.writableEnded) this._socket.write(encodeFrame(0x8, payload));
145
147
  // close handshake complete → shut down the tcp stream
146
148
  if (this._closeReceived) this._socket.end();
147
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
@@ -149,6 +149,14 @@ check(
149
149
  (out) => /\$\{olum\.esc\(state\.count \+ 1\)\}/.test(tmpl(out)) && parses(out)
150
150
  );
151
151
 
152
+ // jsdom entity-encodes <,>,& in text nodes on serialize — the escape pass must decode them
153
+ // back inside the captured expr or the emitted JS is broken (`width &gt; 380` → SyntaxError)
154
+ check(
155
+ "comparison operators in a text {expr} survive the jsdom round-trip",
156
+ comp(`<p>{state.width > 380 && state.width < 800 ? 'mid' : 'other'}</p>`),
157
+ (out) => /olum\.esc\(state\.width > 380 && state\.width < 800 \? 'mid' : 'other'\)/.test(tmpl(out)) && parses(out)
158
+ );
159
+
152
160
  // ── §5 String attributes (literal + {expr}) ────────────────────────────────
153
161
  section("§5 String attributes");
154
162
 
@@ -170,6 +178,47 @@ check(
170
178
  (out) => /style="color:\$\{olum\.esc\(state\.color\)\}; padding:8px;"/.test(tmpl(out)) && parses(out)
171
179
  );
172
180
 
181
+ // textarea has no `value` attribute in HTML (its value is its text content), so a
182
+ // serialized value="..." would be silently dropped by the browser's parser —
183
+ // the compiler must move it into the element's content
184
+ check(
185
+ "textarea value attribute becomes text content",
186
+ comp(`<textarea value="{state.cls}"></textarea>`),
187
+ (out) => /<textarea[^>]*>\$\{olum\.esc\(state\.cls\)\}<\/textarea>/.test(tmpl(out)) && !/value=/.test(tmpl(out)) && parses(out)
188
+ );
189
+
190
+ check(
191
+ "textarea value attribute wins over authored content",
192
+ comp(`<textarea value="{state.cls}">stale</textarea>`),
193
+ (out) => /<textarea[^>]*>\$\{olum\.esc\(state\.cls\)\}<\/textarea>/.test(tmpl(out)) && !/stale/.test(tmpl(out)) && parses(out)
194
+ );
195
+
196
+ // boolean attributes are truthy by PRESENCE (checked="false" is still checked), so
197
+ // attr="{expr}" must toggle the attribute's existence, never interpolate its value
198
+ check(
199
+ "boolean attribute compiles to a presence toggle (checked)",
200
+ comp(`<input type="checkbox" checked="{state.count}" />`),
201
+ (out) => /\$\{\(state\.count\) \? "checked" : ""\}/.test(tmpl(out)) && !/checked="\$\{olum\.esc/.test(tmpl(out)) && parses(out)
202
+ );
203
+
204
+ check(
205
+ "boolean attribute with an expression (disabled)",
206
+ comp(`<button disabled="{!state.count}">Go</button>`),
207
+ (out) => /\$\{\(!state\.count\) \? "disabled" : ""\}/.test(tmpl(out)) && parses(out)
208
+ );
209
+
210
+ check(
211
+ "static boolean attribute is left alone",
212
+ comp(`<input type="text" disabled />`),
213
+ (out) => /disabled/.test(tmpl(out)) && !/\? "disabled"/.test(tmpl(out)) && parses(out)
214
+ );
215
+
216
+ check(
217
+ "boolean attribute inside <for> stays a presence toggle",
218
+ comp(`<for each="x of state.items"><option selected="{x.id === state.count}">{x.name}</option></for>`),
219
+ (out) => /\$\{\(x\.id === state\.count\) \? "selected" : ""\}/.test(tmpl(out)) && parses(out)
220
+ );
221
+
173
222
  // ── §6 Events on* (code in "") ─────────────────────────────────────────────
174
223
  section("§6 Events");
175
224
 
@@ -190,13 +239,33 @@ check(
190
239
  comp(`<input oninput="setVal($event)" />`, `const setVal = (e) => 0;`),
191
240
  (out) => /oninput\|setVal=\$\{JSON\.stringify\(\['\$event'\]\)\}/.test(tmpl(out)) && parses(out)
192
241
  );
193
-
194
242
  check(
195
243
  "inline arrow handler becomes a named __olumAnon_ method",
196
244
  comp(`<input oninput="(e) => state.name = e.target.value" />`),
197
245
  (out) => /__olumAnon_\w+/.test(out) && /data-o-event/.test(tmpl(out)) && parses(out)
198
246
  );
199
247
 
248
+ // anon handlers are hoisted to component scope where <for> loop variables don't exist,
249
+ // so a referenced loop variable must become a handler parameter whose per-item value
250
+ // is serialized into the data-o-event args at render time
251
+ check(
252
+ "anon handler inside <for> receives the loop variable as an argument",
253
+ comp(
254
+ `<for each="flavour of state.items"><input type="checkbox" onchange="toggle(flavour)($event)" /></for>`,
255
+ `const toggle = (f) => (e) => 0;`
256
+ ),
257
+ (out) =>
258
+ /const __olumAnon_\w+ = \(\$event, flavour\) => \{ toggle\(flavour\)\(\$event\) \}/.test(out) &&
259
+ /JSON\.stringify\(\['\$event', flavour\]\)/.test(tmpl(out)) &&
260
+ parses(out)
261
+ );
262
+
263
+ check(
264
+ "inline arrow handler inside <for> receives the loop variable as an argument",
265
+ comp(`<for each="(x, i) of state.items"><button onclick="(e) => state.count = i">x</button></for>`),
266
+ (out) => /const __olumAnon_\w+ = \(\$event, i\) =>/.test(out) && /JSON\.stringify\(\['\$event', i\]\)/.test(tmpl(out)) && parses(out)
267
+ );
268
+
200
269
  // ── §7 Conditionals <if>/<else-if>/<else> ──────────────────────────────────
201
270
  section("§7 Conditionals");
202
271
 
@@ -248,6 +317,20 @@ check(
248
317
  (out) => /data-o-key/.test(tmpl(out)) && parses(out)
249
318
  );
250
319
 
320
+ // the HTML parser drops unknown tags inside <select> and foster-parents them out of tables —
321
+ // the tag shield (tokens.js) must keep <for>/<if> alive in these containers
322
+ check(
323
+ "<for> inside <select> survives the parse and scopes the loop variable",
324
+ comp(`<select><for each="q of state.questions"><option value="{q.id}">{q.text}</option></for></select>`),
325
+ (out) => /<select>\$\{state\.questions\.map\(function\(q\)/.test(tmpl(out)) && !/<olum-select/.test(tmpl(out)) && parses(out)
326
+ );
327
+
328
+ check(
329
+ "<for> inside <table>/<tbody> is not foster-parented out",
330
+ comp(`<table><tbody><for each="row of state.rows"><tr><td>{row.a}</td></tr></for></tbody></table>`),
331
+ (out) => /<tbody>\$\{state\.rows\.map\(function\(row\)/.test(tmpl(out)) && /<tr><td>/.test(tmpl(out)) && parses(out)
332
+ );
333
+
251
334
  // ── §10 Raw HTML (html="expr" + olum.html()) ───────────────────────────────
252
335
  section("§10 Raw HTML");
253
336
 
@@ -323,6 +406,26 @@ check(
323
406
  (out) => /item: item/.test(out) && !/item:method/.test(out) && parses(out)
324
407
  );
325
408
 
409
+ check(
410
+ "forwarding a destructured prop emits a kind-props source (function props survive nesting)",
411
+ comp(`<C onMessage="{onMessage}" />`, `import C from "./C";\nconst { onMessage } = props();`),
412
+ (out) => /data-o-props-src="onMessage:props:onMessage"/.test(out) && /onMessage: onMessage/.test(out) && !/onMessage:method/.test(out) && parses(out)
413
+ );
414
+
415
+ check(
416
+ "forwarding a RENAMED destructured prop keys the source by the original prop name",
417
+ comp(`<C onMessage="{om}" />`, `import C from "./C";\nconst { onMessage: om } = props();`),
418
+ (out) => /data-o-props-src="onMessage:props:onMessage"/.test(out) && parses(out)
419
+ );
420
+
421
+ check(
422
+ // a destructured prop isn't in methodsRef, so the data-o-event chain can't dispatch it by
423
+ // name — the compiler must wrap the call in an anon handler whose closure holds the prop
424
+ "calling a destructured prop in an event handler wraps it in an anon method",
425
+ comp(`<button onclick="onclick()">x</button>`, `const { onclick } = props();`),
426
+ (out) => /__olumAnon_\w+ = \(\$event\) => \{ onclick\(\) \}/.test(out) && /onclick\|__olumAnon_/.test(out) && parses(out)
427
+ );
428
+
326
429
  check(
327
430
  "forwarding a function prop records a props source (resolved live at runtime)",
328
431
  comp(`<C fn="{props().onSave}" />`, `import C from "./C";\nimport { props } from "../core/olum.js";`),
@@ -384,9 +487,12 @@ check(
384
487
  section("§16 Scoped CSS");
385
488
 
386
489
  check(
387
- "styles are scoped with a [data-o-*] prefix and injected",
388
- comp(`<div class="box"></div>`).replace("</script>", "</script>\n<style>.box{color:red}</style>"),
389
- (out) => /\[data-o-\w+\] \.box/.test(out) && /olum\.injectStyle\(/.test(out) && parses(out)
490
+ // the scope attr attaches to the selector's LAST COMPOUND (.box[data-o-x], p[data-o-x]:hover),
491
+ // not as a `[data-o-x] .box` descendant prefix — a descendant rule would also match nested
492
+ // components' elements, which sit inside this component's DOM but carry their own scope attr
493
+ "styles are scoped onto the selector's last compound and injected",
494
+ comp(`<div class="box"></div>`).replace("</script>", "</script>\n<style>.box{color:red}\np:hover{color:blue}</style>"),
495
+ (out) => /\.box\[data-o-\w+\]/.test(out) && /p\[data-o-\w+\]:hover/.test(out) && /olum\.injectStyle\(/.test(out) && parses(out)
390
496
  );
391
497
 
392
498
  // ── §17 Imports ─────────────────────────────────────────────────────────────
@@ -418,6 +524,105 @@ check(
418
524
  (out) => /<olum name="C"/.test(tmpl(out)) && !/data-o-props=/.test(tmpl(out)) && parses(out)
419
525
  );
420
526
 
527
+ // ── §20 File-based routing (compileRoutes) ──────────────────────────────────
528
+ // compileRoutes(entryPoint) scans a src tree and emits the router entry module:
529
+ // imports + `export const routes = [...]` + Router/Olum bootstrap. Unlike the
530
+ // parser checks above it reads the filesystem, so each check builds a throwaway
531
+ // fixture tree in the OS temp dir and removes it afterwards.
532
+ section("§20 File-based routing (compileRoutes)");
533
+
534
+ const { compileRoutes } = require("../lib/helpers");
535
+ const fs = require("fs");
536
+ const os = require("os");
537
+ const nodePath = require("path");
538
+
539
+ // like check() but for units that aren't parser(template): producer() returns
540
+ // the value under test (and owns its fixture setup/teardown)
541
+ function checkFn(name, producer, assertion) {
542
+ let out;
543
+ try {
544
+ out = producer();
545
+ } catch (e) {
546
+ recordFail(name);
547
+ console.log(" " + FAIL_ICON + " " + name + dim(" (threw: " + e.message + ")"));
548
+ console.log(" " + dim("↳ in " + currentSection));
549
+ return;
550
+ }
551
+ let ok = false;
552
+ let detail = "";
553
+ try {
554
+ ok = assertion(out);
555
+ } catch (e) {
556
+ detail = dim(" (" + e.message + ")");
557
+ }
558
+ if (ok) {
559
+ passed++;
560
+ console.log(" " + PASS_ICON + " " + name);
561
+ } else {
562
+ recordFail(name);
563
+ if (!detail) detail = "\n " + dim(String(out).replace(/\s+/g, " ").slice(0, 200));
564
+ console.log(" " + FAIL_ICON + " " + red(name) + detail);
565
+ console.log(" " + dim("↳ in " + currentSection));
566
+ }
567
+ }
568
+
569
+ function withRouteTree(files, fn) {
570
+ const root = fs.mkdtempSync(nodePath.join(os.tmpdir(), "olum-routes-"));
571
+ try {
572
+ files.forEach((f) => {
573
+ const abs = nodePath.join(root, f);
574
+ fs.mkdirSync(nodePath.dirname(abs), { recursive: true });
575
+ fs.writeFileSync(abs, "<div></div>");
576
+ });
577
+ return fn(root);
578
+ } finally {
579
+ fs.rmSync(root, { recursive: true, force: true });
580
+ }
581
+ }
582
+
583
+ checkFn(
584
+ "route tree compiles: / first, /404 last, [param] -> :param, (group) and NN- prefixes stripped",
585
+ () =>
586
+ withRouteTree(
587
+ [
588
+ "page.html",
589
+ "not-found.html",
590
+ "about/page.html",
591
+ "(main)/club/page.html",
592
+ "01-blog/[slug]/page.html",
593
+ "components/Widget.html", // excluded dir — never a route
594
+ "_drafts/page.html", // _-prefixed dir — excluded
595
+ ],
596
+ (root) => compileRoutes(root)
597
+ ),
598
+ (out) => {
599
+ const paths = [...out.matchAll(/path: "([^"]+)"/g)].map((m) => m[1]);
600
+ return (
601
+ /import App from "\.\/page\.js";/.test(out) &&
602
+ /import NotFound from "\.\/not-found\.js";/.test(out) &&
603
+ /import About from "\.\/about\/page\.js";/.test(out) &&
604
+ // imports keep the REAL file location; only route path/comp are cleaned
605
+ /import Club from "\.\/\(main\)\/club\/page\.js";/.test(out) &&
606
+ /import BlogSlug from "\.\/01-blog\/\[slug\]\/page\.js";/.test(out) &&
607
+ /\{ path: "\/club", comp: Club \}/.test(out) &&
608
+ /\{ path: "\/blog\/:slug", comp: BlogSlug \}/.test(out) &&
609
+ /\{ path: "\/about", comp: About \}/.test(out) &&
610
+ paths[0] === "/" &&
611
+ paths[paths.length - 1] === "/404" &&
612
+ /err: "\/404",/.test(out) && // not-found.html wires the router's 404 redirect
613
+ !/Widget|_drafts|Drafts/.test(out) && // excluded dirs leave no trace
614
+ /new Router\(config\)/.test(out) &&
615
+ /new Olum\(\)\.\$\("#app"\)\.use\(router\)/.test(out)
616
+ );
617
+ }
618
+ );
619
+
620
+ checkFn(
621
+ "no not-found.html -> no /404 route and no err in the router config",
622
+ () => withRouteTree(["page.html", "about/page.html"], (root) => compileRoutes(root)),
623
+ (out) => !/\/404/.test(out) && !/err:/.test(out) && /\{ path: "\/", comp: App \}/.test(out) && /\{ path: "\/about", comp: About \}/.test(out)
624
+ );
625
+
421
626
  console.log("\n========================");
422
627
  const summary = `${passed} passed, ${failed} failed`;
423
628
  console.log((failed ? red(bold(summary)) : green(bold(summary))) + "\n");
@@ -439,7 +644,7 @@ if (failed) {
439
644
 
440
645
  // Guard against a whole section silently disappearing (a bad merge, a `check` that
441
646
  // throws before registering, etc.). Bump EXPECTED_CHECKS when you add/remove tests.
442
- const EXPECTED_CHECKS = 42;
647
+ const EXPECTED_CHECKS = 58;
443
648
  const total = passed + failed;
444
649
  if (total !== EXPECTED_CHECKS) {
445
650
  console.log(yellow(`⚠ ran ${total} checks but expected ${EXPECTED_CHECKS} — did a test get dropped?`) + "\n");