@decohere/flux 0.0.1-dev.12 → 0.0.1-dev.121

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 (47) hide show
  1. package/README.md +273 -0
  2. package/commonjs/src/deferred-script-runner.js +56 -0
  3. package/commonjs/src/flux.command.js +3 -3
  4. package/commonjs/src/flux.js +56 -0
  5. package/commonjs/src/flux.module.js +9 -8
  6. package/commonjs/src/hot-reload-server.js +307 -219
  7. package/commonjs/src/index.js +34 -2
  8. package/commonjs/src/rewrite-serve-specifier.js +61 -0
  9. package/commonjs/src/run.action.js +47 -0
  10. package/commonjs/src/run.command.js +65 -0
  11. package/commonjs/src/serve.action.js +78 -7
  12. package/commonjs/src/serve.command.js +35 -4
  13. package/commonjs/src/slice-serve.js +130 -0
  14. package/commonjs/src/source-module-loader.js +378 -0
  15. package/commonjs/src/static-imports.js +37 -0
  16. package/commonjs/src/transpile-disk-cache.js +148 -0
  17. package/es6/src/deferred-script-runner.js +46 -0
  18. package/es6/src/flux.command.js +3 -3
  19. package/es6/src/flux.js +41 -0
  20. package/es6/src/flux.module.js +9 -8
  21. package/es6/src/hot-reload-server.js +287 -175
  22. package/es6/src/index.js +5 -3
  23. package/es6/src/rewrite-serve-specifier.js +51 -0
  24. package/es6/src/run.action.js +37 -0
  25. package/es6/src/run.command.js +55 -0
  26. package/es6/src/serve.action.js +73 -9
  27. package/es6/src/serve.command.js +35 -4
  28. package/es6/src/slice-serve.js +105 -0
  29. package/es6/src/source-module-loader.js +322 -0
  30. package/es6/src/static-imports.js +27 -0
  31. package/es6/src/transpile-disk-cache.js +142 -0
  32. package/package.json +8 -6
  33. package/types/src/deferred-script-runner.d.ts +18 -0
  34. package/types/src/flux.command.d.ts +2 -2
  35. package/types/src/flux.d.ts +43 -0
  36. package/types/src/flux.module.d.ts +6 -4
  37. package/types/src/hot-reload-server.d.ts +57 -23
  38. package/types/src/index.d.ts +8 -1
  39. package/types/src/rewrite-serve-specifier.d.ts +14 -0
  40. package/types/src/run.action.d.ts +15 -0
  41. package/types/src/run.command.d.ts +11 -0
  42. package/types/src/serve.action.d.ts +13 -3
  43. package/types/src/serve.command.d.ts +7 -1
  44. package/types/src/slice-serve.d.ts +52 -0
  45. package/types/src/source-module-loader.d.ts +96 -0
  46. package/types/src/static-imports.d.ts +5 -0
  47. package/types/src/transpile-disk-cache.d.ts +38 -0
@@ -0,0 +1,378 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "SourceModuleLoader", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return SourceModuleLoader;
9
+ }
10
+ });
11
+ const _nodefs = require("node:fs");
12
+ const _nodemodule = require("node:module");
13
+ const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
14
+ const _nodeurl = require("node:url");
15
+ const _decorators = require("@decohere/crucible/decorators");
16
+ const _forge = require("@decohere/forge");
17
+ const _workspace = require("@decohere/workspace");
18
+ const _io = require("@decohere/core/io");
19
+ const _scribe = require("@decohere/scribe");
20
+ const _rewriteservespecifier = require("./rewrite-serve-specifier.js");
21
+ const _staticimports = require("./static-imports.js");
22
+ const _transpilediskcache = require("./transpile-disk-cache.js");
23
+ function _interop_require_default(obj) {
24
+ return obj && obj.__esModule ? obj : {
25
+ default: obj
26
+ };
27
+ }
28
+ function _getRequireWildcardCache(nodeInterop) {
29
+ if (typeof WeakMap !== "function") return null;
30
+ var cacheBabelInterop = new WeakMap();
31
+ var cacheNodeInterop = new WeakMap();
32
+ return (_getRequireWildcardCache = function(nodeInterop) {
33
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
34
+ })(nodeInterop);
35
+ }
36
+ function _interop_require_wildcard(obj, nodeInterop) {
37
+ if (!nodeInterop && obj && obj.__esModule) {
38
+ return obj;
39
+ }
40
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
41
+ return {
42
+ default: obj
43
+ };
44
+ }
45
+ var cache = _getRequireWildcardCache(nodeInterop);
46
+ if (cache && cache.has(obj)) {
47
+ return cache.get(obj);
48
+ }
49
+ var newObj = {
50
+ __proto__: null
51
+ };
52
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
53
+ for(var key in obj){
54
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
55
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
56
+ if (desc && (desc.get || desc.set)) {
57
+ Object.defineProperty(newObj, key, desc);
58
+ } else {
59
+ newObj[key] = obj[key];
60
+ }
61
+ }
62
+ }
63
+ newObj.default = obj;
64
+ if (cache) {
65
+ cache.set(obj, newObj);
66
+ }
67
+ return newObj;
68
+ }
69
+ function _ts_decorate(decorators, target, key, desc) {
70
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
71
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
72
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
73
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
74
+ }
75
+ class SourceModuleLoader {
76
+ logger = _scribe.scribe.logger(SourceModuleLoader.name);
77
+ transpiler = new _forge.SwcTranspiler();
78
+ disposed = false;
79
+ hooksRegistered = false;
80
+ workspace;
81
+ buildConfig = "debug";
82
+ fileInfoMap = new Map();
83
+ transpileCache = new Map();
84
+ /** Bumped when a file's cached code is dropped, so an up-front compile already running can't put it back. */ transpileVersions = new Map();
85
+ /** The source files each entry's walk reached, so a reboot only walks out from what changed. */ reachedFrom = new Map();
86
+ /** Compiled code on disk across runs (#514); null when caching is off. */ diskCache = null;
87
+ /** Up-front compiles in flight, shared by entries booting at the same time. */ compilingAhead = new Map();
88
+ /** SWC options per project, built on first use and kept until the next `configure()`. */ swcConfigs = new Map();
89
+ commonJsConfigs = new Map();
90
+ aliasPaths = {};
91
+ aliasBaseUrl = _nodepath.default.resolve(".");
92
+ versionFileUrl = (fileUrl)=>fileUrl;
93
+ onResolved;
94
+ getWorkspace() {
95
+ return this.workspace;
96
+ }
97
+ hasSourceFile(absolutePath) {
98
+ return this.fileInfoMap.has(absolutePath);
99
+ }
100
+ sourceFilePaths() {
101
+ return this.fileInfoMap.keys();
102
+ }
103
+ setSourceFile(absolutePath, project) {
104
+ this.fileInfoMap.set(absolutePath, {
105
+ project
106
+ });
107
+ }
108
+ async configure(options) {
109
+ this.disposed = false;
110
+ // A new Map, not clear(): an up-front compile from before can't write into this one.
111
+ this.transpileCache = new Map();
112
+ this.reachedFrom = new Map();
113
+ this.swcConfigs.clear();
114
+ this.commonJsConfigs.clear();
115
+ this.buildConfig = options.buildConfig;
116
+ this.workspace = options.workspace ?? await (0, _forge.createWorkspace)();
117
+ this.versionFileUrl = options.versionFileUrl ?? ((fileUrl)=>fileUrl);
118
+ this.onResolved = options.onResolved;
119
+ this.fileInfoMap = await this.buildFileInfoMap(this.buildConfig);
120
+ this.diskCache = _transpilediskcache.TranspileDiskCache.forWorkspace(this.workspace.rootDir);
121
+ // In the background; it turns the cache off, with a warning, rather than throw.
122
+ void this.diskCache?.pruneIfDue();
123
+ const aliases = this.workspace.getPackageAliases(this.buildConfig);
124
+ this.aliasBaseUrl = aliases.baseUrl;
125
+ this.aliasPaths = aliases.paths;
126
+ }
127
+ registerHooks() {
128
+ if (this.hooksRegistered) return;
129
+ this.hooksRegistered = true;
130
+ // Compiled code carries inline source maps; Node only applies them to stack traces when
131
+ // this is on. Without it, errors point at compiled line numbers (#506).
132
+ process.setSourceMapsEnabled(true);
133
+ (0, _nodemodule.registerHooks)({
134
+ resolve: (specifier, context, next)=>{
135
+ if (this.disposed) return next(specifier, context);
136
+ const parentUrl = context.parentURL ?? "";
137
+ const rewritten = (0, _rewriteservespecifier.rewriteServeSpecifier)({
138
+ specifier,
139
+ parentUrl,
140
+ isWatchedTs: (filePath)=>this.fileInfoMap.has(filePath),
141
+ resolveBare: (bare)=>_workspace.packageAliases.resolvePath(bare, this.aliasPaths, this.aliasBaseUrl),
142
+ versionFileUrl: this.versionFileUrl
143
+ }) ?? specifier;
144
+ const result = next(rewritten, context);
145
+ this.onResolved?.(result, parentUrl);
146
+ return result;
147
+ },
148
+ load: (url, context, next)=>{
149
+ if (this.disposed) return next(url, context);
150
+ const result = this.loadTs(url);
151
+ if (result != null) {
152
+ return {
153
+ format: result.format,
154
+ source: result.source,
155
+ shortCircuit: true
156
+ };
157
+ }
158
+ return next(url, context);
159
+ }
160
+ });
161
+ }
162
+ async importEntry(absolutePath) {
163
+ await this.compileAhead(_nodepath.default.resolve(absolutePath));
164
+ const url = this.versionFileUrl(_io.io.pathToFileUrl(_nodepath.default.resolve(absolutePath)));
165
+ return Promise.resolve(url).then((p)=>/*#__PURE__*/ _interop_require_wildcard(require(p)));
166
+ }
167
+ invalidateTranspile(...absolutePaths) {
168
+ for (const fullPath of absolutePaths){
169
+ this.transpileCache.delete(fullPath);
170
+ this.transpileVersions.set(fullPath, (this.transpileVersions.get(fullPath) ?? 0) + 1);
171
+ }
172
+ }
173
+ dispose() {
174
+ this.disposed = true;
175
+ this.transpileCache = new Map();
176
+ this.reachedFrom = new Map();
177
+ this.swcConfigs.clear();
178
+ this.commonJsConfigs.clear();
179
+ this.fileInfoMap.clear();
180
+ this.workspace?.[Symbol.dispose]();
181
+ this.workspace = undefined;
182
+ }
183
+ async buildFileInfoMap(buildConfig) {
184
+ const projects = this.workspace?.getProjects(buildConfig) ?? [];
185
+ const entries = await Promise.all(projects.map(async (project)=>{
186
+ const files = await project.getAllFiles();
187
+ return files.map((file)=>[
188
+ file.fullPath,
189
+ {
190
+ project
191
+ }
192
+ ]);
193
+ }));
194
+ return new Map(entries.flat());
195
+ }
196
+ /**
197
+ * Compiles the entry and the source files it imports, before Node imports it (#661). The load
198
+ * hook is synchronous, so it would compile one file at a time on the main thread; async SWC
199
+ * runs on the thread pool. Walks out from the entry, compiling each file's imports in parallel,
200
+ * so files the app never imports (tests, other apps) are not compiled. A reboot walks out only
201
+ * from the files it reached before that are no longer cached (the saved ones), so their new
202
+ * imports are found without visiting the rest of the graph again.
203
+ *
204
+ * A file that fails here is left out of the cache instead of failing the boot: the load hook
205
+ * then compiles it again and throws as before, naming the file. The walk is a hint; whatever
206
+ * it misses is compiled by the load hook when Node gets to it.
207
+ */ async compileAhead(entryPath) {
208
+ const reached = this.reachedFrom.get(entryPath);
209
+ const starts = reached == null ? [
210
+ entryPath
211
+ ] : [
212
+ ...reached
213
+ ].filter((fullPath)=>!this.transpileCache.has(fullPath));
214
+ const seen = new Set(reached);
215
+ for (const start of starts)seen.delete(start);
216
+ const visit = async (fullPath)=>{
217
+ if (seen.has(fullPath)) return;
218
+ seen.add(fullPath);
219
+ const code = await this.compiledAhead(fullPath);
220
+ if (code == null) return;
221
+ const parentUrl = (0, _nodeurl.pathToFileURL)(fullPath).toString();
222
+ await Promise.all(_staticimports.staticImports.scan(code).map((specifier)=>{
223
+ const target = this.sourcePathOf(specifier, parentUrl);
224
+ return target == null ? undefined : visit(target);
225
+ }));
226
+ };
227
+ await Promise.all(starts.map(visit));
228
+ this.reachedFrom.set(entryPath, seen);
229
+ }
230
+ /** The file's compiled code, from the cache or compiled now; undefined if it isn't a source. */ compiledAhead(fullPath) {
231
+ const fileInfo = this.fileInfoMap.get(fullPath);
232
+ if (fileInfo == null) return Promise.resolve(undefined);
233
+ const cached = this.transpileCache.get(fullPath);
234
+ if (cached != null) return Promise.resolve(cached);
235
+ const inFlight = this.compilingAhead.get(fullPath);
236
+ if (inFlight != null) return inFlight;
237
+ const version = this.transpileVersions.get(fullPath);
238
+ const cache = this.transpileCache;
239
+ const compiling = this.compileAsync(fullPath, fileInfo.project).then((code)=>{
240
+ if (code == null) return undefined;
241
+ // Saved, reconfigured or disposed while compiling: don't cache stale code.
242
+ const current = !this.disposed && cache === this.transpileCache && version === this.transpileVersions.get(fullPath);
243
+ if (current) cache.set(fullPath, code);
244
+ return code;
245
+ }).finally(()=>this.compilingAhead.delete(fullPath));
246
+ this.compilingAhead.set(fullPath, compiling);
247
+ return compiling;
248
+ }
249
+ /** The source file a specifier names, mapped the way the resolve hook maps it. */ sourcePathOf(specifier, parentUrl) {
250
+ const url = (0, _rewriteservespecifier.rewriteServeSpecifier)({
251
+ specifier,
252
+ parentUrl,
253
+ isWatchedTs: (filePath)=>this.fileInfoMap.has(filePath),
254
+ resolveBare: (bare)=>_workspace.packageAliases.resolvePath(bare, this.aliasPaths, this.aliasBaseUrl),
255
+ versionFileUrl: (fileUrl)=>fileUrl
256
+ });
257
+ return url == null ? null : (0, _nodeurl.fileURLToPath)(url);
258
+ }
259
+ loadTs(url) {
260
+ if (!url.startsWith("file:")) return null;
261
+ // fileURLToPath, not URL.pathname: decodes %20 and gives Windows paths, so files
262
+ // whose path has a space still match the workspace's package list (#511).
263
+ const cleanPath = (0, _nodeurl.fileURLToPath)(url);
264
+ const fileInfo = this.fileInfoMap.get(cleanPath);
265
+ if (fileInfo == null) return null;
266
+ const format = _workspace.sourceExtensions.isCommonJs(cleanPath) ? "commonjs" : "module";
267
+ const cached = this.transpileCache.get(cleanPath);
268
+ if (cached != null) return {
269
+ source: cached,
270
+ format
271
+ };
272
+ const code = this.compileSync(cleanPath, fileInfo.project);
273
+ this.transpileCache.set(cleanPath, code);
274
+ return {
275
+ source: code,
276
+ format
277
+ };
278
+ }
279
+ /**
280
+ * Compiles a file for the load hook, through the disk cache (#514). Throws, naming the file,
281
+ * when it can't be read or doesn't compile.
282
+ */ compileSync(fullPath, project) {
283
+ const file = new _io.FileEx({
284
+ fullPath
285
+ });
286
+ const baseConfig = this.swcConfigFor(project, fullPath);
287
+ let source;
288
+ try {
289
+ source = (0, _nodefs.readFileSync)(fullPath, "utf8");
290
+ } catch (error) {
291
+ this.logger.error(`Failed to transpile ${fullPath}`, error);
292
+ throw new Error(`Failed to transpile ${fullPath}`, {
293
+ cause: error
294
+ });
295
+ }
296
+ const key = this.diskCache?.keyFor(fullPath, source, baseConfig);
297
+ const hit = key == null ? undefined : this.diskCache?.readSync(key);
298
+ if (hit != null) return hit;
299
+ const response = this.transpiler.transformCodeSync(source, file, _forge.BuildTargets.es6, baseConfig);
300
+ if (response.outcome !== "success") {
301
+ this.logger.error(`Failed to transpile ${fullPath}`, response);
302
+ throw new Error(`Failed to transpile ${fullPath}`);
303
+ }
304
+ if (key != null) this.diskCache?.writeSync(key, response.code);
305
+ return response.code;
306
+ }
307
+ /**
308
+ * Compiles a file ahead, through the disk cache; undefined when it doesn't compile, which the
309
+ * load hook then reports (see {@link compileAhead}). The source and the cache entry are read
310
+ * synchronously: for small files that is far cheaper than a trip through libuv's thread pool,
311
+ * which async SWC needs for the compiles that miss (#514).
312
+ */ async compileAsync(fullPath, project) {
313
+ const file = new _io.FileEx({
314
+ fullPath
315
+ });
316
+ const baseConfig = this.swcConfigFor(project, fullPath);
317
+ let source;
318
+ try {
319
+ source = (0, _nodefs.readFileSync)(fullPath, "utf8");
320
+ } catch {
321
+ // Left to the load hook, which reads it again and fails naming it, as for a file
322
+ // that doesn't compile.
323
+ return undefined;
324
+ }
325
+ const key = this.diskCache?.keyFor(fullPath, source, baseConfig);
326
+ const hit = key == null ? undefined : this.diskCache?.readSync(key);
327
+ if (hit != null) return hit;
328
+ const response = await this.transpiler.transformCode(source, file, _forge.BuildTargets.es6, baseConfig);
329
+ if (response.outcome !== "success") return undefined;
330
+ if (key != null) await this.diskCache?.write(key, response.code);
331
+ return response.code;
332
+ }
333
+ /**
334
+ * The project's SWC options, built once: rebuilding them for every file was about a quarter
335
+ * of load time (#513). Import specifiers are left as written, without `jsc.paths` or
336
+ * `resolveFully`: the resolve hook maps them to source files (aliases, `.js` to `.ts`,
337
+ * directory indexes), so SWC does not resolve them a second time against the disk.
338
+ */ swcConfigFor(project, fullPath) {
339
+ const config = this.esModuleConfigFor(project);
340
+ if (!_workspace.sourceExtensions.isCommonJs(fullPath)) return config;
341
+ // `.cts` is CommonJS: Node loads it with `require` semantics, so SWC emits CommonJS (#518).
342
+ // Kept per project, like the ES module options, so the disk cache hashes them once.
343
+ const cached = this.commonJsConfigs.get(project);
344
+ if (cached != null) return cached;
345
+ const commonJs = {
346
+ ...config,
347
+ module: {
348
+ type: "commonjs"
349
+ }
350
+ };
351
+ this.commonJsConfigs.set(project, commonJs);
352
+ return commonJs;
353
+ }
354
+ esModuleConfigFor(project) {
355
+ const cached = this.swcConfigs.get(project);
356
+ if (cached != null) return cached;
357
+ const base = this.transpiler.createBaseConfig(_forge.BuildTargets.es6, {
358
+ tsConfig: project.getTsConfigSync(),
359
+ userConfig: project.getSwcConfigSync(),
360
+ aliasPaths: false,
361
+ workspace: this.workspace
362
+ });
363
+ // `module` is the ES module config (`type: "es6"` above); the spread loses the narrowing.
364
+ const module = {
365
+ ...base.module,
366
+ resolveFully: false
367
+ };
368
+ const config = {
369
+ ...base,
370
+ module
371
+ };
372
+ this.swcConfigs.set(project, config);
373
+ return config;
374
+ }
375
+ }
376
+ SourceModuleLoader = _ts_decorate([
377
+ (0, _decorators.injectable)()
378
+ ], SourceModuleLoader);
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "staticImports", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return staticImports;
9
+ }
10
+ });
11
+ /**
12
+ * The module specifiers a compiled ES module names in `import … from`, `export … from`, bare
13
+ * `import "x"` and literal `import("x")`.
14
+ *
15
+ * Only a hint for compiling ahead (#661): a specifier it misses is compiled when Node loads it,
16
+ * and one it finds by mistake (an import written inside a string) costs one extra compile. So a
17
+ * scan of SWC's output is enough; it never decides what runs.
18
+ */ const STATIC = /\b(?:import|export)\s*(?:[\w$*{},\s]+?\s*from\s*)?["']([^"'\n]+)["']/g;
19
+ const DYNAMIC = /\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g;
20
+ function scan(code) {
21
+ const found = new Set();
22
+ for (const pattern of [
23
+ STATIC,
24
+ DYNAMIC
25
+ ]){
26
+ for (const match of code.matchAll(pattern)){
27
+ const specifier = match[1];
28
+ if (specifier != null) found.add(specifier);
29
+ }
30
+ }
31
+ return [
32
+ ...found
33
+ ];
34
+ }
35
+ const staticImports = {
36
+ scan
37
+ };
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "TranspileDiskCache", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return TranspileDiskCache;
9
+ }
10
+ });
11
+ const _nodecrypto = require("node:crypto");
12
+ const _nodefs = /*#__PURE__*/ _interop_require_default(require("node:fs"));
13
+ const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
14
+ const _forge = require("@decohere/forge");
15
+ const _scribe = require("@decohere/scribe");
16
+ function _interop_require_default(obj) {
17
+ return obj && obj.__esModule ? obj : {
18
+ default: obj
19
+ };
20
+ }
21
+ /** Bump when what flux stores changes, so older entries stop matching. */ const FORMAT = 1;
22
+ /** Entries untouched for this long are pruned. */ const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
23
+ /** Pruning runs at most this often, recorded by the mtime of a marker file. */ const PRUNE_EVERY_MS = 24 * 60 * 60 * 1000;
24
+ const PRUNE_MARKER = ".last-prune";
25
+ class TranspileDiskCache {
26
+ dir;
27
+ logger = _scribe.scribe.logger(TranspileDiskCache.name);
28
+ disabled = false;
29
+ constructor(dir){
30
+ this.dir = dir;
31
+ }
32
+ /** The cache for a workspace, or null when caching is off (`DECOHERE_CACHE=0`). */ static forWorkspace(rootDir) {
33
+ const base = _forge.transpileCache.directory(rootDir);
34
+ return base == null ? null : new TranspileDiskCache(_nodepath.default.join(base, "flux"));
35
+ }
36
+ get directory() {
37
+ return this.dir;
38
+ }
39
+ /**
40
+ * The key for a file compiled with `baseOptions`: the per-file options are those plus the
41
+ * file's path (forge's `createFileConfig`), so hashing the base once per project and adding
42
+ * the path covers them without serialising options for every file.
43
+ */ keyFor(fullPath, source, baseOptions) {
44
+ return (0, _nodecrypto.createHash)("sha256").update(`${FORMAT}\0${_forge.transpileCache.swcVersion}\0${this.optionsHash(baseOptions)}\0`).update(`${fullPath}\0`).update(source).digest("hex");
45
+ }
46
+ optionsHashes = new WeakMap();
47
+ optionsHash(options) {
48
+ const cached = this.optionsHashes.get(options);
49
+ if (cached != null) return cached;
50
+ const hash = (0, _nodecrypto.createHash)("sha256").update(JSON.stringify(options)).digest("hex");
51
+ this.optionsHashes.set(options, hash);
52
+ return hash;
53
+ }
54
+ readSync(key) {
55
+ if (this.disabled) return undefined;
56
+ try {
57
+ return _nodefs.default.readFileSync(this.entryPath(key), "utf8");
58
+ } catch (error) {
59
+ return this.missOrDisable(error);
60
+ }
61
+ }
62
+ async read(key) {
63
+ if (this.disabled) return undefined;
64
+ try {
65
+ return await _nodefs.default.promises.readFile(this.entryPath(key), "utf8");
66
+ } catch (error) {
67
+ return this.missOrDisable(error);
68
+ }
69
+ }
70
+ writeSync(key, code) {
71
+ if (this.disabled) return;
72
+ const file = this.entryPath(key);
73
+ const temp = this.tempPath(file);
74
+ try {
75
+ _nodefs.default.mkdirSync(_nodepath.default.dirname(file), {
76
+ recursive: true
77
+ });
78
+ _nodefs.default.writeFileSync(temp, code);
79
+ _nodefs.default.renameSync(temp, file);
80
+ } catch (error) {
81
+ this.disable("write", error);
82
+ }
83
+ }
84
+ async write(key, code) {
85
+ if (this.disabled) return;
86
+ const file = this.entryPath(key);
87
+ const temp = this.tempPath(file);
88
+ try {
89
+ await _nodefs.default.promises.mkdir(_nodepath.default.dirname(file), {
90
+ recursive: true
91
+ });
92
+ await _nodefs.default.promises.writeFile(temp, code);
93
+ await _nodefs.default.promises.rename(temp, file);
94
+ } catch (error) {
95
+ this.disable("write", error);
96
+ }
97
+ }
98
+ /** Deletes entries older than 30 days, if it hasn't done so in the last day. */ async pruneIfDue(now = Date.now()) {
99
+ if (this.disabled) return;
100
+ const marker = _nodepath.default.join(this.dir, PRUNE_MARKER);
101
+ try {
102
+ const last = await _nodefs.default.promises.stat(marker).then((stat)=>stat.mtimeMs, (error)=>{
103
+ if (error.code === "ENOENT") return 0;
104
+ throw error;
105
+ });
106
+ if (now - last < PRUNE_EVERY_MS) return;
107
+ await _nodefs.default.promises.mkdir(this.dir, {
108
+ recursive: true
109
+ });
110
+ await _nodefs.default.promises.writeFile(marker, "");
111
+ for (const shard of (await _nodefs.default.promises.readdir(this.dir, {
112
+ withFileTypes: true
113
+ }))){
114
+ if (!shard.isDirectory()) continue;
115
+ const shardDir = _nodepath.default.join(this.dir, shard.name);
116
+ for (const entry of (await _nodefs.default.promises.readdir(shardDir))){
117
+ // Old entries, and temp files a crashed process left mid-write.
118
+ const file = _nodepath.default.join(shardDir, entry);
119
+ const mtime = await _nodefs.default.promises.stat(file).then((stat)=>stat.mtimeMs, (error)=>{
120
+ // Renamed or removed by another process since the listing: nothing to prune.
121
+ if (error.code === "ENOENT") return undefined;
122
+ throw error;
123
+ });
124
+ if (mtime != null && now - mtime > MAX_AGE_MS) await _nodefs.default.promises.rm(file, {
125
+ force: true
126
+ });
127
+ }
128
+ }
129
+ } catch (error) {
130
+ this.disable("prune", error);
131
+ }
132
+ }
133
+ entryPath(key) {
134
+ return _nodepath.default.join(this.dir, key.slice(0, 2), `${key}.js`);
135
+ }
136
+ tempPath(file) {
137
+ return `${file}.${process.pid}.${(0, _nodecrypto.randomBytes)(4).toString("hex")}.tmp`;
138
+ }
139
+ /** A missing entry is a miss; any other read error turns the cache off. */ missOrDisable(error) {
140
+ if (error.code !== "ENOENT") this.disable("read", error);
141
+ return undefined;
142
+ }
143
+ disable(operation, error) {
144
+ if (this.disabled) return;
145
+ this.disabled = true;
146
+ this.logger.warn(`Transpile cache turned off for this run: could not ${operation} ${this.dir} (${String(error)}). ` + "Flux compiles without it. Set DECOHERE_CACHE_DIR to a writable directory, or DECOHERE_CACHE=0 to silence this.");
147
+ }
148
+ }
@@ -0,0 +1,46 @@
1
+ function _ts_decorate(decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ }
7
+ import { spawn } from "node:child_process";
8
+ import { injectable } from "@decohere/crucible/decorators";
9
+ import { detectPackageManager, packageManagerFromString } from "@decohere/devkit/interop";
10
+ import { scribe } from "@decohere/scribe";
11
+ export class DeferredScriptRunner {
12
+ logger = scribe.logger(DeferredScriptRunner.name);
13
+ children = [];
14
+ start(options) {
15
+ const pm = detectPackageManager(options.workspaceRoot) ?? packageManagerFromString("pnpm");
16
+ this.logger.info(`deferred ${options.label} — running ${pm.name} run ${options.script} in ${options.cwd}`);
17
+ const child = spawn(pm.name, [
18
+ "run",
19
+ options.script
20
+ ], {
21
+ cwd: options.cwd,
22
+ stdio: "inherit",
23
+ env: process.env,
24
+ shell: false
25
+ });
26
+ child.on("exit", (code, signal)=>{
27
+ if (signal) return;
28
+ if (code != null && code !== 0) {
29
+ this.logger.warn(`deferred ${options.label} exited with ${code}`);
30
+ }
31
+ });
32
+ this.children.push(child);
33
+ return child;
34
+ }
35
+ async [Symbol.asyncDispose]() {
36
+ for (const child of this.children){
37
+ if (!child.killed) {
38
+ child.kill("SIGTERM");
39
+ }
40
+ }
41
+ this.children.length = 0;
42
+ }
43
+ }
44
+ DeferredScriptRunner = _ts_decorate([
45
+ injectable()
46
+ ], DeferredScriptRunner);
@@ -1,4 +1,5 @@
1
- import { DecohereCommand } from "@decohere/nexus/cli";
1
+ import { DecohereCommand } from "@decohere/devkit/cli";
2
+ import { RunCommand } from "./run.command.js";
2
3
  import { ServeCommand } from "./serve.command.js";
3
4
  export class FluxCommand extends DecohereCommand {
4
5
  constructor(commands, handler){
@@ -6,6 +7,7 @@ export class FluxCommand extends DecohereCommand {
6
7
  this.exitOverride();
7
8
  this.registerSubcommand({
8
9
  serve: ServeCommand,
10
+ run: RunCommand,
9
11
  ...commands
10
12
  }, handler);
11
13
  }
@@ -13,5 +15,3 @@ export class FluxCommand extends DecohereCommand {
13
15
  return this.help();
14
16
  }
15
17
  }
16
-
17
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9ob21lL3J1bm5lci93b3JrL2RlY29oZXJlL2RlY29oZXJlL3Byb2plY3RzL2ZsdXgvc3JjL2ZsdXguY29tbWFuZC50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSB7IEFjdGlvbnMgfSBmcm9tIFwiQGRlY29oZXJlL25leHVzL2NsaVwiO1xuaW1wb3J0IHtcblx0dHlwZSBDb21tYW5kSGFuZGxlcixcblx0dHlwZSBDb21tYW5kUmVzcG9uc2UsXG5cdHR5cGUgQ29tbWFuZFR5cGUsXG5cdERlY29oZXJlQ29tbWFuZCxcbn0gZnJvbSBcIkBkZWNvaGVyZS9uZXh1cy9jbGlcIjtcbmltcG9ydCB7IFNlcnZlQ29tbWFuZCB9IGZyb20gXCIuL3NlcnZlLmNvbW1hbmQuanNcIjtcblxuZXhwb3J0IGNsYXNzIEZsdXhDb21tYW5kIGV4dGVuZHMgRGVjb2hlcmVDb21tYW5kIHtcblx0cHVibGljIGNvbnN0cnVjdG9yKGNvbW1hbmRzOiBSZWNvcmQ8c3RyaW5nLCBDb21tYW5kVHlwZT4sIGhhbmRsZXI6IENvbW1hbmRIYW5kbGVyKSB7XG5cdFx0c3VwZXIoRmx1eENvbW1hbmQpO1xuXHRcdHRoaXMuZXhpdE92ZXJyaWRlKCk7XG5cdFx0dGhpcy5yZWdpc3RlclN1YmNvbW1hbmQoeyBzZXJ2ZTogU2VydmVDb21tYW5kLCAuLi5jb21tYW5kcyB9LCBoYW5kbGVyKTtcblx0fVxuXG5cdHB1YmxpYyBydW4oX2FjdGlvbnM6IEFjdGlvbnMsIF9vcHRpb25zOiBuZXZlcik6IFByb21pc2U8Q29tbWFuZFJlc3BvbnNlPiB7XG5cdFx0cmV0dXJuIHRoaXMuaGVscCgpO1xuXHR9XG59XG4iXSwibmFtZXMiOlsiRGVjb2hlcmVDb21tYW5kIiwiU2VydmVDb21tYW5kIiwiRmx1eENvbW1hbmQiLCJjb21tYW5kcyIsImhhbmRsZXIiLCJleGl0T3ZlcnJpZGUiLCJyZWdpc3RlclN1YmNvbW1hbmQiLCJzZXJ2ZSIsInJ1biIsIl9hY3Rpb25zIiwiX29wdGlvbnMiLCJoZWxwIl0sIm1hcHBpbmdzIjoiQUFDQSxTQUlDQSxlQUFlLFFBQ1Qsc0JBQXNCO0FBQzdCLFNBQVNDLFlBQVksUUFBUSxxQkFBcUI7QUFFbEQsT0FBTyxNQUFNQyxvQkFBb0JGO0lBQ2hDLFlBQW1CRyxRQUFxQyxFQUFFQyxPQUF1QixDQUFFO1FBQ2xGLEtBQUssQ0FBQ0Y7UUFDTixJQUFJLENBQUNHLFlBQVk7UUFDakIsSUFBSSxDQUFDQyxrQkFBa0IsQ0FBQztZQUFFQyxPQUFPTjtZQUFjLEdBQUdFLFFBQVE7UUFBQyxHQUFHQztJQUMvRDtJQUVPSSxJQUFJQyxRQUFpQixFQUFFQyxRQUFlLEVBQTRCO1FBQ3hFLE9BQU8sSUFBSSxDQUFDQyxJQUFJO0lBQ2pCO0FBQ0QifQ==
@@ -0,0 +1,41 @@
1
+ import path from "node:path";
2
+ import { HotReloadServer } from "./hot-reload-server.js";
3
+ import { SourceModuleLoader } from "./source-module-loader.js";
4
+ /** Process-level one-shot loader so a second `run()` reconfigures instead of stacking hooks. */ const runLoader = new SourceModuleLoader();
5
+ async function run(entry, options = {}) {
6
+ const trimmed = entry.trim();
7
+ if (trimmed == null || trimmed === "") {
8
+ throw new Error("flux.run requires an entry file path");
9
+ }
10
+ const absoluteEntry = path.resolve(trimmed);
11
+ await runLoader.configure({
12
+ workspace: options.workspace,
13
+ buildConfig: options.configuration ?? "debug"
14
+ });
15
+ runLoader.registerHooks();
16
+ process.argv = [
17
+ process.execPath,
18
+ absoluteEntry,
19
+ ...options.args ?? []
20
+ ];
21
+ return runLoader.importEntry(absoluteEntry);
22
+ }
23
+ async function serve(options = {}) {
24
+ const server = new HotReloadServer();
25
+ await server.start({
26
+ buildConfig: options.configuration ?? "debug",
27
+ project: options.project,
28
+ projects: options.projects,
29
+ workspace: options.workspace,
30
+ rebootDebounceMs: options.rebootDebounceMs
31
+ });
32
+ return server;
33
+ }
34
+ function dispose() {
35
+ runLoader.dispose();
36
+ }
37
+ export const flux = {
38
+ run,
39
+ serve,
40
+ dispose
41
+ };