path-class 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,6 +24,43 @@ export declare class Path {
24
24
  *
25
25
  */
26
26
  static resolve(path: string | URL | Path, base: string | URL | Path): Path;
27
+ /**
28
+ * Convenience function. The following are equivalent:
29
+ *
30
+ * B.resolve(A);
31
+ * Path.resolve(A, B);
32
+ *
33
+ */
34
+ resolve(path: string | URL | Path): Path;
35
+ /**
36
+ * Computes the relative path from an ancestor (this) to another path.
37
+ *
38
+ * - If the path is a descendant *or is the same path*, this returns a
39
+ * relative path. Call {@link Path.asBare `.asBare()`} on the output if
40
+ * needed.
41
+ * - The output is `null` unless the input paths are:
42
+ * - Both absolute paths.
43
+ * - Both relative paths. Resolve the paths before passing to this function
44
+ * if needed.
45
+ * - Trailing slashes:
46
+ * - By default, the ancestor path must have a trailing slash for the
47
+ * function to be called. Pass `{ requireTrailingSlashForAncestor: false
48
+ * }` if needed. Note that recombining the ancestor path with the output
49
+ * using {@link Path.prototype.resolve `.resolve(…)` } does not result in
50
+ * the original input path if the ancestor path did not have a trailing
51
+ * slash.
52
+ * - For the descendant/same path check, trailing slashes are ignored. In
53
+ * particular, if the ancestor path has a trailing slash and the
54
+ * descendant path is the same path without a trailing slash, this is
55
+ * still considered to be the same path.
56
+ * - The output has trailing slash if and only if:
57
+ * - the input descendant does, or
58
+ * - the output is the absolute path `/`.
59
+ */
60
+ descendantRelativePath(potentialDescendant: string | URL | Path, options?: {
61
+ requireTrailingSlashForAncestor: boolean;
62
+ }): Path | null;
63
+ unresolve(path: string | URL | Path): Path;
27
64
  isAbsolutePath(): boolean;
28
65
  toFileURL(): URL;
29
66
  /**
@@ -160,6 +197,31 @@ export declare class Path {
160
197
  *
161
198
  * */
162
199
  static makeTempDir(prefix?: string): Promise<AsyncDisposablePath>;
200
+ /**
201
+ * Return a path:
202
+ *
203
+ * - whose parent dir is a temp dir that *has* been created, but
204
+ * - which has itself not yet been created.
205
+ *
206
+ * Note that this path can actually also be used to create dir, but it is most
207
+ * convenient to get a path for a temporary file that can be written to, while
208
+ * having a disposal implementation that cleans everything up:
209
+ *
210
+ * await using tempFile = await Path.tempFilePath({ basename: "foo.txt" });
211
+ * await tempFile.write("hello world!");
212
+ * // …
213
+ *
214
+ * Note that that the following are equivalent when *not* using `await using`:
215
+ *
216
+ * await Path.tempFilePath({ basename: "foo.txt" });
217
+ * (await Path.makeTempDir()).join("file.txt");
218
+ *
219
+ * However, it is recommended to use `await using` to ensure cleanup.
220
+ */
221
+ static tempFilePath(options: {
222
+ tempDirPrefix?: string;
223
+ basename?: string | Path;
224
+ }): Promise<AsyncDisposablePath>;
163
225
  rm(options?: Parameters<typeof rm>[1]): Promise<void>;
164
226
  rmDir(): Promise<void>;
165
227
  /**
@@ -251,17 +313,11 @@ export declare class Path {
251
313
  debugPrint(...args: any[]): Path;
252
314
  }
253
315
  export declare class AsyncDisposablePath extends Path {
316
+ #private;
317
+ constructor(path: ConstructorParameters<typeof Path>[0], options?: {
318
+ disposePathInstead: Path | string;
319
+ });
254
320
  [Symbol.asyncDispose](): Promise<void>;
255
321
  }
256
- /**
257
- * This function is useful to serialize any `Path`s in a structure to pass on to
258
- * functions that do not know about the `Path` class, e.g.
259
- *
260
- * function process(args: (string | Path)[]) {
261
- * const argsAsStrings = args.map(stringifyIfPath);
262
- * }
263
- *
264
- */
265
- export declare function stringifyIfPath<T>(value: T | Path): T | string;
266
322
  export declare function mustNotHaveTrailingSlash(path: Path): void;
267
323
  export {};
@@ -61,6 +61,17 @@ function resolutionPrefix(pathString) {
61
61
  }
62
62
  return "bare" /* Bare */;
63
63
  }
64
+ var DEFAULT_TEMP_PREFIX = "js-temp-";
65
+ var DEFAULT_TEMP_FILE_NAME = "file";
66
+ function preserveRelativeResolutionPrefix(pathString, from) {
67
+ if (resolutionPrefix(from) === "relative" /* Relative */ && resolutionPrefix(pathString) !== "relative" /* Relative */) {
68
+ return `./${pathString}`;
69
+ }
70
+ return pathString;
71
+ }
72
+ function joinPreservingRelativeResolutionPrefix(base, relative) {
73
+ return preserveRelativeResolutionPrefix(join(base, ...relative), base);
74
+ }
64
75
  var Path = class _Path {
65
76
  // @ts-expect-error ts(2564): False positive. https://github.com/microsoft/TypeScript/issues/32194
66
77
  #path;
@@ -71,6 +82,25 @@ var Path = class _Path {
71
82
  const s = _Path.#pathlikeToString(path);
72
83
  this.#setNormalizedPath(s);
73
84
  }
85
+ static #pathlikeToString(path) {
86
+ if (path instanceof _Path) {
87
+ return path.#path;
88
+ }
89
+ if (path instanceof URL) {
90
+ return fileURLToPath(path);
91
+ }
92
+ if (typeof path === "string") {
93
+ if (path.startsWith("file:///")) {
94
+ return fileURLToPath(path);
95
+ }
96
+ return path;
97
+ }
98
+ throw new Error("Invalid path");
99
+ }
100
+ // Preserves the `ResolutionPrefix` status when possible.
101
+ #setNormalizedPath(path) {
102
+ this.#path = joinPreservingRelativeResolutionPrefix(path, []);
103
+ }
74
104
  static fromString(s) {
75
105
  if (typeof s !== "string") {
76
106
  throw new Error(
@@ -107,28 +137,67 @@ var Path = class _Path {
107
137
  })();
108
138
  return new _Path(new URL(_Path.#pathlikeToString(path), baseURL));
109
139
  }
110
- static #pathlikeToString(path) {
111
- if (path instanceof _Path) {
112
- return path.#path;
140
+ /**
141
+ * Convenience function. The following are equivalent:
142
+ *
143
+ * B.resolve(A);
144
+ * Path.resolve(A, B);
145
+ *
146
+ */
147
+ resolve(path) {
148
+ return _Path.resolve(path, this);
149
+ }
150
+ /**
151
+ * Computes the relative path from an ancestor (this) to another path.
152
+ *
153
+ * - If the path is a descendant *or is the same path*, this returns a
154
+ * relative path. Call {@link Path.asBare `.asBare()`} on the output if
155
+ * needed.
156
+ * - The output is `null` unless the input paths are:
157
+ * - Both absolute paths.
158
+ * - Both relative paths. Resolve the paths before passing to this function
159
+ * if needed.
160
+ * - Trailing slashes:
161
+ * - By default, the ancestor path must have a trailing slash for the
162
+ * function to be called. Pass `{ requireTrailingSlashForAncestor: false
163
+ * }` if needed. Note that recombining the ancestor path with the output
164
+ * using {@link Path.prototype.resolve `.resolve(…)` } does not result in
165
+ * the original input path if the ancestor path did not have a trailing
166
+ * slash.
167
+ * - For the descendant/same path check, trailing slashes are ignored. In
168
+ * particular, if the ancestor path has a trailing slash and the
169
+ * descendant path is the same path without a trailing slash, this is
170
+ * still considered to be the same path.
171
+ * - The output has trailing slash if and only if:
172
+ * - the input descendant does, or
173
+ * - the output is the absolute path `/`.
174
+ */
175
+ descendantRelativePath(potentialDescendant, options) {
176
+ const requireTrailingSlashForAncestor = options?.requireTrailingSlashForAncestor ?? true;
177
+ if (requireTrailingSlashForAncestor && !this.hasTrailingSlash()) {
178
+ throw new Error(
179
+ "Ancestor must have a trailing slash. Pass `{ requireTrailingSlashForAncestor: false }` if needed."
180
+ );
113
181
  }
114
- if (path instanceof URL) {
115
- return fileURLToPath(path);
182
+ const other = new _Path(potentialDescendant);
183
+ if (this.isAbsolutePath() !== other.isAbsolutePath()) {
184
+ return null;
116
185
  }
117
- if (typeof path === "string") {
118
- if (path.startsWith("file:///")) {
119
- return fileURLToPath(path);
186
+ const thisParts = this.toggleTrailingSlash(false).#path.split("/");
187
+ const otherParts = other.toggleTrailingSlash(false).#path.split("/");
188
+ if (otherParts.length < thisParts.length) {
189
+ return null;
190
+ }
191
+ for (let i = 0; i < thisParts.length; i++) {
192
+ console.log(i, thisParts[i], otherParts[i]);
193
+ if (thisParts[i] !== otherParts[i]) {
194
+ return null;
120
195
  }
121
- return path;
122
196
  }
123
- throw new Error("Invalid path");
197
+ return new _Path("./").join(...otherParts.slice(thisParts.length)).toggleTrailingSlash(other.hasTrailingSlash());
124
198
  }
125
- // Preserves the `ResolutionPrefix` status when possible.
126
- #setNormalizedPath(path) {
127
- const prefix = resolutionPrefix(path);
128
- this.#path = join(path);
129
- if (prefix === "relative" /* Relative */ && !this.#path.startsWith(".")) {
130
- this.#path = `./${this.#path}`;
131
- }
199
+ unresolve(path) {
200
+ return _Path.resolve(path, this);
132
201
  }
133
202
  isAbsolutePath() {
134
203
  return this.resolutionPrefix === "absolute" /* Absolute */;
@@ -206,7 +275,9 @@ var Path = class _Path {
206
275
  }
207
276
  return s;
208
277
  });
209
- return new _Path(join(this.#path, ...segmentStrings));
278
+ return new _Path(
279
+ joinPreservingRelativeResolutionPrefix(this.#path, segmentStrings)
280
+ );
210
281
  }
211
282
  /**
212
283
  * Adjust the prefix to construct a relative path.
@@ -429,7 +500,41 @@ var Path = class _Path {
429
500
  * */
430
501
  static async makeTempDir(prefix) {
431
502
  return new AsyncDisposablePath(
432
- await mkdtemp(new _Path(tmpdir()).join(prefix ?? "js-temp-").toString())
503
+ await mkdtemp(
504
+ new _Path(tmpdir()).join(prefix ?? DEFAULT_TEMP_PREFIX).toString()
505
+ )
506
+ );
507
+ }
508
+ /**
509
+ * Return a path:
510
+ *
511
+ * - whose parent dir is a temp dir that *has* been created, but
512
+ * - which has itself not yet been created.
513
+ *
514
+ * Note that this path can actually also be used to create dir, but it is most
515
+ * convenient to get a path for a temporary file that can be written to, while
516
+ * having a disposal implementation that cleans everything up:
517
+ *
518
+ * await using tempFile = await Path.tempFilePath({ basename: "foo.txt" });
519
+ * await tempFile.write("hello world!");
520
+ * // …
521
+ *
522
+ * Note that that the following are equivalent when *not* using `await using`:
523
+ *
524
+ * await Path.tempFilePath({ basename: "foo.txt" });
525
+ * (await Path.makeTempDir()).join("file.txt");
526
+ *
527
+ * However, it is recommended to use `await using` to ensure cleanup.
528
+ */
529
+ static async tempFilePath(options) {
530
+ const tempDir = new _Path(
531
+ await mkdtemp(
532
+ new _Path(tmpdir()).join(options?.tempDirPrefix ?? DEFAULT_TEMP_PREFIX).toString()
533
+ )
534
+ );
535
+ return new AsyncDisposablePath(
536
+ tempDir.join(options?.basename ?? DEFAULT_TEMP_FILE_NAME),
537
+ { disposePathInstead: tempDir }
433
538
  );
434
539
  }
435
540
  async rm(options) {
@@ -606,16 +711,19 @@ var Path = class _Path {
606
711
  }
607
712
  };
608
713
  var AsyncDisposablePath = class extends Path {
714
+ #options;
715
+ constructor(path, options) {
716
+ super(path);
717
+ if (options) {
718
+ this.#options = {
719
+ disposePathInstead: new Path(options.disposePathInstead)
720
+ };
721
+ }
722
+ }
609
723
  async [Symbol.asyncDispose]() {
610
- await this.rm_rf();
724
+ await (this.#options?.disposePathInstead ?? this).rm_rf();
611
725
  }
612
726
  };
613
- function stringifyIfPath(value) {
614
- if (value instanceof Path) {
615
- return value.toString();
616
- }
617
- return value;
618
- }
619
727
  function mustNotHaveTrailingSlash(path) {
620
728
  if (path.hasTrailingSlash()) {
621
729
  throw new Error(
@@ -623,16 +731,20 @@ function mustNotHaveTrailingSlash(path) {
623
731
  );
624
732
  }
625
733
  }
626
- var tmp = await Path.makeTempDir();
627
- (await tmp.join("foo.json").write("foo")).rename(
628
- tmp.join("sdfsD", "sdfsdfsdf", "sdfsdf.json")
629
- );
734
+
735
+ // src/stringifyfIfPath.ts
736
+ function stringifyIfPath(value) {
737
+ if (value instanceof Path) {
738
+ return value.toString();
739
+ }
740
+ return value;
741
+ }
630
742
 
631
743
  export {
744
+ stringifyIfPath,
632
745
  ResolutionPrefix,
633
746
  Path,
634
747
  AsyncDisposablePath,
635
- stringifyIfPath,
636
748
  mustNotHaveTrailingSlash
637
749
  };
638
- //# sourceMappingURL=chunk-7GEFMWZY.js.map
750
+ //# sourceMappingURL=chunk-IZ3HOMWW.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/Path.ts", "../../../../src/stringifyfIfPath.ts"],
4
+ "sourcesContent": ["import { createReadStream } from \"node:fs\";\nimport {\n appendFile,\n chmod,\n constants,\n cp,\n lstat,\n mkdir,\n mkdtemp,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n rmdir,\n stat,\n symlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { basename, dirname, extname, join } from \"node:path\";\nimport { cwd } from \"node:process\";\nimport { createInterface } from \"node:readline/promises\";\nimport { Readable } from \"node:stream\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n xdgCache,\n xdgConfig,\n xdgData,\n xdgRuntime,\n xdgState,\n} from \"xdg-basedir\";\nimport type {\n lstatType,\n readDirType,\n readFileType,\n statType,\n} from \"./modifiedNodeTypes\";\nimport { stringifyIfPath } from \"./stringifyfIfPath\";\n\n// Note that (non-static) functions in this file are defined using `function(\u2026)\n// { \u2026 }` rather than arrow functions, specifically because we want `this` to\n// operate on the `Path` instance.\n\ntype WritableData = Parameters<typeof writeFile>[1] | ReadableStream | Response;\nasync function wrangleWritableData(\n data: WritableData | Promise<WritableData>,\n): Promise<Parameters<typeof writeFile>[1]> {\n data = await data;\n if (data instanceof Response) {\n data = data.body ? Readable.fromWeb(data.body) : new Uint8Array(0);\n }\n if (data instanceof ReadableStream) {\n data = Readable.fromWeb(data);\n }\n return data;\n}\n\nexport enum ResolutionPrefix {\n Absolute = \"absolute\",\n Relative = \"relative\",\n Bare = \"bare\",\n}\n\nexport function resolutionPrefix(pathString: string): ResolutionPrefix {\n if (pathString.startsWith(\"/\")) {\n return ResolutionPrefix.Absolute;\n } else if (pathString.startsWith(\"./\")) {\n return ResolutionPrefix.Relative;\n } else if (pathString.startsWith(\"../\")) {\n return ResolutionPrefix.Relative;\n } else if (pathString === \".\") {\n return ResolutionPrefix.Relative;\n } else if (pathString === \"..\") {\n return ResolutionPrefix.Relative;\n }\n return ResolutionPrefix.Bare;\n}\n\nconst DEFAULT_TEMP_PREFIX = \"js-temp-\";\nconst DEFAULT_TEMP_FILE_NAME = \"file\";\n\nfunction preserveRelativeResolutionPrefix(\n pathString: string,\n from: string,\n): string {\n if (\n resolutionPrefix(from) === ResolutionPrefix.Relative &&\n resolutionPrefix(pathString) !== ResolutionPrefix.Relative\n ) {\n // We don't have to handle the case of `\".\"`, as it already starts with `\".\"`\n return `./${pathString}`;\n }\n return pathString;\n}\n\nfunction joinPreservingRelativeResolutionPrefix(\n base: string,\n relative: string[],\n): string {\n return preserveRelativeResolutionPrefix(join(base, ...relative), base);\n}\n\nexport class Path {\n // @ts-expect-error ts(2564): False positive. https://github.com/microsoft/TypeScript/issues/32194\n #path: string;\n /**\n * If `path` is a string starting with `file:///`, it will be parsed as a file URL.\n */\n constructor(path: string | URL | Path) {\n const s = Path.#pathlikeToString(path);\n this.#setNormalizedPath(s);\n }\n\n static #pathlikeToString(path: string | URL | Path): string {\n if (path instanceof Path) {\n return path.#path;\n }\n if (path instanceof URL) {\n return fileURLToPath(path);\n }\n if (typeof path === \"string\") {\n // TODO: allow turning off this heuristic?\n if (path.startsWith(\"file:///\")) {\n return fileURLToPath(path);\n }\n return path;\n }\n throw new Error(\"Invalid path\");\n }\n\n // Preserves the `ResolutionPrefix` status when possible.\n #setNormalizedPath(path: string): void {\n this.#path = joinPreservingRelativeResolutionPrefix(path, []);\n }\n static fromString(s: string): Path {\n if (typeof s !== \"string\") {\n throw new Error(\n \"Invalid argument to `Path.fromString(\u2026)` \u2014 expected a string.\",\n );\n }\n return new Path(s);\n }\n\n get resolutionPrefix(): ResolutionPrefix {\n return resolutionPrefix(this.#path);\n }\n\n /**\n * Similar to `new URL(path, base)`, but accepting and returning `Path` objects.\n * Note that `base` must be one of:\n *\n * - a valid second argument to `new URL(\u2026)`.\n * - a `Path` representing an absolute path.\n *\n */\n static resolve(path: string | URL | Path, base: string | URL | Path): Path {\n const baseURL = (() => {\n if (!(base instanceof Path)) {\n if (typeof base === \"string\" && !base.startsWith(\"file://\")) {\n return pathToFileURL(base);\n }\n return base;\n }\n if (!base.isAbsolutePath()) {\n throw new Error(\n \"The `base` arg to `Path.resolve(\u2026)` must be an absolute path.\",\n );\n }\n return pathToFileURL(base.#path);\n })();\n return new Path(new URL(Path.#pathlikeToString(path), baseURL));\n }\n\n /**\n * Convenience function. The following are equivalent:\n *\n * B.resolve(A);\n * Path.resolve(A, B);\n *\n */\n resolve(path: string | URL | Path): Path {\n return Path.resolve(path, this);\n }\n\n /**\n * Computes the relative path from an ancestor (this) to another path.\n *\n * - If the path is a descendant *or is the same path*, this returns a\n * relative path. Call {@link Path.asBare `.asBare()`} on the output if\n * needed.\n * - The output is `null` unless the input paths are:\n * - Both absolute paths.\n * - Both relative paths. Resolve the paths before passing to this function\n * if needed.\n * - Trailing slashes:\n * - By default, the ancestor path must have a trailing slash for the\n * function to be called. Pass `{ requireTrailingSlashForAncestor: false\n * }` if needed. Note that recombining the ancestor path with the output\n * using {@link Path.prototype.resolve `.resolve(\u2026)` } does not result in\n * the original input path if the ancestor path did not have a trailing\n * slash.\n * - For the descendant/same path check, trailing slashes are ignored. In\n * particular, if the ancestor path has a trailing slash and the\n * descendant path is the same path without a trailing slash, this is\n * still considered to be the same path.\n * - The output has trailing slash if and only if:\n * - the input descendant does, or\n * - the output is the absolute path `/`.\n */\n descendantRelativePath(\n potentialDescendant: string | URL | Path,\n options?: { requireTrailingSlashForAncestor: boolean },\n ): Path | null {\n const requireTrailingSlashForAncestor =\n options?.requireTrailingSlashForAncestor ?? true;\n if (requireTrailingSlashForAncestor && !this.hasTrailingSlash()) {\n throw new Error(\n \"Ancestor must have a trailing slash. Pass `{ requireTrailingSlashForAncestor: false }` if needed.\",\n );\n }\n\n const other = new Path(potentialDescendant);\n if (this.isAbsolutePath() !== other.isAbsolutePath()) {\n return null;\n }\n\n // Leading slashes are okay, as they will result in a `\"\"` component for\n // absolute paths (and we don't compare absolute paths to relative paths.)\n const thisParts = this.toggleTrailingSlash(false).#path.split(\"/\");\n const otherParts = other.toggleTrailingSlash(false).#path.split(\"/\");\n\n if (otherParts.length < thisParts.length) {\n return null;\n }\n for (let i = 0; i < thisParts.length; i++) {\n console.log(i, thisParts[i], otherParts[i]);\n if (thisParts[i] !== otherParts[i]) {\n return null;\n }\n }\n return new Path(\"./\")\n .join(...otherParts.slice(thisParts.length))\n .toggleTrailingSlash(other.hasTrailingSlash());\n }\n\n unresolve(path: string | URL | Path): Path {\n return Path.resolve(path, this);\n }\n\n isAbsolutePath(): boolean {\n return this.resolutionPrefix === ResolutionPrefix.Absolute;\n }\n\n toFileURL(): URL {\n if (!this.isAbsolutePath()) {\n throw new Error(\n \"Tried to convert to file URL when the path is not absolute.\",\n );\n }\n return pathToFileURL(this.#path);\n }\n\n /**\n * The `Path` can have a trailing slash, indicating that it represents a\n * directory. (If there is no trailing slash, it can represent either a file\n * or a directory.)\n *\n * Some operations will refuse to treat a directory path as a file path. This\n * function identifies such paths.\n */\n hasTrailingSlash(): boolean {\n // TODO: handle Windows semantically\n return this.#path.endsWith(\"/\");\n }\n\n /**\n * Toggles or sets a trailing slash as specified.\n * If the path is `/`, it will always be left as-is.\n */\n // Similar convention to:\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle Most\n // use cases will probably use the `force` parameters, but supporting the\n // \"toggle\" use case is easy to implement and hopefully will make the name\n // and API more familiar to web devs.\n toggleTrailingSlash(force?: boolean): Path {\n if (this.#path === \"/\") {\n return this;\n }\n const wantTrailingSlash = force ?? !this.hasTrailingSlash();\n if (wantTrailingSlash) {\n return this.hasTrailingSlash() ? this : this.join(\"./\");\n } else {\n return this.hasTrailingSlash() ? new Path(this.#path.slice(0, -1)) : this;\n }\n }\n\n /**\n * Same as `.toString()`, but more concise.\n */\n get path() {\n return this.#path;\n }\n\n toString(): string {\n return this.#path;\n }\n\n /**\n * Format this with the escape codes for printing to the shell in bold blue.\n *\n * Example usage:\n *\n * console.log(`Processing: ${path.blue}`)\n *\n */\n get blue() {\n const { styleText } = globalThis.process.getBuiltinModule(\"node:util\");\n return styleText([\"bold\", \"blue\"], this.#path);\n }\n\n /** Constructs a new path by appending the given path segments.\n * This follows `node` semantics for absolute paths: leading slashes in the given descendant segments are ignored.\n */\n join(...segments: (string | Path)[]): Path {\n const segmentStrings = segments.map((segment) => {\n const s = stringifyIfPath(segment);\n if (resolutionPrefix(s) === ResolutionPrefix.Absolute) {\n throw new Error(\n \"Arguments to `.join(\u2026)` cannot be absolute. Use `.asRelative()` to convert them first if needed.\",\n );\n }\n return s;\n });\n return new Path(\n joinPreservingRelativeResolutionPrefix(this.#path, segmentStrings),\n );\n }\n\n /**\n * Adjust the prefix to construct a relative path.\n *\n * | Example input | Output |\n * |-----------------|-----------------|\n * | `\"bare\"` | `\"./bare\"` |\n * | `\"./relative\"` | `\"./relative\"` |\n * | `\"../up-first\"` | `\"../up-first\"` |\n * | `\"/absolute\"` | `\"./absolute\"` |\n *\n */\n asRelative(): Path {\n return new Path(`./${this.#path}`);\n }\n\n /**\n * Adjust the prefix to construct an absolute path.\n *\n * | Example input | Output |\n * |-----------------|---------------|\n * | `\"bare\"` | `\"/bare\"` |\n * | `\"./relative\"` | `\"/relative\"` |\n * | `\"../up-first\"` | `\"/up-first\"` |\n * | `\"/absolute\"` | `\"/absolute\"` |\n *\n */\n asAbsolute(): Path {\n return new Path(join(\"/\", this.#path));\n }\n\n /**\n * Adjust the prefix to construct a bare path. Note that this returns `\".\"` if\n * there are no named paths left.\n *\n * | Example input | Output |\n * |-------------------|--------------|\n * | `\"bare\"` | `\"bare\"` |\n * | `\"./relative\" ` | `\"relative\"` |\n * | `\"/absolute\"` | `\"absolute\"` |\n * | `\".\"` | `\".\"` |\n * | `\"down-first/..\"` | `\".\"` |\n * | `\"../up-first\"` | (error) |\n * | `\"..\"` | (error) |\n *\n * Specify `parentTraversalPrefixHandling` in the `options` if you would like\n * to strip or keep resolution prefixes like `../` rather than erroring.\n *\n * | Example input | Output with `{ parentTraversalPrefixHandling: \"strip\" }` |\n * |----------------------|----------------------------------------------------------|\n * | `\"../up-first\"` | `\"up-first\"` |\n * | `\"..\"` | `\".\"` |\n *\n * | Example input | Output with `{ parentTraversalPrefixHandling: \"keep\" }` |\n * |----------------------|---------------------------------------------------------|\n * | `\"../up-first\"` | `\"../up-first\"` |\n * | `\"..\"` | `\"..\"` |\n *\n * If you need the output to start with a named component and return values\n * like `.`, `..`, `../`, or `../\u2026` are not okay, pass\n * `requireNamedComponentPrefix: true`. This is useful if the path represents\n * an `npm`-style package name (e.g. `\"typescript\"`, `\"@biomejs/biome\"`).\n *\n */\n asBare(options?: {\n parentTraversalPrefixHandling?: \"error\" | \"strip\" | \"keep\";\n requireNamedComponentPrefix?: boolean;\n }): Path {\n const path = new Path(join(\".\", this.#path));\n if (!path.#path.startsWith(\"../\") && path.#path !== \"..\") {\n if (\n options?.requireNamedComponentPrefix &&\n path.resolutionPrefix === ResolutionPrefix.Relative\n ) {\n throw new Error(\"Output does not start with a named component.\");\n }\n return path;\n }\n const parentTraversalHandling =\n options?.parentTraversalPrefixHandling ?? \"error\";\n switch (parentTraversalHandling) {\n case \"error\": {\n throw new Error(\n 'Converting path to a bare path resulted in a `..` traversal prefix. Pass `\"strip\"` or `\"keep\"` as the `parentTraversalHandling` option to avoid an error.',\n );\n }\n case \"strip\": {\n let newPath = path.#path.replace(/^(\\.\\.\\/)+/, \"\");\n if ([\"\", \"..\"].includes(newPath)) {\n newPath = \".\";\n }\n const output = new Path(newPath);\n if (\n options?.requireNamedComponentPrefix &&\n output.resolutionPrefix === ResolutionPrefix.Relative\n ) {\n throw new Error(\"Output does not start with a named component.\");\n }\n return new Path(newPath);\n }\n case \"keep\": {\n if (options?.requireNamedComponentPrefix) {\n throw new Error(\"Output does not start with a named component.\");\n }\n return path;\n }\n }\n }\n\n extendBasename(suffix: string): Path {\n const joinedSuffix = join(suffix);\n if (joinedSuffix !== basename(joinedSuffix)) {\n throw new Error(\"Invalid suffix to extend file name.\");\n }\n // TODO: join basename and dirname instead?\n return new Path(this.#path + joinedSuffix);\n }\n\n get parent(): Path {\n return new Path(dirname(this.#path));\n }\n\n // Normally I'd stick with `node`'s name, but I think `.dirname` is a\n // particularly poor name. So we support `.dirname` for discovery but mark it\n // as deprecated, even if it will never be removed.\n /** @deprecated Alias for `.parent`. */\n get dirname(): Path {\n return this.parent;\n }\n\n get basename(): Path {\n return new Path(basename(this.#path));\n }\n\n get extension(): string {\n mustNotHaveTrailingSlash(this);\n return extname(this.#path);\n }\n\n // Normally I'd stick with `node`'s name, but I think `.extname` is a\n // particularly poor name. So we support `.extname` for discovery but mark it\n // as deprecated, even if it will never be removed.\n /** @deprecated Alias for `.extension`. */\n get extname(): string {\n return this.extension;\n }\n\n // TODO: find a neat way to dedup with the sync version?\n async exists(constraints?: {\n mustBe: \"file\" | \"directory\";\n }): Promise<boolean> {\n if (constraints?.mustBe === \"file\") {\n mustNotHaveTrailingSlash(this);\n }\n let stats: Awaited<ReturnType<typeof stat>>;\n try {\n stats = await stat(this.#path);\n // biome-ignore lint/suspicious/noExplicitAny: TypeScript limitation\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n return false;\n }\n throw e;\n }\n if (!constraints?.mustBe) {\n return true;\n }\n switch (constraints?.mustBe) {\n case \"file\": {\n if (stats.isFile()) {\n return true;\n }\n throw new Error(`Path exists but is not a file: ${this.#path}`);\n }\n case \"directory\": {\n if (stats.isDirectory()) {\n return true;\n }\n throw new Error(`Path exists but is not a directory: ${this.#path}`);\n }\n default: {\n throw new Error(\"Invalid path type constraint\");\n }\n }\n }\n\n async existsAsFile(): Promise<boolean> {\n return this.exists({ mustBe: \"file\" });\n }\n\n async existsAsDir(): Promise<boolean> {\n return this.exists({ mustBe: \"directory\" });\n }\n\n // I don't think `mkdir` is a great name, but it does match the\n // well-established canonical commandline name. So in this case we keep the\n // awkward abbreviation.\n /** Defaults to `recursive: true`. */\n async mkdir(options?: Parameters<typeof mkdir>[1]): Promise<Path> {\n const optionsObject = (() => {\n if (typeof options === \"string\" || typeof options === \"number\") {\n return { mode: options };\n }\n return options ?? {};\n })();\n await mkdir(this.#path, { recursive: true, ...optionsObject });\n return this;\n }\n\n // TODO: check idempotency semantics when the destination exists and is a folder.\n /** Returns the destination path. */\n async cp(\n destination: string | URL | Path,\n options?: Parameters<typeof cp>[2] & { createIntermediateDirs?: boolean },\n ): Promise<Path> {\n const { createIntermediateDirs, ...cpOptions } = options ?? {};\n const destinationPath = new Path(destination);\n if (createIntermediateDirs ?? true) {\n await destinationPath.parent.mkdir();\n }\n await cp(this.#path, destinationPath.#path, cpOptions);\n return destinationPath;\n }\n\n // TODO: check idempotency semantics when the destination exists and is a folder.\n async rename(\n destination: string | URL | Path,\n options?: { createIntermediateDirs?: boolean },\n ): Promise<Path> {\n const destinationPath = new Path(destination);\n if (options?.createIntermediateDirs ?? true) {\n await destinationPath.parent.mkdir();\n }\n await rename(this.#path, destinationPath.#path);\n return destinationPath;\n }\n\n /**\n * Create a temporary dir inside the global temp dir for the current user.\n *\n * This can be used with [`await\n * using`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/await_using)\n * to automatically delete the dir when it goes out of scope.\n *\n * {\n * await using tempDir = await Path.makeTempDir();\n * // Temporary dir exists while we're inside this block.\n * }\n * // Temporary dir has now been deleted.\n *\n * Note that (due to the semantics of JS runtime implementations) this does\n * not delete the temp dir if the process calls `exit(\u2026)` before the `using`\n * goes out of scope.\n *\n * */\n static async makeTempDir(prefix?: string): Promise<AsyncDisposablePath> {\n return new AsyncDisposablePath(\n await mkdtemp(\n new Path(tmpdir()).join(prefix ?? DEFAULT_TEMP_PREFIX).toString(),\n ),\n );\n }\n\n /**\n * Return a path:\n *\n * - whose parent dir is a temp dir that *has* been created, but\n * - which has itself not yet been created.\n *\n * Note that this path can actually also be used to create dir, but it is most\n * convenient to get a path for a temporary file that can be written to, while\n * having a disposal implementation that cleans everything up:\n *\n * await using tempFile = await Path.tempFilePath({ basename: \"foo.txt\" });\n * await tempFile.write(\"hello world!\");\n * // \u2026\n *\n * Note that that the following are equivalent when *not* using `await using`:\n *\n * await Path.tempFilePath({ basename: \"foo.txt\" });\n * (await Path.makeTempDir()).join(\"file.txt\");\n *\n * However, it is recommended to use `await using` to ensure cleanup.\n */\n static async tempFilePath(options: {\n tempDirPrefix?: string;\n basename?: string | Path;\n }): Promise<AsyncDisposablePath> {\n const tempDir = new Path(\n await mkdtemp(\n new Path(tmpdir())\n .join(options?.tempDirPrefix ?? DEFAULT_TEMP_PREFIX)\n .toString(),\n ),\n );\n return new AsyncDisposablePath(\n tempDir.join(options?.basename ?? DEFAULT_TEMP_FILE_NAME),\n { disposePathInstead: tempDir },\n );\n }\n\n async rm(options?: Parameters<typeof rm>[1]): Promise<void> {\n await rm(this.#path, options);\n }\n\n async rmDir(): Promise<void> {\n await rmdir(this.#path);\n }\n\n /**\n * Equivalent to:\n *\n * .rm({ recursive: true, force: true, ...(options ?? {}) })\n *\n */\n async rm_rf(options?: Parameters<typeof rm>[1]): Promise<void> {\n await this.rm({ recursive: true, force: true, ...(options ?? {}) });\n }\n\n read: typeof readFileType = (options) =>\n // biome-ignore lint/suspicious/noExplicitAny: Needed to wrangle the types.\n readFile(this.#path, options as any) as any;\n\n async readText(): Promise<string> {\n return readFile(this.#path, \"utf-8\");\n }\n\n /**\n * Yields one line from the text of the line at a time.\n *\n * This uses streams, so it can be considerably more efficient than calling e.g. `.split(\"\\n\")` on the output of {@link readText `.readText()`}.\n *\n * Note that this function does not have a `.readLinesSync()` counterpart.\n */\n async *readLines(): AsyncIterable<string> {\n const stream = createReadStream(this.#path, \"utf-8\");\n yield* createInterface({ input: stream, terminal: false });\n }\n\n /**\n * Reads JSON from the given file and parses it. No validation is performed\n * (beyond JSON parsing).\n *\n * An optional `fallback` value can be specified. It will be used if (and only\n * if) the file does not exist.\n *\n */\n\n // biome-ignore lint/suspicious/noExplicitAny: Allow a default of `any` to match `JSON.parse(\u2026)`.\n async readJSON<T = any>(options?: { fallback?: T }): Promise<T> {\n try {\n return JSON.parse(await this.readText());\n } catch (e) {\n if (\n (e as { code?: string }).code === \"ENOENT\" &&\n options &&\n \"fallback\" in options\n ) {\n return options.fallback as T;\n }\n throw e;\n }\n }\n\n /**\n * Returns the original `Path` (for chaining).\n */\n async appendFile(\n data: Parameters<typeof appendFile>[1],\n options?: Parameters<typeof appendFile>[2],\n ): Promise<Path> {\n await appendFile(this.#path, data, options);\n return this;\n }\n\n /** Creates intermediate directories if they do not exist.\n *\n * Returns the original `Path` (for chaining).\n */\n async write(\n data: WritableData | Promise<WritableData>,\n options?: Parameters<typeof writeFile>[2],\n ): Promise<Path> {\n await this.parent.mkdir();\n await writeFile(this.#path, await wrangleWritableData(data), options);\n return this;\n }\n\n /**\n * If only `data` is provided, this is equivalent to:\n *\n * .write(JSON.stringify(data, null, \" \"));\n *\n * `replacer` and `space` can also be specified, making this equivalent to:\n *\n * .write(JSON.stringify(data, replacer, space));\n *\n * Returns the original `Path` (for chaining).\n */\n async writeJSON<T>(\n data: T,\n replacer: Parameters<typeof JSON.stringify>[1] = null,\n space: Parameters<typeof JSON.stringify>[2] = \" \",\n ): Promise<Path> {\n await this.write(JSON.stringify(data, replacer, space));\n return this;\n }\n\n // Normally we'd add a `@deprecated` alias named `.readdir`, but that would\n // differ only by capitalization of a single non-leading character. This can\n // be a bit confusing, especially when autocompleting. So for this function in\n // particular we don't include an alias.\n readDir: typeof readDirType = (options) =>\n // biome-ignore lint/suspicious/noExplicitAny: Needed to wrangle the types.\n readdir(this.#path, options as any) as any;\n\n /** Returns the destination path. */\n async symlink(\n target: string | URL | Path,\n type?: Parameters<typeof symlink>[2],\n ): Promise<Path> {\n const targetPath = new Path(target);\n await symlink(\n this.path,\n targetPath.path,\n type as Exclude<Parameters<typeof symlink>[2], undefined>, // \uD83E\uDD37\n );\n return targetPath;\n }\n\n // I don't think `realpath` is a great name, but it does match the\n // well-established canonical commandline name. So in this case we keep the\n // name instead of using `realPath`.\n //\n // Note: There are no options in our API, because the only option is an\n // encoding. We set the encoding to construct the returned `Path`.\n async realpath(): Promise<Path> {\n return new Path(await realpath(this.#path, \"utf-8\"));\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Needed to wrangle the types.\n stat: typeof statType = (...options) => stat(this.#path, ...options) as any;\n\n // I don't think `lstat` is a great name, but it does match the\n // well-established canonical system call. So in this case we keep the\n // awkward abbreviation.\n lstat: typeof lstatType = (...options) =>\n // biome-ignore lint/suspicious/noExplicitAny: Needed to wrangle the types.\n lstat(this.#path, ...options) as any;\n\n async chmod(mode: Parameters<typeof chmod>[1]): Promise<Path> {\n await chmod(this.#path, mode);\n return this;\n }\n\n /**\n * Add the executable bit (for everyone) to the given path without modifying other bits (`chmod +x`).\n */\n async chmodX(): Promise<Path> {\n const { mode } = await this.stat();\n await this.chmod(\n mode | constants.S_IXUSR | constants.S_IXGRP | constants.S_IXOTH,\n );\n return this;\n }\n\n static get homedir(): Path {\n return new Path(homedir());\n }\n\n /**\n * Get the current working directory as a path. Always includes a trailing slash.\n * Note that this computes the `cwd` from fresh every time, in case it has changed for the current process.\n */\n static get cwd(): Path {\n return new Path(cwd()).toggleTrailingSlash(true);\n }\n\n static xdg = {\n cache: new Path(xdgCache ?? Path.homedir.join(\".cache\")),\n config: new Path(xdgConfig ?? Path.homedir.join(\".config\")),\n data: new Path(xdgData ?? Path.homedir.join(\".local/share\")),\n state: new Path(xdgState ?? Path.homedir.join(\".local/state\")),\n /**\n * {@link Path.xdg.runtime} does not have a default value. Consider\n * {@link Path.xdg.runtimeWithStateFallback} if you need a fallback but do not have a particular fallback in mind.\n */\n runtime: xdgRuntime ? new Path(xdgRuntime) : undefined,\n runtimeWithStateFallback: xdgRuntime\n ? new Path(xdgRuntime)\n : new Path(xdgState ?? Path.homedir.join(\".local/state\")),\n };\n\n /** Chainable function to print the path. Prints the same as:\n *\n * if (args.length > 0) {\n * console.log(...args);\n * }\n * console.log(this.path);\n *\n */\n // biome-ignore lint/suspicious/noExplicitAny: This is the correct type, based on `console.log(\u2026)`.\n debugPrint(...args: any[]): Path {\n if (args.length > 0) {\n console.log(...args);\n }\n console.log(this.#path);\n return this;\n }\n}\n\nexport class AsyncDisposablePath extends Path {\n #options?: { disposePathInstead: Path };\n constructor(\n path: ConstructorParameters<typeof Path>[0],\n options?: { disposePathInstead: Path | string },\n ) {\n super(path);\n if (options) {\n this.#options = {\n disposePathInstead: new Path(options.disposePathInstead),\n };\n }\n }\n\n async [Symbol.asyncDispose]() {\n await (this.#options?.disposePathInstead ?? this).rm_rf();\n }\n}\n\nexport function mustNotHaveTrailingSlash(path: Path): void {\n if (path.hasTrailingSlash()) {\n throw new Error(\n \"Path ends with a slash, which cannot be treated as a file.\",\n );\n }\n}\n", "import { Path } from \"./Path\";\n\n/**\n * This function is useful to serialize any `Path`s in a structure to pass on to\n * functions that do not know about the `Path` class, e.g.\n *\n * function process(args: (string | Path)[]) {\n * const argsAsStrings = args.map(stringifyIfPath);\n * }\n *\n */\nexport function stringifyIfPath<T>(value: Exclude<T, Path> | Path): T | string {\n if (value instanceof Path) {\n return value.toString();\n }\n return value;\n}\n"],
5
+ "mappings": ";AAAA,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS,cAAc;AAChC,SAAS,UAAU,SAAS,SAAS,YAAY;AACjD,SAAS,WAAW;AACpB,SAAS,uBAAuB;AAChC,SAAS,gBAAgB;AACzB,SAAS,eAAe,qBAAqB;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAcP,eAAe,oBACb,MAC0C;AAC1C,SAAO,MAAM;AACb,MAAI,gBAAgB,UAAU;AAC5B,WAAO,KAAK,OAAO,SAAS,QAAQ,KAAK,IAAI,IAAI,IAAI,WAAW,CAAC;AAAA,EACnE;AACA,MAAI,gBAAgB,gBAAgB;AAClC,WAAO,SAAS,QAAQ,IAAI;AAAA,EAC9B;AACA,SAAO;AACT;AAEO,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,cAAW;AACX,EAAAA,kBAAA,cAAW;AACX,EAAAA,kBAAA,UAAO;AAHG,SAAAA;AAAA,GAAA;AAML,SAAS,iB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B,WAAO,MAAM,SAAS;AAAA,EACxB;AACA,SAAO;AACT;",
6
+ "names": ["ResolutionPrefix"]
7
+ }
@@ -1 +1,2 @@
1
- export { AsyncDisposablePath, Path, ResolutionPrefix, stringifyIfPath, } from "./Path";
1
+ export { AsyncDisposablePath, Path, ResolutionPrefix, } from "./Path";
2
+ export { stringifyIfPath } from "./stringifyfIfPath";
@@ -3,7 +3,7 @@ import {
3
3
  Path,
4
4
  ResolutionPrefix,
5
5
  stringifyIfPath
6
- } from "./chunks/chunk-7GEFMWZY.js";
6
+ } from "./chunks/chunk-IZ3HOMWW.js";
7
7
  export {
8
8
  AsyncDisposablePath,
9
9
  Path,
@@ -0,0 +1,11 @@
1
+ import { Path } from "./Path";
2
+ /**
3
+ * This function is useful to serialize any `Path`s in a structure to pass on to
4
+ * functions that do not know about the `Path` class, e.g.
5
+ *
6
+ * function process(args: (string | Path)[]) {
7
+ * const argsAsStrings = args.map(stringifyIfPath);
8
+ * }
9
+ *
10
+ */
11
+ export declare function stringifyIfPath<T>(value: Exclude<T, Path> | Path): T | string;
@@ -4,6 +4,8 @@ import type { lstatSyncType, readDirSyncType, readFileSyncType, statSyncType } f
4
4
  export declare class PathSync extends Path {
5
5
  static fromString(s: string): PathSync;
6
6
  static resolve(...args: Parameters<typeof Path.resolve>): PathSync;
7
+ resolve(...args: Parameters<Path["resolve"]>): PathSync;
8
+ descendantRelativePath(...args: Parameters<Path["descendantRelativePath"]>): PathSync | null;
7
9
  toggleTrailingSlash(...args: Parameters<Path["toggleTrailingSlash"]>): PathSync;
8
10
  join(...args: Parameters<Path["join"]>): PathSync;
9
11
  asRelative(...args: Parameters<Path["asRelative"]>): PathSync;
@@ -28,7 +30,32 @@ export declare class PathSync extends Path {
28
30
  renameSync(destination: string | URL | Path, options?: {
29
31
  createIntermediateDirs?: boolean;
30
32
  }): PathSync;
31
- static makeTempDirSync(prefix?: string): PathSync;
33
+ static makeTempDirSync(prefix?: string): DisposablePathSync;
34
+ /**
35
+ * Return a path:
36
+ *
37
+ * - whose parent dir is a temp dir that *has* been created, but
38
+ * - which has itself not yet been created.
39
+ *
40
+ * Note that this path can actually also be used to create dir, but it is most
41
+ * convenient to get a path for a temporary file that can be written to, while
42
+ * having a disposal implementation that cleans everything up:
43
+ *
44
+ * using tempFile = PathSync.tempFilePathSync({ basename: "foo.txt" });
45
+ * tempFile.writeSync("hello world!");
46
+ * // …
47
+ *
48
+ * Note that that the following are equivalent when *not* using `using`:
49
+ *
50
+ * PathSync.tempFilePathSync({ basename: "foo.txt" });
51
+ * PathSync.makeTempDirSync().join("file.txt");
52
+ *
53
+ * However, it is recommended to use `using` to ensure cleanup.
54
+ */
55
+ static tempFilePathSync(options: {
56
+ tempDirPrefix?: string;
57
+ basename?: string | Path;
58
+ }): DisposablePathSync;
32
59
  rmSync(options?: Parameters<typeof rmSync>[1]): void;
33
60
  rmDirSync(): void;
34
61
  rm_rfSync(options?: Parameters<typeof rmSync>[1]): void;
@@ -48,3 +75,10 @@ export declare class PathSync extends Path {
48
75
  chmodSync(mode: Parameters<typeof chmodSync>[1]): PathSync;
49
76
  chmodXSync(): PathSync;
50
77
  }
78
+ export declare class DisposablePathSync extends PathSync {
79
+ #private;
80
+ constructor(path: ConstructorParameters<typeof Path>[0], options?: {
81
+ disposePathInstead: Path | string;
82
+ });
83
+ [Symbol.dispose](): void;
84
+ }
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  Path,
3
3
  mustNotHaveTrailingSlash
4
- } from "../chunks/chunk-7GEFMWZY.js";
4
+ } from "../chunks/chunk-IZ3HOMWW.js";
5
5
 
6
6
  // src/sync/PathSync.ts
7
7
  import {
@@ -23,6 +23,8 @@ import {
23
23
  } from "node:fs";
24
24
  import { constants } from "node:fs/promises";
25
25
  import { tmpdir } from "node:os";
26
+ var DEFAULT_TEMP_PREFIX = "js-temp-sync-";
27
+ var DEFAULT_TEMP_FILE_NAME = "file";
26
28
  var PathSync = class _PathSync extends Path {
27
29
  static fromString(s) {
28
30
  return new _PathSync(s);
@@ -30,6 +32,16 @@ var PathSync = class _PathSync extends Path {
30
32
  static resolve(...args) {
31
33
  return new _PathSync(Path.resolve(...args));
32
34
  }
35
+ resolve(...args) {
36
+ return new _PathSync(super.resolve(...args));
37
+ }
38
+ descendantRelativePath(...args) {
39
+ const v = super.descendantRelativePath(...args);
40
+ if (v === null) {
41
+ return null;
42
+ }
43
+ return new _PathSync(v);
44
+ }
33
45
  toggleTrailingSlash(...args) {
34
46
  return new _PathSync(super.toggleTrailingSlash(...args));
35
47
  }
@@ -135,8 +147,38 @@ var PathSync = class _PathSync extends Path {
135
147
  return destinationPath;
136
148
  }
137
149
  static makeTempDirSync(prefix) {
138
- return new _PathSync(
139
- mkdtempSync(new Path(tmpdir()).join(prefix ?? "js-temp-").toString())
150
+ return new DisposablePathSync(
151
+ mkdtempSync(
152
+ new Path(tmpdir()).join(prefix ?? DEFAULT_TEMP_PREFIX).toString()
153
+ )
154
+ );
155
+ }
156
+ /**
157
+ * Return a path:
158
+ *
159
+ * - whose parent dir is a temp dir that *has* been created, but
160
+ * - which has itself not yet been created.
161
+ *
162
+ * Note that this path can actually also be used to create dir, but it is most
163
+ * convenient to get a path for a temporary file that can be written to, while
164
+ * having a disposal implementation that cleans everything up:
165
+ *
166
+ * using tempFile = PathSync.tempFilePathSync({ basename: "foo.txt" });
167
+ * tempFile.writeSync("hello world!");
168
+ * // …
169
+ *
170
+ * Note that that the following are equivalent when *not* using `using`:
171
+ *
172
+ * PathSync.tempFilePathSync({ basename: "foo.txt" });
173
+ * PathSync.makeTempDirSync().join("file.txt");
174
+ *
175
+ * However, it is recommended to use `using` to ensure cleanup.
176
+ */
177
+ static tempFilePathSync(options) {
178
+ const tempDir = _PathSync.makeTempDirSync(options?.tempDirPrefix);
179
+ return new DisposablePathSync(
180
+ tempDir.join(options?.basename ?? DEFAULT_TEMP_FILE_NAME),
181
+ { disposePathInstead: tempDir }
140
182
  );
141
183
  }
142
184
  rmSync(options) {
@@ -217,6 +259,20 @@ var PathSync = class _PathSync extends Path {
217
259
  return this;
218
260
  }
219
261
  };
262
+ var DisposablePathSync = class extends PathSync {
263
+ #options;
264
+ constructor(path, options) {
265
+ super(path);
266
+ if (options) {
267
+ this.#options = {
268
+ disposePathInstead: new PathSync(options.disposePathInstead)
269
+ };
270
+ }
271
+ }
272
+ [Symbol.dispose]() {
273
+ (this.#options?.disposePathInstead ?? this).rm_rfSync();
274
+ }
275
+ };
220
276
  export {
221
277
  PathSync
222
278
  };