olum-compiler 1.7.1 → 1.8.2

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.
@@ -0,0 +1,11 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(npm test *)",
5
+ "Bash(node *)",
6
+ "Bash(sed -i 's|require\\(\"./helpers\"\\)|require\\(\"/home/eissapk/olum/compiler/lib/helpers\"\\)|' \"/tmp/claude-1000/-home-eissapk-olum-compiler/3f440c76-2772-4edd-891c-d2dfdb356243/scratchpad/placeholder.old.js\")",
7
+ "Bash(sed \"s|lib/placeholder\\\\\"\\)|../../../../../tmp/claude-1000/-home-eissapk-olum-compiler/3f440c76-2772-4edd-891c-d2dfdb356243/scratchpad/placeholder.old.js\\\\\"\\)|\" \"/tmp/claude-1000/-home-eissapk-olum-compiler/3f440c76-2772-4edd-891c-d2dfdb356243/scratchpad/probe.js\")",
8
+ "Bash(echo \"--- exit: $? ---\")"
9
+ ]
10
+ }
11
+ }
package/bin/copySrc.js CHANGED
@@ -2,11 +2,20 @@ const path = require("path");
2
2
  const fs = require("fs");
3
3
  const { copy, compileRoutes } = require("../lib/helpers");
4
4
  const importMap = require("../lib/importMap");
5
+ const usage = require("../lib/usage");
5
6
 
6
7
  const cwd = process.cwd();
7
8
  const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src");
8
9
  const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public");
9
10
 
11
+ const devtoolSrc = path.resolve(
12
+ cwd.replace(/\/module$/, ""),
13
+ "node_modules/olum-devtool/dist",
14
+ );
15
+ const devtoolScript = path.resolve(devtoolSrc, "./script.js");
16
+ const devtoolEnabled =
17
+ process.env.NODE_ENV === "development" && fs.existsSync(devtoolScript);
18
+
10
19
  const srcDest = path.resolve(__dirname, "../src");
11
20
  const publicDest = path.resolve(__dirname, "../public");
12
21
  const indexHtmlDest = path.resolve(__dirname, "../public/index.html");
@@ -14,12 +23,15 @@ const mainJsPathDest = path.resolve(__dirname, "../src/main.js");
14
23
 
15
24
  function injectIndexHtml(indexHtmlPath) {
16
25
  let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
26
+ const devtoolScriptContent = devtoolEnabled
27
+ ? "<script>" + fs.readFileSync(devtoolScript).toString() + "</script>\n"
28
+ : "";
17
29
 
18
30
  const importMapTag =
19
31
  process.env.NODE_ENV === "production" ? "" : `${importMap(entryPoint)}\n`;
20
32
  indexHtmlContent = indexHtmlContent.replace(
21
33
  /<\/body>/,
22
- `\n<div id="app"></div>\n${importMapTag}<script defer type="module" src="../src/main.js"></script>\n</body>`,
34
+ `\n<div id="app"></div>\n${importMapTag}<script defer type="module" src="../src/main.js"></script>\n${devtoolScriptContent}</body>`,
23
35
  );
24
36
  fs.writeFileSync(indexHtmlPath, indexHtmlContent);
25
37
  }
@@ -42,8 +54,10 @@ function syncFile(event, file) {
42
54
  : path.join(publicDest, path.relative(entryPoint2, file));
43
55
  if (event.startsWith("unlink")) {
44
56
  fs.rmSync(dest, { recursive: true, force: true });
45
- if (inSrc && dest.endsWith(".html"))
57
+ if (inSrc && dest.endsWith(".html")) {
46
58
  fs.rmSync(dest.replace(/\.html$/, ".js"), { force: true });
59
+ usage.drop(dest);
60
+ }
47
61
  } else {
48
62
  fs.mkdirSync(path.dirname(dest), { recursive: true });
49
63
  fs.copyFileSync(file, dest);
@@ -75,6 +89,14 @@ module.exports = function copySrc(event, file) {
75
89
  copy(entryPoint, srcDest, () => handleMainJs());
76
90
  copy(entryPoint2, publicDest, () => injectIndexHtml(indexHtmlDest));
77
91
 
92
+ if (devtoolEnabled) {
93
+ fs.mkdirSync(publicDest + "/__olum_devtool", {
94
+ recursive: true,
95
+ force: true,
96
+ });
97
+ copy(devtoolSrc, publicDest + "/__olum_devtool");
98
+ }
99
+
78
100
  resolve(null);
79
101
  } catch (err) {
80
102
  reject(err);
package/bin/dev.js CHANGED
@@ -7,8 +7,49 @@ const colors = require("../lib/colors");
7
7
  const path = require("path");
8
8
  const fs = require("fs");
9
9
 
10
- let instance;
10
+ let sockets;
11
11
  const entryPoint = path.resolve(__dirname, "../public");
12
+
13
+ const lockFile = path.resolve(__dirname, "../.dev.lock");
14
+ const me = String(process.pid);
15
+ const read = () => {
16
+ try {
17
+ return fs.readFileSync(lockFile, "utf8").trim();
18
+ } catch (e) {
19
+ return "";
20
+ }
21
+ };
22
+ const alive = (pid) => {
23
+ try {
24
+ return !!process.kill(pid, 0);
25
+ } catch (e) {
26
+ return e.code === "EPERM";
27
+ }
28
+ };
29
+
30
+ const holder = Number(read());
31
+ if (holder && holder !== process.pid && alive(holder)) {
32
+ console.error(
33
+ colors(
34
+ "red",
35
+ `A dev server for this project is already running (pid ${holder}).`,
36
+ ),
37
+ );
38
+ console.error(
39
+ colors(
40
+ "white",
41
+ `Stop it first — two of them share one build output and will overwrite each other's work.\n kill ${holder} # or delete ${lockFile} if that process is gone`,
42
+ ),
43
+ );
44
+ process.exit(1);
45
+ }
46
+
47
+ fs.writeFileSync(lockFile, me);
48
+ process.on("exit", () => read() === me && fs.rmSync(lockFile, { force: true }));
49
+ ["SIGINT", "SIGTERM", "SIGHUP"].forEach((signal) =>
50
+ process.on(signal, () => process.exit(0)),
51
+ );
52
+
12
53
  serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
13
54
  const bootAt = Date.now();
14
55
  copySrc()
@@ -31,34 +72,32 @@ serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
31
72
 
32
73
  (function startWs(port) {
33
74
  const wss = new WebSocket.Server({ server });
75
+ sockets = wss.clients;
34
76
  wss.on("listening", () => setWsPort(port));
35
77
  wss.on("error", (e) => {
36
78
  if (e.code === "EADDRINUSE") startWs(port + 1);
37
79
  });
38
- wss.on("connection", (ws) => {
39
- instance = ws;
40
- ws.send(JSON.stringify({ msg: "connected" }));
41
- });
80
+ wss.on("connection", (ws) =>
81
+ ws.send(JSON.stringify({ msg: "connected" })),
82
+ );
42
83
  })(wsPort);
43
84
  });
44
85
  })
45
86
  .catch(console.error);
46
87
  });
47
88
 
89
+ const send = (data) =>
90
+ sockets && sockets.forEach((ws) => ws.send(JSON.stringify(data)));
91
+
92
+ const logFile = path.resolve(__dirname, "../lib/log.txt");
48
93
  function getLogs() {
49
- const logFilePath = path.resolve(__dirname, "../lib/log.txt");
50
- if (fs.existsSync(logFilePath)) {
51
- return fs.readFileSync(logFilePath).toString();
52
- } else {
53
- return null;
54
- }
94
+ return fs.existsSync(logFile) ? fs.readFileSync(logFile).toString() : null;
55
95
  }
56
96
 
57
- const send = (data) => instance && instance.send(JSON.stringify(data));
58
-
59
97
  function notify() {
60
98
  const logs = getLogs();
61
- logs ? send({ msg: "warn", data: logs }) : send({ msg: "reload" });
99
+
100
+ send(logs && logs.trim() ? { msg: "warn", data: logs } : { msg: "reload" });
62
101
  }
63
102
 
64
103
  const isComp = (dest) =>
package/bin/server.js CHANGED
@@ -72,8 +72,34 @@ function serve(entry, port, mode = "development") {
72
72
  });
73
73
  }
74
74
 
75
+ function serveDevtools() {
76
+ const devtoolsPath = path.join(entry, "__olum_devtool", "index.html");
77
+
78
+ fs.readFile(devtoolsPath, (err, content) => {
79
+ if (err) {
80
+ res.writeHead(404, { "content-type": "text/plain" });
81
+ res.end("404 Not Found: " + urlPath);
82
+ return;
83
+ }
84
+ const dom = parseDOM(content.toString());
85
+ const html = dom.querySelector("html");
86
+ if (mode == "development") {
87
+ const wsContent = handleWsFile();
88
+ dom.body.insertAdjacentHTML("beforeend", wsContent);
89
+ }
90
+ res.writeHead(200, {
91
+ "content-type": "text/html",
92
+ "cache-control": "no-cache",
93
+ });
94
+ res.end("<!DOCTYPE html>" + html.outerHTML);
95
+ });
96
+ }
97
+
75
98
  if (urlPath === "/") return serveIndex();
76
99
 
100
+ if (urlPath === "/__olum_devtool" || urlPath === "/__olum_devtool/")
101
+ return serveDevtools();
102
+
77
103
  const finalPath = getPath(entry, urlPath);
78
104
  if (finalPath && fs.statSync(finalPath).isFile()) {
79
105
  const ext = path.extname(finalPath).toLowerCase();
package/bin/ws.js CHANGED
@@ -1,61 +1,67 @@
1
1
  (() => {
2
- if ("WebSocket" in window) {
3
- const parse = (str) => str.replace(/>/g, "&gt;").replace(/</g, "&lt;");
4
- const interval = 500;
5
- const maxAttempts = 30;
6
- let attempts = 0;
7
- const wsProtocol = location.protocol === "https:" ? "wss:" : "ws:";
2
+ if (!("WebSocket" in window))
3
+ return console.error(
4
+ "Upgrade your browser. This Browser is doesn't support WebSocket for Live-Reloading.",
5
+ );
8
6
 
9
- const socketUrl = `${wsProtocol}//${location.host}`;
10
- let socket = new WebSocket(socketUrl);
7
+ const url = `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}`;
8
+ const esc = (str) => str.replace(/>/g, "&gt;").replace(/</g, "&lt;");
9
+ const retry = 500;
10
+ const maxAttempts = 30;
11
+ let attempts = 0;
12
+ let dropped = false;
11
13
 
12
- socket.onmessage = function (res) {
13
- const obj = JSON.parse(res.data);
14
- if (obj.msg === "connected") enabled();
15
- if (obj.msg === "reload") window.location.reload();
16
- else if (obj.msg === "css") css();
17
- else if (obj.msg === "warn") {
18
- const stderr = obj.data.trim();
19
- const arr = stderr.split("<<Olum Warning>>");
20
- const markup = arr
21
- .map((item) => {
22
- if (item.trim() !== "")
23
- return `<pre style="border-bottom: 1px solid #ccc; padding-bottom:10px;">${parse(item)}</pre>`;
24
- })
25
- .join("");
26
- document.body.innerHTML = markup;
27
- }
28
- };
14
+ const show = (data) => {
15
+ const blocks = data
16
+ .split("<<Olum Warning>>")
17
+ .map((item) => item.trim())
18
+ .filter(Boolean);
19
+ if (!blocks.length) return;
29
20
 
30
- function enabled() {
31
- let key = "IS_FIRST_TIME_OLUM_HOT_RELOAD";
32
- if (sessionStorage && !sessionStorage.getItem(key)) {
33
- sessionStorage.setItem(key, true);
21
+ const box =
22
+ document.getElementById("olum-warning") ||
23
+ document.body.appendChild(document.createElement("div"));
24
+ box.id = "olum-warning";
25
+ box.style.cssText =
26
+ "position:fixed;top:0;left:0;right:0;z-index:2147483001;max-height:60vh;overflow:auto;padding:12px 16px;" +
27
+ "background:#1c1917;color:#fde68a;box-shadow:0 2px 12px rgba(0,0,0,.35);font:12px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace";
28
+ box.innerHTML =
29
+ '<button style="float:right;border:0;background:none;color:inherit;font:inherit;cursor:pointer">dismiss ✕</button>' +
30
+ blocks
31
+ .map(
32
+ (item) =>
33
+ `<pre style="margin:0 0 8px;white-space:pre-wrap">${esc(item)}</pre>`,
34
+ )
35
+ .join("");
36
+ box.querySelector("button").onclick = () => box.remove();
37
+ };
34
38
 
35
- console.log("Olum hot-reload enabled.");
36
- }
37
- }
39
+ const enabled = () => {
40
+ const key = "IS_FIRST_TIME_OLUM_HOT_RELOAD";
41
+ if (!sessionStorage || sessionStorage.getItem(key)) return;
42
+ sessionStorage.setItem(key, true);
43
+ console.log("Olum hot-reload enabled.");
44
+ };
38
45
 
39
- function css() {
40
- const sheets = document.querySelectorAll("link[rel='stylesheet']");
41
- sheets.forEach((sheet) => sheet.replaceWith(sheet));
42
- }
46
+ const attach = (socket) => {
47
+ socket.onopen = () => (dropped ? location.reload() : (attempts = 0));
48
+ socket.onmessage = (event) => {
49
+ const { msg, data } = JSON.parse(event.data);
50
+ if (msg === "connected") enabled();
51
+ else if (msg === "reload") location.reload();
52
+ else if (msg === "css")
53
+ document
54
+ .querySelectorAll("link[rel='stylesheet']")
55
+ .forEach((sheet) => sheet.replaceWith(sheet));
56
+ else if (msg === "warn") show(data);
57
+ };
58
+ socket.onclose = () => {
59
+ dropped = true;
60
+ if (++attempts > maxAttempts)
61
+ return console.error("Could not reconnect to dev server.");
62
+ setTimeout(() => attach(new WebSocket(url)), retry);
63
+ };
64
+ };
43
65
 
44
- socket.addEventListener("close", () => {
45
- const reloadIfCanConnect = () => {
46
- attempts++;
47
- if (attempts > maxAttempts)
48
- return console.error("Could not reconnect to dev server.");
49
- socket = new WebSocket(socketUrl);
50
- socket.addEventListener("error", () =>
51
- setTimeout(reloadIfCanConnect, interval),
52
- );
53
- };
54
- reloadIfCanConnect();
55
- });
56
- } else {
57
- console.error(
58
- "Upgrade your browser. This Browser is doesn't support WebSocket for Live-Reloading.",
59
- );
60
- }
66
+ attach(new WebSocket(url));
61
67
  })();
package/lib/htmlParser.js CHANGED
@@ -1,5 +1,4 @@
1
1
  const { parseDOM } = require("./dom");
2
- const { selfClosingTag, normalTag } = require("./regex");
3
2
  const placeholder = require("./placeholder");
4
3
  const handleIfStatement = require("./if");
5
4
  const handleForStatement = require("./for");
@@ -23,20 +22,7 @@ const {
23
22
  } = require("./tokens");
24
23
 
25
24
  function htmlparser(content, counter, filePath, parentMethods, propsAliases) {
26
- content = placeholder(
27
- content,
28
- selfClosingTag,
29
- "self",
30
- parentMethods,
31
- propsAliases,
32
- );
33
- content = placeholder(
34
- content,
35
- normalTag,
36
- "normal",
37
- parentMethods,
38
- propsAliases,
39
- );
25
+ content = placeholder(content, parentMethods, propsAliases);
40
26
 
41
27
  const anonHandlers = [];
42
28
 
package/lib/parser.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const isDev = true;
2
+
2
3
  const splitSFC = require("./sfc");
3
4
  const htmlParser = require("./htmlParser");
4
5
  const cssParser = require("./cssParser");
@@ -17,6 +18,7 @@ const {
17
18
  } = require("./helpers");
18
19
  const createSourceMap = require("./sourcemap");
19
20
  const liveProps = require("./liveProps");
21
+ const usage = require("./usage");
20
22
 
21
23
  const parser = (str, counter, filePath) => {
22
24
  const sfc = splitSFC(str);
@@ -108,6 +110,27 @@ const parser = (str, counter, filePath) => {
108
110
  const scopedProps = handleScope(globalProps, "props");
109
111
  const scopedMethods = handleScope(globalMethods, "methods");
110
112
 
113
+ if (process.env.NODE_ENV === "development") {
114
+ try {
115
+ const children = [];
116
+ (comps || []).forEach((name) => {
117
+ const hit = (imports || []).find((item) =>
118
+ new RegExp("\\b" + name + "\\b").test(item.statement),
119
+ );
120
+ const spec =
121
+ hit && (hit.statement.match(/from\s+["'](.+?)["']/) || [])[1];
122
+ if (!spec || !spec.startsWith(".")) return;
123
+ const child = usage.relative(
124
+ path
125
+ .resolve(path.dirname(filePath), spec)
126
+ .replace(/\.(js|html)$/, "") + ".html",
127
+ );
128
+ if (!children.includes(child)) children.push(child);
129
+ });
130
+ usage.record(filePath, children);
131
+ } catch (e) {}
132
+ }
133
+
111
134
  if (imports) imports = imports.map((item) => toJs(item.statement));
112
135
 
113
136
  function mkComponentsList(comps) {
@@ -149,6 +172,7 @@ const parser = (str, counter, filePath) => {
149
172
  methods: ${scopedMethods},
150
173
  props: ${scopedProps},
151
174
  compName: "${compName}",
175
+ ${process.env.NODE_ENV === "development" ? `file: ${JSON.stringify(usage.relative(filePath))},` : ""}
152
176
  deps: ${templateDeps ? JSON.stringify(templateDeps) : "null"},
153
177
  components: {${mkComponentsList(comps)}},
154
178
  get getElm() {
@@ -177,6 +201,14 @@ const parser = (str, counter, filePath) => {
177
201
  el: el_${currentID},
178
202
  methodsRef: methods_${currentID},
179
203
  ${isDev ? `stateProps: ${hasState ? "state" : "null"},` : ""}
204
+ ${
205
+ isDev
206
+ ? `localsRef: {${globalProps
207
+ .filter((name) => name !== "state")
208
+ .map((name) => `get ${name}(){return ${name}}`)
209
+ .join(",")}},`
210
+ : ""
211
+ }
180
212
  hooks: {
181
213
  mounted: typeof mounted !== "undefined" ? mounted : null,
182
214
  unMounted: null,
@@ -1,7 +1,8 @@
1
- const { isFullArr, isUpper } = require("./helpers");
2
-
3
1
  const ESC = "&amp;lt;-olum-&amp;gt;";
4
2
 
3
+ // Component names can contain `$`, which is special inside a regex.
4
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
+
5
6
  function literalExpr(raw) {
6
7
  if (/\{[^{}]+\}/.test(raw)) {
7
8
  const body = raw.replace(/`/g, "\\`").replace(/\{([^{}]+)\}/g, "${$1}");
@@ -108,26 +109,131 @@ function buildPropsAttr(attrsStr, parentMethods, propsAliases) {
108
109
  return attr;
109
110
  }
110
111
 
111
- function placeholder(content, regex, type, parentMethods, propsAliases) {
112
- return content.replace(regex, (str, $1, $2) => {
113
- let data = $1.split(" ");
114
- if (isFullArr(data)) {
115
- let name = data[0].trim();
116
- if (isUpper(name[0])) {
117
- name = "name='" + name + "'";
118
- const propsAttr =
119
- data.length > 1
120
- ? buildPropsAttr(
121
- data.slice(1).join(" "),
122
- parentMethods,
123
- propsAliases,
124
- )
125
- : "";
126
- const slot = type === "normal" ? $2 : "";
127
- return "<olum " + name + propsAttr + ">" + slot + "</olum>";
128
- }
112
+ /* ---------------------------------------------------------------------------
113
+ * Component tags
114
+ *
115
+ * A component is a PascalCase tag -- <Card>...</Card> or <Card />. Everything
116
+ * else is plain HTML and is copied through untouched.
117
+ *
118
+ * Tags are scanned left to right instead of being matched with one global
119
+ * regex, because a regex cannot pair <Card> with its OWN </Card>: it stops at
120
+ * the first uppercase close tag it meets. That breaks the moment a component
121
+ * wraps another one --
122
+ *
123
+ * <Spinner><Spinner></Spinner></Spinner> nested under the same name
124
+ * <KbdGroup><Kbd/><Kbd/></KbdGroup> more than one child
125
+ * <Card><CardHeader/></Card> child name starts with the parent's
126
+ * ------------------------------------------------------------------------- */
127
+
128
+ // Attributes between the tag name and its `>`. Quoted values are consumed
129
+ // whole so that a `>` inside one doesn't end the tag early.
130
+ const ATTRS = "(?:\"[^\"]*\"|'[^']*'|[^\"'>])*?";
131
+
132
+ // Names must be valid JS identifiers -- parser.js emits them straight into the
133
+ // component map as `Card: Card`.
134
+ const nextComponent = /<([A-Z][\w$]*)(?=[\s/>])/g;
135
+
136
+ const tagCache = new Map();
137
+
138
+ // `head` matches an open tag at a known offset; `open` and `close` search
139
+ // forward from one. Group 1 of `head`/`open` is set when the tag self-closes.
140
+ function tagsFor(name) {
141
+ let tags = tagCache.get(name);
142
+ if (!tags) {
143
+ const safe = escapeRegExp(name);
144
+ const open = "<" + safe + "(?=[\\s/>])" + ATTRS + "(/)?>";
145
+ tags = {
146
+ head: new RegExp(open, "y"),
147
+ open: new RegExp(open, "g"),
148
+ close: new RegExp("</" + safe + "\\s*>", "g"),
149
+ };
150
+ tagCache.set(name, tags);
151
+ }
152
+ return tags;
153
+ }
154
+
155
+ // Locates the `</name>` closing the tag that ends at `from`, depth-tracking
156
+ // same-name tags on the way so a component pairs with its own close tag.
157
+ // Returns null when there is none, i.e. the markup is unbalanced.
158
+ function findClose(content, name, from) {
159
+ const { open, close } = tagsFor(name);
160
+ let depth = 1;
161
+ let i = from;
162
+
163
+ for (;;) {
164
+ open.lastIndex = close.lastIndex = i;
165
+ const nextOpen = open.exec(content);
166
+ const nextClose = close.exec(content);
167
+ if (!nextClose) return null;
168
+
169
+ if (nextOpen && nextOpen.index < nextClose.index) {
170
+ if (!nextOpen[1]) depth++; // a nested twin, and not self-closing
171
+ i = nextOpen.index + nextOpen[0].length;
172
+ continue;
173
+ }
174
+
175
+ i = nextClose.index + nextClose[0].length;
176
+ if (--depth === 0) return { start: nextClose.index, end: i };
177
+ }
178
+ }
179
+
180
+ function olumTag(name, attrs, slot, parentMethods, propsAliases) {
181
+ const props = attrs.trim()
182
+ ? buildPropsAttr(attrs, parentMethods, propsAliases)
183
+ : "";
184
+ return "<olum name='" + name + "'" + props + ">" + slot + "</olum>";
185
+ }
186
+
187
+ function placeholder(content, parentMethods, propsAliases) {
188
+ let out = "";
189
+ let i = 0;
190
+
191
+ while (i < content.length) {
192
+ nextComponent.lastIndex = i;
193
+ const found = nextComponent.exec(content);
194
+ if (!found) break;
195
+
196
+ const start = found.index;
197
+ const name = found[1];
198
+ const { head } = tagsFor(name);
199
+ head.lastIndex = start;
200
+ const open = head.exec(content);
201
+
202
+ // `<Card` with no `>` after it isn't a tag -- step over the `<` and go on.
203
+ if (!open) {
204
+ out += content.slice(i, start + 1);
205
+ i = start + 1;
206
+ continue;
129
207
  }
130
- });
208
+
209
+ out += content.slice(i, start);
210
+ const selfClosing = !!open[1];
211
+ const attrs = open[0].slice(1 + name.length, selfClosing ? -2 : -1);
212
+ i = start + open[0].length;
213
+
214
+ if (selfClosing) {
215
+ out += olumTag(name, attrs, "", parentMethods, propsAliases);
216
+ continue;
217
+ }
218
+
219
+ const close = findClose(content, name, i);
220
+ if (!close) {
221
+ // Unbalanced: emit the open tag verbatim and keep scanning its content,
222
+ // so the components inside it are still converted.
223
+ out += open[0];
224
+ continue;
225
+ }
226
+
227
+ const slot = placeholder(
228
+ content.slice(i, close.start),
229
+ parentMethods,
230
+ propsAliases,
231
+ );
232
+ out += olumTag(name, attrs, slot, parentMethods, propsAliases);
233
+ i = close.end;
234
+ }
235
+
236
+ return out + content.slice(i);
131
237
  }
132
238
 
133
239
  module.exports = placeholder;
package/lib/regex.js CHANGED
@@ -2,7 +2,5 @@ module.exports = {
2
2
  forOf: /(.*)( of )(.*)/g,
3
3
  forIn: /(.*)( in )(.*)/g,
4
4
 
5
- selfClosingTag: /<([A-Z](?:"[^"]*"|'[^']*'|[^"'>])*?)\/>/g,
6
- normalTag: /<([A-Z](?:"[^"]*"|'[^']*'|[^"'>])*?)>([\s\S]*?)<\/[A-Z][^>]*>/g,
7
5
  compExt: /\.html$/i,
8
6
  };
package/lib/usage.js ADDED
@@ -0,0 +1,39 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ const srcDest = path.resolve(__dirname, "../src");
5
+ const mapFile = path.join(srcDest, "usage.json");
6
+
7
+ const relative = (file) =>
8
+ "src/" + path.relative(srcDest, file).split(path.sep).join("/");
9
+
10
+ const read = () => {
11
+ try {
12
+ return JSON.parse(fs.readFileSync(mapFile, "utf8"));
13
+ } catch (e) {
14
+ return {};
15
+ }
16
+ };
17
+
18
+ const write = (map) => {
19
+ try {
20
+ fs.writeFileSync(mapFile, JSON.stringify(map, null, 2));
21
+ } catch (e) {}
22
+ };
23
+
24
+ module.exports = {
25
+ relative,
26
+ record(file, children) {
27
+ const map = read();
28
+ map[relative(file)] = children;
29
+ write(map);
30
+ },
31
+
32
+ drop(file) {
33
+ const map = read();
34
+ const key = relative(file);
35
+ if (!(key in map)) return;
36
+ delete map[key];
37
+ write(map);
38
+ },
39
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "1.7.1",
3
+ "version": "1.8.2",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
@@ -453,6 +453,122 @@ check(
453
453
  ) && parses(out),
454
454
  );
455
455
 
456
+ section("§11a Nested components");
457
+
458
+ check(
459
+ "a component nested directly inside another of the same name (both normal pairs)",
460
+ comp(
461
+ `<Spinner><Spinner></Spinner></Spinner>`,
462
+ `import Spinner from "./Spinner";`,
463
+ ),
464
+ (out) =>
465
+ /<olum name="Spinner"><olum name="Spinner"><\/olum><\/olum>/.test(
466
+ tmpl(out),
467
+ ) && parses(out),
468
+ );
469
+
470
+ check(
471
+ "a component wrapping multiple same-named children pairs with its OWN close tag",
472
+ comp(
473
+ `<KbdGroup><Kbd>Ctrl</Kbd><Kbd>Alt</Kbd><Kbd>Del</Kbd></KbdGroup>`,
474
+ `import KbdGroup from "./KbdGroup";\nimport Kbd from "./Kbd";`,
475
+ ),
476
+ (out) =>
477
+ /<olum name="KbdGroup">\s*<olum name="Kbd">Ctrl<\/olum>\s*<olum name="Kbd">Alt<\/olum>\s*<olum name="Kbd">Del<\/olum>\s*<\/olum>/.test(
478
+ tmpl(out),
479
+ ) && parses(out),
480
+ );
481
+
482
+ check(
483
+ "a component wrapping differently-named children (each with its own props) nests correctly",
484
+ comp(
485
+ `<Card variant="outline"><CardHeader>Title</CardHeader><CardContent>Body</CardContent></Card>`,
486
+ `import Card from "./Card";\nimport CardHeader from "./CardHeader";\nimport CardContent from "./CardContent";`,
487
+ ),
488
+ (out) =>
489
+ /<olum name="Card" data-o-props/.test(tmpl(out)) &&
490
+ /<olum name="CardHeader">Title<\/olum>/.test(tmpl(out)) &&
491
+ /<olum name="CardContent">Body<\/olum>/.test(tmpl(out)) &&
492
+ parses(out),
493
+ );
494
+
495
+ check(
496
+ "a child component name that is a PREFIX of the parent's name doesn't confuse pairing (Card / CardHeader)",
497
+ comp(
498
+ `<Card><CardHeader>Hi</CardHeader></Card>`,
499
+ `import Card from "./Card";\nimport CardHeader from "./CardHeader";`,
500
+ ),
501
+ (out) =>
502
+ /<olum name="Card">\s*<olum name="CardHeader">Hi<\/olum>\s*<\/olum>/.test(
503
+ tmpl(out),
504
+ ) && parses(out),
505
+ );
506
+
507
+ check(
508
+ "same-name recursive nesting depth-tracks correctly (Tree > Tree > Tree)",
509
+ comp(
510
+ `<Tree label="root"><Tree label="child"><Tree label="grandchild" /></Tree></Tree>`,
511
+ `import Tree from "./Tree";`,
512
+ ),
513
+ (out) =>
514
+ /<olum name="Tree"[\s\S]*<olum name="Tree"[\s\S]*<olum name="Tree"[\s\S]*<\/olum>\s*<\/olum>\s*<\/olum>/.test(
515
+ tmpl(out),
516
+ ) && parses(out),
517
+ );
518
+
519
+ check(
520
+ "three levels of different-named nesting all convert (Accordion > AccordionItem > AccordionTrigger/Content)",
521
+ comp(
522
+ `<Accordion multiple="{true}"><AccordionItem value="a"><AccordionTrigger>Q</AccordionTrigger><AccordionContent>A</AccordionContent></AccordionItem></Accordion>`,
523
+ `import Accordion from "./Accordion";\nimport AccordionItem from "./AccordionItem";\nimport AccordionTrigger from "./AccordionTrigger";\nimport AccordionContent from "./AccordionContent";`,
524
+ ),
525
+ (out) =>
526
+ /<olum name="Accordion"/.test(tmpl(out)) &&
527
+ /<olum name="AccordionItem"/.test(tmpl(out)) &&
528
+ /<olum name="AccordionTrigger">Q<\/olum>/.test(tmpl(out)) &&
529
+ /<olum name="AccordionContent">A<\/olum>/.test(tmpl(out)) &&
530
+ parses(out),
531
+ );
532
+
533
+ check(
534
+ "self-closing and normal component siblings mix correctly inside plain HTML",
535
+ comp(
536
+ `<div class="row"><Button variant="outline">Click</Button><Badge /><Button>Second</Button></div>`,
537
+ `import Button from "./Button";\nimport Badge from "./Badge";`,
538
+ ),
539
+ (out) =>
540
+ /<olum name="Button" data-o-props[\s\S]*>Click<\/olum>/.test(
541
+ tmpl(out),
542
+ ) &&
543
+ /<olum name="Badge"><\/olum>/.test(tmpl(out)) &&
544
+ /<olum name="Button">Second<\/olum>/.test(tmpl(out)) &&
545
+ parses(out),
546
+ );
547
+
548
+ check(
549
+ "attributes split across lines and indented with tabs keep the component name intact",
550
+ comp(
551
+ `<div>\n\t<Foo\n\t\tbar="1"\n\t\tbaz="2">x</Foo>\n</div>`,
552
+ `import Foo from "./Foo";`,
553
+ ),
554
+ (out) =>
555
+ /<olum name="Foo" data-o-props=/.test(tmpl(out)) &&
556
+ /bar: '1', baz: '2'/.test(tmpl(out)) &&
557
+ parses(out),
558
+ );
559
+
560
+ check(
561
+ "an unbalanced component tag is left alone, but the components inside it still convert",
562
+ comp(
563
+ `<div><Foo>a<Bar>b</Bar></div>`,
564
+ `import Foo from "./Foo";\nimport Bar from "./Bar";`,
565
+ ),
566
+ (out) =>
567
+ !/<olum name="Foo"/.test(tmpl(out)) &&
568
+ /<olum name="Bar">b<\/olum>/.test(tmpl(out)) &&
569
+ parses(out),
570
+ );
571
+
456
572
  section("§11b Function props");
457
573
 
458
574
  check(
@@ -918,7 +1034,7 @@ if (failed) {
918
1034
  console.log("");
919
1035
  }
920
1036
 
921
- const EXPECTED_CHECKS = 81;
1037
+ const EXPECTED_CHECKS = 90;
922
1038
  const total = passed + failed;
923
1039
  if (total !== EXPECTED_CHECKS) {
924
1040
  console.log(