polyfill-crypto-methods
Version:
Polyfill for Crypto instance methods of Web Crypto API
52 lines (51 loc) • 2.2 kB
TypeScript
declare module "global-this" {
type GlobalType<T extends any> = T extends Window ? Window : T extends typeof globalThis ? typeof globalThis : never;
export function getGlobalThis(): GlobalType<typeof globalThis>;
}
declare module "shim" {
/**
* @see https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
*/
type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
type RandomBytesCallback = (err: Error | null, buf: Uint8Array) => void;
/**
* Web Crypto API 中的 Crypto 实例方法 + Node.js 中的 crypto.randomBytes() 方法
* @see https://developer.mozilla.org/docs/Web/API/Crypto
*/
export interface CryptoMethods {
getRandomValues<T extends TypedArray>(array: T): T;
randomUUID(): string;
/** Node.js 中的 crypto.randomBytes() 方法 */
randomBytes(size: number): Uint8Array;
randomBytes(size: number, callback: RandomBytesCallback): Promise<Uint8Array>;
}
/**
* crypto.getRandomValues() 方法实现
* @see https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues
*/
export function getRandomValues<T extends TypedArray>(array: T): T;
/**
* Node.js 中的 crypto.randomBytes() 方法实现
* @see https://nodejs.cn/api/crypto.html#crypto_crypto_randombytes_size_callback
*/
export function randomBytes<T extends Uint8Array | Promise<Uint8Array> = Uint8Array>(size: number, callback?: RandomBytesCallback): T;
/**
* crypto.randomUUID() 方法实现
* @see https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID
*/
export function randomUUID(): string;
}
declare module "polyfill" {
import type { CryptoMethods } from "shim";
export const crypto: CryptoMethods;
}
declare module "index" {
/**
* 填补某些运行环境 (例如微信小程序) 缺失的 Web Crypto API 的 Crypto 实例方法,包括:
* - crypto.getRandomValues()
* - crypto.randomUUID()
* - Node.js crypto.randomBytes()
*/
export { crypto } from "polyfill";
export type { CryptoMethods } from "shim";
}