UNPKG

@clerk/shared

Version:

Internal package utils used by the Clerk SDKs

261 lines (257 loc) • 8.51 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/error.ts var error_exports = {}; __export(error_exports, { ClerkAPIResponseError: () => ClerkAPIResponseError, ClerkRuntimeError: () => ClerkRuntimeError, EmailLinkError: () => EmailLinkError, EmailLinkErrorCode: () => EmailLinkErrorCode, MagicLinkError: () => MagicLinkError, MagicLinkErrorCode: () => MagicLinkErrorCode, buildErrorThrower: () => buildErrorThrower, is4xxError: () => is4xxError, isClerkAPIResponseError: () => isClerkAPIResponseError, isClerkRuntimeError: () => isClerkRuntimeError, isEmailLinkError: () => isEmailLinkError, isKnownError: () => isKnownError, isMagicLinkError: () => isMagicLinkError, isMetamaskError: () => isMetamaskError, isNetworkError: () => isNetworkError, isUnauthorizedError: () => isUnauthorizedError, parseError: () => parseError, parseErrors: () => parseErrors }); module.exports = __toCommonJS(error_exports); // src/utils/runtimeEnvironment.ts var isTestEnvironment = () => { try { return process.env.NODE_ENV === "test"; } catch (err) { } return false; }; var isProductionEnvironment = () => { try { return process.env.NODE_ENV === "production"; } catch (err) { } return false; }; // src/deprecated.ts var displayedWarnings = /* @__PURE__ */ new Set(); var deprecated = (fnName, warning, key) => { const hideWarning = isTestEnvironment() || isProductionEnvironment(); const messageId = key ?? fnName; if (displayedWarnings.has(messageId) || hideWarning) { return; } displayedWarnings.add(messageId); console.warn( `Clerk - DEPRECATION WARNING: "${fnName}" is deprecated and will be removed in the next major release. ${warning}` ); }; // src/error.ts function isUnauthorizedError(e) { const status = e?.status; const code = e?.errors?.[0]?.code; return code === "authentication_invalid" && status === 401; } function is4xxError(e) { const status = e?.status; return !!status && status >= 400 && status < 500; } function isNetworkError(e) { const message = (`${e.message}${e.name}` || "").toLowerCase().replace(/\s+/g, ""); return message.includes("networkerror"); } function isKnownError(error) { return isClerkAPIResponseError(error) || isMetamaskError(error) || isClerkRuntimeError(error); } function isClerkAPIResponseError(err) { return "clerkError" in err; } function isClerkRuntimeError(err) { return "clerkRuntimeError" in err; } function isMetamaskError(err) { return "code" in err && [4001, 32602, 32603].includes(err.code) && "message" in err; } function parseErrors(data = []) { return data.length > 0 ? data.map(parseError) : []; } function parseError(error) { return { code: error.code, message: error.message, longMessage: error.long_message, meta: { paramName: error?.meta?.param_name, sessionId: error?.meta?.session_id, emailAddresses: error?.meta?.email_addresses, identifiers: error?.meta?.identifiers, zxcvbn: error?.meta?.zxcvbn } }; } var ClerkAPIResponseError = class _ClerkAPIResponseError extends Error { constructor(message, { data, status }) { super(message); this.toString = () => { return `[${this.name}] Message:${this.message} Status:${this.status} Serialized errors: ${this.errors.map( (e) => JSON.stringify(e) )}`; }; Object.setPrototypeOf(this, _ClerkAPIResponseError.prototype); this.status = status; this.message = message; this.clerkError = true; this.errors = parseErrors(data); } }; var ClerkRuntimeError = class _ClerkRuntimeError extends Error { constructor(message, { code }) { super(message); /** * Returns a string representation of the error. * * @returns {string} A formatted string with the error name and message. * @memberof ClerkRuntimeError */ this.toString = () => { return `[${this.name}] Message:${this.message}`; }; Object.setPrototypeOf(this, _ClerkRuntimeError.prototype); this.code = code; this.message = message; this.clerkRuntimeError = true; } }; var MagicLinkError = class _MagicLinkError extends Error { constructor(code) { super(code); this.code = code; Object.setPrototypeOf(this, _MagicLinkError.prototype); deprecated("MagicLinkError", "Use `EmailLinkError` instead."); } }; var EmailLinkError = class _EmailLinkError extends Error { constructor(code) { super(code); this.code = code; Object.setPrototypeOf(this, _EmailLinkError.prototype); } }; function isMagicLinkError(err) { deprecated("isMagicLinkError", "Use `isEmailLinkError` instead."); return err instanceof MagicLinkError; } function isEmailLinkError(err) { return err instanceof EmailLinkError; } var _MagicLinkErrorCode = { Expired: "expired", Failed: "failed" }; var MagicLinkErrorCode = new Proxy(_MagicLinkErrorCode, { get(target, prop, receiver) { deprecated("MagicLinkErrorCode", "Use `EmailLinkErrorCode` instead."); return Reflect.get(target, prop, receiver); } }); var EmailLinkErrorCode = { Expired: "expired", Failed: "failed" }; var DefaultMessages = Object.freeze({ InvalidFrontendApiErrorMessage: `The frontendApi passed to Clerk is invalid. You can get your Frontend API key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`, InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`, InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`, MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.` }); function buildErrorThrower({ packageName, customMessages }) { let pkg = packageName; const messages = { ...DefaultMessages, ...customMessages }; function buildMessage(rawMessage, replacements) { if (!replacements) { return `${pkg}: ${rawMessage}`; } let msg = rawMessage; const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g); for (const match of matches) { const replacement = (replacements[match[1]] || "").toString(); msg = msg.replace(`{{${match[1]}}}`, replacement); } return `${pkg}: ${msg}`; } return { setPackageName({ packageName: packageName2 }) { if (typeof packageName2 === "string") { pkg = packageName2; } return this; }, setMessages({ customMessages: customMessages2 }) { Object.assign(messages, customMessages2 || {}); return this; }, throwInvalidPublishableKeyError(params) { throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params)); }, throwInvalidFrontendApiError(params) { throw new Error(buildMessage(messages.InvalidFrontendApiErrorMessage, params)); }, throwInvalidProxyUrl(params) { throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params)); }, throwMissingPublishableKeyError() { throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage)); } }; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ClerkAPIResponseError, ClerkRuntimeError, EmailLinkError, EmailLinkErrorCode, MagicLinkError, MagicLinkErrorCode, buildErrorThrower, is4xxError, isClerkAPIResponseError, isClerkRuntimeError, isEmailLinkError, isKnownError, isMagicLinkError, isMetamaskError, isNetworkError, isUnauthorizedError, parseError, parseErrors }); //# sourceMappingURL=error.js.map