@atproto/lex-data 0.0.11 → 0.0.13
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/CHANGELOG.md +14 -0
- package/dist/cid.d.ts +3 -3
- package/dist/cid.d.ts.map +1 -1
- package/dist/cid.js +11 -13
- package/dist/cid.js.map +1 -1
- package/dist/lex-error.d.ts +7 -34
- package/dist/lex-error.d.ts.map +1 -1
- package/dist/lex-error.js +6 -35
- package/dist/lex-error.js.map +1 -1
- package/dist/lex.d.ts.map +1 -1
- package/dist/lex.js +14 -34
- package/dist/lex.js.map +1 -1
- package/dist/lib/util.d.ts +3 -0
- package/dist/lib/util.d.ts.map +1 -0
- package/dist/lib/util.js +11 -0
- package/dist/lib/util.js.map +1 -0
- package/package.json +1 -1
- package/src/cid.ts +22 -18
- package/src/lex-error.test.ts +54 -0
- package/src/lex-error.ts +7 -37
- package/src/lex.test.ts +3 -3
- package/src/lex.ts +11 -29
- package/src/lib/util.test.ts +49 -0
- package/src/lib/util.ts +7 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @atproto/lex-data
|
|
2
2
|
|
|
3
|
+
## 0.0.13
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#4688](https://github.com/bluesky-social/atproto/pull/4688) [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Remove concept of "downstream error response" (`toResponse()` method) from the `LexError` class
|
|
8
|
+
|
|
9
|
+
- [#4688](https://github.com/bluesky-social/atproto/pull/4688) [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Improve messaging of various errors by making them more precisely describe what happened.
|
|
10
|
+
|
|
11
|
+
## 0.0.12
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- [#4660](https://github.com/bluesky-social/atproto/pull/4660) [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Minor code simplification
|
|
16
|
+
|
|
3
17
|
## 0.0.11
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/dist/cid.d.ts
CHANGED
|
@@ -201,7 +201,7 @@ export type CheckCidOptions = {
|
|
|
201
201
|
*
|
|
202
202
|
* @typeParam TOptions - The options used for checking
|
|
203
203
|
*/
|
|
204
|
-
export type InferCheckedCid<TOptions> = TOptions extends {
|
|
204
|
+
export type InferCheckedCid<TOptions extends CheckCidOptions> = TOptions extends {
|
|
205
205
|
flavor: 'raw';
|
|
206
206
|
} ? RawCid : TOptions extends {
|
|
207
207
|
flavor: 'cbor';
|
|
@@ -229,7 +229,7 @@ export declare function ifCid<TValue>(value: TValue, options?: CheckCidOptions):
|
|
|
229
229
|
* @throws if the input is not a valid {@link Cid}.
|
|
230
230
|
*/
|
|
231
231
|
export declare function asCid<TValue, TOptions extends CheckCidOptions>(value: TValue, options: TOptions): TValue & InferCheckedCid<TOptions>;
|
|
232
|
-
export declare function asCid<TValue>(value: TValue, options?: CheckCidOptions):
|
|
232
|
+
export declare function asCid<TValue>(value: TValue, options?: CheckCidOptions): TValue & Cid;
|
|
233
233
|
/**
|
|
234
234
|
* Decodes a CID from its binary representation.
|
|
235
235
|
*
|
|
@@ -329,7 +329,7 @@ export declare function cidForRawBytes(bytes: Uint8Array): Promise<RawCid>;
|
|
|
329
329
|
*
|
|
330
330
|
* @param digest - The SHA-256 hash digest (must be 32 bytes)
|
|
331
331
|
* @returns A RawCid with the given digest
|
|
332
|
-
* @throws If the digest
|
|
332
|
+
* @throws If the digest is not a valid SHA-256 hash (not 32 bytes)
|
|
333
333
|
*/
|
|
334
334
|
export declare function cidForRawHash(digest: Uint8Array): RawCid;
|
|
335
335
|
//# sourceMappingURL=cid.d.ts.map
|
package/dist/cid.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cid.d.ts","sourceRoot":"","sources":["../src/cid.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;
|
|
1
|
+
{"version":3,"file":"cid.d.ts","sourceRoot":"","sources":["../src/cid.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAOtC;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,MAAO,CAAA;AACnC,MAAM,MAAM,eAAe,GAAG,OAAO,eAAe,CAAA;AAEpD;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,KAAO,CAAA;AAClC,MAAM,MAAM,cAAc,GAAG,OAAO,cAAc,CAAA;AAElD;;GAEG;AACH,eAAO,MAAM,gBAAgB,IAAc,CAAA;AAC3C,MAAM,MAAM,gBAAgB,GAAG,OAAO,gBAAgB,CAAA;AAEtD;;GAEG;AACH,eAAO,MAAM,gBAAgB,IAAc,CAAA;AAC3C,MAAM,MAAM,gBAAgB,GAAG,OAAO,gBAAgB,CAAA;AAEtD;;;;;GAKG;AACH,MAAM,WAAW,SAAS,CAAC,SAAS,SAAS,MAAM,GAAG,MAAM;IAC1D;;OAEG;IACH,IAAI,EAAE,SAAS,CAAA;IAEf;;OAEG;IACH,MAAM,EAAE,UAAU,CAAA;CACnB;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,SAAS,GAAG,OAAO,CAGnE;AAED,OAAO,QAAQ,kBAAkB,CAAC;IAChC;;;;;;;;;;;;;;;;;;OAkBG;IACH,UAAU,GAAG;KAAG;CACjB;AAqBD,OAAO,EAAE,kBAAkB,CAAC,GAAG,EAAE,CAAA;AAEjC;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,SAAS,CAAC,GAA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,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,eAAe,GACxB,GAAG,GAAG,IAAI,CAAA;AAYb;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,eAAe,GACxB,IAAI,CAIN;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CACjC,GAAG,EAAE,GAAG,EACR,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,OAAO,CAAC,CAelB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,MAAM,SAAS,MAAM,EAAE,SAAS,SAAS,MAAM,EACvE,IAAI,EAAE,MAAM,EACZ,aAAa,EAAE,SAAS,EACxB,MAAM,EAAE,UAAU,GAGJ,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,CACxC;AAED;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAGpE;AAED;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAGvE;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAQxD"}
|
package/dist/cid.js
CHANGED
|
@@ -24,6 +24,7 @@ const cid_1 = require("multiformats/cid");
|
|
|
24
24
|
Object.defineProperty(exports, "CID", { enumerable: true, get: function () { return cid_1.CID; } });
|
|
25
25
|
const digest_1 = require("multiformats/hashes/digest");
|
|
26
26
|
const sha2_1 = require("multiformats/hashes/sha2");
|
|
27
|
+
const util_js_1 = require("./lib/util.js");
|
|
27
28
|
const object_js_1 = require("./object.js");
|
|
28
29
|
const uint8array_js_1 = require("./uint8array.js");
|
|
29
30
|
/**
|
|
@@ -131,14 +132,14 @@ function isCid(value, options) {
|
|
|
131
132
|
return isCidImplementation(value) && checkCid(value, options);
|
|
132
133
|
}
|
|
133
134
|
function ifCid(value, options) {
|
|
134
|
-
if (
|
|
135
|
+
if (isCid(value, options))
|
|
135
136
|
return value;
|
|
136
137
|
return null;
|
|
137
138
|
}
|
|
138
139
|
function asCid(value, options) {
|
|
139
|
-
if (
|
|
140
|
+
if (isCid(value, options))
|
|
140
141
|
return value;
|
|
141
|
-
throw new Error(
|
|
142
|
+
throw new Error(`Invalid ${options?.flavor ? `${options.flavor} CID` : 'CID'} "${value}"`);
|
|
142
143
|
}
|
|
143
144
|
function decodeCid(cidBytes, options) {
|
|
144
145
|
const cid = cid_1.CID.decode(cidBytes);
|
|
@@ -178,7 +179,7 @@ function parseCidSafe(input, options) {
|
|
|
178
179
|
*/
|
|
179
180
|
function ensureValidCidString(input, options) {
|
|
180
181
|
if (!validateCidString(input, options)) {
|
|
181
|
-
throw new Error(`Invalid CID string`);
|
|
182
|
+
throw new Error(`Invalid CID string "${input}"`);
|
|
182
183
|
}
|
|
183
184
|
}
|
|
184
185
|
/**
|
|
@@ -197,7 +198,7 @@ async function isCidForBytes(cid, bytes) {
|
|
|
197
198
|
return multihashEquals(multihash, cid.multihash);
|
|
198
199
|
}
|
|
199
200
|
// Don't know how to verify other multihash codes
|
|
200
|
-
throw new Error(
|
|
201
|
+
throw new Error(`Unsupported CID multihash code: ${(0, util_js_1.toHexString)(cid.multihash.code)}`);
|
|
201
202
|
}
|
|
202
203
|
/**
|
|
203
204
|
* Creates a CID from a multicodec, multihash code, and digest.
|
|
@@ -247,12 +248,12 @@ async function cidForRawBytes(bytes) {
|
|
|
247
248
|
*
|
|
248
249
|
* @param digest - The SHA-256 hash digest (must be 32 bytes)
|
|
249
250
|
* @returns A RawCid with the given digest
|
|
250
|
-
* @throws If the digest
|
|
251
|
+
* @throws If the digest is not a valid SHA-256 hash (not 32 bytes)
|
|
251
252
|
*/
|
|
252
253
|
function cidForRawHash(digest) {
|
|
253
254
|
// Fool-proofing
|
|
254
|
-
if (digest.length !==
|
|
255
|
-
throw new Error(`Invalid SHA-256 hash length: ${digest.length}`);
|
|
255
|
+
if (digest.length !== 0x20) {
|
|
256
|
+
throw new Error(`Invalid SHA-256 hash length: ${(0, util_js_1.toHexString)(digest.length)}`);
|
|
256
257
|
}
|
|
257
258
|
return createCid(exports.RAW_DATA_CODEC, sha2_1.sha256.code, digest);
|
|
258
259
|
}
|
|
@@ -270,12 +271,12 @@ function isCidImplementation(value) {
|
|
|
270
271
|
const val = value;
|
|
271
272
|
if (val.version !== 0 && val.version !== 1)
|
|
272
273
|
return false;
|
|
273
|
-
if (!isUint8(val.code))
|
|
274
|
+
if (!(0, util_js_1.isUint8)(val.code))
|
|
274
275
|
return false;
|
|
275
276
|
if (!(0, object_js_1.isObject)(val.multihash))
|
|
276
277
|
return false;
|
|
277
278
|
const mh = val.multihash;
|
|
278
|
-
if (!isUint8(mh.code))
|
|
279
|
+
if (!(0, util_js_1.isUint8)(mh.code))
|
|
279
280
|
return false;
|
|
280
281
|
if (!(mh.digest instanceof Uint8Array))
|
|
281
282
|
return false;
|
|
@@ -305,7 +306,4 @@ function isCidImplementation(value) {
|
|
|
305
306
|
}
|
|
306
307
|
}
|
|
307
308
|
}
|
|
308
|
-
function isUint8(val) {
|
|
309
|
-
return Number.isInteger(val) && val >= 0 && val < 256;
|
|
310
|
-
}
|
|
311
309
|
//# sourceMappingURL=cid.js.map
|
package/dist/cid.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cid.js","sourceRoot":"","sources":["../src/cid.ts"],"names":[],"mappings":";;;AA+DA,0CAGC;AAsDD,8CAoBC;AAkFD,4BAEC;AAkBD,8BAOC;AAiBD,8BAEC;AAmCD,4BAaC;AAWD,sBAEC;AAaD,sBAGC;AAeD,sBAGC;AAaD,8BAMC;AAYD,4BAGC;AAYD,8CAKC;AA2BD,oCASC;AASD,oDAOC;AAQD,sCAgBC;AAiBD,8BAOC;AAUD,gCAGC;AAUD,wCAGC;AASD,sCAMC;AA3iBD,0CAAsC;AA8GV,o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OAAO,KAAK,CAAA;YAC3C,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,IAAI;gBAAE,OAAO,KAAK,CAAA;YAC1C,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,MAAM,CAAC,MAAM;gBAAE,OAAO,KAAK,CAAA;YACnD,IAAI,GAAG,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM;gBAAE,OAAO,KAAK,CAAA;YAC3D,IAAI,CAAC,IAAA,yBAAS,EAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC;gBAAE,OAAO,KAAK,CAAA;YAE9D,IAAI,OAAO,GAAG,CAAC,MAAM,KAAK,UAAU;gBAAE,OAAO,KAAK,CAAA;YAClD,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI;gBAAE,OAAO,KAAK,CAAA;YAE1C,OAAO,IAAI,CAAA;QACb,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,OAAO,CAAC,GAAY;IAC3B,OAAO,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,IAAK,GAAc,IAAI,CAAC,IAAK,GAAc,GAAG,GAAG,CAAA;AAC/E,CAAC","sourcesContent":["import { CID } from 'multiformats/cid'\nimport { create as createDigest } from 'multiformats/hashes/digest'\nimport { sha256, sha512 } from 'multiformats/hashes/sha2'\nimport { isObject } from './object.js'\nimport { ui8Equals } from './uint8array.js'\n\n/**\n * Codec code that indicates the CID references a CBOR-encoded data structure.\n *\n * Used when encoding structured data in AT Protocol repositories.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport const CBOR_DATA_CODEC = 0x71\nexport type CBOR_DATA_CODEC = typeof CBOR_DATA_CODEC\n\n/**\n * Codec code that indicates the CID references raw binary data (like media blobs).\n *\n * Used in DASL CIDs for binary blobs like images and media.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport const RAW_DATA_CODEC = 0x55\nexport type RAW_DATA_CODEC = typeof RAW_DATA_CODEC\n\n/**\n * Hash code that indicates that a CID uses SHA-256.\n */\nexport const SHA256_HASH_CODE = sha256.code\nexport type SHA256_HASH_CODE = typeof SHA256_HASH_CODE\n\n/**\n * Hash code that indicates that a CID uses SHA-512.\n */\nexport const SHA512_HASH_CODE = sha512.code\nexport type SHA512_HASH_CODE = typeof SHA512_HASH_CODE\n\n/**\n * Represent the hash part of a CID, which includes the hash algorithm code and\n * the raw digest bytes.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport interface Multihash<THashCode extends number = number> {\n /**\n * Code of the hash algorithm (e.g., SHA256_HASH_CODE).\n */\n code: THashCode\n\n /**\n * Raw digest bytes.\n */\n digest: Uint8Array\n}\n\n/**\n * Compares two {@link Multihash} for equality.\n *\n * @param a - First {@link Multihash}\n * @param b - Second {@link Multihash}\n * @returns `true` if both multihashes have the same code and digest\n */\nexport function multihashEquals(a: Multihash, b: Multihash): boolean {\n if (a === b) return true\n return a.code === b.code && ui8Equals(a.digest, b.digest)\n}\n\ndeclare module 'multiformats/cid' {\n /**\n * @deprecated use the {@link Cid} interface from `@atproto/lex-data`, and\n * related helpers ({@link isCid}, {@link ifCid}, {@link asCid},\n * {@link parseCid}, {@link decodeCid}), instead.\n *\n * This is marked as deprecated because we want to discourage direct usage of\n * `multiformats/cid` in dependent packages, and instead have them rely on the\n * {@link Cid} interface from `@atproto/lex-data`. The {@link CID} class from\n * `multiformats` version <10 has compatibility issues with certain TypeScript\n * configuration, which can lead to type errors in dependent packages.\n *\n * We are stuck with version 9 because `@atproto` packages did not drop\n * CommonJS support yet, and multiformats version 10 only supports ES modules.\n *\n * In order to avoid compatibility issues, while preparing for future breaking\n * changes (CID in multiformats v10+ has a slightly different interface), as\n * we update or swap out `multiformats`, `@atproto/lex-data` provides its own\n * stable {@link Cid} interface.\n */\n interface CID {}\n}\n\n// multiformats' CID class is not very portable because:\n//\n// - In dependent packages that use \"moduleResolution\" set to \"node16\",\n// \"nodenext\" or \"bundler\", TypeScript fails to properly resolve the\n// multiformats package when importing CID from @atproto/lex-data. This causes\n// type errors in those packages. This is caused by the fact that the\n// multiformats version <10 (which is the last version that supports CommonJS)\n// uses \"exports\" field in package.json, which do not contain \"types\"\n// entrypoints.\n// https://www.npmjs.com/package/multiformats/v/9.9.0?activeTab=code\n// - By defining our own interface and helper functions, we can have more\n// control over the public API exposed by this package.\n// - It allow us to have a stable interface in case we need to swap out, or\n// eventually update multiformats (should we choose to drop CommonJS support)\n// in the future.\n\n// @NOTE Even though it is not portable, we still re-export CID here so that\n// dependent packages where it can be used, have access to it (instead of\n// importing directly from \"multiformats\" or \"multiformats/cid\").\nexport { /** @deprecated */ CID }\n\n/**\n * Converts a {@link Cid} to a multiformats {@link CID} instance.\n *\n * @deprecated Packages depending on `@atproto/lex-data` should use the\n * {@link Cid} interface instead of relying on `multiformats`'s {@link CID}\n * implementation directly. This is to avoid compatibility issues, and in order\n * to allow better portability, compatibility and future updates.\n */\nexport function asMultiformatsCID<\n TVersion extends 0 | 1 = 0 | 1,\n TCodec extends number = number,\n THashCode extends number = number,\n>(input: Cid<TVersion, TCodec, THashCode>) {\n const cid =\n // Already a multiformats CID instance\n CID.asCID(input) ??\n // Create a new multiformats CID instance\n CID.create(\n input.version,\n input.code,\n createDigest(input.multihash.code, input.multihash.digest),\n )\n\n // @NOTE: the \"satisfies\" operator is used here to ensure that the Cid\n // interface is indeed compatible with multiformats' CID implementation, which\n // allows us to safely rely on multiformats' CID implementation where Cid are\n // needed.\n return cid satisfies Cid as CID & Cid<TVersion, TCodec, THashCode>\n}\n\n/**\n * Content Identifier (CID) for addressing content by its hash.\n *\n * CIDs are self-describing content addresses used throughout AT Protocol for\n * linking to data by its cryptographic hash. This interface provides a\n * stable API that is compatible with the `multiformats` library but avoids\n * direct dependency issues.\n *\n * @typeParam TVersion - CID version (0 or 1)\n * @typeParam TCodec - Multicodec content type code\n * @typeParam THashCode - Multihash algorithm code\n *\n * @example\n * ```typescript\n * import type { Cid } from '@atproto/lex-data'\n * import { parseCid, isCid } from '@atproto/lex-data'\n *\n * // Parse a CID from a string\n * const cid: Cid = parseCid('bafyreib...')\n *\n * // Check if a value is a CID\n * if (isCid(value)) {\n * console.log(cid.toString())\n * }\n * ```\n *\n * @see {@link isCid} to check if a value is a valid CID\n * @see {@link parseCid} to parse a CID from a string\n * @see {@link decodeCid} to decode a CID from bytes\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport interface Cid<\n TVersion extends 0 | 1 = 0 | 1,\n TCodec extends number = number,\n THashCode extends number = number,\n> {\n // @NOTE This interface is compatible with multiformats' CID implementation\n // which we are using under the hood.\n\n /** CID version (0 or 1). AT Protocol uses CIDv1. */\n readonly version: TVersion\n /** Coded (e.g., {@link CBOR_DATA_CODEC}, {@link RAW_DATA_CODEC}). */\n readonly code: TCodec\n /** The multihash containing the hash algorithm and digest. */\n readonly multihash: Multihash<THashCode>\n\n /**\n * Binary representation of the whole CID.\n */\n readonly bytes: Uint8Array\n\n /**\n * Compares this CID with another for equality.\n *\n * @param other - The CID to compare with\n * @returns `true` if the CIDs are equal\n */\n equals(other: Cid): boolean\n\n /**\n * Returns the string representation of this CID (base32 for v1, base58btc for v0).\n */\n toString(): string\n}\n\n/**\n * Represents the CID of raw binary data (like media blobs).\n *\n * The use of {@link SHA256_HASH_CODE} is recommended but not required for raw CIDs.\n *\n * @see {@link https://atproto.com/specs/data-model#link-and-cid-formats AT Protocol Data Model - Link and CID Formats}\n */\nexport type RawCid = Cid<1, RAW_DATA_CODEC>\n\n/**\n * Type guard to check if a CID is a raw binary CID.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is a version 1 CID with raw multicodec\n */\nexport function isRawCid(cid: Cid): cid is RawCid {\n return cid.version === 1 && cid.code === RAW_DATA_CODEC\n}\n\n/**\n * Represents a DASL compliant CID.\n *\n * DASL CIDs are version 1 CIDs using either raw or DAG-CBOR multicodec\n * with SHA-256 multihash.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport type DaslCid = Cid<1, RAW_DATA_CODEC | CBOR_DATA_CODEC, SHA256_HASH_CODE>\n\n/**\n * Type guard to check if a CID is DASL compliant.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is DASL compliant (v1, raw/dag-cbor, sha256)\n */\nexport function isDaslCid(cid: Cid): cid is DaslCid {\n return (\n cid.version === 1 &&\n (cid.code === RAW_DATA_CODEC || cid.code === CBOR_DATA_CODEC) &&\n cid.multihash.code === SHA256_HASH_CODE &&\n cid.multihash.digest.byteLength === 0x20 // Should always be 32 bytes (256 bits) for SHA-256, but double-checking anyways\n )\n}\n\n/**\n * Represents the CID of AT Protocol DAG-CBOR data (like repository MST nodes).\n *\n * CBOR CIDs are version 1 CIDs using DAG-CBOR multicodec with SHA-256 multihash.\n *\n * @see {@link https://atproto.com/specs/data-model#link-and-cid-formats AT Protocol Data Model - Link and CID Formats}\n */\nexport type CborCid = Cid<1, CBOR_DATA_CODEC, SHA256_HASH_CODE>\n\n/**\n * Type guard to check if a CID is a DAG-CBOR CID.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is a DAG-CBOR CID (v1, dag-cbor, sha256)\n */\nexport function isCborCid(cid: Cid): cid is CborCid {\n return cid.code === CBOR_DATA_CODEC && isDaslCid(cid)\n}\n\n/**\n * Options for checking CID flavor constraints.\n */\nexport type CheckCidOptions = {\n /**\n * The CID flavor to check for.\n * - `'raw'` - Raw binary CID ({@link RawCid})\n * - `'cbor'` - DAG-CBOR CID ({@link CborCid})\n * - `'dasl'` - DASL compliant CID ({@link DaslCid})\n */\n flavor?: 'raw' | 'cbor' | 'dasl'\n}\n\n/**\n * Infers the CID type based on check options.\n *\n * @typeParam TOptions - The options used for checking\n */\nexport type InferCheckedCid<TOptions> = TOptions extends { flavor: 'raw' }\n ? RawCid\n : TOptions extends { flavor: 'cbor' }\n ? CborCid\n : Cid\n\n/**\n * Type guard to check whether a {@link Cid} instance meets specific flavor\n * constraints.\n */\nexport function checkCid<TOptions extends CheckCidOptions>(\n cid: Cid,\n options: TOptions,\n): cid is InferCheckedCid<TOptions>\nexport function checkCid(cid: Cid, options?: CheckCidOptions): boolean\nexport function checkCid(cid: Cid, options?: CheckCidOptions): boolean {\n switch (options?.flavor) {\n case undefined:\n return true\n case 'cbor':\n return isCborCid(cid)\n case 'dasl':\n return isDaslCid(cid)\n case 'raw':\n return isRawCid(cid)\n default:\n throw new TypeError(`Unknown CID flavor: ${options?.flavor}`)\n }\n}\n\n/**\n * Type guard to check whether a value is a valid {@link Cid} instance,\n * optionally checking for specific flavor constraints.\n */\nexport function isCid<TOptions extends CheckCidOptions>(\n value: unknown,\n options: TOptions,\n): value is InferCheckedCid<TOptions>\nexport function isCid(value: unknown, options?: CheckCidOptions): value is Cid\nexport function isCid(value: unknown, options?: CheckCidOptions): value is Cid {\n return isCidImplementation(value) && checkCid(value, options)\n}\n\n/**\n * Returns the input value as a {@link Cid} if it is valid, or `null` otherwise.\n */\nexport function ifCid<TValue, TOptions extends CheckCidOptions>(\n value: unknown,\n options: TOptions,\n): (TValue & InferCheckedCid<TOptions>) | null\nexport function ifCid<TValue>(\n value: TValue,\n options?: CheckCidOptions,\n): (TValue & Cid) | null\nexport function ifCid(value: unknown, options?: CheckCidOptions): Cid | null {\n if (isCidImplementation(value) && checkCid(value, options)) return value\n return null\n}\n\n/**\n * Returns the input value as a {@link Cid} if it is valid.\n *\n * @throws if the input is not a valid {@link Cid}.\n */\nexport function asCid<TValue, TOptions extends CheckCidOptions>(\n value: TValue,\n options: TOptions,\n): TValue & InferCheckedCid<TOptions>\nexport function asCid<TValue>(\n value: TValue,\n options?: CheckCidOptions,\n): Cid & TValue\nexport function asCid(value: unknown, options?: CheckCidOptions): Cid {\n if (isCidImplementation(value) && checkCid(value, options)) return value\n throw new Error('Not a valid CID')\n}\n\n/**\n * Decodes a CID from its binary representation.\n *\n * @see {@link https://dasl.ing/cid.html DASL-CIDs}\n * @throws if the input do not represent a valid DASL {@link Cid}\n */\nexport function decodeCid<TOptions extends CheckCidOptions>(\n cidBytes: Uint8Array,\n options: TOptions,\n): InferCheckedCid<TOptions>\nexport function decodeCid(cidBytes: Uint8Array, options?: CheckCidOptions): Cid\nexport function decodeCid(\n cidBytes: Uint8Array,\n options?: CheckCidOptions,\n): Cid {\n const cid = CID.decode(cidBytes)\n return asCid(cid, options)\n}\n\n/**\n * Parses a CID string into a Cid object.\n *\n * @throws if the input is not a valid CID string.\n */\nexport function parseCid<TOptions extends CheckCidOptions>(\n input: string,\n options: TOptions,\n): InferCheckedCid<TOptions>\nexport function parseCid(input: string, options?: CheckCidOptions): Cid\nexport function parseCid(input: string, options?: CheckCidOptions): Cid {\n const cid = CID.parse(input)\n return asCid(cid, options)\n}\n\n/**\n * Validates that a string is a valid CID representation.\n *\n * Unlike {@link parseCid}, this function returns a boolean instead of throwing.\n * It also verifies that the string is the canonical representation of the CID.\n *\n * @param input - The string to validate\n * @param options - Optional flavor constraints\n * @returns `true` if the string is a valid CID\n */\nexport function validateCidString(\n input: string,\n options?: CheckCidOptions,\n): boolean {\n return parseCidSafe(input, options)?.toString() === input\n}\n\n/**\n * Safely parses a CID string, returning `null` on failure instead of throwing.\n *\n * @param input - The string to parse\n * @param options - Optional flavor constraints\n * @returns The parsed CID, or `null` if parsing fails\n *\n * @example\n * ```typescript\n * import { parseCidSafe } from '@atproto/lex-data'\n *\n * const cid = parseCidSafe('bafyreib...')\n * if (cid) {\n * console.log(cid.toString())\n * }\n * ```\n */\nexport function parseCidSafe<TOptions extends CheckCidOptions>(\n input: string,\n options: TOptions,\n): InferCheckedCid<TOptions> | null\nexport function parseCidSafe(\n input: string,\n options?: CheckCidOptions,\n): Cid | null\nexport function parseCidSafe(\n input: string,\n options?: CheckCidOptions,\n): Cid | null {\n try {\n return parseCid(input, options)\n } catch {\n return null\n }\n}\n\n/**\n * Ensures that a string is a valid CID representation.\n *\n * @param input - The string to validate\n * @param options - Optional flavor constraints\n * @throws If the string is not a valid CID\n */\nexport function ensureValidCidString(\n input: string,\n options?: CheckCidOptions,\n): void {\n if (!validateCidString(input, options)) {\n throw new Error(`Invalid CID string`)\n }\n}\n\n/**\n * Verifies whether the multihash of a given {@link cid} matches the hash of the provided {@link bytes}.\n * @params cid The CID to match against the bytes.\n * @params bytes The bytes to verify.\n * @returns true if the CID matches the bytes, false otherwise.\n */\nexport async function isCidForBytes(\n cid: Cid,\n bytes: Uint8Array,\n): Promise<boolean> {\n if (cid.multihash.code === sha256.code) {\n const multihash = await sha256.digest(bytes)\n return multihashEquals(multihash, cid.multihash)\n }\n\n if (cid.multihash.code === sha512.code) {\n const multihash = await sha512.digest(bytes)\n return multihashEquals(multihash, cid.multihash)\n }\n\n // Don't know how to verify other multihash codes\n throw new Error('Unsupported CID multihash')\n}\n\n/**\n * Creates a CID from a multicodec, multihash code, and digest.\n *\n * @param code - The multicodec content type code\n * @param multihashCode - The multihash algorithm code\n * @param digest - The raw hash digest bytes\n * @returns A new CIDv1 instance\n *\n * @example\n * ```typescript\n * import { createCid, RAW_DATA_CODEC, SHA256_HASH_CODE } from '@atproto/lex-data'\n *\n * const cid = createCid(RAW_DATA_CODEC, SHA256_HASH_CODE, hashDigest)\n * ```\n */\nexport function createCid<TCodec extends number, THashCode extends number>(\n code: TCodec,\n multihashCode: THashCode,\n digest: Uint8Array,\n) {\n const cid: Cid = CID.createV1(code, createDigest(multihashCode, digest))\n return cid as Cid<1, TCodec, THashCode>\n}\n\n/**\n * Creates a DAG-CBOR CID for the given CBOR bytes.\n *\n * Computes the SHA-256 hash of the bytes and creates a CIDv1 with DAG-CBOR multicodec.\n *\n * @param bytes - The CBOR-encoded bytes to hash\n * @returns A promise that resolves to the CborCid\n */\nexport async function cidForCbor(bytes: Uint8Array): Promise<CborCid> {\n const multihash = await sha256.digest(bytes)\n return CID.createV1(CBOR_DATA_CODEC, multihash) as CborCid\n}\n\n/**\n * Creates a raw CID for the given binary bytes.\n *\n * Computes the SHA-256 hash of the bytes and creates a CIDv1 with raw multicodec.\n *\n * @param bytes - The raw binary bytes to hash\n * @returns A promise that resolves to the RawCid\n */\nexport async function cidForRawBytes(bytes: Uint8Array): Promise<RawCid> {\n const multihash = await sha256.digest(bytes)\n return CID.createV1(RAW_DATA_CODEC, multihash) as RawCid\n}\n\n/**\n * Creates a raw CID from an existing SHA-256 hash digest.\n *\n * @param digest - The SHA-256 hash digest (must be 32 bytes)\n * @returns A RawCid with the given digest\n * @throws If the digest length is not 32 bytes\n */\nexport function cidForRawHash(digest: Uint8Array): RawCid {\n // Fool-proofing\n if (digest.length !== 32) {\n throw new Error(`Invalid SHA-256 hash length: ${digest.length}`)\n }\n return createCid(RAW_DATA_CODEC, sha256.code, digest)\n}\n\nfunction isCidImplementation(value: unknown): value is Cid {\n if (CID.asCID(value)) {\n // CIDs created using older multiformats versions did not have a \"bytes\"\n // property.\n return (value as { bytes?: Uint8Array }).bytes != null\n } else {\n // Unknown implementation, do a structural check\n try {\n if (!isObject(value)) return false\n\n const val = value as Record<string, unknown>\n if (val.version !== 0 && val.version !== 1) return false\n if (!isUint8(val.code)) return false\n\n if (!isObject(val.multihash)) return false\n const mh = val.multihash as Record<string, unknown>\n if (!isUint8(mh.code)) return false\n if (!(mh.digest instanceof Uint8Array)) return false\n\n // Ensure that the bytes array is consistent with other properties\n if (!(val.bytes instanceof Uint8Array)) return false\n if (val.bytes[0] !== val.version) return false\n if (val.bytes[1] !== val.code) return false\n if (val.bytes[2] !== mh.code) return false\n if (val.bytes[3] !== mh.digest.length) return false\n if (val.bytes.length !== 4 + mh.digest.length) return false\n if (!ui8Equals(val.bytes.subarray(4), mh.digest)) return false\n\n if (typeof val.equals !== 'function') return false\n if (val.equals(val) !== true) return false\n\n return true\n } catch {\n return false\n }\n }\n}\n\nfunction isUint8(val: unknown): val is number {\n return Number.isInteger(val) && (val as number) >= 0 && (val as number) < 256\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cid.js","sourceRoot":"","sources":["../src/cid.ts"],"names":[],"mappings":";;;AAgEA,0CAGC;AAsDD,8CAoBC;AAkFD,4BAEC;AAkBD,8BAOC;AAiBD,8BAEC;AAoCD,4BAaC;AAWD,sBAEC;AAaD,sBAGC;AAeD,sBAKC;AAaD,8BAMC;AAYD,4BAGC;AAYD,8CAKC;AA2BD,oCASC;AASD,oDAOC;AAQD,sCAkBC;AAiBD,8BAOC;AAUD,gCAGC;AAUD,wCAGC;AASD,sCAQC;AAnjBD,0CAAsC;AA+GV,oFA/GnB,SAAG,OA+GmB;AA9G/B,uDAAmE;AACnE,mDAAyD;AACzD,2CAAoD;AACpD,2CAAsC;AACtC,mDAA2C;AAE3C;;;;;;GAMG;AACU,QAAA,eAAe,GAAG,IAAI,CAAA;AAGnC;;;;;;GAMG;AACU,QAAA,cAAc,GAAG,IAAI,CAAA;AAGlC;;GAEG;AACU,QAAA,gBAAgB,GAAG,aAAM,CAAC,IAAI,CAAA;AAG3C;;GAEG;AACU,QAAA,gBAAgB,GAAG,aAAM,CAAC,IAAI,CAAA;AAqB3C;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,CAAY,EAAE,CAAY;IACxD,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAA;IACxB,OAAO,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,IAAI,IAAA,yBAAS,EAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAA;AAC3D,CAAC;AA8CD;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAI/B,KAAuC;IACvC,MAAM,GAAG;IACP,sCAAsC;IACtC,SAAG,CAAC,KAAK,CAAC,KAAK,CAAC;QAChB,yCAAyC;QACzC,SAAG,CAAC,MAAM,CACR,KAAK,CAAC,OAAO,EACb,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AO,KAAK,CAAA;YAE1C,OAAO,IAAI,CAAA;QACb,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { CID } from 'multiformats/cid'\nimport { create as createDigest } from 'multiformats/hashes/digest'\nimport { sha256, sha512 } from 'multiformats/hashes/sha2'\nimport { isUint8, toHexString } from './lib/util.js'\nimport { isObject } from './object.js'\nimport { ui8Equals } from './uint8array.js'\n\n/**\n * Codec code that indicates the CID references a CBOR-encoded data structure.\n *\n * Used when encoding structured data in AT Protocol repositories.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport const CBOR_DATA_CODEC = 0x71\nexport type CBOR_DATA_CODEC = typeof CBOR_DATA_CODEC\n\n/**\n * Codec code that indicates the CID references raw binary data (like media blobs).\n *\n * Used in DASL CIDs for binary blobs like images and media.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport const RAW_DATA_CODEC = 0x55\nexport type RAW_DATA_CODEC = typeof RAW_DATA_CODEC\n\n/**\n * Hash code that indicates that a CID uses SHA-256.\n */\nexport const SHA256_HASH_CODE = sha256.code\nexport type SHA256_HASH_CODE = typeof SHA256_HASH_CODE\n\n/**\n * Hash code that indicates that a CID uses SHA-512.\n */\nexport const SHA512_HASH_CODE = sha512.code\nexport type SHA512_HASH_CODE = typeof SHA512_HASH_CODE\n\n/**\n * Represent the hash part of a CID, which includes the hash algorithm code and\n * the raw digest bytes.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport interface Multihash<THashCode extends number = number> {\n /**\n * Code of the hash algorithm (e.g., SHA256_HASH_CODE).\n */\n code: THashCode\n\n /**\n * Raw digest bytes.\n */\n digest: Uint8Array\n}\n\n/**\n * Compares two {@link Multihash} for equality.\n *\n * @param a - First {@link Multihash}\n * @param b - Second {@link Multihash}\n * @returns `true` if both multihashes have the same code and digest\n */\nexport function multihashEquals(a: Multihash, b: Multihash): boolean {\n if (a === b) return true\n return a.code === b.code && ui8Equals(a.digest, b.digest)\n}\n\ndeclare module 'multiformats/cid' {\n /**\n * @deprecated use the {@link Cid} interface from `@atproto/lex-data`, and\n * related helpers ({@link isCid}, {@link ifCid}, {@link asCid},\n * {@link parseCid}, {@link decodeCid}), instead.\n *\n * This is marked as deprecated because we want to discourage direct usage of\n * `multiformats/cid` in dependent packages, and instead have them rely on the\n * {@link Cid} interface from `@atproto/lex-data`. The {@link CID} class from\n * `multiformats` version <10 has compatibility issues with certain TypeScript\n * configuration, which can lead to type errors in dependent packages.\n *\n * We are stuck with version 9 because `@atproto` packages did not drop\n * CommonJS support yet, and multiformats version 10 only supports ES modules.\n *\n * In order to avoid compatibility issues, while preparing for future breaking\n * changes (CID in multiformats v10+ has a slightly different interface), as\n * we update or swap out `multiformats`, `@atproto/lex-data` provides its own\n * stable {@link Cid} interface.\n */\n interface CID {}\n}\n\n// multiformats' CID class is not very portable because:\n//\n// - In dependent packages that use \"moduleResolution\" set to \"node16\",\n// \"nodenext\" or \"bundler\", TypeScript fails to properly resolve the\n// multiformats package when importing CID from @atproto/lex-data. This causes\n// type errors in those packages. This is caused by the fact that the\n// multiformats version <10 (which is the last version that supports CommonJS)\n// uses \"exports\" field in package.json, which do not contain \"types\"\n// entrypoints.\n// https://www.npmjs.com/package/multiformats/v/9.9.0?activeTab=code\n// - By defining our own interface and helper functions, we can have more\n// control over the public API exposed by this package.\n// - It allow us to have a stable interface in case we need to swap out, or\n// eventually update multiformats (should we choose to drop CommonJS support)\n// in the future.\n\n// @NOTE Even though it is not portable, we still re-export CID here so that\n// dependent packages where it can be used, have access to it (instead of\n// importing directly from \"multiformats\" or \"multiformats/cid\").\nexport { /** @deprecated */ CID }\n\n/**\n * Converts a {@link Cid} to a multiformats {@link CID} instance.\n *\n * @deprecated Packages depending on `@atproto/lex-data` should use the\n * {@link Cid} interface instead of relying on `multiformats`'s {@link CID}\n * implementation directly. This is to avoid compatibility issues, and in order\n * to allow better portability, compatibility and future updates.\n */\nexport function asMultiformatsCID<\n TVersion extends 0 | 1 = 0 | 1,\n TCodec extends number = number,\n THashCode extends number = number,\n>(input: Cid<TVersion, TCodec, THashCode>) {\n const cid =\n // Already a multiformats CID instance\n CID.asCID(input) ??\n // Create a new multiformats CID instance\n CID.create(\n input.version,\n input.code,\n createDigest(input.multihash.code, input.multihash.digest),\n )\n\n // @NOTE: the \"satisfies\" operator is used here to ensure that the Cid\n // interface is indeed compatible with multiformats' CID implementation, which\n // allows us to safely rely on multiformats' CID implementation where Cid are\n // needed.\n return cid satisfies Cid as CID & Cid<TVersion, TCodec, THashCode>\n}\n\n/**\n * Content Identifier (CID) for addressing content by its hash.\n *\n * CIDs are self-describing content addresses used throughout AT Protocol for\n * linking to data by its cryptographic hash. This interface provides a\n * stable API that is compatible with the `multiformats` library but avoids\n * direct dependency issues.\n *\n * @typeParam TVersion - CID version (0 or 1)\n * @typeParam TCodec - Multicodec content type code\n * @typeParam THashCode - Multihash algorithm code\n *\n * @example\n * ```typescript\n * import type { Cid } from '@atproto/lex-data'\n * import { parseCid, isCid } from '@atproto/lex-data'\n *\n * // Parse a CID from a string\n * const cid: Cid = parseCid('bafyreib...')\n *\n * // Check if a value is a CID\n * if (isCid(value)) {\n * console.log(cid.toString())\n * }\n * ```\n *\n * @see {@link isCid} to check if a value is a valid CID\n * @see {@link parseCid} to parse a CID from a string\n * @see {@link decodeCid} to decode a CID from bytes\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport interface Cid<\n TVersion extends 0 | 1 = 0 | 1,\n TCodec extends number = number,\n THashCode extends number = number,\n> {\n // @NOTE This interface is compatible with multiformats' CID implementation\n // which we are using under the hood.\n\n /** CID version (0 or 1). AT Protocol uses CIDv1. */\n readonly version: TVersion\n /** Coded (e.g., {@link CBOR_DATA_CODEC}, {@link RAW_DATA_CODEC}). */\n readonly code: TCodec\n /** The multihash containing the hash algorithm and digest. */\n readonly multihash: Multihash<THashCode>\n\n /**\n * Binary representation of the whole CID.\n */\n readonly bytes: Uint8Array\n\n /**\n * Compares this CID with another for equality.\n *\n * @param other - The CID to compare with\n * @returns `true` if the CIDs are equal\n */\n equals(other: Cid): boolean\n\n /**\n * Returns the string representation of this CID (base32 for v1, base58btc for v0).\n */\n toString(): string\n}\n\n/**\n * Represents the CID of raw binary data (like media blobs).\n *\n * The use of {@link SHA256_HASH_CODE} is recommended but not required for raw CIDs.\n *\n * @see {@link https://atproto.com/specs/data-model#link-and-cid-formats AT Protocol Data Model - Link and CID Formats}\n */\nexport type RawCid = Cid<1, RAW_DATA_CODEC>\n\n/**\n * Type guard to check if a CID is a raw binary CID.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is a version 1 CID with raw multicodec\n */\nexport function isRawCid(cid: Cid): cid is RawCid {\n return cid.version === 1 && cid.code === RAW_DATA_CODEC\n}\n\n/**\n * Represents a DASL compliant CID.\n *\n * DASL CIDs are version 1 CIDs using either raw or DAG-CBOR multicodec\n * with SHA-256 multihash.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport type DaslCid = Cid<1, RAW_DATA_CODEC | CBOR_DATA_CODEC, SHA256_HASH_CODE>\n\n/**\n * Type guard to check if a CID is DASL compliant.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is DASL compliant (v1, raw/dag-cbor, sha256)\n */\nexport function isDaslCid(cid: Cid): cid is DaslCid {\n return (\n cid.version === 1 &&\n (cid.code === RAW_DATA_CODEC || cid.code === CBOR_DATA_CODEC) &&\n cid.multihash.code === SHA256_HASH_CODE &&\n cid.multihash.digest.byteLength === 0x20 // Should always be 32 bytes (256 bits) for SHA-256, but double-checking anyways\n )\n}\n\n/**\n * Represents the CID of AT Protocol DAG-CBOR data (like repository MST nodes).\n *\n * CBOR CIDs are version 1 CIDs using DAG-CBOR multicodec with SHA-256 multihash.\n *\n * @see {@link https://atproto.com/specs/data-model#link-and-cid-formats AT Protocol Data Model - Link and CID Formats}\n */\nexport type CborCid = Cid<1, CBOR_DATA_CODEC, SHA256_HASH_CODE>\n\n/**\n * Type guard to check if a CID is a DAG-CBOR CID.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is a DAG-CBOR CID (v1, dag-cbor, sha256)\n */\nexport function isCborCid(cid: Cid): cid is CborCid {\n return cid.code === CBOR_DATA_CODEC && isDaslCid(cid)\n}\n\n/**\n * Options for checking CID flavor constraints.\n */\nexport type CheckCidOptions = {\n /**\n * The CID flavor to check for.\n * - `'raw'` - Raw binary CID ({@link RawCid})\n * - `'cbor'` - DAG-CBOR CID ({@link CborCid})\n * - `'dasl'` - DASL compliant CID ({@link DaslCid})\n */\n flavor?: 'raw' | 'cbor' | 'dasl'\n}\n\n/**\n * Infers the CID type based on check options.\n *\n * @typeParam TOptions - The options used for checking\n */\nexport type InferCheckedCid<TOptions extends CheckCidOptions> =\n TOptions extends { flavor: 'raw' }\n ? RawCid\n : TOptions extends { flavor: 'cbor' }\n ? CborCid\n : Cid\n\n/**\n * Type guard to check whether a {@link Cid} instance meets specific flavor\n * constraints.\n */\nexport function checkCid<TOptions extends CheckCidOptions>(\n cid: Cid,\n options: TOptions,\n): cid is InferCheckedCid<TOptions>\nexport function checkCid(cid: Cid, options?: CheckCidOptions): boolean\nexport function checkCid(cid: Cid, options?: CheckCidOptions): boolean {\n switch (options?.flavor) {\n case undefined:\n return true\n case 'cbor':\n return isCborCid(cid)\n case 'dasl':\n return isDaslCid(cid)\n case 'raw':\n return isRawCid(cid)\n default:\n throw new TypeError(`Unknown CID flavor: ${options?.flavor}`)\n }\n}\n\n/**\n * Type guard to check whether a value is a valid {@link Cid} instance,\n * optionally checking for specific flavor constraints.\n */\nexport function isCid<TOptions extends CheckCidOptions>(\n value: unknown,\n options: TOptions,\n): value is InferCheckedCid<TOptions>\nexport function isCid(value: unknown, options?: CheckCidOptions): value is Cid\nexport function isCid(value: unknown, options?: CheckCidOptions): value is Cid {\n return isCidImplementation(value) && checkCid(value, options)\n}\n\n/**\n * Returns the input value as a {@link Cid} if it is valid, or `null` otherwise.\n */\nexport function ifCid<TValue, TOptions extends CheckCidOptions>(\n value: unknown,\n options: TOptions,\n): (TValue & InferCheckedCid<TOptions>) | null\nexport function ifCid<TValue>(\n value: TValue,\n options?: CheckCidOptions,\n): (TValue & Cid) | null\nexport function ifCid(value: unknown, options?: CheckCidOptions): Cid | null {\n if (isCid(value, options)) return value\n return null\n}\n\n/**\n * Returns the input value as a {@link Cid} if it is valid.\n *\n * @throws if the input is not a valid {@link Cid}.\n */\nexport function asCid<TValue, TOptions extends CheckCidOptions>(\n value: TValue,\n options: TOptions,\n): TValue & InferCheckedCid<TOptions>\nexport function asCid<TValue>(\n value: TValue,\n options?: CheckCidOptions,\n): TValue & Cid\nexport function asCid(value: unknown, options?: CheckCidOptions): Cid {\n if (isCid(value, options)) return value\n throw new Error(\n `Invalid ${options?.flavor ? `${options.flavor} CID` : 'CID'} \"${value}\"`,\n )\n}\n\n/**\n * Decodes a CID from its binary representation.\n *\n * @see {@link https://dasl.ing/cid.html DASL-CIDs}\n * @throws if the input do not represent a valid DASL {@link Cid}\n */\nexport function decodeCid<TOptions extends CheckCidOptions>(\n cidBytes: Uint8Array,\n options: TOptions,\n): InferCheckedCid<TOptions>\nexport function decodeCid(cidBytes: Uint8Array, options?: CheckCidOptions): Cid\nexport function decodeCid(\n cidBytes: Uint8Array,\n options?: CheckCidOptions,\n): Cid {\n const cid = CID.decode(cidBytes)\n return asCid(cid, options)\n}\n\n/**\n * Parses a CID string into a Cid object.\n *\n * @throws if the input is not a valid CID string.\n */\nexport function parseCid<TOptions extends CheckCidOptions>(\n input: string,\n options: TOptions,\n): InferCheckedCid<TOptions>\nexport function parseCid(input: string, options?: CheckCidOptions): Cid\nexport function parseCid(input: string, options?: CheckCidOptions): Cid {\n const cid = CID.parse(input)\n return asCid(cid, options)\n}\n\n/**\n * Validates that a string is a valid CID representation.\n *\n * Unlike {@link parseCid}, this function returns a boolean instead of throwing.\n * It also verifies that the string is the canonical representation of the CID.\n *\n * @param input - The string to validate\n * @param options - Optional flavor constraints\n * @returns `true` if the string is a valid CID\n */\nexport function validateCidString(\n input: string,\n options?: CheckCidOptions,\n): boolean {\n return parseCidSafe(input, options)?.toString() === input\n}\n\n/**\n * Safely parses a CID string, returning `null` on failure instead of throwing.\n *\n * @param input - The string to parse\n * @param options - Optional flavor constraints\n * @returns The parsed CID, or `null` if parsing fails\n *\n * @example\n * ```typescript\n * import { parseCidSafe } from '@atproto/lex-data'\n *\n * const cid = parseCidSafe('bafyreib...')\n * if (cid) {\n * console.log(cid.toString())\n * }\n * ```\n */\nexport function parseCidSafe<TOptions extends CheckCidOptions>(\n input: string,\n options: TOptions,\n): InferCheckedCid<TOptions> | null\nexport function parseCidSafe(\n input: string,\n options?: CheckCidOptions,\n): Cid | null\nexport function parseCidSafe(\n input: string,\n options?: CheckCidOptions,\n): Cid | null {\n try {\n return parseCid(input, options)\n } catch {\n return null\n }\n}\n\n/**\n * Ensures that a string is a valid CID representation.\n *\n * @param input - The string to validate\n * @param options - Optional flavor constraints\n * @throws If the string is not a valid CID\n */\nexport function ensureValidCidString(\n input: string,\n options?: CheckCidOptions,\n): void {\n if (!validateCidString(input, options)) {\n throw new Error(`Invalid CID string \"${input}\"`)\n }\n}\n\n/**\n * Verifies whether the multihash of a given {@link cid} matches the hash of the provided {@link bytes}.\n * @params cid The CID to match against the bytes.\n * @params bytes The bytes to verify.\n * @returns true if the CID matches the bytes, false otherwise.\n */\nexport async function isCidForBytes(\n cid: Cid,\n bytes: Uint8Array,\n): Promise<boolean> {\n if (cid.multihash.code === sha256.code) {\n const multihash = await sha256.digest(bytes)\n return multihashEquals(multihash, cid.multihash)\n }\n\n if (cid.multihash.code === sha512.code) {\n const multihash = await sha512.digest(bytes)\n return multihashEquals(multihash, cid.multihash)\n }\n\n // Don't know how to verify other multihash codes\n throw new Error(\n `Unsupported CID multihash code: ${toHexString(cid.multihash.code)}`,\n )\n}\n\n/**\n * Creates a CID from a multicodec, multihash code, and digest.\n *\n * @param code - The multicodec content type code\n * @param multihashCode - The multihash algorithm code\n * @param digest - The raw hash digest bytes\n * @returns A new CIDv1 instance\n *\n * @example\n * ```typescript\n * import { createCid, RAW_DATA_CODEC, SHA256_HASH_CODE } from '@atproto/lex-data'\n *\n * const cid = createCid(RAW_DATA_CODEC, SHA256_HASH_CODE, hashDigest)\n * ```\n */\nexport function createCid<TCodec extends number, THashCode extends number>(\n code: TCodec,\n multihashCode: THashCode,\n digest: Uint8Array,\n) {\n const cid: Cid = CID.createV1(code, createDigest(multihashCode, digest))\n return cid as Cid<1, TCodec, THashCode>\n}\n\n/**\n * Creates a DAG-CBOR CID for the given CBOR bytes.\n *\n * Computes the SHA-256 hash of the bytes and creates a CIDv1 with DAG-CBOR multicodec.\n *\n * @param bytes - The CBOR-encoded bytes to hash\n * @returns A promise that resolves to the CborCid\n */\nexport async function cidForCbor(bytes: Uint8Array): Promise<CborCid> {\n const multihash = await sha256.digest(bytes)\n return CID.createV1(CBOR_DATA_CODEC, multihash) as CborCid\n}\n\n/**\n * Creates a raw CID for the given binary bytes.\n *\n * Computes the SHA-256 hash of the bytes and creates a CIDv1 with raw multicodec.\n *\n * @param bytes - The raw binary bytes to hash\n * @returns A promise that resolves to the RawCid\n */\nexport async function cidForRawBytes(bytes: Uint8Array): Promise<RawCid> {\n const multihash = await sha256.digest(bytes)\n return CID.createV1(RAW_DATA_CODEC, multihash) as RawCid\n}\n\n/**\n * Creates a raw CID from an existing SHA-256 hash digest.\n *\n * @param digest - The SHA-256 hash digest (must be 32 bytes)\n * @returns A RawCid with the given digest\n * @throws If the digest is not a valid SHA-256 hash (not 32 bytes)\n */\nexport function cidForRawHash(digest: Uint8Array): RawCid {\n // Fool-proofing\n if (digest.length !== 0x20) {\n throw new Error(\n `Invalid SHA-256 hash length: ${toHexString(digest.length)}`,\n )\n }\n return createCid(RAW_DATA_CODEC, sha256.code, digest)\n}\n\nfunction isCidImplementation(value: unknown): value is Cid {\n if (CID.asCID(value)) {\n // CIDs created using older multiformats versions did not have a \"bytes\"\n // property.\n return (value as { bytes?: Uint8Array }).bytes != null\n } else {\n // Unknown implementation, do a structural check\n try {\n if (!isObject(value)) return false\n\n const val = value as Record<string, unknown>\n if (val.version !== 0 && val.version !== 1) return false\n if (!isUint8(val.code)) return false\n\n if (!isObject(val.multihash)) return false\n const mh = val.multihash as Record<string, unknown>\n if (!isUint8(mh.code)) return false\n if (!(mh.digest instanceof Uint8Array)) return false\n\n // Ensure that the bytes array is consistent with other properties\n if (!(val.bytes instanceof Uint8Array)) return false\n if (val.bytes[0] !== val.version) return false\n if (val.bytes[1] !== val.code) return false\n if (val.bytes[2] !== mh.code) return false\n if (val.bytes[3] !== mh.digest.length) return false\n if (val.bytes.length !== 4 + mh.digest.length) return false\n if (!ui8Equals(val.bytes.subarray(4), mh.digest)) return false\n\n if (typeof val.equals !== 'function') return false\n if (val.equals(val) !== true) return false\n\n return true\n } catch {\n return false\n }\n }\n}\n"]}
|
package/dist/lex-error.d.ts
CHANGED
|
@@ -37,37 +37,17 @@ export type LexErrorData<N extends LexErrorCode = LexErrorCode> = {
|
|
|
37
37
|
/**
|
|
38
38
|
* Error class for Lexicon-related errors.
|
|
39
39
|
*
|
|
40
|
-
* LexError extends the standard JavaScript {@link Error} with AT
|
|
41
|
-
* functionality including
|
|
42
|
-
*
|
|
43
|
-
* - JSON serialization for API responses
|
|
44
|
-
* - HTTP Response generation
|
|
40
|
+
* LexError extends the standard JavaScript {@link Error} with AT
|
|
41
|
+
* Protocol-specific functionality including an `error` code property and
|
|
42
|
+
* methods for representation as (XRPC) error responses payloads.
|
|
45
43
|
*
|
|
46
44
|
* @typeParam N - The specific error code type
|
|
47
|
-
*
|
|
48
|
-
* @example
|
|
49
|
-
* ```typescript
|
|
50
|
-
* import { LexError } from '@atproto/lex-data'
|
|
51
|
-
*
|
|
52
|
-
* // Throw a Lexicon error
|
|
53
|
-
* throw new LexError('InvalidRequest', 'Missing required field')
|
|
54
|
-
*
|
|
55
|
-
* // Create and serialize
|
|
56
|
-
* const error = new LexError('NotFound', 'Record not found')
|
|
57
|
-
* console.log(error.toJSON())
|
|
58
|
-
* // { error: 'NotFound', message: 'Record not found' }
|
|
59
|
-
*
|
|
60
|
-
* // Return as HTTP response
|
|
61
|
-
* return error.toResponse() // 400 Bad Request with JSON body
|
|
62
|
-
* ```
|
|
63
45
|
*/
|
|
64
46
|
export declare class LexError<N extends LexErrorCode = LexErrorCode> extends Error {
|
|
65
47
|
readonly error: N;
|
|
66
48
|
name: string;
|
|
67
49
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
* @param error - The error code identifying the type of error
|
|
50
|
+
* @param error - The error code identifying the type of error, typically used in XRPC error payloads
|
|
71
51
|
* @param message - Optional human-readable error message
|
|
72
52
|
* @param options - Standard Error options (e.g., cause)
|
|
73
53
|
*/
|
|
@@ -76,22 +56,15 @@ export declare class LexError<N extends LexErrorCode = LexErrorCode> extends Err
|
|
|
76
56
|
/**
|
|
77
57
|
* Returns a string representation of this error.
|
|
78
58
|
*
|
|
79
|
-
* @returns A formatted string: "
|
|
59
|
+
* @returns A formatted string: "LexErrorClass: [MyErrorCode] My message"
|
|
80
60
|
*/
|
|
81
61
|
toString(): string;
|
|
82
62
|
/**
|
|
83
63
|
* Converts this error to a JSON-serializable object.
|
|
84
64
|
*
|
|
85
65
|
* @returns The error data suitable for JSON serialization
|
|
66
|
+
* @note The `error` generic is *not* constrained to {@link N} to allow subclasses to override the error code type.
|
|
86
67
|
*/
|
|
87
|
-
toJSON(): LexErrorData<
|
|
88
|
-
/**
|
|
89
|
-
* Converts this error to an HTTP Response for downstream clients.
|
|
90
|
-
*
|
|
91
|
-
* Returns a 400 Bad Request response with the JSON-serialized error body.
|
|
92
|
-
*
|
|
93
|
-
* @returns A Response object with status 400 and JSON body
|
|
94
|
-
*/
|
|
95
|
-
toResponse(): Response;
|
|
68
|
+
toJSON(): LexErrorData<LexErrorCode>;
|
|
96
69
|
}
|
|
97
70
|
//# sourceMappingURL=lex-error.d.ts.map
|
package/dist/lex-error.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lex-error.d.ts","sourceRoot":"","sources":["../src/lex-error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,CAAA;AAExD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,IAAI;IAChE,oDAAoD;IACpD,KAAK,EAAE,CAAC,CAAA;IACR,6CAA6C;IAC7C,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED
|
|
1
|
+
{"version":3,"file":"lex-error.d.ts","sourceRoot":"","sources":["../src/lex-error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,CAAA;AAExD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,IAAI;IAChE,oDAAoD;IACpD,KAAK,EAAE,CAAC,CAAA;IACR,6CAA6C;IAC7C,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED;;;;;;;;GAQG;AACH,qBAAa,QAAQ,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,CAAE,SAAQ,KAAK;IAStE,QAAQ,CAAC,KAAK,EAAE,CAAC;IARnB,IAAI,SAAa;IAEjB;;;;OAIG;gBAEQ,KAAK,EAAE,CAAC,EACjB,OAAO,CAAC,EAAE,MAAM,EAAE,gDAAgD;IAClE,OAAO,CAAC,EAAE,YAAY;IAKxB;;;;OAIG;IACH,QAAQ,IAAI,MAAM;IAIlB;;;;;OAKG;IACH,MAAM,IAAI,YAAY,CAAC,YAAY,CAAC;CAIrC"}
|
package/dist/lex-error.js
CHANGED
|
@@ -4,37 +4,17 @@ exports.LexError = void 0;
|
|
|
4
4
|
/**
|
|
5
5
|
* Error class for Lexicon-related errors.
|
|
6
6
|
*
|
|
7
|
-
* LexError extends the standard JavaScript {@link Error} with AT
|
|
8
|
-
* functionality including
|
|
9
|
-
*
|
|
10
|
-
* - JSON serialization for API responses
|
|
11
|
-
* - HTTP Response generation
|
|
7
|
+
* LexError extends the standard JavaScript {@link Error} with AT
|
|
8
|
+
* Protocol-specific functionality including an `error` code property and
|
|
9
|
+
* methods for representation as (XRPC) error responses payloads.
|
|
12
10
|
*
|
|
13
11
|
* @typeParam N - The specific error code type
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```typescript
|
|
17
|
-
* import { LexError } from '@atproto/lex-data'
|
|
18
|
-
*
|
|
19
|
-
* // Throw a Lexicon error
|
|
20
|
-
* throw new LexError('InvalidRequest', 'Missing required field')
|
|
21
|
-
*
|
|
22
|
-
* // Create and serialize
|
|
23
|
-
* const error = new LexError('NotFound', 'Record not found')
|
|
24
|
-
* console.log(error.toJSON())
|
|
25
|
-
* // { error: 'NotFound', message: 'Record not found' }
|
|
26
|
-
*
|
|
27
|
-
* // Return as HTTP response
|
|
28
|
-
* return error.toResponse() // 400 Bad Request with JSON body
|
|
29
|
-
* ```
|
|
30
12
|
*/
|
|
31
13
|
class LexError extends Error {
|
|
32
14
|
error;
|
|
33
15
|
name = 'LexError';
|
|
34
16
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* @param error - The error code identifying the type of error
|
|
17
|
+
* @param error - The error code identifying the type of error, typically used in XRPC error payloads
|
|
38
18
|
* @param message - Optional human-readable error message
|
|
39
19
|
* @param options - Standard Error options (e.g., cause)
|
|
40
20
|
*/
|
|
@@ -46,7 +26,7 @@ class LexError extends Error {
|
|
|
46
26
|
/**
|
|
47
27
|
* Returns a string representation of this error.
|
|
48
28
|
*
|
|
49
|
-
* @returns A formatted string: "
|
|
29
|
+
* @returns A formatted string: "LexErrorClass: [MyErrorCode] My message"
|
|
50
30
|
*/
|
|
51
31
|
toString() {
|
|
52
32
|
return `${this.name}: [${this.error}] ${this.message}`;
|
|
@@ -55,21 +35,12 @@ class LexError extends Error {
|
|
|
55
35
|
* Converts this error to a JSON-serializable object.
|
|
56
36
|
*
|
|
57
37
|
* @returns The error data suitable for JSON serialization
|
|
38
|
+
* @note The `error` generic is *not* constrained to {@link N} to allow subclasses to override the error code type.
|
|
58
39
|
*/
|
|
59
40
|
toJSON() {
|
|
60
41
|
const { error, message } = this;
|
|
61
42
|
return { error, message: message || undefined };
|
|
62
43
|
}
|
|
63
|
-
/**
|
|
64
|
-
* Converts this error to an HTTP Response for downstream clients.
|
|
65
|
-
*
|
|
66
|
-
* Returns a 400 Bad Request response with the JSON-serialized error body.
|
|
67
|
-
*
|
|
68
|
-
* @returns A Response object with status 400 and JSON body
|
|
69
|
-
*/
|
|
70
|
-
toResponse() {
|
|
71
|
-
return Response.json(this.toJSON(), { status: 400 });
|
|
72
|
-
}
|
|
73
44
|
}
|
|
74
45
|
exports.LexError = LexError;
|
|
75
46
|
//# sourceMappingURL=lex-error.js.map
|
package/dist/lex-error.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lex-error.js","sourceRoot":"","sources":["../src/lex-error.ts"],"names":[],"mappings":";;;AAsCA
|
|
1
|
+
{"version":3,"file":"lex-error.js","sourceRoot":"","sources":["../src/lex-error.ts"],"names":[],"mappings":";;;AAsCA;;;;;;;;GAQG;AACH,MAAa,QAAgD,SAAQ,KAAK;IAS7D;IARX,IAAI,GAAG,UAAU,CAAA;IAEjB;;;;OAIG;IACH,YACW,KAAQ,EACjB,OAAgB,EAAE,gDAAgD;IAClE,OAAsB;QAEtB,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;QAJd,UAAK,GAAL,KAAK,CAAG;IAKnB,CAAC;IAED;;;;OAIG;IACH,QAAQ;QACN,OAAO,GAAG,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,OAAO,EAAE,CAAA;IACxD,CAAC;IAED;;;;;OAKG;IACH,MAAM;QACJ,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,IAAI,CAAA;QAC/B,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,CAAA;IACjD,CAAC;CACF;AAnCD,4BAmCC","sourcesContent":["/**\n * Error code type for Lexicon errors.\n *\n * Error codes identify the type of error that occurred (e.g., 'InvalidRequest').\n *\n * @example\n * ```typescript\n * import type { LexErrorCode } from '@atproto/lex-data'\n *\n * const errorCode: LexErrorCode = 'InvalidRequest'\n * ```\n */\nexport type LexErrorCode = string & NonNullable<unknown>\n\n/**\n * JSON-serializable error data structure.\n *\n * This is the standard format for error responses in the AT Protocol XRPC protocol.\n *\n * @typeParam N - The specific error code type\n *\n * @example\n * ```typescript\n * import type { LexErrorData } from '@atproto/lex-data'\n *\n * const errorData: LexErrorData = {\n * error: 'InvalidRequest',\n * message: 'Missing required field: handle'\n * }\n * ```\n */\nexport type LexErrorData<N extends LexErrorCode = LexErrorCode> = {\n /** The error code identifying the type of error. */\n error: N\n /** Optional human-readable error message. */\n message?: string\n}\n\n/**\n * Error class for Lexicon-related errors.\n *\n * LexError extends the standard JavaScript {@link Error} with AT\n * Protocol-specific functionality including an `error` code property and\n * methods for representation as (XRPC) error responses payloads.\n *\n * @typeParam N - The specific error code type\n */\nexport class LexError<N extends LexErrorCode = LexErrorCode> extends Error {\n name = 'LexError'\n\n /**\n * @param error - The error code identifying the type of error, typically used in XRPC error payloads\n * @param message - Optional human-readable error message\n * @param options - Standard Error options (e.g., cause)\n */\n constructor(\n readonly error: N,\n message?: string, // Defaults to empty string in Error constructor\n options?: ErrorOptions,\n ) {\n super(message, options)\n }\n\n /**\n * Returns a string representation of this error.\n *\n * @returns A formatted string: \"LexErrorClass: [MyErrorCode] My message\"\n */\n toString(): string {\n return `${this.name}: [${this.error}] ${this.message}`\n }\n\n /**\n * Converts this error to a JSON-serializable object.\n *\n * @returns The error data suitable for JSON serialization\n * @note The `error` generic is *not* constrained to {@link N} to allow subclasses to override the error code type.\n */\n toJSON(): LexErrorData<LexErrorCode> {\n const { error, message } = this\n return { error, message: message || undefined }\n }\n}\n"]}
|
package/dist/lex.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lex.d.ts","sourceRoot":"","sources":["../src/lex.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAS,MAAM,UAAU,CAAA;AAGrC;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,GAAG,GAAG,UAAU,CAAA;AAE3E;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,MAAM,QAAQ,GAAG,SAAS,GAAG,QAAQ,EAAE,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,EAAE,QAAQ;CAAE,CAAA;AAE5E;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,MAAM,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,EAAE,QAAQ;CAAE,CAAA;AAEjD;;;;;;;;;GASG;AACH,MAAM,MAAM,QAAQ,GAAG,QAAQ,EAAE,CAAA;AAEjC;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAExD;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAa9D;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,UAAU,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AA;CAAE,CAAA;AAE1E;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,QAAQ,GAAG,KAAK,IAAI,WAAW,CAInE"}
|
package/dist/lex.js
CHANGED
|
@@ -116,40 +116,20 @@ function isLexValue(value) {
|
|
|
116
116
|
const visited = new Set();
|
|
117
117
|
do {
|
|
118
118
|
const value = stack.pop();
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (visited.has(value))
|
|
134
|
-
return false;
|
|
135
|
-
visited.add(value);
|
|
136
|
-
stack.push(...value);
|
|
137
|
-
}
|
|
138
|
-
else if (value instanceof Uint8Array || (0, cid_js_1.isCid)(value)) {
|
|
139
|
-
// LexScalar
|
|
140
|
-
}
|
|
141
|
-
else {
|
|
142
|
-
return false;
|
|
143
|
-
}
|
|
144
|
-
break;
|
|
145
|
-
case 'string':
|
|
146
|
-
case 'boolean':
|
|
147
|
-
break;
|
|
148
|
-
case 'number':
|
|
149
|
-
if (Number.isInteger(value))
|
|
150
|
-
break;
|
|
151
|
-
// fallthrough
|
|
152
|
-
default:
|
|
119
|
+
if ((0, object_js_1.isPlainObject)(value)) {
|
|
120
|
+
if (visited.has(value))
|
|
121
|
+
return false;
|
|
122
|
+
visited.add(value);
|
|
123
|
+
stack.push(...Object.values(value));
|
|
124
|
+
}
|
|
125
|
+
else if (Array.isArray(value)) {
|
|
126
|
+
if (visited.has(value))
|
|
127
|
+
return false;
|
|
128
|
+
visited.add(value);
|
|
129
|
+
stack.push(...value);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
if (!isLexScalar(value))
|
|
153
133
|
return false;
|
|
154
134
|
}
|
|
155
135
|
} while (stack.length > 0);
|
package/dist/lex.js.map
CHANGED
|
@@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;AACb,CAAC;AAwBD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,aAAa,CAAC,KAAe;IAC3C,OAAO,CACL,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAC7E,CAAA;AACH,CAAC","sourcesContent":["import { Cid, isCid } from './cid.js'\nimport { isPlainObject, isPlainProto } from './object.js'\n\n/**\n * Primitive values in the Lexicon data model.\n *\n * Represents the basic scalar types that can appear in AT Protocol data:\n * - `number` - Integer values only (no floats)\n * - `string` - UTF-8 text\n * - `boolean` - true or false\n * - `null` - Explicit null value\n * - `Cid` - Content Identifier (link by hash)\n * - `Uint8Array` - Binary data (bytes)\n *\n * @see {@link LexValue} for the complete recursive value type\n */\nexport type LexScalar = number | string | boolean | null | Cid | Uint8Array\n\n/**\n * Any valid Lexicon value (recursive type).\n *\n * This is the union of all types that can appear in AT Protocol Lexicon data:\n * - {@link LexScalar} - Primitive values (number, string, boolean, null, Cid, Uint8Array)\n * - `LexValue[]` - Arrays of LexValues\n * - `{ [key: string]?: LexValue }` - Objects with string keys and LexValue values\n *\n * @example\n * ```typescript\n * import type { LexValue } from '@atproto/lex'\n *\n * const scalar: LexValue = 'hello'\n * const array: LexValue = [1, 2, 3]\n * const object: LexValue = { name: 'Alice', age: 30 }\n * ```\n *\n * @see {@link LexScalar} for primitive value types\n * @see {@link LexMap} for object types\n * @see {@link LexArray} for array types\n */\nexport type LexValue = LexScalar | LexValue[] | { [_ in string]?: LexValue }\n\n/**\n * Object with string keys and LexValue values.\n *\n * Represents a plain object in the Lexicon data model where all values\n * must be valid {@link LexValue} types.\n *\n * @example\n * ```typescript\n * import type { LexMap } from '@atproto/lex'\n *\n * const user: LexMap = {\n * name: 'Alice',\n * age: 30,\n * tags: ['admin', 'user']\n * }\n * ```\n *\n * @see {@link TypedLexMap} for objects with a required `$type` property\n */\nexport type LexMap = { [_ in string]?: LexValue }\n\n/**\n * Array of {@link LexValue} elements.\n *\n * @example\n * ```typescript\n * import type { LexArray } from '@atproto/lex'\n *\n * const items: LexArray = [1, 'two', { three: 3 }]\n * ```\n */\nexport type LexArray = LexValue[]\n\n/**\n * Type guard to check if a value is a valid {@link LexMap}.\n *\n * Returns true if the value is a plain object where all values are valid\n * {@link LexValue} types.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexMap\n *\n * @example\n * ```typescript\n * import { isLexMap } from '@atproto/lex'\n *\n * if (isLexMap(data)) {\n * // data is narrowed to LexMap\n * console.log(Object.keys(data))\n * }\n * ```\n */\nexport function isLexMap(value: unknown): value is LexMap {\n return isPlainObject(value) && Object.values(value).every(isLexValue)\n}\n\n/**\n * Type guard to check if a value is a valid {@link LexArray}.\n *\n * Returns true if the value is an array where all elements are valid\n * {@link LexValue} types.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexArray\n *\n * @example\n * ```typescript\n * import { isLexArray } from '@atproto/lex'\n *\n * if (isLexArray(data)) {\n * // data is narrowed to LexArray\n * data.forEach(item => console.log(item))\n * }\n * ```\n */\nexport function isLexArray(value: unknown): value is LexArray {\n return Array.isArray(value) && value.every(isLexValue)\n}\n\n/**\n * Type guard to check if a value is a valid {@link LexScalar}.\n *\n * Returns true if the value is one of the primitive Lexicon types:\n * number (integer only), string, boolean, null, Cid, or Uint8Array.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexScalar\n *\n * @example\n * ```typescript\n * import { isLexScalar } from '@atproto/lex'\n *\n * isLexScalar('hello') // true\n * isLexScalar(42) // true\n * isLexScalar(3.14) // false (floats not allowed)\n * isLexScalar([1, 2]) // false (arrays are not scalars)\n * ```\n */\nexport function isLexScalar(value: unknown): value is LexScalar {\n switch (typeof value) {\n case 'object':\n return value === null || value instanceof Uint8Array || isCid(value)\n case 'string':\n case 'boolean':\n return true\n case 'number':\n if (Number.isInteger(value)) return true\n // fallthrough\n default:\n return false\n }\n}\n\n/**\n * Type guard to check if a value is a valid {@link LexValue}.\n *\n * Performs a deep check to validate that the value (and all nested values)\n * conform to the Lexicon data model. This includes checking for:\n * - Valid scalar types (number, string, boolean, null, Cid, Uint8Array)\n * - Arrays containing only valid LexValues\n * - Plain objects with string keys and valid LexValue values\n * - No cyclic references (which cannot be serialized to JSON or CBOR)\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexValue\n *\n * @example\n * ```typescript\n * import { isLexValue } from '@atproto/lex'\n *\n * isLexValue({ name: 'Alice', tags: ['admin'] }) // true\n * isLexValue(new Date()) // false (not a plain object)\n * isLexValue({ fn: () => {} }) // false (functions not allowed)\n * ```\n */\nexport function isLexValue(value: unknown): value is LexValue {\n // Using a stack to avoid recursion depth issues.\n const stack: unknown[] = [value]\n // Cyclic structures are not valid LexValues as they cannot be serialized to\n // JSON or CBOR. This also allows us to avoid infinite loops when traversing\n // the structure.\n const visited = new Set<object>()\n\n do {\n const value = stack.pop()!\n\n // Optimization: we are not using `isLexScalar` here to avoid extra function\n // calls, and to avoid computing `typeof value` multiple times.\n switch (typeof value) {\n case 'object':\n if (value === null) {\n // LexScalar\n } else if (isPlainProto(value)) {\n if (visited.has(value)) return false\n visited.add(value)\n stack.push(...Object.values(value))\n } else if (Array.isArray(value)) {\n if (visited.has(value)) return false\n visited.add(value)\n stack.push(...value)\n } else if (value instanceof Uint8Array || isCid(value)) {\n // LexScalar\n } else {\n return false\n }\n break\n case 'string':\n case 'boolean':\n break\n case 'number':\n if (Number.isInteger(value)) break\n // fallthrough\n default:\n return false\n }\n } while (stack.length > 0)\n\n // Optimization: ease GC's work\n visited.clear()\n\n return true\n}\n\n/**\n * A {@link LexMap} with a required `$type` property.\n *\n * Used to represent typed objects in the Lexicon data model, where the\n * `$type` property identifies the Lexicon schema that defines the object's\n * structure.\n *\n * @example\n * ```typescript\n * import type { TypedLexMap } from '@atproto/lex'\n *\n * const post: TypedLexMap = {\n * $type: 'app.bsky.feed.post',\n * text: 'Hello world!',\n * createdAt: '2024-01-01T00:00:00Z'\n * }\n * ```\n *\n * @see {@link isTypedLexMap} to check if a value is a TypedLexMap\n */\nexport type TypedLexMap<T extends string = string> = LexMap & { $type: T }\n\n/**\n * Type guard to check if a value is a {@link TypedLexMap}.\n *\n * Returns true if the value is a valid {@link LexMap} with a non-empty\n * `$type` string property.\n *\n * @param value - The LexValue to check\n * @returns `true` if the value is a TypedLexMap\n *\n * @example\n * ```typescript\n * import { isTypedLexMap } from '@atproto/lex'\n *\n * const data = { $type: 'app.bsky.feed.post', text: 'Hello' }\n *\n * if (isTypedLexMap(data)) {\n * console.log(data.$type) // 'app.bsky.feed.post'\n * }\n * ```\n */\nexport function isTypedLexMap(value: LexValue): value is TypedLexMap {\n return (\n isLexMap(value) && typeof value.$type === 'string' && value.$type.length > 0\n )\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lex.js","sourceRoot":"","sources":["../src/lex.ts"],"names":[],"mappings":";;AA6FA,4BAEC;AAqBD,gCAEC;AAqBD,kCAaC;AAwBD,gCA4BC;AA4CD,sCAIC;AA5PD,qCAAqC;AACrC,2CAA2C;AAyE3C;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,QAAQ,CAAC,KAAc;IACrC,OAAO,IAAA,yBAAa,EAAC,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;AACvE,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,UAAU,CAAC,KAAc;IACvC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;AACxD,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,QAAQ,OAAO,KAAK,EAAE,CAAC;QACrB,KAAK,QAAQ;YACX,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,YAAY,UAAU,IAAI,I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IAC/B,OAAO,CAAC,KAAK,EAAE,CAAA;IAEf,OAAO,IAAI,CAAA;AACb,CAAC;AAwBD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,aAAa,CAAC,KAAe;IAC3C,OAAO,CACL,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAC7E,CAAA;AACH,CAAC","sourcesContent":["import { Cid, isCid } from './cid.js'\nimport { isPlainObject } from './object.js'\n\n/**\n * Primitive values in the Lexicon data model.\n *\n * Represents the basic scalar types that can appear in AT Protocol data:\n * - `number` - Integer values only (no floats)\n * - `string` - UTF-8 text\n * - `boolean` - true or false\n * - `null` - Explicit null value\n * - `Cid` - Content Identifier (link by hash)\n * - `Uint8Array` - Binary data (bytes)\n *\n * @see {@link LexValue} for the complete recursive value type\n */\nexport type LexScalar = number | string | boolean | null | Cid | Uint8Array\n\n/**\n * Any valid Lexicon value (recursive type).\n *\n * This is the union of all types that can appear in AT Protocol Lexicon data:\n * - {@link LexScalar} - Primitive values (number, string, boolean, null, Cid, Uint8Array)\n * - `LexValue[]` - Arrays of LexValues\n * - `{ [key: string]?: LexValue }` - Objects with string keys and LexValue values\n *\n * @example\n * ```typescript\n * import type { LexValue } from '@atproto/lex'\n *\n * const scalar: LexValue = 'hello'\n * const array: LexValue = [1, 2, 3]\n * const object: LexValue = { name: 'Alice', age: 30 }\n * ```\n *\n * @see {@link LexScalar} for primitive value types\n * @see {@link LexMap} for object types\n * @see {@link LexArray} for array types\n */\nexport type LexValue = LexScalar | LexValue[] | { [_ in string]?: LexValue }\n\n/**\n * Object with string keys and LexValue values.\n *\n * Represents a plain object in the Lexicon data model where all values\n * must be valid {@link LexValue} types.\n *\n * @example\n * ```typescript\n * import type { LexMap } from '@atproto/lex'\n *\n * const user: LexMap = {\n * name: 'Alice',\n * age: 30,\n * tags: ['admin', 'user']\n * }\n * ```\n *\n * @see {@link TypedLexMap} for objects with a required `$type` property\n */\nexport type LexMap = { [_ in string]?: LexValue }\n\n/**\n * Array of {@link LexValue} elements.\n *\n * @example\n * ```typescript\n * import type { LexArray } from '@atproto/lex'\n *\n * const items: LexArray = [1, 'two', { three: 3 }]\n * ```\n */\nexport type LexArray = LexValue[]\n\n/**\n * Type guard to check if a value is a valid {@link LexMap}.\n *\n * Returns true if the value is a plain object where all values are valid\n * {@link LexValue} types.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexMap\n *\n * @example\n * ```typescript\n * import { isLexMap } from '@atproto/lex'\n *\n * if (isLexMap(data)) {\n * // data is narrowed to LexMap\n * console.log(Object.keys(data))\n * }\n * ```\n */\nexport function isLexMap(value: unknown): value is LexMap {\n return isPlainObject(value) && Object.values(value).every(isLexValue)\n}\n\n/**\n * Type guard to check if a value is a valid {@link LexArray}.\n *\n * Returns true if the value is an array where all elements are valid\n * {@link LexValue} types.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexArray\n *\n * @example\n * ```typescript\n * import { isLexArray } from '@atproto/lex'\n *\n * if (isLexArray(data)) {\n * // data is narrowed to LexArray\n * data.forEach(item => console.log(item))\n * }\n * ```\n */\nexport function isLexArray(value: unknown): value is LexArray {\n return Array.isArray(value) && value.every(isLexValue)\n}\n\n/**\n * Type guard to check if a value is a valid {@link LexScalar}.\n *\n * Returns true if the value is one of the primitive Lexicon types:\n * number (integer only), string, boolean, null, Cid, or Uint8Array.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexScalar\n *\n * @example\n * ```typescript\n * import { isLexScalar } from '@atproto/lex'\n *\n * isLexScalar('hello') // true\n * isLexScalar(42) // true\n * isLexScalar(3.14) // false (floats not allowed)\n * isLexScalar([1, 2]) // false (arrays are not scalars)\n * ```\n */\nexport function isLexScalar(value: unknown): value is LexScalar {\n switch (typeof value) {\n case 'object':\n return value === null || value instanceof Uint8Array || isCid(value)\n case 'string':\n case 'boolean':\n return true\n case 'number':\n if (Number.isInteger(value)) return true\n // fallthrough\n default:\n return false\n }\n}\n\n/**\n * Type guard to check if a value is a valid {@link LexValue}.\n *\n * Performs a deep check to validate that the value (and all nested values)\n * conform to the Lexicon data model. This includes checking for:\n * - Valid scalar types (number, string, boolean, null, Cid, Uint8Array)\n * - Arrays containing only valid LexValues\n * - Plain objects with string keys and valid LexValue values\n * - No cyclic references (which cannot be serialized to JSON or CBOR)\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid LexValue\n *\n * @example\n * ```typescript\n * import { isLexValue } from '@atproto/lex'\n *\n * isLexValue({ name: 'Alice', tags: ['admin'] }) // true\n * isLexValue(new Date()) // false (not a plain object)\n * isLexValue({ fn: () => {} }) // false (functions not allowed)\n * ```\n */\nexport function isLexValue(value: unknown): value is LexValue {\n // Using a stack to avoid recursion depth issues.\n const stack: unknown[] = [value]\n // Cyclic structures are not valid LexValues as they cannot be serialized to\n // JSON or CBOR. This also allows us to avoid infinite loops when traversing\n // the structure.\n const visited = new Set<object>()\n\n do {\n const value = stack.pop()!\n\n if (isPlainObject(value)) {\n if (visited.has(value)) return false\n visited.add(value)\n stack.push(...Object.values(value))\n } else if (Array.isArray(value)) {\n if (visited.has(value)) return false\n visited.add(value)\n stack.push(...value)\n } else {\n if (!isLexScalar(value)) return false\n }\n } while (stack.length > 0)\n\n // Optimization: ease GC's work\n visited.clear()\n\n return true\n}\n\n/**\n * A {@link LexMap} with a required `$type` property.\n *\n * Used to represent typed objects in the Lexicon data model, where the\n * `$type` property identifies the Lexicon schema that defines the object's\n * structure.\n *\n * @example\n * ```typescript\n * import type { TypedLexMap } from '@atproto/lex'\n *\n * const post: TypedLexMap = {\n * $type: 'app.bsky.feed.post',\n * text: 'Hello world!',\n * createdAt: '2024-01-01T00:00:00Z'\n * }\n * ```\n *\n * @see {@link isTypedLexMap} to check if a value is a TypedLexMap\n */\nexport type TypedLexMap<T extends string = string> = LexMap & { $type: T }\n\n/**\n * Type guard to check if a value is a {@link TypedLexMap}.\n *\n * Returns true if the value is a valid {@link LexMap} with a non-empty\n * `$type` string property.\n *\n * @param value - The LexValue to check\n * @returns `true` if the value is a TypedLexMap\n *\n * @example\n * ```typescript\n * import { isTypedLexMap } from '@atproto/lex'\n *\n * const data = { $type: 'app.bsky.feed.post', text: 'Hello' }\n *\n * if (isTypedLexMap(data)) {\n * console.log(data.$type) // 'app.bsky.feed.post'\n * }\n * ```\n */\nexport function isTypedLexMap(value: LexValue): value is TypedLexMap {\n return (\n isLexMap(value) && typeof value.$type === 'string' && value.$type.length > 0\n )\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../src/lib/util.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,MAAM,CAEnD"}
|
package/dist/lib/util.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toHexString = toHexString;
|
|
4
|
+
exports.isUint8 = isUint8;
|
|
5
|
+
function toHexString(number) {
|
|
6
|
+
return `0x${number.toString(16).padStart(2, '0')}`;
|
|
7
|
+
}
|
|
8
|
+
function isUint8(val) {
|
|
9
|
+
return Number.isInteger(val) && val >= 0 && val < 256;
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=util.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/lib/util.ts"],"names":[],"mappings":";;AAAA,kCAEC;AAED,0BAEC;AAND,SAAgB,WAAW,CAAC,MAAc;IACxC,OAAO,KAAK,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAA;AACpD,CAAC;AAED,SAAgB,OAAO,CAAC,GAAY;IAClC,OAAO,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,IAAK,GAAc,IAAI,CAAC,IAAK,GAAc,GAAG,GAAG,CAAA;AAC/E,CAAC","sourcesContent":["export function toHexString(number: number): string {\n return `0x${number.toString(16).padStart(2, '0')}`\n}\n\nexport function isUint8(val: unknown): val is number {\n return Number.isInteger(val) && (val as number) >= 0 && (val as number) < 256\n}\n"]}
|
package/package.json
CHANGED
package/src/cid.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { CID } from 'multiformats/cid'
|
|
2
2
|
import { create as createDigest } from 'multiformats/hashes/digest'
|
|
3
3
|
import { sha256, sha512 } from 'multiformats/hashes/sha2'
|
|
4
|
+
import { isUint8, toHexString } from './lib/util.js'
|
|
4
5
|
import { isObject } from './object.js'
|
|
5
6
|
import { ui8Equals } from './uint8array.js'
|
|
6
7
|
|
|
@@ -286,11 +287,12 @@ export type CheckCidOptions = {
|
|
|
286
287
|
*
|
|
287
288
|
* @typeParam TOptions - The options used for checking
|
|
288
289
|
*/
|
|
289
|
-
export type InferCheckedCid<TOptions
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
290
|
+
export type InferCheckedCid<TOptions extends CheckCidOptions> =
|
|
291
|
+
TOptions extends { flavor: 'raw' }
|
|
292
|
+
? RawCid
|
|
293
|
+
: TOptions extends { flavor: 'cbor' }
|
|
294
|
+
? CborCid
|
|
295
|
+
: Cid
|
|
294
296
|
|
|
295
297
|
/**
|
|
296
298
|
* Type guard to check whether a {@link Cid} instance meets specific flavor
|
|
@@ -341,7 +343,7 @@ export function ifCid<TValue>(
|
|
|
341
343
|
options?: CheckCidOptions,
|
|
342
344
|
): (TValue & Cid) | null
|
|
343
345
|
export function ifCid(value: unknown, options?: CheckCidOptions): Cid | null {
|
|
344
|
-
if (
|
|
346
|
+
if (isCid(value, options)) return value
|
|
345
347
|
return null
|
|
346
348
|
}
|
|
347
349
|
|
|
@@ -357,10 +359,12 @@ export function asCid<TValue, TOptions extends CheckCidOptions>(
|
|
|
357
359
|
export function asCid<TValue>(
|
|
358
360
|
value: TValue,
|
|
359
361
|
options?: CheckCidOptions,
|
|
360
|
-
):
|
|
362
|
+
): TValue & Cid
|
|
361
363
|
export function asCid(value: unknown, options?: CheckCidOptions): Cid {
|
|
362
|
-
if (
|
|
363
|
-
throw new Error(
|
|
364
|
+
if (isCid(value, options)) return value
|
|
365
|
+
throw new Error(
|
|
366
|
+
`Invalid ${options?.flavor ? `${options.flavor} CID` : 'CID'} "${value}"`,
|
|
367
|
+
)
|
|
364
368
|
}
|
|
365
369
|
|
|
366
370
|
/**
|
|
@@ -462,7 +466,7 @@ export function ensureValidCidString(
|
|
|
462
466
|
options?: CheckCidOptions,
|
|
463
467
|
): void {
|
|
464
468
|
if (!validateCidString(input, options)) {
|
|
465
|
-
throw new Error(`Invalid CID string`)
|
|
469
|
+
throw new Error(`Invalid CID string "${input}"`)
|
|
466
470
|
}
|
|
467
471
|
}
|
|
468
472
|
|
|
@@ -487,7 +491,9 @@ export async function isCidForBytes(
|
|
|
487
491
|
}
|
|
488
492
|
|
|
489
493
|
// Don't know how to verify other multihash codes
|
|
490
|
-
throw new Error(
|
|
494
|
+
throw new Error(
|
|
495
|
+
`Unsupported CID multihash code: ${toHexString(cid.multihash.code)}`,
|
|
496
|
+
)
|
|
491
497
|
}
|
|
492
498
|
|
|
493
499
|
/**
|
|
@@ -545,12 +551,14 @@ export async function cidForRawBytes(bytes: Uint8Array): Promise<RawCid> {
|
|
|
545
551
|
*
|
|
546
552
|
* @param digest - The SHA-256 hash digest (must be 32 bytes)
|
|
547
553
|
* @returns A RawCid with the given digest
|
|
548
|
-
* @throws If the digest
|
|
554
|
+
* @throws If the digest is not a valid SHA-256 hash (not 32 bytes)
|
|
549
555
|
*/
|
|
550
556
|
export function cidForRawHash(digest: Uint8Array): RawCid {
|
|
551
557
|
// Fool-proofing
|
|
552
|
-
if (digest.length !==
|
|
553
|
-
throw new Error(
|
|
558
|
+
if (digest.length !== 0x20) {
|
|
559
|
+
throw new Error(
|
|
560
|
+
`Invalid SHA-256 hash length: ${toHexString(digest.length)}`,
|
|
561
|
+
)
|
|
554
562
|
}
|
|
555
563
|
return createCid(RAW_DATA_CODEC, sha256.code, digest)
|
|
556
564
|
}
|
|
@@ -592,7 +600,3 @@ function isCidImplementation(value: unknown): value is Cid {
|
|
|
592
600
|
}
|
|
593
601
|
}
|
|
594
602
|
}
|
|
595
|
-
|
|
596
|
-
function isUint8(val: unknown): val is number {
|
|
597
|
-
return Number.isInteger(val) && (val as number) >= 0 && (val as number) < 256
|
|
598
|
-
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { LexError } from './lex-error.js'
|
|
3
|
+
|
|
4
|
+
describe(LexError, () => {
|
|
5
|
+
it('stores error code and message', () => {
|
|
6
|
+
const err = new LexError('TestError', 'This is a test error')
|
|
7
|
+
expect(err.error).toBe('TestError')
|
|
8
|
+
expect(err.message).toBe('This is a test error')
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('strips empty message in toJSON output', () => {
|
|
12
|
+
const err = new LexError('TestError')
|
|
13
|
+
expect(err.toJSON()).toEqual({ error: 'TestError' })
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('includes message in toJSON when present', () => {
|
|
17
|
+
const err = new LexError('TestError', 'details here')
|
|
18
|
+
expect(err.toJSON()).toEqual({
|
|
19
|
+
error: 'TestError',
|
|
20
|
+
message: 'details here',
|
|
21
|
+
})
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('formats string output correctly', () => {
|
|
25
|
+
const err = new LexError('TestError', 'This is a test error')
|
|
26
|
+
expect(err.toString()).toBe('LexError: [TestError] This is a test error')
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('uses constructor name for the name property', () => {
|
|
30
|
+
const err = new LexError('TestError')
|
|
31
|
+
expect(err.name).toBe('LexError')
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('subclasses use their own constructor name', () => {
|
|
35
|
+
class MyCustomError extends LexError {
|
|
36
|
+
name = 'MyCustomError'
|
|
37
|
+
}
|
|
38
|
+
const err = new MyCustomError('CustomCode', 'custom message')
|
|
39
|
+
expect(err.name).toBe('MyCustomError')
|
|
40
|
+
expect(err.toString()).toBe('MyCustomError: [CustomCode] custom message')
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('preserves cause option', () => {
|
|
44
|
+
const cause = new Error('original')
|
|
45
|
+
const err = new LexError('TestError', 'wrapped', { cause })
|
|
46
|
+
expect(err.cause).toBe(cause)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('is an instance of Error', () => {
|
|
50
|
+
const err = new LexError('TestError')
|
|
51
|
+
expect(err).toBeInstanceOf(Error)
|
|
52
|
+
expect(err).toBeInstanceOf(LexError)
|
|
53
|
+
})
|
|
54
|
+
})
|
package/src/lex-error.ts
CHANGED
|
@@ -39,37 +39,17 @@ export type LexErrorData<N extends LexErrorCode = LexErrorCode> = {
|
|
|
39
39
|
/**
|
|
40
40
|
* Error class for Lexicon-related errors.
|
|
41
41
|
*
|
|
42
|
-
* LexError extends the standard JavaScript {@link Error} with AT
|
|
43
|
-
* functionality including
|
|
44
|
-
*
|
|
45
|
-
* - JSON serialization for API responses
|
|
46
|
-
* - HTTP Response generation
|
|
42
|
+
* LexError extends the standard JavaScript {@link Error} with AT
|
|
43
|
+
* Protocol-specific functionality including an `error` code property and
|
|
44
|
+
* methods for representation as (XRPC) error responses payloads.
|
|
47
45
|
*
|
|
48
46
|
* @typeParam N - The specific error code type
|
|
49
|
-
*
|
|
50
|
-
* @example
|
|
51
|
-
* ```typescript
|
|
52
|
-
* import { LexError } from '@atproto/lex-data'
|
|
53
|
-
*
|
|
54
|
-
* // Throw a Lexicon error
|
|
55
|
-
* throw new LexError('InvalidRequest', 'Missing required field')
|
|
56
|
-
*
|
|
57
|
-
* // Create and serialize
|
|
58
|
-
* const error = new LexError('NotFound', 'Record not found')
|
|
59
|
-
* console.log(error.toJSON())
|
|
60
|
-
* // { error: 'NotFound', message: 'Record not found' }
|
|
61
|
-
*
|
|
62
|
-
* // Return as HTTP response
|
|
63
|
-
* return error.toResponse() // 400 Bad Request with JSON body
|
|
64
|
-
* ```
|
|
65
47
|
*/
|
|
66
48
|
export class LexError<N extends LexErrorCode = LexErrorCode> extends Error {
|
|
67
49
|
name = 'LexError'
|
|
68
50
|
|
|
69
51
|
/**
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* @param error - The error code identifying the type of error
|
|
52
|
+
* @param error - The error code identifying the type of error, typically used in XRPC error payloads
|
|
73
53
|
* @param message - Optional human-readable error message
|
|
74
54
|
* @param options - Standard Error options (e.g., cause)
|
|
75
55
|
*/
|
|
@@ -84,7 +64,7 @@ export class LexError<N extends LexErrorCode = LexErrorCode> extends Error {
|
|
|
84
64
|
/**
|
|
85
65
|
* Returns a string representation of this error.
|
|
86
66
|
*
|
|
87
|
-
* @returns A formatted string: "
|
|
67
|
+
* @returns A formatted string: "LexErrorClass: [MyErrorCode] My message"
|
|
88
68
|
*/
|
|
89
69
|
toString(): string {
|
|
90
70
|
return `${this.name}: [${this.error}] ${this.message}`
|
|
@@ -94,20 +74,10 @@ export class LexError<N extends LexErrorCode = LexErrorCode> extends Error {
|
|
|
94
74
|
* Converts this error to a JSON-serializable object.
|
|
95
75
|
*
|
|
96
76
|
* @returns The error data suitable for JSON serialization
|
|
77
|
+
* @note The `error` generic is *not* constrained to {@link N} to allow subclasses to override the error code type.
|
|
97
78
|
*/
|
|
98
|
-
toJSON(): LexErrorData<
|
|
79
|
+
toJSON(): LexErrorData<LexErrorCode> {
|
|
99
80
|
const { error, message } = this
|
|
100
81
|
return { error, message: message || undefined }
|
|
101
82
|
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Converts this error to an HTTP Response for downstream clients.
|
|
105
|
-
*
|
|
106
|
-
* Returns a 400 Bad Request response with the JSON-serialized error body.
|
|
107
|
-
*
|
|
108
|
-
* @returns A Response object with status 400 and JSON body
|
|
109
|
-
*/
|
|
110
|
-
toResponse(): Response {
|
|
111
|
-
return Response.json(this.toJSON(), { status: 400 })
|
|
112
|
-
}
|
|
113
83
|
}
|
package/src/lex.test.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
|
|
|
2
2
|
import { parseCid } from './cid.js'
|
|
3
3
|
import { isLexArray, isLexScalar, isLexValue, isTypedLexMap } from './lex.js'
|
|
4
4
|
|
|
5
|
-
describe(
|
|
5
|
+
describe(isLexScalar, () => {
|
|
6
6
|
for (const { note, value, expected } of [
|
|
7
7
|
{ note: 'string', value: 'hello', expected: true },
|
|
8
8
|
{ note: 'boolean', value: true, expected: true },
|
|
@@ -29,7 +29,7 @@ describe('isLexScalar', () => {
|
|
|
29
29
|
}
|
|
30
30
|
})
|
|
31
31
|
|
|
32
|
-
describe(
|
|
32
|
+
describe(isLexArray, () => {
|
|
33
33
|
it('returns true for valid LexArray', () => {
|
|
34
34
|
const list = [123, 'blah', true, null, new Uint8Array([1, 2, 3]), { a: 1 }]
|
|
35
35
|
expect(isLexArray(list)).toBe(true)
|
|
@@ -55,7 +55,7 @@ describe('isLexArray', () => {
|
|
|
55
55
|
})
|
|
56
56
|
})
|
|
57
57
|
|
|
58
|
-
describe(
|
|
58
|
+
describe(isLexValue, () => {
|
|
59
59
|
describe('valid values', () => {
|
|
60
60
|
for (const { note, value } of [
|
|
61
61
|
{ note: 'string', value: 'hello' },
|
package/src/lex.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Cid, isCid } from './cid.js'
|
|
2
|
-
import { isPlainObject
|
|
2
|
+
import { isPlainObject } from './object.js'
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Primitive values in the Lexicon data model.
|
|
@@ -185,34 +185,16 @@ export function isLexValue(value: unknown): value is LexValue {
|
|
|
185
185
|
do {
|
|
186
186
|
const value = stack.pop()!
|
|
187
187
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
} else if (Array.isArray(value)) {
|
|
199
|
-
if (visited.has(value)) return false
|
|
200
|
-
visited.add(value)
|
|
201
|
-
stack.push(...value)
|
|
202
|
-
} else if (value instanceof Uint8Array || isCid(value)) {
|
|
203
|
-
// LexScalar
|
|
204
|
-
} else {
|
|
205
|
-
return false
|
|
206
|
-
}
|
|
207
|
-
break
|
|
208
|
-
case 'string':
|
|
209
|
-
case 'boolean':
|
|
210
|
-
break
|
|
211
|
-
case 'number':
|
|
212
|
-
if (Number.isInteger(value)) break
|
|
213
|
-
// fallthrough
|
|
214
|
-
default:
|
|
215
|
-
return false
|
|
188
|
+
if (isPlainObject(value)) {
|
|
189
|
+
if (visited.has(value)) return false
|
|
190
|
+
visited.add(value)
|
|
191
|
+
stack.push(...Object.values(value))
|
|
192
|
+
} else if (Array.isArray(value)) {
|
|
193
|
+
if (visited.has(value)) return false
|
|
194
|
+
visited.add(value)
|
|
195
|
+
stack.push(...value)
|
|
196
|
+
} else {
|
|
197
|
+
if (!isLexScalar(value)) return false
|
|
216
198
|
}
|
|
217
199
|
} while (stack.length > 0)
|
|
218
200
|
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { isUint8, toHexString } from './util.js'
|
|
3
|
+
|
|
4
|
+
describe(toHexString, () => {
|
|
5
|
+
it('converts 0 to 0x00', () => {
|
|
6
|
+
expect(toHexString(0)).toBe('0x00')
|
|
7
|
+
})
|
|
8
|
+
|
|
9
|
+
it('converts single-digit hex values with padding', () => {
|
|
10
|
+
expect(toHexString(1)).toBe('0x01')
|
|
11
|
+
expect(toHexString(15)).toBe('0x0f')
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('converts two-digit hex values without extra padding', () => {
|
|
15
|
+
expect(toHexString(16)).toBe('0x10')
|
|
16
|
+
expect(toHexString(255)).toBe('0xff')
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('converts larger numbers', () => {
|
|
20
|
+
expect(toHexString(256)).toBe('0x100')
|
|
21
|
+
expect(toHexString(4096)).toBe('0x1000')
|
|
22
|
+
})
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
describe(isUint8, () => {
|
|
26
|
+
it('returns true for valid uint8 values', () => {
|
|
27
|
+
expect(isUint8(0)).toBe(true)
|
|
28
|
+
expect(isUint8(1)).toBe(true)
|
|
29
|
+
expect(isUint8(127)).toBe(true)
|
|
30
|
+
expect(isUint8(255)).toBe(true)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('returns false for values outside uint8 range', () => {
|
|
34
|
+
expect(isUint8(-1)).toBe(false)
|
|
35
|
+
expect(isUint8(256)).toBe(false)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('returns false for non-integer numbers', () => {
|
|
39
|
+
expect(isUint8(1.5)).toBe(false)
|
|
40
|
+
expect(isUint8(0.1)).toBe(false)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('returns false for non-number types', () => {
|
|
44
|
+
expect(isUint8('0')).toBe(false)
|
|
45
|
+
expect(isUint8(null)).toBe(false)
|
|
46
|
+
expect(isUint8(undefined)).toBe(false)
|
|
47
|
+
expect(isUint8(true)).toBe(false)
|
|
48
|
+
})
|
|
49
|
+
})
|
package/src/lib/util.ts
ADDED