@tauri-apps/plugin-fs 2.0.0-alpha.4 → 2.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist-js/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var path = require('@tauri-apps/api/path');
4
- var primitives = require('@tauri-apps/api/primitives');
4
+ var core = require('@tauri-apps/api/core');
5
5
 
6
6
  // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
7
7
  // SPDX-License-Identifier: Apache-2.0
@@ -20,7 +20,7 @@ var primitives = require('@tauri-apps/api/primitives');
20
20
  *
21
21
  * The scope configuration is an array of glob patterns describing folder paths that are allowed.
22
22
  * For instance, this scope configuration only allows accessing files on the
23
- * *databases* folder of the {@link path.appDataDir | $APPDATA directory}:
23
+ * *databases* folder of the {@link https://beta.tauri.app/2/reference/js/core/namespacepath/#appdatadir | `$APPDATA` directory}:
24
24
  * ```json
25
25
  * {
26
26
  * "plugins": {
@@ -31,16 +31,32 @@ var primitives = require('@tauri-apps/api/primitives');
31
31
  * }
32
32
  * ```
33
33
  *
34
- * Notice the use of the `$APPDATA` variable. The value is injected at runtime, resolving to the {@link path.appDataDir | app data directory}.
34
+ * Notice the use of the `$APPDATA` variable. The value is injected at runtime, resolving to the {@link https://beta.tauri.app/2/reference/js/core/namespacepath/#appdatadir | app data directory}.
35
+ *
35
36
  * The available variables are:
36
- * {@link path.appConfigDir | `$APPCONFIG`}, {@link path.appDataDir | `$APPDATA`}, {@link path.appLocalDataDir | `$APPLOCALDATA`},
37
- * {@link path.appCacheDir | `$APPCACHE`}, {@link path.appLogDir | `$APPLOG`},
38
- * {@link path.audioDir | `$AUDIO`}, {@link path.cacheDir | `$CACHE`}, {@link path.configDir | `$CONFIG`}, {@link path.dataDir | `$DATA`},
39
- * {@link path.localDataDir | `$LOCALDATA`}, {@link path.desktopDir | `$DESKTOP`}, {@link path.documentDir | `$DOCUMENT`},
40
- * {@link path.downloadDir | `$DOWNLOAD`}, {@link path.executableDir | `$EXE`}, {@link path.fontDir | `$FONT`}, {@link path.homeDir | `$HOME`},
41
- * {@link path.pictureDir | `$PICTURE`}, {@link path.publicDir | `$PUBLIC`}, {@link path.runtimeDir | `$RUNTIME`},
42
- * {@link path.templateDir | `$TEMPLATE`}, {@link path.videoDir | `$VIDEO`}, {@link path.resourceDir | `$RESOURCE`},
43
- * {@link os.tempdir | `$TEMP`}.
37
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appconfigdir | $APPCONFIG},
38
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appdatadir | $APPDATA},
39
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appLocaldatadir | $APPLOCALDATA},
40
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appcachedir | $APPCACHE},
41
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#applogdir | $APPLOG},
42
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#audiodir | $AUDIO},
43
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#cachedir | $CACHE},
44
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#configdir | $CONFIG},
45
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#datadir | $DATA},
46
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#localdatadir | $LOCALDATA},
47
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#desktopdir | $DESKTOP},
48
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#documentdir | $DOCUMENT},
49
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#downloaddir | $DOWNLOAD},
50
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#executabledir | $EXE},
51
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#fontdir | $FONT},
52
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#homedir | $HOME},
53
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#picturedir | $PICTURE},
54
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#publicdir | $PUBLIC},
55
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#runtimedir | $RUNTIME},
56
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#templatedir | $TEMPLATE},
57
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#videodir | $VIDEO},
58
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#resourcedir | $RESOURCE},
59
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#tempdir | $TEMP}.
44
60
  *
45
61
  * Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
46
62
  *
@@ -48,127 +64,299 @@ var primitives = require('@tauri-apps/api/primitives');
48
64
  *
49
65
  * @module
50
66
  */
67
+ exports.SeekMode = void 0;
68
+ (function (SeekMode) {
69
+ SeekMode[SeekMode["Start"] = 0] = "Start";
70
+ SeekMode[SeekMode["Current"] = 1] = "Current";
71
+ SeekMode[SeekMode["End"] = 2] = "End";
72
+ })(exports.SeekMode || (exports.SeekMode = {}));
73
+ function parseFileInfo(r) {
74
+ return {
75
+ isFile: r.isFile,
76
+ isDirectory: r.isDirectory,
77
+ isSymlink: r.isSymlink,
78
+ size: r.size,
79
+ mtime: r.mtime != null ? new Date(r.mtime) : null,
80
+ atime: r.atime != null ? new Date(r.atime) : null,
81
+ birthtime: r.birthtime != null ? new Date(r.birthtime) : null,
82
+ readonly: r.readonly,
83
+ fileAttributes: r.fileAttributes,
84
+ dev: r.dev,
85
+ ino: r.ino,
86
+ mode: r.mode,
87
+ nlink: r.nlink,
88
+ uid: r.uid,
89
+ gid: r.gid,
90
+ rdev: r.rdev,
91
+ blksize: r.blksize,
92
+ blocks: r.blocks,
93
+ };
94
+ }
51
95
  /**
52
- * Reads a file as an UTF-8 encoded string.
96
+ * The Tauri abstraction for reading and writing files.
97
+ *
98
+ * @since 2.0.0
99
+ */
100
+ class FileHandle extends core.Resource {
101
+ constructor(rid) {
102
+ super(rid);
103
+ }
104
+ /**
105
+ * Reads up to `p.byteLength` bytes into `p`. It resolves to the number of
106
+ * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
107
+ * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may
108
+ * use all of `p` as scratch space during the call. If some data is
109
+ * available but not `p.byteLength` bytes, `read()` conventionally resolves
110
+ * to what is available instead of waiting for more.
111
+ *
112
+ * When `read()` encounters end-of-file condition, it resolves to EOF
113
+ * (`null`).
114
+ *
115
+ * When `read()` encounters an error, it rejects with an error.
116
+ *
117
+ * Callers should always process the `n` > `0` bytes returned before
118
+ * considering the EOF (`null`). Doing so correctly handles I/O errors that
119
+ * happen after reading some bytes and also both of the allowed EOF
120
+ * behaviors.
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * import { open, read, close, BaseDirectory } from "@tauri-apps/plugin-fs"
125
+ * // if "$APP/foo/bar.txt" contains the text "hello world":
126
+ * const file = await open("foo/bar.txt", { dir: BaseDirectory.App });
127
+ * const buf = new Uint8Array(100);
128
+ * const numberOfBytesRead = await file.read(buf); // 11 bytes
129
+ * const text = new TextDecoder().decode(buf); // "hello world"
130
+ * await close(file.rid);
131
+ * ```
132
+ *
133
+ * @since 2.0.0
134
+ */
135
+ async read(buffer) {
136
+ if (buffer.byteLength === 0) {
137
+ return 0;
138
+ }
139
+ const [data, nread] = await core.invoke("plugin:fs|read", {
140
+ rid: this.rid,
141
+ len: buffer.byteLength,
142
+ });
143
+ buffer.set(data);
144
+ return nread === 0 ? null : nread;
145
+ }
146
+ /**
147
+ * Seek sets the offset for the next `read()` or `write()` to offset,
148
+ * interpreted according to `whence`: `Start` means relative to the
149
+ * start of the file, `Current` means relative to the current offset,
150
+ * and `End` means relative to the end. Seek resolves to the new offset
151
+ * relative to the start of the file.
152
+ *
153
+ * Seeking to an offset before the start of the file is an error. Seeking to
154
+ * any positive offset is legal, but the behavior of subsequent I/O
155
+ * operations on the underlying object is implementation-dependent.
156
+ * It returns the number of cursor position.
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * import { open, seek, write, SeekMode, BaseDirectory } from '@tauri-apps/plugin-fs';
161
+ *
162
+ * // Given hello.txt pointing to file with "Hello world", which is 11 bytes long:
163
+ * const file = await open('hello.txt', { read: true, write: true, truncate: true, create: true, dir: BaseDirectory.App });
164
+ * await file.write(new TextEncoder().encode("Hello world"), { dir: BaseDirectory.App });
165
+ *
166
+ * // Seek 6 bytes from the start of the file
167
+ * console.log(await file.seek(6, SeekMode.Start)); // "6"
168
+ * // Seek 2 more bytes from the current position
169
+ * console.log(await file.seek(2, SeekMode.Current)); // "8"
170
+ * // Seek backwards 2 bytes from the end of the file
171
+ * console.log(await file.seek(-2, SeekMode.End)); // "9" (e.g. 11-2)
172
+ * ```
173
+ *
174
+ * @since 2.0.0
175
+ */
176
+ async seek(offset, whence) {
177
+ return core.invoke("plugin:fs|seek", {
178
+ rid: this.rid,
179
+ offset,
180
+ whence,
181
+ });
182
+ }
183
+ /**
184
+ * Returns a {@linkcode FileInfo } for this file.
185
+ *
186
+ * @example
187
+ * ```typescript
188
+ * import { open, fstat, BaseDirectory } from '@tauri-apps/plugin-fs';
189
+ * const file = await open("file.txt", { read: true, dir: BaseDirectory.App });
190
+ * const fileInfo = await fstat(file.rid);
191
+ * console.log(fileInfo.isFile); // true
192
+ * ```
193
+ *
194
+ * @since 2.0.0
195
+ */
196
+ async stat() {
197
+ const res = await core.invoke("plugin:fs|fstat", {
198
+ rid: this.rid,
199
+ });
200
+ return parseFileInfo(res);
201
+ }
202
+ /**
203
+ * Truncates or extends this file, to reach the specified `len`.
204
+ * If `len` is not specified then the entire file contents are truncated.
205
+ *
206
+ * @example
207
+ * ```typescript
208
+ * import { ftruncate, open, write, read, BaseDirectory } from '@tauri-apps/plugin-fs';
209
+ *
210
+ * // truncate the entire file
211
+ * const file = await open("my_file.txt", { read: true, write: true, create: true, dir: BaseDirectory.App });
212
+ * await ftruncate(file.rid);
213
+ *
214
+ * // truncate part of the file
215
+ * const file = await open("my_file.txt", { read: true, write: true, create: true, dir: BaseDirectory.App });
216
+ * await write(file.rid, new TextEncoder().encode("Hello World"));
217
+ * await ftruncate(file.rid, 7);
218
+ * const data = new Uint8Array(32);
219
+ * await read(file.rid, data);
220
+ * console.log(new TextDecoder().decode(data)); // Hello W
221
+ * ```
222
+ *
223
+ * @since 2.0.0
224
+ */
225
+ async truncate(len) {
226
+ return core.invoke("plugin:fs|ftruncate", {
227
+ rid: this.rid,
228
+ len,
229
+ });
230
+ }
231
+ /**
232
+ * Writes `p.byteLength` bytes from `p` to the underlying data stream. It
233
+ * resolves to the number of bytes written from `p` (`0` <= `n` <=
234
+ * `p.byteLength`) or reject with the error encountered that caused the
235
+ * write to stop early. `write()` must reject with a non-null error if
236
+ * would resolve to `n` < `p.byteLength`. `write()` must not modify the
237
+ * slice data, even temporarily.
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * import { open, write, close, BaseDirectory } from '@tauri-apps/plugin-fs';
242
+ * const encoder = new TextEncoder();
243
+ * const data = encoder.encode("Hello world");
244
+ * const file = await open("bar.txt", { write: true, dir: BaseDirectory.App });
245
+ * const bytesWritten = await write(file.rid, data); // 11
246
+ * await close(file.rid);
247
+ * ```
248
+ *
249
+ * @since 2.0.0
250
+ */
251
+ async write(data) {
252
+ return core.invoke("plugin:fs|write", {
253
+ rid: this.rid,
254
+ data: Array.from(data),
255
+ });
256
+ }
257
+ }
258
+ /**
259
+ * Creates a file if none exists or truncates an existing file and resolves to
260
+ * an instance of {@linkcode FileHandle }.
261
+ *
53
262
  * @example
54
263
  * ```typescript
55
- * import { readTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
56
- * // Read the text file in the `$APPCONFIG/app.conf` path
57
- * const contents = await readTextFile('app.conf', { dir: BaseDirectory.AppConfig });
264
+ * import { create, BaseDirectory } from "@tauri-apps/plugin-fs"
265
+ * const file = await create("foo/bar.txt", { dir: BaseDirectory.App });
58
266
  * ```
59
267
  *
60
268
  * @since 2.0.0
61
269
  */
62
- async function readTextFile(filePath, options = {}) {
63
- return await primitives.invoke("plugin:fs|read_text_file", {
64
- path: filePath,
270
+ async function create(path, options) {
271
+ if (path instanceof URL && path.protocol !== "file:") {
272
+ throw new TypeError("Must be a file URL.");
273
+ }
274
+ const rid = await core.invoke("plugin:fs|create", {
275
+ path: path instanceof URL ? path.toString() : path,
65
276
  options,
66
277
  });
278
+ return new FileHandle(rid);
67
279
  }
68
280
  /**
69
- * Reads a file as byte array.
281
+ * Open a file and resolve to an instance of {@linkcode FileHandle}. The
282
+ * file does not need to previously exist if using the `create` or `createNew`
283
+ * open options. It is the callers responsibility to close the file when finished
284
+ * with it.
285
+ *
70
286
  * @example
71
287
  * ```typescript
72
- * import { readBinaryFile, BaseDirectory } from '@tauri-apps/plugin-fs';
73
- * // Read the image file in the `$RESOURCEDIR/avatar.png` path
74
- * const contents = await readBinaryFile('avatar.png', { dir: BaseDirectory.Resource });
288
+ * import { open, BaseDirectory } from "@tauri-apps/plugin-fs"
289
+ * const file = await open("foo/bar.txt", { read: true, write: true, dir: BaseDirectory.App });
290
+ * // Do work with file
291
+ * await close(file.rid);
75
292
  * ```
76
293
  *
77
294
  * @since 2.0.0
78
295
  */
79
- async function readBinaryFile(filePath, options = {}) {
80
- const arr = await primitives.invoke("plugin:fs|read_file", {
81
- path: filePath,
296
+ async function open(path, options) {
297
+ if (path instanceof URL && path.protocol !== "file:") {
298
+ throw new TypeError("Must be a file URL.");
299
+ }
300
+ const rid = await core.invoke("plugin:fs|open", {
301
+ path: path instanceof URL ? path.toString() : path,
82
302
  options,
83
303
  });
84
- return Uint8Array.from(arr);
304
+ return new FileHandle(rid);
85
305
  }
86
306
  /**
87
- * Writes a UTF-8 text file.
88
- *
89
- * @returns A promise indicating the success or failure of the operation.
307
+ * Copies the contents and permissions of one file to another specified path, by default creating a new file if needed, else overwriting.
308
+ * @example
309
+ * ```typescript
310
+ * import { copyFile, BaseDirectory } from '@tauri-apps/plugin-fs';
311
+ * await copyFile('app.conf', 'app.conf.bk', { dir: BaseDirectory.App });
312
+ * ```
90
313
  *
91
314
  * @since 2.0.0
92
315
  */
93
- async function writeTextFile(path, contents, options) {
94
- if (typeof options === "object") {
95
- Object.freeze(options);
96
- }
97
- if (typeof path === "object") {
98
- Object.freeze(path);
99
- }
100
- const file = { path: "", contents: "" };
101
- let fileOptions = options;
102
- if (typeof path === "string") {
103
- file.path = path;
104
- }
105
- else {
106
- file.path = path.path;
107
- file.contents = path.contents;
108
- }
109
- if (typeof contents === "string") {
110
- file.contents = contents ?? "";
111
- }
112
- else {
113
- fileOptions = contents;
316
+ async function copyFile(fromPath, toPath, options) {
317
+ if ((fromPath instanceof URL && fromPath.protocol !== "file:") ||
318
+ (toPath instanceof URL && toPath.protocol !== "file:")) {
319
+ throw new TypeError("Must be a file URL.");
114
320
  }
115
- return await primitives.invoke("plugin:fs|write_file", {
116
- path: file.path,
117
- contents: Array.from(new TextEncoder().encode(file.contents)),
118
- options: fileOptions,
321
+ return core.invoke("plugin:fs|copy_file", {
322
+ fromPath: fromPath instanceof URL ? fromPath.toString() : fromPath,
323
+ toPath: toPath instanceof URL ? toPath.toString() : toPath,
324
+ options,
119
325
  });
120
326
  }
121
327
  /**
122
- * Writes a byte array content to a file.
123
- *
124
- * @returns A promise indicating the success or failure of the operation.
328
+ * Creates a new directory with the specified path.
329
+ * @example
330
+ * ```typescript
331
+ * import { mkdir, BaseDirectory } from '@tauri-apps/plugin-fs';
332
+ * await mkdir('users', { dir: BaseDirectory.App });
333
+ * ```
125
334
  *
126
335
  * @since 2.0.0
127
336
  */
128
- async function writeBinaryFile(path, contents, options) {
129
- if (typeof options === "object") {
130
- Object.freeze(options);
131
- }
132
- if (typeof path === "object") {
133
- Object.freeze(path);
134
- }
135
- const file = { path: "", contents: [] };
136
- let fileOptions = options;
137
- if (typeof path === "string") {
138
- file.path = path;
139
- }
140
- else {
141
- file.path = path.path;
142
- file.contents = path.contents;
337
+ async function mkdir(path, options) {
338
+ if (path instanceof URL && path.protocol !== "file:") {
339
+ throw new TypeError("Must be a file URL.");
143
340
  }
144
- if (contents && "dir" in contents) {
145
- fileOptions = contents;
146
- }
147
- else if (typeof path === "string") {
148
- // @ts-expect-error in this case `contents` is always a BinaryFileContents
149
- file.contents = contents ?? [];
150
- }
151
- return await primitives.invoke("plugin:fs|write_file", {
152
- path: file.path,
153
- contents: Array.from(file.contents instanceof ArrayBuffer
154
- ? new Uint8Array(file.contents)
155
- : file.contents),
156
- options: fileOptions,
341
+ return core.invoke("plugin:fs|mkdir", {
342
+ path: path instanceof URL ? path.toString() : path,
343
+ options,
157
344
  });
158
345
  }
159
346
  /**
160
- * List directory files.
347
+ * Reads the directory given by path and returns an array of `DirEntry`.
161
348
  * @example
162
349
  * ```typescript
163
350
  * import { readDir, BaseDirectory } from '@tauri-apps/plugin-fs';
164
- * // Reads the `$APPDATA/users` directory recursively
165
- * const entries = await readDir('users', { dir: BaseDirectory.AppData, recursive: true });
166
- *
167
- * function processEntries(entries) {
351
+ * const dir = "users"
352
+ * const entries = await readDir('users', { dir: BaseDirectory.App });
353
+ * processEntriesRecursive(dir, entries);
354
+ * async function processEntriesRecursive(parent, entries) {
168
355
  * for (const entry of entries) {
169
- * console.log(`Entry: ${entry.path}`);
170
- * if (entry.children) {
171
- * processEntries(entry.children)
356
+ * console.log(`Entry: ${entry.name}`);
357
+ * if (entry.isDirectory) {
358
+ * const dir = parent + entry.name;
359
+ * processEntriesRecursive(dir, await readDir(dir, { dir: BaseDirectory.App }))
172
360
  * }
173
361
  * }
174
362
  * }
@@ -176,109 +364,258 @@ async function writeBinaryFile(path, contents, options) {
176
364
  *
177
365
  * @since 2.0.0
178
366
  */
179
- async function readDir(dir, options = {}) {
180
- return await primitives.invoke("plugin:fs|read_dir", {
181
- path: dir,
367
+ async function readDir(path, options) {
368
+ if (path instanceof URL && path.protocol !== "file:") {
369
+ throw new TypeError("Must be a file URL.");
370
+ }
371
+ return core.invoke("plugin:fs|read_dir", {
372
+ path: path instanceof URL ? path.toString() : path,
182
373
  options,
183
374
  });
184
375
  }
185
376
  /**
186
- * Creates a directory.
187
- * If one of the path's parent components doesn't exist
188
- * and the `recursive` option isn't set to true, the promise will be rejected.
377
+ * Reads and resolves to the entire contents of a file as an array of bytes.
378
+ * TextDecoder can be used to transform the bytes to string if required.
189
379
  * @example
190
380
  * ```typescript
191
- * import { createDir, BaseDirectory } from '@tauri-apps/plugin-fs';
192
- * // Create the `$APPDATA/users` directory
193
- * await createDir('users', { dir: BaseDirectory.AppData, recursive: true });
381
+ * import { readFile, BaseDirectory } from '@tauri-apps/plugin-fs';
382
+ * const contents = await readFile('avatar.png', { dir: BaseDirectory.Resource });
194
383
  * ```
195
384
  *
196
- * @returns A promise indicating the success or failure of the operation.
385
+ * @since 2.0.0
386
+ */
387
+ async function readFile(path, options) {
388
+ if (path instanceof URL && path.protocol !== "file:") {
389
+ throw new TypeError("Must be a file URL.");
390
+ }
391
+ const arr = await core.invoke("plugin:fs|read_file", {
392
+ path: path instanceof URL ? path.toString() : path,
393
+ options,
394
+ });
395
+ return Uint8Array.from(arr);
396
+ }
397
+ /**
398
+ * Reads and returns the entire contents of a file as UTF-8 string.
399
+ * @example
400
+ * ```typescript
401
+ * import { readTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
402
+ * const contents = await readTextFile('app.conf', { dir: BaseDirectory.App });
403
+ * ```
197
404
  *
198
405
  * @since 2.0.0
199
406
  */
200
- async function createDir(dir, options = {}) {
201
- return await primitives.invoke("plugin:fs|create_dir", {
202
- path: dir,
407
+ async function readTextFile(path, options) {
408
+ if (path instanceof URL && path.protocol !== "file:") {
409
+ throw new TypeError("Must be a file URL.");
410
+ }
411
+ return core.invoke("plugin:fs|read_text_file", {
412
+ path: path instanceof URL ? path.toString() : path,
203
413
  options,
204
414
  });
205
415
  }
206
416
  /**
207
- * Removes a directory.
208
- * If the directory is not empty and the `recursive` option isn't set to true, the promise will be rejected.
417
+ * Returns an async {@linkcode AsyncIterableIterator} over the lines of a file as UTF-8 string.
209
418
  * @example
210
419
  * ```typescript
211
- * import { removeDir, BaseDirectory } from '@tauri-apps/plugin-fs';
212
- * // Remove the directory `$APPDATA/users`
213
- * await removeDir('users', { dir: BaseDirectory.AppData });
420
+ * import { readTextFileLines, BaseDirectory } from '@tauri-apps/plugin-fs';
421
+ * const lines = await readTextFileLines('app.conf', { dir: BaseDirectory.App });
422
+ * for await (const line of lines) {
423
+ * console.log(line);
424
+ * }
214
425
  * ```
426
+ * You could also call {@linkcode AsyncIterableIterator.next} to advance the
427
+ * iterator so you can lazily read the next line whenever you want.
215
428
  *
216
- * @returns A promise indicating the success or failure of the operation.
429
+ * @since 2.0.0
430
+ */
431
+ async function readTextFileLines(path, options) {
432
+ if (path instanceof URL && path.protocol !== "file:") {
433
+ throw new TypeError("Must be a file URL.");
434
+ }
435
+ const pathStr = path instanceof URL ? path.toString() : path;
436
+ return Promise.resolve({
437
+ path: pathStr,
438
+ rid: null,
439
+ async next() {
440
+ if (!this.rid) {
441
+ this.rid = await core.invoke("plugin:fs|read_text_file_lines", {
442
+ path: pathStr,
443
+ options,
444
+ });
445
+ }
446
+ const [line, done] = await core.invoke("plugin:fs|read_text_file_lines_next", { rid: this.rid });
447
+ // an iteration is over, reset rid for next iteration
448
+ if (done)
449
+ this.rid = null;
450
+ return {
451
+ value: done ? "" : line,
452
+ done,
453
+ };
454
+ },
455
+ [Symbol.asyncIterator]() {
456
+ return this;
457
+ },
458
+ });
459
+ }
460
+ /**
461
+ * Removes the named file or directory.
462
+ * If the directory is not empty and the `recursive` option isn't set to true, the promise will be rejected.
463
+ * @example
464
+ * ```typescript
465
+ * import { remove, BaseDirectory } from '@tauri-apps/plugin-fs';
466
+ * await remove('users/file.txt', { dir: BaseDirectory.App });
467
+ * await remove('users', { dir: BaseDirectory.App });
468
+ * ```
217
469
  *
218
470
  * @since 2.0.0
219
471
  */
220
- async function removeDir(dir, options = {}) {
221
- return await primitives.invoke("plugin:fs|remove_dir", {
222
- path: dir,
472
+ async function remove(path, options) {
473
+ if (path instanceof URL && path.protocol !== "file:") {
474
+ throw new TypeError("Must be a file URL.");
475
+ }
476
+ return core.invoke("plugin:fs|remove", {
477
+ path: path instanceof URL ? path.toString() : path,
223
478
  options,
224
479
  });
225
480
  }
226
481
  /**
227
- * Copies a file to a destination.
482
+ * Renames (moves) oldpath to newpath. Paths may be files or directories.
483
+ * If newpath already exists and is not a directory, rename() replaces it.
484
+ * OS-specific restrictions may apply when oldpath and newpath are in different directories.
485
+ *
486
+ * On Unix, this operation does not follow symlinks at either path.
487
+ *
228
488
  * @example
229
489
  * ```typescript
230
- * import { copyFile, BaseDirectory } from '@tauri-apps/plugin-fs';
231
- * // Copy the `$APPCONFIG/app.conf` file to `$APPCONFIG/app.conf.bk`
232
- * await copyFile('app.conf', 'app.conf.bk', { dir: BaseDirectory.AppConfig });
490
+ * import { rename, BaseDirectory } from '@tauri-apps/plugin-fs';
491
+ * await rename('avatar.png', 'deleted.png', { dir: BaseDirectory.App });
233
492
  * ```
234
493
  *
235
- * @returns A promise indicating the success or failure of the operation.
236
- *
237
494
  * @since 2.0.0
238
495
  */
239
- async function copyFile(source, destination, options = {}) {
240
- return await primitives.invoke("plugin:fs|copy_file", {
241
- source,
242
- destination,
496
+ async function rename(oldPath, newPath, options) {
497
+ if ((oldPath instanceof URL && oldPath.protocol !== "file:") ||
498
+ (newPath instanceof URL && newPath.protocol !== "file:")) {
499
+ throw new TypeError("Must be a file URL.");
500
+ }
501
+ return core.invoke("plugin:fs|rename", {
502
+ oldPath: oldPath instanceof URL ? oldPath.toString() : oldPath,
503
+ newPath: newPath instanceof URL ? newPath.toString() : newPath,
243
504
  options,
244
505
  });
245
506
  }
246
507
  /**
247
- * Removes a file.
508
+ * Resolves to a {@linkcode FileInfo} for the specified `path`. Will always
509
+ * follow symlinks but will reject if the symlink points to a path outside of the scope.
510
+ *
248
511
  * @example
249
512
  * ```typescript
250
- * import { removeFile, BaseDirectory } from '@tauri-apps/plugin-fs';
251
- * // Remove the `$APPConfig/app.conf` file
252
- * await removeFile('app.conf', { dir: BaseDirectory.AppConfig });
513
+ * import { stat, BaseDirectory } from '@tauri-apps/plugin-fs';
514
+ * const fileInfo = await stat("hello.txt", { dir: BaseDirectory.App });
515
+ * console.log(fileInfo.isFile); // true
253
516
  * ```
254
517
  *
255
- * @returns A promise indicating the success or failure of the operation.
518
+ * @since 2.0.0
519
+ */
520
+ async function stat(path, options) {
521
+ const res = await core.invoke("plugin:fs|stat", {
522
+ path: path instanceof URL ? path.toString() : path,
523
+ options,
524
+ });
525
+ return parseFileInfo(res);
526
+ }
527
+ /**
528
+ * Resolves to a {@linkcode FileInfo} for the specified `path`. If `path` is a
529
+ * symlink, information for the symlink will be returned instead of what it
530
+ * points to.
531
+ *
532
+ * @example
533
+ * ```typescript
534
+ * import { lstat, BaseDirectory } from '@tauri-apps/plugin-fs';
535
+ * const fileInfo = await lstat("hello.txt", { dir: BaseDirectory.App });
536
+ * console.log(fileInfo.isFile); // true
537
+ * ```
256
538
  *
257
539
  * @since 2.0.0
258
540
  */
259
- async function removeFile(file, options = {}) {
260
- return await primitives.invoke("plugin:fs|remove_file", {
261
- path: file,
541
+ async function lstat(path, options) {
542
+ const res = await core.invoke("plugin:fs|lstat", {
543
+ path: path instanceof URL ? path.toString() : path,
262
544
  options,
263
545
  });
546
+ return parseFileInfo(res);
264
547
  }
265
548
  /**
266
- * Renames a file.
549
+ * Truncates or extends the specified file, to reach the specified `len`.
550
+ * If `len` is `0` or not specified, then the entire file contents are truncated.
551
+ *
267
552
  * @example
268
553
  * ```typescript
269
- * import { renameFile, BaseDirectory } from '@tauri-apps/plugin-fs';
270
- * // Rename the `$APPDATA/avatar.png` file
271
- * await renameFile('avatar.png', 'deleted.png', { dir: BaseDirectory.AppData });
554
+ * import { truncate, readFile, writeFile, BaseDirectory } from '@tauri-apps/plugin-fs';
555
+ * // truncate the entire file
556
+ * await truncate("my_file.txt", 0, { dir: BaseDirectory.App });
557
+ *
558
+ * // truncate part of the file
559
+ * let file = "file.txt";
560
+ * await writeFile(file, new TextEncoder().encode("Hello World"), { dir: BaseDirectory.App });
561
+ * await truncate(file, 7);
562
+ * const data = await readFile(file, { dir: BaseDirectory.App });
563
+ * console.log(new TextDecoder().decode(data)); // "Hello W"
272
564
  * ```
273
565
  *
274
- * @returns A promise indicating the success or failure of the operation.
566
+ * @since 2.0.0
567
+ */
568
+ async function truncate(path, len, options) {
569
+ if (path instanceof URL && path.protocol !== "file:") {
570
+ throw new TypeError("Must be a file URL.");
571
+ }
572
+ return core.invoke("plugin:fs|truncate", {
573
+ path: path instanceof URL ? path.toString() : path,
574
+ len,
575
+ options,
576
+ });
577
+ }
578
+ /**
579
+ * Write `data` to the given `path`, by default creating a new file if needed, else overwriting.
580
+ * @example
581
+ * ```typescript
582
+ * import { writeFile, BaseDirectory } from '@tauri-apps/plugin-fs';
583
+ *
584
+ * let encoder = new TextEncoder();
585
+ * let data = encoder.encode("Hello World");
586
+ * await writeFile('file.txt', data, { dir: BaseDirectory.App });
587
+ * ```
275
588
  *
276
589
  * @since 2.0.0
277
590
  */
278
- async function renameFile(oldPath, newPath, options = {}) {
279
- return await primitives.invoke("plugin:fs|rename_file", {
280
- oldPath,
281
- newPath,
591
+ async function writeFile(path, data, options) {
592
+ if (path instanceof URL && path.protocol !== "file:") {
593
+ throw new TypeError("Must be a file URL.");
594
+ }
595
+ return core.invoke("plugin:fs|write_file", {
596
+ path: path instanceof URL ? path.toString() : path,
597
+ data: Array.from(data),
598
+ options,
599
+ });
600
+ }
601
+ /**
602
+ * Writes UTF-8 string `data` to the given `path`, by default creating a new file if needed, else overwriting.
603
+ @example
604
+ * ```typescript
605
+ * import { writeTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
606
+ *
607
+ * await writeTextFile('file.txt', "Hello world", { dir: BaseDirectory.App });
608
+ * ```
609
+ *
610
+ * @since 2.0.0
611
+ */
612
+ async function writeTextFile(path, data, options) {
613
+ if (path instanceof URL && path.protocol !== "file:") {
614
+ throw new TypeError("Must be a file URL.");
615
+ }
616
+ return core.invoke("plugin:fs|write_text_file", {
617
+ path: path instanceof URL ? path.toString() : path,
618
+ data,
282
619
  options,
283
620
  });
284
621
  }
@@ -293,46 +630,95 @@ async function renameFile(oldPath, newPath, options = {}) {
293
630
  *
294
631
  * @since 2.0.0
295
632
  */
296
- async function exists(path, options = {}) {
297
- return await primitives.invoke("plugin:fs|exists", { path, options });
633
+ async function exists(path, options) {
634
+ if (path instanceof URL && path.protocol !== "file:") {
635
+ throw new TypeError("Must be a file URL.");
636
+ }
637
+ return core.invoke("plugin:fs|exists", {
638
+ path: path instanceof URL ? path.toString() : path,
639
+ options,
640
+ });
641
+ }
642
+ async function unwatch(id) {
643
+ await core.invoke("plugin:fs|unwatch", { id });
644
+ }
645
+ /**
646
+ * Watch changes (after a delay) on files or directories.
647
+ *
648
+ * @since 2.0.0
649
+ */
650
+ async function watch(paths, cb, options) {
651
+ const opts = {
652
+ recursive: false,
653
+ delayMs: 2000,
654
+ ...options,
655
+ };
656
+ const watchPaths = Array.isArray(paths) ? paths : [paths];
657
+ for (const path of watchPaths) {
658
+ if (path instanceof URL && path.protocol !== "file:") {
659
+ throw new TypeError("Must be a file URL.");
660
+ }
661
+ }
662
+ const onEvent = new core.Channel();
663
+ onEvent.onmessage = cb;
664
+ const rid = await core.invoke("plugin:fs|watch", {
665
+ paths: watchPaths.map((p) => (p instanceof URL ? p.toString() : p)),
666
+ options: opts,
667
+ onEvent,
668
+ });
669
+ return () => {
670
+ void unwatch(rid);
671
+ };
298
672
  }
299
673
  /**
300
- * Returns the metadata for the given path.
674
+ * Watch changes on files or directories.
301
675
  *
302
676
  * @since 2.0.0
303
677
  */
304
- async function metadata(path) {
305
- return await primitives.invoke("plugin:fs|metadata", {
306
- path,
307
- }).then((metadata) => {
308
- const { accessedAtMs, createdAtMs, modifiedAtMs, ...data } = metadata;
309
- return {
310
- accessedAt: new Date(accessedAtMs),
311
- createdAt: new Date(createdAtMs),
312
- modifiedAt: new Date(modifiedAtMs),
313
- ...data,
314
- };
678
+ async function watchImmediate(paths, cb, options) {
679
+ const opts = {
680
+ recursive: false,
681
+ ...options,
682
+ delayMs: null,
683
+ };
684
+ const watchPaths = Array.isArray(paths) ? paths : [paths];
685
+ for (const path of watchPaths) {
686
+ if (path instanceof URL && path.protocol !== "file:") {
687
+ throw new TypeError("Must be a file URL.");
688
+ }
689
+ }
690
+ const onEvent = new core.Channel();
691
+ onEvent.onmessage = cb;
692
+ const rid = await core.invoke("plugin:fs|watch", {
693
+ paths: watchPaths.map((p) => (p instanceof URL ? p.toString() : p)),
694
+ options: opts,
695
+ onEvent,
315
696
  });
697
+ return () => {
698
+ void unwatch(rid);
699
+ };
316
700
  }
317
701
 
318
702
  Object.defineProperty(exports, 'BaseDirectory', {
319
- enumerable: true,
320
- get: function () { return path.BaseDirectory; }
321
- });
322
- Object.defineProperty(exports, 'Dir', {
323
- enumerable: true,
324
- get: function () { return path.BaseDirectory; }
703
+ enumerable: true,
704
+ get: function () { return path.BaseDirectory; }
325
705
  });
706
+ exports.FileHandle = FileHandle;
326
707
  exports.copyFile = copyFile;
327
- exports.createDir = createDir;
708
+ exports.create = create;
328
709
  exports.exists = exists;
329
- exports.metadata = metadata;
330
- exports.readBinaryFile = readBinaryFile;
710
+ exports.lstat = lstat;
711
+ exports.mkdir = mkdir;
712
+ exports.open = open;
331
713
  exports.readDir = readDir;
714
+ exports.readFile = readFile;
332
715
  exports.readTextFile = readTextFile;
333
- exports.removeDir = removeDir;
334
- exports.removeFile = removeFile;
335
- exports.renameFile = renameFile;
336
- exports.writeBinaryFile = writeBinaryFile;
337
- exports.writeFile = writeTextFile;
716
+ exports.readTextFileLines = readTextFileLines;
717
+ exports.remove = remove;
718
+ exports.rename = rename;
719
+ exports.stat = stat;
720
+ exports.truncate = truncate;
721
+ exports.watch = watch;
722
+ exports.watchImmediate = watchImmediate;
723
+ exports.writeFile = writeFile;
338
724
  exports.writeTextFile = writeTextFile;