@package-pal/core 0.0.8 → 0.0.11

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 (62) hide show
  1. package/index.d.ts +4 -0
  2. package/index.d.ts.map +1 -1
  3. package/index.js +389 -374
  4. package/index.js.map +27 -27
  5. package/lib/api.d.ts +1 -1
  6. package/lib/api.d.ts.map +1 -1
  7. package/lib/configuration/functions/load-config.d.ts.map +1 -1
  8. package/lib/configuration/functions/parse-config.d.ts +1 -0
  9. package/lib/configuration/functions/parse-config.d.ts.map +1 -1
  10. package/lib/configuration/schemas/config.d.ts +5 -75
  11. package/lib/configuration/schemas/config.d.ts.map +1 -1
  12. package/lib/graph/functions/dfs-traverse-graph-paths.d.ts +8 -1
  13. package/lib/graph/functions/dfs-traverse-graph-paths.d.ts.map +1 -1
  14. package/lib/graph/functions/extract-subgraph.d.ts.map +1 -1
  15. package/lib/graph/functions/generate-graphs.d.ts.map +1 -1
  16. package/lib/graph/functions/generate-topological-sorted-groups.d.ts +1 -1
  17. package/lib/graph/functions/generate-topological-sorted-groups.d.ts.map +1 -1
  18. package/lib/package/functions/load-packages.d.ts +2 -1
  19. package/lib/package/functions/load-packages.d.ts.map +1 -1
  20. package/lib/package/functions/run-for-each-package.d.ts.map +1 -1
  21. package/lib/package/functions/scan-glob-pattern-paths.d.ts +3 -0
  22. package/lib/package/functions/scan-glob-pattern-paths.d.ts.map +1 -0
  23. package/lib/package/types/package-adapter.d.ts +36 -0
  24. package/lib/package/types/package-adapter.d.ts.map +1 -0
  25. package/lib/package/types/package-data.d.ts +1 -0
  26. package/lib/package/types/package-data.d.ts.map +1 -1
  27. package/lib/process/functions/get-commands-for-shell.d.ts +5 -1
  28. package/lib/process/functions/get-commands-for-shell.d.ts.map +1 -1
  29. package/lib/process/functions/get-line-buffered-writer.d.ts +7 -1
  30. package/lib/process/functions/get-line-buffered-writer.d.ts.map +1 -1
  31. package/lib/process/functions/get-shell.d.ts +3 -0
  32. package/lib/process/functions/get-shell.d.ts.map +1 -0
  33. package/lib/process/functions/parse-ps-shell-flags.d.ts.map +1 -1
  34. package/lib/process/functions/read-stream.d.ts.map +1 -1
  35. package/lib/process/functions/run-subprocess.d.ts +2 -1
  36. package/lib/process/functions/run-subprocess.d.ts.map +1 -1
  37. package/lib/process/functions/strip-clixml.d.ts +6 -0
  38. package/lib/process/functions/strip-clixml.d.ts.map +1 -0
  39. package/lib/types/bump-package-version-options.d.ts +2 -0
  40. package/lib/types/bump-package-version-options.d.ts.map +1 -1
  41. package/lib/types/get-package-data-options.d.ts +2 -0
  42. package/lib/types/get-package-data-options.d.ts.map +1 -1
  43. package/lib/types/shell.d.ts +12 -0
  44. package/lib/types/shell.d.ts.map +1 -0
  45. package/lib/watch/functions/dedupe-shared-paths.d.ts +3 -0
  46. package/lib/watch/functions/dedupe-shared-paths.d.ts.map +1 -0
  47. package/lib/watch/functions/filter-files-modified-since.d.ts +1 -1
  48. package/lib/watch/functions/filter-files-modified-since.d.ts.map +1 -1
  49. package/lib/watch/functions/get-change-logic.d.ts +1 -1
  50. package/lib/watch/functions/get-change-logic.d.ts.map +1 -1
  51. package/lib/watch/functions/watch-package-changes.d.ts.map +1 -1
  52. package/lib/watch/types/dedupe-paths-by.d.ts +7 -0
  53. package/lib/watch/types/dedupe-paths-by.d.ts.map +1 -0
  54. package/package.json +6 -7
  55. package/lib/package/functions/parse-package.d.ts +0 -3
  56. package/lib/package/functions/parse-package.d.ts.map +0 -1
  57. package/lib/package/functions/scan-packages.d.ts +0 -4
  58. package/lib/package/functions/scan-packages.d.ts.map +0 -1
  59. package/lib/package/functions/update-package-version.d.ts +0 -5
  60. package/lib/package/functions/update-package-version.d.ts.map +0 -1
  61. package/lib/watch/functions/normalise-pattern-separators.d.ts +0 -2
  62. package/lib/watch/functions/normalise-pattern-separators.d.ts.map +0 -1
package/index.js CHANGED
@@ -9,8 +9,11 @@ var BumpVersionType = {
9
9
  Prepatch: "prepatch",
10
10
  Prerelease: "prerelease"
11
11
  };
12
+ // packages/core/src/lib/package/types/package-adapter.ts
13
+ class PackageAdapter {
14
+ }
12
15
  // packages/core/src/lib/api.ts
13
- import { isDefined as isDefined5 } from "@package-pal/util";
16
+ import { isDefined as isDefined4 } from "@package-pal/util";
14
17
 
15
18
  // packages/core/src/lib/configuration/functions/check-bun.ts
16
19
  var checkBun = () => {
@@ -20,9 +23,9 @@ var checkBun = () => {
20
23
  };
21
24
 
22
25
  // packages/core/src/lib/configuration/functions/load-config.ts
23
- import { styleText } from "util";
24
26
  import { dirname as dirname3 } from "path";
25
27
  import { cwd } from "process";
28
+ import { styleText } from "util";
26
29
  import {
27
30
  deepMergeDefined,
28
31
  formatSimpleLogObject,
@@ -85,6 +88,11 @@ var LogLevel = z3.enum([
85
88
  "silent"
86
89
  ]);
87
90
  var Config = z3.object({
91
+ adapter: z3.optional(z3.enum([
92
+ "package-json",
93
+ "msbuild",
94
+ "auto"
95
+ ])),
88
96
  packages: z3.optional(z3.union([z3.string(), z3.array(z3.string())])),
89
97
  version: z3.optional(z3.object({
90
98
  preId: z3.optional(z3.string()),
@@ -210,6 +218,7 @@ var searchConfigPath = async (pathOverride) => {
210
218
 
211
219
  // packages/core/src/lib/configuration/functions/load-config.ts
212
220
  var defaultConfig = {
221
+ adapter: "auto",
213
222
  packages: "packages/*",
214
223
  version: {
215
224
  preId: "",
@@ -241,7 +250,7 @@ var defaultConfig = {
241
250
  var loadConfig = async (overrideConfigPath) => {
242
251
  const path = await searchConfigPath(overrideConfigPath);
243
252
  if (!path) {
244
- defaultConfig.logger.info("No config file found. Defaults will be applied.");
253
+ defaultConfig.logger.debug("No config file found. Defaults will be applied.");
245
254
  return {
246
255
  config: defaultConfig,
247
256
  rootDir: cwd()
@@ -268,32 +277,16 @@ ${styleText("dim", formatSimpleLogObject(activatedConfig))}`);
268
277
  // packages/core/src/lib/graph/functions/generate-graphs.ts
269
278
  import { styleText as styleText2 } from "util";
270
279
  import { assertDefined as assertDefined2 } from "@package-pal/util";
271
-
272
- // packages/core/src/lib/package/types/dependencies-field.ts
273
- var DependenciesField = {
274
- Dependencies: "dependencies",
275
- DevDependencies: "devDependencies",
276
- PeerDependencies: "peerDependencies",
277
- OptionalDependencies: "optionalDependencies"
278
- };
279
-
280
- // packages/core/src/lib/graph/functions/generate-graphs.ts
281
280
  var trackPackageEntryDependencies = ({
282
281
  trackedDependencies,
283
282
  packageNames,
284
283
  packageData
285
284
  }) => {
286
- const iterateEntries = Object.values(DependenciesField).map((field) => packageData[field]);
287
- for (const packageEntries of iterateEntries) {
288
- if (!packageEntries) {
285
+ for (const trackPackageName of packageData.localDependencies ?? []) {
286
+ if (!packageNames.has(trackPackageName)) {
289
287
  continue;
290
288
  }
291
- for (const trackPackageName of Object.keys(packageEntries)) {
292
- if (!packageNames.has(trackPackageName)) {
293
- continue;
294
- }
295
- trackedDependencies.add(trackPackageName);
296
- }
289
+ trackedDependencies.add(trackPackageName);
297
290
  }
298
291
  };
299
292
  var generateReverseGraph = (packages, packageGraph) => {
@@ -339,7 +332,8 @@ import { assertDefined as assertDefined6 } from "@package-pal/util";
339
332
 
340
333
  // packages/core/src/lib/graph/functions/dfs-traverse-graph-paths.ts
341
334
  import { assertDefined as assertDefined3 } from "@package-pal/util";
342
- var dfsTraverseGraphPaths = function* (graph, traverseFromPackages) {
335
+ var dfsTraverseGraphPaths = function* (graph, traverseFromPackages, options = {}) {
336
+ const { useGlobalVisited = true } = options;
343
337
  const globalVisited = new Set;
344
338
  const startPackages = Array.isArray(traverseFromPackages) ? traverseFromPackages : [traverseFromPackages];
345
339
  for (const start of startPackages) {
@@ -361,7 +355,7 @@ var dfsTraverseGraphPaths = function* (graph, traverseFromPackages) {
361
355
  }
362
356
  continue;
363
357
  }
364
- if (globalVisited.has(node)) {
358
+ if (useGlobalVisited && globalVisited.has(node)) {
365
359
  continue;
366
360
  }
367
361
  const newPath = [...path, node];
@@ -382,7 +376,9 @@ var dfsTraverseGraphPaths = function* (graph, traverseFromPackages) {
382
376
  if (!pushed) {
383
377
  yield newPath;
384
378
  }
385
- globalVisited.add(node);
379
+ if (useGlobalVisited) {
380
+ globalVisited.add(node);
381
+ }
386
382
  }
387
383
  }
388
384
  };
@@ -420,7 +416,12 @@ var extractSubgraph = (graph, fromPackages) => {
420
416
  const subgraph = new Map;
421
417
  for (const packageName of reachablePackages) {
422
418
  const node = assertDefined5(graph.get(packageName));
423
- const filteredNeighbours = new Set([...node.pointsToPackages].filter((dep) => reachablePackages.has(dep)));
419
+ const filteredNeighbours = new Set;
420
+ for (const dep of node.pointsToPackages) {
421
+ if (reachablePackages.has(dep)) {
422
+ filteredNeighbours.add(dep);
423
+ }
424
+ }
424
425
  subgraph.set(packageName, {
425
426
  packageData: node.packageData,
426
427
  pointsToPackages: filteredNeighbours
@@ -510,11 +511,14 @@ var getCircularDependencies = (inDegree) => {
510
511
  return Array.from(inDegree.keys()).sort((a, b) => {
511
512
  const degA = assertDefined7(inDegree.get(a));
512
513
  const degB = assertDefined7(inDegree.get(b));
513
- return degB - degA;
514
- }).sort();
514
+ if (degB !== degA) {
515
+ return degB - degA;
516
+ }
517
+ return a.localeCompare(b);
518
+ });
515
519
  };
516
520
  var generateTopologicalSortedGroups = (packageGraph, logger) => {
517
- logger.debug(styleText4("dim", "Generating topological sorted groups..."));
521
+ logger?.debug(styleText4("dim", "Generating topological sorted groups..."));
518
522
  const graphEntries = Array.from(packageGraph.entries());
519
523
  const inDegree = new Map(graphEntries.map(([packageName]) => [packageName, 0]));
520
524
  const graph = new Map(graphEntries.map(([packageName]) => [packageName, new Set]));
@@ -549,10 +553,10 @@ var generateTopologicalSortedGroups = (packageGraph, logger) => {
549
553
  }
550
554
  ready = nextReady;
551
555
  }
552
- logger.debug(styleText4("dim", `Sorted packages into ${result.length.toString()} sequential groups of parallelizable dependencies.`));
556
+ logger?.debug(styleText4("dim", `Sorted packages into ${result.length.toString()} sequential groups of parallelizable dependencies.`));
553
557
  const circular = getCircularDependencies(inDegree);
554
558
  if (circular.length) {
555
- logger.warn(styleText4("yellow", `${circular.length.toString()} packages could not be sorted due to circular dependencies. Correct ordering cannot be guaranteed.`));
559
+ logger?.warn(styleText4("yellow", `${circular.length.toString()} packages could not be sorted due to circular dependencies. Correct ordering cannot be guaranteed.`));
556
560
  }
557
561
  return {
558
562
  groups: result.map((group) => group.sort()),
@@ -561,98 +565,13 @@ var generateTopologicalSortedGroups = (packageGraph, logger) => {
561
565
  };
562
566
 
563
567
  // packages/core/src/lib/package/functions/load-packages.ts
564
- import { styleText as styleText6 } from "util";
565
-
566
- // packages/core/src/lib/package/functions/scan-packages.ts
567
568
  import { styleText as styleText5 } from "util";
568
- import {
569
- dirname as dirname5,
570
- join as join2
571
- } from "path";
572
- import { formatUnknownError } from "@package-pal/util";
573
-
574
- // packages/core/src/lib/package/functions/parse-package.ts
575
- import {
576
- dirname as dirname4,
577
- basename as basename2
578
- } from "path";
579
- import { isDefined as isDefined2 } from "@package-pal/util";
580
- var parsePackage = (path, text) => {
581
- const base = JSON.parse(text);
582
- if (!isDefined2(base) || typeof base !== "object") {
583
- return;
584
- }
585
- const props = base;
586
- const {
587
- dependencies,
588
- peerDependencies,
589
- devDependencies
590
- } = props;
591
- for (const field of Object.values(DependenciesField)) {
592
- const value = props[field];
593
- if (isDefined2(value) && typeof value !== "object") {
594
- return;
595
- }
596
- }
597
- return {
598
- rawContent: text,
599
- path,
600
- name: props.name ?? path,
601
- dir: basename2(dirname4(path)),
602
- version: props.version ?? undefined,
603
- dependencies: dependencies ?? undefined,
604
- peerDependencies: peerDependencies ?? undefined,
605
- devDependencies: devDependencies ?? undefined
606
- };
607
- };
608
-
609
- // packages/core/src/lib/package/functions/scan-package-paths.ts
610
- import { scanGlobPatternPaths } from "@package-pal/util";
611
- var scanPackagePaths = (packages, cwd2) => {
612
- const baseOpts = {
613
- absolute: true,
614
- onlyFiles: false
615
- };
616
- const opts = {
617
- ...baseOpts,
618
- ...cwd2 ? { cwd: cwd2 } : {}
619
- };
620
- return scanGlobPatternPaths(packages, opts);
621
- };
622
-
623
- // packages/core/src/lib/package/functions/scan-packages.ts
624
- var scanPackages = async function* (patterns, logger, cwd2) {
625
- for await (const path of scanPackagePaths(patterns, cwd2)) {
626
- const packagePath = join2(path, "package.json");
627
- const dir = dirname5(packagePath);
628
- try {
629
- logger.debug(styleText5("dim", `Trying to read read package.json in '${dir}'.`));
630
- const file = Bun.file(packagePath);
631
- if (!file.size) {
632
- logger.debug(styleText5("dim", `Failed to read package.json in '${dir}' - ${styleText5("red", "File not found")}.`));
633
- continue;
634
- }
635
- const text = await file.text();
636
- const packageData = parsePackage(packagePath, text);
637
- if (!packageData) {
638
- logger.debug(styleText5("dim", `Invalid package.json found in '${dir}'.`));
639
- continue;
640
- }
641
- logger.debug(styleText5("dim", `Successfully read package.json in '${dir}'.`));
642
- yield packageData;
643
- } catch (e) {
644
- logger.debug(styleText5("dim", `Failed to read package.json in '${dir}' - ${styleText5("red", formatUnknownError(e))}.`));
645
- }
646
- }
647
- };
648
-
649
- // packages/core/src/lib/package/functions/load-packages.ts
650
- var loadPackages = async (rootDir, packagePatterns, logger) => {
569
+ var loadPackages = async (rootDir, packagePatterns, adapter, logger) => {
651
570
  const patternContent = packagePatterns.map((pattern) => `'${pattern}'`).join(", ");
652
- logger.debug(styleText6("dim", `Loading packages matching pattern/s ${patternContent}...${rootDir ? ` from ${rootDir}` : ""}`));
571
+ logger.debug(styleText5("dim", `Loading packages matching pattern/s ${patternContent}...${rootDir ? ` from ${rootDir}` : ""}`));
653
572
  const packages = [];
654
573
  const seen = new Set;
655
- for await (const packageData of scanPackages(Array.from(new Set(packagePatterns)), logger, rootDir)) {
574
+ for await (const packageData of adapter.scanPackages(Array.from(new Set(packagePatterns)), logger, rootDir)) {
656
575
  if (seen.has(packageData.name)) {
657
576
  continue;
658
577
  }
@@ -666,14 +585,14 @@ var loadPackages = async (rootDir, packagePatterns, logger) => {
666
585
  };
667
586
 
668
587
  // packages/core/src/lib/package/functions/run-for-each-package.ts
669
- import { dirname as dirname6 } from "path";
588
+ import { dirname as dirname4 } from "path";
670
589
  import {
671
- assertDefined as assertDefined9,
590
+ assertDefined as assertDefined8,
672
591
  runAsync
673
592
  } from "@package-pal/util";
674
593
 
675
594
  // packages/core/src/lib/process/functions/run-subprocess.ts
676
- import { styleText as styleText7 } from "util";
595
+ import { styleText as styleText6 } from "util";
677
596
 
678
597
  // packages/core/src/lib/process/types/exit-state.ts
679
598
  var ExitState = {
@@ -689,18 +608,94 @@ var StdType = {
689
608
  };
690
609
 
691
610
  // packages/core/src/lib/process/functions/get-commands-for-shell.ts
611
+ import { identity } from "@package-pal/util";
612
+
613
+ // packages/core/src/lib/types/shell.ts
614
+ var Shell = {
615
+ sh: "sh",
616
+ bash: "bash",
617
+ zsh: "zsh",
618
+ pwsh: "pwsh",
619
+ fish: "fish",
620
+ powershell: "powershell",
621
+ cmd: "cmd"
622
+ };
623
+
624
+ // packages/core/src/lib/process/functions/get-shell.ts
625
+ import { userInfo } from "os";
626
+ import { basename as basename2 } from "path";
692
627
  import {
693
- escapeShellArg,
694
- getShell,
695
- Shell
696
- } from "@package-pal/util";
628
+ platform,
629
+ env
630
+ } from "process";
631
+ var cachedShell = null;
632
+ var cacheShell = (shell) => {
633
+ cachedShell = shell;
634
+ return shell;
635
+ };
636
+ var mapShell = (shellPath) => {
637
+ if (!shellPath) {
638
+ return Shell.sh;
639
+ }
640
+ const name = basename2(shellPath).replace(/\.exe$/i, "").toLowerCase();
641
+ switch (name) {
642
+ case "bash":
643
+ return Shell.bash;
644
+ case "zsh":
645
+ return Shell.zsh;
646
+ case "fish":
647
+ return Shell.fish;
648
+ case "sh":
649
+ return Shell.sh;
650
+ default:
651
+ return Shell.sh;
652
+ }
653
+ };
654
+ var getShell = () => {
655
+ if (cachedShell !== null) {
656
+ return cachedShell;
657
+ }
658
+ if (env.ZSH_VERSION) {
659
+ return cacheShell(Shell.zsh);
660
+ }
661
+ if (env.BASH_VERSION) {
662
+ return cacheShell(Shell.bash);
663
+ }
664
+ if (env.FISH_VERSION) {
665
+ return cacheShell(Shell.fish);
666
+ }
667
+ const isWindows = platform === "win32";
668
+ if (isWindows) {
669
+ if ((env.MSYSTEM || env.MINGW_PREFIX) && Bun.which(Shell.bash)) {
670
+ return cacheShell(Shell.bash);
671
+ }
672
+ if (Bun.which(Shell.pwsh)) {
673
+ return cacheShell(Shell.pwsh);
674
+ }
675
+ if (Bun.which(Shell.powershell)) {
676
+ return cacheShell(Shell.powershell);
677
+ }
678
+ return cacheShell(Shell.cmd);
679
+ }
680
+ if (env.SHELL) {
681
+ return cacheShell(mapShell(env.SHELL));
682
+ }
683
+ try {
684
+ const userShell = userInfo().shell;
685
+ if (userShell) {
686
+ return cacheShell(mapShell(userShell));
687
+ }
688
+ } catch {}
689
+ return cacheShell(Shell.sh);
690
+ };
697
691
 
698
692
  // packages/core/src/lib/process/functions/parse-ps-shell-flags.ts
699
- import { assertDefined as assertDefined8 } from "@package-pal/util";
700
693
  var shellFlagsWithParams = new Set([
701
694
  "-executionpolicy",
702
695
  "-windowstyle",
703
- "-version"
696
+ "-version",
697
+ "-encodedcommand",
698
+ "-command"
704
699
  ]);
705
700
  var shellFlagsNoParams = new Set([
706
701
  "-noprofile",
@@ -714,45 +709,83 @@ var shellFlagsNoParams = new Set([
714
709
  "-usewindowspowerShell"
715
710
  ]);
716
711
  var parsePsShellFlags = (input) => {
717
- const isPreEncoded = input.toLowerCase().includes("-encodedcommand");
718
- const tokens = input.match(/"[^"]*"|'[^']*'|\S+/g) ?? [];
719
712
  const flags = new Set;
720
- let i = 0;
721
- while (i < tokens.length) {
722
- const token = assertDefined8(tokens[i]);
713
+ const tokenRegex = /("[^"]*"|'[^']*'|\S+)/g;
714
+ let match;
715
+ while ((match = tokenRegex.exec(input)) !== null) {
716
+ const token = match[0];
723
717
  const tokenLower = token.toLowerCase();
724
718
  if (shellFlagsWithParams.has(tokenLower)) {
725
719
  flags.add(token);
726
- if (i + 1 < tokens.length) {
727
- flags.add(assertDefined8(tokens[i + 1]));
728
- i++;
720
+ const nextMatch = tokenRegex.exec(input);
721
+ if (nextMatch) {
722
+ flags.add(nextMatch[0]);
729
723
  }
730
- i++;
731
724
  } else if (shellFlagsNoParams.has(tokenLower)) {
732
725
  flags.add(token);
733
- i++;
734
726
  } else {
735
- break;
727
+ const isPreEncoded2 = Array.from(flags).some((flag) => flag.toLowerCase() === "-encodedcommand");
728
+ return {
729
+ flags,
730
+ command: input.slice(match.index),
731
+ isPreEncoded: isPreEncoded2
732
+ };
736
733
  }
737
734
  }
738
- const command = tokens.slice(i).join(" ");
735
+ const isPreEncoded = Array.from(flags).some((flag) => flag.toLowerCase() === "-encodedcommand");
739
736
  return {
740
737
  flags,
741
- command,
738
+ command: "",
742
739
  isPreEncoded
743
740
  };
744
741
  };
745
742
 
743
+ // packages/core/src/lib/process/functions/strip-clixml.ts
744
+ var createClixmlStripper = () => {
745
+ let buffer = "";
746
+ return (chunk) => {
747
+ buffer += chunk;
748
+ if (!buffer.includes("<") && !buffer.includes("#< CLIXML")) {
749
+ const out = buffer;
750
+ buffer = "";
751
+ return out;
752
+ }
753
+ const hasClixmlHeader = buffer.includes("#< CLIXML");
754
+ const hasClixmlTags = /<Obj|S S="Error"|<\/Objs>/.test(buffer);
755
+ if (!hasClixmlHeader && !hasClixmlTags) {
756
+ const out = buffer;
757
+ buffer = "";
758
+ return out;
759
+ }
760
+ buffer = buffer.replace(/#< CLIXML/g, "").replace(/<Obj S="progress"[\s\S]*?<\/Obj>/g, "");
761
+ let output = "";
762
+ buffer = buffer.replace(/<S S="Error">([\s\S]*?)<\/S>/g, (_, msg) => {
763
+ output += msg;
764
+ return "";
765
+ });
766
+ if (buffer.includes("</Objs>")) {
767
+ output += buffer.replace(/<[^>]+>/g, "");
768
+ buffer = "";
769
+ }
770
+ if (!output)
771
+ return "";
772
+ return output.replace(/_x([0-9A-F]{4})_/g, (_, hex) => String.fromCharCode(parseInt(hex, 16))).replace(/<[^>]+>/g, "");
773
+ };
774
+ };
775
+
746
776
  // packages/core/src/lib/process/functions/get-commands-for-shell.ts
747
777
  var getCommandsForShell = (shellCommand) => {
748
778
  const shell = getShell();
749
779
  switch (shell) {
750
780
  case Shell.cmd:
751
- return [
752
- shell,
753
- "/c",
754
- escapeShellArg(shellCommand, shell)
755
- ];
781
+ return {
782
+ commands: [
783
+ shell,
784
+ "/c",
785
+ shellCommand
786
+ ],
787
+ stderrProcessor: identity
788
+ };
756
789
  case Shell.pwsh:
757
790
  case Shell.powershell:
758
791
  const {
@@ -761,35 +794,66 @@ var getCommandsForShell = (shellCommand) => {
761
794
  isPreEncoded
762
795
  } = parsePsShellFlags(shellCommand);
763
796
  if (isPreEncoded) {
764
- return [shell, shellCommand];
797
+ return {
798
+ commands: [shell, ...flags],
799
+ stderrProcessor: createClixmlStripper()
800
+ };
765
801
  }
766
802
  const encodedCommand = Buffer.from(command || " ", "utf16le").toString("base64");
767
- return [
768
- shell,
769
- ...flags,
770
- ...encodedCommand ? ["-EncodedCommand", encodedCommand] : []
771
- ];
803
+ return {
804
+ commands: [
805
+ shell,
806
+ ...flags,
807
+ ...encodedCommand ? ["-EncodedCommand", encodedCommand] : []
808
+ ],
809
+ stderrProcessor: createClixmlStripper()
810
+ };
772
811
  default:
773
- return [
774
- shell,
775
- "-c",
776
- escapeShellArg(shellCommand, shell)
777
- ];
812
+ return {
813
+ commands: [
814
+ shell,
815
+ "-c",
816
+ shellCommand
817
+ ],
818
+ stderrProcessor: identity
819
+ };
778
820
  }
779
821
  };
780
822
 
781
823
  // packages/core/src/lib/process/functions/get-line-buffered-writer.ts
782
- import { identity } from "@package-pal/util";
783
- var getLineBufferedWriter = (prefix, style = identity, write = process.stdout.write.bind(process.stdout)) => {
824
+ import { identity as identity2 } from "@package-pal/util";
825
+ var getLineBufferedWriter = (prefix, style = identity2, write = process.stdout.write.bind(process.stdout)) => {
784
826
  let buffer = "";
785
- return (chunk) => {
786
- buffer += chunk;
787
- const lines = buffer.split(`
827
+ return {
828
+ write: (chunk) => {
829
+ if (chunk === null) {
830
+ if (buffer.length > 0) {
831
+ write(`${prefix}${style(buffer)}
788
832
  `);
789
- buffer = lines.pop() ?? "";
790
- for (const line of lines) {
791
- write(`${prefix}${style(line)}
833
+ buffer = "";
834
+ }
835
+ return;
836
+ }
837
+ buffer += chunk;
838
+ let start = 0;
839
+ let newlineIndex = buffer.indexOf(`
792
840
  `);
841
+ while (newlineIndex !== -1) {
842
+ let end = newlineIndex;
843
+ if (end > start && buffer[end - 1] === "\r") {
844
+ end--;
845
+ }
846
+ const line = buffer.slice(start, end);
847
+ write(`${prefix}${style(line)}
848
+ `);
849
+ start = newlineIndex + 1;
850
+ newlineIndex = buffer.indexOf(`
851
+ `, start);
852
+ }
853
+ buffer = buffer.slice(start);
854
+ },
855
+ flush() {
856
+ this.write(null);
793
857
  }
794
858
  };
795
859
  };
@@ -798,10 +862,14 @@ var getLineBufferedWriter = (prefix, style = identity, write = process.stdout.wr
798
862
  var readStream = async (stream, use) => {
799
863
  const decoder = new TextDecoder;
800
864
  const reader = stream.getReader();
801
- let result = await reader.read();
802
- while (!result.done) {
803
- use(decoder.decode(result.value, { stream: true }));
804
- result = await reader.read();
865
+ try {
866
+ let result = await reader.read();
867
+ while (!result.done) {
868
+ use(decoder.decode(result.value, { stream: true }));
869
+ result = await reader.read();
870
+ }
871
+ } finally {
872
+ reader.releaseLock();
805
873
  }
806
874
  const flush = decoder.decode();
807
875
  if (flush) {
@@ -820,14 +888,21 @@ var cancelCodes = new Set([
820
888
  ]);
821
889
  var runSubprocess = async (opts) => {
822
890
  if (opts.signal?.aborted) {
823
- opts.logger.debug(styleText7("dim", `Skipped '${opts.debugName}' subprocess command; signal already cancelled.`));
891
+ opts.logger?.debug(styleText6("dim", `Skipped '${opts.debugName}' subprocess command; signal already cancelled.`));
824
892
  return ExitState.Cancelled;
825
893
  }
826
- const commands = getCommandsForShell(opts.shellCommand);
894
+ const {
895
+ commands,
896
+ stderrProcessor
897
+ } = getCommandsForShell(opts.shellCommand);
827
898
  const baseSubprocessOpts = {
828
899
  stdout: "pipe",
829
900
  stderr: "pipe",
830
- stdin: "ignore"
901
+ stdin: "ignore",
902
+ env: {
903
+ ...process.env,
904
+ ...opts.env
905
+ }
831
906
  };
832
907
  const subprocessOpts = {
833
908
  ...baseSubprocessOpts,
@@ -840,25 +915,30 @@ var runSubprocess = async (opts) => {
840
915
  const [readStdout, readStderr] = [{
841
916
  source: subprocess.stdout,
842
917
  type: StdType.Out,
843
- write: getLineBufferedWriter(styleText7("dim", `[O-${pid}]`.padEnd(minPrefixLen, " ")))
918
+ writer: getLineBufferedWriter(styleText6("dim", `[O-${pid}]`.padEnd(minPrefixLen, " ")))
844
919
  }, {
845
920
  source: subprocess.stderr,
846
921
  type: StdType.Err,
847
- write: getLineBufferedWriter(styleText7("yellow", styleText7("dim", `[E-${pid}]`.padEnd(minPrefixLen, " "))))
848
- }].map(({
922
+ writer: getLineBufferedWriter(styleText6("yellow", styleText6("dim", `[E-${pid}]`.padEnd(minPrefixLen, " "))), undefined, process.stderr.write.bind(process.stderr))
923
+ }].map(async ({
849
924
  source,
850
925
  type,
851
- write
926
+ writer
852
927
  }) => {
853
- return readStream(source, (chunk) => {
854
- write(chunk);
928
+ await readStream(source, (chunk) => {
929
+ const processedChunk = type === StdType.Err ? stderrProcessor(chunk) : chunk;
930
+ if (processedChunk === "" && chunk !== "") {
931
+ return;
932
+ }
933
+ writer.write(processedChunk);
855
934
  if (opts.onStdChunk) {
856
- opts.onStdChunk(chunk, type);
935
+ opts.onStdChunk(processedChunk, type);
857
936
  }
858
937
  });
938
+ writer.flush();
859
939
  });
860
940
  const executedCommand = commands.join(" ");
861
- opts.logger.debug(styleText7("dim", `Started '${opts.debugName}' subprocess command '${opts.shellCommand}' (${executedCommand}) with PID ${pid}.`));
941
+ opts.logger?.debug(styleText6("dim", `Started '${opts.debugName}' subprocess command '${opts.shellCommand}' (${executedCommand}) with PID ${pid}.`));
862
942
  const [
863
943
  ,
864
944
  ,
@@ -868,14 +948,14 @@ var runSubprocess = async (opts) => {
868
948
  readStderr,
869
949
  subprocess.exited.then((exitCode) => {
870
950
  if (cancelCodes.has(exitCode)) {
871
- opts.logger.debug(styleText7("dim", `Cancelled '${opts.debugName}' subprocess command; PID ${pid} exited.`));
951
+ opts.logger?.debug(styleText6("dim", `Cancelled '${opts.debugName}' subprocess command; PID ${pid} exited.`));
872
952
  return ExitState.Cancelled;
873
953
  }
874
954
  if (exitCode !== 0) {
875
- opts.logger.error(styleText7("red", `'${opts.debugName}' command '${opts.shellCommand}' (${executedCommand}) with PID ${pid} failed with exit code ${exitCode.toString()}.`));
955
+ opts.logger?.error(styleText6("red", `'${opts.debugName}' command '${opts.shellCommand}' (${executedCommand}) with PID ${pid} failed with exit code ${exitCode.toString()}.`));
876
956
  return ExitState.Errored;
877
957
  }
878
- opts.logger.debug(styleText7("dim", `Completed '${opts.debugName}' subprocess command; PID ${pid} exited.`));
958
+ opts.logger?.debug(styleText6("dim", `Completed '${opts.debugName}' subprocess command; PID ${pid} exited.`));
879
959
  return ExitState.Completed;
880
960
  })
881
961
  ]);
@@ -885,18 +965,18 @@ var runSubprocess = async (opts) => {
885
965
  // packages/core/src/lib/package/functions/run-for-each-package.ts
886
966
  var runForEachPackage = async (packageGraphs, packageOrder, getCommand, logger, topological = true, concurrency) => {
887
967
  const controller = new AbortController;
888
- let processPackageOrder = packageOrder.groups.concat(packageOrder.circular);
968
+ let processPackageOrder = packageOrder.circular.length > 0 ? packageOrder.groups.concat([packageOrder.circular]) : packageOrder.groups;
889
969
  if (!topological) {
890
970
  processPackageOrder = [processPackageOrder.flat()];
891
971
  }
892
972
  for (const group of processPackageOrder) {
893
973
  await runAsync(group.map((packageName) => async () => {
894
- const packageNode = assertDefined9(packageGraphs.dependencies.get(packageName));
974
+ const packageNode = assertDefined8(packageGraphs.dependencies.get(packageName));
895
975
  const processPackageProps = {
896
976
  name: packageName,
897
977
  dir: packageNode.packageData.dir
898
978
  };
899
- const processPackageCwd = dirname6(packageNode.packageData.path);
979
+ const processPackageCwd = dirname4(packageNode.packageData.path);
900
980
  const shellCommand = await getCommand(processPackageProps);
901
981
  if (!shellCommand) {
902
982
  return;
@@ -905,6 +985,10 @@ var runForEachPackage = async (packageGraphs, packageOrder, getCommand, logger,
905
985
  debugName: `run for ${packageName}`,
906
986
  shellCommand,
907
987
  cwd: processPackageCwd,
988
+ env: {
989
+ PP_PACKAGE_NAME: packageName,
990
+ PP_PACKAGE_DIR: processPackageProps.dir
991
+ },
908
992
  signal: controller.signal,
909
993
  logger
910
994
  });
@@ -916,136 +1000,21 @@ var runForEachPackage = async (packageGraphs, packageOrder, getCommand, logger,
916
1000
  }
917
1001
  };
918
1002
 
919
- // packages/core/src/lib/package/functions/update-package-version.ts
920
- import { styleText as styleText8 } from "util";
921
- var {semver } = globalThis.Bun;
922
- import { inc } from "semver";
923
- var findAndReplaceVersion = ({
924
- raw,
925
- field,
926
- packageName,
927
- updatePackageName,
928
- newVersion,
929
- exact,
930
- logger
931
- }) => {
932
- if (field === "version" && packageName === updatePackageName) {
933
- const versionKey = `"version"`;
934
- const keyIndex = raw.indexOf(versionKey);
935
- if (keyIndex === -1) {
936
- return raw;
937
- }
938
- const versionStart2 = raw.indexOf('"', keyIndex + versionKey.length);
939
- const versionEnd2 = raw.indexOf('"', versionStart2 + 1);
940
- if (versionStart2 === -1 || versionEnd2 === -1) {
941
- return raw;
942
- }
943
- const currentVersionString2 = raw.slice(versionStart2 + 1, versionEnd2);
944
- const updatedVersion2 = newVersion;
945
- logger.info(`Updating '${updatePackageName}' version: ${currentVersionString2} \u2192 ${updatedVersion2}.`);
946
- const before2 = raw.slice(0, versionStart2 + 1);
947
- const after2 = raw.slice(versionEnd2);
948
- return `${before2}${updatedVersion2}${after2}`;
949
- }
950
- const fieldIndex = raw.indexOf(`"${field}"`);
951
- if (fieldIndex === -1) {
952
- return raw;
953
- }
954
- const fieldStart = raw.indexOf("{", fieldIndex);
955
- if (fieldStart === -1) {
956
- return raw;
957
- }
958
- const fieldEnd = raw.indexOf("}", fieldStart);
959
- if (fieldEnd === -1) {
960
- return raw;
961
- }
962
- const fieldBlock = raw.slice(fieldStart, fieldEnd);
963
- const depKey = `"${packageName}"`;
964
- const depIndex = fieldBlock.indexOf(depKey);
965
- if (depIndex === -1) {
966
- return raw;
967
- }
968
- const versionStart = fieldBlock.indexOf('"', depIndex + depKey.length);
969
- const versionEnd = fieldBlock.indexOf('"', versionStart + 1);
970
- if (versionStart === -1 || versionEnd === -1) {
971
- return raw;
972
- }
973
- const currentVersionString = fieldBlock.slice(versionStart + 1, versionEnd);
974
- const preservedPrefix = exact ? "" : /^([~^><=]*)/.exec(currentVersionString)?.[1] ?? "";
975
- const updatedVersion = `${preservedPrefix}${newVersion}`;
976
- logger.info(`Updating '${updatePackageName}' ${field} '${packageName}': ${currentVersionString} \u2192 ${updatedVersion}.`);
977
- const before = raw.slice(0, fieldStart + versionStart + 1);
978
- const after = raw.slice(fieldStart + versionEnd);
979
- return `${before}${updatedVersion}${after}`;
980
- };
981
- var updatePackageVersion = async (packageName, type, packageGraphs, preId, exact, logger) => {
982
- logger.debug(styleText8("dim", `Bumping package '${packageName}'...`));
983
- const packageNode = packageGraphs.dependencies.get(packageName);
984
- if (!packageNode) {
985
- throw new Error(`Package '${packageName}' not found.`);
986
- }
987
- const currentVersion = packageNode.packageData.version;
988
- if (!currentVersion) {
989
- throw new Error(`Package '${packageName}' has no version.`);
990
- }
991
- const bumpedVersion = inc(currentVersion, type, undefined, preId);
992
- if (!bumpedVersion) {
993
- throw new Error(`Package '${packageName}' version '${currentVersion}' is invalid.`);
994
- }
995
- const updatedContent = findAndReplaceVersion({
996
- raw: packageNode.packageData.rawContent,
997
- field: "version",
998
- packageName,
999
- updatePackageName: packageName,
1000
- newVersion: bumpedVersion,
1001
- exact,
1002
- logger
1003
- });
1004
- const baseWrite = Bun.write(packageNode.packageData.path, updatedContent);
1005
- const dependentWrites = Array.from(dfsTraverseGraph(packageGraphs.dependents, packageName).flatMap((dependent) => {
1006
- return Object.values(DependenciesField).flatMap((field) => {
1007
- const entry = dependent[field];
1008
- const depVersion = entry?.[packageName];
1009
- if (!depVersion) {
1010
- return [];
1011
- }
1012
- if (exact ? depVersion === bumpedVersion : semver.satisfies(bumpedVersion, depVersion)) {
1013
- logger.debug(styleText8("dim", `Skipping '${dependent.name}': ${field} version '${depVersion}' already satisfies '${bumpedVersion}'.`));
1014
- return [];
1015
- }
1016
- const updatedContent2 = findAndReplaceVersion({
1017
- raw: dependent.rawContent,
1018
- field,
1019
- packageName,
1020
- updatePackageName: dependent.name,
1021
- newVersion: bumpedVersion,
1022
- exact,
1023
- logger
1024
- });
1025
- return [Bun.write(dependent.path, updatedContent2)];
1026
- });
1027
- }));
1028
- return Promise.all([baseWrite, ...dependentWrites]).then(() => {
1029
- return;
1030
- });
1031
- };
1032
-
1033
1003
  // packages/core/src/lib/watch/functions/watch-package-changes.ts
1034
1004
  import {
1035
1005
  watch
1036
1006
  } from "fs";
1037
- import { styleText as styleText10 } from "util";
1038
1007
  import {
1039
- dirname as dirname8,
1040
- join as join4
1008
+ dirname as dirname6,
1009
+ join as join3
1041
1010
  } from "path";
1011
+ import { styleText as styleText8 } from "util";
1042
1012
  import {
1043
1013
  assertDefined as assertDefined12,
1044
- DedupePathsBy,
1045
- dedupeSharedPaths,
1046
1014
  getDeferredPromise,
1047
1015
  getStringMatcher,
1048
- isDefined as isDefined4,
1016
+ isDefined as isDefined3,
1017
+ normalisePath,
1049
1018
  runAsync as runAsync2
1050
1019
  } from "@package-pal/util";
1051
1020
  var {Glob } = globalThis.Bun;
@@ -1075,28 +1044,67 @@ var ChangeAction = {
1075
1044
  Restart: "Restart"
1076
1045
  };
1077
1046
 
1047
+ // packages/core/src/lib/watch/types/dedupe-paths-by.ts
1048
+ var DedupePathsBy = {
1049
+ Parent: "parent",
1050
+ Child: "child"
1051
+ };
1052
+
1053
+ // packages/core/src/lib/watch/functions/dedupe-shared-paths.ts
1054
+ import { sep } from "path";
1055
+ import { assertDefined as assertDefined9 } from "@package-pal/util";
1056
+ var dedupeSharedPaths = (paths, by) => {
1057
+ const sorted = paths.toSorted((a, b) => a.split(sep).length - b.split(sep).length);
1058
+ const deduped = [];
1059
+ if (by === DedupePathsBy.Parent) {
1060
+ for (const path of sorted) {
1061
+ if (!deduped.some((base) => path.startsWith(base + sep))) {
1062
+ deduped.push(path);
1063
+ }
1064
+ }
1065
+ return deduped;
1066
+ }
1067
+ for (const path of sorted) {
1068
+ for (let i = deduped.length - 1;i >= 0; i--) {
1069
+ const base = assertDefined9(deduped[i]);
1070
+ if (path.startsWith(base + sep)) {
1071
+ deduped.splice(i, 1);
1072
+ }
1073
+ }
1074
+ if (!deduped.some((base) => base.startsWith(path + sep))) {
1075
+ deduped.push(path);
1076
+ }
1077
+ }
1078
+ return Array.from(new Set(deduped));
1079
+ };
1080
+
1078
1081
  // packages/core/src/lib/watch/functions/filter-files-modified-since.ts
1079
- var filterFilesModifiedSince = (paths, sinceMs) => {
1080
- return paths.filter((path) => {
1081
- const changedFile = Bun.file(path);
1082
- const isDeleted = changedFile.lastModified === 0;
1083
- const isModifiedSince = changedFile.lastModified >= sinceMs;
1084
- return isDeleted || isModifiedSince;
1085
- });
1082
+ import { stat } from "fs/promises";
1083
+ var filterFilesModifiedSince = async (paths, sinceMs) => {
1084
+ const results = await Promise.all(paths.map(async (path) => {
1085
+ try {
1086
+ const s = await stat(path);
1087
+ const isModifiedSince = s.mtimeMs >= sinceMs;
1088
+ return isModifiedSince ? path : null;
1089
+ } catch {
1090
+ return path;
1091
+ }
1092
+ }));
1093
+ return results.filter((path) => path !== null);
1086
1094
  };
1087
1095
 
1088
1096
  // packages/core/src/lib/watch/functions/get-change-logic.ts
1089
- import { styleText as styleText9 } from "util";
1097
+ import { styleText as styleText7 } from "util";
1090
1098
  import { assertDefined as assertDefined11 } from "@package-pal/util";
1091
1099
 
1092
1100
  // packages/core/src/lib/graph/functions/generate-topological-ranking-range.ts
1093
- import { isDefined as isDefined3 } from "@package-pal/util";
1101
+ import { isDefined as isDefined2 } from "@package-pal/util";
1094
1102
  var generateTopologicalRankingRange = (graph, ranking) => {
1095
1103
  let min = Infinity;
1096
1104
  let max = -Infinity;
1097
1105
  for (const key of graph.keys()) {
1098
1106
  const rank = ranking.get(key);
1099
- if (!isDefined3(rank)) {
1107
+ if (!isDefined2(rank)) {
1100
1108
  continue;
1101
1109
  }
1102
1110
  if (rank < min) {
@@ -1187,21 +1195,21 @@ var getChangeLogic = (packageGraphs, packageChanges, lastProcessedSubgraph, conf
1187
1195
  const changedPackages = Array.from(packageChanges.keys());
1188
1196
  const changedFilePaths = Array.from(packageChanges.values()).flat();
1189
1197
  if (packageChanges.size) {
1190
- logger.debug(styleText9("dim", `Changes detected in ${changedPackages.map((packageName) => `'${packageName}'`).join(", ")}.`));
1191
- logger.debug(styleText9("dim", `Changed file paths: ${changedFilePaths.map((filePath) => `'${filePath}'`).join(", ")}.`));
1198
+ logger?.debug(styleText7("dim", `Changes detected in ${changedPackages.map((packageName) => `'${packageName}'`).join(", ")}.`));
1199
+ logger?.debug(styleText7("dim", `Changed file paths: ${changedFilePaths.map((filePath) => `'${filePath}'`).join(", ")}.`));
1192
1200
  }
1193
1201
  const packageOrder = generateTopologicalSortedGroups(packageGraphs.dependents, logger);
1194
- const packageProcessOrder = packageOrder.groups.toReversed().concat(packageOrder.circular);
1202
+ const packageProcessOrder = packageOrder.circular.length > 0 ? packageOrder.groups.toReversed().concat([packageOrder.circular]) : packageOrder.groups.toReversed();
1195
1203
  const packageRankings = generateTopologicalRanking(packageProcessOrder);
1196
1204
  const changedPackageSubgraph = extractSubgraph(packageGraphs.dependents, changedPackages);
1197
1205
  const changedPackageOrder = generateTopologicalSortedGroups(changedPackageSubgraph, logger);
1198
- const changedPackageProcessOrder = changedPackageOrder.groups.toReversed().concat(changedPackageOrder.circular);
1206
+ const changedPackageProcessOrder = changedPackageOrder.circular.length > 0 ? changedPackageOrder.groups.toReversed().concat([changedPackageOrder.circular]) : changedPackageOrder.groups.toReversed();
1199
1207
  const isSubgraphOfPrevious = !!lastProcessedSubgraph && isSubgraph(lastProcessedSubgraph, changedPackageSubgraph);
1200
1208
  const isDisjointFromPrevious = !lastProcessedSubgraph || !isSubgraphOfPrevious && isDisjoint(lastProcessedSubgraph, changedPackageSubgraph);
1201
1209
  const isRankedGreaterThanOrEqualToPrevious = !!lastProcessedSubgraph && !isSubgraphOfPrevious && isRankedGreaterThanOrEqual(lastProcessedSubgraph, changedPackageSubgraph, packageRankings);
1202
- logger.debug(styleText9("dim", `Changes are subgraph of previous: ${isSubgraphOfPrevious.toString()}.`));
1203
- logger.debug(styleText9("dim", `Changes are disjoint from previous: ${isDisjointFromPrevious.toString()}.`));
1204
- logger.debug(styleText9("dim", `Changes are ranked greater than or equal to previous: ${isRankedGreaterThanOrEqualToPrevious.toString()}.`));
1210
+ logger?.debug(styleText7("dim", `Changes are subgraph of previous: ${isSubgraphOfPrevious.toString()}.`));
1211
+ logger?.debug(styleText7("dim", `Changes are disjoint from previous: ${isDisjointFromPrevious.toString()}.`));
1212
+ logger?.debug(styleText7("dim", `Changes are ranked greater than or equal to previous: ${isRankedGreaterThanOrEqualToPrevious.toString()}.`));
1205
1213
  let action = ChangeAction.Restart;
1206
1214
  if (!packageChanges.size) {
1207
1215
  action = ChangeAction.Ignore;
@@ -1221,7 +1229,7 @@ var getChangeLogic = (packageGraphs, packageChanges, lastProcessedSubgraph, conf
1221
1229
  });
1222
1230
  }
1223
1231
  }
1224
- logger.debug(styleText9("dim", `Determined change action: ${action}.`));
1232
+ logger?.debug(styleText7("dim", `Determined change action: ${action}.`));
1225
1233
  return {
1226
1234
  changedPackageProcessOrder,
1227
1235
  changedPackageSubgraph,
@@ -1229,16 +1237,11 @@ var getChangeLogic = (packageGraphs, packageChanges, lastProcessedSubgraph, conf
1229
1237
  };
1230
1238
  };
1231
1239
 
1232
- // packages/core/src/lib/watch/functions/normalise-pattern-separators.ts
1233
- var normalisePatternSeparators = (path) => {
1234
- return path.replace(/\\/g, "/");
1235
- };
1236
-
1237
1240
  // packages/core/src/lib/watch/functions/normalise-watched-file-path.ts
1238
1241
  import {
1239
1242
  basename as basename3,
1240
- dirname as dirname7,
1241
- join as join3
1243
+ dirname as dirname5,
1244
+ join as join2
1242
1245
  } from "path";
1243
1246
  var removeTrailing = [
1244
1247
  "~",
@@ -1251,7 +1254,7 @@ var removeTrailing = [
1251
1254
  ".swn"
1252
1255
  ];
1253
1256
  var normaliseWatchedFilePath = (filePath) => {
1254
- const dir = dirname7(filePath);
1257
+ const dir = dirname5(filePath);
1255
1258
  let base = basename3(filePath);
1256
1259
  for (const trailing of removeTrailing) {
1257
1260
  if (base.toLowerCase().endsWith(trailing)) {
@@ -1260,33 +1263,32 @@ var normaliseWatchedFilePath = (filePath) => {
1260
1263
  break;
1261
1264
  }
1262
1265
  }
1263
- return join3(dir, base);
1266
+ return join2(dir, base);
1264
1267
  };
1265
1268
 
1266
1269
  // packages/core/src/lib/watch/functions/watch-package-changes.ts
1267
1270
  var fileModifiedThresholdMs = 5000;
1268
- var lastProcessedSubgraph;
1269
- var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determineAbortController, logger) => {
1271
+ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determineAbortController, state, logger) => {
1270
1272
  const {
1271
1273
  action,
1272
1274
  changedPackageProcessOrder,
1273
1275
  changedPackageSubgraph
1274
- } = getChangeLogic(packageGraphs, packageChanges, lastProcessedSubgraph, watchConfig, logger);
1276
+ } = getChangeLogic(packageGraphs, packageChanges, state.lastProcessedSubgraph, watchConfig, logger);
1275
1277
  const isRestart = action === ChangeAction.Restart;
1276
1278
  const isSequential = watchConfig.subprocess.concurrency === 1;
1277
1279
  const controller = determineAbortController(isRestart);
1278
1280
  const onProcessFailure = () => {
1279
- logger.debug(styleText10("dim", "Aborting controller: process failed."));
1281
+ logger.debug(styleText8("dim", "Aborting controller: process failed."));
1280
1282
  controller.abort();
1281
- lastProcessedSubgraph = undefined;
1283
+ state.lastProcessedSubgraph = undefined;
1282
1284
  };
1283
1285
  if (action === ChangeAction.Ignore && packageChanges.size) {
1284
1286
  logger.info(`Changes detected; but were ignored due to 'partialProcessing: true'. Waiting for changes..`);
1285
1287
  return;
1286
1288
  }
1287
1289
  if (packageChanges.size) {
1288
- logger.info(`${isRestart ? "Restarting processing" : "Initiating partial processing"} ${isSequential ? "sequentially" : `in parallel${isDefined4(watchConfig.subprocess.concurrency) ? ` with concurrency ${watchConfig.subprocess.concurrency.toString()}` : ""}`}.`);
1289
- lastProcessedSubgraph = lastProcessedSubgraph && !isRestart ? mergeGraphs(lastProcessedSubgraph, changedPackageSubgraph) : changedPackageSubgraph;
1290
+ logger.info(`${isRestart ? "Restarting processing" : "Initiating partial processing"} ${isSequential ? "sequentially" : `in parallel${isDefined3(watchConfig.subprocess.concurrency) ? ` with concurrency ${watchConfig.subprocess.concurrency.toString()}` : ""}`}.`);
1291
+ state.lastProcessedSubgraph = state.lastProcessedSubgraph && !isRestart ? mergeGraphs(state.lastProcessedSubgraph, changedPackageSubgraph) : changedPackageSubgraph;
1290
1292
  }
1291
1293
  for (const group of changedPackageProcessOrder) {
1292
1294
  await runAsync2(group.map((packageName) => async () => {
@@ -1300,7 +1302,7 @@ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determ
1300
1302
  totalProcessOrder: changedPackageProcessOrder,
1301
1303
  signal: controller.signal
1302
1304
  };
1303
- const processPackageCwd = dirname8(packageNode.packageData.path);
1305
+ const processPackageCwd = dirname6(packageNode.packageData.path);
1304
1306
  const beforeProcessPackageShellCommand = await watchConfig.hooks.onBeforeProcessPackage(processPackageProps);
1305
1307
  if (beforeProcessPackageShellCommand) {
1306
1308
  await runSubprocess({
@@ -1341,7 +1343,7 @@ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determ
1341
1343
  if (!errored) {
1342
1344
  const matchedErrorText = erroredMatcher?.push(chunk).matched();
1343
1345
  if (matchedErrorText) {
1344
- logger.error(styleText10("red", `'${packageName}' subprocess matched error text '${matchedErrorText}'.`));
1346
+ logger.error(styleText8("red", `'${packageName}' subprocess matched error text '${matchedErrorText}'.`));
1345
1347
  errored = true;
1346
1348
  Promise.resolve(watchConfig.hooks.onProcessPackageError(processPackageProps)).then((processPackageErrorCommand) => {
1347
1349
  if (!processPackageErrorCommand) {
@@ -1419,8 +1421,9 @@ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determ
1419
1421
  };
1420
1422
  var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, logger) => {
1421
1423
  const dedupedRootPackageData = dedupeSharedPaths(packageData.map((packageData2) => packageData2.path), DedupePathsBy.Parent).map((packagePath) => assertDefined12(packageData.find((data) => data.path === packagePath)));
1422
- logger.debug(styleText10("dim", `Starting ${dedupedRootPackageData.length.toString()} watchers for ${packageData.length.toString()} packages.`));
1424
+ logger.debug(styleText8("dim", `Starting ${dedupedRootPackageData.length.toString()} watchers for ${packageData.length.toString()} packages.`));
1423
1425
  let closed = false;
1426
+ const state = { lastProcessedSubgraph: undefined };
1424
1427
  let debounceTimeout;
1425
1428
  let startedDebounceMs;
1426
1429
  let controller;
@@ -1429,7 +1432,7 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1429
1432
  const useController = (reset) => {
1430
1433
  if (controller && (reset || controller.signal.aborted)) {
1431
1434
  if (reset) {
1432
- logger.debug(styleText10("dim", "Aborting controller: reset for new packages."));
1435
+ logger.debug(styleText8("dim", "Aborting controller: reset for new packages."));
1433
1436
  controller.abort();
1434
1437
  }
1435
1438
  controller = undefined;
@@ -1443,16 +1446,16 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1443
1446
  filePath,
1444
1447
  isInitial = false
1445
1448
  }) => {
1446
- if (!isDefined4(startedDebounceMs)) {
1449
+ if (!isDefined3(startedDebounceMs)) {
1447
1450
  startedDebounceMs = Date.now();
1448
1451
  }
1449
1452
  if (packageName && watchPath && filePath) {
1450
- const changedPath = normalisePatternSeparators(join4(watchPath, normaliseWatchedFilePath(filePath)));
1453
+ const changedPath = normalisePath(join3(watchPath, normaliseWatchedFilePath(filePath)));
1451
1454
  if (ignoreGlobs?.some((glob) => glob.match(changedPath))) {
1452
- logger.debug(styleText10("dim", `Ignoring change '${changedPath}' (matched ignore pattern).`));
1455
+ logger.debug(styleText8("dim", `Ignoring change '${changedPath}' (matched ignore pattern).`));
1453
1456
  return;
1454
1457
  }
1455
- logger.debug(styleText10("dim", `Tracked change '${changedPath}'.`));
1458
+ logger.debug(styleText8("dim", `Tracked change '${changedPath}'.`));
1456
1459
  const existingPaths = changedPackagePaths.get(packageName);
1457
1460
  if (existingPaths) {
1458
1461
  existingPaths.add(changedPath);
@@ -1465,30 +1468,32 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1465
1468
  }
1466
1469
  const debounceMs = isInitial ? 0 : watchConfig.debounceMs;
1467
1470
  debounceTimeout = setTimeout(() => {
1468
- if (closed) {
1469
- return;
1470
- }
1471
- const packageChanges = new Map;
1472
- for (const [packageName2, paths] of changedPackagePaths) {
1473
- const dedupedPaths = dedupeSharedPaths(Array.from(paths), DedupePathsBy.Child).sort();
1474
- const processedPaths = filterFilesModifiedSince(dedupedPaths, assertDefined12(startedDebounceMs) - fileModifiedThresholdMs);
1475
- if (processedPaths.length) {
1476
- packageChanges.set(packageName2, processedPaths);
1471
+ (async () => {
1472
+ if (closed) {
1473
+ return;
1477
1474
  }
1478
- }
1479
- startedDebounceMs = undefined;
1480
- changedPackagePaths.clear();
1481
- if (!packageChanges.size && !isInitial) {
1482
- return;
1483
- }
1484
- onProcessPackage(packageGraphs, packageChanges, watchConfig, (reset) => useController(reset), logger);
1475
+ const packageChanges = new Map;
1476
+ for (const [packageName2, paths] of changedPackagePaths) {
1477
+ const dedupedPaths = dedupeSharedPaths(Array.from(paths), DedupePathsBy.Child).sort();
1478
+ const processedPaths = await filterFilesModifiedSince(dedupedPaths, assertDefined12(startedDebounceMs) - fileModifiedThresholdMs);
1479
+ if (processedPaths.length) {
1480
+ packageChanges.set(packageName2, processedPaths);
1481
+ }
1482
+ }
1483
+ startedDebounceMs = undefined;
1484
+ changedPackagePaths.clear();
1485
+ if (!packageChanges.size && !isInitial) {
1486
+ return;
1487
+ }
1488
+ onProcessPackage(packageGraphs, packageChanges, watchConfig, (reset) => useController(reset), state, logger);
1489
+ })();
1485
1490
  }, debounceMs);
1486
1491
  };
1487
1492
  const watchers = dedupedRootPackageData.map(({
1488
1493
  name,
1489
1494
  path
1490
1495
  }) => {
1491
- const watchPath = dirname8(path);
1496
+ const watchPath = dirname6(path);
1492
1497
  return watch(watchPath, { recursive: true }, (event, filePath) => {
1493
1498
  onWatchEvent({
1494
1499
  watchPath,
@@ -1502,12 +1507,12 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1502
1507
  watchers.forEach((watcher) => {
1503
1508
  watcher.close();
1504
1509
  });
1505
- logger.debug(styleText10("dim", "Aborting controller: closing watchers."));
1510
+ logger.debug(styleText8("dim", "Aborting controller: closing watchers."));
1506
1511
  controller?.abort();
1507
1512
  closed = true;
1508
1513
  };
1509
1514
  process.on("SIGINT", () => {
1510
- logger.debug(styleText10("dim", "Received SIGINT: closing watchers."));
1515
+ logger.debug(styleText8("dim", "Received SIGINT: closing watchers."));
1511
1516
  closeWatchers();
1512
1517
  process.exit(0);
1513
1518
  });
@@ -1525,10 +1530,10 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1525
1530
  });
1526
1531
  return { close: () => {
1527
1532
  if (closed) {
1528
- logger.debug(styleText10("dim", "Watchers already closed."));
1533
+ logger.debug(styleText8("dim", "Watchers already closed."));
1529
1534
  return;
1530
1535
  }
1531
- logger.debug(styleText10("dim", "Closing watchers."));
1536
+ logger.debug(styleText8("dim", "Closing watchers."));
1532
1537
  closeWatchers();
1533
1538
  } };
1534
1539
  };
@@ -1541,7 +1546,7 @@ var readPackagePalConfig = (options) => {
1541
1546
  var readPackageData = async (options) => {
1542
1547
  checkBun();
1543
1548
  const packagePatterns = Array.isArray(options.config.packages) ? options.config.packages : [options.config.packages];
1544
- return loadPackages(options.rootDir, packagePatterns, options.config.logger);
1549
+ return loadPackages(options.rootDir, packagePatterns, options.adapter, options.config.logger);
1545
1550
  };
1546
1551
  var getPackageGraphs = (options) => {
1547
1552
  checkBun();
@@ -1557,9 +1562,16 @@ var getPackageCircularDependencyPaths = (options) => {
1557
1562
  };
1558
1563
  var bumpPackageVersion = (options) => {
1559
1564
  checkBun();
1560
- const exact = isDefined5(options.exact) ? options.exact : options.config.version.exact;
1561
- const preId = isDefined5(options.preId) ? options.preId : options.config.version.preId;
1562
- return updatePackageVersion(options.packageName, options.type, options.packageGraphs, preId, exact, options.config.logger);
1565
+ const exact = isDefined4(options.exact) ? options.exact : options.config.version.exact;
1566
+ const preId = isDefined4(options.preId) ? options.preId : options.config.version.preId;
1567
+ return options.adapter.updateVersion({
1568
+ packageName: options.packageName,
1569
+ type: options.type,
1570
+ packageGraphs: options.packageGraphs,
1571
+ preId,
1572
+ exact,
1573
+ logger: options.config.logger
1574
+ });
1563
1575
  };
1564
1576
  var watchPackages = (options) => {
1565
1577
  checkBun();
@@ -1571,15 +1583,18 @@ var forEachPackage = (options) => {
1571
1583
  };
1572
1584
  export {
1573
1585
  watchPackages,
1586
+ scanPackagePaths,
1574
1587
  readPackagePalConfig,
1575
1588
  readPackageData,
1576
1589
  getPackageOrder,
1577
1590
  getPackageGraphs,
1578
1591
  getPackageCircularDependencyPaths,
1579
1592
  forEachPackage,
1593
+ dfsTraverseGraph2 as dfsTraverseGraph,
1580
1594
  bumpPackageVersion,
1595
+ PackageAdapter,
1581
1596
  BumpVersionType
1582
1597
  };
1583
1598
 
1584
- //# debugId=68AF287603F1263364756E2164756E21
1599
+ //# debugId=2C554E09012C798F64756E2164756E21
1585
1600
  //# sourceMappingURL=index.js.map