olum-compiler 1.5.0 → 1.6.1

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/bin/build.js +1 -1
  2. package/bin/bundle.js +32 -30
  3. package/bin/compiler.js +20 -10
  4. package/bin/copySrc.js +45 -41
  5. package/bin/dev.js +46 -39
  6. package/bin/index.js +6 -3
  7. package/bin/server.js +58 -33
  8. package/bin/watcher.js +11 -14
  9. package/bin/ws.js +16 -11
  10. package/lib/attr.js +1 -25
  11. package/lib/boolAttr.js +32 -15
  12. package/lib/chokidar.js +52 -101
  13. package/lib/colors.js +1 -7
  14. package/lib/compPlaceholder.js +5 -3
  15. package/lib/compiler.js +3 -6
  16. package/lib/coreLibs.js +1 -10
  17. package/lib/cross-spawn.js +45 -59
  18. package/lib/cssParser.js +61 -37
  19. package/lib/domEvents.js +6 -2
  20. package/lib/events.js +75 -77
  21. package/lib/for.js +56 -28
  22. package/lib/getImports.js +35 -17
  23. package/lib/getTempPath.js +8 -4
  24. package/lib/helpers.js +289 -184
  25. package/lib/html.js +3 -10
  26. package/lib/htmlParser.js +45 -45
  27. package/lib/if.js +40 -20
  28. package/lib/importMap.js +49 -24
  29. package/lib/jsParser.js +8 -13
  30. package/lib/lineCounter.js +18 -5
  31. package/lib/liveProps.js +124 -78
  32. package/lib/log.js +30 -0
  33. package/lib/magic-string.js +45 -52
  34. package/lib/models.js +8 -7
  35. package/lib/parser.js +76 -44
  36. package/lib/placeholder.js +73 -58
  37. package/lib/regex.js +4 -3
  38. package/lib/show.js +16 -8
  39. package/lib/sourcemap.js +23 -24
  40. package/lib/styles.js +7 -13
  41. package/lib/textarea.js +3 -6
  42. package/lib/toJs.js +1 -1
  43. package/lib/tokens.js +10 -22
  44. package/lib/transition.js +86 -0
  45. package/lib/websocket.js +68 -62
  46. package/package.json +1 -1
  47. package/tests/compiler.test.js +423 -188
  48. package/.claude/settings.local.json +0 -12
@@ -1,13 +1,3 @@
1
- /**
2
- * spawn.js — standalone single-file port of cross-spawn@7.0.6 (MIT)
3
- * with its dependencies inlined: which@2.0.2, isexe@2.0.0, path-key@3.1.1,
4
- * shebang-command@2.0.0, shebang-regex@3.0.0 (all MIT).
5
- * Uses only node built-ins (child_process, fs, path).
6
- *
7
- * API (same as cross-spawn):
8
- * spawn(command, [args], [options]) → ChildProcess
9
- * spawn.sync(command, [args], [options]) → SpawnSyncReturns
10
- */
11
1
  "use strict";
12
2
 
13
3
  const cp = require("child_process");
@@ -15,21 +5,24 @@ const fs = require("fs");
15
5
  const path = require("path");
16
6
 
17
7
  const isWin = process.platform === "win32";
18
- // `which`/`isexe` treat cygwin/msys shells as windows too
19
- const isWindowsEnv = isWin || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
20
8
 
21
- // ---------------------------------------------------------------- path-key
9
+ const isWindowsEnv =
10
+ isWin || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
11
+
22
12
  function pathKey(options = {}) {
23
13
  const environment = options.env || process.env;
24
14
  const platform = options.platform || process.platform;
25
15
  if (platform !== "win32") return "PATH";
26
- return Object.keys(environment).reverse().find(key => key.toUpperCase() === "PATH") || "Path";
16
+ return (
17
+ Object.keys(environment)
18
+ .reverse()
19
+ .find((key) => key.toUpperCase() === "PATH") || "Path"
20
+ );
27
21
  }
28
22
 
29
- // ------------------------------------------------------------------- isexe
30
- // windows flavor: a file is executable if its extension is in PATHEXT
31
23
  function checkPathExt(file, options) {
32
- let pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT;
24
+ let pathext =
25
+ options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT;
33
26
  if (!pathext) return true;
34
27
  pathext = pathext.split(";");
35
28
  if (pathext.indexOf("") !== -1) return true;
@@ -58,26 +51,31 @@ function isexePosix(file) {
58
51
  const g = parseInt("010", 8);
59
52
  const o = parseInt("001", 8);
60
53
  const ug = u | g;
61
- return (mod & o) || (mod & g && gid === myGid) || (mod & u && uid === myUid) || (mod & ug && myUid === 0);
54
+ return (
55
+ mod & o ||
56
+ (mod & g && gid === myGid) ||
57
+ (mod & u && uid === myUid) ||
58
+ (mod & ug && myUid === 0)
59
+ );
62
60
  }
63
61
 
64
62
  function isexeSync(file, options) {
65
63
  return isWindowsEnv ? isexeWindows(file, options) : isexePosix(file);
66
64
  }
67
65
 
68
- // ------------------------------------------------------------------- which
69
66
  function getPathInfo(cmd, opt) {
70
67
  const colon = opt.colon || (isWindowsEnv ? ";" : ":");
71
68
 
72
- // if cmd has a slash, don't search PATH — check the file itself
73
- const pathEnv = cmd.match(/\//) || (isWindowsEnv && cmd.match(/\\/))
74
- ? [""]
75
- : [
76
- // windows always checks the cwd first
77
- ...(isWindowsEnv ? [process.cwd()] : []),
78
- ...(opt.path || process.env.PATH || "").split(colon),
79
- ];
80
- const pathExtExe = isWindowsEnv ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
69
+ const pathEnv =
70
+ cmd.match(/\//) || (isWindowsEnv && cmd.match(/\\/))
71
+ ? [""]
72
+ : [
73
+ ...(isWindowsEnv ? [process.cwd()] : []),
74
+ ...(opt.path || process.env.PATH || "").split(colon),
75
+ ];
76
+ const pathExtExe = isWindowsEnv
77
+ ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM"
78
+ : "";
81
79
  const pathExt = isWindowsEnv ? pathExtExe.split(colon) : [""];
82
80
 
83
81
  if (isWindowsEnv) {
@@ -102,7 +100,7 @@ function whichSync(cmd, opt) {
102
100
  const cur = p + pathExt[j];
103
101
  try {
104
102
  if (isexeSync(cur, { pathExt: pathExtExe })) return cur;
105
- } catch (ex) { /* Empty */ }
103
+ } catch (ex) {}
106
104
  }
107
105
  }
108
106
 
@@ -110,19 +108,18 @@ function whichSync(cmd, opt) {
110
108
  throw Object.assign(new Error("not found: " + cmd), { code: "ENOENT" });
111
109
  }
112
110
 
113
- // -------------------------------------------------- cross-spawn/lib/util/*
114
111
  function resolveCommandAttempt(parsed, withoutPathExt) {
115
112
  const env = parsed.options.env || process.env;
116
113
  const cwd = process.cwd();
117
114
  const hasCustomCwd = parsed.options.cwd != null;
118
- // worker threads do not have process.chdir()
119
- const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
120
115
 
121
- // `which` stats against the process cwd, so temporarily switch to the custom one
116
+ const shouldSwitchCwd =
117
+ hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
118
+
122
119
  if (shouldSwitchCwd) {
123
120
  try {
124
121
  process.chdir(parsed.options.cwd);
125
- } catch (err) { /* Empty */ }
122
+ } catch (err) {}
126
123
  }
127
124
 
128
125
  let resolved;
@@ -132,12 +129,13 @@ function resolveCommandAttempt(parsed, withoutPathExt) {
132
129
  path: env[pathKey({ env })],
133
130
  pathExt: withoutPathExt ? path.delimiter : undefined,
134
131
  });
135
- } catch (e) { /* Empty */ } finally {
132
+ } catch (e) {
133
+ } finally {
136
134
  if (shouldSwitchCwd) process.chdir(cwd);
137
135
  }
138
136
 
139
- // ensure an absolute path is returned (resolved against the custom cwd if any)
140
- if (resolved) resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
137
+ if (resolved)
138
+ resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
141
139
 
142
140
  return resolved;
143
141
  }
@@ -146,7 +144,6 @@ function resolveCommand(parsed) {
146
144
  return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
147
145
  }
148
146
 
149
- // shebang-command: "#!/usr/bin/env node" → "node", "#!/usr/bin/node -x" → "node -x"
150
147
  function shebangCommand(string = "") {
151
148
  const match = string.match(/^#!(.*)/);
152
149
  if (!match) return null;
@@ -159,7 +156,6 @@ function shebangCommand(string = "") {
159
156
  }
160
157
 
161
158
  function readShebang(command) {
162
- // read the first 150 bytes of the file
163
159
  const size = 150;
164
160
  const buffer = Buffer.alloc(size);
165
161
 
@@ -168,12 +164,11 @@ function readShebang(command) {
168
164
  fd = fs.openSync(command, "r");
169
165
  fs.readSync(fd, buffer, 0, size, 0);
170
166
  fs.closeSync(fd);
171
- } catch (e) { /* Empty */ }
167
+ } catch (e) {}
172
168
 
173
169
  return shebangCommand(buffer.toString());
174
170
  }
175
171
 
176
- // see http://www.robvanderwoude.com/escapechars.php
177
172
  const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
178
173
 
179
174
  function escapeCommand(arg) {
@@ -183,23 +178,18 @@ function escapeCommand(arg) {
183
178
  function escapeArgument(arg, doubleEscapeMetaChars) {
184
179
  arg = `${arg}`;
185
180
 
186
- // algorithm based on https://qntm.org/cmd, altered to avoid regex backtracking
187
- // sequence of backslashes followed by a double quote: double the backslashes, escape the quote
188
181
  arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
189
- // sequence of backslashes at the end (a double quote follows once wrapped): double them
182
+
190
183
  arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
191
184
 
192
- // quote the whole thing, then escape cmd.exe meta chars
193
185
  arg = `"${arg}"`;
194
186
  arg = arg.replace(metaCharsRegExp, "^$1");
195
187
 
196
- // cmd-shims are re-parsed by a second cmd.exe, so escape twice
197
188
  if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
198
189
 
199
190
  return arg;
200
191
  }
201
192
 
202
- // --------------------------------------------------- cross-spawn/lib/parse
203
193
  const isExecutableRegExp = /\.(?:com|exe)$/i;
204
194
  const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
205
195
 
@@ -222,31 +212,29 @@ function parseNonShell(parsed) {
222
212
 
223
213
  const commandFile = detectShebang(parsed);
224
214
 
225
- // no shell needed if the command resolved to a real executable (.com/.exe)
226
215
  const needsShell = !isExecutableRegExp.test(commandFile);
227
216
 
228
217
  if (parsed.options.forceShell || needsShell) {
229
- // cmd-shims in node_modules/.bin invoke a nested cmd.exe, requiring double escaping
230
218
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
231
219
 
232
- // normalize posix paths (foo/bar → foo\bar) or cmd.exe fails with ENOENT
233
220
  parsed.command = path.normalize(parsed.command);
234
221
 
235
222
  parsed.command = escapeCommand(parsed.command);
236
- parsed.args = parsed.args.map(arg => escapeArgument(arg, needsDoubleEscapeMetaChars));
223
+ parsed.args = parsed.args.map((arg) =>
224
+ escapeArgument(arg, needsDoubleEscapeMetaChars),
225
+ );
237
226
 
238
227
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
239
228
 
240
229
  parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
241
230
  parsed.command = process.env.comspec || "cmd.exe";
242
- parsed.options.windowsVerbatimArguments = true; // args are already escaped
231
+ parsed.options.windowsVerbatimArguments = true;
243
232
  }
244
233
 
245
234
  return parsed;
246
235
  }
247
236
 
248
237
  function parse(command, args, options) {
249
- // normalize arguments, similar to nodejs
250
238
  if (args && !Array.isArray(args)) {
251
239
  options = args;
252
240
  args = null;
@@ -266,7 +254,6 @@ function parse(command, args, options) {
266
254
  return options.shell ? parsed : parseNonShell(parsed);
267
255
  }
268
256
 
269
- // -------------------------------------------------- cross-spawn/lib/enoent
270
257
  function notFoundError(original, syscall) {
271
258
  return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
272
259
  code: "ENOENT",
@@ -277,10 +264,9 @@ function notFoundError(original, syscall) {
277
264
  });
278
265
  }
279
266
 
280
- // on windows a missing command exits cmd.exe with status 1 instead of erroring;
281
- // convert that into the ENOENT error posix would have produced
282
267
  function verifyENOENT(status, parsed, syscall) {
283
- if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, syscall);
268
+ if (isWin && status === 1 && !parsed.file)
269
+ return notFoundError(parsed.original, syscall);
284
270
  return null;
285
271
  }
286
272
 
@@ -297,7 +283,6 @@ function hookChildProcess(child, parsed) {
297
283
  };
298
284
  }
299
285
 
300
- // ------------------------------------------------------- cross-spawn/index
301
286
  function spawn(command, args, options) {
302
287
  const parsed = parse(command, args, options);
303
288
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
@@ -308,7 +293,8 @@ function spawn(command, args, options) {
308
293
  function spawnSync(command, args, options) {
309
294
  const parsed = parse(command, args, options);
310
295
  const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
311
- result.error = result.error || verifyENOENT(result.status, parsed, "spawnSync");
296
+ result.error =
297
+ result.error || verifyENOENT(result.status, parsed, "spawnSync");
312
298
  return result;
313
299
  }
314
300
 
package/lib/cssParser.js CHANGED
@@ -1,28 +1,35 @@
1
1
  const { style } = require("./regex");
2
2
 
3
3
  function escapeRe(str) {
4
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
5
  }
6
6
 
7
- // Rename @keyframes declarations and all their animation/animation-name references
8
- // to <name>-<compName> so same-named keyframes in different components don't collide.
9
7
  function renameKeyframes(css, compName) {
10
8
  const names = [];
11
9
  css.replace(/@keyframes\s+([\w-]+)/g, (_, name) => names.push(name));
12
10
  if (!names.length) return css;
13
- names.forEach(name => {
11
+ names.forEach((name) => {
14
12
  const re = escapeRe(name);
15
13
  const newName = name + "-" + compName;
16
- css = css.replace(new RegExp(`(@keyframes\\s+)${re}\\b`, "g"), "$1" + newName);
17
- css = css.replace(new RegExp(`(animation-name\\s*:[^;{]*)\\b${re}\\b`, "g"), "$1" + newName);
18
- css = css.replace(new RegExp(`(animation\\s*:[^;{]*)\\b${re}\\b`, "g"), "$1" + newName);
14
+ css = css.replace(
15
+ new RegExp(`(@keyframes\\s+)${re}\\b`, "g"),
16
+ "$1" + newName,
17
+ );
18
+ css = css.replace(
19
+ new RegExp(`(animation-name\\s*:[^;{]*)\\b${re}\\b`, "g"),
20
+ "$1" + newName,
21
+ );
22
+ css = css.replace(
23
+ new RegExp(`(animation\\s*:[^;{]*)\\b${re}\\b`, "g"),
24
+ "$1" + newName,
25
+ );
19
26
  });
20
27
  return css;
21
28
  }
22
29
 
23
30
  function scopeCSS(css, scopeAttr, compName) {
24
31
  css = renameKeyframes(css, compName);
25
- css = css.replace(/\/\*[\s\S]*?\*\//g, ""); // strip comments
32
+ css = css.replace(/\/\*[\s\S]*?\*\//g, "");
26
33
 
27
34
  const scope = `[data-o-${scopeAttr}]`;
28
35
  let out = "";
@@ -33,11 +40,18 @@ function scopeCSS(css, scopeAttr, compName) {
33
40
  }
34
41
 
35
42
  function readBlock() {
36
- let depth = 1, content = "";
37
- i++; // skip opening {
43
+ let depth = 1,
44
+ content = "";
45
+ i++;
38
46
  while (i < css.length && depth > 0) {
39
47
  if (css[i] === "{") depth++;
40
- else if (css[i] === "}") { depth--; if (depth === 0) { i++; break; } }
48
+ else if (css[i] === "}") {
49
+ depth--;
50
+ if (depth === 0) {
51
+ i++;
52
+ break;
53
+ }
54
+ }
41
55
  if (depth > 0) content += css[i];
42
56
  i++;
43
57
  }
@@ -45,31 +59,40 @@ function scopeCSS(css, scopeAttr, compName) {
45
59
  }
46
60
 
47
61
  function scopeSelectors(sel) {
48
- return sel.split(",").map(s => {
49
- s = s.trim();
50
- if (!s) return "";
51
- if (/^(:root|html|body)\b/.test(s)) return s;
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);
72
- }).filter(Boolean).join(", ");
62
+ return sel
63
+ .split(",")
64
+ .map((s) => {
65
+ s = s.trim();
66
+ if (!s) return "";
67
+ if (/^(:root|html|body)\b/.test(s)) return s;
68
+
69
+ let depth = 0,
70
+ start = 0;
71
+ for (let j = 0; j < s.length; j++) {
72
+ const c = s[j];
73
+ if (c === "(" || c === "[") depth++;
74
+ else if (c === ")" || c === "]") depth--;
75
+ else if (
76
+ depth === 0 &&
77
+ (c === " " || c === ">" || c === "+" || c === "~")
78
+ )
79
+ start = j + 1;
80
+ }
81
+ const compound = s.slice(start);
82
+ let k = 0;
83
+ depth = 0;
84
+ for (; k < compound.length; k++) {
85
+ const c = compound[k];
86
+ if (c === "(" || c === "[") depth++;
87
+ else if (c === ")" || c === "]") depth--;
88
+ else if (c === ":" && depth === 0) break;
89
+ }
90
+ return (
91
+ s.slice(0, start) + compound.slice(0, k) + scope + compound.slice(k)
92
+ );
93
+ })
94
+ .filter(Boolean)
95
+ .join(", ");
73
96
  }
74
97
 
75
98
  while (i < css.length) {
@@ -99,7 +122,8 @@ function cssParser(str, scopeAttr, compName) {
99
122
  content = content.replace(/(<style.*?>)/, "");
100
123
  content = content.replace(/(<\/style>)$/, "");
101
124
  content = content.trim();
102
- if (scopeAttr && compName && content) content = scopeCSS(content, scopeAttr, compName);
125
+ if (scopeAttr && compName && content)
126
+ content = scopeCSS(content, scopeAttr, compName);
103
127
  return "__style__() { return `" + content + "`;},\n";
104
128
  }
105
129
 
package/lib/domEvents.js CHANGED
@@ -108,5 +108,9 @@ module.exports = [
108
108
  "ondevicemotion",
109
109
  "ondeviceorientation",
110
110
  "ondeviceorientationabsolute",
111
- "onpointerrawupdate"
112
- ];
111
+ "onpointerrawupdate",
112
+ "ontouchstart",
113
+ "ontouchmove",
114
+ "ontouchend",
115
+ "ontouchcancel",
116
+ ];
package/lib/events.js CHANGED
@@ -2,35 +2,25 @@ const events = require("./domEvents");
2
2
  const { getLineInfo } = require("./lineCounter");
3
3
  const path = require("path");
4
4
 
5
- // An event value is plain JS inside "" (like native HTML `onclick="..."`): either a method-call
6
- // list — onclick="inc()" / onclick="inc(), dec()" — or an inline arrow/function expression —
7
- // oninput="(e)=> state.x = e.target.value". Arrow/function values are extracted to a named
8
- // __olumAnon_ method (collected in anonHandlers, injected into the component JS) so the call-list
9
- // parser below can treat them uniformly as `__olumAnon_xxx($event)`.
10
5
  function looksLikeFunction(str) {
11
6
  return /^(?:\([^)]*\)|[\w$]+)\s*=>/.test(str) || /^function\b/.test(str);
12
7
  }
13
8
 
14
- // True when the value is a plain call list the legacy parser can split — one or more
15
- // `name(args)` calls where each callee is a bare identifier: onclick="inc()" / "inc(), dec()".
16
- // Anything else (props().toggle(id), state.count++, obj.method()) must run as a real JS
17
- // expression, so the caller wraps it in an anonymous handler instead.
18
9
  function isSimpleCallList(str) {
19
10
  try {
20
11
  const acorn = require("acorn");
21
12
  const node = acorn.parseExpressionAt(str, 0, { ecmaVersion: "latest" });
22
13
  if (node.end !== str.length) return false;
23
- const calls = node.type === "SequenceExpression" ? node.expressions : [node];
24
- return calls.every((c) => c.type === "CallExpression" && c.callee.type === "Identifier");
14
+ const calls =
15
+ node.type === "SequenceExpression" ? node.expressions : [node];
16
+ return calls.every(
17
+ (c) => c.type === "CallExpression" && c.callee.type === "Identifier",
18
+ );
25
19
  } catch (e) {
26
- return true; // unparseable as a single expression -> let the legacy splitter have it
20
+ return true;
27
21
  }
28
22
  }
29
23
 
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
24
  function referencesPropsAlias(str, propsAliases) {
35
25
  const names = propsAliases ? Object.keys(propsAliases) : [];
36
26
  if (!names.length) return false;
@@ -41,15 +31,20 @@ function referencesPropsAlias(str, propsAliases) {
41
31
  (function walk(n, parent, key) {
42
32
  if (found || !n || typeof n.type !== "string") return;
43
33
  if (n.type === "Identifier" && names.includes(n.name)) {
44
- // skip non-value positions: obj.onclick (member property) / { onclick: x } (literal key)
45
34
  const isStaticProp =
46
- parent && !parent.computed && ((parent.type === "MemberExpression" && key === "property") || (parent.type === "Property" && key === "key"));
35
+ parent &&
36
+ !parent.computed &&
37
+ ((parent.type === "MemberExpression" && key === "property") ||
38
+ (parent.type === "Property" && key === "key"));
47
39
  if (!isStaticProp) found = true;
48
40
  return;
49
41
  }
50
42
  for (const k of Object.keys(n)) {
51
43
  const v = n[k];
52
- if (Array.isArray(v)) v.forEach((item) => item && typeof item === "object" && walk(item, n, k));
44
+ if (Array.isArray(v))
45
+ v.forEach(
46
+ (item) => item && typeof item === "object" && walk(item, n, k),
47
+ );
53
48
  else if (v && typeof v === "object") walk(v, n, k);
54
49
  }
55
50
  })(node, null, null);
@@ -59,103 +54,106 @@ function referencesPropsAlias(str, propsAliases) {
59
54
  }
60
55
  }
61
56
 
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
57
  function loopVarNames(item) {
66
58
  const vars = [];
67
59
  let cur = item;
68
60
  while ((cur = cur.parentElement)) {
69
61
  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
- });
62
+ const m = cur
63
+ .getAttribute("each")
64
+ .trim()
65
+ .match(/(.*)( of | in )/);
66
+ if (m)
67
+ m[1]
68
+ .replace(/\(|\)/g, "")
69
+ .split(",")
70
+ .forEach((p) => {
71
+ p = p.trim();
72
+ if (p && !vars.includes(p)) vars.push(p);
73
+ });
75
74
  }
76
75
  }
77
76
  return vars;
78
77
  }
79
78
 
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
79
  function usedLoopVars(str, item) {
84
- return loopVarNames(item).filter((v) => new RegExp("(?<![.\\w$])" + v + "\\b").test(str));
80
+ return loopVarNames(item).filter((v) =>
81
+ new RegExp("(?<![.\\w$])" + v + "\\b").test(str),
82
+ );
85
83
  }
86
84
 
87
85
  function handleEvents(body, counter, filePath, anonHandlers, propsAliases) {
88
86
  let name = path.basename(filePath).replace(/\.html/i, "");
89
- name = name.slice(0, 1).toLowerCase() + name.slice(1); // make compName camel case
87
+ name = name.slice(0, 1).toLowerCase() + name.slice(1);
90
88
 
91
89
  const elms = new Array().slice.call(body.querySelectorAll("*"));
92
- elms.forEach(item => {
93
- events.forEach(e => {
90
+ elms.forEach((item) => {
91
+ events.forEach((e) => {
94
92
  if (item.hasAttribute(e)) {
95
93
  let attrValue = item.getAttribute(e).trim();
96
94
 
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
95
  const loopArgs = usedLoopVars(attrValue, item);
103
96
  const params = ["$event"].concat(loopArgs).join(", ");
104
97
 
105
- // inline arrow/function handler -> extract to a named method, then parse the call below
106
98
  if (looksLikeFunction(attrValue)) {
107
- const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
99
+ const handlerName =
100
+ "__olumAnon_" + Math.random().toString(36).slice(2, 9);
108
101
  if (anonHandlers) {
109
- if (loopArgs.length) anonHandlers.push(`const ${handlerName} = (${params}) => (${attrValue})($event);`);
102
+ if (loopArgs.length)
103
+ anonHandlers.push(
104
+ `const ${handlerName} = (${params}) => (${attrValue})($event);`,
105
+ );
110
106
  else anonHandlers.push(`const ${handlerName} = ${attrValue};`);
111
107
  }
112
108
  attrValue = handlerName + "(" + params + ")";
113
- } else if (!isSimpleCallList(attrValue) || referencesPropsAlias(attrValue, propsAliases)) {
114
- // not a plain `name(args)` call list — e.g. a function prop call props().toggle(id)
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
117
- // so it executes as-is in component scope ($event = the DOM event)
118
- const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
119
- if (anonHandlers) anonHandlers.push(`const ${handlerName} = (${params}) => { ${attrValue} };`);
109
+ } else if (
110
+ !isSimpleCallList(attrValue) ||
111
+ referencesPropsAlias(attrValue, propsAliases)
112
+ ) {
113
+ const handlerName =
114
+ "__olumAnon_" + Math.random().toString(36).slice(2, 9);
115
+ if (anonHandlers)
116
+ anonHandlers.push(
117
+ `const ${handlerName} = (${params}) => { ${attrValue} };`,
118
+ );
120
119
  attrValue = handlerName + "(" + params + ")";
121
120
  }
122
121
 
123
122
  let methods = attrValue.split("),");
124
- methods = methods.map(str => (str.replace(/\)$/, "") + ")").trim());
125
- let methodsNames = methods.map(str => (str.trim().split("(")[0]).trim());
126
- // args = everything between the FIRST "(" and the LAST ")", so arguments that themselves
127
- // contain parens (e.g. toggle(props().todo.id)) aren't truncated at the inner "(".
128
- let methodsArgs = methods.map(str => {
123
+ methods = methods.map((str) => (str.replace(/\)$/, "") + ")").trim());
124
+ let methodsNames = methods.map((str) =>
125
+ str.trim().split("(")[0].trim(),
126
+ );
127
+
128
+ let methodsArgs = methods.map((str) => {
129
129
  const s = str.trim();
130
130
  return s.slice(s.indexOf("(") + 1, s.lastIndexOf(")")).trim();
131
131
  });
132
-
132
+
133
133
  function handle$event(str) {
134
- return str.replace(/\$event/g, "'$event'")
134
+ return str.replace(/\$event/g, "'$event'");
135
135
  }
136
-
137
- // added special delimiters for json in attribute to overcome double quotes issue -[[- , -]]-
138
- let chain = e+"|"
136
+
137
+ let chain = e + "|";
139
138
  methodsNames.forEach((item, index) => {
140
- if (index === methodsNames.length - 1) return chain += item + "=${JSON.stringify([" + handle$event(methodsArgs[index]) +"])}-]]-"
141
- chain += item + "=${JSON.stringify([" + handle$event(methodsArgs[index]) + "])}&";
142
- })
143
-
144
- chain = chain.replace(/{/g, "&lt;-olum-&gt;") // using <-olum-> (&lt;-olum-&gt;) as placeholder for "{"
145
- // console.log({chain});
146
- item.setAttribute("data-o-event", "-[[-"+chain);
139
+ if (index === methodsNames.length - 1)
140
+ return (chain +=
141
+ item +
142
+ "=${JSON.stringify([" +
143
+ handle$event(methodsArgs[index]) +
144
+ "])}-]]-");
145
+ chain +=
146
+ item +
147
+ "=${JSON.stringify([" +
148
+ handle$event(methodsArgs[index]) +
149
+ "])}&";
150
+ });
151
+
152
+ chain = chain.replace(/{/g, "&lt;-olum-&gt;");
153
+
154
+ const prevEvent = item.getAttribute("data-o-event") || "";
155
+ item.setAttribute("data-o-event", prevEvent + "-[[-" + chain);
147
156
  item.removeAttribute(e);
148
- // console.log(item.outerHTML);
149
-
150
- // DISABLED — `mode` event modifiers (mode="prevent|stop|once|passive|capture|self").
151
- // Handle it inside the arrow instead, e.g. onsubmit="(e)=> { e.preventDefault(); save() }".
152
- // Uncomment to re-enable. (The runtime data-o-event-mode reader in app.js is now dead code.)
153
- // const mode = item.getAttribute("mode");
154
- // if (mode) {
155
- // item.setAttribute("data-o-event-mode", mode);
156
- // item.removeAttribute("mode");
157
- // }
158
- // console.log(item.outerHTML + "\n----------");
159
157
  }
160
158
  });
161
159
  });