UNPKG

advanced-js-kit

Version:

Modern TypeScript utility library with tree-shaking support - Array, String, Number, Network, Sleep, and JWT utilities for JavaScript and TypeScript projects

1 lines 27.5 kB
{"version":3,"sources":["../../../src/universal/utils/index.ts","../../../src/node/jwt/index.ts"],"names":["jsonwebtoken"],"mappings":";;;;;;;;;;;AAQO,SAAS,iBAAA,GAA6B;AAC3C,EAAA,OAAO,OAAO,YAAY,WAAA,IACnB,OAAA,CAAQ,YAAY,IAAA,IACpB,OAAA,CAAQ,SAAS,IAAA,IAAQ,IAAA;AAClC;AAMO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OAAO,OAAO,MAAA,KAAW,WAAA,IAClB,OAAO,QAAA,KAAa,WAAA;AAC7B;AAMO,SAAS,sBAAA,GAAkC;AAChD,EAAA,OAAO,OAAQ,UAAA,CAAmB,aAAA,KAAkB,UAAA,IAC7C,OAAO,MAAA,KAAW,WAAA;AAC3B;AAMO,SAAS,cAAA,GAA+D;AAC7E,EAAA,IAAI,iBAAA,IAAqB,OAAO,MAAA;AAChC,EAAA,IAAI,oBAAA,IAAwB,OAAO,SAAA;AACnC,EAAA,IAAI,sBAAA,IAA0B,OAAO,WAAA;AACrC,EAAA,OAAO,SAAA;AACT;AAKO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAC1C,WAAA,CACE,OAAA,EACgB,mBAAA,EACA,kBAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,mBAAA,GAAA,mBAAA;AACA,IAAA,IAAA,CAAA,kBAAA,GAAA,kBAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AAAA;AAEhB,CAAA;AAMO,SAAS,qBAAA,GAA8B;AAC5C,EAAA,IAAI,CAAC,mBAAkB,EAAG;AACxB,IAAA,MAAM,IAAI,gBAAA;AAAA,MACR,iDAAA;AAAA,MACA,MAAA;AAAA,MACA,cAAA;AAAe,KACjB;AAAA;AAEJ;;;AC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GAAA,GAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAKf,MAAA,EAAQ,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,IAAA,EAAM,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMN,MAAA,EAAQ,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,SAAA,EAAW,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMX,eAAA,EAAiB;AACrB","file":"index.cjs","sourcesContent":["/**\r\n * Environment detection utilities\r\n */\r\n\r\n/**\r\n * Determines if the current environment is Node.js\r\n * @returns true if running in Node.js, false otherwise\r\n */\r\nexport function isNodeEnvironment(): boolean {\r\n return typeof process !== 'undefined' && \r\n process.versions != null && \r\n process.versions.node != null;\r\n}\r\n\r\n/**\r\n * Determines if the current environment is a browser\r\n * @returns true if running in a browser, false otherwise\r\n */\r\nexport function isBrowserEnvironment(): boolean {\r\n return typeof window !== 'undefined' && \r\n typeof document !== 'undefined';\r\n}\r\n\r\n/**\r\n * Determines if the current environment is a web worker\r\n * @returns true if running in a web worker, false otherwise\r\n */\r\nexport function isWebWorkerEnvironment(): boolean {\r\n return typeof (globalThis as any).importScripts === 'function' && \r\n typeof window === 'undefined';\r\n}\r\n\r\n/**\r\n * Gets the current runtime environment\r\n * @returns 'node' | 'browser' | 'webworker' | 'unknown'\r\n */\r\nexport function getEnvironment(): 'node' | 'browser' | 'webworker' | 'unknown' {\r\n if (isNodeEnvironment()) return 'node';\r\n if (isBrowserEnvironment()) return 'browser';\r\n if (isWebWorkerEnvironment()) return 'webworker';\r\n return 'unknown';\r\n}\r\n\r\n/**\r\n * Error thrown when functionality is not supported in the current environment\r\n */\r\nexport class EnvironmentError extends Error {\r\n constructor(\r\n message: string,\r\n public readonly requiredEnvironment: string,\r\n public readonly currentEnvironment: string\r\n ) {\r\n super(message);\r\n this.name = 'EnvironmentError';\r\n }\r\n}\r\n\r\n/**\r\n * Asserts that the current environment is Node.js\r\n * @throws {EnvironmentError} if not running in Node.js\r\n */\r\nexport function assertNodeEnvironment(): void {\r\n if (!isNodeEnvironment()) {\r\n throw new EnvironmentError(\r\n 'This functionality requires Node.js environment',\r\n 'node',\r\n getEnvironment()\r\n );\r\n }\r\n}\r\n\r\n/**\r\n * Asserts that the current environment is a browser\r\n * @throws {EnvironmentError} if not running in a browser\r\n */\r\nexport function assertBrowserEnvironment(): void {\r\n if (!isBrowserEnvironment()) {\r\n throw new EnvironmentError(\r\n 'This functionality requires browser environment',\r\n 'browser',\r\n getEnvironment()\r\n );\r\n }\r\n}\r\n","import jsonwebtoken from \"jsonwebtoken\";\r\nimport { JwtPayload, VerifyOptions, SignOptions, Secret, SignCallback } from \"jsonwebtoken\";\r\nimport { assertNodeEnvironment } from \"../../universal/utils\";\r\n\r\n/**\r\n * Type-safe error codes for JWT operations\r\n */\r\nexport type JwtErrorCode = \r\n | 'invalid_token'\r\n | 'invalid_secret' \r\n | 'invalid_payload'\r\n | 'verification_failed'\r\n | 'signing_failed'\r\n | 'token_expired'\r\n | 'decode_failed'\r\n | 'environment_error';\r\n\r\n/**\r\n * Error object for JWT operations\r\n */\r\nexport interface JwtError {\r\n code: JwtErrorCode;\r\n message: string;\r\n originalError?: Error;\r\n}\r\n\r\n/**\r\n * Success result for JWT operations\r\n */\r\nexport interface JwtSuccessResult<T> {\r\n status: 'success';\r\n data: T;\r\n}\r\n\r\n/**\r\n * Error result for JWT operations\r\n */\r\nexport interface JwtErrorResult {\r\n status: 'error';\r\n error: JwtError;\r\n}\r\n\r\n/**\r\n * Result type for JWT operations\r\n */\r\nexport type JwtResult<T> = JwtSuccessResult<T> | JwtErrorResult;\r\n\r\n/**\r\n * Generic payload type for JWT tokens\r\n */\r\nexport interface JwtTokenPayload extends JwtPayload {\r\n [key: string]: any;\r\n}\r\n\r\n/**\r\n * Input parameters for JWT verification\r\n */\r\nexport interface JwtVerifyInput {\r\n /** The JWT token to verify */\r\n token: string;\r\n /** The secret key or public key for verification */\r\n secret: Secret;\r\n /** Additional verification options */\r\n options?: VerifyOptions;\r\n}\r\n\r\n/**\r\n * Input parameters for JWT signing\r\n */\r\nexport interface JwtSignInput<T extends Record<string, any> = Record<string, any>> {\r\n /** The payload to sign */\r\n payload: T;\r\n /** The secret key for signing */\r\n secret: Secret;\r\n /** Additional signing options */\r\n options?: JwtSignOptions;\r\n}\r\n\r\n/**\r\n * Options for JWT signing\r\n */\r\nexport interface JwtSignOptions extends Omit<SignOptions, 'expiresIn'> {\r\n /** Token expiration time */\r\n expiresIn?: string | number;\r\n /** Default expiration time if not specified in payload */\r\n defaultExpiresIn?: string | number;\r\n}\r\n\r\n/**\r\n * Input parameters for JWT decoding\r\n */\r\nexport interface JwtDecodeInput {\r\n /** The JWT token to decode */\r\n token: string;\r\n /** Decode options */\r\n options?: { complete?: boolean };\r\n}\r\n\r\n/**\r\n * Input parameters for JWT expiration check\r\n */\r\nexport interface JwtExpirationInput {\r\n /** The JWT token to check */\r\n token: string;\r\n}\r\n\r\n/**\r\n * Verifies a JWT token and returns a result object.\r\n * \r\n * @template T - The expected payload type\r\n * @param input - Object containing token, secret, and verification options\r\n * @returns Promise that resolves to a result object with status and either data or error\r\n * \r\n * @example\r\n * ```typescript\r\n * // Basic usage\r\n * const result = await jwtVerify<{ userId: string }>({\r\n * token: 'your-jwt-token',\r\n * secret: 'your-secret'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('User ID:', result.data.userId);\r\n * } else {\r\n * console.log('Error:', result.error.code, result.error.message);\r\n * }\r\n * \r\n * // With custom options\r\n * const result = await jwtVerify({\r\n * token: 'your-jwt-token',\r\n * secret: 'your-secret',\r\n * options: { \r\n * audience: 'my-app',\r\n * issuer: 'my-service'\r\n * }\r\n * });\r\n * ```\r\n */\r\nexport async function jwtVerify<T extends JwtTokenPayload = JwtTokenPayload>(\r\n input: JwtVerifyInput\r\n): Promise<JwtResult<T>> {\r\n const { token, secret, options = {} } = input;\r\n\r\n try {\r\n // Check if running in Node.js environment\r\n assertNodeEnvironment();\r\n } catch (error) {\r\n return {\r\n status: 'error',\r\n error: {\r\n code: 'environment_error',\r\n message: 'JWT operations are only supported in Node.js environment',\r\n originalError: error as Error\r\n }\r\n };\r\n }\r\n\r\n return new Promise<JwtResult<T>>((resolve) => {\r\n if (!token || typeof token !== 'string') {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'invalid_token',\r\n message: 'Invalid token: Token must be a non-empty string'\r\n }\r\n });\r\n }\r\n\r\n if (!secret) {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'invalid_secret',\r\n message: 'Invalid secret: Secret is required for token verification'\r\n }\r\n });\r\n }\r\n\r\n jsonwebtoken.verify(token, secret, options, (err, decoded) => {\r\n if (err) {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'verification_failed',\r\n message: `JWT verification failed: ${err.message}`,\r\n originalError: err\r\n }\r\n });\r\n }\r\n\r\n // Ensure we have a valid payload object\r\n if (!decoded || typeof decoded === 'string') {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'invalid_payload',\r\n message: 'Invalid payload: Expected object payload'\r\n }\r\n });\r\n }\r\n\r\n resolve({\r\n status: 'success',\r\n data: decoded as unknown as T\r\n });\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Signs a payload and creates a JWT token.\r\n * \r\n * @template T - The payload type\r\n * @param input - Object containing payload, secret, and signing options\r\n * @returns Promise that resolves to a result object with status and either token or error\r\n * \r\n * @example\r\n * ```typescript\r\n * // Basic usage\r\n * const result = await jwtSign({\r\n * payload: { userId: '123' },\r\n * secret: 'your-secret'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('Token:', result.data);\r\n * } else {\r\n * console.log('Error:', result.error.code, result.error.message);\r\n * }\r\n * \r\n * // With expiration\r\n * const result = await jwtSign({\r\n * payload: { userId: '123', role: 'admin' },\r\n * secret: 'your-secret',\r\n * options: { expiresIn: '1h' }\r\n * });\r\n * \r\n * // With default expiration\r\n * const result = await jwtSign({\r\n * payload: { userId: '123' },\r\n * secret: 'your-secret',\r\n * options: { defaultExpiresIn: '24h' }\r\n * });\r\n * ```\r\n */\r\nexport async function jwtSign<T extends Record<string, any> = Record<string, any>>(\r\n input: JwtSignInput<T>\r\n): Promise<JwtResult<string>> {\r\n const { payload, secret, options = {} } = input;\r\n\r\n try {\r\n // Check if running in Node.js environment\r\n assertNodeEnvironment();\r\n } catch (error) {\r\n return {\r\n status: 'error',\r\n error: {\r\n code: 'environment_error',\r\n message: 'JWT operations are only supported in Node.js environment',\r\n originalError: error as Error\r\n }\r\n };\r\n }\r\n \r\n const { defaultExpiresIn, ...signOptions } = options;\r\n\r\n return new Promise<JwtResult<string>>((resolve) => {\r\n if (!payload || typeof payload !== 'object') {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'invalid_payload',\r\n message: 'Invalid payload: Payload must be an object'\r\n }\r\n });\r\n }\r\n\r\n if (!secret) {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'invalid_secret',\r\n message: 'Invalid secret: Secret is required for token signing'\r\n }\r\n });\r\n }\r\n\r\n // Apply default expiration if not already set\r\n const finalOptions = {\r\n ...signOptions,\r\n ...(defaultExpiresIn && !signOptions.expiresIn && { expiresIn: defaultExpiresIn })\r\n };\r\n\r\n jsonwebtoken.sign(payload, secret, finalOptions as SignOptions, (err, token) => {\r\n if (err) {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'signing_failed',\r\n message: `JWT signing failed: ${err.message}`,\r\n originalError: err\r\n }\r\n });\r\n }\r\n\r\n if (!token) {\r\n return resolve({\r\n status: 'error',\r\n error: {\r\n code: 'signing_failed',\r\n message: 'JWT signing failed: No token generated'\r\n }\r\n });\r\n }\r\n\r\n resolve({\r\n status: 'success',\r\n data: token\r\n });\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Decodes a JWT token without verification and returns a result object.\r\n * Useful for inspecting token contents when verification is not required.\r\n * \r\n * @template T - The expected payload type\r\n * @param input - Object containing token and decode options\r\n * @returns The result object with status and either decoded token or error\r\n * \r\n * @example\r\n * ```typescript\r\n * const result = jwtDecode<{ userId: string }>({\r\n * token: 'your-jwt-token'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('User ID:', result.data.userId);\r\n * console.log('Expires at:', new Date(result.data.exp * 1000));\r\n * } else {\r\n * console.log('Decode error:', result.error.code, result.error.message);\r\n * }\r\n * \r\n * // With complete option\r\n * const result = jwtDecode({\r\n * token: 'your-jwt-token',\r\n * options: { complete: true }\r\n * });\r\n * ```\r\n */\r\nexport function jwtDecode<T extends JwtTokenPayload = JwtTokenPayload>(\r\n input: JwtDecodeInput\r\n): JwtResult<T> {\r\n const { token, options = {} } = input;\r\n\r\n try {\r\n if (!token || typeof token !== 'string') {\r\n return {\r\n status: 'error',\r\n error: {\r\n code: 'invalid_token',\r\n message: 'Invalid token: Token must be a non-empty string'\r\n }\r\n };\r\n }\r\n\r\n const decoded = jsonwebtoken.decode(token, options);\r\n \r\n if (!decoded) {\r\n return {\r\n status: 'error',\r\n error: {\r\n code: 'decode_failed',\r\n message: 'Failed to decode token: Invalid token format'\r\n }\r\n };\r\n }\r\n\r\n return {\r\n status: 'success',\r\n data: decoded as T\r\n };\r\n } catch (error) {\r\n return {\r\n status: 'error',\r\n error: {\r\n code: 'decode_failed',\r\n message: `Failed to decode token: ${error instanceof Error ? error.message : 'Unknown error'}`,\r\n originalError: error instanceof Error ? error : undefined\r\n }\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Checks if a JWT token is expired without full verification and returns a result object.\r\n * \r\n * @param input - Object containing the token to check\r\n * @returns Result object with status and either boolean result or error\r\n * \r\n * @example\r\n * ```typescript\r\n * const result = jwtIsExpired({ token: 'your-jwt-token' });\r\n * if (result.status === 'success') {\r\n * if (result.data) {\r\n * console.log('Token is expired');\r\n * } else {\r\n * console.log('Token is still valid');\r\n * }\r\n * } else {\r\n * console.log('Error checking expiration:', result.error.code);\r\n * }\r\n * ```\r\n */\r\nexport function jwtIsExpired(input: JwtExpirationInput): JwtResult<boolean> {\r\n const { token } = input;\r\n const decoded = jwtDecode({ token });\r\n \r\n if (decoded.status === 'error') {\r\n return decoded;\r\n }\r\n\r\n if (!decoded.data.exp) {\r\n return {\r\n status: 'error',\r\n error: {\r\n code: 'invalid_payload',\r\n message: 'Token does not contain expiration time (exp claim)'\r\n }\r\n };\r\n }\r\n\r\n const currentTime = Math.floor(Date.now() / 1000);\r\n return {\r\n status: 'success',\r\n data: decoded.data.exp < currentTime\r\n };\r\n}\r\n\r\n/**\r\n * Gets the remaining time until token expiration in seconds and returns a result object.\r\n * \r\n * @param input - Object containing the token to check\r\n * @returns Result object with status and either remaining seconds or error\r\n * \r\n * @example\r\n * ```typescript\r\n * const result = jwtTimeUntilExpiry({ token: 'your-jwt-token' });\r\n * if (result.status === 'success') {\r\n * console.log(`Token expires in ${result.data} seconds`);\r\n * } else {\r\n * console.log('Error checking expiry time:', result.error.code);\r\n * }\r\n * ```\r\n */\r\nexport function jwtTimeUntilExpiry(input: JwtExpirationInput): JwtResult<number> {\r\n const { token } = input;\r\n const decoded = jwtDecode({ token });\r\n \r\n if (decoded.status === 'error') {\r\n return decoded;\r\n }\r\n\r\n if (!decoded.data.exp) {\r\n return {\r\n status: 'error',\r\n error: {\r\n code: 'invalid_payload',\r\n message: 'Token does not contain expiration time (exp claim)'\r\n }\r\n };\r\n }\r\n\r\n const currentTime = Math.floor(Date.now() / 1000);\r\n const timeLeft = decoded.data.exp - currentTime;\r\n \r\n return {\r\n status: 'success',\r\n data: timeLeft > 0 ? timeLeft : 0\r\n };\r\n}\r\n\r\n/**\r\n * Type guard to check if a JWT result is successful\r\n * \r\n * @param result - The JWT result to check\r\n * @returns True if the result is successful\r\n * \r\n * @example\r\n * ```typescript\r\n * const result = await jwtVerify(token, secret);\r\n * if (isJwtSuccess(result)) {\r\n * // TypeScript knows result.data is available here\r\n * console.log('User ID:', result.data.userId);\r\n * }\r\n * ```\r\n */\r\nexport function isJwtSuccess<T>(result: JwtResult<T>): result is JwtSuccessResult<T> {\r\n return result.status === 'success';\r\n}\r\n\r\n/**\r\n * Type guard to check if a JWT result is an error\r\n * \r\n * @param result - The JWT result to check\r\n * @returns True if the result is an error\r\n * \r\n * @example\r\n * ```typescript\r\n * const result = await jwtVerify(token, secret);\r\n * if (isJwtError(result)) {\r\n * // TypeScript knows result.error is available here\r\n * console.log('Error code:', result.error.code);\r\n * }\r\n * ```\r\n */\r\nexport function isJwtError<T>(result: JwtResult<T>): result is JwtErrorResult {\r\n return result.status === 'error';\r\n}\r\n\r\n/**\r\n * Extracts data from a JWT result, throwing an error if the result is not successful\r\n * \r\n * @param result - The JWT result\r\n * @returns The data from the result\r\n * @throws Error if the result is not successful\r\n * \r\n * @example\r\n * ```typescript\r\n * try {\r\n * const result = await jwtVerify(token, secret);\r\n * const payload = unwrapJwtResult(result);\r\n * console.log('User ID:', payload.userId);\r\n * } catch (error) {\r\n * console.log('JWT error:', error.message);\r\n * }\r\n * ```\r\n */\r\nexport function unwrapJwtResult<T>(result: JwtResult<T>): T {\r\n if (result.status === 'success') {\r\n return result.data;\r\n }\r\n throw new Error(`JWT ${result.error.code}: ${result.error.message}`);\r\n}\r\n\r\n/**\r\n * JWT utility namespace providing a convenient API for JWT operations.\r\n * All methods take input as objects and return result objects with status 'success' or 'error'.\r\n * \r\n * @example\r\n * ```typescript\r\n * import { jwt } from 'advanced-js-kit/jwt/jwt';\r\n * \r\n * // Verify a token\r\n * const result = await jwt.verify({\r\n * token: 'your-jwt-token',\r\n * secret: 'your-secret'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('Payload:', result.data);\r\n * } else {\r\n * console.log('Error:', result.error.code, result.error.message);\r\n * }\r\n * \r\n * // Sign a token\r\n * const signResult = await jwt.sign({\r\n * payload: { userId: '123' },\r\n * secret: 'your-secret'\r\n * });\r\n * if (signResult.status === 'success') {\r\n * console.log('Token:', signResult.data);\r\n * }\r\n * \r\n * // Decode a token\r\n * const decodeResult = jwt.decode({\r\n * token: 'your-jwt-token'\r\n * });\r\n * \r\n * // Check expiration\r\n * const expiredResult = jwt.isExpired({\r\n * token: 'your-jwt-token'\r\n * });\r\n * ```\r\n */\r\nexport const jwt = {\r\n /**\r\n * Verifies a JWT token and returns a result object.\r\n * Alias for jwtVerify function.\r\n */\r\n verify: jwtVerify,\r\n \r\n /**\r\n * Signs a payload and creates a JWT token, returns a result object.\r\n * Alias for jwtSign function.\r\n */\r\n sign: jwtSign,\r\n \r\n /**\r\n * Decodes a JWT token without verification, returns a result object.\r\n * Alias for jwtDecode function.\r\n */\r\n decode: jwtDecode,\r\n \r\n /**\r\n * Checks if a JWT token is expired, returns a result object.\r\n * Alias for jwtIsExpired function.\r\n */\r\n isExpired: jwtIsExpired,\r\n \r\n /**\r\n * Gets the remaining time until token expiration, returns a result object.\r\n * Alias for jwtTimeUntilExpiry function.\r\n */\r\n timeUntilExpiry: jwtTimeUntilExpiry\r\n} as const;\r\n"]}