@agoric/pola-io 0.1.1-dev-fab25c1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,111 @@
1
+ # @agoric/pola-io
2
+
3
+ A least-authority I/O library for JavaScript.
4
+
5
+ ## Getting Started
6
+
7
+ ```
8
+ npm install @agoric/pola-io
9
+ ```
10
+
11
+ **WIP WIP WIP - EXAMPLES BELOW ARE BROKEN**
12
+
13
+ ### Example: `agoric run` as `npx` subcommand
14
+
15
+ ```js
16
+ import { makeCmdRunner } from '@agoric/pola-io';
17
+ import { execFile as execFileNode } from 'node:child_process';
18
+ import { promisify } from 'node:util';
19
+
20
+ export const main = async ({ execFile = promisify(execFileNode) }) => {
21
+ const npx = makeCmdRunner('npx', { execFile }); // TODO --no-install
22
+ return miscTask(npx);
23
+ };
24
+
25
+ const miscTask = async npx => {
26
+ const agoric = npx.subCommand('agoric');
27
+ const { stdout } = await agoric.subCommand('run').exec(['builder.js']);
28
+ return stdout.split('\n');
29
+ };
30
+ ```
31
+
32
+ ### Example: Read-Only File Wrapper
33
+
34
+ ```js
35
+ import { makeFileRW } from '@agoric/pola-io';
36
+ import * as fsp from 'node:fs/promises';
37
+
38
+ const file = makeFileRW('/', { fsp });
39
+ const readonly = file.readOnly();
40
+ await readonly.readText(); // Allowed
41
+ // @ts-expect-error static error
42
+ await readonly.writeText();
43
+ ```
44
+
45
+ ## What This Package Offers
46
+
47
+ The `@agoric/pola-io` package facilitates using the [Principle of Least Authority (POLA)](https://capnproto.org/capabilities.html#least-authority) for I/O, applying object-capability (ocap) principles to common file, network, and shell operations:
48
+
49
+ - **Scoped Authority**: Interfaces are built to represent the smallest usable unit of authority—e.g., read-only file handles, command runners with fixed executable paths, or network dialers scoped to specific hosts.
50
+ - **Composable Wrappers**: Inspired by Stiegler's PictureBook of Secure Cooperation, components like revocable forwarders, logging wrappers, and facets are encouraged as default patterns.
51
+ - **Minimize Ambient Authority**: Core interfaces require explicit authority objects. Convenience layers (e.g., `ambient/cmd.js`) exist, but are clearly labeled and should be used with care.
52
+
53
+ ## Background
54
+
55
+ ### Why Minimal Trust Enables Maximal Cooperation
56
+
57
+ Traditional I/O libraries often assume broad access: open any file, connect to any host, run any command. But this creates fragile systems—where one misused reference or library can do serious harm.
58
+
59
+ `@agoric/pola-io` takes a different approach. Every I/O action starts from a **scoped authority**—an object that grants only a narrow, intended power. For example, a command runner that can execute *only* a given binary, or a file handle that supports *only* reading.
60
+
61
+ By making these boundaries explicit, we reduce how much code needs to be trusted—while still making it easy to delegate, revoke, and wrap access. This is what lets us cooperate safely: code can use what it’s been given, but nothing more.
62
+
63
+ ## Related Work
64
+
65
+ This package builds on a long tradition of work in object-capability security and least-authority design:
66
+
67
+ - 2023: [**cap-std**](https://crates.io/crates/cap-std) — A Rust library for capability-based I/O that eliminates ambient authority from `std`, providing a least-authority alternative to conventional file and network APIs.
68
+ - 2021: [**Genode's VFS**](https://genodians.org/m-stein/2021-06-21-vfs-1) — Constructs a process's file namespace from explicitly delegated capabilities: "a component can’t just open an arbitrary file. It can only use what the system integrator explicitly handed to it."
69
+ - 2013: [**Distributed Electronic Rights in JavaScript**](https://papers.agoric.com/papers/distributed-electronic-rights-in-javascript/abstract/) — Shows how object-capability techniques in JavaScript support POLA not just for local I/O, but also across distributed systems. Introduces SES (Secure EcmaScript), eventual messaging (!), and authority-constraining wrappers as practical tools for secure cooperation.
70
+ - 2006: [**Emily**](http://www.hpl.hp.com/techreports/2006/HPL-2006-116.html) — A POLA-enforcing subset of OCaml, which uses a verifier to constrain authority and introduces `readable` and `editable` file interfaces that map closely to our approach:
71
+ ```ocaml
72
+ type readable = {
73
+ isDir : unit -> bool;
74
+ exists : unit -> bool;
75
+ subRdFiles : unit -> readable list;
76
+ subRdFile : string -> readable;
77
+ inChannel : unit -> in_channel;
78
+ getBytes : unit -> string;
79
+ fullPath : unit -> string;
80
+ }
81
+ type editable = {
82
+ ro : readable;
83
+ subEdFiles : unit -> editable list;
84
+ subEdFile : string -> editable;
85
+ outChannel : unit -> out_channel;
86
+ setBytes : string -> unit;
87
+ mkDir : unit -> unit;
88
+ createNewFile : unit -> unit;
89
+ delete : unit -> unit;
90
+ }
91
+ ```
92
+ - 2002: [**DarpaBrowser Report**](http://www.combex.com/papers/darpa-report/html/index.html) — Critiques the ambient authority embedded in interfaces like Java's `java.io.File`.
93
+ - 2004: [**A PictureBook of Secure Cooperation**](http://erights.org/talks/efun/SecurityPictureBook.pdf) — A visual introduction to object-capability patterns like revocable forwarders, facets, and sealers, showing how authority can be safely delegated and composed.
94
+
95
+ These systems share the goal of enabling secure cooperation through modular, delegatable authority. `@agoric/pola-io` brings these patterns to JavaScript I/O.
96
+
97
+
98
+
99
+ ## Philosophy: Secure Cooperation
100
+
101
+ Just like the PictureBook describes, this package is about **delegating only what is necessary**, and composing secure patterns like revocation, logging, and least authority by default. Think:
102
+
103
+ - Giving a friend temporary read access to a file.
104
+ - Running a single binary with a fixed command.
105
+ - Logging access without breaking encapsulation.
106
+
107
+ Applying these techniques uniformly leads to systems where cooperation is safer, authority is easier to reason about, and trust boundaries are clear.
108
+
109
+ ## Contributing
110
+
111
+ Please do! See [CONTRIBUTING](./CONTRIBUTING.md).
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@agoric/pola-io",
3
+ "version": "0.1.1-dev-fab25c1.0+fab25c1",
4
+ "description": "Least Authority I/O utilities",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./src/types.ts",
8
+ "scripts": {
9
+ "build": "exit 0",
10
+ "test": "ava",
11
+ "test:xs": "exit 0",
12
+ "lint": "yarn run -T run-s --continue-on-error 'lint:*'",
13
+ "lint:eslint": "eslint .",
14
+ "lint:types": "yarn run -T tsc",
15
+ "lint-fix": "eslint --fix ."
16
+ },
17
+ "devDependencies": {
18
+ "ava": "^5.3.0"
19
+ },
20
+ "files": [
21
+ "src/"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "eslintConfig": {
27
+ "extends": [
28
+ "@agoric"
29
+ ]
30
+ },
31
+ "ava": {
32
+ "files": [
33
+ "test/**/*.test.*"
34
+ ],
35
+ "timeout": "2m"
36
+ },
37
+ "typeCoverage": {
38
+ "atLeast": 80
39
+ },
40
+ "gitHead": "fab25c1d7df5590379b9d71d12d4b72500652932"
41
+ }
@@ -0,0 +1,21 @@
1
+ import { execFile as execFileAmbient } from 'child_process';
2
+ import { promisify } from 'node:util';
3
+ import * as cmd from '../cmd.js';
4
+
5
+ /**
6
+ * Access to run a command with flags appended.
7
+ *
8
+ * @example
9
+ * const lsPlain = makeCmdRunner('ls', { execFile });
10
+ * const ls = ls.withFlags('-F')
11
+ * await ls.exec('/tmp') // runs: ls /tmp -F
12
+ *
13
+ * TODO? .withPath('/opt') or .withEnv({PATH: `${env.PATH}:/opt`})
14
+ *
15
+ * @param {string} file
16
+ * @param {{ execFile: any }} io
17
+ */
18
+ export const makeCmdRunner = (
19
+ file,
20
+ { execFile = promisify(execFileAmbient) },
21
+ ) => cmd.makeCmdRunner(file, { execFile });
package/src/ambient.js ADDED
@@ -0,0 +1 @@
1
+ export * from './ambient/cmd.js';
package/src/cmd.js ADDED
@@ -0,0 +1,65 @@
1
+ // freeze() rather than harden() to stay with ZERO dependencies.
2
+ // expected to be compatible with HardenedJS / ses.
3
+ // XXX what hazards does this expose us to?
4
+ const { freeze } = Object;
5
+
6
+ /**
7
+ * Access to run a command with flags appended.
8
+ *
9
+ * @example
10
+ * const execP = promisify(childProcess.execFile);
11
+ * const lsPlain = makeCmdRunner('ls', { execFile: execP });
12
+ * const ls = ls.withFlags('-F')
13
+ * await ls.exec('/tmp') // runs: ls /tmp -F
14
+ *
15
+ * TODO? .withPath('/opt') or .withEnv({PATH: `${env.PATH}:/opt`})
16
+ *
17
+ * XXX use a different name from execFile since the meaning is different
18
+ * @param {string} file
19
+ * @param {{ execFile: any }} io XXX expects promisify
20
+ */
21
+ export const makeCmdRunner = (file, { execFile }) => {
22
+ /** @param {{ preArgs?: string[], postArgs?: string[] }} [opts] */
23
+ const make = ({ preArgs = [], postArgs = [] } = {}) => {
24
+ return freeze({
25
+ /**
26
+ * @param {string[]} args
27
+ * @param {*} [opts]
28
+ */
29
+ exec: (
30
+ args,
31
+ opts = { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] },
32
+ ) => execFile(file, [...preArgs, ...args, ...postArgs], opts),
33
+ /**
34
+ * @param {string} name
35
+ @param {string[]} [opts] */
36
+ subCommand: (name, opts = []) =>
37
+ make({ preArgs: [...preArgs, name, ...opts], postArgs }),
38
+ /** @param {string[]} tailFlags */
39
+ withFlags: (...tailFlags) =>
40
+ make({ preArgs, postArgs: [...postArgs, ...tailFlags] }),
41
+ });
42
+ };
43
+ return make();
44
+ };
45
+ freeze(makeCmdRunner);
46
+ /** @typedef {ReturnType<makeCmdRunner>} CmdRunner */
47
+
48
+ /**
49
+ * @param {Record<string, string | string[] | undefined>} record - e.g. { color: 'blue' }
50
+ * @returns {string[]} - e.g. ['--color', 'blue']
51
+ */
52
+ export const flags = record => {
53
+ // TODO? support --yes with boolean?
54
+
55
+ /** @type {[string, string][]} */
56
+ // @ts-expect-error undefined is filtered out
57
+ const skipUndef = Object.entries(record).filter(([_k, v]) => v !== undefined);
58
+ return skipUndef.flatMap(([key, value]) => {
59
+ if (Array.isArray(value)) {
60
+ return value.flatMap(v => [`--${key}`, v]);
61
+ }
62
+ return [`--${key}`, value];
63
+ });
64
+ };
65
+ freeze(flags);
package/src/file.js ADDED
@@ -0,0 +1,118 @@
1
+ // @ts-check
2
+
3
+ const { freeze } = Object;
4
+
5
+ // XXX: what hazards may not using endo assert.fail expose us to?
6
+ export const fail = reason => {
7
+ throw Error(reason);
8
+ };
9
+ freeze(fail);
10
+
11
+ /**
12
+ * Dynamic access
13
+ *
14
+ * @template {Record<string, any>} T
15
+ * @param {Partial<T>} io
16
+ * @returns {T}
17
+ */
18
+ const dyn = io => {
19
+ const it = new Proxy(io, {
20
+ get(_t, p) {
21
+ if (!(p in io)) {
22
+ return () => fail(`no access to ${String(p)}`);
23
+ }
24
+ // @ts-expect-error tsc doesn't refine per p in o
25
+ return io[p];
26
+ },
27
+ });
28
+ return /** @type {T} */ (it);
29
+ };
30
+
31
+ /**
32
+ * @template [T=any]
33
+ * @typedef {{
34
+ * join(...segments: string[]): T;
35
+ * toString: () => string;
36
+ * basename: () => string;
37
+ * relative(to: string): string;
38
+ * }} PathNode
39
+ *
40
+ * XXX how to test / assert / declare that FileRd and FileWR extend PathNode?
41
+ * interfaces?
42
+ */
43
+
44
+ /**
45
+ * @typedef {ReturnType<typeof makeFileRd>} FileRd
46
+ */
47
+
48
+ /**
49
+ * Reify file read access as an object.
50
+ *
51
+ * @param {string} root
52
+ * @param {object} [io]
53
+ * @param {Partial<typeof import('fs')>} [io.fs]
54
+ * @param {Partial<typeof import('fs/promises')>} [io.fsp]
55
+ * @param {Partial<typeof import('path')>} [io.path]
56
+ */
57
+ export const makeFileRd = (root, { fs = {}, fsp = {}, path = {} } = {}) => {
58
+ const [fsio, fspio, pathio] = [dyn(fs), dyn(fsp), dyn(path)];
59
+
60
+ /** @param {string} there */
61
+ const make = there => {
62
+ const self = {
63
+ toString: () => there,
64
+ /** @param {string[]} segments */
65
+ join: (...segments) => make(pathio.join(there, ...segments)),
66
+ /** @param {string} to */
67
+ relative: to => pathio.relative(there, to),
68
+ stat: () => fspio.stat(there),
69
+ readText: () => fspio.readFile(there, 'utf8'),
70
+ readJSON: () => self.readText().then(txt => JSON.parse(txt)),
71
+ /** @param {string} [suffix] */
72
+ basename: suffix => pathio.basename(there, suffix),
73
+ existsSync: () => fsio.existsSync(there),
74
+ /** @returns {Promise<FileRd[]>} */
75
+ readdir: () =>
76
+ fspio
77
+ .readdir(there)
78
+ .then(files => files.map(segment => self.join(segment))),
79
+ };
80
+ return freeze(self);
81
+ };
82
+ return make(root);
83
+ };
84
+ freeze(makeFileRd);
85
+
86
+ /**
87
+ * Reify file read/write access as an object.
88
+ *
89
+ * @param {string} root
90
+ * @param {object} [io]
91
+ * @param {Partial<typeof import('fs')>} [io.fs]
92
+ * @param {Partial<typeof import('fs/promises')>} [io.fsp]
93
+ * @param {Partial<typeof import('path')>} [io.path]
94
+ *
95
+ * @typedef {ReturnType<typeof makeFileRW>} FileRW
96
+ */
97
+ export const makeFileRW = (root, { fs = {}, fsp = {}, path = {} } = {}) => {
98
+ // XXX share dyn with makeFileRd?
99
+ const [fspio, pathio] = [dyn(fsp), dyn(path)];
100
+
101
+ /** @param {string} there */
102
+ const make = there => {
103
+ const ro = makeFileRd(there, { fs, fsp, path });
104
+ const self = {
105
+ toString: () => there,
106
+ readOnly: () => ro,
107
+ /** @param {string[]} segments */
108
+ join: (...segments) => make(pathio.join(there, ...segments)),
109
+ writeText: text => fspio.writeFile(there, text, 'utf8'),
110
+ unlink: () => fspio.unlink(there),
111
+ mkdir: () => fspio.mkdir(there, { recursive: true }),
112
+ rmdir: () => fspio.rmdir(there),
113
+ };
114
+ return freeze(self);
115
+ };
116
+ return make(root);
117
+ };
118
+ freeze(makeFileRW);
package/src/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './file.js';
2
+ export * from './cmd.js';
3
+ export * from './net.js';
package/src/net.js ADDED
@@ -0,0 +1,119 @@
1
+ // @ts-check
2
+
3
+ const { freeze } = Object;
4
+
5
+ /**
6
+ * @import {PathNode, FileRd, FileRW} from './file';
7
+ *
8
+ * XXX TODO: basename, relative
9
+ * @typedef {Omit<PathNode, 'basename' | 'relative'> & Pick<FileRd, 'readText' | 'readJSON'>} TextRd
10
+ */
11
+
12
+ const dbg = label => x => {
13
+ label;
14
+ // console.log(label, x);
15
+ return x;
16
+ };
17
+
18
+ /**
19
+ *
20
+ * @param {string} root
21
+ * @param {object} io
22
+ * @param {typeof fetch} io.fetch
23
+ * @param {(...msgs: any[]) => void} [io.log]
24
+ * @returns {TextRd}
25
+ */
26
+ export const makeWebRd = (root, { fetch, log = console.log }) => {
27
+ /** @param {string} there */
28
+ const make = there => {
29
+ /** @param {string[]} segments */
30
+ const join = (...segments) => {
31
+ dbg('web.join')({ there, segments });
32
+ let out = there;
33
+ for (const segment of segments) {
34
+ out = `${new URL(segment, out)}`;
35
+ }
36
+ return out;
37
+ };
38
+
39
+ const checkedFetch = async () => {
40
+ log('WebRd fetch:', there);
41
+ const res = await fetch(there);
42
+ if (!res.ok) {
43
+ throw Error(`${res.statusText} @ ${there}`);
44
+ }
45
+ return res;
46
+ };
47
+ /** @type {TextRd} */
48
+ const self = {
49
+ toString: () => there,
50
+ /** @param {string[]} segments */
51
+ join: (...segments) => make(join(...segments)),
52
+ readText: () => checkedFetch().then(res => res.text()),
53
+ readJSON: () => checkedFetch().then(res => res.json()),
54
+ };
55
+ return freeze(self);
56
+ };
57
+ return make(root);
58
+ };
59
+ freeze(makeWebRd);
60
+
61
+ /**
62
+ * @param {TextRd} src
63
+ * @param {FileRW} dest
64
+ *
65
+ * @typedef {ReturnType<typeof makeWebCache>} WebCache
66
+ */
67
+ export const makeWebCache = (src, dest) => {
68
+ /** @type {Map<string, Promise<FileRd>>} */
69
+ const saved = new Map();
70
+
71
+ /** @param {string} segment */
72
+ const getFileP = segment => {
73
+ const target = src.join(segment);
74
+ const addr = `${target}`;
75
+ const cached = saved.get(addr);
76
+ if (cached) return cached;
77
+
78
+ const f = dest.join(segment);
79
+ /** @type {Promise<FileRd>} */
80
+ const p = new Promise((resolve, reject) =>
81
+ target
82
+ .readText()
83
+ .then(txt =>
84
+ dest
85
+ .mkdir()
86
+ .then(() => f.writeText(txt).then(_ => resolve(f.readOnly()))),
87
+ )
88
+ .catch(reject),
89
+ );
90
+ saved.set(addr, p);
91
+ return p;
92
+ };
93
+
94
+ const remove = async () => {
95
+ throw Error('TODO');
96
+ // await Promise.all([...saved.values()].map(p => p.then(f => f.unlink())));
97
+ // await dest.rmdir();
98
+ };
99
+
100
+ const self = {
101
+ toString: () => `${src} -> ${dest}`,
102
+ /** @param {string} segment */
103
+ getText: async segment => {
104
+ const fr = await getFileP(segment);
105
+ return fr.readText();
106
+ },
107
+ /** @param {string} segment */
108
+ storedPath: segment => getFileP(segment).then(f => f.toString()),
109
+ /** @param {string} segment */
110
+ size: async segment => {
111
+ const fr = await getFileP(segment);
112
+ const info = await fr.stat();
113
+ return info.size;
114
+ },
115
+ remove,
116
+ };
117
+ return freeze(self);
118
+ };
119
+ freeze(makeWebCache);