@prisma/composer-cli 0.6.0-dev.21

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/LICENSE +201 -0
  2. package/dist/bin.mjs +987 -0
  3. package/dist/bin.mjs.map +1 -0
  4. package/dist/container-transport-DKmKg5JQ-CoY4XPma.mjs +30 -0
  5. package/dist/container-transport-DKmKg5JQ-CoY4XPma.mjs.map +1 -0
  6. package/dist/execute-deploy-destroy-DfVJUICu-D-kARRtf.mjs +317 -0
  7. package/dist/execute-deploy-destroy-DfVJUICu-D-kARRtf.mjs.map +1 -0
  8. package/dist/execute-deploy-destroy-DfVJUICu-quUQ08T8.mjs +316 -0
  9. package/dist/execute-deploy-destroy-DfVJUICu-quUQ08T8.mjs.map +1 -0
  10. package/dist/execute-dev-BMTFWfFc-B1whS-Rr.mjs +2011 -0
  11. package/dist/execute-dev-BMTFWfFc-B1whS-Rr.mjs.map +1 -0
  12. package/dist/execute-dev-BMTFWfFc-D0niyhe3.mjs +2012 -0
  13. package/dist/execute-dev-BMTFWfFc-D0niyhe3.mjs.map +1 -0
  14. package/dist/execute-log-Cay9hlKW-DJMh35AZ.mjs +158 -0
  15. package/dist/execute-log-Cay9hlKW-DJMh35AZ.mjs.map +1 -0
  16. package/dist/execute-log-Cay9hlKW-DrMeVOXq.mjs +157 -0
  17. package/dist/execute-log-Cay9hlKW-DrMeVOXq.mjs.map +1 -0
  18. package/dist/family-DkH0si4D-CN5QubKS.d.mts +1294 -0
  19. package/dist/family-DkH0si4D-CN5QubKS.d.mts.map +1 -0
  20. package/dist/family.d.mts +52 -0
  21. package/dist/family.d.mts.map +1 -0
  22. package/dist/family.mjs +923 -0
  23. package/dist/family.mjs.map +1 -0
  24. package/dist/local-target-CBZyaBy0.mjs +68 -0
  25. package/dist/local-target-CBZyaBy0.mjs.map +1 -0
  26. package/dist/local-target-H0IWu_FM.mjs +68 -0
  27. package/dist/local-target-H0IWu_FM.mjs.map +1 -0
  28. package/dist/pipeline-AoW8zq4I-C6Qe0VaZ.mjs +976 -0
  29. package/dist/pipeline-AoW8zq4I-C6Qe0VaZ.mjs.map +1 -0
  30. package/dist/pipeline-AoW8zq4I-DYNbf-ad.mjs +977 -0
  31. package/dist/pipeline-AoW8zq4I-DYNbf-ad.mjs.map +1 -0
  32. package/dist/result-B4XjxVK6.mjs +384 -0
  33. package/dist/result-B4XjxVK6.mjs.map +1 -0
  34. package/dist/result-D4d-xy4I.mjs +230 -0
  35. package/dist/result-D4d-xy4I.mjs.map +1 -0
  36. package/dist/run-alchemy-D44OZlyB-DA7s331N.mjs +93 -0
  37. package/dist/run-alchemy-D44OZlyB-DA7s331N.mjs.map +1 -0
  38. package/dist/run-alchemy-D44OZlyB-wmf8mHRE.mjs +93 -0
  39. package/dist/run-alchemy-D44OZlyB-wmf8mHRE.mjs.map +1 -0
  40. package/dist/shared-BTnATsqm-CDCqKwCF.mjs +158 -0
  41. package/dist/shared-BTnATsqm-CDCqKwCF.mjs.map +1 -0
  42. package/dist/testing.d.mts +53 -0
  43. package/dist/testing.d.mts.map +1 -0
  44. package/dist/testing.mjs +151 -0
  45. package/dist/testing.mjs.map +1 -0
  46. package/package.json +53 -0
  47. package/src/exports/family.ts +14 -0
  48. package/src/exports/testing.ts +6 -0
@@ -0,0 +1,2011 @@
1
+ import { c as CliStructuredError, n as ok, s as toStructured, t as notOk } from "./result-B4XjxVK6.mjs";
2
+ import { n as alchemyInvocation, r as spawnAlchemy } from "./run-alchemy-D44OZlyB-DA7s331N.mjs";
3
+ import { n as runPipeline } from "./pipeline-AoW8zq4I-C6Qe0VaZ.mjs";
4
+ import { t as containerEnv } from "./container-transport-DKmKg5JQ-CoY4XPma.mjs";
5
+ import { n as withEmulatorRetry, r as DEV_DIR, t as resolveLocalTargets } from "./local-target-H0IWu_FM.mjs";
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { join, relative, resolve, sep } from "node:path";
9
+ import { stat, unwatchFile, watch, watchFile } from "fs";
10
+ import { lstat, open, readdir, realpath, stat as stat$1 } from "fs/promises";
11
+ import { EventEmitter } from "events";
12
+ import * as sysPath from "path";
13
+ import { lstat as lstat$1, readdir as readdir$1, realpath as realpath$1, stat as stat$2 } from "node:fs/promises";
14
+ import { Readable } from "node:stream";
15
+ import { type } from "os";
16
+ //#region ../../0-framework/3-tooling/cli/node_modules/readdirp/esm/index.js
17
+ const EntryTypes = {
18
+ FILE_TYPE: "files",
19
+ DIR_TYPE: "directories",
20
+ FILE_DIR_TYPE: "files_directories",
21
+ EVERYTHING_TYPE: "all"
22
+ };
23
+ const defaultOptions = {
24
+ root: ".",
25
+ fileFilter: (_entryInfo) => true,
26
+ directoryFilter: (_entryInfo) => true,
27
+ type: EntryTypes.FILE_TYPE,
28
+ lstat: false,
29
+ depth: 2147483648,
30
+ alwaysStat: false,
31
+ highWaterMark: 4096
32
+ };
33
+ Object.freeze(defaultOptions);
34
+ const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
35
+ const NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set([
36
+ "ENOENT",
37
+ "EPERM",
38
+ "EACCES",
39
+ "ELOOP",
40
+ RECURSIVE_ERROR_CODE
41
+ ]);
42
+ const ALL_TYPES = [
43
+ EntryTypes.DIR_TYPE,
44
+ EntryTypes.EVERYTHING_TYPE,
45
+ EntryTypes.FILE_DIR_TYPE,
46
+ EntryTypes.FILE_TYPE
47
+ ];
48
+ const DIR_TYPES = /* @__PURE__ */ new Set([
49
+ EntryTypes.DIR_TYPE,
50
+ EntryTypes.EVERYTHING_TYPE,
51
+ EntryTypes.FILE_DIR_TYPE
52
+ ]);
53
+ const FILE_TYPES = /* @__PURE__ */ new Set([
54
+ EntryTypes.EVERYTHING_TYPE,
55
+ EntryTypes.FILE_DIR_TYPE,
56
+ EntryTypes.FILE_TYPE
57
+ ]);
58
+ const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
59
+ const wantBigintFsStats = process.platform === "win32";
60
+ const emptyFn = (_entryInfo) => true;
61
+ const normalizeFilter = (filter) => {
62
+ if (filter === void 0) return emptyFn;
63
+ if (typeof filter === "function") return filter;
64
+ if (typeof filter === "string") {
65
+ const fl = filter.trim();
66
+ return (entry) => entry.basename === fl;
67
+ }
68
+ if (Array.isArray(filter)) {
69
+ const trItems = filter.map((item) => item.trim());
70
+ return (entry) => trItems.some((f) => entry.basename === f);
71
+ }
72
+ return emptyFn;
73
+ };
74
+ /** Readable readdir stream, emitting new files as they're being listed. */
75
+ var ReaddirpStream = class extends Readable {
76
+ constructor(options = {}) {
77
+ super({
78
+ objectMode: true,
79
+ autoDestroy: true,
80
+ highWaterMark: options.highWaterMark
81
+ });
82
+ const opts = {
83
+ ...defaultOptions,
84
+ ...options
85
+ };
86
+ const { root, type } = opts;
87
+ this._fileFilter = normalizeFilter(opts.fileFilter);
88
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
89
+ const statMethod = opts.lstat ? lstat$1 : stat$2;
90
+ if (wantBigintFsStats) this._stat = (path) => statMethod(path, { bigint: true });
91
+ else this._stat = statMethod;
92
+ this._maxDepth = opts.depth ?? defaultOptions.depth;
93
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
94
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
95
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
96
+ this._root = resolve(root);
97
+ this._isDirent = !opts.alwaysStat;
98
+ this._statsProp = this._isDirent ? "dirent" : "stats";
99
+ this._rdOptions = {
100
+ encoding: "utf8",
101
+ withFileTypes: this._isDirent
102
+ };
103
+ this.parents = [this._exploreDir(root, 1)];
104
+ this.reading = false;
105
+ this.parent = void 0;
106
+ }
107
+ async _read(batch) {
108
+ if (this.reading) return;
109
+ this.reading = true;
110
+ try {
111
+ while (!this.destroyed && batch > 0) {
112
+ const par = this.parent;
113
+ const fil = par && par.files;
114
+ if (fil && fil.length > 0) {
115
+ const { path, depth } = par;
116
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
117
+ const awaited = await Promise.all(slice);
118
+ for (const entry of awaited) {
119
+ if (!entry) continue;
120
+ if (this.destroyed) return;
121
+ const entryType = await this._getEntryType(entry);
122
+ if (entryType === "directory" && this._directoryFilter(entry)) {
123
+ if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
124
+ if (this._wantsDir) {
125
+ this.push(entry);
126
+ batch--;
127
+ }
128
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
129
+ if (this._wantsFile) {
130
+ this.push(entry);
131
+ batch--;
132
+ }
133
+ }
134
+ }
135
+ } else {
136
+ const parent = this.parents.pop();
137
+ if (!parent) {
138
+ this.push(null);
139
+ break;
140
+ }
141
+ this.parent = await parent;
142
+ if (this.destroyed) return;
143
+ }
144
+ }
145
+ } catch (error) {
146
+ this.destroy(error);
147
+ } finally {
148
+ this.reading = false;
149
+ }
150
+ }
151
+ async _exploreDir(path, depth) {
152
+ let files;
153
+ try {
154
+ files = await readdir$1(path, this._rdOptions);
155
+ } catch (error) {
156
+ this._onError(error);
157
+ }
158
+ return {
159
+ files,
160
+ depth,
161
+ path
162
+ };
163
+ }
164
+ async _formatEntry(dirent, path) {
165
+ let entry;
166
+ const basename = this._isDirent ? dirent.name : dirent;
167
+ try {
168
+ const fullPath = resolve(join(path, basename));
169
+ entry = {
170
+ path: relative(this._root, fullPath),
171
+ fullPath,
172
+ basename
173
+ };
174
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
175
+ } catch (err) {
176
+ this._onError(err);
177
+ return;
178
+ }
179
+ return entry;
180
+ }
181
+ _onError(err) {
182
+ if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
183
+ else this.destroy(err);
184
+ }
185
+ async _getEntryType(entry) {
186
+ if (!entry && this._statsProp in entry) return "";
187
+ const stats = entry[this._statsProp];
188
+ if (stats.isFile()) return "file";
189
+ if (stats.isDirectory()) return "directory";
190
+ if (stats && stats.isSymbolicLink()) {
191
+ const full = entry.fullPath;
192
+ try {
193
+ const entryRealPath = await realpath$1(full);
194
+ const entryRealPathStats = await lstat$1(entryRealPath);
195
+ if (entryRealPathStats.isFile()) return "file";
196
+ if (entryRealPathStats.isDirectory()) {
197
+ const len = entryRealPath.length;
198
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) {
199
+ const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
200
+ recursiveError.code = RECURSIVE_ERROR_CODE;
201
+ return this._onError(recursiveError);
202
+ }
203
+ return "directory";
204
+ }
205
+ } catch (error) {
206
+ this._onError(error);
207
+ return "";
208
+ }
209
+ }
210
+ }
211
+ _includeAsFile(entry) {
212
+ const stats = entry && entry[this._statsProp];
213
+ return stats && this._wantsEverything && !stats.isDirectory();
214
+ }
215
+ };
216
+ /**
217
+ * Streaming version: Reads all files and directories in given root recursively.
218
+ * Consumes ~constant small amount of RAM.
219
+ * @param root Root directory
220
+ * @param options Options to specify root (start directory), filters and recursion depth
221
+ */
222
+ function readdirp(root, options = {}) {
223
+ let type = options.entryType || options.type;
224
+ if (type === "both") type = EntryTypes.FILE_DIR_TYPE;
225
+ if (type) options.type = type;
226
+ if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
227
+ else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
228
+ else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
229
+ options.root = root;
230
+ return new ReaddirpStream(options);
231
+ }
232
+ //#endregion
233
+ //#region ../../0-framework/3-tooling/cli/node_modules/chokidar/esm/handler.js
234
+ const STR_DATA = "data";
235
+ const STR_CLOSE = "close";
236
+ const EMPTY_FN = () => {};
237
+ const pl = process.platform;
238
+ const isWindows = pl === "win32";
239
+ const isMacos = pl === "darwin";
240
+ const isLinux = pl === "linux";
241
+ const isFreeBSD = pl === "freebsd";
242
+ const isIBMi = type() === "OS400";
243
+ const EVENTS = {
244
+ ALL: "all",
245
+ READY: "ready",
246
+ ADD: "add",
247
+ CHANGE: "change",
248
+ ADD_DIR: "addDir",
249
+ UNLINK: "unlink",
250
+ UNLINK_DIR: "unlinkDir",
251
+ RAW: "raw",
252
+ ERROR: "error"
253
+ };
254
+ const EV = EVENTS;
255
+ const THROTTLE_MODE_WATCH = "watch";
256
+ const statMethods = {
257
+ lstat,
258
+ stat: stat$1
259
+ };
260
+ const KEY_LISTENERS = "listeners";
261
+ const KEY_ERR = "errHandlers";
262
+ const KEY_RAW = "rawEmitters";
263
+ const HANDLER_KEYS = [
264
+ KEY_LISTENERS,
265
+ KEY_ERR,
266
+ KEY_RAW
267
+ ];
268
+ const binaryExtensions = /* @__PURE__ */ new Set([
269
+ "3dm",
270
+ "3ds",
271
+ "3g2",
272
+ "3gp",
273
+ "7z",
274
+ "a",
275
+ "aac",
276
+ "adp",
277
+ "afdesign",
278
+ "afphoto",
279
+ "afpub",
280
+ "ai",
281
+ "aif",
282
+ "aiff",
283
+ "alz",
284
+ "ape",
285
+ "apk",
286
+ "appimage",
287
+ "ar",
288
+ "arj",
289
+ "asf",
290
+ "au",
291
+ "avi",
292
+ "bak",
293
+ "baml",
294
+ "bh",
295
+ "bin",
296
+ "bk",
297
+ "bmp",
298
+ "btif",
299
+ "bz2",
300
+ "bzip2",
301
+ "cab",
302
+ "caf",
303
+ "cgm",
304
+ "class",
305
+ "cmx",
306
+ "cpio",
307
+ "cr2",
308
+ "cur",
309
+ "dat",
310
+ "dcm",
311
+ "deb",
312
+ "dex",
313
+ "djvu",
314
+ "dll",
315
+ "dmg",
316
+ "dng",
317
+ "doc",
318
+ "docm",
319
+ "docx",
320
+ "dot",
321
+ "dotm",
322
+ "dra",
323
+ "DS_Store",
324
+ "dsk",
325
+ "dts",
326
+ "dtshd",
327
+ "dvb",
328
+ "dwg",
329
+ "dxf",
330
+ "ecelp4800",
331
+ "ecelp7470",
332
+ "ecelp9600",
333
+ "egg",
334
+ "eol",
335
+ "eot",
336
+ "epub",
337
+ "exe",
338
+ "f4v",
339
+ "fbs",
340
+ "fh",
341
+ "fla",
342
+ "flac",
343
+ "flatpak",
344
+ "fli",
345
+ "flv",
346
+ "fpx",
347
+ "fst",
348
+ "fvt",
349
+ "g3",
350
+ "gh",
351
+ "gif",
352
+ "graffle",
353
+ "gz",
354
+ "gzip",
355
+ "h261",
356
+ "h263",
357
+ "h264",
358
+ "icns",
359
+ "ico",
360
+ "ief",
361
+ "img",
362
+ "ipa",
363
+ "iso",
364
+ "jar",
365
+ "jpeg",
366
+ "jpg",
367
+ "jpgv",
368
+ "jpm",
369
+ "jxr",
370
+ "key",
371
+ "ktx",
372
+ "lha",
373
+ "lib",
374
+ "lvp",
375
+ "lz",
376
+ "lzh",
377
+ "lzma",
378
+ "lzo",
379
+ "m3u",
380
+ "m4a",
381
+ "m4v",
382
+ "mar",
383
+ "mdi",
384
+ "mht",
385
+ "mid",
386
+ "midi",
387
+ "mj2",
388
+ "mka",
389
+ "mkv",
390
+ "mmr",
391
+ "mng",
392
+ "mobi",
393
+ "mov",
394
+ "movie",
395
+ "mp3",
396
+ "mp4",
397
+ "mp4a",
398
+ "mpeg",
399
+ "mpg",
400
+ "mpga",
401
+ "mxu",
402
+ "nef",
403
+ "npx",
404
+ "numbers",
405
+ "nupkg",
406
+ "o",
407
+ "odp",
408
+ "ods",
409
+ "odt",
410
+ "oga",
411
+ "ogg",
412
+ "ogv",
413
+ "otf",
414
+ "ott",
415
+ "pages",
416
+ "pbm",
417
+ "pcx",
418
+ "pdb",
419
+ "pdf",
420
+ "pea",
421
+ "pgm",
422
+ "pic",
423
+ "png",
424
+ "pnm",
425
+ "pot",
426
+ "potm",
427
+ "potx",
428
+ "ppa",
429
+ "ppam",
430
+ "ppm",
431
+ "pps",
432
+ "ppsm",
433
+ "ppsx",
434
+ "ppt",
435
+ "pptm",
436
+ "pptx",
437
+ "psd",
438
+ "pya",
439
+ "pyc",
440
+ "pyo",
441
+ "pyv",
442
+ "qt",
443
+ "rar",
444
+ "ras",
445
+ "raw",
446
+ "resources",
447
+ "rgb",
448
+ "rip",
449
+ "rlc",
450
+ "rmf",
451
+ "rmvb",
452
+ "rpm",
453
+ "rtf",
454
+ "rz",
455
+ "s3m",
456
+ "s7z",
457
+ "scpt",
458
+ "sgi",
459
+ "shar",
460
+ "snap",
461
+ "sil",
462
+ "sketch",
463
+ "slk",
464
+ "smv",
465
+ "snk",
466
+ "so",
467
+ "stl",
468
+ "suo",
469
+ "sub",
470
+ "swf",
471
+ "tar",
472
+ "tbz",
473
+ "tbz2",
474
+ "tga",
475
+ "tgz",
476
+ "thmx",
477
+ "tif",
478
+ "tiff",
479
+ "tlz",
480
+ "ttc",
481
+ "ttf",
482
+ "txz",
483
+ "udf",
484
+ "uvh",
485
+ "uvi",
486
+ "uvm",
487
+ "uvp",
488
+ "uvs",
489
+ "uvu",
490
+ "viv",
491
+ "vob",
492
+ "war",
493
+ "wav",
494
+ "wax",
495
+ "wbmp",
496
+ "wdp",
497
+ "weba",
498
+ "webm",
499
+ "webp",
500
+ "whl",
501
+ "wim",
502
+ "wm",
503
+ "wma",
504
+ "wmv",
505
+ "wmx",
506
+ "woff",
507
+ "woff2",
508
+ "wrm",
509
+ "wvx",
510
+ "xbm",
511
+ "xif",
512
+ "xla",
513
+ "xlam",
514
+ "xls",
515
+ "xlsb",
516
+ "xlsm",
517
+ "xlsx",
518
+ "xlt",
519
+ "xltm",
520
+ "xltx",
521
+ "xm",
522
+ "xmind",
523
+ "xpi",
524
+ "xpm",
525
+ "xwd",
526
+ "xz",
527
+ "z",
528
+ "zip",
529
+ "zipx"
530
+ ]);
531
+ const isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
532
+ const foreach = (val, fn) => {
533
+ if (val instanceof Set) val.forEach(fn);
534
+ else fn(val);
535
+ };
536
+ const addAndConvert = (main, prop, item) => {
537
+ let container = main[prop];
538
+ if (!(container instanceof Set)) main[prop] = container = /* @__PURE__ */ new Set([container]);
539
+ container.add(item);
540
+ };
541
+ const clearItem = (cont) => (key) => {
542
+ const set = cont[key];
543
+ if (set instanceof Set) set.clear();
544
+ else delete cont[key];
545
+ };
546
+ const delFromSet = (main, prop, item) => {
547
+ const container = main[prop];
548
+ if (container instanceof Set) container.delete(item);
549
+ else if (container === item) delete main[prop];
550
+ };
551
+ const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
552
+ const FsWatchInstances = /* @__PURE__ */ new Map();
553
+ /**
554
+ * Instantiates the fs_watch interface
555
+ * @param path to be watched
556
+ * @param options to be passed to fs_watch
557
+ * @param listener main event handler
558
+ * @param errHandler emits info about errors
559
+ * @param emitRaw emits raw event data
560
+ * @returns {NativeFsWatcher}
561
+ */
562
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
563
+ const handleEvent = (rawEvent, evPath) => {
564
+ listener(path);
565
+ emitRaw(rawEvent, evPath, { watchedPath: path });
566
+ if (evPath && path !== evPath) fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
567
+ };
568
+ try {
569
+ return watch(path, { persistent: options.persistent }, handleEvent);
570
+ } catch (error) {
571
+ errHandler(error);
572
+ return;
573
+ }
574
+ }
575
+ /**
576
+ * Helper for passing fs_watch event data to a collection of listeners
577
+ * @param fullPath absolute path bound to fs_watch instance
578
+ */
579
+ const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
580
+ const cont = FsWatchInstances.get(fullPath);
581
+ if (!cont) return;
582
+ foreach(cont[listenerType], (listener) => {
583
+ listener(val1, val2, val3);
584
+ });
585
+ };
586
+ /**
587
+ * Instantiates the fs_watch interface or binds listeners
588
+ * to an existing one covering the same file system entry
589
+ * @param path
590
+ * @param fullPath absolute path
591
+ * @param options to be passed to fs_watch
592
+ * @param handlers container for event listener functions
593
+ */
594
+ const setFsWatchListener = (path, fullPath, options, handlers) => {
595
+ const { listener, errHandler, rawEmitter } = handlers;
596
+ let cont = FsWatchInstances.get(fullPath);
597
+ let watcher;
598
+ if (!options.persistent) {
599
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
600
+ if (!watcher) return;
601
+ return watcher.close.bind(watcher);
602
+ }
603
+ if (cont) {
604
+ addAndConvert(cont, KEY_LISTENERS, listener);
605
+ addAndConvert(cont, KEY_ERR, errHandler);
606
+ addAndConvert(cont, KEY_RAW, rawEmitter);
607
+ } else {
608
+ watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
609
+ if (!watcher) return;
610
+ watcher.on(EV.ERROR, async (error) => {
611
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
612
+ if (cont) cont.watcherUnusable = true;
613
+ if (isWindows && error.code === "EPERM") try {
614
+ await (await open(path, "r")).close();
615
+ broadcastErr(error);
616
+ } catch (err) {}
617
+ else broadcastErr(error);
618
+ });
619
+ cont = {
620
+ listeners: listener,
621
+ errHandlers: errHandler,
622
+ rawEmitters: rawEmitter,
623
+ watcher
624
+ };
625
+ FsWatchInstances.set(fullPath, cont);
626
+ }
627
+ return () => {
628
+ delFromSet(cont, KEY_LISTENERS, listener);
629
+ delFromSet(cont, KEY_ERR, errHandler);
630
+ delFromSet(cont, KEY_RAW, rawEmitter);
631
+ if (isEmptySet(cont.listeners)) {
632
+ cont.watcher.close();
633
+ FsWatchInstances.delete(fullPath);
634
+ HANDLER_KEYS.forEach(clearItem(cont));
635
+ cont.watcher = void 0;
636
+ Object.freeze(cont);
637
+ }
638
+ };
639
+ };
640
+ const FsWatchFileInstances = /* @__PURE__ */ new Map();
641
+ /**
642
+ * Instantiates the fs_watchFile interface or binds listeners
643
+ * to an existing one covering the same file system entry
644
+ * @param path to be watched
645
+ * @param fullPath absolute path
646
+ * @param options options to be passed to fs_watchFile
647
+ * @param handlers container for event listener functions
648
+ * @returns closer
649
+ */
650
+ const setFsWatchFileListener = (path, fullPath, options, handlers) => {
651
+ const { listener, rawEmitter } = handlers;
652
+ let cont = FsWatchFileInstances.get(fullPath);
653
+ const copts = cont && cont.options;
654
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
655
+ unwatchFile(fullPath);
656
+ cont = void 0;
657
+ }
658
+ if (cont) {
659
+ addAndConvert(cont, KEY_LISTENERS, listener);
660
+ addAndConvert(cont, KEY_RAW, rawEmitter);
661
+ } else {
662
+ cont = {
663
+ listeners: listener,
664
+ rawEmitters: rawEmitter,
665
+ options,
666
+ watcher: watchFile(fullPath, options, (curr, prev) => {
667
+ foreach(cont.rawEmitters, (rawEmitter) => {
668
+ rawEmitter(EV.CHANGE, fullPath, {
669
+ curr,
670
+ prev
671
+ });
672
+ });
673
+ const currmtime = curr.mtimeMs;
674
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener) => listener(path, curr));
675
+ })
676
+ };
677
+ FsWatchFileInstances.set(fullPath, cont);
678
+ }
679
+ return () => {
680
+ delFromSet(cont, KEY_LISTENERS, listener);
681
+ delFromSet(cont, KEY_RAW, rawEmitter);
682
+ if (isEmptySet(cont.listeners)) {
683
+ FsWatchFileInstances.delete(fullPath);
684
+ unwatchFile(fullPath);
685
+ cont.options = cont.watcher = void 0;
686
+ Object.freeze(cont);
687
+ }
688
+ };
689
+ };
690
+ /**
691
+ * @mixin
692
+ */
693
+ var NodeFsHandler = class {
694
+ constructor(fsW) {
695
+ this.fsw = fsW;
696
+ this._boundHandleError = (error) => fsW._handleError(error);
697
+ }
698
+ /**
699
+ * Watch file for changes with fs_watchFile or fs_watch.
700
+ * @param path to file or dir
701
+ * @param listener on fs change
702
+ * @returns closer for the watcher instance
703
+ */
704
+ _watchWithNodeFs(path, listener) {
705
+ const opts = this.fsw.options;
706
+ const directory = sysPath.dirname(path);
707
+ const basename = sysPath.basename(path);
708
+ this.fsw._getWatchedDir(directory).add(basename);
709
+ const absolutePath = sysPath.resolve(path);
710
+ const options = { persistent: opts.persistent };
711
+ if (!listener) listener = EMPTY_FN;
712
+ let closer;
713
+ if (opts.usePolling) {
714
+ options.interval = opts.interval !== opts.binaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
715
+ closer = setFsWatchFileListener(path, absolutePath, options, {
716
+ listener,
717
+ rawEmitter: this.fsw._emitRaw
718
+ });
719
+ } else closer = setFsWatchListener(path, absolutePath, options, {
720
+ listener,
721
+ errHandler: this._boundHandleError,
722
+ rawEmitter: this.fsw._emitRaw
723
+ });
724
+ return closer;
725
+ }
726
+ /**
727
+ * Watch a file and emit add event if warranted.
728
+ * @returns closer for the watcher instance
729
+ */
730
+ _handleFile(file, stats, initialAdd) {
731
+ if (this.fsw.closed) return;
732
+ const dirname = sysPath.dirname(file);
733
+ const basename = sysPath.basename(file);
734
+ const parent = this.fsw._getWatchedDir(dirname);
735
+ let prevStats = stats;
736
+ if (parent.has(basename)) return;
737
+ const listener = async (path, newStats) => {
738
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
739
+ if (!newStats || newStats.mtimeMs === 0) try {
740
+ const newStats = await stat$1(file);
741
+ if (this.fsw.closed) return;
742
+ const at = newStats.atimeMs;
743
+ const mt = newStats.mtimeMs;
744
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
745
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
746
+ this.fsw._closeFile(path);
747
+ prevStats = newStats;
748
+ const closer = this._watchWithNodeFs(file, listener);
749
+ if (closer) this.fsw._addPathCloser(path, closer);
750
+ } else prevStats = newStats;
751
+ } catch (error) {
752
+ this.fsw._remove(dirname, basename);
753
+ }
754
+ else if (parent.has(basename)) {
755
+ const at = newStats.atimeMs;
756
+ const mt = newStats.mtimeMs;
757
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
758
+ prevStats = newStats;
759
+ }
760
+ };
761
+ const closer = this._watchWithNodeFs(file, listener);
762
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
763
+ if (!this.fsw._throttle(EV.ADD, file, 0)) return;
764
+ this.fsw._emit(EV.ADD, file, stats);
765
+ }
766
+ return closer;
767
+ }
768
+ /**
769
+ * Handle symlinks encountered while reading a dir.
770
+ * @param entry returned by readdirp
771
+ * @param directory path of dir being read
772
+ * @param path of this item
773
+ * @param item basename of this item
774
+ * @returns true if no more processing is needed for this entry.
775
+ */
776
+ async _handleSymlink(entry, directory, path, item) {
777
+ if (this.fsw.closed) return;
778
+ const full = entry.fullPath;
779
+ const dir = this.fsw._getWatchedDir(directory);
780
+ if (!this.fsw.options.followSymlinks) {
781
+ this.fsw._incrReadyCount();
782
+ let linkPath;
783
+ try {
784
+ linkPath = await realpath(path);
785
+ } catch (e) {
786
+ this.fsw._emitReady();
787
+ return true;
788
+ }
789
+ if (this.fsw.closed) return;
790
+ if (dir.has(item)) {
791
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
792
+ this.fsw._symlinkPaths.set(full, linkPath);
793
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
794
+ }
795
+ } else {
796
+ dir.add(item);
797
+ this.fsw._symlinkPaths.set(full, linkPath);
798
+ this.fsw._emit(EV.ADD, path, entry.stats);
799
+ }
800
+ this.fsw._emitReady();
801
+ return true;
802
+ }
803
+ if (this.fsw._symlinkPaths.has(full)) return true;
804
+ this.fsw._symlinkPaths.set(full, true);
805
+ }
806
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
807
+ directory = sysPath.join(directory, "");
808
+ throttler = this.fsw._throttle("readdir", directory, 1e3);
809
+ if (!throttler) return;
810
+ const previous = this.fsw._getWatchedDir(wh.path);
811
+ const current = /* @__PURE__ */ new Set();
812
+ let stream = this.fsw._readdirp(directory, {
813
+ fileFilter: (entry) => wh.filterPath(entry),
814
+ directoryFilter: (entry) => wh.filterDir(entry)
815
+ });
816
+ if (!stream) return;
817
+ stream.on(STR_DATA, async (entry) => {
818
+ if (this.fsw.closed) {
819
+ stream = void 0;
820
+ return;
821
+ }
822
+ const item = entry.path;
823
+ let path = sysPath.join(directory, item);
824
+ current.add(item);
825
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) return;
826
+ if (this.fsw.closed) {
827
+ stream = void 0;
828
+ return;
829
+ }
830
+ if (item === target || !target && !previous.has(item)) {
831
+ this.fsw._incrReadyCount();
832
+ path = sysPath.join(dir, sysPath.relative(dir, path));
833
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
834
+ }
835
+ }).on(EV.ERROR, this._boundHandleError);
836
+ return new Promise((resolve, reject) => {
837
+ if (!stream) return reject();
838
+ stream.once("end", () => {
839
+ if (this.fsw.closed) {
840
+ stream = void 0;
841
+ return;
842
+ }
843
+ const wasThrottled = throttler ? throttler.clear() : false;
844
+ resolve(void 0);
845
+ previous.getChildren().filter((item) => {
846
+ return item !== directory && !current.has(item);
847
+ }).forEach((item) => {
848
+ this.fsw._remove(directory, item);
849
+ });
850
+ stream = void 0;
851
+ if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
852
+ });
853
+ });
854
+ }
855
+ /**
856
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
857
+ * @param dir fs path
858
+ * @param stats
859
+ * @param initialAdd
860
+ * @param depth relative to user-supplied path
861
+ * @param target child path targeted for watch
862
+ * @param wh Common watch helpers for this path
863
+ * @param realpath
864
+ * @returns closer for the watcher instance.
865
+ */
866
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
867
+ const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
868
+ const tracked = parentDir.has(sysPath.basename(dir));
869
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats);
870
+ parentDir.add(sysPath.basename(dir));
871
+ this.fsw._getWatchedDir(dir);
872
+ let throttler;
873
+ let closer;
874
+ const oDepth = this.fsw.options.depth;
875
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
876
+ if (!target) {
877
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
878
+ if (this.fsw.closed) return;
879
+ }
880
+ closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
881
+ if (stats && stats.mtimeMs === 0) return;
882
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
883
+ });
884
+ }
885
+ return closer;
886
+ }
887
+ /**
888
+ * Handle added file, directory, or glob pattern.
889
+ * Delegates call to _handleFile / _handleDir after checks.
890
+ * @param path to file or ir
891
+ * @param initialAdd was the file added at watch instantiation?
892
+ * @param priorWh depth relative to user-supplied path
893
+ * @param depth Child path actually targeted for watch
894
+ * @param target Child path actually targeted for watch
895
+ */
896
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
897
+ const ready = this.fsw._emitReady;
898
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
899
+ ready();
900
+ return false;
901
+ }
902
+ const wh = this.fsw._getWatchHelpers(path);
903
+ if (priorWh) {
904
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
905
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
906
+ }
907
+ try {
908
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
909
+ if (this.fsw.closed) return;
910
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
911
+ ready();
912
+ return false;
913
+ }
914
+ const follow = this.fsw.options.followSymlinks;
915
+ let closer;
916
+ if (stats.isDirectory()) {
917
+ const absPath = sysPath.resolve(path);
918
+ const targetPath = follow ? await realpath(path) : path;
919
+ if (this.fsw.closed) return;
920
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
921
+ if (this.fsw.closed) return;
922
+ if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
923
+ } else if (stats.isSymbolicLink()) {
924
+ const targetPath = follow ? await realpath(path) : path;
925
+ if (this.fsw.closed) return;
926
+ const parent = sysPath.dirname(wh.watchPath);
927
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
928
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
929
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
930
+ if (this.fsw.closed) return;
931
+ if (targetPath !== void 0) this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
932
+ } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
933
+ ready();
934
+ if (closer) this.fsw._addPathCloser(path, closer);
935
+ return false;
936
+ } catch (error) {
937
+ if (this.fsw._handleError(error)) {
938
+ ready();
939
+ return path;
940
+ }
941
+ }
942
+ }
943
+ };
944
+ //#endregion
945
+ //#region ../../0-framework/3-tooling/cli/node_modules/chokidar/esm/index.js
946
+ /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
947
+ const SLASH = "/";
948
+ const SLASH_SLASH = "//";
949
+ const ONE_DOT = ".";
950
+ const TWO_DOTS = "..";
951
+ const STRING_TYPE = "string";
952
+ const BACK_SLASH_RE = /\\/g;
953
+ const DOUBLE_SLASH_RE = /\/\//;
954
+ const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
955
+ const REPLACER_RE = /^\.[/\\]/;
956
+ function arrify(item) {
957
+ return Array.isArray(item) ? item : [item];
958
+ }
959
+ const isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
960
+ function createPattern(matcher) {
961
+ if (typeof matcher === "function") return matcher;
962
+ if (typeof matcher === "string") return (string) => matcher === string;
963
+ if (matcher instanceof RegExp) return (string) => matcher.test(string);
964
+ if (typeof matcher === "object" && matcher !== null) return (string) => {
965
+ if (matcher.path === string) return true;
966
+ if (matcher.recursive) {
967
+ const relative = sysPath.relative(matcher.path, string);
968
+ if (!relative) return false;
969
+ return !relative.startsWith("..") && !sysPath.isAbsolute(relative);
970
+ }
971
+ return false;
972
+ };
973
+ return () => false;
974
+ }
975
+ function normalizePath(path) {
976
+ if (typeof path !== "string") throw new Error("string expected");
977
+ path = sysPath.normalize(path);
978
+ path = path.replace(/\\/g, "/");
979
+ let prepend = false;
980
+ if (path.startsWith("//")) prepend = true;
981
+ const DOUBLE_SLASH_RE = /\/\//;
982
+ while (path.match(DOUBLE_SLASH_RE)) path = path.replace(DOUBLE_SLASH_RE, "/");
983
+ if (prepend) path = "/" + path;
984
+ return path;
985
+ }
986
+ function matchPatterns(patterns, testString, stats) {
987
+ const path = normalizePath(testString);
988
+ for (let index = 0; index < patterns.length; index++) {
989
+ const pattern = patterns[index];
990
+ if (pattern(path, stats)) return true;
991
+ }
992
+ return false;
993
+ }
994
+ function anymatch(matchers, testString) {
995
+ if (matchers == null) throw new TypeError("anymatch: specify first argument");
996
+ const patterns = arrify(matchers).map((matcher) => createPattern(matcher));
997
+ if (testString == null) return (testString, stats) => {
998
+ return matchPatterns(patterns, testString, stats);
999
+ };
1000
+ return matchPatterns(patterns, testString);
1001
+ }
1002
+ const unifyPaths = (paths_) => {
1003
+ const paths = arrify(paths_).flat();
1004
+ if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
1005
+ return paths.map(normalizePathToUnix);
1006
+ };
1007
+ const toUnix = (string) => {
1008
+ let str = string.replace(BACK_SLASH_RE, SLASH);
1009
+ let prepend = false;
1010
+ if (str.startsWith(SLASH_SLASH)) prepend = true;
1011
+ while (str.match(DOUBLE_SLASH_RE)) str = str.replace(DOUBLE_SLASH_RE, SLASH);
1012
+ if (prepend) str = SLASH + str;
1013
+ return str;
1014
+ };
1015
+ const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
1016
+ const normalizeIgnored = (cwd = "") => (path) => {
1017
+ if (typeof path === "string") return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
1018
+ else return path;
1019
+ };
1020
+ const getAbsolutePath = (path, cwd) => {
1021
+ if (sysPath.isAbsolute(path)) return path;
1022
+ return sysPath.join(cwd, path);
1023
+ };
1024
+ const EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
1025
+ /**
1026
+ * Directory entry.
1027
+ */
1028
+ var DirEntry = class {
1029
+ constructor(dir, removeWatcher) {
1030
+ this.path = dir;
1031
+ this._removeWatcher = removeWatcher;
1032
+ this.items = /* @__PURE__ */ new Set();
1033
+ }
1034
+ add(item) {
1035
+ const { items } = this;
1036
+ if (!items) return;
1037
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
1038
+ }
1039
+ async remove(item) {
1040
+ const { items } = this;
1041
+ if (!items) return;
1042
+ items.delete(item);
1043
+ if (items.size > 0) return;
1044
+ const dir = this.path;
1045
+ try {
1046
+ await readdir(dir);
1047
+ } catch (err) {
1048
+ if (this._removeWatcher) this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
1049
+ }
1050
+ }
1051
+ has(item) {
1052
+ const { items } = this;
1053
+ if (!items) return;
1054
+ return items.has(item);
1055
+ }
1056
+ getChildren() {
1057
+ const { items } = this;
1058
+ if (!items) return [];
1059
+ return [...items.values()];
1060
+ }
1061
+ dispose() {
1062
+ this.items.clear();
1063
+ this.path = "";
1064
+ this._removeWatcher = EMPTY_FN;
1065
+ this.items = EMPTY_SET;
1066
+ Object.freeze(this);
1067
+ }
1068
+ };
1069
+ const STAT_METHOD_F = "stat";
1070
+ const STAT_METHOD_L = "lstat";
1071
+ var WatchHelper = class {
1072
+ constructor(path, follow, fsw) {
1073
+ this.fsw = fsw;
1074
+ const watchPath = path;
1075
+ this.path = path = path.replace(REPLACER_RE, "");
1076
+ this.watchPath = watchPath;
1077
+ this.fullWatchPath = sysPath.resolve(watchPath);
1078
+ this.dirParts = [];
1079
+ this.dirParts.forEach((parts) => {
1080
+ if (parts.length > 1) parts.pop();
1081
+ });
1082
+ this.followSymlinks = follow;
1083
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1084
+ }
1085
+ entryPath(entry) {
1086
+ return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath));
1087
+ }
1088
+ filterPath(entry) {
1089
+ const { stats } = entry;
1090
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
1091
+ const resolvedPath = this.entryPath(entry);
1092
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1093
+ }
1094
+ filterDir(entry) {
1095
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1096
+ }
1097
+ };
1098
+ /**
1099
+ * Watches files & directories for changes. Emitted events:
1100
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
1101
+ *
1102
+ * new FSWatcher()
1103
+ * .add(directories)
1104
+ * .on('add', path => log('File', path, 'was added'))
1105
+ */
1106
+ var FSWatcher = class extends EventEmitter {
1107
+ constructor(_opts = {}) {
1108
+ super();
1109
+ this.closed = false;
1110
+ this._closers = /* @__PURE__ */ new Map();
1111
+ this._ignoredPaths = /* @__PURE__ */ new Set();
1112
+ this._throttled = /* @__PURE__ */ new Map();
1113
+ this._streams = /* @__PURE__ */ new Set();
1114
+ this._symlinkPaths = /* @__PURE__ */ new Map();
1115
+ this._watched = /* @__PURE__ */ new Map();
1116
+ this._pendingWrites = /* @__PURE__ */ new Map();
1117
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
1118
+ this._readyCount = 0;
1119
+ this._readyEmitted = false;
1120
+ const awf = _opts.awaitWriteFinish;
1121
+ const DEF_AWF = {
1122
+ stabilityThreshold: 2e3,
1123
+ pollInterval: 100
1124
+ };
1125
+ const opts = {
1126
+ persistent: true,
1127
+ ignoreInitial: false,
1128
+ ignorePermissionErrors: false,
1129
+ interval: 100,
1130
+ binaryInterval: 300,
1131
+ followSymlinks: true,
1132
+ usePolling: false,
1133
+ atomic: true,
1134
+ ..._opts,
1135
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1136
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? {
1137
+ ...DEF_AWF,
1138
+ ...awf
1139
+ } : false
1140
+ };
1141
+ if (isIBMi) opts.usePolling = true;
1142
+ if (opts.atomic === void 0) opts.atomic = !opts.usePolling;
1143
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
1144
+ if (envPoll !== void 0) {
1145
+ const envLower = envPoll.toLowerCase();
1146
+ if (envLower === "false" || envLower === "0") opts.usePolling = false;
1147
+ else if (envLower === "true" || envLower === "1") opts.usePolling = true;
1148
+ else opts.usePolling = !!envLower;
1149
+ }
1150
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
1151
+ if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
1152
+ let readyCalls = 0;
1153
+ this._emitReady = () => {
1154
+ readyCalls++;
1155
+ if (readyCalls >= this._readyCount) {
1156
+ this._emitReady = EMPTY_FN;
1157
+ this._readyEmitted = true;
1158
+ process.nextTick(() => this.emit(EVENTS.READY));
1159
+ }
1160
+ };
1161
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1162
+ this._boundRemove = this._remove.bind(this);
1163
+ this.options = opts;
1164
+ this._nodeFsHandler = new NodeFsHandler(this);
1165
+ Object.freeze(opts);
1166
+ }
1167
+ _addIgnoredPath(matcher) {
1168
+ if (isMatcherObject(matcher)) {
1169
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return;
1170
+ }
1171
+ this._ignoredPaths.add(matcher);
1172
+ }
1173
+ _removeIgnoredPath(matcher) {
1174
+ this._ignoredPaths.delete(matcher);
1175
+ if (typeof matcher === "string") {
1176
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored);
1177
+ }
1178
+ }
1179
+ /**
1180
+ * Adds paths to be watched on an existing FSWatcher instance.
1181
+ * @param paths_ file or file list. Other arguments are unused
1182
+ */
1183
+ add(paths_, _origAdd, _internal) {
1184
+ const { cwd } = this.options;
1185
+ this.closed = false;
1186
+ this._closePromise = void 0;
1187
+ let paths = unifyPaths(paths_);
1188
+ if (cwd) paths = paths.map((path) => {
1189
+ return getAbsolutePath(path, cwd);
1190
+ });
1191
+ paths.forEach((path) => {
1192
+ this._removeIgnoredPath(path);
1193
+ });
1194
+ this._userIgnored = void 0;
1195
+ if (!this._readyCount) this._readyCount = 0;
1196
+ this._readyCount += paths.length;
1197
+ Promise.all(paths.map(async (path) => {
1198
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
1199
+ if (res) this._emitReady();
1200
+ return res;
1201
+ })).then((results) => {
1202
+ if (this.closed) return;
1203
+ results.forEach((item) => {
1204
+ if (item) this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
1205
+ });
1206
+ });
1207
+ return this;
1208
+ }
1209
+ /**
1210
+ * Close watchers or start ignoring events from specified paths.
1211
+ */
1212
+ unwatch(paths_) {
1213
+ if (this.closed) return this;
1214
+ const paths = unifyPaths(paths_);
1215
+ const { cwd } = this.options;
1216
+ paths.forEach((path) => {
1217
+ if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
1218
+ if (cwd) path = sysPath.join(cwd, path);
1219
+ path = sysPath.resolve(path);
1220
+ }
1221
+ this._closePath(path);
1222
+ this._addIgnoredPath(path);
1223
+ if (this._watched.has(path)) this._addIgnoredPath({
1224
+ path,
1225
+ recursive: true
1226
+ });
1227
+ this._userIgnored = void 0;
1228
+ });
1229
+ return this;
1230
+ }
1231
+ /**
1232
+ * Close watchers and remove all listeners from watched paths.
1233
+ */
1234
+ close() {
1235
+ if (this._closePromise) return this._closePromise;
1236
+ this.closed = true;
1237
+ this.removeAllListeners();
1238
+ const closers = [];
1239
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
1240
+ const promise = closer();
1241
+ if (promise instanceof Promise) closers.push(promise);
1242
+ }));
1243
+ this._streams.forEach((stream) => stream.destroy());
1244
+ this._userIgnored = void 0;
1245
+ this._readyCount = 0;
1246
+ this._readyEmitted = false;
1247
+ this._watched.forEach((dirent) => dirent.dispose());
1248
+ this._closers.clear();
1249
+ this._watched.clear();
1250
+ this._streams.clear();
1251
+ this._symlinkPaths.clear();
1252
+ this._throttled.clear();
1253
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
1254
+ return this._closePromise;
1255
+ }
1256
+ /**
1257
+ * Expose list of watched paths
1258
+ * @returns for chaining
1259
+ */
1260
+ getWatched() {
1261
+ const watchList = {};
1262
+ this._watched.forEach((entry, dir) => {
1263
+ const index = (this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir) || ONE_DOT;
1264
+ watchList[index] = entry.getChildren().sort();
1265
+ });
1266
+ return watchList;
1267
+ }
1268
+ emitWithAll(event, args) {
1269
+ this.emit(event, ...args);
1270
+ if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args);
1271
+ }
1272
+ /**
1273
+ * Normalize and emit events.
1274
+ * Calling _emit DOES NOT MEAN emit() would be called!
1275
+ * @param event Type of event
1276
+ * @param path File or directory path
1277
+ * @param stats arguments to be passed with event
1278
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1279
+ */
1280
+ async _emit(event, path, stats) {
1281
+ if (this.closed) return;
1282
+ const opts = this.options;
1283
+ if (isWindows) path = sysPath.normalize(path);
1284
+ if (opts.cwd) path = sysPath.relative(opts.cwd, path);
1285
+ const args = [path];
1286
+ if (stats != null) args.push(stats);
1287
+ const awf = opts.awaitWriteFinish;
1288
+ let pw;
1289
+ if (awf && (pw = this._pendingWrites.get(path))) {
1290
+ pw.lastChange = /* @__PURE__ */ new Date();
1291
+ return this;
1292
+ }
1293
+ if (opts.atomic) {
1294
+ if (event === EVENTS.UNLINK) {
1295
+ this._pendingUnlinks.set(path, [event, ...args]);
1296
+ setTimeout(() => {
1297
+ this._pendingUnlinks.forEach((entry, path) => {
1298
+ this.emit(...entry);
1299
+ this.emit(EVENTS.ALL, ...entry);
1300
+ this._pendingUnlinks.delete(path);
1301
+ });
1302
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
1303
+ return this;
1304
+ }
1305
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1306
+ event = EVENTS.CHANGE;
1307
+ this._pendingUnlinks.delete(path);
1308
+ }
1309
+ }
1310
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1311
+ const awfEmit = (err, stats) => {
1312
+ if (err) {
1313
+ event = EVENTS.ERROR;
1314
+ args[0] = err;
1315
+ this.emitWithAll(event, args);
1316
+ } else if (stats) {
1317
+ if (args.length > 1) args[1] = stats;
1318
+ else args.push(stats);
1319
+ this.emitWithAll(event, args);
1320
+ }
1321
+ };
1322
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1323
+ return this;
1324
+ }
1325
+ if (event === EVENTS.CHANGE) {
1326
+ if (!this._throttle(EVENTS.CHANGE, path, 50)) return this;
1327
+ }
1328
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1329
+ const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
1330
+ let stats;
1331
+ try {
1332
+ stats = await stat$1(fullPath);
1333
+ } catch (err) {}
1334
+ if (!stats || this.closed) return;
1335
+ args.push(stats);
1336
+ }
1337
+ this.emitWithAll(event, args);
1338
+ return this;
1339
+ }
1340
+ /**
1341
+ * Common handler for errors
1342
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1343
+ */
1344
+ _handleError(error) {
1345
+ const code = error && error.code;
1346
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EVENTS.ERROR, error);
1347
+ return error || this.closed;
1348
+ }
1349
+ /**
1350
+ * Helper utility for throttling
1351
+ * @param actionType type being throttled
1352
+ * @param path being acted upon
1353
+ * @param timeout duration of time to suppress duplicate actions
1354
+ * @returns tracking object or false if action should be suppressed
1355
+ */
1356
+ _throttle(actionType, path, timeout) {
1357
+ if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
1358
+ const action = this._throttled.get(actionType);
1359
+ if (!action) throw new Error("invalid throttle");
1360
+ const actionPath = action.get(path);
1361
+ if (actionPath) {
1362
+ actionPath.count++;
1363
+ return false;
1364
+ }
1365
+ let timeoutObject;
1366
+ const clear = () => {
1367
+ const item = action.get(path);
1368
+ const count = item ? item.count : 0;
1369
+ action.delete(path);
1370
+ clearTimeout(timeoutObject);
1371
+ if (item) clearTimeout(item.timeoutObject);
1372
+ return count;
1373
+ };
1374
+ timeoutObject = setTimeout(clear, timeout);
1375
+ const thr = {
1376
+ timeoutObject,
1377
+ clear,
1378
+ count: 0
1379
+ };
1380
+ action.set(path, thr);
1381
+ return thr;
1382
+ }
1383
+ _incrReadyCount() {
1384
+ return this._readyCount++;
1385
+ }
1386
+ /**
1387
+ * Awaits write operation to finish.
1388
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
1389
+ * @param path being acted upon
1390
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
1391
+ * @param event
1392
+ * @param awfEmit Callback to be called when ready for event to be emitted.
1393
+ */
1394
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
1395
+ const awf = this.options.awaitWriteFinish;
1396
+ if (typeof awf !== "object") return;
1397
+ const pollInterval = awf.pollInterval;
1398
+ let timeoutHandler;
1399
+ let fullPath = path;
1400
+ if (this.options.cwd && !sysPath.isAbsolute(path)) fullPath = sysPath.join(this.options.cwd, path);
1401
+ const now = /* @__PURE__ */ new Date();
1402
+ const writes = this._pendingWrites;
1403
+ function awaitWriteFinishFn(prevStat) {
1404
+ stat(fullPath, (err, curStat) => {
1405
+ if (err || !writes.has(path)) {
1406
+ if (err && err.code !== "ENOENT") awfEmit(err);
1407
+ return;
1408
+ }
1409
+ const now = Number(/* @__PURE__ */ new Date());
1410
+ if (prevStat && curStat.size !== prevStat.size) writes.get(path).lastChange = now;
1411
+ if (now - writes.get(path).lastChange >= threshold) {
1412
+ writes.delete(path);
1413
+ awfEmit(void 0, curStat);
1414
+ } else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1415
+ });
1416
+ }
1417
+ if (!writes.has(path)) {
1418
+ writes.set(path, {
1419
+ lastChange: now,
1420
+ cancelWait: () => {
1421
+ writes.delete(path);
1422
+ clearTimeout(timeoutHandler);
1423
+ return event;
1424
+ }
1425
+ });
1426
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1427
+ }
1428
+ }
1429
+ /**
1430
+ * Determines whether user has asked to ignore this path.
1431
+ */
1432
+ _isIgnored(path, stats) {
1433
+ if (this.options.atomic && DOT_RE.test(path)) return true;
1434
+ if (!this._userIgnored) {
1435
+ const { cwd } = this.options;
1436
+ const ignored = (this.options.ignored || []).map(normalizeIgnored(cwd));
1437
+ const list = [...[...this._ignoredPaths].map(normalizeIgnored(cwd)), ...ignored];
1438
+ this._userIgnored = anymatch(list, void 0);
1439
+ }
1440
+ return this._userIgnored(path, stats);
1441
+ }
1442
+ _isntIgnored(path, stat) {
1443
+ return !this._isIgnored(path, stat);
1444
+ }
1445
+ /**
1446
+ * Provides a set of common helpers and properties relating to symlink handling.
1447
+ * @param path file or directory pattern being watched
1448
+ */
1449
+ _getWatchHelpers(path) {
1450
+ return new WatchHelper(path, this.options.followSymlinks, this);
1451
+ }
1452
+ /**
1453
+ * Provides directory tracking objects
1454
+ * @param directory path of the directory
1455
+ */
1456
+ _getWatchedDir(directory) {
1457
+ const dir = sysPath.resolve(directory);
1458
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1459
+ return this._watched.get(dir);
1460
+ }
1461
+ /**
1462
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
1463
+ */
1464
+ _hasReadPermissions(stats) {
1465
+ if (this.options.ignorePermissionErrors) return true;
1466
+ return Boolean(Number(stats.mode) & 256);
1467
+ }
1468
+ /**
1469
+ * Handles emitting unlink events for
1470
+ * files and directories, and via recursion, for
1471
+ * files and directories within directories that are unlinked
1472
+ * @param directory within which the following item is located
1473
+ * @param item base path of item/directory
1474
+ */
1475
+ _remove(directory, item, isDirectory) {
1476
+ const path = sysPath.join(directory, item);
1477
+ const fullPath = sysPath.resolve(path);
1478
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1479
+ if (!this._throttle("remove", path, 100)) return;
1480
+ if (!isDirectory && this._watched.size === 1) this.add(directory, item, true);
1481
+ this._getWatchedDir(path).getChildren().forEach((nested) => this._remove(path, nested));
1482
+ const parent = this._getWatchedDir(directory);
1483
+ const wasTracked = parent.has(item);
1484
+ parent.remove(item);
1485
+ if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
1486
+ let relPath = path;
1487
+ if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
1488
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1489
+ if (this._pendingWrites.get(relPath).cancelWait() === EVENTS.ADD) return;
1490
+ }
1491
+ this._watched.delete(path);
1492
+ this._watched.delete(fullPath);
1493
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1494
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
1495
+ this._closePath(path);
1496
+ }
1497
+ /**
1498
+ * Closes all watchers for a path
1499
+ */
1500
+ _closePath(path) {
1501
+ this._closeFile(path);
1502
+ const dir = sysPath.dirname(path);
1503
+ this._getWatchedDir(dir).remove(sysPath.basename(path));
1504
+ }
1505
+ /**
1506
+ * Closes only file-specific watchers
1507
+ */
1508
+ _closeFile(path) {
1509
+ const closers = this._closers.get(path);
1510
+ if (!closers) return;
1511
+ closers.forEach((closer) => closer());
1512
+ this._closers.delete(path);
1513
+ }
1514
+ _addPathCloser(path, closer) {
1515
+ if (!closer) return;
1516
+ let list = this._closers.get(path);
1517
+ if (!list) {
1518
+ list = [];
1519
+ this._closers.set(path, list);
1520
+ }
1521
+ list.push(closer);
1522
+ }
1523
+ _readdirp(root, opts) {
1524
+ if (this.closed) return;
1525
+ let stream = readdirp(root, {
1526
+ type: EVENTS.ALL,
1527
+ alwaysStat: true,
1528
+ lstat: true,
1529
+ ...opts,
1530
+ depth: 0
1531
+ });
1532
+ this._streams.add(stream);
1533
+ stream.once(STR_CLOSE, () => {
1534
+ stream = void 0;
1535
+ });
1536
+ stream.once("end", () => {
1537
+ if (stream) {
1538
+ this._streams.delete(stream);
1539
+ stream = void 0;
1540
+ }
1541
+ });
1542
+ return stream;
1543
+ }
1544
+ };
1545
+ /**
1546
+ * Instantiates watcher with paths to be tracked.
1547
+ * @param paths file / directory paths
1548
+ * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
1549
+ * @returns an instance of FSWatcher for chaining.
1550
+ * @example
1551
+ * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
1552
+ * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
1553
+ */
1554
+ function watch$1(paths, options = {}) {
1555
+ const watcher = new FSWatcher(options);
1556
+ watcher.add(paths);
1557
+ return watcher;
1558
+ }
1559
+ var esm_default = {
1560
+ watch: watch$1,
1561
+ FSWatcher
1562
+ };
1563
+ //#endregion
1564
+ //#region ../../0-framework/3-tooling/cli/dist/execute-dev-BMTFWfFc.mjs
1565
+ /**
1566
+ * Local-dev spec § 6 `generate-dev-stack.ts`: like generate-stack.ts but at
1567
+ * `.prisma-composer/dev/alchemy.run.ts`, always Alchemy stage `dev`, using
1568
+ * Alchemy's own `localState()` and no `report` — dev prints its own front
1569
+ * door (run-dev.ts), so core's presentation-free lower() gets nothing to
1570
+ * call back into. The generated module IS the one orchestration point where
1571
+ * dev provenance is resolved (spec § 3 REVISED): it deserializes the
1572
+ * containers, top-level-awaits `resolveLocalTargets(config)` (the lazy
1573
+ * `localTarget` thunks, ADR-0041), and passes
1574
+ * `providers: localTargetProviders(...)` + `state: localState()` explicitly
1575
+ * — `lower()` learns nothing about dev.
1576
+ */
1577
+ const DEV_GENERATED_DIR = ".prisma-composer/dev";
1578
+ const DEV_GENERATED_FILE = "alchemy.run.ts";
1579
+ /** A relative import specifier from `.prisma-composer/dev/alchemy.run.ts` to `target` (posix separators). */
1580
+ function relativeImportSpecifier(generatedDir, target) {
1581
+ const rel = path.relative(generatedDir, target).split(path.sep).join("/");
1582
+ return rel.startsWith(".") ? rel : `./${rel}`;
1583
+ }
1584
+ function quote(value) {
1585
+ return JSON.stringify(value);
1586
+ }
1587
+ function renderBundle(bundle) {
1588
+ return `{ dir: ${quote(bundle.dir)}, entry: ${quote(bundle.entry)} }`;
1589
+ }
1590
+ function renderOptions(input) {
1591
+ const lines = [];
1592
+ lines.push(` name: ${quote(input.name)},`);
1593
+ lines.push(" bundles: {");
1594
+ for (const [id, bundle] of Object.entries(input.assembled.bundles)) lines.push(` ${quote(id)}: ${renderBundle(bundle)},`);
1595
+ lines.push(" },");
1596
+ lines.push(" providers: localTargetProviders(resolved, containers, devDir),");
1597
+ lines.push(" state: localState(),");
1598
+ return lines.join("\n");
1599
+ }
1600
+ /** Renders the dev stack module's source (tests assert on it without touching disk). */
1601
+ function renderDevStackFile(input) {
1602
+ const generatedDir = path.join(input.cwd, DEV_GENERATED_DIR);
1603
+ const appImport = relativeImportSpecifier(generatedDir, input.entryPath);
1604
+ const configImport = relativeImportSpecifier(generatedDir, input.configPath);
1605
+ return `// Generated by \`prisma-composer dev\` — overwritten on every run; do not
1606
+ // edit by hand. Independently runnable from ${quote(input.cwd)}:
1607
+ //
1608
+ // alchemy deploy ${DEV_GENERATED_DIR}/${DEV_GENERATED_FILE} --stage dev
1609
+ //
1610
+ // bisects a CLI bug from an Alchemy bug (deploy-cli.md § Implementation decisions).
1611
+ import * as path from 'node:path';
1612
+ import { deserializeContainers } from '@prisma/composer/config';
1613
+ import { lower } from '@prisma/composer/deploy';
1614
+ import { DEV_DIR, localTargetProviders, resolveLocalTargets } from '@prisma/composer/local-target';
1615
+ import { localState } from 'alchemy/State/LocalState';
1616
+ import config from ${quote(configImport)};
1617
+ import app from ${quote(appImport)};
1618
+
1619
+ const containers = deserializeContainers(config.extensions, process.env);
1620
+ const resolved = await resolveLocalTargets(config);
1621
+ const devDir = path.join(process.cwd(), DEV_DIR);
1622
+
1623
+ export default lower(app, config, {
1624
+ ${renderOptions(input)}
1625
+ });
1626
+ `;
1627
+ }
1628
+ /** Writes the dev stack file, returning its absolute path. */
1629
+ function writeDevStackFile(input) {
1630
+ const generatedDir = path.join(input.cwd, DEV_GENERATED_DIR);
1631
+ fs.mkdirSync(generatedDir, { recursive: true });
1632
+ const filePath = path.join(generatedDir, DEV_GENERATED_FILE);
1633
+ fs.writeFileSync(filePath, renderDevStackFile(input));
1634
+ return filePath;
1635
+ }
1636
+ const DEV_STACK_RELATIVE_PATH = path.join(DEV_GENERATED_DIR, DEV_GENERATED_FILE);
1637
+ /**
1638
+ * Local-dev spec § 6 `watch.ts`: watches each assembled bundle's declared
1639
+ * `watch` paths (a directory watched recursively, a file watched through
1640
+ * its parent — see `startWatch`), debounced 300 ms and coalesced across
1641
+ * every service — one edit across several files/services still fires
1642
+ * exactly one rebuild.
1643
+ *
1644
+ * The watch ENGINE is `chokidar` v4 (operator decision, design tip 74272d8:
1645
+ * don't-reinvent-the-wheel beats the no-new-deps contract here — it absorbs
1646
+ * the atomic-rename class and the cross-platform recursive-watch
1647
+ * differences; v4 is pure JS, no native code, no glob surface — irrelevant
1648
+ * here anyway, since every target is a literal file or directory path,
1649
+ * never a pattern). The parent-directory indirection for FILE targets stays
1650
+ * OURS (`startWatch` explains why), as does the debounce: chokidar's own
1651
+ * `awaitWriteFinish` is a per-file "has this file's size stopped changing"
1652
+ * poll, a different semantic from "coalesce a burst across many files into
1653
+ * one callback," which is what the dev loop actually needs.
1654
+ */
1655
+ const DEBOUNCE_MS = 300;
1656
+ /** Bundles → watch targets, plus the addresses with nothing watchable (the pinned one-line startup note). */
1657
+ function watchTargetsFrom(bundles) {
1658
+ const targets = [];
1659
+ const unwatchable = [];
1660
+ for (const [address, bundle] of Object.entries(bundles)) {
1661
+ const paths = bundle.watch;
1662
+ if (paths === void 0 || paths.length === 0) {
1663
+ unwatchable.push(address);
1664
+ continue;
1665
+ }
1666
+ targets.push({
1667
+ address,
1668
+ paths
1669
+ });
1670
+ }
1671
+ return {
1672
+ targets,
1673
+ unwatchable
1674
+ };
1675
+ }
1676
+ /**
1677
+ * Watches every target's paths via chokidar, debounced 300 ms and coalesced
1678
+ * across every service, invoking `onChange` once per burst.
1679
+ *
1680
+ * File targets are watched THROUGH their parent directory, filtered to the
1681
+ * exact path: a watch bound directly to a file dies with the file's inode
1682
+ * on Linux, so `rm -rf dist && bun build --outfile dist/x.mjs` — every
1683
+ * rebuild's shape — would go silently unobserved after the first delete
1684
+ * (chokidar absorbs atomic renames, not unlink+recreate of a directly
1685
+ * watched file; proven by the delete-recreate test failing on Linux CI
1686
+ * only). Directory targets are watched recursively as themselves; a
1687
+ * nonexistent path is treated as a file target, so it starts reporting the
1688
+ * moment something creates it.
1689
+ */
1690
+ function startWatch(targets, onChange, onError) {
1691
+ let timer;
1692
+ const trigger = () => {
1693
+ if (timer !== void 0) clearTimeout(timer);
1694
+ timer = setTimeout(() => {
1695
+ timer = void 0;
1696
+ onChange();
1697
+ }, DEBOUNCE_MS);
1698
+ };
1699
+ const fileTargets = /* @__PURE__ */ new Set();
1700
+ const directoryRoots = /* @__PURE__ */ new Set();
1701
+ const parentRoots = /* @__PURE__ */ new Set();
1702
+ for (const target of targets) for (const p of target.paths) {
1703
+ const abs = path.resolve(p);
1704
+ let isDirectory = false;
1705
+ try {
1706
+ isDirectory = fs.statSync(abs).isDirectory();
1707
+ } catch {}
1708
+ if (isDirectory) directoryRoots.add(abs);
1709
+ else {
1710
+ fileTargets.add(abs);
1711
+ parentRoots.add(path.dirname(abs));
1712
+ }
1713
+ }
1714
+ const reportError = (error) => {
1715
+ onError?.(error);
1716
+ };
1717
+ const watchers = [];
1718
+ if (directoryRoots.size > 0) {
1719
+ const directoryWatcher = esm_default.watch([...directoryRoots], { ignoreInitial: true });
1720
+ directoryWatcher.on("all", () => trigger());
1721
+ directoryWatcher.on("error", reportError);
1722
+ watchers.push(directoryWatcher);
1723
+ }
1724
+ if (parentRoots.size > 0) {
1725
+ const parentWatcher = esm_default.watch([...parentRoots], {
1726
+ ignoreInitial: true,
1727
+ depth: 0
1728
+ });
1729
+ parentWatcher.on("all", (_event, eventPath) => {
1730
+ if (fileTargets.has(path.resolve(eventPath))) trigger();
1731
+ });
1732
+ parentWatcher.on("error", reportError);
1733
+ watchers.push(parentWatcher);
1734
+ }
1735
+ let markReady = () => {};
1736
+ const allReady = Promise.all(watchers.map((watcher) => new Promise((resolve) => watcher.on("ready", () => resolve())))).then(() => {});
1737
+ return {
1738
+ ready: Promise.race([allReady, new Promise((resolve) => markReady = resolve)]),
1739
+ stop: () => {
1740
+ if (timer !== void 0) clearTimeout(timer);
1741
+ markReady();
1742
+ for (const watcher of watchers) watcher.close();
1743
+ }
1744
+ };
1745
+ }
1746
+ /**
1747
+ * The dev executor — run-dev.ts's pipeline (local-dev spec § 6) with console
1748
+ * and signal handling removed: events out through `onEvent`, lifetime owned by
1749
+ * the returned DevSession. The operation NEVER touches process signal
1750
+ * handlers — the host does (see run-dev.ts). Reached only by lazy import
1751
+ * from dev.ts — this module's static graph transitively loads alchemy's
1752
+ * provider tree, so the control entry must never import it statically.
1753
+ */
1754
+ function failureMessage(error) {
1755
+ return error instanceof Error ? error.message : String(error);
1756
+ }
1757
+ async function mergedEndpoints(attachments) {
1758
+ return (await Promise.all(attachments.map((a) => withEmulatorRetry(() => a.endpoints())))).flat();
1759
+ }
1760
+ /** Runs the full dev pipeline; resolves to a running session or a structured failure. */
1761
+ async function executeDev(input, deps, cwd) {
1762
+ if (process.platform === "win32") return notOk(new CliStructuredError("DEV.PLATFORM_UNSUPPORTED", "local dev is not supported on Windows yet."));
1763
+ const { onEvent } = input;
1764
+ const devDir = path.join(cwd, DEV_DIR);
1765
+ let pipeline;
1766
+ let resolved;
1767
+ const containers = /* @__PURE__ */ new Map();
1768
+ try {
1769
+ const pipelineDeps = {
1770
+ runAssembler: deps.runAssembler,
1771
+ config: deps.config,
1772
+ configPath: deps.configPath
1773
+ };
1774
+ pipeline = await runPipeline(input.entry, input.name, cwd, pipelineDeps);
1775
+ const { config, graph, name } = pipeline;
1776
+ resolved = await resolveLocalTargets(config);
1777
+ for (const [id, dev] of resolved) try {
1778
+ containers.set(id, await dev.container.ensure({
1779
+ appName: name,
1780
+ stage: void 0
1781
+ }));
1782
+ } catch (error) {
1783
+ throw toStructured("DEV.CONTAINER_FAILED", error);
1784
+ }
1785
+ if (input.fresh === true) for (const [id, dev] of resolved) {
1786
+ if (dev.teardown === void 0) continue;
1787
+ try {
1788
+ await dev.teardown({
1789
+ container: containers.get(id),
1790
+ stage: void 0
1791
+ });
1792
+ } catch (error) {
1793
+ throw toStructured("DEV.TEARDOWN_FAILED", error);
1794
+ }
1795
+ }
1796
+ for (const [id, dev] of resolved) {
1797
+ if (dev.preflight === void 0) continue;
1798
+ try {
1799
+ await dev.preflight({
1800
+ graph,
1801
+ container: containers.get(id),
1802
+ stage: void 0
1803
+ });
1804
+ } catch (error) {
1805
+ throw toStructured("DEV.PREFLIGHT_FAILED", error);
1806
+ }
1807
+ }
1808
+ for (const [id, dev] of resolved) {
1809
+ if (dev.emulators === void 0) continue;
1810
+ try {
1811
+ await dev.emulators({
1812
+ graph,
1813
+ container: containers.get(id),
1814
+ devDir
1815
+ });
1816
+ } catch (error) {
1817
+ throw toStructured("DEV.EMULATOR_FAILED", error);
1818
+ }
1819
+ }
1820
+ } catch (error) {
1821
+ if (CliStructuredError.is(error)) return notOk(error);
1822
+ throw error;
1823
+ }
1824
+ const reproduceCommand = `alchemy deploy ${DEV_STACK_RELATIVE_PATH} --yes --stage dev`;
1825
+ const converge = async () => {
1826
+ let stackPath;
1827
+ try {
1828
+ stackPath = writeDevStackFile({
1829
+ entryPath: pipeline.entryModule.path,
1830
+ cwd,
1831
+ configPath: pipeline.configPath,
1832
+ name: pipeline.name,
1833
+ assembled: pipeline.assembled
1834
+ });
1835
+ } catch (error) {
1836
+ throw toStructured("DEV.STACK_WRITE_FAILED", error);
1837
+ }
1838
+ let outcome;
1839
+ try {
1840
+ outcome = await (deps.alchemy ?? spawnAlchemy)(alchemyInvocation({
1841
+ command: "deploy",
1842
+ stackFileRelativePath: DEV_STACK_RELATIVE_PATH,
1843
+ cwd,
1844
+ stage: "dev",
1845
+ containerEnv: containerEnv(containers)
1846
+ }));
1847
+ } catch (error) {
1848
+ if (CliStructuredError.is(error)) throw error;
1849
+ throw new CliStructuredError("DEV.CONVERGE_FAILED", failureMessage(error), {
1850
+ cause: error,
1851
+ meta: { diagnostics: {
1852
+ exitCode: void 0,
1853
+ stackFilePath: stackPath,
1854
+ reproduceCommand,
1855
+ cwd
1856
+ } }
1857
+ });
1858
+ }
1859
+ return {
1860
+ outcome,
1861
+ stackPath
1862
+ };
1863
+ };
1864
+ let first;
1865
+ try {
1866
+ first = await converge();
1867
+ } catch (error) {
1868
+ if (CliStructuredError.is(error)) return notOk(error);
1869
+ throw error;
1870
+ }
1871
+ const firstStatus = first.outcome.signal !== null ? null : first.outcome.exitCode ?? 1;
1872
+ if (firstStatus !== 0) return notOk(new CliStructuredError("DEV.CONVERGE_FAILED", first.outcome.signal !== null ? `alchemy deploy was interrupted by ${first.outcome.signal}.` : `alchemy deploy exited with status ${String(firstStatus)}.`, { meta: {
1873
+ ...first.outcome.signal !== null ? { signal: first.outcome.signal } : { exitCode: firstStatus },
1874
+ diagnostics: {
1875
+ exitCode: firstStatus ?? void 0,
1876
+ ...first.outcome.signal !== null ? { signal: first.outcome.signal } : {},
1877
+ stackFilePath: first.stackPath,
1878
+ reproduceCommand,
1879
+ cwd
1880
+ }
1881
+ } }));
1882
+ const emit = (event) => {
1883
+ try {
1884
+ onEvent?.(event);
1885
+ } catch {}
1886
+ };
1887
+ const attachments = [];
1888
+ const started = [];
1889
+ let watch;
1890
+ try {
1891
+ for (const [id, dev] of resolved) try {
1892
+ attachments.push(await dev.attach({
1893
+ container: containers.get(id),
1894
+ devDir
1895
+ }));
1896
+ } catch (error) {
1897
+ throw toStructured("DEV.ATTACH_FAILED", error);
1898
+ }
1899
+ for (const attachment of attachments) {
1900
+ started.push(attachment);
1901
+ try {
1902
+ await withEmulatorRetry(() => attachment.startServices());
1903
+ } catch (error) {
1904
+ throw toStructured("DEV.SERVICE_START_FAILED", error);
1905
+ }
1906
+ }
1907
+ let endpoints;
1908
+ try {
1909
+ endpoints = await mergedEndpoints(attachments);
1910
+ } catch (error) {
1911
+ throw toStructured("DEV.ATTACH_FAILED", error);
1912
+ }
1913
+ emit({
1914
+ kind: "ready",
1915
+ endpoints
1916
+ });
1917
+ const { targets, unwatchable } = watchTargetsFrom(pipeline.assembled.bundles);
1918
+ for (const address of unwatchable) emit({
1919
+ kind: "unwatchable",
1920
+ address
1921
+ });
1922
+ const watchDeps = {
1923
+ runAssembler: deps.runAssembler,
1924
+ config: deps.config,
1925
+ configPath: deps.configPath
1926
+ };
1927
+ watch = startWatch(targets, () => {
1928
+ (async () => {
1929
+ try {
1930
+ const rePipeline = await runPipeline(input.entry, input.name, cwd, watchDeps);
1931
+ const stackPath = writeDevStackFile({
1932
+ entryPath: rePipeline.entryModule.path,
1933
+ cwd,
1934
+ configPath: rePipeline.configPath,
1935
+ name: rePipeline.name,
1936
+ assembled: rePipeline.assembled
1937
+ });
1938
+ const outcome = await (deps.alchemy ?? spawnAlchemy)(alchemyInvocation({
1939
+ command: "deploy",
1940
+ stackFileRelativePath: DEV_STACK_RELATIVE_PATH,
1941
+ cwd,
1942
+ stage: "dev",
1943
+ containerEnv: containerEnv(containers)
1944
+ }));
1945
+ if (outcome.signal !== null || outcome.exitCode !== 0) {
1946
+ emit({
1947
+ kind: "converge-failed",
1948
+ stackFilePath: stackPath,
1949
+ reproduceCommand,
1950
+ cwd
1951
+ });
1952
+ return;
1953
+ }
1954
+ emit({
1955
+ kind: "ready",
1956
+ endpoints: await mergedEndpoints(attachments)
1957
+ });
1958
+ } catch (error) {
1959
+ emit({
1960
+ kind: "rebuild-failed",
1961
+ message: failureMessage(error)
1962
+ });
1963
+ }
1964
+ })();
1965
+ }, (error) => emit({
1966
+ kind: "watch-error",
1967
+ message: failureMessage(error)
1968
+ }));
1969
+ const startedWatch = watch;
1970
+ await watch.ready;
1971
+ let stopping = false;
1972
+ let resolveClosed = () => void 0;
1973
+ const closed = new Promise((resolve) => {
1974
+ resolveClosed = resolve;
1975
+ });
1976
+ const stop = () => {
1977
+ if (!stopping) {
1978
+ stopping = true;
1979
+ emit({ kind: "stopping" });
1980
+ startedWatch.stop();
1981
+ (async () => {
1982
+ for (const attachment of attachments) try {
1983
+ await attachment.stopServices();
1984
+ } catch (error) {
1985
+ emit({
1986
+ kind: "stop-error",
1987
+ message: failureMessage(error)
1988
+ });
1989
+ }
1990
+ emit({ kind: "stopped" });
1991
+ resolveClosed();
1992
+ })();
1993
+ }
1994
+ return closed;
1995
+ };
1996
+ return ok({
1997
+ endpoints,
1998
+ stop,
1999
+ closed
2000
+ });
2001
+ } catch (error) {
2002
+ watch?.stop();
2003
+ await Promise.all(started.map((a) => a.stopServices().catch(() => void 0)));
2004
+ if (CliStructuredError.is(error)) return notOk(error);
2005
+ throw error;
2006
+ }
2007
+ }
2008
+ //#endregion
2009
+ export { executeDev };
2010
+
2011
+ //# sourceMappingURL=execute-dev-BMTFWfFc-B1whS-Rr.mjs.map