olum-compiler 1.1.6 → 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/server.js CHANGED
@@ -74,7 +74,7 @@ function serve(entry, port) {
74
74
  const html = dom.querySelector("html");
75
75
  const wsContent = handleWsFile();
76
76
  dom.body.insertAdjacentHTML("beforeend", wsContent);
77
- res.writeHead(200, { "content-type": "text/html" });
77
+ res.writeHead(200, { "content-type": "text/html", "cache-control": "no-cache" });
78
78
  res.end("<!DOCTYPE html>" + html.outerHTML);
79
79
  });
80
80
  }
@@ -86,7 +86,9 @@ function serve(entry, port) {
86
86
  if (finalPath && fs.statSync(finalPath).isFile()) {
87
87
  const ext = path.extname(finalPath).toLowerCase();
88
88
  const obj = mimes.find(item => ext === item.ext.toLowerCase());
89
- 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" });
90
92
  fs.createReadStream(finalPath).pipe(res);
91
93
  return;
92
94
  }
package/lib/events.js CHANGED
@@ -59,6 +59,31 @@ function referencesPropsAlias(str, propsAliases) {
59
59
  }
60
60
  }
61
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
+
62
87
  function handleEvents(body, counter, filePath, anonHandlers, propsAliases) {
63
88
  let name = path.basename(filePath).replace(/\.html/i, "");
64
89
  name = name.slice(0, 1).toLowerCase() + name.slice(1); // make compName camel case
@@ -69,19 +94,30 @@ function handleEvents(body, counter, filePath, anonHandlers, propsAliases) {
69
94
  if (item.hasAttribute(e)) {
70
95
  let attrValue = item.getAttribute(e).trim();
71
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
+
72
105
  // inline arrow/function handler -> extract to a named method, then parse the call below
73
106
  if (looksLikeFunction(attrValue)) {
74
107
  const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
75
- if (anonHandlers) anonHandlers.push(`const ${handlerName} = ${attrValue};`);
76
- attrValue = handlerName + "($event)";
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 + ")";
77
113
  } else if (!isSimpleCallList(attrValue) || referencesPropsAlias(attrValue, propsAliases)) {
78
114
  // not a plain `name(args)` call list — e.g. a function prop call props().toggle(id)
79
115
  // or a statement like state.count++ — OR a call touching a destructured prop
80
116
  // (onclick="onclick()") — wrap the whole expression in an anon handler
81
117
  // so it executes as-is in component scope ($event = the DOM event)
82
118
  const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
83
- if (anonHandlers) anonHandlers.push(`const ${handlerName} = ($event) => { ${attrValue} };`);
84
- attrValue = handlerName + "($event)";
119
+ if (anonHandlers) anonHandlers.push(`const ${handlerName} = (${params}) => { ${attrValue} };`);
120
+ attrValue = handlerName + "(" + params + ")";
85
121
  }
86
122
 
87
123
  let methods = attrValue.split("),");
package/lib/htmlParser.js CHANGED
@@ -12,7 +12,8 @@ const handleEvents = require("./events");
12
12
  const handleCompPlaceholder = require("./compPlaceholder");
13
13
  const handleHtml = require("./html");
14
14
  const handleBoolAttrs = require("./boolAttr");
15
- const { RAW_OPEN, RAW_CLOSE, LT, GT } = require("./tokens");
15
+ const handleTextarea = require("./textarea");
16
+ const { RAW_OPEN, RAW_CLOSE, LT, GT, shieldTags, unshieldTags } = require("./tokens");
16
17
 
17
18
  function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
18
19
  let content = str.replace(script, "").replace(style, "");
@@ -24,9 +25,11 @@ function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
24
25
  // __olumAnon_ methods inside handleEvents (collected here, injected into the component JS later).
25
26
  const anonHandlers = [];
26
27
 
27
- // using dom parser
28
- 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;
29
31
  handleHtml(body); // html="expr" -> unescaped ${expr} content (before control-flow dissolves elements)
32
+ handleTextarea(body); // textarea value="..." -> text content (no value attribute exists on textarea)
30
33
  handleEvents(body, counter, filePath, anonHandlers, propsAliases);
31
34
  // DISABLED — :style object binding. Colon attributes are gone; use a string style with
32
35
  // {expr} interpolation instead, e.g. style="color:{state.color}". Uncomment to re-enable.
@@ -40,7 +43,7 @@ function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
40
43
  handleShowStatement(body, counter, filePath);
41
44
  const comps = handleCompPlaceholder(body, counter, filePath);
42
45
 
43
- content = body.innerHTML;
46
+ content = unshieldTags(body.innerHTML);
44
47
 
45
48
  // presence-based boolean attributes: checked="{expr}" -> ${(expr) ? "checked" : ""}.
46
49
  // Must run before the {expr} escape pass below, which would otherwise interpolate the VALUE
@@ -60,7 +63,10 @@ function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
60
63
  const raw = expr.trim();
61
64
  if (raw === "children") return "${children}";
62
65
  if (/^props\(\s*\)\.children$/.test(raw)) return "${" + raw + "}";
63
- 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 + ")}";
64
70
  });
65
71
 
66
72
  content = content.replace(/&amp;/g, "&"); // fix entity
package/lib/importMap.js CHANGED
@@ -63,6 +63,22 @@ function toPkgName(specifier) {
63
63
  return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
64
64
  }
65
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
+
66
82
  /**
67
83
  * Build the <script type="importmap"> tag injected into index.html so bare imports
68
84
  * (e.g. import { marked } from "marked") resolve in the browser without a bundler.
@@ -91,14 +107,8 @@ function importMap(srcDir) {
91
107
 
92
108
  getBareSpecifiers(srcDir).forEach((spec) => {
93
109
  const pkgName = toPkgName(spec);
94
- if (pkgName in localLibs || imports[pkgName]) return;
95
- const entry = resolvePackage(rootDir, pkgName);
96
- if (!entry) {
97
- console.warn(colors("yellow", 'Can\'t resolve "' + pkgName + '" — install it at the project root: npm i ' + pkgName));
98
- return;
99
- }
100
- imports[pkgName] = entry;
101
- imports[pkgName + "/"] = "/node_modules/" + pkgName + "/"; // subpath imports e.g. "pkg/x.js"
110
+ if (pkgName in localLibs) return;
111
+ addPackage(rootDir, pkgName, imports);
102
112
  });
103
113
  return '<script type="importmap">' + JSON.stringify({ imports }, null, 2) + "</script>";
104
114
  }
@@ -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/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.6",
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,21 @@ 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
+
173
196
  // boolean attributes are truthy by PRESENCE (checked="false" is still checked), so
174
197
  // attr="{expr}" must toggle the attribute's existence, never interpolate its value
175
198
  check(
@@ -216,13 +239,33 @@ check(
216
239
  comp(`<input oninput="setVal($event)" />`, `const setVal = (e) => 0;`),
217
240
  (out) => /oninput\|setVal=\$\{JSON\.stringify\(\['\$event'\]\)\}/.test(tmpl(out)) && parses(out)
218
241
  );
219
-
220
242
  check(
221
243
  "inline arrow handler becomes a named __olumAnon_ method",
222
244
  comp(`<input oninput="(e) => state.name = e.target.value" />`),
223
245
  (out) => /__olumAnon_\w+/.test(out) && /data-o-event/.test(tmpl(out)) && parses(out)
224
246
  );
225
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
+
226
269
  // ── §7 Conditionals <if>/<else-if>/<else> ──────────────────────────────────
227
270
  section("§7 Conditionals");
228
271
 
@@ -274,6 +317,20 @@ check(
274
317
  (out) => /data-o-key/.test(tmpl(out)) && parses(out)
275
318
  );
276
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
+
277
334
  // ── §10 Raw HTML (html="expr" + olum.html()) ───────────────────────────────
278
335
  section("§10 Raw HTML");
279
336
 
@@ -587,7 +644,7 @@ if (failed) {
587
644
 
588
645
  // Guard against a whole section silently disappearing (a bad merge, a `check` that
589
646
  // throws before registering, etc.). Bump EXPECTED_CHECKS when you add/remove tests.
590
- const EXPECTED_CHECKS = 51;
647
+ const EXPECTED_CHECKS = 58;
591
648
  const total = passed + failed;
592
649
  if (total !== EXPECTED_CHECKS) {
593
650
  console.log(yellow(`⚠ ran ${total} checks but expected ${EXPECTED_CHECKS} — did a test get dropped?`) + "\n");