forked from storacha/w3cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
349 lines (324 loc) · 9.85 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import fs from 'fs'
import path from 'path'
// @ts-expect-error no typings :(
import tree from 'pretty-tree'
import { importDAG } from '@ucanto/core/delegation'
import { connect } from '@ucanto/client'
import * as CAR from '@ucanto/transport/car'
import * as HTTP from '@ucanto/transport/http'
import * as Signer from '@ucanto/principal/ed25519'
import * as Link from 'multiformats/link'
import { base58btc } from 'multiformats/bases/base58'
import * as Digest from 'multiformats/hashes/digest'
import * as raw from 'multiformats/codecs/raw'
import { parse } from '@ipld/dag-ucan/did'
import * as dagJSON from '@ipld/dag-json'
import { create } from '@web3-storage/w3up-client'
import { StoreConf } from '@web3-storage/w3up-client/stores/conf'
import { CarReader } from '@ipld/car'
import chalk from 'chalk'
/**
* @typedef {import('@web3-storage/w3up-client/types').AnyLink} AnyLink
* @typedef {import('@web3-storage/w3up-client/types').CARLink} CARLink
* @typedef {import('@web3-storage/w3up-client/types').FileLike & { size: number }} FileLike
* @typedef {import('@web3-storage/w3up-client/types').BlobListSuccess} BlobListSuccess
* @typedef {import('@web3-storage/w3up-client/types').StoreListSuccess} StoreListSuccess
* @typedef {import('@web3-storage/w3up-client/types').UploadListSuccess} UploadListSuccess
* @typedef {import('@web3-storage/capabilities/types').FilecoinInfoSuccess} FilecoinInfoSuccess
*/
/**
*
*/
export function getPkg() {
// @ts-ignore JSON.parse works with Buffer in Node.js
return JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url)))
}
/** @param {string[]|string} paths */
export function checkPathsExist(paths) {
paths = Array.isArray(paths) ? paths : [paths]
for (const p of paths) {
if (!fs.existsSync(p)) {
console.error(`The path ${path.resolve(p)} does not exist`)
process.exit(1)
}
}
return paths
}
/** @param {number} bytes */
export function filesize(bytes) {
if (bytes < 50) return `${bytes}B` // avoid 0.0KB
if (bytes < 50000) return `${(bytes / 1000).toFixed(1)}KB` // avoid 0.0MB
if (bytes < 50000000) return `${(bytes / 1000 / 1000).toFixed(1)}MB` // avoid 0.0GB
return `${(bytes / 1000 / 1000 / 1000).toFixed(1)}GB`
}
/** @param {number} bytes */
export function filesizeMB(bytes) {
return `${(bytes / 1000 / 1000).toFixed(1)}MB`
}
/** Get a configured w3up store used by the CLI. */
export function getStore() {
return new StoreConf({ profile: process.env.W3_STORE_NAME ?? 'w3cli' })
}
/**
* Get a new API client configured from env vars.
*/
export function getClient() {
const store = getStore()
if (process.env.W3_ACCESS_SERVICE_URL || process.env.W3_UPLOAD_SERVICE_URL) {
console.warn(
chalk.dim(
'warning: the W3_ACCESS_SERVICE_URL and W3_UPLOAD_SERVICE_URL environment variables are deprecated and will be removed in a future release - please use W3UP_SERVICE_URL instead.'
)
)
}
if (process.env.W3_ACCESS_SERVICE_DID || process.env.W3_UPLOAD_SERVICE_DID) {
console.warn(
chalk.dim(
'warning: the W3_ACCESS_SERVICE_DID and W3_UPLOAD_SERVICE_DID environment variables are deprecated and will be removed in a future release - please use W3UP_SERVICE_DID instead.'
)
)
}
const accessServiceDID =
process.env.W3UP_SERVICE_DID || process.env.W3_ACCESS_SERVICE_DID
const accessServiceURL =
process.env.W3UP_SERVICE_URL || process.env.W3_ACCESS_SERVICE_URL
const uploadServiceDID =
process.env.W3UP_SERVICE_DID || process.env.W3_UPLOAD_SERVICE_DID
const uploadServiceURL =
process.env.W3UP_SERVICE_URL || process.env.W3_UPLOAD_SERVICE_URL
const receiptsEndpointString = (process.env.W3UP_RECEIPTS_ENDPOINT || process.env.W3_UPLOAD_RECEIPTS_URL)
let receiptsEndpoint
if (receiptsEndpointString) {
receiptsEndpoint = new URL(receiptsEndpointString)
}
let serviceConf
if (
accessServiceDID &&
accessServiceURL &&
uploadServiceDID &&
uploadServiceURL
) {
serviceConf =
/** @type {import('@web3-storage/w3up-client/types').ServiceConf} */
({
access: connect({
id: parse(accessServiceDID),
codec: CAR.outbound,
channel: HTTP.open({
url: new URL(accessServiceURL),
method: 'POST',
}),
}),
upload: connect({
id: parse(uploadServiceDID),
codec: CAR.outbound,
channel: HTTP.open({
url: new URL(uploadServiceURL),
method: 'POST',
}),
}),
filecoin: connect({
id: parse(uploadServiceDID),
codec: CAR.outbound,
channel: HTTP.open({
url: new URL(uploadServiceURL),
method: 'POST',
}),
}),
})
}
/** @type {import('@web3-storage/w3up-client/types').ClientFactoryOptions} */
const createConfig = { store, serviceConf, receiptsEndpoint }
const principal = process.env.W3_PRINCIPAL
if (principal) {
createConfig.principal = Signer.parse(principal)
}
return create(createConfig)
}
/**
* @param {string} path Path to the proof file.
*/
export async function readProof(path) {
let bytes
try {
const buff = await fs.promises.readFile(path)
bytes = new Uint8Array(buff.buffer)
} catch (/** @type {any} */ err) {
console.error(`Error: failed to read proof: ${err.message}`)
process.exit(1)
}
return readProofFromBytes(bytes)
}
/**
* @param {Uint8Array} bytes Path to the proof file.
*/
export async function readProofFromBytes(bytes) {
const blocks = []
try {
const reader = await CarReader.fromBytes(bytes)
for await (const block of reader.blocks()) {
blocks.push(block)
}
} catch (/** @type {any} */ err) {
console.error(`Error: failed to parse proof: ${err.message}`)
process.exit(1)
}
try {
// @ts-expect-error
return importDAG(blocks)
} catch (/** @type {any} */ err) {
console.error(`Error: failed to import proof: ${err.message}`)
process.exit(1)
}
}
/**
* @param {UploadListSuccess} res
* @param {object} [opts]
* @param {boolean} [opts.raw]
* @param {boolean} [opts.json]
* @param {boolean} [opts.shards]
* @param {boolean} [opts.plainTree]
* @returns {string}
*/
export function uploadListResponseToString(res, opts = {}) {
if (opts.json) {
return res.results
.map(({ root, shards }) => dagJSON.stringify({ root, shards }))
.join('\n')
} else if (opts.shards) {
return res.results
.map(({ root, shards }) => {
const treeBuilder = opts.plainTree ? tree.plain : tree
return treeBuilder({
label: root.toString(),
nodes: [
{
label: 'shards',
leaf: shards?.map((s) => s.toString()),
},
],
})}
)
.join('\n')
} else {
return res.results.map(({ root }) => root.toString()).join('\n')
}
}
/**
* @param {BlobListSuccess} res
* @param {object} [opts]
* @param {boolean} [opts.raw]
* @param {boolean} [opts.json]
* @returns {string}
*/
export function blobListResponseToString(res, opts = {}) {
if (opts.json) {
return res.results
.map(({ blob }) => dagJSON.stringify({ blob }))
.join('\n')
} else {
return res.results
.map(({ blob }) => {
const digest = Digest.decode(blob.digest)
const cid = Link.create(raw.code, digest)
return `${base58btc.encode(digest.bytes)} (${cid})`
})
.join('\n')
}
}
/**
* @param {StoreListSuccess} res
* @param {object} [opts]
* @param {boolean} [opts.raw]
* @param {boolean} [opts.json]
* @returns {string}
*/
export function storeListResponseToString(res, opts = {}) {
if (opts.json) {
return res.results
.map(({ link, size }) => dagJSON.stringify({ link, size }))
.join('\n')
} else {
return res.results.map(({ link }) => link.toString()).join('\n')
}
}
/**
* @param {FilecoinInfoSuccess} res
* @param {object} [opts]
* @param {boolean} [opts.raw]
* @param {boolean} [opts.json]
*/
export function filecoinInfoToString(res, opts = {}) {
if (opts.json) {
return res.deals
.map(deal => dagJSON.stringify(({
aggregate: deal.aggregate.toString(),
provider: deal.provider,
dealId: deal.aux.dataSource.dealID,
inclusion: res.aggregates.find(a => a.aggregate.toString() === deal.aggregate.toString())?.inclusion
})))
.join('\n')
} else {
if (!res.deals.length) {
return `
Piece CID: ${res.piece.toString()}
Deals: Piece being aggregated and offered for deal...
`
}
// not showing inclusion proof as it would just be bytes
return `
Piece CID: ${res.piece.toString()}
Deals: ${res.deals.map((deal) => `
Aggregate: ${deal.aggregate.toString()}
Provider: ${deal.provider}
Deal ID: ${deal.aux.dataSource.dealID}
`).join('')}
`
}
}
/**
* Return validated CARLink or undefined
*
* @param {AnyLink} cid
*/
export function asCarLink(cid) {
if (cid.version === 1 && cid.code === CAR.codec.code) {
return /** @type {CARLink} */ (cid)
}
}
/**
* Return validated CARLink type or exit the process with an error code and message
*
* @param {string} cidStr
*/
export function parseCarLink(cidStr) {
try {
return asCarLink(Link.parse(cidStr.trim()))
} catch {
return undefined
}
}
/** @param {string|number|Date} now */
const startOfMonth = (now) => {
const d = new Date(now)
d.setUTCDate(1)
d.setUTCHours(0)
d.setUTCMinutes(0)
d.setUTCSeconds(0)
d.setUTCMilliseconds(0)
return d
}
/** @param {string|number|Date} now */
export const startOfLastMonth = (now) => {
const d = startOfMonth(now)
d.setUTCMonth(d.getUTCMonth() - 1)
return d
}
/** @param {ReadableStream<Uint8Array>} source */
export const streamToBlob = async source => {
const chunks = /** @type {Uint8Array[]} */ ([])
await source.pipeTo(new WritableStream({
write: chunk => { chunks.push(chunk) }
}))
return new Blob(chunks)
}