@wener/utils 1.1.50 → 1.1.53

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 (506) hide show
  1. package/lib/arrays/MaybeArray.js +58 -8
  2. package/lib/arrays/arrayFromAsync.js +254 -6
  3. package/lib/asyncs/AsyncInterval.js +145 -9
  4. package/lib/asyncs/MaybePromise.js +0 -2
  5. package/lib/asyncs/Promises.js +95 -48
  6. package/lib/asyncs/createAsyncIterator.js +313 -23
  7. package/lib/asyncs/createLazyPromise.js +72 -31
  8. package/lib/asyncs/createLazyPromise.test.js +367 -0
  9. package/lib/asyncs/firstOfAsyncIterator.js +6 -6
  10. package/lib/asyncs/generatorOfStream.js +125 -14
  11. package/lib/asyncs/isIterator.js +1 -3
  12. package/lib/asyncs/isPromise.js +2 -4
  13. package/lib/asyncs/isThenable.js +0 -2
  14. package/lib/asyncs/nextOfAsyncIterator.js +15 -9
  15. package/lib/asyncs/promiseOfCallback.js +2 -4
  16. package/lib/asyncs/timeout.js +122 -13
  17. package/lib/browsers/copy.js +7 -8
  18. package/lib/browsers/download.js +215 -40
  19. package/lib/browsers/getFileFromDataTransfer.js +17 -14
  20. package/lib/browsers/loaders.js +251 -18
  21. package/lib/crypto/base.js +3 -3
  22. package/lib/crypto/getNodeCrypto.js +3 -5
  23. package/lib/crypto/hashing.js +236 -30
  24. package/lib/crypto/hashing.test.js +323 -0
  25. package/lib/crypto/md5.bench.js +11 -11
  26. package/lib/crypto/md5.d.js +0 -2
  27. package/lib/crypto/md5.js +0 -2
  28. package/lib/crypto/md5.test.js +7 -0
  29. package/lib/crypto/pem/pem.js +197 -35
  30. package/lib/crypto/pem/pem.test.js +104 -0
  31. package/lib/crypto/randomUUIDv7.js +0 -2
  32. package/lib/crypto/ulid.js +84 -48
  33. package/lib/crypto/ulid.test.js +115 -0
  34. package/lib/emitter/types.js +0 -2
  35. package/lib/errors/DetailError.js +297 -0
  36. package/lib/errors/Errors.js +2 -202
  37. package/lib/errors/Errors.mod.js +206 -0
  38. package/lib/errors/Errors.test.js +24 -0
  39. package/lib/fetch/HttpStatus.js +1 -3
  40. package/lib/fetch/createFetchWith.js +188 -19
  41. package/lib/fetch/createFetchWithLogging.js +17 -16
  42. package/lib/fetch/createFetchWithRetry.js +40 -24
  43. package/lib/fetch/dumpRequest.js +467 -41
  44. package/lib/fetch/dumpRequest.test.js +384 -0
  45. package/lib/fetch/dumpResponse.js +271 -16
  46. package/lib/fetch/dumpResponse.test.js +393 -0
  47. package/lib/fetch/http.types.js +0 -2
  48. package/lib/fetch/index.js +5 -7
  49. package/lib/fetch/isTextContentType.js +5 -0
  50. package/lib/fetch/resolveRequest.js +7 -0
  51. package/lib/fetch/types.js +0 -2
  52. package/lib/i18n/createTranslate.js +40 -20
  53. package/lib/i18n/createTranslate.test.js +177 -0
  54. package/lib/index.js +75 -75
  55. package/lib/io/AbstractEncoding.js +0 -2
  56. package/lib/io/ArrayBuffer.test-d.js +4 -6
  57. package/lib/io/ArrayBuffers.base64.test.js +60 -0
  58. package/lib/io/ArrayBuffers.js +2 -334
  59. package/lib/io/ArrayBuffers.mod.js +531 -0
  60. package/lib/io/ArrayBuffers.test.js +77 -0
  61. package/lib/io/Buffer.js +190 -20
  62. package/lib/io/Buffer.test.js +22 -0
  63. package/lib/io/ByteBuffer.js +752 -441
  64. package/lib/io/ByteBuffer.test.js +184 -0
  65. package/lib/io/base64.js +17 -19
  66. package/lib/io/dump.js +16 -16
  67. package/lib/io/isBuffer.js +2 -3
  68. package/lib/io/isBuffer.test.js +8 -0
  69. package/lib/io/isTransferable.js +16 -8
  70. package/lib/io/isTransferable.test.js +17 -0
  71. package/lib/io/parseDataUri.js +288 -40
  72. package/lib/io/parseDataUri.test.js +286 -0
  73. package/lib/io/types.js +1 -0
  74. package/lib/langs/AsyncCloser.js +276 -0
  75. package/lib/langs/Closer.js +100 -0
  76. package/lib/langs/MaybeFunction.js +38 -5
  77. package/lib/langs/classOf.js +0 -2
  78. package/lib/langs/deepEqual.js +82 -22
  79. package/lib/langs/deepEqual.test.js +11 -0
  80. package/lib/langs/deepFreeze.js +28 -9
  81. package/lib/langs/getGlobalStates.js +19 -7
  82. package/lib/langs/getObjectId.js +4 -6
  83. package/lib/langs/ifPresent.js +3 -0
  84. package/lib/langs/isClass.js +0 -2
  85. package/lib/langs/isDefined.js +0 -2
  86. package/lib/langs/isEmptyObject.js +1 -3
  87. package/lib/langs/isFunction.js +0 -2
  88. package/lib/langs/isNil.js +3 -0
  89. package/lib/langs/isPlainObject.js +2 -4
  90. package/lib/langs/langs.test.js +126 -0
  91. package/lib/langs/memoize.js +11 -7
  92. package/lib/langs/mixin.js +7 -4
  93. package/lib/langs/mixin.test.js +135 -0
  94. package/lib/langs/parseBoolean.js +11 -8
  95. package/lib/langs/shallowClone.js +5 -3
  96. package/lib/langs/shallowEqual.js +8 -6
  97. package/lib/libs/ms.js +28 -26
  98. package/lib/libs/ms.test.js +301 -0
  99. package/lib/logger/const.js +15 -0
  100. package/lib/logger/index.js +1 -0
  101. package/lib/logger/types.js +1 -0
  102. package/lib/maths/clamp.js +81 -12
  103. package/lib/maths/clamp.test.js +186 -0
  104. package/lib/maths/createRandom.test.js +36 -0
  105. package/lib/maths/random.js +162 -13
  106. package/lib/modules/isModule.js +0 -2
  107. package/lib/modules/parseModuleId.js +14 -15
  108. package/lib/modules/parseModuleId.test.js +153 -0
  109. package/lib/objects/computeIfAbsent.js +8 -3
  110. package/lib/objects/get.js +26 -8
  111. package/lib/objects/get.test-d.js +23 -25
  112. package/lib/objects/merge/index.js +1 -3
  113. package/lib/objects/merge/isMergeableObject.js +5 -3
  114. package/lib/objects/merge/merge.js +82 -26
  115. package/lib/objects/merge/merge.test.js +1397 -0
  116. package/lib/objects/parseObjectPath.js +47 -15
  117. package/lib/objects/parseObjectPath.test.js +138 -0
  118. package/lib/objects/set.js +25 -19
  119. package/lib/objects/set.test.js +522 -0
  120. package/lib/schema/typebox/index.js +2 -3
  121. package/lib/schema/typebox/typebox.js +6 -6
  122. package/lib/scripts/getGenerateContext.js +386 -76
  123. package/lib/server/crypto/md5.js +0 -2
  124. package/lib/server/fetch/createFetchWithProxy.js +2 -4
  125. package/lib/server/fetch/createFetchWithProxyByNodeFetch.js +258 -31
  126. package/lib/server/fetch/createFetchWithProxyByUndici.js +307 -49
  127. package/lib/server/getPackageDir.js +2 -3
  128. package/lib/server/index.js +5 -7
  129. package/lib/server/jsdom.js +1 -3
  130. package/lib/server/node-fetch.js +2 -4
  131. package/lib/server/polyfill/polyfillBrowser.js +163 -9
  132. package/lib/server/polyfill/polyfillBrowser.test.js +164 -0
  133. package/lib/server/polyfill/polyfillCrypto.js +157 -9
  134. package/lib/server/polyfill/polyfillFetch.js +13 -13
  135. package/lib/server/polyfill/polyfillJsDom.js +264 -58
  136. package/lib/server/polyfill/polyfillWebSocket.js +11 -11
  137. package/lib/server/ws.js +1 -3
  138. package/lib/strings/bytes.test.js +327 -0
  139. package/lib/strings/camelCase.js +23 -14
  140. package/lib/strings/formatBytes.js +29 -20
  141. package/lib/strings/parseBytes.js +54 -0
  142. package/lib/strings/renderTemplate.js +17 -12
  143. package/lib/strings/renderTemplate.test.js +104 -0
  144. package/lib/typedoc.js +2 -4
  145. package/lib/types.d.js +0 -2
  146. package/lib/validations/asserts.js +0 -2
  147. package/lib/validations/isUUID.js +0 -2
  148. package/lib/validations/isUUID.test.js +87 -0
  149. package/lib/validations/parseTimestamp.js +12 -7
  150. package/lib/validations/parseTimestamp.test.js +6 -0
  151. package/lib/{runtime → web}/getGlobalThis.js +3 -4
  152. package/lib/web/getRandomValues.js +44 -0
  153. package/lib/web/randomUUID.js +15 -0
  154. package/lib/web/requestIdleCallback.js +17 -0
  155. package/lib/{runtime → web}/structuredClone.js +35 -28
  156. package/lib/web/structuredClone.test.js +81 -0
  157. package/package.json +10 -18
  158. package/src/arrays/MaybeArray.ts +22 -22
  159. package/src/arrays/arrayFromAsync.ts +3 -3
  160. package/src/asyncs/AsyncInterval.ts +8 -8
  161. package/src/asyncs/Promises.ts +51 -51
  162. package/src/asyncs/createAsyncIterator.ts +34 -34
  163. package/src/asyncs/createLazyPromise.test.ts +73 -73
  164. package/src/asyncs/createLazyPromise.ts +68 -73
  165. package/src/asyncs/firstOfAsyncIterator.ts +5 -5
  166. package/src/asyncs/generatorOfStream.ts +12 -12
  167. package/src/asyncs/isIterator.ts +1 -1
  168. package/src/asyncs/isThenable.ts +2 -2
  169. package/src/asyncs/nextOfAsyncIterator.ts +20 -20
  170. package/src/asyncs/promiseOfCallback.ts +13 -13
  171. package/src/asyncs/timeout.ts +23 -23
  172. package/src/browsers/copy.ts +48 -48
  173. package/src/browsers/download.ts +38 -36
  174. package/src/browsers/getFileFromDataTransfer.ts +35 -35
  175. package/src/browsers/loaders.ts +49 -49
  176. package/src/crypto/base.ts +3 -3
  177. package/src/crypto/getNodeCrypto.ts +3 -3
  178. package/src/crypto/hashing.test.ts +34 -48
  179. package/src/crypto/hashing.ts +67 -67
  180. package/src/crypto/md5.bench.ts +20 -24
  181. package/src/crypto/md5.test.ts +3 -3
  182. package/src/crypto/pem/pem.test.ts +26 -42
  183. package/src/crypto/pem/pem.ts +65 -65
  184. package/src/crypto/ulid.test.ts +32 -32
  185. package/src/crypto/ulid.ts +117 -117
  186. package/src/emitter/types.ts +6 -6
  187. package/src/errors/DetailError.ts +151 -0
  188. package/src/errors/Errors.mod.ts +104 -0
  189. package/src/errors/Errors.test.ts +15 -15
  190. package/src/errors/Errors.ts +1 -247
  191. package/src/fetch/HttpStatus.ts +77 -77
  192. package/src/fetch/createFetchWith.ts +27 -27
  193. package/src/fetch/createFetchWithLogging.ts +13 -16
  194. package/src/fetch/createFetchWithRetry.ts +80 -80
  195. package/src/fetch/dumpRequest.test.ts +176 -0
  196. package/src/fetch/dumpRequest.ts +149 -52
  197. package/src/fetch/dumpResponse.test.ts +160 -0
  198. package/src/fetch/dumpResponse.ts +48 -20
  199. package/src/fetch/http.types.ts +35 -35
  200. package/src/fetch/isTextContentType.ts +12 -0
  201. package/src/fetch/resolveRequest.ts +1 -0
  202. package/src/fetch/types.ts +2 -2
  203. package/src/i18n/createTranslate.test.ts +90 -113
  204. package/src/i18n/createTranslate.ts +55 -55
  205. package/src/index.ts +26 -27
  206. package/src/io/AbstractEncoding.ts +12 -12
  207. package/src/io/ArrayBuffer.test-d.ts +1 -1
  208. package/src/io/ArrayBuffers.base64.test.ts +52 -52
  209. package/src/io/ArrayBuffers.mod.ts +670 -0
  210. package/src/io/ArrayBuffers.test.ts +14 -14
  211. package/src/io/ArrayBuffers.ts +1 -446
  212. package/src/io/Buffer.test.ts +17 -17
  213. package/src/io/Buffer.ts +17 -17
  214. package/src/io/ByteBuffer.test.ts +37 -37
  215. package/src/io/ByteBuffer.ts +574 -566
  216. package/src/io/base64.ts +46 -44
  217. package/src/io/dump.ts +22 -22
  218. package/src/io/isBuffer.test.ts +2 -2
  219. package/src/io/isBuffer.ts +1 -1
  220. package/src/io/isTransferable.test.ts +4 -4
  221. package/src/io/isTransferable.ts +30 -30
  222. package/src/io/parseDataUri.test.ts +22 -27
  223. package/src/io/parseDataUri.ts +57 -57
  224. package/src/io/types.ts +13 -0
  225. package/src/langs/AsyncCloser.ts +45 -0
  226. package/src/langs/Closer.ts +39 -0
  227. package/src/langs/MaybeFunction.ts +5 -5
  228. package/src/langs/classOf.ts +1 -1
  229. package/src/langs/deepEqual.test.ts +1 -12
  230. package/src/langs/deepEqual.ts +82 -82
  231. package/src/langs/deepFreeze.ts +11 -11
  232. package/src/langs/getGlobalStates.ts +21 -11
  233. package/src/langs/getObjectId.ts +10 -13
  234. package/src/langs/ifPresent.ts +3 -0
  235. package/src/langs/isClass.ts +1 -1
  236. package/src/langs/isDefined.ts +1 -1
  237. package/src/langs/isEmptyObject.ts +1 -1
  238. package/src/langs/isFunction.ts +1 -1
  239. package/src/langs/isNil.ts +3 -0
  240. package/src/langs/isPlainObject.ts +4 -4
  241. package/src/langs/langs.test.ts +18 -18
  242. package/src/langs/memoize.ts +21 -21
  243. package/src/langs/mixin.test.ts +22 -26
  244. package/src/langs/mixin.ts +6 -9
  245. package/src/langs/parseBoolean.ts +30 -26
  246. package/src/langs/shallowClone.ts +11 -11
  247. package/src/langs/shallowEqual.ts +19 -19
  248. package/src/libs/ms.test.ts +274 -274
  249. package/src/libs/ms.ts +137 -137
  250. package/src/logger/const.ts +18 -0
  251. package/src/logger/index.ts +2 -0
  252. package/src/logger/types.ts +10 -0
  253. package/src/maths/clamp.test.ts +18 -18
  254. package/src/maths/clamp.ts +17 -17
  255. package/src/maths/createRandom.test.ts +12 -0
  256. package/src/maths/random.ts +50 -14
  257. package/src/modules/isModule.ts +4 -4
  258. package/src/modules/parseModuleId.test.ts +61 -68
  259. package/src/modules/parseModuleId.ts +29 -43
  260. package/src/objects/computeIfAbsent.ts +10 -10
  261. package/src/objects/get.test-d.ts +33 -51
  262. package/src/objects/get.ts +31 -31
  263. package/src/objects/merge/isMergeableObject.ts +5 -5
  264. package/src/objects/merge/merge.test.ts +658 -880
  265. package/src/objects/merge/merge.ts +84 -84
  266. package/src/objects/parseObjectPath.test.ts +13 -13
  267. package/src/objects/parseObjectPath.ts +25 -25
  268. package/src/objects/set.test.ts +271 -366
  269. package/src/objects/set.ts +36 -36
  270. package/src/schema/typebox/typebox.ts +20 -26
  271. package/src/scripts/getGenerateContext.ts +82 -80
  272. package/src/server/crypto/md5.ts +1 -1
  273. package/src/server/fetch/createFetchWithProxyByNodeFetch.ts +30 -33
  274. package/src/server/fetch/createFetchWithProxyByUndici.ts +64 -70
  275. package/src/server/getPackageDir.ts +7 -7
  276. package/src/server/polyfill/polyfillBrowser.test.ts +10 -10
  277. package/src/server/polyfill/polyfillBrowser.ts +3 -3
  278. package/src/server/polyfill/polyfillCrypto.ts +7 -7
  279. package/src/server/polyfill/polyfillFetch.ts +11 -21
  280. package/src/server/polyfill/polyfillJsDom.ts +60 -72
  281. package/src/server/polyfill/polyfillWebSocket.ts +15 -15
  282. package/src/strings/bytes.test.ts +69 -0
  283. package/src/strings/camelCase.ts +58 -63
  284. package/src/strings/formatBytes.ts +50 -29
  285. package/src/strings/parseBytes.ts +66 -0
  286. package/src/strings/renderTemplate.test.ts +10 -17
  287. package/src/strings/renderTemplate.ts +19 -22
  288. package/src/types.d.ts +9 -9
  289. package/src/validations/asserts.ts +8 -8
  290. package/src/validations/isUUID.test.ts +9 -9
  291. package/src/validations/isUUID.ts +1 -1
  292. package/src/validations/parseTimestamp.test.ts +2 -2
  293. package/src/validations/parseTimestamp.ts +21 -21
  294. package/src/{runtime → web}/getGlobalThis.ts +6 -6
  295. package/src/web/getRandomValues.ts +41 -0
  296. package/src/web/randomUUID.ts +19 -0
  297. package/src/web/requestIdleCallback.ts +11 -0
  298. package/src/{runtime → web}/structuredClone.test.ts +8 -8
  299. package/src/web/structuredClone.ts +88 -0
  300. package/tsconfig.json +35 -34
  301. package/lib/arrays/MaybeArray.js.map +0 -1
  302. package/lib/arrays/arrayFromAsync.js.map +0 -1
  303. package/lib/asyncs/AsyncInterval.js.map +0 -1
  304. package/lib/asyncs/MaybePromise.js.map +0 -1
  305. package/lib/asyncs/Promises.js.map +0 -1
  306. package/lib/asyncs/createAsyncIterator.js.map +0 -1
  307. package/lib/asyncs/createLazyPromise.js.map +0 -1
  308. package/lib/asyncs/firstOfAsyncIterator.js.map +0 -1
  309. package/lib/asyncs/generatorOfStream.js.map +0 -1
  310. package/lib/asyncs/isIterator.js.map +0 -1
  311. package/lib/asyncs/isPromise.js.map +0 -1
  312. package/lib/asyncs/isThenable.js.map +0 -1
  313. package/lib/asyncs/nextOfAsyncIterator.js.map +0 -1
  314. package/lib/asyncs/promiseOfCallback.js.map +0 -1
  315. package/lib/asyncs/timeout.js.map +0 -1
  316. package/lib/browsers/copy.js.map +0 -1
  317. package/lib/browsers/download.js.map +0 -1
  318. package/lib/browsers/getFileFromDataTransfer.js.map +0 -1
  319. package/lib/browsers/loaders.js.map +0 -1
  320. package/lib/cn/division/DivisionCode.js +0 -209
  321. package/lib/cn/division/DivisionCode.js.map +0 -1
  322. package/lib/cn/division/binarySearch.js +0 -27
  323. package/lib/cn/division/binarySearch.js.map +0 -1
  324. package/lib/cn/formatChineseAmount.js +0 -77
  325. package/lib/cn/formatChineseAmount.js.map +0 -1
  326. package/lib/cn/id/Mod11.js +0 -43
  327. package/lib/cn/id/Mod11.js.map +0 -1
  328. package/lib/cn/id/ResidentIdNumber.js +0 -98
  329. package/lib/cn/id/ResidentIdNumber.js.map +0 -1
  330. package/lib/cn/id/types.js +0 -8
  331. package/lib/cn/id/types.js.map +0 -1
  332. package/lib/cn/index.js +0 -14
  333. package/lib/cn/index.js.map +0 -1
  334. package/lib/cn/parseChineseNumber.js +0 -94
  335. package/lib/cn/parseChineseNumber.js.map +0 -1
  336. package/lib/cn/pinyin/cartesianProduct.js +0 -22
  337. package/lib/cn/pinyin/cartesianProduct.js.map +0 -1
  338. package/lib/cn/pinyin/data.json +0 -413
  339. package/lib/cn/pinyin/loader.js +0 -15
  340. package/lib/cn/pinyin/loader.js.map +0 -1
  341. package/lib/cn/pinyin/preload.js +0 -4
  342. package/lib/cn/pinyin/preload.js.map +0 -1
  343. package/lib/cn/pinyin/toPinyinPure.js +0 -32
  344. package/lib/cn/pinyin/toPinyinPure.js.map +0 -1
  345. package/lib/cn/pinyin/transform.js +0 -14
  346. package/lib/cn/pinyin/transform.js.map +0 -1
  347. package/lib/cn/types.js +0 -3
  348. package/lib/cn/types.js.map +0 -1
  349. package/lib/cn/uscc/Mod31.js +0 -49
  350. package/lib/cn/uscc/Mod31.js.map +0 -1
  351. package/lib/cn/uscc/USCC.js +0 -94
  352. package/lib/cn/uscc/USCC.js.map +0 -1
  353. package/lib/cn/uscc/isUSCC.js +0 -8
  354. package/lib/cn/uscc/isUSCC.js.map +0 -1
  355. package/lib/crypto/base.js.map +0 -1
  356. package/lib/crypto/getNodeCrypto.js.map +0 -1
  357. package/lib/crypto/getRandomValues.js +0 -36
  358. package/lib/crypto/getRandomValues.js.map +0 -1
  359. package/lib/crypto/hashing.js.map +0 -1
  360. package/lib/crypto/md5.bench.js.map +0 -1
  361. package/lib/crypto/md5.d.js.map +0 -1
  362. package/lib/crypto/md5.js.map +0 -1
  363. package/lib/crypto/pem/pem.js.map +0 -1
  364. package/lib/crypto/randomUUID.js +0 -16
  365. package/lib/crypto/randomUUID.js.map +0 -1
  366. package/lib/crypto/randomUUIDv7.js.map +0 -1
  367. package/lib/crypto/ulid.js.map +0 -1
  368. package/lib/emitter/types.js.map +0 -1
  369. package/lib/errors/Errors.js.map +0 -1
  370. package/lib/fetch/HttpStatus.js.map +0 -1
  371. package/lib/fetch/createFetchWith.js.map +0 -1
  372. package/lib/fetch/createFetchWithLogging.js.map +0 -1
  373. package/lib/fetch/createFetchWithRetry.js.map +0 -1
  374. package/lib/fetch/dumpRequest.js.map +0 -1
  375. package/lib/fetch/dumpResponse.js.map +0 -1
  376. package/lib/fetch/http.types.js.map +0 -1
  377. package/lib/fetch/index.js.map +0 -1
  378. package/lib/fetch/types.js.map +0 -1
  379. package/lib/i18n/createTranslate.js.map +0 -1
  380. package/lib/index.js.map +0 -1
  381. package/lib/io/AbstractEncoding.js.map +0 -1
  382. package/lib/io/ArrayBuffer.test-d.js.map +0 -1
  383. package/lib/io/ArrayBuffers.js.map +0 -1
  384. package/lib/io/Buffer.js.map +0 -1
  385. package/lib/io/ByteBuffer.js.map +0 -1
  386. package/lib/io/base64.js.map +0 -1
  387. package/lib/io/dump.js.map +0 -1
  388. package/lib/io/isBuffer.js.map +0 -1
  389. package/lib/io/isTransferable.js.map +0 -1
  390. package/lib/io/parseDataUri.js.map +0 -1
  391. package/lib/langs/MaybeFunction.js.map +0 -1
  392. package/lib/langs/classOf.js.map +0 -1
  393. package/lib/langs/deepEqual.js.map +0 -1
  394. package/lib/langs/deepFreeze.js.map +0 -1
  395. package/lib/langs/getGlobalStates.js.map +0 -1
  396. package/lib/langs/getObjectId.js.map +0 -1
  397. package/lib/langs/isClass.js.map +0 -1
  398. package/lib/langs/isDefined.js.map +0 -1
  399. package/lib/langs/isEmptyObject.js.map +0 -1
  400. package/lib/langs/isFunction.js.map +0 -1
  401. package/lib/langs/isNullish.js +0 -5
  402. package/lib/langs/isNullish.js.map +0 -1
  403. package/lib/langs/isPlainObject.js.map +0 -1
  404. package/lib/langs/memoize.js.map +0 -1
  405. package/lib/langs/mixin.js.map +0 -1
  406. package/lib/langs/parseBoolean.js.map +0 -1
  407. package/lib/langs/shallowClone.js.map +0 -1
  408. package/lib/langs/shallowEqual.js.map +0 -1
  409. package/lib/libs/ms.js.map +0 -1
  410. package/lib/logging/Logger.js +0 -5
  411. package/lib/logging/Logger.js.map +0 -1
  412. package/lib/logging/createChildLogger.js +0 -16
  413. package/lib/logging/createChildLogger.js.map +0 -1
  414. package/lib/logging/createLogger.js +0 -63
  415. package/lib/logging/createLogger.js.map +0 -1
  416. package/lib/logging/createNoopLogger.js +0 -13
  417. package/lib/logging/createNoopLogger.js.map +0 -1
  418. package/lib/logging/slog.js +0 -143
  419. package/lib/logging/slog.js.map +0 -1
  420. package/lib/maths/clamp.js.map +0 -1
  421. package/lib/maths/random.js.map +0 -1
  422. package/lib/mitt/index.js +0 -77
  423. package/lib/mitt/index.js.map +0 -1
  424. package/lib/modules/isModule.js.map +0 -1
  425. package/lib/modules/parseModuleId.js.map +0 -1
  426. package/lib/objects/computeIfAbsent.js.map +0 -1
  427. package/lib/objects/get.js.map +0 -1
  428. package/lib/objects/get.test-d.js.map +0 -1
  429. package/lib/objects/merge/index.js.map +0 -1
  430. package/lib/objects/merge/isMergeableObject.js.map +0 -1
  431. package/lib/objects/merge/merge.js.map +0 -1
  432. package/lib/objects/parseObjectPath.js.map +0 -1
  433. package/lib/objects/set.js.map +0 -1
  434. package/lib/runtime/AsyncCloser.js +0 -40
  435. package/lib/runtime/AsyncCloser.js.map +0 -1
  436. package/lib/runtime/Closer.js +0 -34
  437. package/lib/runtime/Closer.js.map +0 -1
  438. package/lib/runtime/getGlobalThis.js.map +0 -1
  439. package/lib/runtime/structuredClone.js.map +0 -1
  440. package/lib/schema/typebox/index.js.map +0 -1
  441. package/lib/schema/typebox/typebox.js.map +0 -1
  442. package/lib/scripts/getGenerateContext.js.map +0 -1
  443. package/lib/server/crypto/md5.js.map +0 -1
  444. package/lib/server/fetch/createFetchWithProxy.js.map +0 -1
  445. package/lib/server/fetch/createFetchWithProxyByNodeFetch.js.map +0 -1
  446. package/lib/server/fetch/createFetchWithProxyByUndici.js.map +0 -1
  447. package/lib/server/getPackageDir.js.map +0 -1
  448. package/lib/server/index.js.map +0 -1
  449. package/lib/server/jsdom.js.map +0 -1
  450. package/lib/server/node-fetch.js.map +0 -1
  451. package/lib/server/polyfill/polyfillBrowser.js.map +0 -1
  452. package/lib/server/polyfill/polyfillCrypto.js.map +0 -1
  453. package/lib/server/polyfill/polyfillFetch.js.map +0 -1
  454. package/lib/server/polyfill/polyfillJsDom.js.map +0 -1
  455. package/lib/server/polyfill/polyfillWebSocket.js.map +0 -1
  456. package/lib/server/ws.js.map +0 -1
  457. package/lib/strings/camelCase.js.map +0 -1
  458. package/lib/strings/formatBytes.js.map +0 -1
  459. package/lib/strings/renderTemplate.js.map +0 -1
  460. package/lib/typedoc.js.map +0 -1
  461. package/lib/types.d.js.map +0 -1
  462. package/lib/validations/asserts.js.map +0 -1
  463. package/lib/validations/isUUID.js.map +0 -1
  464. package/lib/validations/parseTimestamp.js.map +0 -1
  465. package/src/cn/README.md +0 -3
  466. package/src/cn/division/DivisionCode.ts +0 -155
  467. package/src/cn/division/binarySearch.test.ts +0 -64
  468. package/src/cn/division/binarySearch.ts +0 -25
  469. package/src/cn/division/division.test.ts +0 -6
  470. package/src/cn/formatChineseAmount.ts +0 -61
  471. package/src/cn/id/Mod11.ts +0 -26
  472. package/src/cn/id/ResidentIdNumber.ts +0 -126
  473. package/src/cn/id/id.test.ts +0 -20
  474. package/src/cn/id/types.ts +0 -26
  475. package/src/cn/index.ts +0 -17
  476. package/src/cn/parseChineseNumber.test.ts +0 -159
  477. package/src/cn/parseChineseNumber.ts +0 -97
  478. package/src/cn/pinyin/cartesianProduct.test.ts +0 -64
  479. package/src/cn/pinyin/cartesianProduct.ts +0 -24
  480. package/src/cn/pinyin/data.json +0 -413
  481. package/src/cn/pinyin/loader.ts +0 -12
  482. package/src/cn/pinyin/preload.ts +0 -3
  483. package/src/cn/pinyin/toPinyin.test.ts +0 -12
  484. package/src/cn/pinyin/toPinyinPure.ts +0 -43
  485. package/src/cn/pinyin/transform.ts +0 -12
  486. package/src/cn/scripts/gen.test.ts +0 -131
  487. package/src/cn/types.ts +0 -11
  488. package/src/cn/uscc/Mod31.ts +0 -38
  489. package/src/cn/uscc/USCC.ts +0 -94
  490. package/src/cn/uscc/isUSCC.ts +0 -8
  491. package/src/cn/uscc/uscc.test.ts +0 -16
  492. package/src/crypto/getRandomValues.ts +0 -41
  493. package/src/crypto/randomUUID.ts +0 -19
  494. package/src/langs/isNullish.ts +0 -3
  495. package/src/logging/Logger.ts +0 -25
  496. package/src/logging/createChildLogger.ts +0 -16
  497. package/src/logging/createLogger.ts +0 -50
  498. package/src/logging/createNoopLogger.ts +0 -13
  499. package/src/logging/logger.test.ts +0 -36
  500. package/src/logging/slog.test.ts +0 -8
  501. package/src/logging/slog.ts +0 -221
  502. package/src/mitt/README.md +0 -1
  503. package/src/mitt/index.ts +0 -114
  504. package/src/runtime/AsyncCloser.ts +0 -45
  505. package/src/runtime/Closer.ts +0 -39
  506. package/src/runtime/structuredClone.ts +0 -88
@@ -1,3 +1,5 @@
1
+ import type { Bytes } from '../io/types';
2
+
1
3
  /**
2
4
  * Trigger browser download
3
5
  * @param filename download as filename
@@ -6,42 +8,42 @@
6
8
  * @param raw if true, data is treated as raw data, not url
7
9
  */
8
10
  export async function download(filename: string, data: any, { type = 'application/octet-stream', raw = false } = {}) {
9
- const a = document.createElement('a');
10
- let closer: () => void = () => null;
11
- try {
12
- a.download = filename;
11
+ const a = document.createElement('a');
12
+ let closer: () => void = () => null;
13
+ try {
14
+ a.download = filename;
13
15
 
14
- // url or data url
15
- if (typeof data === 'string' && /^(https?:|data:)/.test(data) && !raw) {
16
- a.href = data;
17
- // 只有 same-origin 才能 download
18
- if (/^https?:/.test(data)) {
19
- if (new URL(data).origin !== location.origin) {
20
- // 非同源
21
- a.href = '';
22
- data = await fetch(data).then((res) => res.blob());
23
- }
24
- }
25
- } else if (typeof data === 'string') {
26
- data = new TextEncoder().encode(data);
27
- }
16
+ // url or data url
17
+ if (typeof data === 'string' && /^(https?:|data:)/.test(data) && !raw) {
18
+ a.href = data;
19
+ // 只有 same-origin 才能 download
20
+ if (/^https?:/.test(data)) {
21
+ if (new URL(data).origin !== location.origin) {
22
+ // 非同源
23
+ a.href = '';
24
+ data = await fetch(data).then((res) => res.blob());
25
+ }
26
+ }
27
+ } else if (typeof data === 'string') {
28
+ data = new TextEncoder().encode(data);
29
+ }
28
30
 
29
- if (data instanceof Uint8Array) {
30
- data = new Blob([data], { type });
31
- }
32
- {
33
- if (data instanceof File || data instanceof Blob || data instanceof MediaSource) {
34
- a.href = URL.createObjectURL(data);
35
- closer = () => {
36
- URL.revokeObjectURL(a.href);
37
- };
38
- } else {
39
- console.error(`invalid download data`, data);
40
- throw new Error(`can not download ${data && Object.getPrototypeOf(data)}`);
41
- }
42
- a.click();
43
- }
44
- } finally {
45
- closer();
46
- }
31
+ if (data instanceof Uint8Array) {
32
+ data = new Blob([data as Bytes], { type });
33
+ }
34
+ {
35
+ if (data instanceof File || data instanceof Blob || data instanceof MediaSource) {
36
+ a.href = URL.createObjectURL(data);
37
+ closer = () => {
38
+ URL.revokeObjectURL(a.href);
39
+ };
40
+ } else {
41
+ console.error(`invalid download data`, data);
42
+ throw new Error(`can not download ${data && Object.getPrototypeOf(data)}`);
43
+ }
44
+ a.click();
45
+ }
46
+ } finally {
47
+ closer();
48
+ }
47
49
  }
@@ -1,41 +1,41 @@
1
1
  export function getFileFromDataTransfer(dataTransfer?: DataTransfer | null): { file?: File; name?: string } {
2
- if (!dataTransfer) {
3
- return {};
4
- }
2
+ if (!dataTransfer) {
3
+ return {};
4
+ }
5
5
 
6
- const items: DataTransferItemList = dataTransfer.items ?? [];
6
+ const items: DataTransferItemList = dataTransfer.items ?? [];
7
7
 
8
- if (items.length >= 2 && items[0].kind === 'string' && items[1].kind === 'file') {
9
- // name, file
10
- const text = dataTransfer.getData('text');
11
- const file = items[1].getAsFile() ?? dataTransfer.files?.item(0);
12
- if (!file) {
13
- console.error(`no file ${text}`, items[1]);
14
- return {};
15
- }
8
+ if (items.length >= 2 && items[0].kind === 'string' && items[1].kind === 'file') {
9
+ // name, file
10
+ const text = dataTransfer.getData('text');
11
+ const file = items[1].getAsFile() ?? dataTransfer.files?.item(0);
12
+ if (!file) {
13
+ console.error(`no file ${text}`, items[1]);
14
+ return {};
15
+ }
16
16
 
17
- // let type = file.type;
18
- // // fix type
19
- // type = type;
20
- // // NOTE paste file can not parse by libs
21
- // if (type !== file.type) {
22
- // const blob = file.slice(0, file.size);
23
- // file = new File([blob], text, {type});
24
- // }
17
+ // let type = file.type;
18
+ // // fix type
19
+ // type = type;
20
+ // // NOTE paste file can not parse by libs
21
+ // if (type !== file.type) {
22
+ // const blob = file.slice(0, file.size);
23
+ // file = new File([blob], text, {type});
24
+ // }
25
25
 
26
- return { file, name: text };
27
- } else if (items[0].kind === 'file') {
28
- const file = items[0].getAsFile();
29
- if (!file) {
30
- console.error(`no file`, items[0]);
31
- return {};
32
- }
33
- return { file, name: file.name };
34
- } else {
35
- console.debug(
36
- `file item not match`,
37
- Array.from(items).map((v) => ({ type: v.type, kind: v.kind })),
38
- );
39
- }
40
- return {};
26
+ return { file, name: text };
27
+ } else if (items[0].kind === 'file') {
28
+ const file = items[0].getAsFile();
29
+ if (!file) {
30
+ console.error(`no file`, items[0]);
31
+ return {};
32
+ }
33
+ return { file, name: file.name };
34
+ } else {
35
+ console.debug(
36
+ `file item not match`,
37
+ Array.from(items).map((v) => ({ type: v.type, kind: v.kind })),
38
+ );
39
+ }
40
+ return {};
41
41
  }
@@ -1,65 +1,65 @@
1
1
  function load(
2
- el: HTMLScriptElement | HTMLLinkElement,
3
- resolve: (v: any) => void,
4
- reject: (v: any) => void,
5
- options: { attributes: Record<string, string> } | undefined,
2
+ el: HTMLScriptElement | HTMLLinkElement,
3
+ resolve: (v: any) => void,
4
+ reject: (v: any) => void,
5
+ options: { attributes: Record<string, string> } | undefined,
6
6
  ) {
7
- el.onload = () => {
8
- resolve(el);
9
- };
10
- el.onerror = (e) => {
11
- el.remove();
12
- reject(e);
13
- };
14
- const { attributes = {} } = options || {};
15
- Object.entries(attributes).forEach(([k, v]) => {
16
- el.setAttribute(k, v);
17
- });
7
+ el.onload = () => {
8
+ resolve(el);
9
+ };
10
+ el.onerror = (e) => {
11
+ el.remove();
12
+ reject(e);
13
+ };
14
+ const { attributes = {} } = options || {};
15
+ Object.entries(attributes).forEach(([k, v]) => {
16
+ el.setAttribute(k, v);
17
+ });
18
18
 
19
- document.head.appendChild(el);
19
+ document.head.appendChild(el);
20
20
  }
21
21
 
22
22
  export function loadScripts(
23
- src: string[],
24
- options?: { attributes: Record<string, string> },
23
+ src: string[],
24
+ options?: { attributes: Record<string, string> },
25
25
  ): Promise<HTMLScriptElement[]>;
26
26
  export function loadScripts(src: string, options?: { attributes: Record<string, string> }): Promise<HTMLScriptElement>;
27
27
 
28
28
  export function loadScripts(
29
- src: string | string[],
30
- options?: { attributes: Record<string, string> },
29
+ src: string | string[],
30
+ options?: { attributes: Record<string, string> },
31
31
  ): Promise<HTMLScriptElement | HTMLScriptElement[]> {
32
- if (Array.isArray(src)) {
33
- return Promise.resolve().then(async () => {
34
- const all = [];
35
- for (const s of src) {
36
- all.push(await loadScripts(s));
37
- }
38
- return all;
39
- });
40
- }
41
- // todo quote ?
42
- const $ele = document.querySelector(`script[src="${src}"]`) as HTMLScriptElement;
43
- if ($ele) {
44
- return Promise.resolve($ele);
45
- }
46
- return new Promise((resolve, reject) => {
47
- const el = document.createElement('script');
48
- el.src = src;
49
- load(el, resolve, reject, options);
50
- });
32
+ if (Array.isArray(src)) {
33
+ return Promise.resolve().then(async () => {
34
+ const all = [];
35
+ for (const s of src) {
36
+ all.push(await loadScripts(s));
37
+ }
38
+ return all;
39
+ });
40
+ }
41
+ // todo quote ?
42
+ const $ele = document.querySelector(`script[src="${src}"]`) as HTMLScriptElement;
43
+ if ($ele) {
44
+ return Promise.resolve($ele);
45
+ }
46
+ return new Promise((resolve, reject) => {
47
+ const el = document.createElement('script');
48
+ el.src = src;
49
+ load(el, resolve, reject, options);
50
+ });
51
51
  }
52
52
 
53
53
  export function loadStyles(href: string, options?: { attributes: Record<string, string> }): Promise<HTMLLinkElement> {
54
- const $ele = document.querySelector(`link[href="${href}"]`) as HTMLLinkElement;
55
- if ($ele) {
56
- return Promise.resolve($ele);
57
- }
54
+ const $ele = document.querySelector(`link[href="${href}"]`) as HTMLLinkElement;
55
+ if ($ele) {
56
+ return Promise.resolve($ele);
57
+ }
58
58
 
59
- return new Promise((resolve, reject) => {
60
- const el = document.createElement('link');
61
- el.rel = 'stylesheet';
62
- el.href = href;
63
- load(el, resolve, reject, options);
64
- });
59
+ return new Promise((resolve, reject) => {
60
+ const el = document.createElement('link');
61
+ el.rel = 'stylesheet';
62
+ el.href = href;
63
+ load(el, resolve, reject, options);
64
+ });
65
65
  }
@@ -2,7 +2,7 @@
2
2
  * hex string
3
3
  */
4
4
  export function hex(s: Uint8Array | ArrayBuffer) {
5
- return Array.from(new Uint8Array(s))
6
- .map((v) => v.toString(16).padStart(2, '0'))
7
- .join('');
5
+ return Array.from(new Uint8Array(s))
6
+ .map((v) => v.toString(16).padStart(2, '0'))
7
+ .join('');
8
8
  }
@@ -1,5 +1,5 @@
1
1
  // import type * as NodeCrypto from 'node:crypto';
2
- import { getGlobalThis } from '../runtime/getGlobalThis';
2
+ import { getGlobalThis } from '../web/getGlobalThis';
3
3
 
4
4
  let nodeCrypto;
5
5
  // globalThis.process?.release?.name
@@ -17,6 +17,6 @@ let nodeCrypto;
17
17
  // } catch (e) {}
18
18
  // }
19
19
  export function getNodeCrypto() {
20
- nodeCrypto ||= getGlobalThis().crypto;
21
- return nodeCrypto;
20
+ nodeCrypto ||= getGlobalThis().crypto;
21
+ return nodeCrypto;
22
22
  }
@@ -2,68 +2,54 @@ import { assert, beforeAll, expect, test } from 'vitest';
2
2
  import { ArrayBuffers } from '../io/ArrayBuffers';
3
3
  import { polyfillCrypto } from '../server/polyfill/polyfillCrypto';
4
4
  import { isUUID } from '../validations/isUUID';
5
+ import { _randomUUID } from '../web/randomUUID';
5
6
  import { hex } from './base';
6
7
  import { hmac, sha1, sha256, sha384, sha512 } from './hashing';
7
8
  import { md5 } from './md5';
8
- import { _randomUUID } from './randomUUID';
9
9
 
10
10
  beforeAll(async () => {
11
- await polyfillCrypto();
11
+ await polyfillCrypto();
12
12
  });
13
13
 
14
14
  test('sha', async () => {
15
- expect(hex(await sha1(''))).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709');
16
- expect(await sha1('', 'hex')).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709');
17
- expect(ArrayBuffers.toString(await sha1(''), 'base64')).toBe('2jmj7l5rSw0yVb/vlWAYkK/YBwk=');
18
- expect(await sha1('', 'base64')).toBe('2jmj7l5rSw0yVb/vlWAYkK/YBwk=');
15
+ expect(hex(await sha1('', 'buffer'))).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709');
16
+ expect(await sha1('', 'hex')).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709');
17
+ expect(ArrayBuffers.toString(await sha1('', 'buffer'), 'base64')).toBe('2jmj7l5rSw0yVb/vlWAYkK/YBwk=');
18
+ expect(await sha1('', 'base64')).toBe('2jmj7l5rSw0yVb/vlWAYkK/YBwk=');
19
19
 
20
- expect(await sha1('', 'hex')).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709');
21
- expect(hex(await sha1('abc'))).toBe('a9993e364706816aba3e25717850c26c9cd0d89d');
22
- expect(hex(await sha256(''))).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
23
- expect(hex(await sha384(''))).toBe(
24
- '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b',
25
- );
26
- expect(hex(await sha512(''))).toBe(
27
- 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
28
- );
20
+ expect(await sha1('', 'hex')).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709');
21
+ expect(hex(await sha1('abc', 'buffer'))).toBe('a9993e364706816aba3e25717850c26c9cd0d89d');
22
+ expect(hex(await sha256('', 'buffer'))).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
23
+ expect(hex(await sha384('', 'buffer'))).toBe(
24
+ '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b',
25
+ );
26
+ expect(hex(await sha512('', 'buffer'))).toBe(
27
+ 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
28
+ );
29
29
 
30
- expect(md5('Hello')).toBe('8b1a9953c4611296a827abf8c47804d7');
30
+ expect(md5('Hello')).toBe('8b1a9953c4611296a827abf8c47804d7');
31
31
  });
32
32
 
33
33
  test('randomUUID', () => {
34
- for (let i = 0; i < 20; i++) {
35
- expect(isUUID(_randomUUID())).toBeTruthy();
36
- }
34
+ for (let i = 0; i < 20; i++) {
35
+ expect(isUUID(_randomUUID())).toBeTruthy();
36
+ }
37
37
  });
38
38
 
39
39
  test('hmac', async () => {
40
- let key = await crypto.subtle.importKey(
41
- 'raw',
42
- new TextEncoder().encode('YourAccessKeySecret'),
43
- {
44
- name: 'HMAC',
45
- hash: {
46
- name: 'SHA-256',
47
- },
48
- },
49
- false,
50
- ['sign', 'verify'],
51
- );
52
- const out = hex(
53
- await crypto.subtle.sign(
54
- {
55
- name: 'HMAC',
56
- hash: {
57
- name: 'SHA-256',
58
- },
59
- },
60
- key,
61
- new TextEncoder().encode(''),
62
- ),
63
- );
64
- console.log(out);
65
- const { createHmac } = await import('node:crypto');
66
- let fromNode = createHmac('sha256', 'YourAccessKeySecret').update('').digest('hex');
67
- assert.equal(out, fromNode);
68
- assert.equal(out, await hmac('sha256', 'YourAccessKeySecret', '', 'hex'));
40
+ let key = await crypto.subtle.importKey(
41
+ 'raw',
42
+ new TextEncoder().encode('YourAccessKeySecret'),
43
+ { name: 'HMAC', hash: { name: 'SHA-256' } },
44
+ false,
45
+ ['sign', 'verify'],
46
+ );
47
+ const out = hex(
48
+ await crypto.subtle.sign({ name: 'HMAC', hash: { name: 'SHA-256' } }, key, new TextEncoder().encode('')),
49
+ );
50
+ console.log(out);
51
+ const { createHmac } = await import('node:crypto');
52
+ let fromNode = createHmac('sha256', 'YourAccessKeySecret').update('').digest('hex');
53
+ assert.equal(out, fromNode);
54
+ assert.equal(out, await hmac('sha256', 'YourAccessKeySecret', '', 'hex'));
69
55
  });
@@ -1,112 +1,112 @@
1
1
  import { ArrayBuffers } from '../io/ArrayBuffers';
2
2
 
3
- export function sha1(s: BinaryLike, o?: undefined): Promise<Buffer>;
4
- export function sha1(s: BinaryLike, o: 'hex' | 'base64'): Promise<string>;
3
+ type HashEncoding = 'hex' | 'base64' | 'buffer';
4
+
5
+ type HashFunction = {
6
+ (s: BinaryLike, o?: 'hex' | 'base64' | undefined): Promise<string>;
7
+ (s: BinaryLike, o: 'buffer'): Promise<ArrayBuffer>;
8
+ };
9
+
10
+ function createDigestFunction(a: string): HashFunction {
11
+ return (async (s: BinaryLike, o: HashEncoding = 'hex') => {
12
+ const buffer = await crypto.subtle.digest(a, binaryOf(s));
13
+ if (o === 'buffer') {
14
+ return buffer;
15
+ }
16
+ return ArrayBuffers.toString(buffer, o || 'hex');
17
+ }) as HashFunction;
18
+ }
5
19
 
20
+ export function sha1(s: BinaryLike, o?: undefined | 'buffer'): Promise<Buffer>;
21
+ export function sha1(s: BinaryLike, o: 'hex' | 'base64'): Promise<string>;
6
22
  export function sha1(s: BinaryLike, o?: DigestOptions) {
7
- return digestOf('SHA-1', s, o);
23
+ return digestOf('SHA-1', s, o);
8
24
  }
9
25
 
10
- export function sha256(s: BinaryLike, o?: undefined): Promise<Buffer>;
26
+ export function sha256(s: BinaryLike, o?: undefined | 'buffer'): Promise<Buffer>;
11
27
  export function sha256(s: BinaryLike, o: 'hex' | 'base64'): Promise<string>;
12
28
 
13
29
  export function sha256(s: BinaryLike, o?: DigestOptions) {
14
- return digestOf('SHA-256', s, o);
30
+ return digestOf('SHA-256', s, o);
15
31
  }
16
32
 
17
- export function sha384(s: BinaryLike, o?: undefined): Promise<Buffer>;
33
+ export function sha384(s: BinaryLike, o?: undefined | 'buffer'): Promise<Buffer>;
18
34
  export function sha384(s: BinaryLike, o: 'hex' | 'base64'): Promise<string>;
19
35
 
20
36
  export function sha384(s: BinaryLike, o?: DigestOptions) {
21
- return digestOf('SHA-384', s, o);
37
+ return digestOf('SHA-384', s, o);
22
38
  }
23
39
 
24
- export function sha512(s: BinaryLike, o?: undefined): Promise<Buffer>;
40
+ export function sha512(s: BinaryLike, o?: undefined | 'buffer'): Promise<Buffer>;
25
41
  export function sha512(s: BinaryLike, o: 'hex' | 'base64'): Promise<string>;
26
42
 
27
43
  export function sha512(s: BinaryLike, o?: DigestOptions) {
28
- return digestOf('SHA-512', s, o);
44
+ return digestOf('SHA-512', s, o);
29
45
  }
30
46
 
31
47
  function digestOf(a: string, s: BinaryLike, o?: DigestOptions) {
32
- let buffer = crypto.subtle.digest(a, binaryOf(s));
33
- return o ? buffer.then((v) => encode(v, o)) : buffer;
48
+ let buffer = crypto.subtle.digest(a, binaryOf(s));
49
+ if (o === 'buffer') {
50
+ return buffer;
51
+ }
52
+ return o ? buffer.then((v) => encode(v, o)) : buffer;
34
53
  }
35
54
 
36
- export type DigestOptions =
37
- | 'hex'
38
- | 'base64'
39
- | {
40
- encoding: 'hex' | 'base64';
41
- };
55
+ export type DigestOptions = 'hex' | 'base64' | 'buffer' | { encoding: 'hex' | 'base64' };
42
56
 
43
57
  type BinaryLike = string | BufferSource;
44
58
 
45
59
  function binaryOf(s: BinaryLike) {
46
- // ArrayBuffer, TypedArray, DataView
47
- if (typeof s === 'string') {
48
- return new TextEncoder().encode(s);
49
- }
50
- // ArrayBuffer, Buffer, TypedArray, DataView
51
- return s;
60
+ // ArrayBuffer, TypedArray, DataView
61
+ if (typeof s === 'string') {
62
+ return new TextEncoder().encode(s);
63
+ }
64
+ // ArrayBuffer, Buffer, TypedArray, DataView
65
+ return s;
52
66
  }
53
67
 
54
68
  function encode(buf: BufferSource, o?: DigestOptions) {
55
- if (o) {
56
- switch (o) {
57
- case 'hex':
58
- case 'base64':
59
- return ArrayBuffers.toString(buf, o);
60
- }
61
- }
62
- return buf;
69
+ if (o) {
70
+ switch (o) {
71
+ case 'hex':
72
+ case 'base64':
73
+ return ArrayBuffers.toString(buf, o);
74
+ }
75
+ }
76
+ return buf;
63
77
  }
64
78
 
65
79
  type StringEncoding = 'hex' | 'base64';
66
80
  type IsStringCoding<T> = T extends StringEncoding ? true : T extends { encoding: StringEncoding } ? true : false;
67
81
 
68
82
  export function hmac<O extends DigestOptions>(
69
- hash: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' | 'sha1' | 'sha256' | 'sha384' | 'sha512',
70
- key: BinaryLike | CryptoKey,
71
- data: BinaryLike,
72
- o?: O,
83
+ hash: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' | 'sha1' | 'sha256' | 'sha384' | 'sha512',
84
+ key: BinaryLike | CryptoKey,
85
+ data: BinaryLike,
86
+ o?: O,
73
87
  ): Promise<IsStringCoding<O> extends true ? string : Buffer>;
74
88
 
75
89
  export async function hmac(
76
- hash: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' | 'sha1' | 'sha256' | 'sha384' | 'sha512',
77
- key: BinaryLike | CryptoKey,
78
- data: BinaryLike,
79
- o?: DigestOptions,
90
+ hash: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' | 'sha1' | 'sha256' | 'sha384' | 'sha512',
91
+ key: BinaryLike | CryptoKey,
92
+ data: BinaryLike,
93
+ o?: DigestOptions,
80
94
  ) {
81
- let ck =
82
- key instanceof CryptoKey
83
- ? key
84
- : await crypto.subtle.importKey(
85
- 'raw',
86
- binaryOf(key),
87
- {
88
- name: 'HMAC',
89
- hash: {
90
- name: normalizeHash(hash),
91
- },
92
- },
93
- false,
94
- ['sign'],
95
- );
96
- let buffer = await crypto.subtle.sign(
97
- {
98
- name: 'HMAC',
99
- hash: {
100
- name: hash,
101
- },
102
- },
103
- ck,
104
- binaryOf(data),
105
- );
106
-
107
- return encode(buffer, o);
95
+ let ck =
96
+ key instanceof CryptoKey
97
+ ? key
98
+ : await crypto.subtle.importKey(
99
+ 'raw',
100
+ binaryOf(key),
101
+ { name: 'HMAC', hash: { name: normalizeHash(hash) } },
102
+ false,
103
+ ['sign'],
104
+ );
105
+ let buffer = await crypto.subtle.sign({ name: 'HMAC', hash: { name: hash } }, ck, binaryOf(data));
106
+
107
+ return encode(buffer, o);
108
108
  }
109
109
 
110
110
  function normalizeHash(hash: string) {
111
- return hash.replace(/^sha/i, 'SHA-');
111
+ return hash.replace(/^sha/i, 'SHA-');
112
112
  }
@@ -3,29 +3,25 @@ import { bench, describe } from 'vitest';
3
3
  import { md5 } from './md5';
4
4
 
5
5
  describe('md5', () => {
6
- const dataset = new Array(10000).fill(0).map((_, i) => String(Math.random() * i));
7
- let iterations = 0;
8
- bench(
9
- 'js',
10
- function () {
11
- iterations++;
12
- md5(dataset[iterations % dataset.length]);
13
- },
14
- {
15
- iterations: 10000,
16
- },
17
- );
6
+ const dataset = new Array(10000).fill(0).map((_, i) => String(Math.random() * i));
7
+ let iterations = 0;
8
+ bench(
9
+ 'js',
10
+ function () {
11
+ iterations++;
12
+ md5(dataset[iterations % dataset.length]);
13
+ },
14
+ { iterations: 10000 },
15
+ );
18
16
 
19
- bench(
20
- 'native',
21
- function () {
22
- iterations++;
23
- createHash('md5')
24
- .update(dataset[iterations % dataset.length])
25
- .digest('hex');
26
- },
27
- {
28
- iterations: 10000,
29
- },
30
- );
17
+ bench(
18
+ 'native',
19
+ function () {
20
+ iterations++;
21
+ createHash('md5')
22
+ .update(dataset[iterations % dataset.length])
23
+ .digest('hex');
24
+ },
25
+ { iterations: 10000 },
26
+ );
31
27
  });
@@ -2,7 +2,7 @@ import { assert, describe, test } from 'vitest';
2
2
  import { md5 } from './md5';
3
3
 
4
4
  describe('md5', () => {
5
- test('js', () => {
6
- assert.equal(md5(''), 'd41d8cd98f00b204e9800998ecf8427e');
7
- });
5
+ test('js', () => {
6
+ assert.equal(md5(''), 'd41d8cd98f00b204e9800998ecf8427e');
7
+ });
8
8
  });