olum-compiler 0.7.1 → 0.8.6

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.
package/bin/copySrc.js CHANGED
@@ -1,13 +1,10 @@
1
1
  // todo check changed files only to be copied, use this project https://github.com/eissapk/diff
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
- const { copy, remove, rewriteImports, ls, generateRouteManifest, generateImports, generateRoutes } = require("../lib/helpers");
4
+ const { copy, remove, routerParamsParser, ls, generateRouteManifest, generateImports, generateRoutes } = require("../lib/helpers");
5
+ const entryPoint = path.resolve(process.cwd(), "src").replace(/\/module/, "");
6
+ const entryPoint2 = path.resolve(process.cwd(), "public").replace(/\/module/, "");
5
7
 
6
- // const entryPoint = path.resolve(__dirname, "../../src");
7
- // const entryPoint2 = path.resolve(__dirname, "../../public");
8
- // fix for new router file based
9
- const entryPoint = path.resolve(process.cwd(), "src");
10
- const entryPoint2 = path.resolve(process.cwd(), "public");
11
8
  module.exports = function copySrc() {
12
9
  return new Promise((resolve, reject) => {
13
10
  try {
@@ -37,6 +34,7 @@ module.exports = function copySrc() {
37
34
  let has404Page = false;
38
35
  if (manifest['not-found']) has404Page = true;
39
36
  const libImports = `import Olum from "/node_modules/olum/dist/olum.js";\nimport Router from "/node_modules/olum-router/dist/router.js";`;
37
+ // const libImports = `import Olum from "../core/olum.js";\nimport Router from "../core/router.js";`; // for testing
40
38
  const imports = generateImports(manifest).replace(/.html/g, ".js"); // fix extension by replacing .html with .js since components are js modules
41
39
  const config = `const config = { mode: "history", root: "/", ${has404Page? `err: "/404",` : "" } routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
42
40
  routes = generateRoutes(manifest);
@@ -49,7 +47,15 @@ module.exports = function copySrc() {
49
47
  const mainJsPath = path.resolve(__dirname, "../src/main.js");
50
48
  fs.writeFileSync(mainJsPath, `${libImports}\n${imports}\n${routes}\n${config}`);
51
49
  });
52
- copy(entryPoint2, path.resolve(__dirname, "../public"));
50
+ copy(entryPoint2, path.resolve(__dirname, "../public"), () => {
51
+ const indexHtmlPath = path.resolve(__dirname, "../public/index.html");
52
+ let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
53
+ // auto bind router params handler
54
+ indexHtmlContent = indexHtmlContent.replace(/<body>/, `\n<body>\n${routerParamsParser}`);
55
+ // auto bind div#app placeholder and mainjs script to index.html
56
+ indexHtmlContent = indexHtmlContent.replace(/<\/body>/, `\n<div id="app"></div>\n<script defer type="module" src="../src/main.js"></script>\n</body>`);
57
+ fs.writeFileSync(indexHtmlPath, indexHtmlContent);
58
+ });
53
59
  resolve();
54
60
  } catch (err) {
55
61
  reject();
package/bin/dev.js CHANGED
@@ -8,18 +8,30 @@ const fs = require("fs");
8
8
 
9
9
  let instance;
10
10
  const entryPoint = path.resolve(__dirname, "../public");
11
- serve(entryPoint).then(({ server, wsPort, PORT, log }) => {
11
+ serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
12
12
  // initial compiling
13
13
  copySrc().then(() => {
14
14
  compile().then(() => {
15
- server.listen(PORT, () => console.log(log));
16
- // console.log("initial compiling");
15
+ // EADDRINUSE is emitted as an 'error' event (not thrown), so retry on the next port
16
+ server.on("error", (e) => { if (e.code === "EADDRINUSE") server.listen(++PORT); });
17
+ server.listen(PORT, () => console.log(log.replace(/:\d+/, ":" + PORT)));
18
+
19
+ // Listen for adds, edits and deletes. Editors that save atomically
20
+ // (temp file + rename) surface edits as unlink+add rather than change,
21
+ // so watching only "change" misses new files and many edits.
22
+ watch.on("add", handleChange);
17
23
  watch.on("change", handleChange);
18
- const wss = new WebSocket.Server({ port: wsPort });
19
- wss.on("connection", (ws) => {
20
- instance = ws;
21
- ws.send(JSON.stringify({ msg: "connected" }));
22
- });
24
+ watch.on("unlink", handleChange);
25
+
26
+ (function startWs(port) {
27
+ const wss = new WebSocket.Server({ port });
28
+ wss.on("listening", () => setWsPort(port)); // tell server.js the real ws port to inject
29
+ wss.on("error", (e) => { if (e.code === "EADDRINUSE") startWs(port + 1); });
30
+ wss.on("connection", (ws) => {
31
+ instance = ws;
32
+ ws.send(JSON.stringify({ msg: "connected" }));
33
+ });
34
+ })(wsPort);
23
35
  });
24
36
  });
25
37
  });
package/bin/server.js CHANGED
@@ -5,7 +5,7 @@ const http = require("http");
5
5
  const jsdom = require("jsdom");
6
6
  const colors = require("../lib/colors");
7
7
  const mimes = require("./mimes.json");
8
- const wsPort = 8090;
8
+ let wsPort = 8090;
9
9
 
10
10
  function handleWsFile() {
11
11
  let file = fs.readFileSync(path.resolve(__dirname, "./ws.js")).toString();
@@ -18,13 +18,30 @@ function getPath(entry, url) {
18
18
  entry = entry.endsWith("/") ? entry : entry + "/";
19
19
  url = url.startsWith("/") ? url.slice(1) : url;
20
20
 
21
- const paths = [
22
- path.resolve(entry, url),
23
- path.resolve(entry, "../", url),
24
- path.resolve(process.cwd(), url),
25
- ];
21
+ const resolve = candidate =>
22
+ [
23
+ path.resolve(entry, candidate),
24
+ path.resolve(entry, "../", candidate),
25
+ path.resolve(process.cwd(), candidate),
26
+ ].find(p => fs.existsSync(p) && fs.statSync(p).isFile()) || null;
26
27
 
27
- return paths.find(fs.existsSync) || null;
28
+ // Exact match first (preserves the original behaviour).
29
+ const direct = resolve(url);
30
+ if (direct) return direct;
31
+
32
+ // Assets are referenced relatively in index.html (e.g. "./main.css"), so when
33
+ // a nested client-side route like /blog/x is open the browser requests them as
34
+ // /blog/main.css. Progressively drop leading route segments so the asset still
35
+ // resolves to its real location (/blog/main.css -> main.css).
36
+ if (path.extname(url)) {
37
+ const segments = url.split("/");
38
+ for (let i = 1; i < segments.length; i++) {
39
+ const found = resolve(segments.slice(i).join("/"));
40
+ if (found) return found;
41
+ }
42
+ }
43
+
44
+ return null;
28
45
  }
29
46
  // todo handle https
30
47
  /**
@@ -82,7 +99,10 @@ function serve(entry, port) {
82
99
  res.end("404 Not Found: " + urlPath);
83
100
  }
84
101
  const log = colors("cyan", "Serving ") + colors("green", domain);
85
- resolve({ server: server, wsPort: wsPort, PORT: PORT, log: log });
102
+ // setWsPort lets dev.js report the port the ws server actually bound to (it may
103
+ // retry off 8090 if that's taken) so handleWsFile injects the matching port.
104
+ const setWsPort = (port) => { wsPort = port; };
105
+ resolve({ server: server, wsPort: wsPort, PORT: PORT, log: log, setWsPort: setWsPort });
86
106
  });
87
107
  }
88
108
 
package/bin/watcher.js CHANGED
@@ -1,6 +1,17 @@
1
1
  const chokidar = require("chokidar");
2
2
  const path = require("path");
3
- const entryPoint = path.resolve(__dirname, "../../../src");
3
+ // Resolve against the project root (process.cwd()), same as copySrc.js.
4
+ // The old "../../src" pointed at node_modules/src, which doesn't exist, so
5
+ // chokidar watched 0 directories and never detected any changes.
6
+ const entryPoint = path.resolve(process.cwd(), "src").replace(/\/module/, "");
7
+ const entryPoint2 = path.resolve(process.cwd(), "public").replace(/\/module/, "");
4
8
  // let ignoreRegex = /\_\.js$/;
5
9
  // module.exports = chokidar.watch(entryPoint, {ignored: ignoreRegex, persistent: true });
6
- module.exports = chokidar.watch(entryPoint, { persistent: true });
10
+ // ignoreInitial: don't fire "add" for every existing file on startup (initial
11
+ // compile is handled separately in dev.js). awaitWriteFinish: coalesce the
12
+ // temp-file/rename churn from atomic saves into a single event.
13
+ module.exports = chokidar.watch([entryPoint, entryPoint2], {
14
+ persistent: true,
15
+ ignoreInitial: true,
16
+ awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 },
17
+ });
package/lib/helpers.js CHANGED
@@ -663,6 +663,57 @@ ${routes
663
663
  ];`;
664
664
  }
665
665
 
666
+ // todo: move it to olum-router and bind it from there to window
667
+ const routerParamsParser = `<script>
668
+ /**
669
+ * Extract route params from a file path and pathname.
670
+ *
671
+ * @param {string} filePath
672
+ * @param {string} pathname
673
+ * @returns {Record<string, string | string[]>}
674
+ *
675
+ * Examples:
676
+ * extractParams("/blog/[slug]/page.html", "/blog/hello")
677
+ * -> { slug: "hello" }
678
+ *
679
+ * extractParams("/users/[id]/posts/[postId]/page.html", "/users/5/posts/10")
680
+ * -> { id: "5", postId: "10" }
681
+ */
682
+ function extractParams(filePath, pathname) {
683
+ const routeParts = filePath
684
+ .replace(/\\/page\\.[^/]+$/, "")
685
+ .split("/")
686
+ .filter(Boolean);
687
+
688
+ const pathParts = pathname.split("/").filter(Boolean);
689
+
690
+ const params = {};
691
+
692
+ let i = routeParts.length - 1;
693
+ let j = pathParts.length - 1;
694
+
695
+ while (i >= 0 && j >= 0) {
696
+ const part = routeParts[i];
697
+
698
+ // [...slug]
699
+ if (part.startsWith("[...") && part.endsWith("]")) {
700
+ params[part.slice(4, -1)] = pathParts.slice(0, j + 1);
701
+ break;
702
+ }
703
+
704
+ // [slug]
705
+ if (part.startsWith("[") && part.endsWith("]")) {
706
+ params[part.slice(1, -1)] = decodeURIComponent(pathParts[j]);
707
+ }
708
+
709
+ i--;
710
+ j--;
711
+ }
712
+
713
+ return params;
714
+ }
715
+ </script>`;
716
+
666
717
  module.exports.isNum = isNum;
667
718
  module.exports.id = id;
668
719
  module.exports.isUpper = isUpper;
@@ -688,3 +739,4 @@ module.exports.rewriteImports = rewriteImports;
688
739
  module.exports.generateRouteManifest = generateRouteManifest;
689
740
  module.exports.generateImports = generateImports;
690
741
  module.exports.generateRoutes = generateRoutes;
742
+ module.exports.routerParamsParser = routerParamsParser;
package/lib/parser.js CHANGED
@@ -122,9 +122,10 @@ const parser = (str, counter, filePath) => {
122
122
 
123
123
  // children is declared inside getElm (not at factory-call time) so it re-reads the store on every render
124
124
  const childrenVar = `const children=(olum.app.store[_storeKey]&&olum.app.store[_storeKey].children)||"";`;
125
+ const routerParamsProxy = `const params = new Proxy({},{ get(_, key) { const values = extractParams(currentFilePath, location.pathname); return values[key];}, ownKeys() { return Reflect.ownKeys(extractParams(currentFilePath, location.pathname));},getOwnPropertyDescriptor() {return {enumerable: true,configurable: true,};},});`;
125
126
 
126
127
  // bind props proxy at the top to be accessed by ${js} code
127
- return `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const _storeKey=_instanceKey||"${compName}";${minifyJS(propsProxy)}${js}
128
+ return `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const currentFilePath = "${filePath}"; ${routerParamsProxy} const _storeKey=_instanceKey||"${compName}"; ${minifyJS(propsProxy)}${js}
128
129
  var el_${currentID} = olum.mkElm("div", "${compName}", "${currentID}");
129
130
  var $0 = el_${currentID};
130
131
  var methods_${currentID} = {${globalMethods}};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "0.7.1",
3
+ "version": "0.8.6",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {