From 27ae95c6d046431772c6fb43019ed64172b87cf4 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Fri, 13 Sep 2024 12:42:50 +0100 Subject: [PATCH] feat: add name property to errors Adds a `.name` property to all errors that can be used in a more ideomatic way than `.code`. --- packages/ipfs-unixfs-exporter/package.json | 1 - packages/ipfs-unixfs-exporter/src/errors.ts | 87 +++++++++++++++++++ packages/ipfs-unixfs-exporter/src/index.ts | 10 ++- .../src/resolvers/identity.ts | 4 +- .../src/resolvers/index.ts | 4 +- .../ipfs-unixfs-exporter/src/resolvers/raw.ts | 4 +- .../src/resolvers/unixfs-v1/content/file.ts | 14 +-- .../content/hamt-sharded-directory.ts | 8 +- .../src/resolvers/unixfs-v1/index.ts | 10 +-- .../src/utils/find-cid-in-shard.ts | 10 +-- .../src/utils/resolve-object-path.ts | 4 +- .../src/utils/validate-offset-and-length.ts | 10 +-- packages/ipfs-unixfs-importer/package.json | 1 - .../ipfs-unixfs-importer/src/chunker/rabin.ts | 8 +- .../src/dag-builder/index.ts | 6 +- .../src/dag-builder/validate-chunks.ts | 6 +- packages/ipfs-unixfs-importer/src/errors.ts | 54 ++++++++++++ packages/ipfs-unixfs-importer/src/index.ts | 6 +- packages/ipfs-unixfs/package.json | 1 - packages/ipfs-unixfs/src/errors.ts | 10 +++ packages/ipfs-unixfs/src/index.ts | 7 +- 21 files changed, 208 insertions(+), 57 deletions(-) create mode 100644 packages/ipfs-unixfs-exporter/src/errors.ts create mode 100644 packages/ipfs-unixfs-importer/src/errors.ts create mode 100644 packages/ipfs-unixfs/src/errors.ts diff --git a/packages/ipfs-unixfs-exporter/package.json b/packages/ipfs-unixfs-exporter/package.json index c007b0c0..32ee5c41 100644 --- a/packages/ipfs-unixfs-exporter/package.json +++ b/packages/ipfs-unixfs-exporter/package.json @@ -54,7 +54,6 @@ "@ipld/dag-json": "^10.2.0", "@ipld/dag-pb": "^4.1.0", "@multiformats/murmur3": "^2.1.8", - "err-code": "^3.0.1", "hamt-sharding": "^3.0.6", "interface-blockstore": "^5.2.10", "ipfs-unixfs": "^11.0.0", diff --git a/packages/ipfs-unixfs-exporter/src/errors.ts b/packages/ipfs-unixfs-exporter/src/errors.ts new file mode 100644 index 00000000..33ff7ee2 --- /dev/null +++ b/packages/ipfs-unixfs-exporter/src/errors.ts @@ -0,0 +1,87 @@ +export class BadPathError extends Error { + static name = 'BadPathError' + static code = 'ERR_BAD_PATH' + name = BadPathError.name + code = BadPathError.code + + constructor (message = 'Bad path') { + super(message) + } +} + +export class NotFoundError extends Error { + static name = 'NotFoundError' + static code = 'ERR_NOT_FOUND' + name = NotFoundError.name + code = NotFoundError.code + + constructor (message = 'Not found') { + super(message) + } +} + +export class NoResolverError extends Error { + static name = 'NoResolverError' + static code = 'ERR_NO_RESOLVER' + name = NoResolverError.name + code = NoResolverError.code + + constructor (message = 'No resolver') { + super(message) + } +} + +export class NotUnixFSError extends Error { + static name = 'NotUnixFSError' + static code = 'ERR_NOT_UNIXFS' + name = NotUnixFSError.name + code = NotUnixFSError.code + + constructor (message = 'Not UnixFS') { + super(message) + } +} + +export class OverReadError extends Error { + static name = 'OverReadError' + static code = 'ERR_OVER_READ' + name = OverReadError.name + code = OverReadError.code + + constructor (message = 'Over read') { + super(message) + } +} + +export class UnderReadError extends Error { + static name = 'UnderReadError' + static code = 'ERR_UNDER_READ' + name = UnderReadError.name + code = UnderReadError.code + + constructor (message = 'Under read') { + super(message) + } +} + +export class NoPropError extends Error { + static name = 'NoPropError' + static code = 'ERR_NO_PROP' + name = NoPropError.name + code = NoPropError.code + + constructor (message = 'No Property found') { + super(message) + } +} + +export class InvalidParametersError extends Error { + static name = 'InvalidParametersError' + static code = 'ERR_INVALID_PARAMS' + name = InvalidParametersError.name + code = InvalidParametersError.code + + constructor (message = 'Invalid parameters') { + super(message) + } +} diff --git a/packages/ipfs-unixfs-exporter/src/index.ts b/packages/ipfs-unixfs-exporter/src/index.ts index b1adc319..ead6279a 100644 --- a/packages/ipfs-unixfs-exporter/src/index.ts +++ b/packages/ipfs-unixfs-exporter/src/index.ts @@ -45,9 +45,9 @@ * ``` */ -import errCode from 'err-code' import last from 'it-last' import { CID } from 'multiformats/cid' +import { BadPathError, NotFoundError } from './errors.js' import resolve from './resolvers/index.js' import type { PBNode } from '@ipld/dag-pb' import type { Bucket } from 'hamt-sharding' @@ -55,6 +55,8 @@ import type { Blockstore } from 'interface-blockstore' import type { UnixFS } from 'ipfs-unixfs' import type { ProgressOptions, ProgressEvent } from 'progress-events' +export * from './errors.js' + export interface ExportProgress { /** * How many bytes of the file have been read @@ -361,7 +363,7 @@ const cidAndRest = (path: string | Uint8Array | CID): { cid: CID, toResolve: str } } - throw errCode(new Error(`Unknown path type ${path}`), 'ERR_BAD_PATH') + throw new BadPathError(`Unknown path type ${path}`) } /** @@ -394,7 +396,7 @@ export async function * walkPath (path: string | CID, blockstore: ReadableStorag const result = await resolve(cid, name, entryPath, toResolve, startingDepth, blockstore, options) if (result.entry == null && result.next == null) { - throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND') + throw new NotFoundError(`Could not resolve ${path}`) } if (result.entry != null) { @@ -441,7 +443,7 @@ export async function exporter (path: string | CID, blockstore: ReadableStorage, const result = await last(walkPath(path, blockstore, options)) if (result == null) { - throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND') + throw new NotFoundError(`Could not resolve ${path}`) } return result diff --git a/packages/ipfs-unixfs-exporter/src/resolvers/identity.ts b/packages/ipfs-unixfs-exporter/src/resolvers/identity.ts index 861e6dc7..0ce21223 100644 --- a/packages/ipfs-unixfs-exporter/src/resolvers/identity.ts +++ b/packages/ipfs-unixfs-exporter/src/resolvers/identity.ts @@ -1,6 +1,6 @@ -import errCode from 'err-code' import * as mh from 'multiformats/hashes/digest' import { CustomProgressEvent } from 'progress-events' +import { NotFoundError } from '../errors.js' import extractDataFromBlock from '../utils/extract-data-from-block.js' import validateOffsetAndLength from '../utils/validate-offset-and-length.js' import type { ExporterOptions, Resolver, ExportProgress } from '../index.js' @@ -28,7 +28,7 @@ const rawContent = (node: Uint8Array): ((options?: ExporterOptions) => AsyncGene const resolve: Resolver = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => { if (toResolve.length > 0) { - throw errCode(new Error(`No link named ${path} found in raw node ${cid}`), 'ERR_NOT_FOUND') + throw new NotFoundError(`No link named ${path} found in raw node ${cid}`) } const buf = mh.decode(cid.multihash.bytes) diff --git a/packages/ipfs-unixfs-exporter/src/resolvers/index.ts b/packages/ipfs-unixfs-exporter/src/resolvers/index.ts index c314fa67..099b8444 100644 --- a/packages/ipfs-unixfs-exporter/src/resolvers/index.ts +++ b/packages/ipfs-unixfs-exporter/src/resolvers/index.ts @@ -1,10 +1,10 @@ import * as dagCbor from '@ipld/dag-cbor' import * as dagJson from '@ipld/dag-json' import * as dagPb from '@ipld/dag-pb' -import errCode from 'err-code' import * as json from 'multiformats/codecs/json' import * as raw from 'multiformats/codecs/raw' import { identity } from 'multiformats/hashes/identity' +import { NoResolverError } from '../errors.js' import dagCborResolver from './dag-cbor.js' import dagJsonResolver from './dag-json.js' import identifyResolver from './identity.js' @@ -26,7 +26,7 @@ const resolve: Resolve = async (cid, name, path, toResolve, depth, blockstore, o const resolver = resolvers[cid.code] if (resolver == null) { - throw errCode(new Error(`No resolver for code ${cid.code}`), 'ERR_NO_RESOLVER') + throw new NoResolverError(`No resolver for code ${cid.code}`) } return resolver(cid, name, path, toResolve, resolve, depth, blockstore, options) diff --git a/packages/ipfs-unixfs-exporter/src/resolvers/raw.ts b/packages/ipfs-unixfs-exporter/src/resolvers/raw.ts index 7b5d2429..4082e388 100644 --- a/packages/ipfs-unixfs-exporter/src/resolvers/raw.ts +++ b/packages/ipfs-unixfs-exporter/src/resolvers/raw.ts @@ -1,5 +1,5 @@ -import errCode from 'err-code' import { CustomProgressEvent } from 'progress-events' +import { NotFoundError } from '../errors.js' import extractDataFromBlock from '../utils/extract-data-from-block.js' import validateOffsetAndLength from '../utils/validate-offset-and-length.js' import type { ExporterOptions, Resolver, ExportProgress } from '../index.js' @@ -27,7 +27,7 @@ const rawContent = (node: Uint8Array): ((options?: ExporterOptions) => AsyncGene const resolve: Resolver = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => { if (toResolve.length > 0) { - throw errCode(new Error(`No link named ${path} found in raw node ${cid}`), 'ERR_NOT_FOUND') + throw new NotFoundError(`No link named ${path} found in raw node ${cid}`) } const block = await blockstore.get(cid, options) diff --git a/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/file.ts b/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/file.ts index f65a449a..d88e1a24 100644 --- a/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/file.ts +++ b/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/file.ts @@ -1,5 +1,4 @@ import * as dagPb from '@ipld/dag-pb' -import errCode from 'err-code' import { UnixFS } from 'ipfs-unixfs' import map from 'it-map' import parallel from 'it-parallel' @@ -8,6 +7,7 @@ import { type Pushable, pushable } from 'it-pushable' import * as raw from 'multiformats/codecs/raw' import PQueue from 'p-queue' import { CustomProgressEvent } from 'progress-events' +import { NotUnixFSError, OverReadError, UnderReadError } from '../../../errors.js' import extractDataFromBlock from '../../../utils/extract-data-from-block.js' import validateOffsetAndLength from '../../../utils/validate-offset-and-length.js' import type { ExporterOptions, UnixfsV1FileContent, UnixfsV1Resolver, ReadableStorage, ExportProgress, ExportWalk } from '../../../index.js' @@ -23,7 +23,7 @@ async function walkDAG (blockstore: ReadableStorage, node: dagPb.PBNode | Uint8A } if (node.Data == null) { - throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('no data in PBNode') } let file: UnixFS @@ -31,7 +31,7 @@ async function walkDAG (blockstore: ReadableStorage, node: dagPb.PBNode | Uint8A try { file = UnixFS.unmarshal(node.Data) } catch (err: any) { - throw errCode(err, 'ERR_NOT_UNIXFS') + throw new NotUnixFSError(err.message) } // might be a unixfs `raw` node or have data on intermediate nodes @@ -47,7 +47,7 @@ async function walkDAG (blockstore: ReadableStorage, node: dagPb.PBNode | Uint8A const childOps: Array<{ link: dagPb.PBLink, blockStart: bigint }> = [] if (node.Links.length !== file.blockSizes.length) { - throw errCode(new Error('Inconsistent block sizes and dag links'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('Inconsistent block sizes and dag links') } for (let i = 0; i < node.Links.length; i++) { @@ -98,7 +98,7 @@ async function walkDAG (blockstore: ReadableStorage, node: dagPb.PBNode | Uint8A child = block break default: - queue.end(errCode(new Error(`Unsupported codec: ${link.Hash.code}`), 'ERR_NOT_UNIXFS')) + queue.end(new NotUnixFSError(`Unsupported codec: ${link.Hash.code}`)) return } @@ -171,7 +171,7 @@ const fileContent: UnixfsV1Resolver = (cid, node, unixfs, path, resolve, depth, if (read > wanted) { queue.end() - throw errCode(new Error('Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect'), 'ERR_OVER_READ') + throw new OverReadError('Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect') } if (read === wanted) { @@ -188,7 +188,7 @@ const fileContent: UnixfsV1Resolver = (cid, node, unixfs, path, resolve, depth, } if (read < wanted) { - throw errCode(new Error('Traversed entire DAG but did not read enough bytes'), 'ERR_UNDER_READ') + throw new UnderReadError('Traversed entire DAG but did not read enough bytes') } } diff --git a/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/hamt-sharded-directory.ts b/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/hamt-sharded-directory.ts index 1c482c68..52c2938d 100644 --- a/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/hamt-sharded-directory.ts +++ b/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/hamt-sharded-directory.ts @@ -1,10 +1,10 @@ import { decode, type PBNode } from '@ipld/dag-pb' -import errCode from 'err-code' import { UnixFS } from 'ipfs-unixfs' import map from 'it-map' import parallel from 'it-parallel' import { pipe } from 'it-pipe' import { CustomProgressEvent } from 'progress-events' +import { NotUnixFSError } from '../../../errors.js' import type { ExporterOptions, Resolve, UnixfsV1DirectoryContent, UnixfsV1Resolver, ReadableStorage, ExportWalk } from '../../../index.js' const hamtShardedDirectoryContent: UnixfsV1Resolver = (cid, node, unixfs, path, resolve, depth, blockstore) => { @@ -23,18 +23,18 @@ async function * listDirectory (node: PBNode, path: string, resolve: Resolve, de const links = node.Links if (node.Data == null) { - throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('no data in PBNode') } let dir: UnixFS try { dir = UnixFS.unmarshal(node.Data) } catch (err: any) { - throw errCode(err, 'ERR_NOT_UNIXFS') + throw new NotUnixFSError(err.message) } if (dir.fanout == null) { - throw errCode(new Error('missing fanout'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('missing fanout') } const padLength = (dir.fanout - 1n).toString(16).length diff --git a/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/index.ts b/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/index.ts index 148ac81f..2ed6c6a0 100644 --- a/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/index.ts +++ b/packages/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/index.ts @@ -1,6 +1,6 @@ import { decode, type PBNode } from '@ipld/dag-pb' -import errCode from 'err-code' import { UnixFS } from 'ipfs-unixfs' +import { NotFoundError, NotUnixFSError } from '../../errors.js' import findShardCid from '../../utils/find-cid-in-shard.js' import contentDirectory from './content/directory.js' import contentFile from './content/file.js' @@ -39,14 +39,14 @@ const unixFsResolver: Resolver = async (cid, name, path, toResolve, resolve, dep } if (node.Data == null) { - throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('no data in PBNode') } try { unixfs = UnixFS.unmarshal(node.Data) } catch (err: any) { // non-UnixFS dag-pb node? It could happen. - throw errCode(err, 'ERR_NOT_UNIXFS') + throw new NotUnixFSError(err.message) } if (path == null) { @@ -64,7 +64,7 @@ const unixFsResolver: Resolver = async (cid, name, path, toResolve, resolve, dep } if (linkCid == null) { - throw errCode(new Error('file does not exist'), 'ERR_NOT_FOUND') + throw new NotFoundError('file does not exist') } // remove the path component we have resolved @@ -82,7 +82,7 @@ const unixFsResolver: Resolver = async (cid, name, path, toResolve, resolve, dep const content = contentExporters[unixfs.type](cid, node, unixfs, path, resolve, depth, blockstore) if (content == null) { - throw errCode(new Error('could not find content exporter'), 'ERR_NOT_FOUND') + throw new NotFoundError('could not find content exporter') } if (unixfs.isDirectory()) { diff --git a/packages/ipfs-unixfs-exporter/src/utils/find-cid-in-shard.ts b/packages/ipfs-unixfs-exporter/src/utils/find-cid-in-shard.ts index 13346bf7..d3446ddd 100644 --- a/packages/ipfs-unixfs-exporter/src/utils/find-cid-in-shard.ts +++ b/packages/ipfs-unixfs-exporter/src/utils/find-cid-in-shard.ts @@ -1,8 +1,8 @@ import { decode, type PBLink, type PBNode } from '@ipld/dag-pb' import { murmur3128 } from '@multiformats/murmur3' -import errCode from 'err-code' import { Bucket, type BucketPosition, createHAMT } from 'hamt-sharding' import { UnixFS } from 'ipfs-unixfs' +import { NotUnixFSError } from '../errors.js' import type { ExporterOptions, ShardTraversalContext, ReadableStorage } from '../index.js' import type { CID } from 'multiformats/cid' @@ -66,21 +66,21 @@ const toBucketPath = (position: BucketPosition): Array> const findShardCid = async (node: PBNode, name: string, blockstore: ReadableStorage, context?: ShardTraversalContext, options?: ExporterOptions): Promise => { if (context == null) { if (node.Data == null) { - throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('no data in PBNode') } let dir: UnixFS try { dir = UnixFS.unmarshal(node.Data) } catch (err: any) { - throw errCode(err, 'ERR_NOT_UNIXFS') + throw new NotUnixFSError(err.message) } if (dir.type !== 'hamt-sharded-directory') { - throw errCode(new Error('not a HAMT'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('not a HAMT') } if (dir.fanout == null) { - throw errCode(new Error('missing fanout'), 'ERR_NOT_UNIXFS') + throw new NotUnixFSError('missing fanout') } const rootBucket = createHAMT({ diff --git a/packages/ipfs-unixfs-exporter/src/utils/resolve-object-path.ts b/packages/ipfs-unixfs-exporter/src/utils/resolve-object-path.ts index addb7066..b17f1ebc 100644 --- a/packages/ipfs-unixfs-exporter/src/utils/resolve-object-path.ts +++ b/packages/ipfs-unixfs-exporter/src/utils/resolve-object-path.ts @@ -1,5 +1,5 @@ -import errCode from 'err-code' import { CID } from 'multiformats/cid' +import { NoPropError } from '../errors.js' import type { ResolveResult } from '../index.js' export function resolveObjectPath (object: any, block: Uint8Array, cid: CID, name: string, path: string, toResolve: string[], depth: number): ResolveResult { @@ -41,7 +41,7 @@ export function resolveObjectPath (object: any, block: Uint8Array, cid: CID, nam subObject = subObject[prop] } else { // cannot resolve further - throw errCode(new Error(`No property named ${prop} found in node ${cid}`), 'ERR_NO_PROP') + throw new NoPropError(`No property named ${prop} found in node ${cid}`) } } diff --git a/packages/ipfs-unixfs-exporter/src/utils/validate-offset-and-length.ts b/packages/ipfs-unixfs-exporter/src/utils/validate-offset-and-length.ts index da6d9427..ca3e073a 100644 --- a/packages/ipfs-unixfs-exporter/src/utils/validate-offset-and-length.ts +++ b/packages/ipfs-unixfs-exporter/src/utils/validate-offset-and-length.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { InvalidParametersError } from '../errors.js' const validateOffsetAndLength = (size: number | bigint, offset: number | bigint = 0, length: number | bigint = size): { start: bigint, end: bigint } => { const fileSize = BigInt(size) @@ -14,19 +14,19 @@ const validateOffsetAndLength = (size: number | bigint, offset: number | bigint } if (start < 0n) { - throw errCode(new Error('Offset must be greater than or equal to 0'), 'ERR_INVALID_PARAMS') + throw new InvalidParametersError('Offset must be greater than or equal to 0') } if (start > fileSize) { - throw errCode(new Error('Offset must be less than the file size'), 'ERR_INVALID_PARAMS') + throw new InvalidParametersError('Offset must be less than the file size') } if (end < 0n) { - throw errCode(new Error('Length must be greater than or equal to 0'), 'ERR_INVALID_PARAMS') + throw new InvalidParametersError('Length must be greater than or equal to 0') } if (end > fileSize) { - throw errCode(new Error('Length must be less than the file size'), 'ERR_INVALID_PARAMS') + throw new InvalidParametersError('Length must be less than the file size') } return { diff --git a/packages/ipfs-unixfs-importer/package.json b/packages/ipfs-unixfs-importer/package.json index cb8af317..7aaf1ef5 100644 --- a/packages/ipfs-unixfs-importer/package.json +++ b/packages/ipfs-unixfs-importer/package.json @@ -76,7 +76,6 @@ "dependencies": { "@ipld/dag-pb": "^4.1.0", "@multiformats/murmur3": "^2.1.8", - "err-code": "^3.0.1", "hamt-sharding": "^3.0.6", "interface-blockstore": "^5.2.10", "interface-store": "^5.1.8", diff --git a/packages/ipfs-unixfs-importer/src/chunker/rabin.ts b/packages/ipfs-unixfs-importer/src/chunker/rabin.ts index a64defdb..d491f04e 100644 --- a/packages/ipfs-unixfs-importer/src/chunker/rabin.ts +++ b/packages/ipfs-unixfs-importer/src/chunker/rabin.ts @@ -1,7 +1,7 @@ -import errcode from 'err-code' // @ts-expect-error no types import { create } from 'rabin-wasm' import { Uint8ArrayList } from 'uint8arraylist' +import { InvalidAvgChunkSizeError, InvalidChunkSizeError, InvalidMinChunkSizeError } from '../errors.js' import type { Chunker } from './index.js' const DEFAULT_MIN_CHUNK_SIZE = 262144 @@ -54,15 +54,15 @@ export const rabin = (options: RabinOptions = {}): Chunker => { if (isInvalidChunkSizes) { if (options.avgChunkSize != null) { - throw errcode(new Error('please specify a valid average chunk size number'), 'ERR_INVALID_AVG_CHUNK_SIZE') + throw new InvalidAvgChunkSizeError('please specify a valid average chunk size number') } - throw errcode(new Error('please specify valid numbers for (min|max|avg)ChunkSize'), 'ERR_INVALID_CHUNK_SIZE') + throw new InvalidChunkSizeError('please specify valid numbers for (min|max|avg)ChunkSize') } // validate min/max/avg in the same way as go if (min < 16) { - throw errcode(new Error('rabin min must be greater than 16'), 'ERR_INVALID_MIN_CHUNK_SIZE') + throw new InvalidMinChunkSizeError('rabin min must be greater than 16') } if (max < min) { diff --git a/packages/ipfs-unixfs-importer/src/dag-builder/index.ts b/packages/ipfs-unixfs-importer/src/dag-builder/index.ts index 1559b86a..b9bfe8f6 100644 --- a/packages/ipfs-unixfs-importer/src/dag-builder/index.ts +++ b/packages/ipfs-unixfs-importer/src/dag-builder/index.ts @@ -1,5 +1,5 @@ -import errCode from 'err-code' import { CustomProgressEvent } from 'progress-events' +import { InvalidContentError } from '../errors.js' import { dirBuilder, type DirBuilderOptions } from './dir.js' import { fileBuilder, type FileBuilderOptions } from './file.js' import type { ChunkValidator } from './validate-chunks.js' @@ -52,10 +52,10 @@ function contentAsAsyncIterable (content: Uint8Array | AsyncIterable return content } } catch { - throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT') + throw new InvalidContentError('Content was invalid') } - throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT') + throw new InvalidContentError('Content was invalid') } export interface DagBuilderOptions extends FileBuilderOptions, DirBuilderOptions, ProgressOptions { diff --git a/packages/ipfs-unixfs-importer/src/dag-builder/validate-chunks.ts b/packages/ipfs-unixfs-importer/src/dag-builder/validate-chunks.ts index d01e0628..c1e3ea01 100644 --- a/packages/ipfs-unixfs-importer/src/dag-builder/validate-chunks.ts +++ b/packages/ipfs-unixfs-importer/src/dag-builder/validate-chunks.ts @@ -1,5 +1,5 @@ -import errCode from 'err-code' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' +import { InvalidContentError } from '../errors.js' export interface ChunkValidator { (source: AsyncIterable): AsyncIterable } @@ -7,7 +7,7 @@ export const defaultChunkValidator = (): ChunkValidator => { return async function * validateChunks (source) { for await (const content of source) { if (content.length === undefined) { - throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT') + throw new InvalidContentError('Content was invalid') } if (typeof content === 'string' || content instanceof String) { @@ -17,7 +17,7 @@ export const defaultChunkValidator = (): ChunkValidator => { } else if (content instanceof Uint8Array) { yield content } else { - throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT') + throw new InvalidContentError('Content was invalid') } } } diff --git a/packages/ipfs-unixfs-importer/src/errors.ts b/packages/ipfs-unixfs-importer/src/errors.ts new file mode 100644 index 00000000..a8facda8 --- /dev/null +++ b/packages/ipfs-unixfs-importer/src/errors.ts @@ -0,0 +1,54 @@ +export class InvalidParametersError extends Error { + static name = 'InvalidParametersError' + static code = 'ERR_INVALID_PARAMS' + name = InvalidParametersError.name + code = InvalidParametersError.code + + constructor (message = 'Invalid parameters') { + super(message) + } +} + +export class InvalidAvgChunkSizeError extends Error { + static name = 'InvalidAvgChunkSizeError' + static code = 'ERR_INVALID_AVG_CHUNK_SIZE' + name = InvalidAvgChunkSizeError.name + code = InvalidAvgChunkSizeError.code + + constructor (message = 'Invalid avg chunk size') { + super(message) + } +} + +export class InvalidChunkSizeError extends Error { + static name = 'InvalidChunkSizeError' + static code = 'ERR_INVALID_CHUNK_SIZE' + name = InvalidChunkSizeError.name + code = InvalidChunkSizeError.code + + constructor (message = 'Invalid chunk size') { + super(message) + } +} + +export class InvalidMinChunkSizeError extends Error { + static name = 'InvalidMinChunkSizeError' + static code = 'ERR_INVALID_MIN_CHUNK_SIZE' + name = InvalidMinChunkSizeError.name + code = InvalidMinChunkSizeError.code + + constructor (message = 'Invalid min chunk size') { + super(message) + } +} + +export class InvalidContentError extends Error { + static name = 'InvalidContentError' + static code = 'ERR_INVALID_CONTENT' + name = InvalidContentError.name + code = InvalidContentError.code + + constructor (message = 'Invalid content') { + super(message) + } +} diff --git a/packages/ipfs-unixfs-importer/src/index.ts b/packages/ipfs-unixfs-importer/src/index.ts index aa4c3243..21f4d289 100644 --- a/packages/ipfs-unixfs-importer/src/index.ts +++ b/packages/ipfs-unixfs-importer/src/index.ts @@ -62,13 +62,13 @@ * ``` */ -import errcode from 'err-code' import first from 'it-first' import parallelBatch from 'it-parallel-batch' import { fixedSize } from './chunker/fixed-size.js' import { type BufferImportProgressEvents, defaultBufferImporter } from './dag-builder/buffer-importer.js' import { type DAGBuilder, type DagBuilderProgressEvents, defaultDagBuilder } from './dag-builder/index.js' import { type ChunkValidator, defaultChunkValidator } from './dag-builder/validate-chunks.js' +import { InvalidParametersError } from './errors.js' import { balanced, type FileLayout } from './layout/index.js' import { defaultTreeBuilder } from './tree-builder.js' import type { Chunker } from './chunker/index.js' @@ -382,7 +382,7 @@ export async function importFile (content: FileCandidate, blockstore: WritableSt const result = await first(importer([content], blockstore, options)) if (result == null) { - throw errcode(new Error('Nothing imported'), 'ERR_INVALID_PARAMS') + throw new InvalidParametersError('Nothing imported') } return result @@ -413,7 +413,7 @@ export async function importDirectory (content: DirectoryCandidate, blockstore: const result = await first(importer([content], blockstore, options)) if (result == null) { - throw errcode(new Error('Nothing imported'), 'ERR_INVALID_PARAMS') + throw new InvalidParametersError('Nothing imported') } return result diff --git a/packages/ipfs-unixfs/package.json b/packages/ipfs-unixfs/package.json index fdeb9c62..258de478 100644 --- a/packages/ipfs-unixfs/package.json +++ b/packages/ipfs-unixfs/package.json @@ -54,7 +54,6 @@ "dep-check": "aegir dep-check" }, "dependencies": { - "err-code": "^3.0.1", "protons-runtime": "^5.4.0", "uint8arraylist": "^2.4.8" }, diff --git a/packages/ipfs-unixfs/src/errors.ts b/packages/ipfs-unixfs/src/errors.ts new file mode 100644 index 00000000..949caf24 --- /dev/null +++ b/packages/ipfs-unixfs/src/errors.ts @@ -0,0 +1,10 @@ +export class InvalidTypeError extends Error { + static name = 'InvalidTypeError' + static code = 'ERR_INVALID_TYPE' + name = InvalidTypeError.name + code = InvalidTypeError.code + + constructor (message = 'Invalid type') { + super(message) + } +} diff --git a/packages/ipfs-unixfs/src/index.ts b/packages/ipfs-unixfs/src/index.ts index b6263d64..8cc1ad72 100644 --- a/packages/ipfs-unixfs/src/index.ts +++ b/packages/ipfs-unixfs/src/index.ts @@ -90,7 +90,7 @@ * ``` */ -import errcode from 'err-code' +import { InvalidTypeError } from './errors.js' import { Data as PBData } from './unixfs.js' export interface Mtime { @@ -178,7 +178,7 @@ class UnixFS { } = options if (type != null && !Object.values(types).includes(type)) { - throw errcode(new Error('Type: ' + type + ' is not valid'), 'ERR_INVALID_TYPE') + throw new InvalidTypeError('Type: ' + type + ' is not valid') } this.type = type ?? 'file' @@ -250,7 +250,7 @@ class UnixFS { case 'symlink': type = PBData.DataType.Symlink; break case 'hamt-sharded-directory': type = PBData.DataType.HAMTShard; break default: - throw errcode(new Error(`Type: ${type} is not valid`), 'ERR_INVALID_TYPE') + throw new InvalidTypeError(`Type: ${type} is not valid`) } let data = this.data @@ -296,3 +296,4 @@ class UnixFS { } export { UnixFS } +export * from './errors.js'