Skip to content

Commit

Permalink
fix: various linting issues (#93)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alan Shaw authored Sep 7, 2023
1 parent 8240ba5 commit f829c42
Show file tree
Hide file tree
Showing 12 changed files with 1,460 additions and 5,413 deletions.
10 changes: 5 additions & 5 deletions can.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export async function storeAdd (carPath) {
try {
const data = await fs.promises.readFile(carPath)
blob = new Blob([data])
} catch (err) {
} catch (/** @type {any} */err) {
spinner.fail(`Error: failed to read CAR: ${err.message}`)
process.exit(1)
}
Expand All @@ -39,7 +39,7 @@ export async function storeList (opts = {}) {
const client = await getClient()
const listOptions = {}
if (opts.size) {
listOptions.size = parseInt(opts.size)
listOptions.size = parseInt(String(opts.size))
}
if (opts.cursor) {
listOptions.cursor = opts.cursor
Expand All @@ -66,7 +66,7 @@ export async function uploadAdd (root, shard, opts) {
let rootCID
try {
rootCID = CID.parse(root)
} catch (err) {
} catch (/** @type {any} */err) {
console.error(`Error: failed to parse root CID: ${root}: ${err.message}`)
process.exit(1)
}
Expand All @@ -77,7 +77,7 @@ export async function uploadAdd (root, shard, opts) {
try {
// @ts-expect-error may not be a CAR CID...
shards.push(CID.parse(str))
} catch (err) {
} catch (/** @type {any} */err) {
console.error(`Error: failed to parse shard CID: ${str}: ${err.message}`)
process.exit(1)
}
Expand All @@ -101,7 +101,7 @@ export async function uploadList (opts = {}) {
const client = await getClient()
const listOptions = {}
if (opts.size) {
listOptions.size = parseInt(opts.size)
listOptions.size = parseInt(String(opts.size))
}
if (opts.cursor) {
listOptions.cursor = opts.cursor
Expand Down
65 changes: 38 additions & 27 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export async function accessClaim () {
}

/**
* @param {string} email
* @param {`${string}@${string}`} email
* @param {object} [opts]
* @param {import('@ucanto/interface').Ability[]|import('@ucanto/interface').Ability} [opts.can]
*/
Expand All @@ -42,30 +42,35 @@ export async function authorize (email, opts = {}) {

/**
* @param {string} firstPath
* @param {object} opts
* @param {string[]} opts._
* @param {boolean} [opts.hidden]
* @param {{
* _: string[],
* car?: boolean
* hidden?: boolean
* 'no-wrap'?: boolean
* 'shard-size'?: number
* 'concurrent-requests'?: number
* }} [opts]
*/
export async function upload (firstPath, opts) {
const paths = checkPathsExist([firstPath, ...opts._])
const paths = checkPathsExist([firstPath, ...(opts?._ ?? [])])
const client = await getClient()
const hidden = !!opts.hidden
const hidden = !!opts?.hidden
let totalSent = 0
const spinner = ora('Reading files').start()
const files = await filesFromPaths(paths, { hidden })
const totalSize = files.reduce((total, f) => total + f.size, 0)
spinner.stopAndPersist({ text: `${files.length} file${files.length === 1 ? '' : 's'} (${filesize(totalSize)})` })

if (opts.car && files.length > 1) {
if (opts?.car && files.length > 1) {
console.error('Error: multiple CAR files not supported')
process.exit(1)
}

spinner.start('Storing')
/** @type {(o?: import('@web3-storage/w3up-client/src/types').UploadOptions) => Promise<import('@web3-storage/w3up-client/src/types').AnyLink>} */
const uploadFn = opts.car
const uploadFn = opts?.car
? client.uploadCAR.bind(client, files[0])
: files.length === 1 && opts['no-wrap']
: files.length === 1 && opts?.['no-wrap']
? client.uploadFile.bind(client, files[0])
: client.uploadDirectory.bind(client, files)

Expand All @@ -75,8 +80,8 @@ export async function upload (firstPath, opts) {
spinner.stopAndPersist({ text: cid.toString() })
spinner.start(`Storing ${Math.round((totalSent / totalSize) * 100)}%`)
},
shardSize: opts['shard-size'] && parseInt(opts['shard-size']),
concurrentRequests: opts['concurrent-requests'] && parseInt(opts['concurrent-requests'])
shardSize: opts?.['shard-size'] && parseInt(String(opts?.['shard-size'])),
concurrentRequests: opts?.['concurrent-requests'] && parseInt(String(opts?.['concurrent-requests']))
})
spinner.stopAndPersist({ symbol: '⁂', text: `Stored ${files.length} file${files.length === 1 ? '' : 's'}` })
console.log(`⁂ https://w3s.link/ipfs/${root}`)
Expand All @@ -91,9 +96,11 @@ export async function upload (firstPath, opts) {
export async function list (opts = {}) {
const client = await getClient()
let count = 0
/** @type {import('@web3-storage/w3up-client/types').UploadListOk|undefined} */
let res
do {
res = await client.capability.upload.list({ cursor: res?.cursor })
if (!res) throw new Error('missing upload list response')
count += res.results.length
if (res.results.length) {
console.log(uploadListResponseToString(res, opts))
Expand All @@ -114,15 +121,15 @@ export async function remove (rootCid, opts) {
let root
try {
root = CID.parse(rootCid.trim())
} catch (err) {
} catch (/** @type {any} */err) {
console.error(`Error: ${rootCid} is not a CID`)
process.exit(1)
}
const client = await getClient()
let upload
try {
upload = await client.capability.upload.remove(root)
} catch (err) {
} catch (/** @type {any} */err) {
console.error(`Remove failed: ${err.message ?? err}`)
console.error(err)
process.exit(1)
Expand All @@ -140,6 +147,7 @@ export async function remove (rootCid, opts) {
const { shards } = upload
console.log(`⁂ removing ${shards.length} shard${shards.length === 1 ? '' : 's'}`)

/** @param {import('@web3-storage/w3up-client/types').CARLink} shard */
function removeShard (shard) {
return oraPromise(client.capability.store.remove(shard), {
text: `${shard}`,
Expand All @@ -165,27 +173,30 @@ export async function createSpace (name) {
console.log(space.did())
}

/** @param {import('@web3-storage/w3up-client').Client} client */
function findAccountsThatCanProviderAdd (client) {
/** @type {Array<ReturnType<DidMailto.fromString>>} */
const accounts = []
const proofs = client.proofs()
for (const proof of proofs) {
const allows = ucanto.Delegation.allows(proof)
for (const resourceDID of Object.keys(allows)) {
if (resourceDID.startsWith('did:mailto:') && allows[resourceDID]['provider/add']) {
accounts.push(resourceDID)
accounts.push(DidMailto.fromString(resourceDID))
}
}
}
return accounts
}

/**
* @param {object} [opts]
* @param {string} [opts.email]
* @param {string} [opts.provider]
* @param {`did:web:${string}`} [opts.provider]
*/
export async function registerSpace (opts) {
const client = await getClient()
let accountEmail = opts.email
let accountEmail = opts?.email
if (!accountEmail) {
const accounts = findAccountsThatCanProviderAdd(client)
if (accounts.length === 1) {
Expand All @@ -208,8 +219,8 @@ export async function registerSpace (opts) {
const spinner = ora('registering your space').start()

try {
await client.registerSpace(accountEmail, { provider: opts.provider })
} catch (err) {
await client.registerSpace(accountEmail, { provider: opts?.provider })
} catch (/** @type {any} */err) {
if (spinner) spinner.stop()
if (err.message.startsWith('Space already registered')) {
console.error('Error: space already registered.')
Expand Down Expand Up @@ -260,7 +271,7 @@ export async function useSpace (did) {

/**
* @param {object} opts
* @param {string} [opts.space]
* @param {import('@web3-storage/w3up-client/types').DID} [opts.space]
* @param {string} [opts.json]
*/
export async function spaceInfo (opts) {
Expand All @@ -274,12 +285,14 @@ export async function spaceInfo (opts) {
if (opts.json) {
console.log(JSON.stringify(info, null, 4))
} else {
// @ts-expect-error https://github.com/web3-storage/w3up/pull/911
const providers = info.providers?.join(', ') ?? ''
console.log(`
DID: ${info.did}
Providers: ${info.providers?.join(', ') ?? ''}
Providers: ${providers}
`)
}
} catch (err) {
} catch (/** @type {any} */err) {
console.log(`Error getting info about ${spaceDID}: ${err.message}`)
}
}
Expand Down Expand Up @@ -356,23 +369,21 @@ export async function listDelegations (opts) {

/**
* @param {string} proofPath
* @param {object} opts
* @param {boolean} [opts.json]
* @param {boolean} [opts.dry-run]
* @param {{ json?: boolean, 'dry-run'?: boolean }} [opts]
*/
export async function addProof (proofPath, opts) {
const client = await getClient()
let proof
try {
proof = await readProof(proofPath)
if (!opts['dry-run']) {
if (!opts?.['dry-run']) {
await client.addProof(proof)
}
} catch (err) {
} catch (/** @type {any} */err) {
console.log(`Error: ${err.message}`)
process.exit(1)
}
if (opts.json) {
if (opts?.json) {
console.log(JSON.stringify(proof.toJSON()))
} else {
console.log(proof.cid.toString())
Expand Down
26 changes: 15 additions & 11 deletions lib.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
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'
Expand All @@ -13,16 +14,16 @@ import { CarReader } from '@ipld/car'

/**
* @typedef {import('@web3-storage/w3up-client/types').FileLike & { size: number }} FileLike
* @typedef {import('@web3-storage/w3up-client/types').ListResponse} ListResponse
* @typedef {import('@web3-storage/w3up-client/types').StoreListResult} StoreListResult
* @typedef {import('@web3-storage/w3up-client/types').UploadListResult} UploadListResult
* @typedef {import('@web3-storage/w3up-client/types').StoreListOk} StoreListOk
* @typedef {import('@web3-storage/w3up-client/types').UploadListOk} UploadListOk
*/

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) {
Expand All @@ -34,6 +35,7 @@ export function checkPathsExist (paths) {
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
Expand Down Expand Up @@ -75,6 +77,7 @@ export function getClient () {
}
}

/** @type {import('@web3-storage/w3up-client/types').ClientFactoryOptions} */
const createConfig = { store, serviceConf }

const principal = process.env.W3_PRINCIPAL
Expand All @@ -91,7 +94,7 @@ export function getClient () {
export async function readProof (path) {
try {
await fs.promises.access(path, fs.constants.R_OK)
} catch (err) {
} catch (/** @type {any} */err) {
console.error(`Error: failed to read proof: ${err.message}`)
process.exit(1)
}
Expand All @@ -102,22 +105,23 @@ export async function readProof (path) {
for await (const block of reader.blocks()) {
blocks.push(block)
}
} catch (err) {
} catch (/** @type {any} */err) {
console.error(`Error: failed to parse proof: ${err.message}`)
process.exit(1)
}

try {
// @ts-expect-error
return importDAG(blocks)
} catch (err) {
} catch (/** @type {any} */err) {
console.error(`Error: failed to import proof: ${err.message}`)
process.exit(1)
}
}

/**
* @param {ListResponse<UploadListResult>} res
* @param {UploadListOk} res
* @param {object} [opts]
* @param {boolean} [opts.raw]
* @param {boolean} [opts.json]
* @param {boolean} [opts.shards]
Expand All @@ -143,17 +147,17 @@ export function uploadListResponseToString (res, opts = {}) {
}

/**
* @param {ListResponse<StoreListResult>} res
* @param {StoreListOk} 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, insertedAt }) => JSON.stringify({
return res.results.map(({ link, size }) => JSON.stringify({
link: link.toString(),
size,
insertedAt
size
})).join('\n')
} else {
return res.results.map(({ link }) => link.toString()).join('\n')
Expand Down
Loading

0 comments on commit f829c42

Please sign in to comment.