olum-compiler 0.8.5 → 0.9.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.
package/bin/compiler.js CHANGED
@@ -1,4 +1,4 @@
1
- const spawn = require("cross-spawn");
1
+ const spawn = require("../lib/cross-spawn");
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
4
  const colors = require("../lib/colors");
package/bin/copySrc.js CHANGED
@@ -2,14 +2,9 @@
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
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
-
7
- // for testing
8
- // const entryPoint = path.resolve(__dirname, "../../src");
9
- // const entryPoint2 = path.resolve(__dirname, "../../public");
10
- // for production
11
- const entryPoint = path.resolve(process.cwd(), "src");
12
- const entryPoint2 = path.resolve(process.cwd(), "public");
13
8
  module.exports = function copySrc() {
14
9
  return new Promise((resolve, reject) => {
15
10
  try {
@@ -38,8 +33,8 @@ module.exports = function copySrc() {
38
33
  const manifest = generateRouteManifest(routes, entryPoint);
39
34
  let has404Page = false;
40
35
  if (manifest['not-found']) has404Page = true;
41
- const libImports = `import Olum from "/node_modules/olum/dist/olum.js";\nimport Router from "/node_modules/olum-router/dist/router.js";`; // for production
42
- // const libImports = `import Olum from "../core/app.js";\nimport Router from "../core/router.js";`; // for testing
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
43
38
  const imports = generateImports(manifest).replace(/.html/g, ".js"); // fix extension by replacing .html with .js since components are js modules
44
39
  const config = `const config = { mode: "history", root: "/", ${has404Page? `err: "/404",` : "" } routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
45
40
  routes = generateRoutes(manifest);
package/bin/dev.js CHANGED
@@ -2,7 +2,7 @@ const serve = require("./server");
2
2
  const watch = require("./watcher");
3
3
  const compile = require("./compiler");
4
4
  const copySrc = require("./copySrc");
5
- const WebSocket = require("ws");
5
+ const WebSocket = require("../lib/websocket");
6
6
  const path = require("path");
7
7
  const fs = require("fs");
8
8
 
@@ -16,7 +16,12 @@ serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
16
16
  server.on("error", (e) => { if (e.code === "EADDRINUSE") server.listen(++PORT); });
17
17
  server.listen(PORT, () => console.log(log.replace(/:\d+/, ":" + PORT)));
18
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);
19
23
  watch.on("change", handleChange);
24
+ watch.on("unlink", handleChange);
20
25
 
21
26
  (function startWs(port) {
22
27
  const wss = new WebSocket.Server({ port });
package/bin/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  const path = require("path");
3
- const spawn = require("cross-spawn");
3
+ const spawn = require("../lib/cross-spawn");
4
4
  const script = process.argv[2];
5
5
 
6
6
  if (typeof script !== undefined && ["dev", "build"].includes(script)) {
package/bin/watcher.js CHANGED
@@ -1,7 +1,17 @@
1
- const chokidar = require("chokidar");
1
+ const chokidar = require("../lib/chokidar");
2
2
  const path = require("path");
3
- const entryPoint = path.resolve(__dirname, "../../src");
4
- const entryPoint2 = path.resolve(__dirname, "../../public");
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/, "");
5
8
  // let ignoreRegex = /\_\.js$/;
6
9
  // module.exports = chokidar.watch(entryPoint, {ignored: ignoreRegex, persistent: true });
7
- module.exports = chokidar.watch([entryPoint, entryPoint2], { 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
+ });
@@ -0,0 +1,344 @@
1
+ /**
2
+ * chokidar.js — standalone single-file recursive file watcher
3
+ * Minimal replacement for the `chokidar` package, using only node built-ins
4
+ * (fs, path, events). Cross-platform: instead of fs.watch's `recursive` flag
5
+ * (whose support and event detail differ per OS), every directory gets its own
6
+ * non-recursive fs.watch and events trigger a rescan-and-diff of that
7
+ * directory against a stat snapshot — so add/change/unlink detection behaves
8
+ * identically on Linux, macOS and Windows.
9
+ *
10
+ * Covered (same API shape as chokidar@5.0.0):
11
+ * const chokidar = require("./chokidar");
12
+ * const watcher = chokidar.watch(paths, {
13
+ * persistent: true, // keep the process alive (default true)
14
+ * ignoreInitial: false, // suppress add/addDir for the initial scan
15
+ * ignored: regex|fn|array, // paths to skip entirely
16
+ * awaitWriteFinish: { stabilityThreshold, pollIntervall } | true,
17
+ * });
18
+ * watcher.on("add" | "change" | "unlink" | "addDir" | "unlinkDir" | "ready" | "error", ...)
19
+ * watcher.close();
20
+ *
21
+ * Watched roots that don't exist yet (or get deleted) are polled for and
22
+ * picked up when they appear, like chokidar does.
23
+ *
24
+ * KNOWN LIMITATIONS vs the real chokidar (future maintenance):
25
+ *
26
+ * 1. No `usePolling` fallback — NFS / Docker / VM compatibility.
27
+ * fs.watch relies on OS change events (inotify on Linux, FSEvents/kqueue on
28
+ * macOS, ReadDirectoryChangesW on Windows). On filesystems that don't
29
+ * propagate those events — NFS mounts, Docker bind-mounted volumes with a
30
+ * macOS/Windows host, some VM shared folders (VirtualBox vboxsf, older
31
+ * Vagrant/WSL1 setups) — the watcher goes silent: no errors, just no
32
+ * events. Real chokidar covers this with `usePolling: true` (fs.watchFile
33
+ * stat polling). If dev-inside-Docker/NFS ever becomes a use case, add a
34
+ * polling mode here: replace fs.watch per directory with a setInterval
35
+ * that calls _rescan(dir) (the diffing logic already works unchanged);
36
+ * only _watchDir needs the branch.
37
+ *
38
+ * 2. Whole-directory rescan per event burst.
39
+ * On any event we readdir+stat the affected directory instead of stat-ing
40
+ * just the named file like chokidar. Identical behavior, negligible cost
41
+ * for source trees (measured: 305-dir Next.js project ready in ~41ms,
42
+ * 1000-file burst handled 1:1 with chokidar@5), but a single flat
43
+ * directory with tens of thousands of entries would rescan slowly. If that
44
+ * happens, use the filename argument from fs.watch's callback to stat only
45
+ * that entry, falling back to a full rescan when it's null.
46
+ *
47
+ * 3. Linux inotify limits apply (as they do to chokidar).
48
+ * One watch descriptor per directory, capped by
49
+ * /proc/sys/fs/inotify/max_user_watches (typically 8k–128k). Always pass
50
+ * `ignored` for node_modules/.git/build-output dirs on big repos.
51
+ *
52
+ * 4. Not implemented (unused by this project): add()/unwatch()/getWatched(),
53
+ * depth, cwd, alwaysStat, atomic, followSymlinks:false (symlinked dirs are
54
+ * watched, with realpath-based cycle protection), and sub-mtime-resolution
55
+ * edge: a rewrite with identical size landing in the same mtime tick is
56
+ * undetectable by stat diffing (theoretical on ext4/APFS/NTFS — ns mtime).
57
+ */
58
+ "use strict";
59
+
60
+ const fs = require("fs");
61
+ const path = require("path");
62
+ const { EventEmitter } = require("events");
63
+
64
+ const SCAN_DEBOUNCE = 25; // coalesce fs.watch event bursts per directory
65
+ const ROOT_POLL = 1000; // how often to look for a missing watched root
66
+
67
+ function normalizeIgnored(ignored) {
68
+ if (!ignored) return () => false;
69
+ const list = Array.isArray(ignored) ? ignored : [ignored];
70
+ return p =>
71
+ list.some(entry => {
72
+ if (typeof entry === "function") return entry(p);
73
+ if (entry instanceof RegExp) return entry.test(p);
74
+ return p === entry || p.startsWith(entry + path.sep); // plain path prefix
75
+ });
76
+ }
77
+
78
+ class FSWatcher extends EventEmitter {
79
+ constructor(paths, options = {}) {
80
+ super();
81
+
82
+ this._persistent = options.persistent !== false;
83
+ this._ignoreInitial = !!options.ignoreInitial;
84
+ this._ignored = normalizeIgnored(options.ignored);
85
+
86
+ const awf = options.awaitWriteFinish;
87
+ // chokidar defaults: threshold 2000ms, poll 100ms when awaitWriteFinish: true
88
+ this._awf = awf ? { threshold: awf.stabilityThreshold || 2000, poll: awf.pollInterval || 100 } : null;
89
+
90
+ this._roots = (Array.isArray(paths) ? paths : [paths]).map(p => path.resolve(p));
91
+ this._watchers = new Map(); // dir → fs.FSWatcher
92
+ this._snapshots = new Map(); // dir → Map(name → { isDir, mtimeMs, size })
93
+ this._scanTimers = new Map(); // dir → debounce timeout
94
+ this._pending = new Map(); // file → awaitWriteFinish poll state
95
+ this._rootTimers = new Map(); // missing root → poll interval
96
+ this._realPaths = new Set(); // real paths of watched dirs (symlink-cycle guard)
97
+ this._realByDir = new Map(); // dir → its real path, for cleanup
98
+ this._closed = false;
99
+
100
+ process.nextTick(() => {
101
+ if (this._closed) return;
102
+ for (const root of this._roots) this._addRoot(root, true);
103
+ this.emit("ready");
104
+ });
105
+ }
106
+
107
+ // ------------------------------------------------------------ setup
108
+ _addRoot(root, isInitial) {
109
+ let stat;
110
+ try {
111
+ stat = fs.statSync(root);
112
+ } catch (e) {
113
+ this._waitForRoot(root);
114
+ return;
115
+ }
116
+ if (stat.isDirectory()) {
117
+ // chokidar reports the watched root itself, subject to ignoreInitial
118
+ if (!(isInitial && this._ignoreInitial)) this.emit("addDir", root);
119
+ this._watchDir(root, isInitial);
120
+ }
121
+ // single-file roots: watch the parent dir but only report this file
122
+ else this._watchDir(path.dirname(root), isInitial, root);
123
+ }
124
+
125
+ _waitForRoot(root) {
126
+ if (this._closed || this._rootTimers.has(root)) return;
127
+ const timer = setInterval(() => {
128
+ if (fs.existsSync(root)) {
129
+ clearInterval(timer);
130
+ this._rootTimers.delete(root);
131
+ this._addRoot(root, false); // appeared later → its contents are new adds
132
+ }
133
+ }, ROOT_POLL);
134
+ if (!this._persistent && timer.unref) timer.unref();
135
+ this._rootTimers.set(root, timer);
136
+ }
137
+
138
+ _watchDir(dir, isInitial, onlyFile) {
139
+ if (this._closed || this._watchers.has(dir) || this._ignored(dir)) return;
140
+
141
+ // symlink-cycle guard: a link pointing back into the watched tree must not
142
+ // cause infinite recursion — track the real path of every watched dir
143
+ let real;
144
+ try {
145
+ real = fs.realpathSync(dir);
146
+ } catch (e) {
147
+ return;
148
+ }
149
+ if (this._realPaths.has(real)) return;
150
+ this._realPaths.add(real);
151
+ this._realByDir.set(dir, real);
152
+
153
+ let watcher;
154
+ try {
155
+ watcher = fs.watch(dir, { persistent: this._persistent });
156
+ } catch (err) {
157
+ this.emit("error", err);
158
+ return;
159
+ }
160
+ // fs.watch errors (e.g. EPERM on windows when the dir is deleted) are not
161
+ // fatal: the parent directory's rescan tears this watcher down
162
+ watcher.on("error", () => watcher.close());
163
+ watcher.on("change", () => this._scheduleScan(dir));
164
+
165
+ this._watchers.set(dir, watcher);
166
+ this._snapshots.set(dir, new Map());
167
+ if (onlyFile) this._onlyFile = onlyFile;
168
+ this._rescan(dir, isInitial);
169
+ }
170
+
171
+ // ------------------------------------------------------------ scanning
172
+ _scheduleScan(dir) {
173
+ if (this._closed || this._scanTimers.has(dir)) return;
174
+ this._scanTimers.set(
175
+ dir,
176
+ setTimeout(() => {
177
+ this._scanTimers.delete(dir);
178
+ this._rescan(dir, false);
179
+ }, SCAN_DEBOUNCE)
180
+ );
181
+ }
182
+
183
+ _rescan(dir, isInitial) {
184
+ if (this._closed || !this._snapshots.has(dir)) return;
185
+
186
+ let names;
187
+ try {
188
+ names = fs.readdirSync(dir);
189
+ } catch (e) {
190
+ // directory itself vanished
191
+ this._teardownDir(dir, true);
192
+ if (this._roots.includes(dir)) this._waitForRoot(dir);
193
+ return;
194
+ }
195
+
196
+ const old = this._snapshots.get(dir);
197
+ const next = new Map();
198
+
199
+ for (const name of names) {
200
+ const full = path.join(dir, name);
201
+ if (this._ignored(full)) continue;
202
+
203
+ let stat;
204
+ try {
205
+ stat = fs.statSync(full);
206
+ } catch (e) {
207
+ continue; // deleted between readdir and stat
208
+ }
209
+
210
+ const entry = { isDir: stat.isDirectory(), mtimeMs: stat.mtimeMs, size: stat.size };
211
+ next.set(name, entry);
212
+
213
+ const prev = old.get(name);
214
+ const silent = isInitial && this._ignoreInitial;
215
+
216
+ if (!prev) {
217
+ if (entry.isDir) {
218
+ if (!silent) this.emit("addDir", full);
219
+ this._watchDir(full, isInitial); // walks and reports its contents
220
+ } else if (!silent) {
221
+ this._settle(full, "add");
222
+ }
223
+ } else if (prev.isDir !== entry.isDir) {
224
+ // replaced by the other kind: unlink the old, add the new
225
+ if (prev.isDir) this._teardownDir(full, true);
226
+ else this.emit("unlink", full);
227
+ if (entry.isDir) {
228
+ this.emit("addDir", full);
229
+ this._watchDir(full, false);
230
+ } else {
231
+ this._settle(full, "add");
232
+ }
233
+ } else if (!entry.isDir && (prev.mtimeMs !== entry.mtimeMs || prev.size !== entry.size)) {
234
+ this._settle(full, "change");
235
+ }
236
+ }
237
+
238
+ for (const [name, prev] of old) {
239
+ if (next.has(name)) continue;
240
+ const full = path.join(dir, name);
241
+ if (prev.isDir) this._teardownDir(full, true);
242
+ else this._dropFile(full);
243
+ }
244
+
245
+ this._snapshots.set(dir, next);
246
+ }
247
+
248
+ _dropFile(file) {
249
+ const pending = this._pending.get(file);
250
+ if (pending) {
251
+ clearInterval(pending.timer);
252
+ this._pending.delete(file);
253
+ // a file that vanished while its "add" was still stabilizing was never
254
+ // reported, so there is nothing to unlink
255
+ if (pending.event === "add") return;
256
+ }
257
+ this.emit("unlink", file);
258
+ }
259
+
260
+ _teardownDir(dir, emitEvents) {
261
+ const watcher = this._watchers.get(dir);
262
+ if (watcher) watcher.close();
263
+ this._watchers.delete(dir);
264
+
265
+ const real = this._realByDir.get(dir);
266
+ if (real !== undefined) {
267
+ this._realPaths.delete(real);
268
+ this._realByDir.delete(dir);
269
+ }
270
+
271
+ const timer = this._scanTimers.get(dir);
272
+ if (timer) clearTimeout(timer);
273
+ this._scanTimers.delete(dir);
274
+
275
+ const snapshot = this._snapshots.get(dir);
276
+ this._snapshots.delete(dir);
277
+ if (!snapshot) return;
278
+
279
+ for (const [name, entry] of snapshot) {
280
+ const full = path.join(dir, name);
281
+ if (entry.isDir) this._teardownDir(full, emitEvents);
282
+ else if (emitEvents) this._dropFile(full);
283
+ }
284
+ if (emitEvents) this.emit("unlinkDir", dir);
285
+ }
286
+
287
+ // ------------------------------------------------- awaitWriteFinish
288
+ _settle(file, event) {
289
+ if (this._onlyFile && file !== this._onlyFile) return; // single-file root filter
290
+
291
+ if (!this._awf) return this.emit(event, file);
292
+
293
+ // an event already stabilizing keeps its original type: more writes while
294
+ // an "add" settles must still surface as a single "add", not a "change"
295
+ const existing = this._pending.get(file);
296
+ if (existing) {
297
+ existing.stableSince = Date.now();
298
+ return;
299
+ }
300
+
301
+ const state = { event, stableSince: Date.now(), mtimeMs: -1, size: -1, timer: null };
302
+ state.timer = setInterval(() => {
303
+ let stat;
304
+ try {
305
+ stat = fs.statSync(file);
306
+ } catch (e) {
307
+ clearInterval(state.timer); // vanished mid-write; unlink comes from the dir rescan
308
+ this._pending.delete(file);
309
+ return;
310
+ }
311
+ if (stat.mtimeMs !== state.mtimeMs || stat.size !== state.size) {
312
+ state.mtimeMs = stat.mtimeMs;
313
+ state.size = stat.size;
314
+ state.stableSince = Date.now();
315
+ return;
316
+ }
317
+ if (Date.now() - state.stableSince >= this._awf.threshold) {
318
+ clearInterval(state.timer);
319
+ this._pending.delete(file);
320
+ this.emit(state.event, file);
321
+ }
322
+ }, this._awf.poll);
323
+ this._pending.set(file, state);
324
+ }
325
+
326
+ // ------------------------------------------------------------ teardown
327
+ close() {
328
+ this._closed = true;
329
+ for (const watcher of this._watchers.values()) watcher.close();
330
+ for (const timer of this._scanTimers.values()) clearTimeout(timer);
331
+ for (const state of this._pending.values()) clearInterval(state.timer);
332
+ for (const timer of this._rootTimers.values()) clearInterval(timer);
333
+ this._watchers.clear();
334
+ this._scanTimers.clear();
335
+ this._pending.clear();
336
+ this._rootTimers.clear();
337
+ this._snapshots.clear();
338
+ this._realPaths.clear();
339
+ this._realByDir.clear();
340
+ return Promise.resolve();
341
+ }
342
+ }
343
+
344
+ module.exports = { watch: (paths, options) => new FSWatcher(paths, options), FSWatcher };