cipher-kit 2.0.0 → 2.1.1

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.
Files changed (40) hide show
  1. package/README.md +26 -28
  2. package/dist/{chunk-N2EW2FDZ.cjs → chunk-56PVVFVM.cjs} +187 -152
  3. package/dist/chunk-56PVVFVM.cjs.map +1 -0
  4. package/dist/{chunk-FKSYSPJR.js → chunk-6C4NIWQ4.js} +24 -22
  5. package/dist/chunk-6C4NIWQ4.js.map +1 -0
  6. package/dist/{chunk-4MFF6V3R.js → chunk-FSEA3UXJ.js} +80 -45
  7. package/dist/chunk-FSEA3UXJ.js.map +1 -0
  8. package/dist/{chunk-CVCDAHDW.cjs → chunk-LTVOIZP5.cjs} +193 -158
  9. package/dist/chunk-LTVOIZP5.cjs.map +1 -0
  10. package/dist/{chunk-ACFPMIXO.js → chunk-PWTFVMW6.js} +79 -44
  11. package/dist/chunk-PWTFVMW6.js.map +1 -0
  12. package/dist/{chunk-3UX5MZ2P.cjs → chunk-X4CS7UXE.cjs} +25 -22
  13. package/dist/chunk-X4CS7UXE.cjs.map +1 -0
  14. package/dist/{export-55tHE0Bw.d.cts → export-C4DbO5zM.d.ts} +200 -26
  15. package/dist/{export-llM6c7Do.d.ts → export-CpZ7s25O.d.cts} +200 -26
  16. package/dist/{export-CQNsJFh_.d.cts → export-DO9n7Np-.d.cts} +200 -26
  17. package/dist/{export-BMvZq46v.d.ts → export-DUgIcobC.d.ts} +200 -26
  18. package/dist/index.cjs +12 -12
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +3 -3
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +3 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/node.cjs +33 -33
  25. package/dist/node.d.cts +2 -2
  26. package/dist/node.d.ts +2 -2
  27. package/dist/node.js +2 -2
  28. package/dist/{validate-EHuJC5QQ.d.cts → validate-cJEdGlj1.d.cts} +54 -67
  29. package/dist/{validate-EHuJC5QQ.d.ts → validate-cJEdGlj1.d.ts} +54 -67
  30. package/dist/web-api.cjs +33 -33
  31. package/dist/web-api.d.cts +2 -2
  32. package/dist/web-api.d.ts +2 -2
  33. package/dist/web-api.js +2 -2
  34. package/package.json +6 -7
  35. package/dist/chunk-3UX5MZ2P.cjs.map +0 -1
  36. package/dist/chunk-4MFF6V3R.js.map +0 -1
  37. package/dist/chunk-ACFPMIXO.js.map +0 -1
  38. package/dist/chunk-CVCDAHDW.cjs.map +0 -1
  39. package/dist/chunk-FKSYSPJR.js.map +0 -1
  40. package/dist/chunk-N2EW2FDZ.cjs.map +0 -1
@@ -30,22 +30,22 @@ var ENCRYPTION_ALGORITHMS = Object.freeze({
30
30
  function $isStr(x, min = 1) {
31
31
  return x !== null && x !== void 0 && typeof x === "string" && x.trim().length >= min;
32
32
  }
33
- function $isObj(x) {
33
+ function $isPlainObj(x) {
34
34
  if (typeof x !== "object" || x === null || x === void 0) return false;
35
35
  const proto = Object.getPrototypeOf(x);
36
36
  return proto === Object.prototype || proto === null;
37
37
  }
38
- function $isLooseObj(x) {
38
+ function $isObj(x) {
39
39
  return typeof x === "object" && x !== null && x !== void 0;
40
40
  }
41
41
  var expectedKeys = /* @__PURE__ */ new Set(["platform", "digest", "algorithm", "key"]);
42
42
  function $isSecretKey(x, platform) {
43
- if (!$isLooseObj(x) || platform !== "node" && platform !== "web" || x.platform !== platform) return null;
43
+ if (!$isObj(x) || platform !== "node" && platform !== "web" || x.platform !== platform) return null;
44
44
  const keys = Object.keys(x);
45
45
  if (keys.length !== expectedKeys.size) return null;
46
46
  for (const key of keys) if (!expectedKeys.has(key)) return null;
47
47
  for (const key of expectedKeys) if (!Object.hasOwn(x, key)) return null;
48
- if (typeof x.digest !== "string" || !(x.digest in DIGEST_ALGORITHMS) || typeof x.algorithm !== "string" || !(x.algorithm in ENCRYPTION_ALGORITHMS) || !$isLooseObj(x.key) || x.key.type !== "secret") {
48
+ if (typeof x.digest !== "string" || !(x.digest in DIGEST_ALGORITHMS) || typeof x.algorithm !== "string" || !(x.algorithm in ENCRYPTION_ALGORITHMS) || !$isObj(x.key) || x.key.type !== "secret") {
49
49
  return null;
50
50
  }
51
51
  const algorithm = ENCRYPTION_ALGORITHMS[x.algorithm];
@@ -55,7 +55,7 @@ function $isSecretKey(x, platform) {
55
55
  }
56
56
  return Object.freeze({ ...x, injected: algorithm });
57
57
  }
58
- if (!$isLooseObj(x.key.algorithm) || x.key.algorithm.name !== algorithm.web || typeof x.key.algorithm.length === "number" && x.key.algorithm.length !== algorithm.keyBytes * 8 || typeof x.key.extractable !== "boolean" || !Array.isArray(x.key.usages) || x.key.usages.length !== 2 || !(x.key.usages.includes("encrypt") && x.key.usages.includes("decrypt"))) {
58
+ if (!$isObj(x.key.algorithm) || x.key.algorithm.name !== algorithm.web || typeof x.key.algorithm.length === "number" && x.key.algorithm.length !== algorithm.keyBytes * 8 || typeof x.key.extractable !== "boolean" || !Array.isArray(x.key.usages) || x.key.usages.length !== 2 || !(x.key.usages.includes("encrypt") && x.key.usages.includes("decrypt"))) {
59
59
  return null;
60
60
  }
61
61
  return Object.freeze({ ...x, injected: algorithm });
@@ -65,7 +65,7 @@ var ENCRYPTED_REGEX = Object.freeze({
65
65
  web: /^([^.]+)\.([^.]+)\.$/,
66
66
  general: /^([^.]+)\.([^.]+)(?:\.([^.]+))?\.$/
67
67
  });
68
- function matchPattern(data, format) {
68
+ function matchEncryptedPattern(data, format) {
69
69
  if (typeof data !== "string") return false;
70
70
  if (!(format in ENCRYPTED_REGEX)) throw new Error(`Unknown format: ${format}`);
71
71
  return ENCRYPTED_REGEX[format].test(data);
@@ -73,7 +73,7 @@ function matchPattern(data, format) {
73
73
 
74
74
  // src/helpers/error.ts
75
75
  function $ok(result) {
76
- if ($isObj(result)) return { success: true, ...result };
76
+ if ($isPlainObj(result)) return { success: true, ...result };
77
77
  return { success: true, result };
78
78
  }
79
79
  function $err(err) {
@@ -101,10 +101,22 @@ function title(platform, title2) {
101
101
  // src/helpers/object.ts
102
102
  function $stringifyObj(obj) {
103
103
  try {
104
- if (!$isObj(obj)) return $err({ msg: "Invalid object", desc: "Input is not a plain object" });
104
+ if (!$isPlainObj(obj)) return $err({ msg: "JSON: Invalid object", desc: "Input is not a plain object" });
105
105
  return $ok(JSON.stringify(obj));
106
106
  } catch (error) {
107
- return $err({ msg: "Utility: Stringify error", desc: $fmtError(error) });
107
+ return $err({ msg: "JSON: Stringify error", desc: $fmtError(error) });
108
+ }
109
+ }
110
+ function $parseToObj(str) {
111
+ try {
112
+ if (!$isStr(str)) return $err({ msg: "JSON: Invalid input", desc: "Input is not a valid string" });
113
+ const obj = JSON.parse(str);
114
+ if (!$isPlainObj(obj)) {
115
+ return $err({ msg: "JSON: Invalid object format", desc: "Parsed data is not a plain object" });
116
+ }
117
+ return $ok({ result: obj });
118
+ } catch (error) {
119
+ return $err({ msg: "JSON: Invalid format", desc: $fmtError(error) });
108
120
  }
109
121
  }
110
122
  function tryStringifyObj(obj) {
@@ -115,16 +127,6 @@ function stringifyObj(obj) {
115
127
  if (error) throw new Error($fmtResultErr(error));
116
128
  return result;
117
129
  }
118
- function $parseToObj(str) {
119
- try {
120
- if (!$isStr(str)) return $err({ msg: "Utility: Invalid input", desc: "Input is not a valid string" });
121
- const obj = JSON.parse(str);
122
- if (!$isObj(obj)) return $err({ msg: "Utility: Invalid object format", desc: "Parsed data is not a plain object" });
123
- return $ok({ result: obj });
124
- } catch (error) {
125
- return $err({ msg: "Utility: Invalid format", desc: $fmtError(error) });
126
- }
127
- }
128
130
  function tryParseToObj(str) {
129
131
  return $parseToObj(str);
130
132
  }
@@ -137,6 +139,7 @@ function parseToObj(str) {
137
139
  exports.$err = $err;
138
140
  exports.$fmtError = $fmtError;
139
141
  exports.$fmtResultErr = $fmtResultErr;
142
+ exports.$isPlainObj = $isPlainObj;
140
143
  exports.$isSecretKey = $isSecretKey;
141
144
  exports.$isStr = $isStr;
142
145
  exports.$ok = $ok;
@@ -148,11 +151,11 @@ exports.ENCODING = ENCODING;
148
151
  exports.ENCRYPTED_REGEX = ENCRYPTED_REGEX;
149
152
  exports.ENCRYPTION_ALGORITHMS = ENCRYPTION_ALGORITHMS;
150
153
  exports.__export = __export;
151
- exports.matchPattern = matchPattern;
154
+ exports.matchEncryptedPattern = matchEncryptedPattern;
152
155
  exports.parseToObj = parseToObj;
153
156
  exports.stringifyObj = stringifyObj;
154
157
  exports.title = title;
155
158
  exports.tryParseToObj = tryParseToObj;
156
159
  exports.tryStringifyObj = tryStringifyObj;
157
- //# sourceMappingURL=chunk-3UX5MZ2P.cjs.map
158
- //# sourceMappingURL=chunk-3UX5MZ2P.cjs.map
160
+ //# sourceMappingURL=chunk-X4CS7UXE.cjs.map
161
+ //# sourceMappingURL=chunk-X4CS7UXE.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/helpers/consts.ts","../src/helpers/validate.ts","../src/helpers/error.ts","../src/helpers/object.ts"],"names":["nodeCrypto","title"],"mappings":";;;;;;;;;;;;;;;AAAO,IAAM,QAAA,GAAW,OAAO,MAAA,CAAO,CAAC,UAAU,WAAA,EAAa,KAAA,EAAO,MAAA,EAAQ,QAAQ,CAAU;AAExF,IAAM,kBAAkB,MAAA,CAAO,MAAA,CAAO,CAAC,QAAA,EAAU,WAAA,EAAa,KAAK,CAAU;AAE7E,IAAM,iBAAA,GAAoB,OAAO,MAAA,CAAO;AAAA,EAC7C,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,KAAK,SAAA,EAAU;AAAA,EACzC,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,KAAK,SAAA,EAAU;AAAA,EACzC,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,KAAK,SAAA;AACjC,CAAU;AAEH,IAAM,qBAAA,GAAwB,OAAO,MAAA,CAAO;AAAA,EACjD,SAAA,EAAW,EAAE,QAAA,EAAU,EAAA,EAAI,UAAU,EAAA,EAAI,IAAA,EAAM,aAAA,E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f8\", \"latin1\"] as const);\r\n\r\nexport const CIPHER_ENCODING = Object.freeze([\"base64\", \"base64url\", \"hex\"] as const);\r\n\r\nexport const DIGEST_ALGORITHMS = Object.freeze({\r\n sha256: { node: \"sha256\", web: \"SHA-256\" },\r\n sha384: { node: \"sha384\", web: \"SHA-384\" },\r\n sha512: { node: \"sha512\", web: \"SHA-512\" },\r\n} as const);\r\n\r\nexport const ENCRYPTION_ALGORITHMS = Object.freeze({\r\n aes256gcm: { keyBytes: 32, ivLength: 12, node: \"aes-256-gcm\", web: \"AES-GCM\" },\r\n aes192gcm: { keyBytes: 24, ivLength: 12, node: \"aes-192-gcm\", web: \"AES-GCM\" },\r\n aes128gcm: { keyBytes: 16, ivLength: 12, node: \"aes-128-gcm\", web: \"AES-GCM\" },\r\n} as const);\r\n","import nodeCrypto from \"node:crypto\";\r\nimport type { SecretKey } from \"~/helpers/types\";\r\nimport { DIGEST_ALGORITHMS, ENCRYPTION_ALGORITHMS } from \"./consts\";\r\n\r\nexport function $isStr(x: unknown, min = 1): x is string {\r\n return x !== null && x !== undefined && typeof x === \"string\" && x.trim().length >= min;\r\n}\r\n\r\nexport function $isPlainObj<T extends object = Record<string, unknown>>(x: unknown): x is T {\r\n if (typeof x !== \"object\" || x === null || x === undefined) return false;\r\n const proto = Object.getPrototypeOf(x);\r\n return proto === Object.prototype || proto === null;\r\n}\r\n\r\nexport function $isObj(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && x !== undefined;\r\n}\r\n\r\ntype InjectedSecretKey<Platform extends \"web\" | \"node\"> = SecretKey<Platform> & {\r\n readonly injected: (typeof ENCRYPTION_ALGORITHMS)[keyof typeof ENCRYPTION_ALGORITHMS];\r\n};\r\n\r\nconst expectedKeys = new Set([\"platform\", \"digest\", \"algorithm\", \"key\"]);\r\n\r\nexport function $isSecretKey<Platform extends \"node\" | \"web\">(\r\n x: unknown,\r\n platform: Platform,\r\n): InjectedSecretKey<Platform> | null {\r\n if (!$isObj(x) || (platform !== \"node\" && platform !== \"web\") || x.platform !== platform) return null;\r\n\r\n const keys = Object.keys(x);\r\n if (keys.length !== expectedKeys.size) return null;\r\n for (const key of keys) if (!expectedKeys.has(key)) return null;\r\n for (const key of expectedKeys) if (!Object.hasOwn(x, key)) return null;\r\n\r\n if (\r\n typeof x.digest !== \"string\" ||\r\n !(x.digest in DIGEST_ALGORITHMS) ||\r\n typeof x.algorithm !== \"string\" ||\r\n !(x.algorithm in ENCRYPTION_ALGORITHMS) ||\r\n !$isObj(x.key) ||\r\n x.key.type !== \"secret\"\r\n ) {\r\n return null;\r\n }\r\n\r\n const algorithm = ENCRYPTION_ALGORITHMS[x.algorithm as keyof typeof ENCRYPTION_ALGORITHMS];\r\n\r\n if (platform === \"node\") {\r\n if (\r\n !(x.key instanceof nodeCrypto.KeyObject) ||\r\n (typeof x.key.symmetricKeySize === \"number\" && x.key.symmetricKeySize !== algorithm.keyBytes)\r\n ) {\r\n return null;\r\n }\r\n return Object.freeze({ ...x, injected: algorithm }) as InjectedSecretKey<Platform>;\r\n }\r\n\r\n if (\r\n !$isObj(x.key.algorithm) ||\r\n x.key.algorithm.name !== algorithm.web ||\r\n (typeof x.key.algorithm.length === \"number\" && x.key.algorithm.length !== algorithm.keyBytes * 8) ||\r\n typeof x.key.extractable !== \"boolean\" ||\r\n !Array.isArray(x.key.usages) ||\r\n x.key.usages.length !== 2 ||\r\n !(x.key.usages.includes(\"encrypt\") && x.key.usages.includes(\"decrypt\"))\r\n ) {\r\n return null;\r\n }\r\n return Object.freeze({ ...x, injected: algorithm }) as InjectedSecretKey<Platform>;\r\n}\r\n\r\n/**\r\n * Regular expressions for encrypted data patterns.\r\n *\r\n * - **node**: `\"iv.cipher.tag.\"` (three dot-separated parts plus a trailing dot)\r\n * - **web**: `\"iv.cipherWithTag.\"` (two parts plus a trailing dot)\r\n * - **general**: accepts both shapes (2 or 3 parts) with a trailing dot\r\n *\r\n * Each part is any non-empty string without dots.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a secret code you want to check. Before you check it,\r\n * you make sure it looks how a secret code should look.\r\n */\r\nexport const ENCRYPTED_REGEX = Object.freeze({\r\n node: /^([^.]+)\\.([^.]+)\\.([^.]+)\\.$/,\r\n web: /^([^.]+)\\.([^.]+)\\.$/,\r\n general: /^([^.]+)\\.([^.]+)(?:\\.([^.]+))?\\.$/,\r\n});\r\n\r\n/**\r\n * Checks if a string matches an expected encrypted payload shape.\r\n *\r\n * - **node**: `\"iv.cipher.tag.\"` (three dot-separated parts plus a trailing dot)\r\n * - **web**: `\"iv.cipherWithTag.\"` (two parts plus a trailing dot)\r\n * - **general**: accepts both shapes (2 or 3 parts) with a trailing dot\r\n *\r\n * Each part is any non-empty string without dots.\r\n *\r\n * This validates only the **shape**, not whether content is valid base64/hex, etc.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a secret code you want to check. Before you check it,\r\n * you make sure it looks how a secret code should look.\r\n *\r\n * @param data - The string to test.\r\n * @param format - Which layout to check: `'node'`, `'web'`, or `'general'`.\r\n * @returns `true` if the string matches the pattern; otherwise `false`.\r\n * @throws {Error} If an unknown `format` is provided.\r\n *\r\n * @example\r\n * ```ts\r\n * matchEncryptedPattern(\"abc.def.ghi.\", \"node\"); // true\r\n * matchEncryptedPattern(\"abc.def.\", \"web\"); // true\r\n * matchEncryptedPattern(\"abc.def.\", \"node\"); // false\r\n * matchEncryptedPattern(\"abc.def.ghi.\", \"general\"); // true\r\n * ```\r\n */\r\nexport function matchEncryptedPattern(data: string, format: \"node\" | \"web\" | \"general\"): boolean {\r\n if (typeof data !== \"string\") return false;\r\n if (!(format in ENCRYPTED_REGEX)) throw new Error(`Unknown format: ${format}`);\r\n return ENCRYPTED_REGEX[format].test(data);\r\n}\r\n","import { $isPlainObj } from \"./validate\";\r\n\r\n/**\r\n * Standardized error object for the `Result` type.\r\n * Always has a brief `message` and a more detailed `description`.\r\n */\r\nexport interface ErrorStruct {\r\n readonly message: string;\r\n readonly description: string;\r\n}\r\n\r\ntype ReservedWords<Obj extends object> = \"success\" extends keyof Obj ? never : \"error\" extends keyof Obj ? never : Obj;\r\n\r\ntype OkType<T> = {\r\n readonly success: true;\r\n readonly error?: undefined;\r\n} & (T extends object ? ReservedWords<{ readonly [K in keyof T]: T[K] }> : { readonly result: T });\r\n\r\ntype ErrType<T> = {\r\n readonly success: false;\r\n readonly error: ErrorStruct;\r\n} & (T extends object ? ReservedWords<{ readonly [K in keyof T]?: undefined }> : { readonly result?: undefined });\r\n\r\n/**\r\n * Discriminated union for functions that can succeed or fail.\r\n *\r\n * - On **success**:\r\n * - If `T` is an object - properties of `T` are **spread** into the result\r\n * along with `success: true`.\r\n * - Otherwise - `{ success: true, result: T }`.\r\n * - On **failure**: `{ success: false, error: E }`.\r\n *\r\n * @example\r\n * ```ts\r\n * // Primitive result\r\n * function getNum(): Result<number> {\r\n * return $ok(42);\r\n * }\r\n * const r1 = getNum();\r\n * if (r1.success) console.log(r1.result); // 42\r\n *\r\n * // Object result (spread)\r\n * function getObject(): Result<{ name: string; age: number }> {\r\n * return $ok({ name: 'Alice', age: 30 });\r\n * }\r\n * const r2 = getObject();\r\n * if (r2.success) console.log(r2.name, r2.age); // 'Alice' 30\r\n * ```\r\n */\r\nexport type Result<T> = OkType<T> | ErrType<T>;\r\n\r\nexport function $ok<T>(result: T): Result<T> {\r\n if ($isPlainObj(result)) return { success: true, ...(result as T & object) } as Result<T>;\r\n return { success: true, result } as Result<T>;\r\n}\r\n\r\ninterface ShortErrorStruct {\r\n readonly msg: string;\r\n readonly desc: string;\r\n}\r\n\r\nexport function $err(err: ShortErrorStruct | ErrorStruct): Result<never> {\r\n return {\r\n success: false,\r\n error: {\r\n message: \"msg\" in err ? err.msg : err.message,\r\n description: \"desc\" in err ? err.desc : err.description,\r\n },\r\n } as Result<never>;\r\n}\r\n\r\nexport function $fmtError(error: unknown): string {\r\n if (typeof error === \"string\") return error;\r\n if (error instanceof Error) return error.message;\r\n return String(error);\r\n}\r\n\r\nexport function $fmtResultErr(err: ErrorStruct | undefined): string {\r\n if (!err) return \"Unknown error\";\r\n return `${err.message} - ${err.description}`;\r\n}\r\n\r\nexport function title(platform: \"web\" | \"node\", title: string): string {\r\n return `${platform === \"web\" ? \"Crypto Web API\" : \"Crypto NodeJS API\"} - ${title}`;\r\n}\r\n","import { $err, $fmtError, $fmtResultErr, $ok, type Result } from \"./error\";\r\nimport { $isPlainObj, $isStr } from \"./validate\";\r\n\r\nexport function $stringifyObj<T extends object = Record<string, unknown>>(obj: T): Result<string> {\r\n try {\r\n if (!$isPlainObj(obj)) return $err({ msg: \"JSON: Invalid object\", desc: \"Input is not a plain object\" });\r\n return $ok(JSON.stringify(obj));\r\n } catch (error) {\r\n return $err({ msg: \"JSON: Stringify error\", desc: $fmtError(error) });\r\n }\r\n}\r\n\r\nexport function $parseToObj<T extends object = Record<string, unknown>>(str: string): Result<{ result: T }> {\r\n try {\r\n if (!$isStr(str)) return $err({ msg: \"JSON: Invalid input\", desc: \"Input is not a valid string\" });\r\n const obj = JSON.parse(str);\r\n\r\n if (!$isPlainObj(obj)) {\r\n return $err({ msg: \"JSON: Invalid object format\", desc: \"Parsed data is not a plain object\" });\r\n }\r\n\r\n return $ok({ result: obj as T });\r\n } catch (error) {\r\n return $err({ msg: \"JSON: Invalid format\", desc: $fmtError(error) });\r\n }\r\n}\r\n\r\n/**\r\n * Safely serializes a plain object to JSON without throwing.\r\n *\r\n * Wraps `JSON.stringify` and returns a `Result` containing the JSON string or an error.\r\n * Only plain objects (POJOs) are accepted. Class instances, Maps, Sets, etc. are rejected.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a box of toys (your object) and take a photo of it (a JSON string)\r\n * so you can send it to a friend.\r\n *\r\n * @template T - Plain object type to serialize.\r\n * @param obj - The object to stringify (must be a plain object).\r\n * @returns A `Result` with the JSON string on success, or an error.\r\n *\r\n * @example\r\n * ```ts\r\n * const { result, error, success } = tryStringifyObj({ a: 1 });\r\n *\r\n * if (success) console.log(result); // \"{\\\"a\\\":1}\"\r\n * else console.error(error); // { message: \"...\", description: \"...\" }\r\n * ```\r\n */\r\nexport function tryStringifyObj<T extends object = Record<string, unknown>>(obj: T): Result<string> {\r\n return $stringifyObj(obj);\r\n}\r\n\r\n/**\r\n * Serializes a plain object to JSON (throwing).\r\n *\r\n * Wraps `JSON.stringify` and returns the result or throws an error.\r\n * Only plain objects (POJOs) are accepted. Class instances, Maps, Sets, etc. are rejected.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a box of toys (your object) and take a photo of it (a JSON string)\r\n * so you can send it to a friend.\r\n *\r\n * @template T - Plain object type to serialize.\r\n * @param obj - The object to stringify (must be a plain object).\r\n * @returns JSON string representation of the object.\r\n * @throws {Error} If `obj` is not a plain object or serialization fails.\r\n *\r\n * @example\r\n * ```ts\r\n * const json = stringifyObj({ a: 1 }); // \"{\\\"a\\\":1}\"\r\n * ```\r\n */\r\nexport function stringifyObj<T extends object = Record<string, unknown>>(obj: T): string {\r\n const { result, error } = $stringifyObj(obj);\r\n if (error) throw new Error($fmtResultErr(error));\r\n return result;\r\n}\r\n\r\n/**\r\n * Safely parses a JSON string to a plain object (non-throwing).\r\n *\r\n * Wraps `JSON.parse` and returns a `Result` containing the parsed object, or an error.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You rebuild your toy box (an object) from a photo you took (a JSON string).\r\n *\r\n * @template T - The expected object type.\r\n * @param str - The JSON string to parse.\r\n * @returns A `Result` with the parsed object on success, or an error.\r\n *\r\n * @example\r\n * ```ts\r\n * const {result, error, success} = tryParseToObj<{ a: number }>('{\"a\":1}');\r\n *\r\n * if (success) console.log(result); // { a: 1 }\r\n * else console.error(error) // { message: \"...\", description: \"...\" }\r\n * ```\r\n */\r\nexport function tryParseToObj<T extends object = Record<string, unknown>>(str: string): Result<{ result: T }> {\r\n return $parseToObj<T>(str);\r\n}\r\n\r\n/**\r\n * Parses a JSON string to a plain object (throwing).\r\n *\r\n * Wraps `JSON.parse` and returns the parsed object, or throws on failure.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You rebuild your toy box (an object) from a photo you took (a JSON string).\r\n *\r\n * @template T - The expected object type.\r\n * @param str - The JSON string to parse.\r\n * @returns The parsed plain object.\r\n * @throws {Error} If the string can’t be parsed or doesn’t represent a plain object.\r\n *\r\n * @example\r\n * ```ts\r\n * const obj = parseToObj<{ a: number }>('{\"a\":1}'); // obj.a === 1\r\n * ```\r\n */\r\nexport function parseToObj<T extends object = Record<string, unknown>>(str: string): T {\r\n const { result, error } = $parseToObj<T>(str);\r\n if (error) throw new Error($fmtResultErr(error));\r\n return result;\r\n}\r\n"]}
@@ -1,4 +1,4 @@
1
- import { S as SecretKey, R as Result, d as CreateSecretKeyOptions, e as EncryptOptions, f as DecryptOptions, H as HashOptions, g as HashPasswordOptions, V as VerifyPasswordOptions, b as Encoding } from './validate-EHuJC5QQ.cjs';
1
+ import { S as SecretKey, R as Result, d as CreateSecretKeyOptions, e as EncryptOptions, f as DecryptOptions, H as HashOptions, g as HashPasswordOptions, V as VerifyPasswordOptions, b as Encoding } from './validate-cJEdGlj1.js';
2
2
 
3
3
  /**
4
4
  * Type guard to check if the provided value is a SecretKey object for Web (Deno, Bun, Cloudflare included) environment.
@@ -8,6 +8,13 @@ import { S as SecretKey, R as Result, d as CreateSecretKeyOptions, e as EncryptO
8
8
  *
9
9
  * @param x - The value to check.
10
10
  * @returns True if the value is a SecretKey object for Web, false otherwise.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * isWebSecretKey(webKey); // true
15
+ * isWebSecretKey(nodeKey); // false
16
+ * isWebSecretKey({}); // false
17
+ * ```
11
18
  */
12
19
  declare function isWebSecretKey(x: unknown): x is SecretKey<"web">;
13
20
  /**
@@ -18,6 +25,14 @@ declare function isWebSecretKey(x: unknown): x is SecretKey<"web">;
18
25
  * The chance of two pets getting the same name tag is practically zero, and it's very hard to guess!
19
26
  *
20
27
  * @returns A `Result` containing the UUID string or an error.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const {result, error, success} = tryGenerateUuid();
32
+ *
33
+ * if (success) console.log(result); // "..." (a UUID string)
34
+ * else console.error(error); // { message: "...", description: "..." }
35
+ * ```
21
36
  */
22
37
  declare function tryGenerateUuid(): Result<string>;
23
38
  /**
@@ -29,6 +44,11 @@ declare function tryGenerateUuid(): Result<string>;
29
44
  *
30
45
  * @returns A UUID string.
31
46
  * @throws {Error} If UUID generation fails.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const uuid = generateUuid(); // "..." (a UUID string)
51
+ * ```
32
52
  */
33
53
  declare function generateUuid(): string;
34
54
  /**
@@ -40,12 +60,20 @@ declare function generateUuid(): string;
40
60
  * Imagine you want to create a special key for future use to lock your treasure box (data).
41
61
  * So, you stir in some secret ingredients (like salt and info) to make sure your key is one-of-a-kind.
42
62
  *
43
- * @param secret - The input string to derive the `SecretKey` from.
63
+ * @param secret - The input string to derive the `SecretKey` from, must be at least 8 characters.
44
64
  * @param options.algorithm - The encryption algorithm to use (default: `'aes256gcm'`).
45
65
  * @param options.digest - The hash algorithm for HKDF (default: `'sha256'`).
46
66
  * @param options.salt - A salt string (default: `'cipher-kit-salt'`, must be ≥ 8 chars).
47
67
  * @param options.info - An info string (default: `'cipher-kit'`).
48
68
  * @returns A `Result` promise containing the derived `SecretKey` or an error.
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * const {result, error, success} = await tryCreateSecretKey("my-secret");
73
+ *
74
+ * if (success) console.log(result); // SecretKey object
75
+ * else console.error(error); // { message: "...", description: "..." }
76
+ * ```
49
77
  */
50
78
  declare function tryCreateSecretKey(secret: string, options?: CreateSecretKeyOptions): Promise<Result<{
51
79
  result: SecretKey<"web">;
@@ -59,13 +87,18 @@ declare function tryCreateSecretKey(secret: string, options?: CreateSecretKeyOpt
59
87
  * Imagine you want to create a special key for future use to lock your treasure box (data).
60
88
  * So, you stir in some secret ingredients (like salt and info) to make sure your key is one-of-a-kind.
61
89
  *
62
- * @param secret - The input string to derive the `SecretKey` from.
90
+ * @param secret - The input string to derive the `SecretKey` from, must be at least 8 characters.
63
91
  * @param options.algorithm - The encryption algorithm to use (default: `'aes256gcm'`).
64
92
  * @param options.digest - The hash algorithm for HKDF (default: `'sha256'`).
65
93
  * @param options.salt - A salt string (default: `'cipher-kit-salt'`, must be ≥ 8 chars).
66
94
  * @param options.info - An info string (default: `'cipher-kit'`).
67
95
  * @returns A promise of the derived `SecretKey`.
68
96
  * @throws {Error} If key derivation fails.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * const secretKey = await createSecretKey("my-secret"); // SecretKey object
101
+ * ```
69
102
  */
70
103
  declare function createSecretKey(secret: string, options?: CreateSecretKeyOptions): Promise<SecretKey<"web">>;
71
104
  /**
@@ -79,8 +112,17 @@ declare function createSecretKey(secret: string, options?: CreateSecretKeyOption
79
112
  *
80
113
  * @param data - A UTF-8 string to encrypt.
81
114
  * @param secretKey - The `SecretKey` object used for encryption.
82
- * @param options.encoding - The encoding format for the output ciphertext (default: `'base64url'`).
115
+ * @param options.outputEncoding - The encoding format for the output ciphertext (default: `'base64url'`).
83
116
  * @returns A `Result` promise containing the encrypted string in the specified format or an error.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const secretKey = await createSecretKey("my-secret");
121
+ * const {result, error, success} = await tryEncrypt("Hello, World!", secretKey);
122
+ *
123
+ * if (success) console.log(result); // "iv.cipherWithTag." (Encrypted string)
124
+ * else console.error(error); // { message: "...", description: "..." }
125
+ * ```
84
126
  */
85
127
  declare function tryEncrypt(data: string, secretKey: SecretKey<"web">, options?: EncryptOptions): Promise<Result<string>>;
86
128
  /**
@@ -94,9 +136,15 @@ declare function tryEncrypt(data: string, secretKey: SecretKey<"web">, options?:
94
136
  *
95
137
  * @param data - A UTF-8 string to encrypt.
96
138
  * @param secretKey - The `SecretKey` object used for encryption.
97
- * @param options.encoding - The encoding format for the output ciphertext (default: `'base64url'`).
139
+ * @param options.outputEncoding - The encoding format for the output ciphertext (default: `'base64url'`).
98
140
  * @returns A promise with the encrypted string in the specified format.
99
141
  * @throws {Error} If the input data or key is invalid, or if encryption fails.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * const secretKey = await createSecretKey("my-secret");
146
+ * const encrypted = await encrypt("Hello, World!", secretKey); // "iv.cipherWithTag." (Encrypted string)
147
+ * ```
100
148
  */
101
149
  declare function encrypt(data: string, secretKey: SecretKey<"web">, options?: EncryptOptions): Promise<string>;
102
150
  /**
@@ -110,8 +158,18 @@ declare function encrypt(data: string, secretKey: SecretKey<"web">, options?: En
110
158
  *
111
159
  * @param encrypted - The input string to decrypt, in the format "iv.cipherWithTag.".
112
160
  * @param secretKey - The `SecretKey` object used for decryption.
113
- * @param options.encoding - The encoding format for the input ciphertext (default: `'base64url'`).
161
+ * @param options.inputEncoding - The encoding format for the input ciphertext (default: `'base64url'`).
114
162
  * @returns A `Result` promise containing the decrypted UTF-8 string or an error.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const secretKey = await createSecretKey("my-secret");
167
+ * const encrypted = await encrypt("Hello, World!", secretKey);
168
+ * const {result, error, success} = await tryDecrypt(encrypted, secretKey);
169
+ *
170
+ * if (success) console.log(result); // "Hello, World!"
171
+ * else console.error(error); // { message: "...", description: "..." }
172
+ * ```
115
173
  */
116
174
  declare function tryDecrypt(encrypted: string, secretKey: SecretKey<"web">, options?: DecryptOptions): Promise<Result<string>>;
117
175
  /**
@@ -125,9 +183,16 @@ declare function tryDecrypt(encrypted: string, secretKey: SecretKey<"web">, opti
125
183
  *
126
184
  * @param encrypted - The input string to decrypt, in the format "iv.cipherWithTag.".
127
185
  * @param secretKey - The `SecretKey` object used for decryption.
128
- * @param options.encoding - The encoding format for the input ciphertext (default: `'base64url'`).
186
+ * @param options.inputEncoding - The encoding format for the input ciphertext (default: `'base64url'`).
129
187
  * @returns A promise with the decrypted UTF-8 string.
130
188
  * @throws {Error} If the input data or key is invalid, or if decryption fails.
189
+ *
190
+ * @example
191
+ * ```ts
192
+ * const secretKey = await createSecretKey("my-secret");
193
+ * const encrypted = await encrypt("Hello, World!", secretKey);
194
+ * const decrypted = await decrypt(encrypted, secretKey); // "Hello, World!"
195
+ * ```
131
196
  */
132
197
  declare function decrypt(encrypted: string, secretKey: SecretKey<"web">, options?: DecryptOptions): Promise<string>;
133
198
  /**
@@ -142,12 +207,22 @@ declare function decrypt(encrypted: string, secretKey: SecretKey<"web">, options
142
207
  * So, you take a picture of your toy box (convert it to JSON), and scramble that with
143
208
  * your special key, creating a jumbled code that only someone with the right key can read.
144
209
  *
145
- * @param data - A plain object to encrypt.
210
+ * @template T - The type of the plain object to encrypt.
211
+ * @param obj - A plain object to encrypt.
146
212
  * @param secretKey - The `SecretKey` object used for encryption.
147
- * @param options.encoding - The encoding format for the output ciphertext (default: `'base64url'`).
213
+ * @param options.outputEncoding - The encoding format for the output ciphertext (default: `'base64url'`).
148
214
  * @returns A `Result` promise containing the encrypted string in the specified format or an error.
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * const secretKey = await createSecretKey("my-secret");
219
+ * const {result, error, success} = await tryEncryptObj({ a: 1 }, secretKey);
220
+ *
221
+ * if (success) console.log(result); // "iv.cipherWithTag." (Encrypted string)
222
+ * else console.error(error); // { message: "...", description: "..." }
223
+ * ```
149
224
  */
150
- declare function tryEncryptObj<T extends object = Record<string, unknown>>(data: T, secretKey: SecretKey<"web">, options?: EncryptOptions): Promise<Result<string>>;
225
+ declare function tryEncryptObj<T extends object = Record<string, unknown>>(obj: T, secretKey: SecretKey<"web">, options?: EncryptOptions): Promise<Result<string>>;
151
226
  /**
152
227
  * Encrypts a plain object using the provided `SecretKey` (throwing).
153
228
  *
@@ -160,15 +235,22 @@ declare function tryEncryptObj<T extends object = Record<string, unknown>>(data:
160
235
  * So, you take a picture of your toy box (convert it to JSON), and scramble that with
161
236
  * your special key, creating a jumbled code that only someone with the right key can read.
162
237
  *
163
- * @param data - A plain object to encrypt.
238
+ * @template T - The type of the plain object to encrypt.
239
+ * @param obj - A plain object to encrypt.
164
240
  * @param secretKey - The `SecretKey` object used for encryption.
165
- * @param options.encoding - The encoding format for the output ciphertext (default: `'base64url'`).
241
+ * @param options.outputEncoding - The encoding format for the output ciphertext (default: `'base64url'`).
166
242
  * @returns A promise with the encrypted string in the specified format.
167
243
  * @throws {Error} If the input data or key is invalid, or if encryption fails.
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * const secretKey = await createSecretKey("my-secret");
248
+ * const encrypted = await encryptObj({ a: 1 }, secretKey); // "iv.cipherWithTag." (Encrypted string)
249
+ * ```
168
250
  */
169
- declare function encryptObj<T extends object = Record<string, unknown>>(data: T, secretKey: SecretKey<"web">, options?: EncryptOptions): Promise<string>;
251
+ declare function encryptObj<T extends object = Record<string, unknown>>(obj: T, secretKey: SecretKey<"web">, options?: EncryptOptions): Promise<string>;
170
252
  /**
171
- * Safely decrypts an encrypted JSON string into an object (non-throwing).
253
+ * Safely decrypts an encrypted JSON string into a plain object (non-throwing).
172
254
  *
173
255
  * Expects input in the format `"iv.cipherWithTag."` and returns a plain object.
174
256
  *
@@ -179,14 +261,24 @@ declare function encryptObj<T extends object = Record<string, unknown>>(data: T,
179
261
  * @template T - The expected shape of the decrypted object.
180
262
  * @param encrypted - The encrypted string (format: `"iv.cipherWithTag."`).
181
263
  * @param secretKey - The `SecretKey` used for decryption.
182
- * @param options.encoding - Input ciphertext encoding (default: `'base64url'`).
264
+ * @param options.inputEncoding - Input ciphertext encoding (default: `'base64url'`).
183
265
  * @returns A `Result` promise with the decrypted object on success, or an error.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const secretKey = await createSecretKey("my-secret");
270
+ * const encrypted = await encryptObj({ a: 1 }, secretKey);
271
+ * const {result, error, success} = await tryDecryptObj<{ a: number }>(encrypted, secretKey);
272
+ *
273
+ * if (success) console.log(result); // { a: 1 }
274
+ * else console.error(error); // { message: "...", description: "..." }
275
+ * ```
184
276
  */
185
277
  declare function tryDecryptObj<T extends object = Record<string, unknown>>(encrypted: string, secretKey: SecretKey<"web">, options?: DecryptOptions): Promise<Result<{
186
278
  result: T;
187
279
  }>>;
188
280
  /**
189
- * Decrypts an encrypted JSON string into an object (throwing).
281
+ * Decrypts an encrypted JSON string into a plain object (throwing).
190
282
  *
191
283
  * Expects input in the format `"iv.cipherWithTag."` and returns a plain object.
192
284
  *
@@ -197,9 +289,16 @@ declare function tryDecryptObj<T extends object = Record<string, unknown>>(encry
197
289
  * @template T - The expected shape of the decrypted object.
198
290
  * @param encrypted - The encrypted string (format: `"iv.cipherWithTag."`).
199
291
  * @param secretKey - The `SecretKey` used for decryption.
200
- * @param options.encoding - Input ciphertext encoding (default: `'base64url'`).
292
+ * @param options.inputEncoding - Input ciphertext encoding (default: `'base64url'`).
201
293
  * @returns A promise with the decrypted object.
202
294
  * @throws {Error} If decryption or JSON parsing fails.
295
+ *
296
+ * @example
297
+ * ```ts
298
+ * const secretKey = await createSecretKey("my-secret");
299
+ * const encrypted = await encryptObj({ a: 1 }, secretKey);
300
+ * const obj = await decryptObj<{ a: number }>(encrypted, secretKey); // obj.a === 1
301
+ * ```
203
302
  */
204
303
  declare function decryptObj<T extends object = Record<string, unknown>>(encrypted: string, secretKey: SecretKey<"web">, options?: DecryptOptions): Promise<T>;
205
304
  /**
@@ -214,8 +313,16 @@ declare function decryptObj<T extends object = Record<string, unknown>>(encrypte
214
313
  *
215
314
  * @param data - The input string to hash.
216
315
  * @param options.digest - Hash algorithm (`'sha256' | 'sha384' | 'sha512'`, default: `'sha256'`).
217
- * @param options.encoding - Output encoding (`'base64' | 'base64url' | 'hex'`, default: `'base64url'`).
316
+ * @param options.outputEncoding - Output encoding (`'base64' | 'base64url' | 'hex'`, default: `'base64url'`).
218
317
  * @returns A `Result` promise with the hash string or an error.
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * const {result, error, success} = await tryHash("my data");
322
+ *
323
+ * if (success) console.log(result); // "..." (Hashed string)
324
+ * else console.error(error); // { message: "...", description: "..." }
325
+ * ```
219
326
  */
220
327
  declare function tryHash(data: string, options?: HashOptions): Promise<Result<string>>;
221
328
  /**
@@ -230,9 +337,14 @@ declare function tryHash(data: string, options?: HashOptions): Promise<Result<st
230
337
  *
231
338
  * @param data - The input string to hash.
232
339
  * @param options.digest - Hash algorithm (`'sha256' | 'sha384' | 'sha512'`, default: `'sha256'`).
233
- * @param options.encoding - Output encoding (`'base64' | 'base64url' | 'hex'`, default: `'base64url'`).
340
+ * @param options.outputEncoding - Output encoding (`'base64' | 'base64url' | 'hex'`, default: `'base64url'`).
234
341
  * @returns A promise of the hashed string.
235
342
  * @throws {Error} If input is invalid or hashing fails.
343
+ *
344
+ * @example
345
+ * ```ts
346
+ * const hashed = await hash("my data"); // "..." (Hashed string)
347
+ * ```
236
348
  */
237
349
  declare function hash(data: string, options?: HashOptions): Promise<string>;
238
350
  /**
@@ -247,14 +359,22 @@ declare function hash(data: string, options?: HashOptions): Promise<string>;
247
359
  *
248
360
  * @param password - The password to hash.
249
361
  * @param options.digest - Hash algorithm (`'sha256' | 'sha384' | 'sha512'`; default: `'sha512'`).
250
- * @param options.encoding - Output encoding (`'base64' | 'base64url' | 'hex'`; default: `'base64url'`).
362
+ * @param options.outputEncoding - Output encoding (`'base64' | 'base64url' | 'hex'`; default: `'base64url'`).
251
363
  * @param options.saltLength - Length of the random salt in bytes (default: `16` bytes, min: `8` bytes).
252
364
  * @param options.iterations - Number of iterations (default: `320000`, min: `1000`).
253
365
  * @param options.keyLength - Length of the derived key in bytes (default: `64` bytes, min: `16` bytes).
254
- * @returns A `Result` promise with `{ hash, salt }` or an error.
366
+ * @returns A `Result` promise with `{ result, salt }` or an error.
367
+ *
368
+ * @example
369
+ * ```ts
370
+ * const {result, error, success} = await tryHashPassword("my-password");
371
+ *
372
+ * if (success) console.log(result, salt); // "..." (hashed password), "..." (salt)
373
+ * else console.error(error); // { message: "...", description: "..." }
374
+ * ```
255
375
  */
256
376
  declare function tryHashPassword(password: string, options?: HashPasswordOptions): Promise<Result<{
257
- hash: string;
377
+ result: string;
258
378
  salt: string;
259
379
  }>>;
260
380
  /**
@@ -269,15 +389,20 @@ declare function tryHashPassword(password: string, options?: HashPasswordOptions
269
389
  *
270
390
  * @param password - The password to hash.
271
391
  * @param options.digest - Hash algorithm (`'sha256' | 'sha384' | 'sha512'`; default: `'sha512'`).
272
- * @param options.encoding - Output encoding (`'base64' | 'base64url' | 'hex'`; default: `'base64url'`).
392
+ * @param options.outputEncoding - Output encoding (`'base64' | 'base64url' | 'hex'`; default: `'base64url'`).
273
393
  * @param options.saltLength - Length of the random salt in bytes (default: `16` bytes, min: `8` bytes).
274
394
  * @param options.iterations - Number of iterations (default: `320000`, min: `1000`).
275
395
  * @param options.keyLength - Length of the derived key in bytes (default: `64` bytes, min: `16` bytes).
276
- * @returns A promise with `{ hash, salt }` for storage.
396
+ * @returns A promise with `{ result, salt }` for storage.
277
397
  * @throws {Error} If inputs are invalid or hashing fails.
398
+ *
399
+ * @example
400
+ * ```ts
401
+ * const {result, salt} = await hashPassword("my-password"); // "..." (hashed password), "..." (salt)
402
+ * ```
278
403
  */
279
404
  declare function hashPassword(password: string, options?: HashPasswordOptions): Promise<{
280
- hash: string;
405
+ result: string;
281
406
  salt: string;
282
407
  }>;
283
408
  /**
@@ -293,10 +418,18 @@ declare function hashPassword(password: string, options?: HashPasswordOptions):
293
418
  * @param hashedPassword - The stored hash (encoded).
294
419
  * @param salt - The stored salt (encoded).
295
420
  * @param options.digest - Hash algorithm used during hashing (`'sha256' | 'sha384' | 'sha512'`; default: `'sha512'`).
296
- * @param options.encoding - Encoding of the stored hash and salt (`'base64' | 'base64url' | 'hex'`; default: `'base64url'`).
421
+ * @param options.inputEncoding - Encoding of the stored hash and salt (`'base64' | 'base64url' | 'hex'`; default: `'base64url'`).
297
422
  * @param options.iterations - Number of iterations used during hashing (default: `320000`).
298
423
  * @param options.keyLength - Length of the derived key in bytes used during hashing (default: `64` bytes).
299
424
  * @returns A promise of boolean, `true` if the password matches, otherwise `false`.
425
+ *
426
+ * @example
427
+ * ```ts
428
+ * const {result, salt} = await hashPassword("my-password");
429
+ *
430
+ * await verifyPassword("my-password", result, salt); // true
431
+ * await verifyPassword("wrong-password", result, salt); // false
432
+ * ```
300
433
  */
301
434
  declare function verifyPassword(password: string, hashedPassword: string, salt: string, options?: VerifyPasswordOptions): Promise<boolean>;
302
435
  /**
@@ -310,6 +443,14 @@ declare function verifyPassword(password: string, hashedPassword: string, salt:
310
443
  * @param data - The input string to convert.
311
444
  * @param inputEncoding - The encoding of the input string (default: `'utf8'`).
312
445
  * @returns A `Result` with `{ result: Uint8Array }` or an error.
446
+ *
447
+ * @example
448
+ * ```ts
449
+ * const {result, error, success} = tryConvertStrToBytes("Hello", "utf8");
450
+ *
451
+ * if (success) console.log(result); // Uint8Array([...])
452
+ * else console.error(error); // { message: "...", description: "..." }
453
+ * ```
313
454
  */
314
455
  declare function tryConvertStrToBytes(data: string, inputEncoding?: Encoding): Result<{
315
456
  result: Uint8Array<ArrayBuffer>;
@@ -326,6 +467,11 @@ declare function tryConvertStrToBytes(data: string, inputEncoding?: Encoding): R
326
467
  * @param inputEncoding - The encoding of the input string (default: `'utf8'`).
327
468
  * @returns A `Uint8Array` containing the bytes.
328
469
  * @throws {Error} If input is invalid or conversion fails.
470
+ *
471
+ * @example
472
+ * ```ts
473
+ * const bytes = convertStrToBytes("Hello", "utf8"); // Uint8Array([...])
474
+ * ```
329
475
  */
330
476
  declare function convertStrToBytes(data: string, inputEncoding?: Encoding): Uint8Array<ArrayBuffer>;
331
477
  /**
@@ -339,6 +485,15 @@ declare function convertStrToBytes(data: string, inputEncoding?: Encoding): Uint
339
485
  * @param data - The `Uint8Array` or `ArrayBuffer` to convert.
340
486
  * @param outputEncoding - The output encoding (default: `'utf8'`).
341
487
  * @returns A `Result` with the string or an error.
488
+ *
489
+ * @example
490
+ * ```ts
491
+ * const bytes = convertStrToBytes("Hello", "utf8"); // Uint8Array([...])
492
+ * const {result, error, success} = tryConvertBytesToStr(bytes, "utf8");
493
+ *
494
+ * if (success) console.log(result); // "Hello"
495
+ * else console.error(error); // { message: "...", description: "..." }
496
+ * ```
342
497
  */
343
498
  declare function tryConvertBytesToStr(data: Uint8Array | ArrayBuffer, outputEncoding?: Encoding): Result<string>;
344
499
  /**
@@ -353,6 +508,12 @@ declare function tryConvertBytesToStr(data: Uint8Array | ArrayBuffer, outputEnco
353
508
  * @param outputEncoding - The output encoding (default: `'utf8'`).
354
509
  * @returns The encoded string.
355
510
  * @throws {Error} If input is invalid or conversion fails.
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * const bytes = convertStrToBytes("Hello", "utf8"); // Uint8Array([...])
515
+ * const str = convertBytesToStr(bytes, "utf8"); // "Hello"
516
+ * ```
356
517
  */
357
518
  declare function convertBytesToStr(data: Uint8Array | ArrayBuffer, outputEncoding?: Encoding): string;
358
519
  /**
@@ -367,6 +528,14 @@ declare function convertBytesToStr(data: Uint8Array | ArrayBuffer, outputEncodin
367
528
  * @param from - The current encoding of `data`.
368
529
  * @param to - The target encoding for `data`.
369
530
  * @returns A `Result` with a string or an error.
531
+ *
532
+ * @example
533
+ * ```ts
534
+ * const {result, error, success} = tryConvertEncoding("Hello", "utf8", "base64url");
535
+ *
536
+ * if (success) console.log(result); // "..." (Base64url encoded string)
537
+ * else console.error(error); // { message: "...", description: "..." }
538
+ * ```
370
539
  */
371
540
  declare function tryConvertEncoding(data: string, from: Encoding, to: Encoding): Result<string>;
372
541
  /**
@@ -382,6 +551,11 @@ declare function tryConvertEncoding(data: string, from: Encoding, to: Encoding):
382
551
  * @param to - The target encoding for `data`.
383
552
  * @returns The converted string.
384
553
  * @throws {Error} If encodings are invalid or conversion fails.
554
+ *
555
+ * @example
556
+ * ```ts
557
+ * const base64url = convertEncoding("Hello", "utf8", "base64url"); // "..." (Base64url encoded string)
558
+ * ```
385
559
  */
386
560
  declare function convertEncoding(data: string, from: Encoding, to: Encoding): string;
387
561