Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
  • Loading branch information
alanshaw committed Nov 11, 2024
1 parent 9edc4fc commit df59407
Show file tree
Hide file tree
Showing 16 changed files with 202 additions and 103 deletions.
17 changes: 12 additions & 5 deletions packages/cli/bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ cli
.describe('Store a file(s) to the service and register an upload.')
.option('-H, --hidden', 'Include paths that start with ".".', false)
.option('-c, --car', 'File is a CAR file.', false)
.option('--wrap', "Wrap single input file in a directory. Has no effect on directory or CAR uploads. Pass --no-wrap to disable.", true)
.option(
'--wrap',
'Wrap single input file in a directory. Has no effect on directory or CAR uploads. Pass --no-wrap to disable.',
true
)
.option('--json', 'Format as newline delimited JSON', false)
.option('--verbose', 'Output more details.', false)
.option(
Expand Down Expand Up @@ -181,7 +185,7 @@ cli
)
.action(Coupon.issue)

cli
cli
.command('bridge generate-tokens <did>')
.option('-c, --can', 'One or more abilities to delegate.')
.option(
Expand All @@ -195,7 +199,6 @@ cli
)
.action(Bridge.generateTokens)


cli
.command('delegation create <audience-did>')
.describe(
Expand Down Expand Up @@ -323,13 +326,17 @@ cli

cli
.command('key create')
.describe('Generate and print a new ed25519 key pair. Does not change your current signing key.')
.describe(
'Generate and print a new ed25519 key pair. Does not change your current signing key.'
)
.option('--json', 'output as json')
.action(createKey)

cli
.command('reset')
.describe('Remove all proofs/delegations from the store but retain the agent DID.')
.describe(
'Remove all proofs/delegations from the store but retain the agent DID.'
)
.action(reset)

// show help text if no command provided
Expand Down
10 changes: 6 additions & 4 deletions packages/cli/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,12 @@ export const generateTokens = async (
const authorization = base64url.encode(bytes)

if (json) {
console.log(JSON.stringify({
"X-Auth-Secret": xAuthSecret,
"Authorization": authorization
}))
console.log(
JSON.stringify({
'X-Auth-Secret': xAuthSecret,
Authorization: authorization,
})
)
} else {
console.log(`
X-Auth-Secret header: ${xAuthSecret}
Expand Down
11 changes: 8 additions & 3 deletions packages/cli/can.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@ export async function blobAdd(blobPath) {

spinner.start('Storing')
const { digest } = await client.capability.blob.add(blob, {
receiptsEndpoint: client._receiptsEndpoint.toString()
receiptsEndpoint: client._receiptsEndpoint.toString(),
})
const cid = Link.create(raw.code, digest)
spinner.stopAndPersist({ symbol: '⁂', text: `Stored ${base58btc.encode(digest.bytes)} (${cid})` })
spinner.stopAndPersist({
symbol: '⁂',
text: `Stored ${base58btc.encode(digest.bytes)} (${cid})`,
})
}

/**
Expand Down Expand Up @@ -211,7 +214,9 @@ export async function filecoinInfo(pieceCid, opts) {
const client = await getClient()
const info = await client.capability.filecoin.info(pieceInfo.link)
if (info.out.error) {
spinner.fail(`Error: failed to get filecoin info: ${info.out.error.message}`)
spinner.fail(
`Error: failed to get filecoin info: ${info.out.error.message}`
)
process.exit(1)
}
spinner.stop()
Expand Down
67 changes: 41 additions & 26 deletions packages/cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,14 @@ export async function upload(firstPath, opts) {
}
} else {
spinner = ora({ text: 'Reading from stdin', isSilent: opts?.json }).start()
files = [{
name: 'stdin',
stream: () =>
/** @type {ReadableStream} */
(Readable.toWeb(process.stdin))
}]
files = [
{
name: 'stdin',
stream: () =>
/** @type {ReadableStream} */
(Readable.toWeb(process.stdin)),
},
]
totalSize = -1
opts = opts ?? { _: [] }
opts.wrap = false
Expand All @@ -155,26 +157,27 @@ export async function upload(firstPath, opts) {
: client.uploadDirectory.bind(client, files)

let totalSent = 0
const getStoringMessage = () => totalSize == -1
// for unknown size, display the amount sent so far
? `Storing ${filesizeMB(totalSent)}`
// for known size, display percentage of total size that has been sent
: `Storing ${Math.min(Math.round((totalSent / totalSize) * 100), 100)}%`
const getStoringMessage = () =>
totalSize == -1
? // for unknown size, display the amount sent so far
`Storing ${filesizeMB(totalSent)}`
: // for known size, display percentage of total size that has been sent
`Storing ${Math.min(Math.round((totalSent / totalSize) * 100), 100)}%`

const root = await uploadFn({
pieceHasher: {
code: PieceHasher.code,
name: 'fr32-sha2-256-trunc254-padded-binary-tree-multihash',
async digest (input) {
async digest(input) {
const hasher = PieceHasher.create()
hasher.write(input)

const bytes = new Uint8Array(hasher.multihashByteLength())
hasher.digestInto(bytes, 0, true)
hasher.free()

return Digest.decode(bytes)
}
},
},
onShardStored: ({ cid, size, piece }) => {
totalSent += size
Expand All @@ -196,7 +199,7 @@ export async function upload(firstPath, opts) {
concurrentRequests:
opts?.['concurrent-requests'] &&
parseInt(String(opts?.['concurrent-requests'])),
receiptsEndpoint: client._receiptsEndpoint.toString()
receiptsEndpoint: client._receiptsEndpoint.toString(),
})
spinner.stopAndPersist({
symbol: '⁂',
Expand Down Expand Up @@ -278,7 +281,9 @@ export async function addSpace(proofPathOrCid) {
cid = CID.parse(proofPathOrCid, base64)
} catch (/** @type {any} */ err) {
if (err?.message?.includes('Unexpected end of data')) {
console.error(`Error: failed to read proof. The string has been truncated.`)
console.error(
`Error: failed to read proof. The string has been truncated.`
)
process.exit(1)
}
/* otherwise, try as path */
Expand All @@ -287,7 +292,9 @@ export async function addSpace(proofPathOrCid) {
let delegation
if (cid) {
if (cid.multihash.code !== identity.code) {
console.error(`Error: failed to read proof. Must be identity CID. Fetching of remote proof CARs not supported by this command yet`)
console.error(
`Error: failed to read proof. Must be identity CID. Fetching of remote proof CARs not supported by this command yet`
)
process.exit(1)
}
delegation = await readProofFromBytes(cid.multihash.digest)
Expand Down Expand Up @@ -386,7 +393,9 @@ export async function createDelegation(audienceDID, opts) {
const client = await getClient()

if (client.currentSpace() == null) {
throw new Error('no current space, use `storacha space register` to create one.')
throw new Error(
'no current space, use `storacha space register` to create one.'
)
}
const audience = DID.parse(audienceDID)

Expand Down Expand Up @@ -603,10 +612,7 @@ export async function usageReport(opts) {
}
const failures = []
let total = 0
for await (const result of getSpaceUsageReports(
client,
period
)) {
for await (const result of getSpaceUsageReports(client, period)) {
if ('error' in result) {
failures.push(result)
} else {
Expand Down Expand Up @@ -637,9 +643,15 @@ export async function usageReport(opts) {
console.log(` Total: ${opts?.human ? filesize(total) : total}`)
if (failures.length) {
console.warn(``)
console.warn(` WARNING: there were ${failures.length} errors getting usage reports for some spaces.`)
console.warn(` This may happen if your agent does not have usage/report authorization for a space.`)
console.warn(` These spaces were not included in the usage report total:`)
console.warn(
` WARNING: there were ${failures.length} errors getting usage reports for some spaces.`
)
console.warn(
` This may happen if your agent does not have usage/report authorization for a space.`
)
console.warn(
` These spaces were not included in the usage report total:`
)
for (const fail of failures) {
console.warn(` * space: ${fail.space}`)
// @ts-expect-error error is unknown
Expand Down Expand Up @@ -697,7 +709,10 @@ export const reset = async () => {
if (exportData) {
let data = AgentData.fromExport(exportData)
// do not reset the principal
data = await AgentData.create({ principal: data.principal, meta: data.meta })
data = await AgentData.create({
principal: data.principal,
meta: data.meta,
})
await store.save(data.export())
}
console.log('⁂ Agent reset.')
Expand Down
52 changes: 32 additions & 20 deletions packages/cli/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ export function filesizeMB(bytes) {

/** Get a configured w3up store used by the CLI. */
export function getStore() {
return new StoreConf({ profile: process.env.STORACHA_STORE_NAME ?? 'storacha-cli' })
return new StoreConf({
profile: process.env.STORACHA_STORE_NAME ?? 'storacha-cli',
})
}

/**
Expand All @@ -81,7 +83,7 @@ export function getClient() {
if (receiptsEndpointString) {
receiptsEndpoint = new URL(receiptsEndpointString)
}

let serviceConf
if (uploadServiceDID && uploadServiceURL) {
serviceConf =
Expand Down Expand Up @@ -180,8 +182,8 @@ export function uploadListResponseToString(res, opts = {}) {
leaf: shards?.map((s) => s.toString()),
},
],
})}
)
})
})
.join('\n')
} else {
return res.results.map(({ root }) => root.toString()).join('\n')
Expand All @@ -197,9 +199,7 @@ export function uploadListResponseToString(res, opts = {}) {
*/
export function blobListResponseToString(res, opts = {}) {
if (opts.json) {
return res.results
.map(({ blob }) => dagJSON.stringify({ blob }))
.join('\n')
return res.results.map(({ blob }) => dagJSON.stringify({ blob })).join('\n')
} else {
return res.results
.map(({ blob }) => {
Expand All @@ -212,20 +212,24 @@ export function blobListResponseToString(res, opts = {}) {
}

/**
* @param {FilecoinInfoSuccess} res
* @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
})))
.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) {
Expand All @@ -237,11 +241,15 @@ export function filecoinInfoToString(res, opts = {}) {
// not showing inclusion proof as it would just be bytes
return `
Piece CID: ${res.piece.toString()}
Deals: ${res.deals.map((deal) => `
Deals: ${res.deals
.map(
(deal) => `
Aggregate: ${deal.aggregate.toString()}
Provider: ${deal.provider}
Deal ID: ${deal.aux.dataSource.dealID}
`).join('')}
`
)
.join('')}
`
}
}
Expand Down Expand Up @@ -289,10 +297,14 @@ export const startOfLastMonth = (now) => {
}

/** @param {ReadableStream<Uint8Array>} source */
export const streamToBlob = async source => {
export const streamToBlob = async (source) => {
const chunks = /** @type {Uint8Array[]} */ ([])
await source.pipeTo(new WritableStream({
write: chunk => { chunks.push(chunk) }
}))
await source.pipeTo(
new WritableStream({
write: (chunk) => {
chunks.push(chunk)
},
})
)
return new Blob(chunks)
}
4 changes: 2 additions & 2 deletions packages/cli/space.js
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,8 @@ const chooseName = async (name, spaces) => {
name === ''
? 'What would you like to call this space?'
: space
? `Name "${space.name}" is already taken, please choose a different one`
: null
? `Name "${space.name}" is already taken, please choose a different one`
: null

if (message == null) {
return name
Expand Down
Loading

0 comments on commit df59407

Please sign in to comment.