pear-install 0.0.0 → 1.0.2

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/.gitattributes ADDED
@@ -0,0 +1 @@
1
+ * text=auto eol=lf
@@ -0,0 +1,17 @@
1
+ name: Publish
2
+ on:
3
+ push:
4
+ tags:
5
+ - v*
6
+ permissions:
7
+ id-token: write
8
+ contents: write
9
+ jobs:
10
+ publish:
11
+ runs-on: ubuntu-latest
12
+ environment:
13
+ name: npm
14
+ name: Publish
15
+ steps:
16
+ - uses: holepunchto/actions/node-base@v1
17
+ - uses: holepunchto/actions/publish@v1
@@ -0,0 +1,32 @@
1
+ name: Test
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ lint:
11
+ runs-on: ubuntu-latest
12
+ name: Lint
13
+ steps:
14
+ - uses: holepunchto/actions/node-base@v1
15
+ - run: npm run lint
16
+
17
+ test:
18
+ strategy:
19
+ matrix:
20
+ include:
21
+ - os: ubuntu-latest
22
+ platform: linux
23
+ - os: macos-latest
24
+ platform: darwin
25
+ - os: windows-latest
26
+ platform: win32
27
+ runs-on: ${{ matrix.os }}
28
+ name: Test / ${{ matrix.platform }}
29
+ timeout-minutes: 2
30
+ steps:
31
+ - uses: holepunchto/actions/bare-base@v1
32
+ - run: npm test
@@ -0,0 +1 @@
1
+ template/appling/package.json
package/.prettierrc ADDED
@@ -0,0 +1 @@
1
+ "prettier-config-holepunch"
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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.
202
+
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2026 Holepunch Inc
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # pear-install
2
+
3
+ > Install Pear and Pear Applications
4
+
5
+ # CLI
6
+
7
+ ```sh
8
+ npx pear-install [link]
9
+ ```
10
+
11
+ Install `pear` binary onto system, if a link is supplied, installs any Pear application or binary onto system.
12
+
13
+ ## License
14
+
15
+ Apache-2.0
package/cmd.js ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ const pkg = require('./package.json')
3
+ const { isWindows } = require('which-runtime')
4
+ const { command, arg, bail } = require('paparam')
5
+ const install = require('.')
6
+
7
+ const program = command(
8
+ 'install',
9
+ arg('[link]', 'Pear link origin to install from'),
10
+ async (cmd) => {
11
+ if (!cmd.args.link) cmd.args.link = pkg.pear.platform.key
12
+ await install(cmd)
13
+ },
14
+ pkg.command,
15
+ bail((info = {}) => {
16
+ process.exitCode = 1
17
+ let message
18
+ if (info.reason === 'UNKNOWN_FLAG') message = 'Unrecognized Flag: --' + info.flag.name
19
+ else if (info.reason === 'UNKNOWN_ARG') {
20
+ message = `Unrecognized Argument at index ${info.arg.index} with value ${info.arg.value}`
21
+ } else message = info.err?.message ?? 'Failed'
22
+ const cross = isWindows ? 'x' : '\x1B[31m✖\x1B[39m'
23
+ console.error(cross, message)
24
+ if (info.reason === 'UNKNOWN_FLAG' || info.reason === 'UNKNOWN_ARG') {
25
+ console.error('\n' + info.command.usage())
26
+ }
27
+ })
28
+ )
29
+
30
+ program.parse(process.argv.slice(2))
package/index.js ADDED
@@ -0,0 +1,343 @@
1
+ 'use strict'
2
+ const path = require('path')
3
+ const os = require('os')
4
+ const fs = require('fs')
5
+ const { spawnSync } = require('child_process')
6
+ const process = require('process')
7
+ const LocalDrive = require('localdrive')
8
+ const { isMac, isLinux, isWindows } = require('which-runtime')
9
+ const crypto = require('hypercore-crypto')
10
+ const Corestore = require('corestore')
11
+ const Hyperdrive = require('hyperdrive')
12
+ const Hyperswarm = require('hyperswarm')
13
+ const plink = require('pear-link')
14
+ const Opstream = require('pear-opstream')
15
+ const PearError = require('pear-errors')
16
+ const byteSize = require('tiny-byte-size')
17
+ const { ERR_INVALID_MANIFEST, ERR_NOT_FOUND, ERR_PERMISSION_REQUIRED, ERR_UNKNOWN } = PearError
18
+
19
+ function ERR_NETWORK_TIMEOUT(msg, info = null) {
20
+ return new PearError(msg, ERR_NETWORK_TIMEOUT, info)
21
+ }
22
+
23
+ function ERR_EXISTS(msg, info = null) {
24
+ return new PearError(msg, ERR_EXISTS, info)
25
+ }
26
+
27
+ const PEAR_DIR = isMac
28
+ ? path.join(os.homedir(), 'Library', 'Application Support', 'pear')
29
+ : isLinux
30
+ ? path.join(os.homedir(), '.config', 'pear')
31
+ : path.join(os.homedir(), 'AppData', 'Roaming', 'pear')
32
+
33
+ class Install extends Opstream {
34
+ static outputs = {
35
+ installing: ({ link }) => `Installing... ${link}`,
36
+ app: ({ app, version, upgrade, dest, key }) =>
37
+ `App: ${app}\nVersion: ${version}\nLink: ${upgrade}\nPathname: ${key}\nTarget: ${dest}`,
38
+ stats({ upload, download, peers }) {
39
+ const dl =
40
+ download.bytes + download.speed === 0
41
+ ? ''
42
+ : `[ down ${byteSize(download.bytes)} - ${byteSize(download.speed)}/s ] `
43
+ const ul =
44
+ upload.bytes + upload.speed === 0
45
+ ? ''
46
+ : `[ up ${byteSize(upload.bytes)} - ${byteSize(upload.speed)}/s ] `
47
+ return `[ Peers: ${peers} ] ${dl}${ul}`
48
+ },
49
+ error: ({ message }) => message,
50
+ final({ success, message }) {
51
+ if (success) return 'Installed'
52
+ return message ?? 'Failed'
53
+ }
54
+ }
55
+
56
+ constructor(params) {
57
+ super((...args) => this.#op(...args), params)
58
+ this.targets = []
59
+ }
60
+
61
+ async #op({ link, only, to, bootstrap, timeout = 30_000 }) {
62
+ const parsed = plink.parse(link)
63
+ if (parsed.pathname) throw new Error('Link must not have pathname')
64
+ const host = process.platform + '-' + process.arch
65
+ this.push({ tag: 'installing', data: { link, host } })
66
+
67
+ const rand = crypto.randomBytes(16).toString('hex')
68
+ const base = path.join(PEAR_DIR, 'gc', rand)
69
+ fs.mkdirSync(base, { recursive: true })
70
+
71
+ const corestore = new Corestore(base)
72
+ const drive = new Hyperdrive(corestore, parsed.drive.key)
73
+ const swarm = new Hyperswarm({ bootstrap })
74
+
75
+ let findingDone = null
76
+ try {
77
+ await drive.ready()
78
+ findingDone = drive.findingPeers()
79
+ const topic = swarm.join(drive.discoveryKey, { server: false, client: true })
80
+ swarm.on('connection', (c) => corestore.replicate(c))
81
+
82
+ let serving = false
83
+ swarm.dht.on('nat-update', () => {
84
+ if (!swarm.dht.randomized && !serving) {
85
+ serving = true
86
+ swarm
87
+ .join(drive.discoveryKey, { server: true, client: false })
88
+ .flushed()
89
+ .then(() => topic.destroy())
90
+ }
91
+ })
92
+ const deferred = Promise.withResolvers()
93
+ const countdown = setTimeout(() => {
94
+ deferred.reject(ERR_NETWORK_TIMEOUT('Network Timeout ' + timeout / 1000 + 's'))
95
+ }, timeout)
96
+ await Promise.race([drive.core.update({ wait: true }), deferred.promise])
97
+ clearTimeout(countdown)
98
+ const pkg = await drive.get('/package.json')
99
+ if (pkg === null) throw ERR_INVALID_MANIFEST('Unable to read application package.json')
100
+ const manifest = JSON.parse(pkg.toString())
101
+
102
+ const { name, productName, version, upgrade, bin } = manifest
103
+ const appName = productName ?? name
104
+ const home = os.homedir()
105
+
106
+ if (bin) {
107
+ const bins = typeof bin === 'string' ? { [name]: bin } : bin
108
+ for (const binName of Object.keys(bins)) {
109
+ const ext = isWindows ? '.msix' : ''
110
+ const dest = isWindows
111
+ ? null
112
+ : to
113
+ ? path.join(to, binName + ext)
114
+ : isMac
115
+ ? path.join('/', 'usr', 'local', 'bin', binName)
116
+ : path.join(home, '.local', 'bin', binName)
117
+ this.targets.push({ filename: binName, ext, dest, isBin: true })
118
+ }
119
+ }
120
+
121
+ const ext = isMac ? '.app' : isWindows ? '.msix' : '.AppImage'
122
+ const dest = isWindows
123
+ ? null
124
+ : to
125
+ ? path.join(to, appName + ext)
126
+ : isMac
127
+ ? path.join('/', 'Applications', appName + ext)
128
+ : fs.existsSync(path.join(home, 'Applications'))
129
+ ? path.join(home, 'Applications', appName + ext)
130
+ : fs.existsSync(path.join(home, 'AppImages'))
131
+ ? path.join(home, 'AppImages', appName + ext)
132
+ : path.join(home, '.local', 'bin', appName + ext)
133
+
134
+ this.targets.push({ filename: appName, ext, dest, isBin: false })
135
+
136
+ const present = new Set()
137
+ const appPath = '/by-arch/' + host + '/app/'
138
+ for await (const name of drive.readdir(appPath)) present.add(name)
139
+
140
+ const required = only
141
+ ? only
142
+ .split(',')
143
+ .map((s) => s.trim())
144
+ .filter(Boolean)
145
+ : this.targets.filter((t) => t.isBin || !bin).map((t) => t.filename + t.ext)
146
+ const missing = required
147
+ .filter((r) => !present.has(r))
148
+ .map((name) => plink.serialize({ ...parsed, pathname: appPath + name }))
149
+ if (missing.length) {
150
+ throw ERR_NOT_FOUND('Not found: ' + missing.join(', '))
151
+ }
152
+
153
+ this.targets = this.targets.filter(({ filename, ext }) => present.has(filename + ext))
154
+
155
+ const exists = []
156
+ const installs = []
157
+ for (const target of this.targets) {
158
+ if (isWindows) {
159
+ const ps = spawnSync('powershell', [
160
+ '-NoProfile',
161
+ '-Command',
162
+ `(Get-AppxPackage '${target.filename}') -ne $null`
163
+ ])
164
+ if (ps.stdout.toString().trim() === 'True') {
165
+ exists.push({ filename: target.filename, dest: target.dest })
166
+ continue
167
+ }
168
+ } else if (fs.existsSync(target.dest)) {
169
+ exists.push({ filename: target.filename, dest: target.dest })
170
+ continue
171
+ }
172
+ installs.push(target)
173
+ }
174
+
175
+ if (installs.length === 0) {
176
+ const message = isWindows
177
+ ? `Already installed:\n${exists.map(({ filename }) => ' ' + filename).join('\n')}\n Manually uninstall first to reinstall`
178
+ : `Refusing to overwrite existing:\n${exists.map(({ dest }) => ' ' + dest).join('\n')}\n Manually remove first to reinstall`
179
+ throw ERR_EXISTS(message)
180
+ }
181
+
182
+ const tmp = path.join(base, 'targets')
183
+ fs.mkdirSync(tmp, { recursive: true })
184
+ const prefixes = installs.map(({ filename, ext }) => appPath + filename + ext)
185
+ const mirror = drive.mirror(new LocalDrive(tmp), {
186
+ prefix: prefixes,
187
+ prune: false,
188
+ progress: true,
189
+ dedup: true
190
+ })
191
+ const monitor = mirror.monitor()
192
+ monitor.on('update', (stats) => this.push({ tag: 'stats', data: stats }))
193
+ await mirror.done()
194
+ monitor.destroy()
195
+
196
+ let installed = 0
197
+ for (const { filename, ext, dest, isBin } of installs) {
198
+ const key = appPath + filename + ext
199
+ this.push({ tag: 'app', data: { app: filename, name, version, upgrade, key, tmp, dest } })
200
+
201
+ const from = path.join(tmp, 'by-arch', host, 'app', filename + ext)
202
+
203
+ if (fs.existsSync(from) === false) {
204
+ throw ERR_NOT_FOUND(plink.serialize({ ...parsed, pathname: key }))
205
+ }
206
+
207
+ if (isWindows) {
208
+ const MSIXManager = require('msix-manager')
209
+ await new MSIXManager().addPackage(from)
210
+ installed++
211
+ continue
212
+ }
213
+
214
+ if (isBin) {
215
+ try {
216
+ if (!to) fs.mkdirSync(path.dirname(dest), { recursive: true })
217
+ this._move(from, dest)
218
+ } catch (err) {
219
+ if (err.code === 'EACCES' || err.code === 'EPERM') {
220
+ const dir = path.dirname(dest)
221
+ const fix = isMac
222
+ ? `sudo chgrp admin ${dir} && sudo chmod g+w ${dir}`
223
+ : `sudo chown -R "$(id -un):$(id -gn)" ${dir}`
224
+ throw ERR_PERMISSION_REQUIRED(`Permission denied: ${dest}\n Fix: ${fix}`)
225
+ }
226
+ throw err
227
+ }
228
+ fs.chmodSync(dest, 0o755)
229
+ } else {
230
+ try {
231
+ await fs.promises.rename(from, dest)
232
+ } catch (err) {
233
+ if (err.code === 'EACCES' || err.code === 'EPERM') {
234
+ const dir = path.dirname(dest)
235
+ const fix = isMac
236
+ ? `sudo chgrp admin ${dir} && sudo chmod g+w ${dir}`
237
+ : `sudo chown -R "$(id -un):$(id -gn)" ${dir}`
238
+ throw ERR_PERMISSION_REQUIRED(`Permission denied: ${dest}\n Fix: ${fix}`)
239
+ }
240
+ throw err
241
+ }
242
+ if (isLinux) await this._linux(dest, filename, tmp, home)
243
+ }
244
+ installed++
245
+ }
246
+ if (installed === 0) {
247
+ throw ERR_UNKNOWN('Failed to install')
248
+ }
249
+ this.final = { success: true, installed, exists }
250
+ } finally {
251
+ if (findingDone) findingDone()
252
+ await drive.close()
253
+ await swarm.destroy()
254
+ await corestore.close()
255
+ fs.rmSync(base, { recursive: true, force: true })
256
+ }
257
+ }
258
+
259
+ static async output(json, stream) {
260
+ for await (const { tag, data } of stream) {
261
+ if (json) {
262
+ process.stdout.write(JSON.stringify({ cmd: 'install', tag, data }) + '\n')
263
+ continue
264
+ }
265
+ if (tag === 'final') {
266
+ process.stdout.write('\r\x1B[2K' + this.outputs.final(data) + '\n')
267
+ return data
268
+ } else if (this.outputs[tag]) {
269
+ process.stdout.write('\r\x1B[2K' + this.outputs[tag](data) + '\n')
270
+ }
271
+ }
272
+ }
273
+
274
+ async _linux(dest, appName, tmp, home) {
275
+ fs.chmodSync(dest, 0o755)
276
+ const extracted = path.join(tmp, 'squashfs-root')
277
+ const desktopPath = this._extract(dest, extracted, tmp, appName + '.desktop')
278
+ const desktop = fs.readFileSync(desktopPath, 'utf8').replace(/^Exec=.*/m, `Exec=${dest}`)
279
+ fs.writeFileSync(desktopPath, desktop)
280
+
281
+ spawnSync(dest, ['--appimage-extract', 'usr/share/icons'], { cwd: tmp })
282
+ const src = new LocalDrive(path.join(extracted, 'usr', 'share', 'icons', 'hicolor'), {
283
+ followLinks: true
284
+ })
285
+ const dst = new LocalDrive(path.join(home, '.local', 'share', 'icons', 'hicolor'))
286
+ const mirror = src.mirror(dst, { prune: false })
287
+ await mirror.done()
288
+
289
+ this._move(
290
+ desktopPath,
291
+ path.join(home, '.local', 'share', 'applications', appName + '.desktop')
292
+ )
293
+ }
294
+
295
+ _extract(appImage, extracted, cwd, file) {
296
+ const { status } = spawnSync(appImage, ['--appimage-extract', file], { cwd })
297
+ if (status !== 0) throw new Error('appimage-extract failed')
298
+ const full = path.join(extracted, file)
299
+ let stat = null
300
+ try {
301
+ stat = fs.lstatSync(full)
302
+ } catch {}
303
+ if (stat !== null && !stat.isSymbolicLink()) return full
304
+ const link = fs.readlinkSync(full)
305
+ const target = path.resolve(path.dirname(full), link)
306
+ let exists = true
307
+ try {
308
+ fs.lstatSync(target)
309
+ } catch {
310
+ exists = false
311
+ }
312
+ return exists
313
+ ? target
314
+ : this._extract(appImage, extracted, cwd, path.relative(extracted, target))
315
+ }
316
+
317
+ _move(src, dst) {
318
+ try {
319
+ fs.renameSync(src, dst)
320
+ } catch (err) {
321
+ if (err.code === 'ENOENT') return // ignore if path does not exist
322
+ if (err.code !== 'EXDEV') throw err
323
+ fs.copyFileSync(src, dst)
324
+ fs.rmSync(src)
325
+ }
326
+ }
327
+ }
328
+
329
+ module.exports = async function (cmd) {
330
+ const { json, only, to, dhtBootstrap } = cmd.flags
331
+ const timeout = (cmd.flags.timeout || 30) * 1000
332
+ const link = cmd.args.link
333
+ const bootstrap = dhtBootstrap
334
+ ? dhtBootstrap.split(',').map((tuple) => {
335
+ const [host, port] = tuple.split(':')
336
+ const int = +port
337
+ if (Number.isInteger(int) === false) throw new Error(`Invalid port: ${port}`)
338
+ return { host, port: int }
339
+ })
340
+ : undefined
341
+ const stream = new Install({ link, only, to, bootstrap, timeout })
342
+ await Install.output(json, stream)
343
+ }
package/package.json CHANGED
@@ -1 +1,94 @@
1
- {"name":"pear-install","version":"0.0.0"}
1
+ {
2
+ "name": "pear-install",
3
+ "version": "1.0.2",
4
+ "main": "index.js",
5
+ "type": "commonjs",
6
+ "description": "Install Pear and Pear Applications",
7
+ "author": "Holepunch Inc",
8
+ "license": "Apache-2.0",
9
+ "bin": {
10
+ "pear-install": "cmd.js"
11
+ },
12
+ "imports": {
13
+ "process": {
14
+ "bare": "bare-process",
15
+ "default": "process"
16
+ },
17
+ "child_process": {
18
+ "bare": "bare-subprocess",
19
+ "default": "child_process"
20
+ },
21
+ "fs": {
22
+ "bare": "bare-fs",
23
+ "default": "fs"
24
+ },
25
+ "os": {
26
+ "bare": "bare-os",
27
+ "default": "os"
28
+ },
29
+ "path": {
30
+ "bare": "bare-path",
31
+ "default": "path"
32
+ }
33
+ },
34
+ "scripts": {
35
+ "format": "prettier --write . && lunte --fix .",
36
+ "lint": "prettier --check . && lunte",
37
+ "test:gen": "brittle -r test/all.js test/*.test.js",
38
+ "test": "npm run test:node && npm run test:bare",
39
+ "test:node": "brittle-node --coverage test/all.js",
40
+ "test:bare": "brittle-bare --coverage test/all.js"
41
+ },
42
+ "command": {
43
+ "summary": "Install applications from peers",
44
+ "description": "Installs from peers directly into OS application folder",
45
+ "flag --only <paths>": "Advanced. Filter by app filenames",
46
+ "flag --timeout seconds": "Advanced. Override network timeout (30s)",
47
+ "flag --to <dir>": "Advanced. Override install target directory",
48
+ "flag --dht-bootstrap <nodes>": "Advanced. Custom DHT bootstrap",
49
+ "flag --json": "Newline delimited JSON output"
50
+ },
51
+ "pear": {
52
+ "platform": {
53
+ "key": "pear://pzcjqmpoo6szkoc4bpkw65ib9ctnrq7b6mneeinbhbheihaq6p6o"
54
+ }
55
+ },
56
+ "dependencies": {
57
+ "bare-fs": "^4.7.1",
58
+ "bare-os": "^3.9.1",
59
+ "bare-path": "^3.0.0",
60
+ "bare-process": "^4.4.1",
61
+ "bare-subprocess": "^6.0.0",
62
+ "corestore": "^7.9.2",
63
+ "hypercore-crypto": "^3.7.0",
64
+ "hyperdrive": "^13.3.2",
65
+ "hyperswarm": "^4.17.0",
66
+ "localdrive": "^2.2.1",
67
+ "pear-errors": "^1.0.1",
68
+ "pear-link": "^4.2.1",
69
+ "pear-opstream": "^1.0.1",
70
+ "pear-opwait": "^1.0.0",
71
+ "streamx": "^2.23.0",
72
+ "tiny-byte-size": "^1.1.0"
73
+ },
74
+ "devDependencies": {
75
+ "brittle": "^3.19.1",
76
+ "lunte": "^1.8.0",
77
+ "prettier": "^3.7.4",
78
+ "prettier-config-holepunch": "^2.0.0",
79
+ "test-tmp": "^1.4.0",
80
+ "which-runtime": "^1.3.2"
81
+ },
82
+ "directories": {
83
+ "test": "test"
84
+ },
85
+ "repository": {
86
+ "type": "git",
87
+ "url": "git+https://github.com/holepunchto/pear-install.git"
88
+ },
89
+ "keywords": [],
90
+ "bugs": {
91
+ "url": "https://github.com/holepunchto/pear-install/issues"
92
+ },
93
+ "homepage": "https://github.com/holepunchto/pear-install#readme"
94
+ }
package/test/all.js ADDED
@@ -0,0 +1,13 @@
1
+ // This runner is auto-generated by Brittle
2
+
3
+ runTests()
4
+
5
+ async function runTests() {
6
+ const test = (await import('brittle')).default
7
+
8
+ test.pause()
9
+
10
+ await import('./index.test.js')
11
+
12
+ test.resume()
13
+ }
package/test/helper.js ADDED
@@ -0,0 +1,80 @@
1
+ 'use strict'
2
+ const Corestore = require('corestore')
3
+ const Hyperdrive = require('hyperdrive')
4
+ const Hyperswarm = require('hyperswarm')
5
+ const tmp = require('test-tmp')
6
+ const { command, arg, bail } = require('paparam')
7
+ const pkg = require('../package.json')
8
+ const install = require('..')
9
+ const process = require('process')
10
+ const arch = `${process.platform}-${process.arch}`
11
+
12
+ async function seed(t, { bootstrap, manifest, files }) {
13
+ const storage = await tmp(t)
14
+ const corestore = new Corestore(storage)
15
+ const drive = new Hyperdrive(corestore)
16
+ await drive.ready()
17
+ await drive.put('/package.json', Buffer.from(JSON.stringify(manifest)))
18
+ for (const [p, content] of Object.entries(files)) {
19
+ await drive.put(p, Buffer.from(content))
20
+ }
21
+ const swarm = new Hyperswarm({ bootstrap })
22
+ swarm.on('connection', (c) => corestore.replicate(c))
23
+ swarm.join(drive.discoveryKey, { server: true, client: false })
24
+ await swarm.flush()
25
+ t.teardown(async () => {
26
+ await swarm.destroy()
27
+ await drive.close()
28
+ await corestore.close()
29
+ })
30
+ return drive.key
31
+ }
32
+
33
+ async function run(args) {
34
+ const lines = []
35
+ let buf = ''
36
+ const origWrite = process.stdout.write
37
+ const origExitCode = process.exitCode
38
+ process.stdout.write = function (chunk) {
39
+ buf += chunk.toString()
40
+ let i
41
+ while ((i = buf.indexOf('\n')) !== -1) {
42
+ lines.push(buf.slice(0, i))
43
+ buf = buf.slice(i + 1)
44
+ }
45
+ return true
46
+ }
47
+ let bailInfo = null
48
+ let exitCode
49
+ try {
50
+ const program = command(
51
+ 'install',
52
+ arg('[link]', 'Pear link'),
53
+ pkg.command,
54
+ install,
55
+ bail((info) => {
56
+ bailInfo = info
57
+ })
58
+ )
59
+ const c = program.parse(args, { run: true })
60
+ if (c?.running) await c.running.catch(() => {})
61
+ } finally {
62
+ process.stdout.write = origWrite
63
+ exitCode = process.exitCode
64
+ process.exitCode = origExitCode
65
+ }
66
+ const events = lines.flatMap((l) => {
67
+ try {
68
+ return [JSON.parse(l)]
69
+ } catch {
70
+ return []
71
+ }
72
+ })
73
+ return { events, bail: bailInfo, stdout: lines.join('\n') + buf, exitCode }
74
+ }
75
+
76
+ function bootstrapArg(testnet) {
77
+ return testnet.bootstrap.map((b) => `${b.host}:${b.port}`).join(',')
78
+ }
79
+
80
+ module.exports = { seed, run, arch, bootstrapArg }
@@ -0,0 +1,238 @@
1
+ 'use strict'
2
+ const test = require('brittle')
3
+ const path = require('path')
4
+ const fs = require('fs')
5
+ const createTestnet = require('hyperdht/testnet')
6
+ const hypercoreCrypto = require('hypercore-crypto')
7
+ const hid = require('hypercore-id-encoding')
8
+ const plink = require('pear-link')
9
+ const { isWindows } = require('which-runtime')
10
+ const tmp = require('test-tmp')
11
+ const { seed, run, arch, bootstrapArg } = require('./helper')
12
+
13
+ test('successful bin install via testnet', { skip: isWindows }, async function (t) {
14
+ t.timeout(60000)
15
+ const testnet = await createTestnet(3, t.teardown)
16
+ const key = await seed(t, {
17
+ bootstrap: testnet.bootstrap,
18
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
19
+ files: { ['/by-arch/' + arch + '/app/tbin']: 'BIN' }
20
+ })
21
+ const link = plink.serialize({ drive: { key } })
22
+ const target = await tmp(t)
23
+ const { events } = await run([
24
+ '--json',
25
+ '--to',
26
+ target,
27
+ '--dht-bootstrap',
28
+ bootstrapArg(testnet),
29
+ link
30
+ ])
31
+ const final = events.find((e) => e.tag === 'final')
32
+ t.ok(final, 'final event emitted')
33
+ t.is(final.data.success, true, 'success')
34
+ t.is(fs.readFileSync(path.join(target, 'tbin'), 'utf8'), 'BIN', 'bin written to target')
35
+ })
36
+
37
+ test('notFound emits full pear:// link when platform binary missing', async function (t) {
38
+ t.timeout(60000)
39
+ const testnet = await createTestnet(3, t.teardown)
40
+ const key = await seed(t, {
41
+ bootstrap: testnet.bootstrap,
42
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
43
+ files: {}
44
+ })
45
+ const link = plink.serialize({ drive: { key } })
46
+ const target = await tmp(t)
47
+ const { events } = await run([
48
+ '--json',
49
+ '--to',
50
+ target,
51
+ '--dht-bootstrap',
52
+ bootstrapArg(testnet),
53
+ link
54
+ ])
55
+ const final = events.find((e) => e.tag === 'final')
56
+ const error = events.find((e) => e.tag === 'error')
57
+ t.ok(final, 'final event emitted')
58
+ t.is(final.data.success, false, 'failure')
59
+ t.is(error?.data.code, 'ERR_NOT_FOUND', 'ERR_NOT_FOUND emitted')
60
+ t.ok(error?.data.message.includes('pear://'), 'error message includes pear link')
61
+ t.ok(
62
+ error?.data.message.includes('/by-arch/' + arch + '/app/tbin'),
63
+ 'error message includes platform path'
64
+ )
65
+ })
66
+
67
+ test('refuses to overwrite an existing install', { skip: isWindows }, async function (t) {
68
+ t.timeout(60000)
69
+ const testnet = await createTestnet(3, t.teardown)
70
+ const key = await seed(t, {
71
+ bootstrap: testnet.bootstrap,
72
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
73
+ files: { ['/by-arch/' + arch + '/app/tbin']: 'NEW' }
74
+ })
75
+ const link = plink.serialize({ drive: { key } })
76
+ const target = await tmp(t)
77
+ fs.writeFileSync(path.join(target, 'tbin'), 'EXISTING')
78
+ const { events } = await run([
79
+ '--json',
80
+ '--to',
81
+ target,
82
+ '--dht-bootstrap',
83
+ bootstrapArg(testnet),
84
+ link
85
+ ])
86
+ const final = events.find((e) => e.tag === 'final')
87
+ const error = events.find((e) => e.tag === 'error')
88
+ t.ok(final, 'final event emitted')
89
+ t.is(final.data.success, false, 'failure')
90
+ t.is(error?.data.code, 'ERR_EXISTS', 'ERR_EXISTS emitted')
91
+ t.ok(
92
+ error?.data.message.includes('Refusing to overwrite existing'),
93
+ 'error message reports refusal'
94
+ )
95
+ t.ok(
96
+ error?.data.message.includes(path.join(target, 'tbin')),
97
+ 'error message lists existing target path'
98
+ )
99
+ t.is(fs.readFileSync(path.join(target, 'tbin'), 'utf8'), 'EXISTING', 'existing file untouched')
100
+ })
101
+
102
+ test('invalid port in --dht-bootstrap reaches bail handler', async function (t) {
103
+ const { bail: info } = await run([
104
+ '--dht-bootstrap',
105
+ '127.0.0.1:nope',
106
+ 'pear://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
107
+ ])
108
+ t.ok(info, 'bail handler invoked')
109
+ t.is(info.err?.message, 'Invalid port: nope')
110
+ })
111
+
112
+ test('link with pathname emits error event', async function (t) {
113
+ const key = hid.encode(hypercoreCrypto.keyPair().publicKey)
114
+ const link = `pear://${key}/some/path`
115
+ const { events } = await run(['--json', link])
116
+ const error = events.find((e) => e.tag === 'error')
117
+ t.ok(error, 'error event emitted')
118
+ t.is(error.data.message, 'Link must not have pathname')
119
+ })
120
+
121
+ test(
122
+ 'non-json output prints installing, app and Installed',
123
+ { skip: isWindows },
124
+ async function (t) {
125
+ t.timeout(60000)
126
+ const testnet = await createTestnet(3, t.teardown)
127
+ const key = await seed(t, {
128
+ bootstrap: testnet.bootstrap,
129
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
130
+ files: { ['/by-arch/' + arch + '/app/tbin']: 'BIN' }
131
+ })
132
+ const link = plink.serialize({ drive: { key } })
133
+ const target = await tmp(t)
134
+ const { stdout } = await run(['--to', target, '--dht-bootstrap', bootstrapArg(testnet), link])
135
+ t.ok(stdout.includes('Installing...'), 'installing message printed')
136
+ t.ok(stdout.includes('App: tbin'), 'app message printed')
137
+ t.ok(stdout.includes('Installed'), 'final installed message printed')
138
+ }
139
+ )
140
+
141
+ test(
142
+ 'non-json output prints Not found for missing platform binary',
143
+ { skip: isWindows },
144
+ async function (t) {
145
+ t.timeout(60000)
146
+ const testnet = await createTestnet(3, t.teardown)
147
+ const key = await seed(t, {
148
+ bootstrap: testnet.bootstrap,
149
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
150
+ files: {}
151
+ })
152
+ const link = plink.serialize({ drive: { key } })
153
+ const target = await tmp(t)
154
+ const { stdout } = await run(['--to', target, '--dht-bootstrap', bootstrapArg(testnet), link])
155
+ t.ok(stdout.includes('Not found: pear://'), 'not found message printed')
156
+ }
157
+ )
158
+
159
+ test(
160
+ 'non-json output prints Refusing to overwrite for existing target',
161
+ { skip: isWindows },
162
+ async function (t) {
163
+ t.timeout(60000)
164
+ const testnet = await createTestnet(3, t.teardown)
165
+ const key = await seed(t, {
166
+ bootstrap: testnet.bootstrap,
167
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
168
+ files: { ['/by-arch/' + arch + '/app/tbin']: 'BIN' }
169
+ })
170
+ const link = plink.serialize({ drive: { key } })
171
+ const target = await tmp(t)
172
+ fs.writeFileSync(path.join(target, 'tbin'), 'EXISTING')
173
+ const { stdout } = await run(['--to', target, '--dht-bootstrap', bootstrapArg(testnet), link])
174
+ t.ok(stdout.includes('Refusing to overwrite existing'), 'refusing message printed')
175
+ t.ok(stdout.includes('Manually remove first'), 'fix hint printed')
176
+ }
177
+ )
178
+
179
+ test('_move falls back to copy+rm on EXDEV', { skip: isWindows }, async function (t) {
180
+ t.timeout(60000)
181
+ const testnet = await createTestnet(3, t.teardown)
182
+ const key = await seed(t, {
183
+ bootstrap: testnet.bootstrap,
184
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
185
+ files: { ['/by-arch/' + arch + '/app/tbin']: 'BIN' }
186
+ })
187
+ const link = plink.serialize({ drive: { key } })
188
+ const target = await tmp(t)
189
+ const renameSync = fs.renameSync
190
+ fs.renameSync = function () {
191
+ const err = new Error('cross-device link not permitted')
192
+ err.code = 'EXDEV'
193
+ throw err
194
+ }
195
+ t.teardown(() => {
196
+ fs.renameSync = renameSync
197
+ })
198
+ const { events } = await run([
199
+ '--json',
200
+ '--to',
201
+ target,
202
+ '--dht-bootstrap',
203
+ bootstrapArg(testnet),
204
+ link
205
+ ])
206
+ const final = events.find((e) => e.tag === 'final')
207
+ t.is(final?.data?.success, true, 'install succeeded via copy+rm fallback')
208
+ t.is(fs.readFileSync(path.join(target, 'tbin'), 'utf8'), 'BIN', 'bin content copied to target')
209
+ })
210
+
211
+ test('permission denied when target dir is read-only', { skip: isWindows }, async function (t) {
212
+ t.timeout(60000)
213
+ const testnet = await createTestnet(3, t.teardown)
214
+ const key = await seed(t, {
215
+ bootstrap: testnet.bootstrap,
216
+ manifest: { name: 'tbin', version: '1.0.0', upgrade: 'pear://x', bin: 'cli.js' },
217
+ files: { ['/by-arch/' + arch + '/app/tbin']: 'BIN' }
218
+ })
219
+ const link = plink.serialize({ drive: { key } })
220
+ const target = await tmp(t)
221
+ fs.chmodSync(target, 0o555)
222
+ t.teardown(() => {
223
+ try {
224
+ fs.chmodSync(target, 0o755)
225
+ } catch {}
226
+ })
227
+ const { events, stdout } = await run([
228
+ '--to',
229
+ target,
230
+ '--dht-bootstrap',
231
+ bootstrapArg(testnet),
232
+ link
233
+ ])
234
+ // since no --json, events is empty; assert via stdout
235
+ t.is(events.length, 0, 'no json events (non-json mode)')
236
+ t.ok(stdout.includes('Permission denied'), 'permission message printed')
237
+ t.ok(stdout.includes('Fix:'), 'fix hint printed')
238
+ })