olum-compiler 1.5.0 → 1.6.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.
Files changed (48) hide show
  1. package/.claude/settings.local.json +2 -1
  2. package/bin/build.js +1 -1
  3. package/bin/bundle.js +32 -30
  4. package/bin/compiler.js +20 -10
  5. package/bin/copySrc.js +45 -41
  6. package/bin/dev.js +46 -39
  7. package/bin/index.js +6 -4
  8. package/bin/server.js +58 -33
  9. package/bin/watcher.js +11 -14
  10. package/bin/ws.js +16 -11
  11. package/lib/attr.js +1 -25
  12. package/lib/boolAttr.js +32 -15
  13. package/lib/chokidar.js +52 -101
  14. package/lib/colors.js +1 -7
  15. package/lib/compPlaceholder.js +5 -3
  16. package/lib/compiler.js +3 -6
  17. package/lib/coreLibs.js +1 -10
  18. package/lib/cross-spawn.js +45 -59
  19. package/lib/cssParser.js +61 -37
  20. package/lib/domEvents.js +6 -2
  21. package/lib/events.js +75 -77
  22. package/lib/for.js +56 -28
  23. package/lib/getImports.js +35 -17
  24. package/lib/getTempPath.js +8 -4
  25. package/lib/helpers.js +289 -184
  26. package/lib/html.js +3 -10
  27. package/lib/htmlParser.js +45 -45
  28. package/lib/if.js +40 -20
  29. package/lib/importMap.js +49 -24
  30. package/lib/jsParser.js +8 -13
  31. package/lib/lineCounter.js +18 -5
  32. package/lib/liveProps.js +124 -78
  33. package/lib/log.js +30 -0
  34. package/lib/magic-string.js +45 -52
  35. package/lib/models.js +8 -7
  36. package/lib/parser.js +76 -44
  37. package/lib/placeholder.js +73 -58
  38. package/lib/regex.js +4 -3
  39. package/lib/show.js +16 -8
  40. package/lib/sourcemap.js +23 -24
  41. package/lib/styles.js +7 -13
  42. package/lib/textarea.js +3 -6
  43. package/lib/toJs.js +1 -1
  44. package/lib/tokens.js +10 -22
  45. package/lib/transition.js +86 -0
  46. package/lib/websocket.js +68 -62
  47. package/package.json +1 -1
  48. package/tests/compiler.test.js +423 -188
@@ -6,7 +6,8 @@
6
6
  "Bash(echo \"exit: $?\")",
7
7
  "Bash(git add *)",
8
8
  "Bash(git commit *)",
9
- "Bash(git check-ignore *)"
9
+ "Bash(git check-ignore *)",
10
+ "Bash(git reset *)"
10
11
  ]
11
12
  }
12
13
  }
package/bin/build.js CHANGED
@@ -10,6 +10,6 @@ const copySrc = require("./copySrc");
10
10
  await bundle(bootAt);
11
11
  } catch (error) {
12
12
  console.error(error);
13
- process.exitCode = 1; // a failed build must not report success to CI
13
+ process.exitCode = 1;
14
14
  }
15
15
  })();
package/bin/bundle.js CHANGED
@@ -1,14 +1,12 @@
1
- // vite task to compile from main.js as entrypoint and outputs dist dir as final vite output
2
1
  const path = require("path");
3
2
  const fs = require("fs");
4
3
  const colors = require("../lib/colors");
5
4
  const spawn = require("../lib/cross-spawn");
6
- const { useLocalCore, localLibs } = require("../lib/coreLibs"); // same runtime switch the dev import map uses
5
+ const { useLocalCore, localLibs } = require("../lib/coreLibs");
7
6
 
8
- // compiled files paths
9
7
  const cwd = process.cwd();
10
- const public = path.resolve(__dirname, "../public"); // node_modules path
11
- const root = cwd.replace(/\/module$/, ""); // project root path
8
+ const public = path.resolve(__dirname, "../public");
9
+ const root = cwd.replace(/\/module$/, "");
12
10
  const outDir = path.resolve(root, "dist");
13
11
 
14
12
  function getLogs() {
@@ -20,10 +18,6 @@ function getLogs() {
20
18
  }
21
19
  }
22
20
 
23
- // vite only emits assets it can trace from the bundle graph — URLs living inside compiled
24
- // component strings (scoped CSS url(), template paths) are invisible to it. Dev serves all
25
- // of public/ verbatim at /, so prod mirrors the rest of it into dist — skipping files vite
26
- // already absorbed under hashed names, and never overwriting what it emitted.
27
21
  function copyStatic(from, to, absorbed) {
28
22
  for (const name of fs.readdirSync(from)) {
29
23
  const src = path.join(from, name);
@@ -37,70 +31,78 @@ function copyStatic(from, to, absorbed) {
37
31
  }
38
32
  }
39
33
 
40
- // public files vite already bundled (e.g. favicon.svg, main.css → hashed copies in dist/assets):
41
- // every emitted asset lists the source files it came from, relative to the vite root
42
34
  function absorbedFiles(buildResult) {
43
35
  const absorbed = new Set();
44
36
  for (const res of [buildResult].flat()) {
45
37
  for (const item of res.output || []) {
46
- for (const orig of item.originalFileNames || []) absorbed.add(path.resolve(public, orig));
38
+ for (const orig of item.originalFileNames || [])
39
+ absorbed.add(path.resolve(public, orig));
47
40
  }
48
41
  }
49
- // processed stylesheets don't report their origin (they're merged into a renamed css chunk),
50
- // but everything index.html links to is by definition handled by vite
42
+
51
43
  const html = fs.readFileSync(path.join(public, "index.html"), "utf8");
52
44
  const attrRegex = /(?:href|src)=["']([^"']+)["']/g;
53
45
  let match;
54
46
  while ((match = attrRegex.exec(html))) {
55
47
  const url = match[1];
56
- if (/^(https?:)?\/\//.test(url)) continue; // external URLs aren't public files
48
+ if (/^(https?:)?\/\//.test(url)) continue;
57
49
  absorbed.add(path.resolve(public, url.replace(/^\//, "")));
58
50
  }
59
51
  return absorbed;
60
52
  }
61
53
 
62
- // vite is build-only, so it installs lazily into the project root on first build — dev installs stay lean
63
54
  function ensureVite() {
64
55
  if (fs.existsSync(path.join(root, "node_modules/vite/package.json"))) return;
65
- console.log(colors("white", "vite not found — installing it into the project root (one-time)..."));
66
- // --include=dev: the build runs with NODE_ENV=production, which npm inherits as omit=dev and would skip the install
67
- const result = spawn.sync("npm", ["install", "--save-dev", "--include=dev", "vite"], { cwd: root, stdio: "inherit" });
68
- if (result.status !== 0) throw new Error("Failed to install vite — run `npm i -D vite` in " + root + " then re-run the build.");
56
+ console.log(
57
+ colors(
58
+ "white",
59
+ "vite not found — installing it into the project root (one-time)...",
60
+ ),
61
+ );
62
+
63
+ const result = spawn.sync(
64
+ "npm",
65
+ ["install", "--save-dev", "--include=dev", "vite"],
66
+ { cwd: root, stdio: "inherit" },
67
+ );
68
+ if (result.status !== 0)
69
+ throw new Error(
70
+ "Failed to install vite — run `npm i -D vite` in " +
71
+ root +
72
+ " then re-run the build.",
73
+ );
69
74
  }
70
75
 
71
76
  async function bundle(bootAt) {
72
77
  const logs = getLogs();
73
78
  if (logs) {
74
- // stop bundler to fix compiler errors first
75
- console.error(colors("red", "Bundle skipped — fix the compiler errors above first."));
79
+ console.error(
80
+ colors("red", "Bundle skipped — fix the compiler errors above first."),
81
+ );
76
82
  process.exitCode = 1;
77
83
  return;
78
84
  }
79
85
 
80
86
  ensureVite();
81
- const { build } = await import("vite"); // vite 5+ is ESM-only → dynamic import from CJS
87
+ const { build } = await import("vite");
82
88
 
83
- // LOCAL_CORE=true → bundle the framework from module/core (like the dev import map);
84
- // otherwise bare "olum"/"olum-router"/"olum-store" resolve from the project root's node_modules
85
89
  const alias = {};
86
90
  if (useLocalCore) {
87
91
  for (const [pkgName, corePath] of Object.entries(localLibs)) {
88
- alias[pkgName] = path.resolve(__dirname, ".." + corePath); // "/core/olum.js" → module/core/olum.js
92
+ alias[pkgName] = path.resolve(__dirname, ".." + corePath);
89
93
  }
90
94
  }
91
95
 
92
96
  const buildResult = await build({
93
- root: public, // index.html here is the entry; its ../src/main.js script gets pulled in and bundled
97
+ root: public,
94
98
  resolve: { alias },
95
99
  build: {
96
100
  outDir,
97
- emptyOutDir: true, // outDir sits outside vite's root, so emptying it must be opted into explicitly
101
+ emptyOutDir: true,
98
102
  },
99
103
  });
100
104
 
101
105
  copyStatic(public, outDir, absorbedFiles(buildResult));
102
-
103
- // console.log("compile + bundle in", colors("white", `${Date.now() - bootAt}ms`));
104
106
  }
105
107
 
106
108
  module.exports = bundle;
package/bin/compiler.js CHANGED
@@ -6,23 +6,33 @@ const colors = require("../lib/colors");
6
6
  let num = -1;
7
7
  module.exports = function (file, startedAt) {
8
8
  num++;
9
- const t0 = startedAt || Date.now(); // build timing — callers pass their copySrc start so the line shows the whole copy+compile
10
- const done = () => num && console.log(colors("white", "Build no."), colors("yellow", num), colors("white", "in"), colors("green", Date.now() - t0 + "ms"));
11
- return new Promise(resolve => {
12
- // wipeout log.txt
9
+ const t0 = startedAt || Date.now();
10
+ const done = () =>
11
+ num &&
12
+ console.log(
13
+ colors("white", "Build no."),
14
+ colors("yellow", num),
15
+ colors("white", "in"),
16
+ colors("green", Date.now() - t0 + "ms"),
17
+ );
18
+ return new Promise((resolve) => {
13
19
  const logFilePath = path.resolve(__dirname, "../lib/log.txt");
14
20
  fs.writeFileSync(logFilePath, "");
15
- // compile
21
+
16
22
  const compilerPath = path.resolve(__dirname, "../lib/compiler.js");
17
- if (file) { // single file → compile in-process: jsdom/acorn are already loaded, so this is ~ms instead of a ~400ms node spawn
18
- try { require(compilerPath)(file); }
19
- catch (err) { console.error(err); } // a broken component must not kill the dev server
23
+ if (file) {
24
+ try {
25
+ require(compilerPath)(file);
26
+ } catch (err) {
27
+ console.error(err);
28
+ }
20
29
  resolve();
21
30
  return done();
22
31
  }
23
- const result = spawn.sync("node", [compilerPath], { stdio: "inherit" }); // full compile stays in a child (startup / fallback / build)
32
+ const result = spawn.sync("node", [compilerPath], { stdio: "inherit" });
24
33
  if (result.signal) {
25
- if (result.signal === "SIGKILL" || result.signal === "SIGTERM") console.log("Failed to run compiler @ " + compilerPath);
34
+ if (result.signal === "SIGKILL" || result.signal === "SIGTERM")
35
+ console.log("Failed to run compiler @ " + compilerPath);
26
36
  process.exit(1);
27
37
  }
28
38
  resolve();
package/bin/copySrc.js CHANGED
@@ -2,72 +2,76 @@ 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
- // src paths (inside user project root path)
5
+
6
6
  const cwd = process.cwd();
7
- const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src")
8
- const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public")
9
- // dest paths (inside node_modules)
7
+ const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src");
8
+ const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public");
9
+
10
10
  const srcDest = path.resolve(__dirname, "../src");
11
11
  const publicDest = path.resolve(__dirname, "../public");
12
12
  const indexHtmlDest = path.resolve(__dirname, "../public/index.html");
13
13
  const mainJsPathDest = path.resolve(__dirname, "../src/main.js");
14
14
 
15
- // auto bind div#app placeholder, import map and mainjs script to index.html
16
- // (import map must precede the module script so bare imports resolve)
17
15
  function injectIndexHtml(indexHtmlPath) {
18
16
  let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
19
- // production bundles bare imports, so the dev-only import map never enters the build output
20
- const importMapTag = process.env.NODE_ENV === "production" ? "" : `${importMap(entryPoint)}\n`;
21
- indexHtmlContent = indexHtmlContent.replace(/<\/body>/, `\n<div id="app"></div>\n${importMapTag}<script defer type="module" src="../src/main.js"></script>\n</body>`);
17
+
18
+ const importMapTag =
19
+ process.env.NODE_ENV === "production" ? "" : `${importMap(entryPoint)}\n`;
20
+ indexHtmlContent = indexHtmlContent.replace(
21
+ /<\/body>/,
22
+ `\n<div id="app"></div>\n${importMapTag}<script defer type="module" src="../src/main.js"></script>\n</body>`,
23
+ );
22
24
  fs.writeFileSync(indexHtmlPath, indexHtmlContent);
23
25
  }
24
26
 
25
- function handleMainJs () {
26
- if (fs.existsSync(mainJsPathDest)) return; // skip main.js automation since user wants to drop router
27
+ function handleMainJs() {
28
+ if (fs.existsSync(mainJsPathDest)) return;
27
29
  const mainJsContent = compileRoutes(entryPoint);
28
- // automated main.js -- new concept
30
+
29
31
  fs.writeFileSync(mainJsPathDest, mainJsContent);
30
32
  }
31
33
 
32
- // Mirror one watcher event into module/{src,public} and keep the automated
33
- // main.js in step. Returns the mirrored path — or null when only the full
34
- // flow can help (path outside both roots, or dest scaffolding deleted by hand).
35
34
  function syncFile(event, file) {
36
- if (!fs.existsSync(mainJsPathDest) || !fs.existsSync(indexHtmlDest)) return null; // dest scaffolding deleted by hand → full flow
37
- const inSrc = file.startsWith(entryPoint + path.sep); // src/... → module/src/...
38
- const inPublic = !inSrc && file.startsWith(entryPoint2 + path.sep); // public/... → module/public/...
39
- if (!inSrc && !inPublic) return null; // outside both roots → full flow
40
- const dest = inSrc ? path.join(srcDest, path.relative(entryPoint, file)) : path.join(publicDest, path.relative(entryPoint2, file));
41
- if (event.startsWith("unlink")) { // file or dir was deleted → remove its mirror
42
- fs.rmSync(dest, { recursive: true, force: true }); // file or dir alike (helpers.remove is dir-only and crashes on empty dirs)
43
- if (inSrc && dest.endsWith(".html")) fs.rmSync(dest.replace(/\.html$/, ".js"), { force: true }); // and the compiled .js twin of a src component
44
- } else { // file was added or edited → copy just it
45
- fs.mkdirSync(path.dirname(dest), { recursive: true }); // make sure the mirror folder exists (mkdir, NOT remove!)
46
- fs.copyFileSync(file, dest); // copy just this one file
47
- if (dest === indexHtmlDest) injectIndexHtml(dest); // re-inject #app + import map + main.js script
35
+ if (!fs.existsSync(mainJsPathDest) || !fs.existsSync(indexHtmlDest))
36
+ return null;
37
+ const inSrc = file.startsWith(entryPoint + path.sep);
38
+ const inPublic = !inSrc && file.startsWith(entryPoint2 + path.sep);
39
+ if (!inSrc && !inPublic) return null;
40
+ const dest = inSrc
41
+ ? path.join(srcDest, path.relative(entryPoint, file))
42
+ : path.join(publicDest, path.relative(entryPoint2, file));
43
+ if (event.startsWith("unlink")) {
44
+ fs.rmSync(dest, { recursive: true, force: true });
45
+ if (inSrc && dest.endsWith(".html"))
46
+ fs.rmSync(dest.replace(/\.html$/, ".js"), { force: true });
47
+ } else {
48
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
49
+ fs.copyFileSync(file, dest);
50
+ if (dest === indexHtmlDest) injectIndexHtml(dest);
48
51
  }
49
- // routes only change when a page (.html), a whole dir, or main.js itself is added/removed under src —
50
- // anything narrower (assets, utils, edits) skips the compileRoutes tree scan entirely
51
- const affectsRoutes = inSrc && event !== "change" && (dest.endsWith(".html") || event === "unlinkDir" || dest === mainJsPathDest);
52
- if (affectsRoutes && !fs.existsSync(path.join(entryPoint, "main.js"))) fs.writeFileSync(mainJsPathDest, compileRoutes(entryPoint)); // refresh automated main.js (skipped when user owns it)
53
- return dest; // tell the caller what was mirrored
52
+
53
+ const affectsRoutes =
54
+ inSrc &&
55
+ event !== "change" &&
56
+ (dest.endsWith(".html") ||
57
+ event === "unlinkDir" ||
58
+ dest === mainJsPathDest);
59
+ if (affectsRoutes && !fs.existsSync(path.join(entryPoint, "main.js")))
60
+ fs.writeFileSync(mainJsPathDest, compileRoutes(entryPoint));
61
+ return dest;
54
62
  }
55
63
 
56
- // copySrc() → full flow: wipe dest, clone src+public (first build / fallback)
57
- // copySrc(event, file) → incremental: mirror that one watcher event only
58
- // Resolves with the mirrored dest path, or null when the full flow ran.
59
64
  module.exports = function copySrc(event, file) {
60
65
  return new Promise((resolve, reject) => {
61
66
  try {
62
- if (event) { // watcher event → try the incremental path first
63
- const dest = syncFile(event, file); // mirror just this one change
64
- if (dest) return resolve(dest); // done — falls through to the full flow otherwise
67
+ if (event) {
68
+ const dest = syncFile(event, file);
69
+ if (dest) return resolve(dest);
65
70
  }
66
- // clean (rmSync handles missing, empty and nested dirs alike —
67
- // helpers.remove crashes on missing/empty dirs)
71
+
68
72
  fs.rmSync(publicDest, { recursive: true, force: true });
69
73
  fs.rmSync(srcDest, { recursive: true, force: true });
70
- // copy
74
+
71
75
  copy(entryPoint, srcDest, () => handleMainJs());
72
76
  copy(entryPoint2, publicDest, () => injectIndexHtml(indexHtmlDest));
73
77
 
package/bin/dev.js CHANGED
@@ -10,32 +10,39 @@ const fs = require("fs");
10
10
  let instance;
11
11
  const entryPoint = path.resolve(__dirname, "../public");
12
12
  serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
13
- // initial compiling
14
- const bootAt = Date.now(); // Build-line timing covers copy + compile
15
- copySrc().then(() => {
16
- compile(undefined, bootAt).then(() => {
17
- // EADDRINUSE is emitted as an 'error' event (not thrown), so retry on the next port
18
- server.on("error", (e) => { if (e.code === "EADDRINUSE") server.listen(++PORT); });
19
- server.listen(PORT, () => console.log(log.replace(/port \d+/, "port " + PORT), colors("white", `(ready in ${Date.now() - bootAt}ms)`))); // boot = clean + copy + first compile + listen; replace keeps the log right after EADDRINUSE port bumps
13
+ const bootAt = Date.now();
14
+ copySrc()
15
+ .then(() => {
16
+ compile(undefined, bootAt).then(() => {
17
+ server.on("error", (e) => {
18
+ if (e.code === "EADDRINUSE") server.listen(++PORT);
19
+ });
20
+ server.listen(PORT, () =>
21
+ console.log(
22
+ log.replace(/port \d+/, "port " + PORT),
23
+ colors("white", `(ready in ${Date.now() - bootAt}ms)`),
24
+ ),
25
+ );
20
26
 
21
- // Listen for adds, edits and deletes. Editors that save atomically
22
- // (temp file + rename) surface edits as unlink+add rather than change,
23
- // so watching only "change" misses new files and many edits.
24
- ["add", "change", "unlink", "unlinkDir"].forEach((event) => watch.on(event, (file) => handleChange(event, file)));
25
- require("../lib/compiler"); // preload jsdom/acorn now so even the first save compiles in-process instantly
27
+ ["add", "change", "unlink", "unlinkDir"].forEach((event) =>
28
+ watch.on(event, (file) => handleChange(event, file)),
29
+ );
30
+ require("../lib/compiler");
26
31
 
27
- (function startWs(port) {
28
- // const wss = new WebSocket.Server({ port });
29
- const wss = new WebSocket.Server({ server }); // using the same server port
30
- wss.on("listening", () => setWsPort(port)); // tell server.js the real ws port to inject
31
- wss.on("error", (e) => { if (e.code === "EADDRINUSE") startWs(port + 1); });
32
- wss.on("connection", (ws) => {
33
- instance = ws;
34
- ws.send(JSON.stringify({ msg: "connected" }));
35
- });
36
- })(wsPort);
37
- });
38
- }).catch(console.error);
32
+ (function startWs(port) {
33
+ const wss = new WebSocket.Server({ server });
34
+ wss.on("listening", () => setWsPort(port));
35
+ wss.on("error", (e) => {
36
+ if (e.code === "EADDRINUSE") startWs(port + 1);
37
+ });
38
+ wss.on("connection", (ws) => {
39
+ instance = ws;
40
+ ws.send(JSON.stringify({ msg: "connected" }));
41
+ });
42
+ })(wsPort);
43
+ });
44
+ })
45
+ .catch(console.error);
39
46
  });
40
47
 
41
48
  function getLogs() {
@@ -47,27 +54,27 @@ function getLogs() {
47
54
  }
48
55
  }
49
56
 
50
- const send = (data) => instance && instance.send(JSON.stringify(data)); // push a message to the browser (if one is connected)
57
+ const send = (data) => instance && instance.send(JSON.stringify(data));
51
58
 
52
- // after compiling: surface compiler warnings, otherwise reload the page
53
59
  function notify() {
54
- const logs = getLogs(); // warnings written by the compiler child to lib/log.txt
55
- logs ? send({ msg: "warn", data: logs }) : send({ msg: "reload" }); // warn overlay or plain reload
60
+ const logs = getLogs();
61
+ logs ? send({ msg: "warn", data: logs }) : send({ msg: "reload" });
56
62
  }
57
63
 
58
- // compilable component: .html under module/src, not a _-partial
59
- const isComp = (dest) => dest.endsWith(".html") && !path.basename(dest).startsWith("_") && dest.startsWith(path.resolve(__dirname, "../src") + path.sep);
64
+ const isComp = (dest) =>
65
+ dest.endsWith(".html") &&
66
+ !path.basename(dest).startsWith("_") &&
67
+ dest.startsWith(path.resolve(__dirname, "../src") + path.sep);
60
68
 
61
- // copySrc mirrors the change (or falls back to its full flow), then:
62
- // full flow → compile all / css → hot-swap / component → compile it / else → reload
63
69
  function handleChange(event, file) {
64
- const t0 = Date.now(); // Build-line timing covers copy + compile
65
- copySrc(event, file) // mirror this one change into module/ (dest = mirrored path, null = full flow ran)
70
+ const t0 = Date.now();
71
+ copySrc(event, file)
66
72
  .then((dest) => {
67
- if (dest === null) return compile(undefined, t0).then(notify); // full rebuild → compile every component
68
- if (file.endsWith("css")) return send({ msg: "css" }); // css → hot-swap styles, no reload
69
- if (!event.startsWith("unlink") && isComp(dest)) return compile(dest, t0).then(notify); // component → compile only this file
70
- send({ msg: "reload" }); // anything else (asset/js/partial/removal) → copy was enough, just reload
73
+ if (dest === null) return compile(undefined, t0).then(notify);
74
+ if (file.endsWith("css")) return send({ msg: "css" });
75
+ if (!event.startsWith("unlink") && isComp(dest))
76
+ return compile(dest, t0).then(notify);
77
+ send({ msg: "reload" });
71
78
  })
72
- .catch(console.error); // watcher must survive a failed build
79
+ .catch(console.error);
73
80
  }
package/bin/index.js CHANGED
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env node
2
1
  const path = require("path");
3
2
  const spawn = require("../lib/cross-spawn");
4
3
  const script = process.argv[2];
@@ -7,12 +6,15 @@ if (script == "dev") process.env.NODE_ENV = "development";
7
6
  else if (script == "build") process.env.NODE_ENV = "production";
8
7
 
9
8
  if (typeof script !== undefined && ["dev", "build"].includes(script)) {
10
- const result = spawn.sync("node", [path.resolve(__dirname, script + ".js")], { stdio: "inherit" });
9
+ const result = spawn.sync("node", [path.resolve(__dirname, script + ".js")], {
10
+ stdio: "inherit",
11
+ });
11
12
 
12
13
  if (result.signal) {
13
- if (result.signal === "SIGKILL" || result.signal === "SIGTERM") console.log("Failed to run " + script + " script!");
14
+ if (result.signal === "SIGKILL" || result.signal === "SIGTERM")
15
+ console.log("Failed to run " + script + " script!");
14
16
  process.exit(1);
15
17
  }
16
18
 
17
19
  process.exit(result.status);
18
- }
20
+ }
package/bin/server.js CHANGED
@@ -1,15 +1,15 @@
1
1
  const fs = require("fs");
2
2
  const path = require("path");
3
3
  const http = require("http");
4
- // const http2 = require("http2");
4
+
5
5
  const jsdom = require("jsdom");
6
6
  const colors = require("../lib/colors");
7
7
  const mimes = require("./mimes.json");
8
- let wsPort = 8090; // old way of ws -- it was using seperated port from server
8
+ let wsPort = 8090;
9
9
 
10
10
  function handleWsFile() {
11
11
  let file = fs.readFileSync(path.resolve(__dirname, "./ws.js")).toString();
12
- // file = file.replace(/{{port}}/, wsPort);
12
+
13
13
  file = "<script>" + file + "</script>";
14
14
  return file;
15
15
  }
@@ -18,22 +18,17 @@ function getPath(entry, url) {
18
18
  entry = entry.endsWith("/") ? entry : entry + "/";
19
19
  url = url.startsWith("/") ? url.slice(1) : url;
20
20
 
21
- const resolve = candidate =>
21
+ const resolve = (candidate) =>
22
22
  [
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
27
- ].find(p => fs.existsSync(p) && fs.statSync(p).isFile()) || null;
26
+ path.resolve(entry, "../../", candidate),
27
+ ].find((p) => fs.existsSync(p) && fs.statSync(p).isFile()) || null;
28
28
 
29
- // Exact match first (preserves the original behaviour).
30
29
  const direct = resolve(url);
31
30
  if (direct) return direct;
32
31
 
33
- // Assets are referenced relatively in index.html (e.g. "./main.css"), so when
34
- // a nested client-side route like /blog/x is open the browser requests them as
35
- // /blog/main.css. Progressively drop leading route segments so the asset still
36
- // resolves to its real location (/blog/main.css -> main.css).
37
32
  if (path.extname(url)) {
38
33
  const segments = url.split("/");
39
34
  for (let i = 1; i < segments.length; i++) {
@@ -44,21 +39,15 @@ function getPath(entry, url) {
44
39
 
45
40
  return null;
46
41
  }
47
- // todo handle https
48
- /**
49
- *
50
- * @param {*} entry must be an absolute path
51
- * @param {*} port optional port, default is 8000
52
- */
42
+
53
43
  function serve(entry, port) {
54
44
  return new Promise((resolve, reject) => {
55
45
  const PORT = Number(port || process.env.PORT || 3000);
56
46
 
57
47
  const server = http.createServer(handler);
58
48
  function handler(req, res) {
59
- const urlPath = req.url.split("?")[0]; // strip query string before resolving
49
+ const urlPath = req.url.split("?")[0];
60
50
 
61
- // serve the (ws-injected) index.html — used for "/" and as the history-mode SPA fallback
62
51
  function serveIndex() {
63
52
  let indexPath = entry + "/index.html";
64
53
  if (!fs.existsSync(indexPath)) indexPath = entry + "/index.htm";
@@ -73,38 +62,74 @@ function serve(entry, port) {
73
62
  const html = dom.querySelector("html");
74
63
  const wsContent = handleWsFile();
75
64
  dom.body.insertAdjacentHTML("beforeend", wsContent);
76
- res.writeHead(200, { "content-type": "text/html", "cache-control": "no-cache" });
65
+ res.writeHead(200, {
66
+ "content-type": "text/html",
67
+ "cache-control": "no-cache",
68
+ });
77
69
  res.end("<!DOCTYPE html>" + html.outerHTML);
78
70
  });
79
71
  }
80
72
 
81
73
  if (urlPath === "/") return serveIndex();
82
74
 
83
- // serve an existing static file with its mime type
84
75
  const finalPath = getPath(entry, urlPath);
85
76
  if (finalPath && fs.statSync(finalPath).isFile()) {
86
77
  const ext = path.extname(finalPath).toLowerCase();
87
- const obj = mimes.find(item => ext === item.ext.toLowerCase());
88
- // no-cache: without it browsers heuristically cache served JS (no headers at all),
89
- // so a framework/runtime edit keeps running stale code until a hard refresh
90
- res.writeHead(200, { "Content-Type": obj ? obj.mime : "application/octet-stream", "Cache-Control": "no-cache" });
78
+ const obj = mimes.find((item) => ext === item.ext.toLowerCase());
79
+ const mime = obj ? obj.mime : "application/octet-stream";
80
+ const size = fs.statSync(finalPath).size;
81
+
82
+ const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || "");
83
+ if (range && (range[1] || range[2])) {
84
+ const start = range[1]
85
+ ? parseInt(range[1], 10)
86
+ : size - parseInt(range[2], 10);
87
+ const end =
88
+ range[1] && range[2]
89
+ ? Math.min(parseInt(range[2], 10), size - 1)
90
+ : size - 1;
91
+ if (start >= size || start < 0 || start > end) {
92
+ res.writeHead(416, { "Content-Range": "bytes */" + size });
93
+ return res.end();
94
+ }
95
+ res.writeHead(206, {
96
+ "Content-Type": mime,
97
+ "Content-Range": "bytes " + start + "-" + end + "/" + size,
98
+ "Content-Length": end - start + 1,
99
+ "Accept-Ranges": "bytes",
100
+ "Cache-Control": "no-cache",
101
+ });
102
+ fs.createReadStream(finalPath, { start, end }).pipe(res);
103
+ return;
104
+ }
105
+
106
+ res.writeHead(200, {
107
+ "Content-Type": mime,
108
+ "Content-Length": size,
109
+ "Accept-Ranges": "bytes",
110
+ "Cache-Control": "no-cache",
111
+ });
91
112
  fs.createReadStream(finalPath).pipe(res);
92
113
  return;
93
114
  }
94
115
 
95
- // history-mode SPA fallback: a request with no file extension is a client-side route
96
- // (e.g. /card) — serve index.html and let the olum router handle it. Anything with an
97
- // extension is a genuinely missing asset, so return a real 404 instead of hanging.
98
116
  if (!path.extname(urlPath)) return serveIndex();
99
117
 
100
118
  res.writeHead(404, { "content-type": "text/plain" });
101
119
  res.end("404 Not Found: " + urlPath);
102
120
  }
103
- const log = colors("cyan", "Serving ") + colors("green", "port " + PORT); // port only — a URL would show "localhost" even on a live server
104
- // setWsPort lets dev.js report the port the ws server actually bound to (it may
105
- // retry off 8090 if that's taken) so handleWsFile injects the matching port.
106
- const setWsPort = (port) => { wsPort = port; };
107
- resolve({ server: server, wsPort: wsPort, PORT: PORT, log: log, setWsPort: setWsPort });
121
+ const log = colors("cyan", "Serving ") + colors("green", "port " + PORT);
122
+
123
+ const setWsPort = (port) => {
124
+ wsPort = port;
125
+ };
126
+ resolve({
127
+ server: server,
128
+ wsPort: wsPort,
129
+ PORT: PORT,
130
+ log: log,
131
+ setWsPort: setWsPort,
132
+ });
108
133
  });
109
134
  }
110
135
 
package/bin/watcher.js CHANGED
@@ -1,24 +1,21 @@
1
1
  const chokidar = require("../lib/chokidar");
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
- // Resolve against the project root (process.cwd()), same as copySrc.js.
5
- // The old "../../src" pointed at node_modules/src, which doesn't exist, so
6
- // chokidar watched 0 directories and never detected any changes.
4
+
7
5
  const cwd = process.cwd();
8
- const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src")
9
- const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public")
10
- // let ignoreRegex = /\_\.js$/;
11
- // module.exports = chokidar.watch(entryPoint, {ignored: ignoreRegex, persistent: true });
12
- // ignoreInitial: don't fire "add" for every existing file on startup (initial
13
- // compile is handled separately in dev.js). awaitWriteFinish: coalesce the
14
- // temp-file/rename churn from atomic saves into a single event.
6
+ const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src");
7
+ const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public");
8
+
15
9
  module.exports = chokidar.watch([entryPoint, entryPoint2], {
16
10
  persistent: true,
17
11
  ignoreInitial: true,
18
12
  awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 },
19
13
  });
20
14
 
21
- // Debug trail: log every event of this session to lib/changes.txt (newest last)
22
- const changesLog = path.resolve(__dirname, "../lib/changes.txt"); // e.g. "add /path/to/src/page.html"
23
- fs.writeFileSync(changesLog, ""); // start fresh each session
24
- ["add", "change", "unlink", "addDir", "unlinkDir"].forEach((event) => module.exports.on(event, (file) => fs.appendFileSync(changesLog, `${event} ${file}\n`))); // one line per event
15
+ const changesLog = path.resolve(__dirname, "../lib/changes.txt");
16
+ fs.writeFileSync(changesLog, "");
17
+ ["add", "change", "unlink", "addDir", "unlinkDir"].forEach((event) =>
18
+ module.exports.on(event, (file) =>
19
+ fs.appendFileSync(changesLog, `${event} ${file}\n`),
20
+ ),
21
+ );