@stackframe/stack-shared 2.8.20 → 2.8.21

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new StackAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // simulate an put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class StackAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Stack. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n }\n}\nStackAssertionError.prototype.name = \"StackAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nconst errorSinks = new Set<(location: string, error: unknown, ...extraArgs: unknown[]) => void>();\nexport function registerErrorSink(sink: (location: string, error: unknown) => void): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, ...extraArgs) => {\n console.error(\n `\\x1b[41mCaptured error in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, extraArgs });\n});\n\nexport function captureError(location: string, error: unknown): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n private readonly __stackStatusErrorBrand = \"stack-status-error-brand-sentinel\" as const;\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new StackAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public static isStatusError(error: unknown): error is StatusError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackStatusErrorBrand\" in error && error.__stackStatusErrorBrand === \"stack-status-error-brand-sentinel\";\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA0B;AAE1B,qBAAqB;AACrB,qBAAuB;AAMhB,SAAS,YAAY,MAAoB;AAC9C,MAAI,OAAO,KAAK,CAAC,MAAM,UAAU;AAC/B,UAAM,IAAI,oBAAoB,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAAA,EAChD,WAAW,KAAK,CAAC,aAAa,OAAO;AACnC,UAAM,KAAK,CAAC;AAAA,EACd,OAAO;AAEL,UAAM,IAAI,YAAY,GAAG,IAAI;AAAA,EAC/B;AACF;AAEA,SAAS,yBAAyB,OAAuB;AAEvD,QAAM,eAAe,IAAI,MAAM,EAAE,OAAO,WAAW,SAAS;AAC5D,SAAO,MAAM,MAAM,IAAI,EAAE,MAAM,eAAe,IAAI,CAAC,EAAE,KAAK,IAAI;AAChE;AAwBO,SAAS,kBAAkB,UAAiB,QAAuB;AAExE,QAAM,qBAAqB,MAAM,OAAO,SAAS,IAAI;AAMrD,QAAM,YAAY,yBAAyB,IAAI,MAAM,EAAE,SAAS,EAAE,EAAE,MAAM,IAAI,EAAE,CAAC;AAGjF,aAAW,SAAS,QAAQ;AAC1B,UAAM,WAAW,yBAAyB,MAAM,SAAS,EAAE;AAC3D,UAAM,UAAU,qBAAqB,KAAK,QAAQ,YAAY,OAAO;AAAA,EACvE;AACF;AAGO,IAAM,sBAAN,cAAkC,MA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,YAAY,KAAK,SAAS,wBAAwB;AA9B9E,YA+BG,kBAAkB,EAAE,YAAY,KAAK,SAAS,oBAAoB;AA/BrE,YAgCG,8BAA8B,EAAE,YAAY,KAAK,SAAS,kCAAkC;AAhC/F,YAiCG,6BAA6B,EAAE,YAAY,KAAK,SAAS,gCAAgC;AAjC5F,YAmCG,sBAAsB,EAAE,YAAY,KAAK,SAAS,wBAAwB;AAnC7E,YAoCG,iBAAiB,EAAE,YAAY,KAAK,SAAS,kBAAkB;AApClE,YAqCG,aAAa,EAAE,YAAY,KAAK,SAAS,cAAc;AArC1D,YAsCG,qBAAqB,EAAE,YAAY,KAAK,SAAS,sBAAsB;AAtC1E,YAuCG,iBAAiB,EAAE,YAAY,KAAK,SAAS,kBAAkB;AAvClE,YAwCG,0BAA0B,EAAE,YAAY,KAAK,SAAS,6BAA6B;AAxCtF,YAyCG,wBAAwB,EAAE,YAAY,KAAK,SAAS,0BAA0B;AAzCjF,YA0CG,sBAAsB,EAAE,YAAY,KAAK,SAAS,uBAAuB;AA1C5E,YA2CG,eAAe,EAAE,YAAY,KAAK,SAAS,gBAAgB;AA3C9D,YA4CG,cAAc,EAAE,YAAY,KAAK,SAAS,eAAe;AA5C5D,YA6CG,gCAAgC,EAAE,YAAY,KAAK,SAAS,kCAAkC;AAiE9G,YAAY,UAAU,OAAO;","names":[]}
1
+ {"version":3,"sources":["../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new StackAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // simulate an put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class StackAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Stack. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n\n if (process.env.NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR === \"true\") {\n debugger;\n }\n }\n}\nStackAssertionError.prototype.name = \"StackAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nconst errorSinks = new Set<(location: string, error: unknown, ...extraArgs: unknown[]) => void>();\nexport function registerErrorSink(sink: (location: string, error: unknown) => void): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, ...extraArgs) => {\n console.error(\n `\\x1b[41mCaptured error in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, extraArgs });\n});\n\nexport function captureError(location: string, error: unknown): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n private readonly __stackStatusErrorBrand = \"stack-status-error-brand-sentinel\" as const;\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new StackAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public static isStatusError(error: unknown): error is StatusError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackStatusErrorBrand\" in error && error.__stackStatusErrorBrand === \"stack-status-error-brand-sentinel\";\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA0B;AAE1B,qBAAqB;AACrB,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YAAY,KAAK,SAAS,sBAAsB;AAtC1E,YAuCG,iBAAiB,EAAE,YAAY,KAAK,SAAS,kBAAkB;AAvClE,YAwCG,0BAA0B,EAAE,YAAY,KAAK,SAAS,6BAA6B;AAxCtF,YAyCG,wBAAwB,EAAE,YAAY,KAAK,SAAS,0BAA0B;AAzCjF,YA0CG,sBAAsB,EAAE,YAAY,KAAK,SAAS,uBAAuB;AA1C5E,YA2CG,eAAe,EAAE,YAAY,KAAK,SAAS,gBAAgB;AA3C9D,YA4CG,cAAc,EAAE,YAAY,KAAK,SAAS,eAAe;AA5C5D,YA6CG,gCAAgC,EAAE,YAAY,KAAK,SAAS,kCAAkC;AAiE9G,YAAY,UAAU,OAAO;","names":[]}
@@ -6,8 +6,8 @@ type Json = null | boolean | number | string | Json[] | {
6
6
  type ReadonlyJson = null | boolean | number | string | readonly ReadonlyJson[] | {
7
7
  readonly [key: string]: ReadonlyJson;
8
8
  };
9
- declare function isJson(value: unknown): value is Json;
9
+ declare function isJsonSerializable(value: unknown): value is Json;
10
10
  declare function parseJson(json: string): Result<Json>;
11
11
  declare function stringifyJson(json: Json): Result<string>;
12
12
 
13
- export { type Json, type ReadonlyJson, isJson, parseJson, stringifyJson };
13
+ export { type Json, type ReadonlyJson, isJsonSerializable, parseJson, stringifyJson };
@@ -6,8 +6,8 @@ type Json = null | boolean | number | string | Json[] | {
6
6
  type ReadonlyJson = null | boolean | number | string | readonly ReadonlyJson[] | {
7
7
  readonly [key: string]: ReadonlyJson;
8
8
  };
9
- declare function isJson(value: unknown): value is Json;
9
+ declare function isJsonSerializable(value: unknown): value is Json;
10
10
  declare function parseJson(json: string): Result<Json>;
11
11
  declare function stringifyJson(json: Json): Result<string>;
12
12
 
13
- export { type Json, type ReadonlyJson, isJson, parseJson, stringifyJson };
13
+ export { type Json, type ReadonlyJson, isJsonSerializable, parseJson, stringifyJson };
@@ -20,18 +20,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/utils/json.tsx
21
21
  var json_exports = {};
22
22
  __export(json_exports, {
23
- isJson: () => isJson,
23
+ isJsonSerializable: () => isJsonSerializable,
24
24
  parseJson: () => parseJson,
25
25
  stringifyJson: () => stringifyJson
26
26
  });
27
27
  module.exports = __toCommonJS(json_exports);
28
28
  var import_results = require("./results.js");
29
- function isJson(value) {
29
+ function isJsonSerializable(value) {
30
30
  switch (typeof value) {
31
31
  case "object": {
32
32
  if (value === null) return true;
33
- if (Array.isArray(value)) return value.every(isJson);
34
- return Object.keys(value).every((k) => typeof k === "string") && Object.values(value).every(isJson);
33
+ if (Array.isArray(value)) return value.every(isJsonSerializable);
34
+ return Object.keys(value).every((k) => typeof k === "string") && Object.values(value).every(isJsonSerializable);
35
35
  }
36
36
  case "string":
37
37
  case "number":
@@ -51,7 +51,7 @@ function stringifyJson(json) {
51
51
  }
52
52
  // Annotate the CommonJS export names for ESM import in node:
53
53
  0 && (module.exports = {
54
- isJson,
54
+ isJsonSerializable,
55
55
  parseJson,
56
56
  stringifyJson
57
57
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/json.tsx"],"sourcesContent":["import { Result } from \"./results\";\n\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [key: string]: Json };\n\nexport type ReadonlyJson =\n | null\n | boolean\n | number\n | string\n | readonly ReadonlyJson[]\n | { readonly [key: string]: ReadonlyJson };\n\nexport function isJson(value: unknown): value is Json {\n switch (typeof value) {\n case \"object\": {\n if (value === null) return true;\n if (Array.isArray(value)) return value.every(isJson);\n return Object.keys(value).every(k => typeof k === \"string\") && Object.values(value).every(isJson);\n }\n case \"string\":\n case \"number\":\n case \"boolean\": {\n return true;\n }\n default: {\n return false;\n }\n }\n}\nundefined?.test(\"isJson\", ({ expect }) => {\n // Test primitive values\n expect(isJson(null)).toBe(true);\n expect(isJson(true)).toBe(true);\n expect(isJson(false)).toBe(true);\n expect(isJson(123)).toBe(true);\n expect(isJson(\"string\")).toBe(true);\n\n // Test arrays\n expect(isJson([])).toBe(true);\n expect(isJson([1, 2, 3])).toBe(true);\n expect(isJson([\"a\", \"b\", \"c\"])).toBe(true);\n expect(isJson([1, \"a\", true, null])).toBe(true);\n expect(isJson([1, [2, 3], { a: \"b\" }])).toBe(true);\n\n // Test objects\n expect(isJson({})).toBe(true);\n expect(isJson({ a: 1, b: 2 })).toBe(true);\n expect(isJson({ a: \"string\", b: true, c: null })).toBe(true);\n expect(isJson({ a: [1, 2, 3], b: { c: \"d\" } })).toBe(true);\n\n // Test invalid JSON values\n expect(isJson(undefined)).toBe(false);\n expect(isJson(() => {})).toBe(false);\n expect(isJson(Symbol())).toBe(false);\n expect(isJson(BigInt(123))).toBe(false);\n\n // Test arrays with invalid JSON values\n expect(isJson([1, undefined, 3])).toBe(false);\n expect(isJson([1, () => {}, 3])).toBe(false);\n\n // Test objects with invalid JSON values\n expect(isJson({ a: 1, b: undefined })).toBe(false);\n expect(isJson({ a: 1, b: () => {} })).toBe(false);\n});\n\nexport function parseJson(json: string): Result<Json> {\n return Result.fromThrowing(() => JSON.parse(json));\n}\nundefined?.test(\"parseJson\", ({ expect }) => {\n // Test valid JSON strings\n const nullResult = parseJson(\"null\");\n expect(nullResult.status).toBe(\"ok\");\n if (nullResult.status === \"ok\") {\n expect(nullResult.data).toBe(null);\n }\n\n const trueResult = parseJson(\"true\");\n expect(trueResult.status).toBe(\"ok\");\n if (trueResult.status === \"ok\") {\n expect(trueResult.data).toBe(true);\n }\n\n const numberResult = parseJson(\"123\");\n expect(numberResult.status).toBe(\"ok\");\n if (numberResult.status === \"ok\") {\n expect(numberResult.data).toBe(123);\n }\n\n const stringResult = parseJson('\"string\"');\n expect(stringResult.status).toBe(\"ok\");\n if (stringResult.status === \"ok\") {\n expect(stringResult.data).toBe(\"string\");\n }\n\n const emptyArrayResult = parseJson(\"[]\");\n expect(emptyArrayResult.status).toBe(\"ok\");\n if (emptyArrayResult.status === \"ok\") {\n expect(emptyArrayResult.data).toEqual([]);\n }\n\n const arrayResult = parseJson(\"[1,2,3]\");\n expect(arrayResult.status).toBe(\"ok\");\n if (arrayResult.status === \"ok\") {\n expect(arrayResult.data).toEqual([1, 2, 3]);\n }\n\n const emptyObjectResult = parseJson(\"{}\");\n expect(emptyObjectResult.status).toBe(\"ok\");\n if (emptyObjectResult.status === \"ok\") {\n expect(emptyObjectResult.data).toEqual({});\n }\n\n const objectResult = parseJson('{\"a\":1,\"b\":\"string\"}');\n expect(objectResult.status).toBe(\"ok\");\n if (objectResult.status === \"ok\") {\n expect(objectResult.data).toEqual({ a: 1, b: \"string\" });\n }\n\n // Test invalid JSON strings\n expect(parseJson(\"\").status).toBe(\"error\");\n expect(parseJson(\"undefined\").status).toBe(\"error\");\n expect(parseJson(\"{\").status).toBe(\"error\");\n expect(parseJson('{\"a\":1,}').status).toBe(\"error\");\n expect(parseJson(\"function(){}\").status).toBe(\"error\");\n});\n\nexport function stringifyJson(json: Json): Result<string> {\n return Result.fromThrowing(() => JSON.stringify(json));\n}\nundefined?.test(\"stringifyJson\", ({ expect }) => {\n // Test primitive values\n const nullResult = stringifyJson(null);\n expect(nullResult.status).toBe(\"ok\");\n if (nullResult.status === \"ok\") {\n expect(nullResult.data).toBe(\"null\");\n }\n\n const trueResult = stringifyJson(true);\n expect(trueResult.status).toBe(\"ok\");\n if (trueResult.status === \"ok\") {\n expect(trueResult.data).toBe(\"true\");\n }\n\n const numberResult = stringifyJson(123);\n expect(numberResult.status).toBe(\"ok\");\n if (numberResult.status === \"ok\") {\n expect(numberResult.data).toBe(\"123\");\n }\n\n const stringResult = stringifyJson(\"string\");\n expect(stringResult.status).toBe(\"ok\");\n if (stringResult.status === \"ok\") {\n expect(stringResult.data).toBe('\"string\"');\n }\n\n // Test arrays\n const emptyArrayResult = stringifyJson([]);\n expect(emptyArrayResult.status).toBe(\"ok\");\n if (emptyArrayResult.status === \"ok\") {\n expect(emptyArrayResult.data).toBe(\"[]\");\n }\n\n const arrayResult = stringifyJson([1, 2, 3]);\n expect(arrayResult.status).toBe(\"ok\");\n if (arrayResult.status === \"ok\") {\n expect(arrayResult.data).toBe(\"[1,2,3]\");\n }\n\n // Test objects\n const emptyObjectResult = stringifyJson({});\n expect(emptyObjectResult.status).toBe(\"ok\");\n if (emptyObjectResult.status === \"ok\") {\n expect(emptyObjectResult.data).toBe(\"{}\");\n }\n\n const objectResult = stringifyJson({ a: 1, b: \"string\" });\n expect(objectResult.status).toBe(\"ok\");\n if (objectResult.status === \"ok\") {\n expect(objectResult.data).toBe('{\"a\":1,\"b\":\"string\"}');\n }\n\n // Test nested structures\n const nested = { a: [1, 2, 3], b: { c: \"d\" } };\n const nestedResult = stringifyJson(nested);\n expect(nestedResult.status).toBe(\"ok\");\n if (nestedResult.status === \"ok\") {\n expect(nestedResult.data).toBe('{\"a\":[1,2,3],\"b\":{\"c\":\"d\"}}');\n }\n\n // Test circular references (should error)\n const circular: any = { a: 1 };\n circular.self = circular;\n expect(stringifyJson(circular).status).toBe(\"error\");\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAuB;AAkBhB,SAAS,OAAO,OAA+B;AACpD,UAAQ,OAAO,OAAO;AAAA,IACpB,KAAK,UAAU;AACb,UAAI,UAAU,KAAM,QAAO;AAC3B,UAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,MAAM,MAAM;AACnD,aAAO,OAAO,KAAK,KAAK,EAAE,MAAM,OAAK,OAAO,MAAM,QAAQ,KAAK,OAAO,OAAO,KAAK,EAAE,MAAM,MAAM;AAAA,IAClG;AAAA,IACA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,WAAW;AACd,aAAO;AAAA,IACT;AAAA,IACA,SAAS;AACP,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAqCO,SAAS,UAAU,MAA4B;AACpD,SAAO,sBAAO,aAAa,MAAM,KAAK,MAAM,IAAI,CAAC;AACnD;AA2DO,SAAS,cAAc,MAA4B;AACxD,SAAO,sBAAO,aAAa,MAAM,KAAK,UAAU,IAAI,CAAC;AACvD;","names":[]}
1
+ {"version":3,"sources":["../../src/utils/json.tsx"],"sourcesContent":["import { Result } from \"./results\";\n\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [key: string]: Json };\n\nexport type ReadonlyJson =\n | null\n | boolean\n | number\n | string\n | readonly ReadonlyJson[]\n | { readonly [key: string]: ReadonlyJson };\n\nexport function isJsonSerializable(value: unknown): value is Json {\n switch (typeof value) {\n case \"object\": {\n if (value === null) return true;\n if (Array.isArray(value)) return value.every(isJsonSerializable);\n return Object.keys(value).every(k => typeof k === \"string\") && Object.values(value).every(isJsonSerializable);\n }\n case \"string\":\n case \"number\":\n case \"boolean\": {\n return true;\n }\n default: {\n return false;\n }\n }\n}\nundefined?.test(\"isJsonSerializable\", ({ expect }) => {\n // Test primitive values\n expect(isJsonSerializable(null)).toBe(true);\n expect(isJsonSerializable(true)).toBe(true);\n expect(isJsonSerializable(false)).toBe(true);\n expect(isJsonSerializable(123)).toBe(true);\n expect(isJsonSerializable(\"string\")).toBe(true);\n\n // Test arrays\n expect(isJsonSerializable([])).toBe(true);\n expect(isJsonSerializable([1, 2, 3])).toBe(true);\n expect(isJsonSerializable([\"a\", \"b\", \"c\"])).toBe(true);\n expect(isJsonSerializable([1, \"a\", true, null])).toBe(true);\n expect(isJsonSerializable([1, [2, 3], { a: \"b\" }])).toBe(true);\n\n // Test objects\n expect(isJsonSerializable({})).toBe(true);\n expect(isJsonSerializable({ a: 1, b: 2 })).toBe(true);\n expect(isJsonSerializable({ a: \"string\", b: true, c: null })).toBe(true);\n expect(isJsonSerializable({ a: [1, 2, 3], b: { c: \"d\" } })).toBe(true);\n\n // Test invalid JSON values\n expect(isJsonSerializable(undefined)).toBe(false);\n expect(isJsonSerializable(() => {})).toBe(false);\n expect(isJsonSerializable(Symbol())).toBe(false);\n expect(isJsonSerializable(BigInt(123))).toBe(false);\n\n // Test arrays with invalid JSON values\n expect(isJsonSerializable([1, undefined, 3])).toBe(false);\n expect(isJsonSerializable([1, () => {}, 3])).toBe(false);\n\n // Test objects with invalid JSON values\n expect(isJsonSerializable({ a: 1, b: undefined })).toBe(false);\n expect(isJsonSerializable({ a: 1, b: () => {} })).toBe(false);\n});\n\nexport function parseJson(json: string): Result<Json> {\n return Result.fromThrowing(() => JSON.parse(json));\n}\nundefined?.test(\"parseJson\", ({ expect }) => {\n // Test valid JSON strings\n const nullResult = parseJson(\"null\");\n expect(nullResult.status).toBe(\"ok\");\n if (nullResult.status === \"ok\") {\n expect(nullResult.data).toBe(null);\n }\n\n const trueResult = parseJson(\"true\");\n expect(trueResult.status).toBe(\"ok\");\n if (trueResult.status === \"ok\") {\n expect(trueResult.data).toBe(true);\n }\n\n const numberResult = parseJson(\"123\");\n expect(numberResult.status).toBe(\"ok\");\n if (numberResult.status === \"ok\") {\n expect(numberResult.data).toBe(123);\n }\n\n const stringResult = parseJson('\"string\"');\n expect(stringResult.status).toBe(\"ok\");\n if (stringResult.status === \"ok\") {\n expect(stringResult.data).toBe(\"string\");\n }\n\n const emptyArrayResult = parseJson(\"[]\");\n expect(emptyArrayResult.status).toBe(\"ok\");\n if (emptyArrayResult.status === \"ok\") {\n expect(emptyArrayResult.data).toEqual([]);\n }\n\n const arrayResult = parseJson(\"[1,2,3]\");\n expect(arrayResult.status).toBe(\"ok\");\n if (arrayResult.status === \"ok\") {\n expect(arrayResult.data).toEqual([1, 2, 3]);\n }\n\n const emptyObjectResult = parseJson(\"{}\");\n expect(emptyObjectResult.status).toBe(\"ok\");\n if (emptyObjectResult.status === \"ok\") {\n expect(emptyObjectResult.data).toEqual({});\n }\n\n const objectResult = parseJson('{\"a\":1,\"b\":\"string\"}');\n expect(objectResult.status).toBe(\"ok\");\n if (objectResult.status === \"ok\") {\n expect(objectResult.data).toEqual({ a: 1, b: \"string\" });\n }\n\n // Test invalid JSON strings\n expect(parseJson(\"\").status).toBe(\"error\");\n expect(parseJson(\"undefined\").status).toBe(\"error\");\n expect(parseJson(\"{\").status).toBe(\"error\");\n expect(parseJson('{\"a\":1,}').status).toBe(\"error\");\n expect(parseJson(\"function(){}\").status).toBe(\"error\");\n});\n\nexport function stringifyJson(json: Json): Result<string> {\n return Result.fromThrowing(() => JSON.stringify(json));\n}\nundefined?.test(\"stringifyJson\", ({ expect }) => {\n // Test primitive values\n const nullResult = stringifyJson(null);\n expect(nullResult.status).toBe(\"ok\");\n if (nullResult.status === \"ok\") {\n expect(nullResult.data).toBe(\"null\");\n }\n\n const trueResult = stringifyJson(true);\n expect(trueResult.status).toBe(\"ok\");\n if (trueResult.status === \"ok\") {\n expect(trueResult.data).toBe(\"true\");\n }\n\n const numberResult = stringifyJson(123);\n expect(numberResult.status).toBe(\"ok\");\n if (numberResult.status === \"ok\") {\n expect(numberResult.data).toBe(\"123\");\n }\n\n const stringResult = stringifyJson(\"string\");\n expect(stringResult.status).toBe(\"ok\");\n if (stringResult.status === \"ok\") {\n expect(stringResult.data).toBe('\"string\"');\n }\n\n // Test arrays\n const emptyArrayResult = stringifyJson([]);\n expect(emptyArrayResult.status).toBe(\"ok\");\n if (emptyArrayResult.status === \"ok\") {\n expect(emptyArrayResult.data).toBe(\"[]\");\n }\n\n const arrayResult = stringifyJson([1, 2, 3]);\n expect(arrayResult.status).toBe(\"ok\");\n if (arrayResult.status === \"ok\") {\n expect(arrayResult.data).toBe(\"[1,2,3]\");\n }\n\n // Test objects\n const emptyObjectResult = stringifyJson({});\n expect(emptyObjectResult.status).toBe(\"ok\");\n if (emptyObjectResult.status === \"ok\") {\n expect(emptyObjectResult.data).toBe(\"{}\");\n }\n\n const objectResult = stringifyJson({ a: 1, b: \"string\" });\n expect(objectResult.status).toBe(\"ok\");\n if (objectResult.status === \"ok\") {\n expect(objectResult.data).toBe('{\"a\":1,\"b\":\"string\"}');\n }\n\n // Test nested structures\n const nested = { a: [1, 2, 3], b: { c: \"d\" } };\n const nestedResult = stringifyJson(nested);\n expect(nestedResult.status).toBe(\"ok\");\n if (nestedResult.status === \"ok\") {\n expect(nestedResult.data).toBe('{\"a\":[1,2,3],\"b\":{\"c\":\"d\"}}');\n }\n\n // Test circular references (should error)\n const circular: any = { a: 1 };\n circular.self = circular;\n expect(stringifyJson(circular).status).toBe(\"error\");\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAuB;AAkBhB,SAAS,mBAAmB,OAA+B;AAChE,UAAQ,OAAO,OAAO;AAAA,IACpB,KAAK,UAAU;AACb,UAAI,UAAU,KAAM,QAAO;AAC3B,UAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,MAAM,kBAAkB;AAC/D,aAAO,OAAO,KAAK,KAAK,EAAE,MAAM,OAAK,OAAO,MAAM,QAAQ,KAAK,OAAO,OAAO,KAAK,EAAE,MAAM,kBAAkB;AAAA,IAC9G;AAAA,IACA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,WAAW;AACd,aAAO;AAAA,IACT;AAAA,IACA,SAAS;AACP,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAqCO,SAAS,UAAU,MAA4B;AACpD,SAAO,sBAAO,aAAa,MAAM,KAAK,MAAM,IAAI,CAAC;AACnD;AA2DO,SAAS,cAAc,MAA4B;AACxD,SAAO,sBAAO,aAAa,MAAM,KAAK,UAAU,IAAI,CAAC;AACvD;","names":[]}
@@ -1,5 +1,10 @@
1
- import React, { MutableRefObject } from 'react';
1
+ import React from 'react';
2
2
 
3
+ declare function componentWrapper<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements, ExtraProps extends {} = {}>(displayName: string, render: React.ForwardRefRenderFunction<RefFromComponent<C>, React.ComponentPropsWithRef<C> & ExtraProps>): React.FC<React.ComponentPropsWithRef<C> & ExtraProps & {
4
+ ref?: React.Ref<RefFromComponent<C>> | undefined;
5
+ }>;
6
+ type RefFromComponent<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements> = NonNullable<RefFromComponentDistCond<React.ComponentPropsWithRef<C>["ref"]>>;
7
+ type RefFromComponentDistCond<A> = A extends React.RefObject<infer T> ? T : never;
3
8
  declare function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & {
4
9
  ref?: React.Ref<T>;
5
10
  }>;
@@ -10,11 +15,14 @@ declare function getNodeText(node: React.ReactNode): string;
10
15
  * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`
11
16
  */
12
17
  declare function suspend(): never;
13
- type InstantStateRef<T> = Readonly<MutableRefObject<T>>;
18
+ declare function mapRef<T, R>(ref: ReadonlyRef<T>, mapper: (value: T) => R): ReadonlyRef<R>;
19
+ type ReadonlyRef<T> = {
20
+ readonly current: T;
21
+ };
14
22
  /**
15
23
  * Like useState, but its value is immediately available.
16
24
  */
17
- declare function useInstantState<T>(initialValue: T): [InstantStateRef<T>, (value: T) => void];
25
+ declare function useInstantState<T>(initialValue: T): [ReadonlyRef<T>, (value: T) => void];
18
26
  declare class NoSuspenseBoundaryError extends Error {
19
27
  digest: string;
20
28
  reason: string;
@@ -27,4 +35,4 @@ declare class NoSuspenseBoundaryError extends Error {
27
35
  */
28
36
  declare function suspendIfSsr(caller?: string): void;
29
37
 
30
- export { type InstantStateRef, NoSuspenseBoundaryError, forwardRefIfNeeded, getNodeText, suspend, suspendIfSsr, useInstantState };
38
+ export { NoSuspenseBoundaryError, type ReadonlyRef, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, suspend, suspendIfSsr, useInstantState };
@@ -1,5 +1,10 @@
1
- import React, { MutableRefObject } from 'react';
1
+ import React from 'react';
2
2
 
3
+ declare function componentWrapper<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements, ExtraProps extends {} = {}>(displayName: string, render: React.ForwardRefRenderFunction<RefFromComponent<C>, React.ComponentPropsWithRef<C> & ExtraProps>): React.FC<React.ComponentPropsWithRef<C> & ExtraProps & {
4
+ ref?: React.Ref<RefFromComponent<C>> | undefined;
5
+ }>;
6
+ type RefFromComponent<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements> = NonNullable<RefFromComponentDistCond<React.ComponentPropsWithRef<C>["ref"]>>;
7
+ type RefFromComponentDistCond<A> = A extends React.RefObject<infer T> ? T : never;
3
8
  declare function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & {
4
9
  ref?: React.Ref<T>;
5
10
  }>;
@@ -10,11 +15,14 @@ declare function getNodeText(node: React.ReactNode): string;
10
15
  * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`
11
16
  */
12
17
  declare function suspend(): never;
13
- type InstantStateRef<T> = Readonly<MutableRefObject<T>>;
18
+ declare function mapRef<T, R>(ref: ReadonlyRef<T>, mapper: (value: T) => R): ReadonlyRef<R>;
19
+ type ReadonlyRef<T> = {
20
+ readonly current: T;
21
+ };
14
22
  /**
15
23
  * Like useState, but its value is immediately available.
16
24
  */
17
- declare function useInstantState<T>(initialValue: T): [InstantStateRef<T>, (value: T) => void];
25
+ declare function useInstantState<T>(initialValue: T): [ReadonlyRef<T>, (value: T) => void];
18
26
  declare class NoSuspenseBoundaryError extends Error {
19
27
  digest: string;
20
28
  reason: string;
@@ -27,4 +35,4 @@ declare class NoSuspenseBoundaryError extends Error {
27
35
  */
28
36
  declare function suspendIfSsr(caller?: string): void;
29
37
 
30
- export { type InstantStateRef, NoSuspenseBoundaryError, forwardRefIfNeeded, getNodeText, suspend, suspendIfSsr, useInstantState };
38
+ export { NoSuspenseBoundaryError, type ReadonlyRef, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, suspend, suspendIfSsr, useInstantState };
@@ -31,8 +31,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var react_exports = {};
32
32
  __export(react_exports, {
33
33
  NoSuspenseBoundaryError: () => NoSuspenseBoundaryError,
34
+ componentWrapper: () => componentWrapper,
34
35
  forwardRefIfNeeded: () => forwardRefIfNeeded,
35
36
  getNodeText: () => getNodeText,
37
+ mapRef: () => mapRef,
36
38
  suspend: () => suspend,
37
39
  suspendIfSsr: () => suspendIfSsr,
38
40
  useInstantState: () => useInstantState
@@ -42,6 +44,11 @@ var import_react = __toESM(require("react"));
42
44
  var import_env = require("./env.js");
43
45
  var import_promises = require("./promises.js");
44
46
  var import_strings = require("./strings.js");
47
+ function componentWrapper(displayName, render) {
48
+ const Component = forwardRefIfNeeded(render);
49
+ Component.displayName = displayName;
50
+ return Component;
51
+ }
45
52
  function forwardRefIfNeeded(render) {
46
53
  const version = import_react.default.version;
47
54
  const major = parseInt(version.split(".")[0]);
@@ -70,6 +77,18 @@ function suspend() {
70
77
  import_react.default.use((0, import_promises.neverResolve)());
71
78
  throw new Error("Somehow a Promise that never resolves was resolved?");
72
79
  }
80
+ function mapRef(ref, mapper) {
81
+ let last = null;
82
+ return {
83
+ get current() {
84
+ const input = ref.current;
85
+ if (last === null || input !== last[0]) {
86
+ last = [input, mapper(input)];
87
+ }
88
+ return last[1];
89
+ }
90
+ };
91
+ }
73
92
  function useInstantState(initialValue) {
74
93
  const [, setState] = import_react.default.useState(initialValue);
75
94
  const ref = import_react.default.useRef(initialValue);
@@ -119,8 +138,10 @@ function suspendIfSsr(caller) {
119
138
  // Annotate the CommonJS export names for ESM import in node:
120
139
  0 && (module.exports = {
121
140
  NoSuspenseBoundaryError,
141
+ componentWrapper,
122
142
  forwardRefIfNeeded,
123
143
  getNodeText,
144
+ mapRef,
124
145
  suspend,
125
146
  suspendIfSsr,
126
147
  useInstantState
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React, { MutableRefObject } from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve } from \"./promises\";\nimport { deindent } from \"./strings\";\n\nexport function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & { ref?: React.Ref<T> }> {\n // TODO: when we drop support for react 18, remove this\n\n const version = React.version;\n const major = parseInt(version.split(\".\")[0]);\n if (major < 19) {\n return React.forwardRef<T, P>(render as any) as any;\n } else {\n return ((props: P) => render(props, (props as any).ref)) as any;\n }\n}\nundefined?.test(\"forwardRefIfNeeded\", ({ expect }) => {\n // Mock React.version and React.forwardRef\n const originalVersion = React.version;\n const originalForwardRef = React.forwardRef;\n\n try {\n // Test with React version < 19\n Object.defineProperty(React, 'version', { value: '18.2.0', writable: true });\n\n // Create a render function\n const renderFn = (props: any, ref: any) => null;\n\n // Call forwardRefIfNeeded\n const result = forwardRefIfNeeded(renderFn);\n\n // Verify the function returns something\n expect(result).toBeDefined();\n\n // Test with React version >= 19\n Object.defineProperty(React, 'version', { value: '19.0.0', writable: true });\n\n // Call forwardRefIfNeeded again with React 19\n const result19 = forwardRefIfNeeded(renderFn);\n\n // Verify the function returns something\n expect(result19).toBeDefined();\n } finally {\n // Restore original values\n Object.defineProperty(React, 'version', { value: originalVersion });\n React.forwardRef = originalForwardRef;\n }\n});\n\nexport function getNodeText(node: React.ReactNode): string {\n if ([\"number\", \"string\"].includes(typeof node)) {\n return `${node}`;\n }\n if (!node) {\n return \"\";\n }\n if (Array.isArray(node)) {\n return node.map(getNodeText).join(\"\");\n }\n if (typeof node === \"object\" && \"props\" in node) {\n return getNodeText(node.props.children);\n }\n throw new Error(`Unknown node type: ${typeof node}`);\n}\nundefined?.test(\"getNodeText\", ({ expect }) => {\n // Test with string\n expect(getNodeText(\"hello\")).toBe(\"hello\");\n\n // Test with number\n expect(getNodeText(42)).toBe(\"42\");\n\n // Test with null/undefined\n expect(getNodeText(null)).toBe(\"\");\n expect(getNodeText(undefined)).toBe(\"\");\n\n // Test with array\n expect(getNodeText([\"hello\", \" \", \"world\"])).toBe(\"hello world\");\n expect(getNodeText([1, 2, 3])).toBe(\"123\");\n\n // Test with mixed array\n expect(getNodeText([\"hello\", 42, null])).toBe(\"hello42\");\n\n // Test with React element (mocked)\n const mockElement = {\n props: {\n children: \"child text\"\n }\n } as React.ReactElement;\n expect(getNodeText(mockElement)).toBe(\"child text\");\n\n // Test with nested React elements\n const nestedElement = {\n props: {\n children: {\n props: {\n children: \"nested text\"\n }\n } as React.ReactElement\n }\n } as React.ReactElement;\n expect(getNodeText(nestedElement)).toBe(\"nested text\");\n\n // Test with array of React elements\n const arrayOfElements = [\n { props: { children: \"first\" } } as React.ReactElement,\n { props: { children: \"second\" } } as React.ReactElement\n ];\n expect(getNodeText(arrayOfElements)).toBe(\"firstsecond\");\n});\n\n/**\n * Suspends the currently rendered component indefinitely. Will not unsuspend unless the component rerenders.\n *\n * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`\n */\nexport function suspend(): never {\n React.use(neverResolve());\n throw new Error(\"Somehow a Promise that never resolves was resolved?\");\n}\n\nexport type InstantStateRef<T> = Readonly<MutableRefObject<T>>;\n\n/**\n * Like useState, but its value is immediately available.\n */\nexport function useInstantState<T>(initialValue: T): [InstantStateRef<T>, (value: T) => void] {\n const [, setState] = React.useState(initialValue);\n const ref = React.useRef(initialValue);\n const setValue = React.useCallback((value: T) => {\n setState(value);\n ref.current = value;\n }, []);\n return [ref, setValue];\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n\n constructor(options: { caller?: string }) {\n super(deindent`\n ${options.caller ?? \"This code path\"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.\n \n The fix depends on which of the 3 scenarios caused it:\n \n 1. You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.\n\n 2. The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:\n\n - app\n - - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? \"this code path\"}\n - - loading.tsx // required for suspense\n - - (main)\n - - - layout.tsx // contains the main layout of your app, like a sidebar or a header, and can use ${options.caller ?? \"this code path\"}\n - - - route.tsx // your actual main page\n - - - the rest of your app\n\n For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups\n \n 3. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.\n\n See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n\n More information on SSR and Suspense boundaries: https://react.dev/reference/react/Suspense#providing-a-fallback-for-server-errors-and-client-only-content\n `);\n\n this.name = \"NoSuspenseBoundaryError\";\n this.reason = options.caller ?? \"suspendIfSsr()\";\n\n // set the digest so nextjs doesn't log the error\n // https://github.com/vercel/next.js/blob/d01d6d9c35a8c2725b3d74c1402ab76d4779a6cf/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts#L14\n this.digest = \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n }\n}\nundefined?.test(\"NoSuspenseBoundaryError\", ({ expect }) => {\n // Test with default options\n const defaultError = new NoSuspenseBoundaryError({});\n expect(defaultError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(defaultError.reason).toBe(\"suspendIfSsr()\");\n expect(defaultError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(defaultError.message).toContain(\"This code path attempted to display a loading indicator\");\n\n // Test with custom caller\n const customError = new NoSuspenseBoundaryError({ caller: \"CustomComponent\" });\n expect(customError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(customError.reason).toBe(\"CustomComponent\");\n expect(customError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(customError.message).toContain(\"CustomComponent attempted to display a loading indicator\");\n\n // Verify error message contains all the necessary information\n expect(customError.message).toContain(\"loading.tsx\");\n expect(customError.message).toContain(\"route groups\");\n expect(customError.message).toContain(\"https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\");\n});\n\n\n/**\n * Use this in a component or a hook to disable SSR. Should be wrapped in a Suspense boundary, or it will throw an error.\n */\nexport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QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,CAAC;AACL,SAAO,CAAC,KAAK,QAAQ;AACvB;AAEO,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAIjD,YAAY,SAA8B;AACxC,UAAM;AAAA,QACF,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kHASwE,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA,6GAGvC,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAW1I;AAED,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ,UAAU;AAIhC,SAAK,SAAS;AAAA,EAChB;AACF;AA0BO,SAAS,aAAa,QAAiB;AAC5C,MAAI,KAAC,0BAAc,GAAG;AACpB,UAAM,IAAI,wBAAwB,EAAE,OAAO,CAAC;AAAA,EAC9C;AACF;","names":["React"]}
1
+ {"version":3,"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve } from \"./promises\";\nimport { deindent } from \"./strings\";\n\nexport function componentWrapper<\n C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements,\n ExtraProps extends {} = {}\n>(displayName: string, render: React.ForwardRefRenderFunction<RefFromComponent<C>, React.ComponentPropsWithRef<C> & ExtraProps>) {\n const Component = forwardRefIfNeeded(render);\n Component.displayName = displayName;\n return Component;\n}\ntype RefFromComponent<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements> = NonNullable<RefFromComponentDistCond<React.ComponentPropsWithRef<C>[\"ref\"]>>;\ntype RefFromComponentDistCond<A> = A extends React.RefObject<infer T> ? T : never; // distributive conditional type; see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n\nexport function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & { ref?: React.Ref<T> }> {\n // TODO: when we drop support for react 18, remove this\n\n const version = React.version;\n const major = parseInt(version.split(\".\")[0]);\n if (major < 19) {\n return React.forwardRef<T, P>(render as any) as any;\n } else {\n return ((props: P) => render(props, (props as any).ref)) as any;\n }\n}\n\nexport function getNodeText(node: React.ReactNode): string {\n if ([\"number\", \"string\"].includes(typeof node)) {\n return `${node}`;\n }\n if (!node) {\n return \"\";\n }\n if (Array.isArray(node)) {\n return node.map(getNodeText).join(\"\");\n }\n if (typeof node === \"object\" && \"props\" in node) {\n return getNodeText(node.props.children);\n }\n throw new Error(`Unknown node type: ${typeof node}`);\n}\nundefined?.test(\"getNodeText\", ({ expect }) => {\n // Test with string\n expect(getNodeText(\"hello\")).toBe(\"hello\");\n\n // Test with number\n expect(getNodeText(42)).toBe(\"42\");\n\n // Test with null/undefined\n expect(getNodeText(null)).toBe(\"\");\n expect(getNodeText(undefined)).toBe(\"\");\n\n // Test with array\n expect(getNodeText([\"hello\", \" \", \"world\"])).toBe(\"hello world\");\n expect(getNodeText([1, 2, 3])).toBe(\"123\");\n\n // Test with mixed array\n expect(getNodeText([\"hello\", 42, null])).toBe(\"hello42\");\n\n // Test with React element (mocked)\n const mockElement = {\n props: {\n children: \"child text\"\n }\n } as React.ReactElement;\n expect(getNodeText(mockElement)).toBe(\"child text\");\n\n // Test with nested React elements\n const nestedElement = {\n props: {\n children: {\n props: {\n children: \"nested text\"\n }\n } as React.ReactElement\n }\n } as React.ReactElement;\n expect(getNodeText(nestedElement)).toBe(\"nested text\");\n\n // Test with array of React elements\n const arrayOfElements = [\n { props: { children: \"first\" } } as React.ReactElement,\n { props: { children: \"second\" } } as React.ReactElement\n ];\n expect(getNodeText(arrayOfElements)).toBe(\"firstsecond\");\n});\n\n/**\n * Suspends the currently rendered component indefinitely. Will not unsuspend unless the component rerenders.\n *\n * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`\n */\nexport function suspend(): never {\n React.use(neverResolve());\n throw new Error(\"Somehow a Promise that never resolves was resolved?\");\n}\n\nexport function mapRef<T, R>(ref: ReadonlyRef<T>, mapper: (value: T) => R): ReadonlyRef<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = ref.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n };\n}\n\nexport type ReadonlyRef<T> = {\n readonly current: T,\n};\n\n/**\n * Like useState, but its value is immediately available.\n */\nexport function useInstantState<T>(initialValue: T): [ReadonlyRef<T>, (value: T) => void] {\n const [, setState] = React.useState(initialValue);\n const ref = React.useRef(initialValue);\n const setValue = React.useCallback((value: T) => {\n setState(value);\n ref.current = value;\n }, []);\n return [ref, setValue];\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n\n constructor(options: { caller?: string }) {\n super(deindent`\n ${options.caller ?? \"This code path\"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.\n \n The fix depends on which of the 3 scenarios caused it:\n \n 1. You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.\n\n 2. The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:\n\n - app\n - - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? \"this code path\"}\n - - loading.tsx // required for suspense\n - - (main)\n - - - layout.tsx // contains the main layout of your app, like a sidebar or a header, and can use ${options.caller ?? \"this code path\"}\n - - - route.tsx // your actual main page\n - - - the rest of your app\n\n For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups\n \n 3. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.\n\n See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n\n More information on SSR and Suspense boundaries: https://react.dev/reference/react/Suspense#providing-a-fallback-for-server-errors-and-client-only-content\n `);\n\n this.name = \"NoSuspenseBoundaryError\";\n this.reason = options.caller ?? \"suspendIfSsr()\";\n\n // set the digest so nextjs doesn't log the error\n // https://github.com/vercel/next.js/blob/d01d6d9c35a8c2725b3d74c1402ab76d4779a6cf/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts#L14\n this.digest = \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n }\n}\nundefined?.test(\"NoSuspenseBoundaryError\", ({ expect }) => {\n // Test with default options\n const defaultError = new NoSuspenseBoundaryError({});\n expect(defaultError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(defaultError.reason).toBe(\"suspendIfSsr()\");\n expect(defaultError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(defaultError.message).toContain(\"This code path attempted to display a loading indicator\");\n\n // Test with custom caller\n const customError = new NoSuspenseBoundaryError({ caller: \"CustomComponent\" });\n expect(customError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(customError.reason).toBe(\"CustomComponent\");\n expect(customError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(customError.message).toContain(\"CustomComponent attempted to display a loading indicator\");\n\n // Verify error message contains all the necessary information\n expect(customError.message).toContain(\"loading.tsx\");\n expect(customError.message).toContain(\"route groups\");\n expect(customError.message).toContain(\"https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\");\n});\n\n\n/**\n * Use this in a component or a hook to disable SSR. Should be wrapped in a Suspense boundary, or it will throw an error.\n */\nexport function suspendIfSsr(caller?: string) {\n if (!isBrowserLike()) {\n throw new NoSuspenseBoundaryError({ caller });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,iBAA8B;AAC9B,sBAA6B;AAC7B,qBAAyB;AAElB,SAAS,iBAGd,aAAqB,QAA0G;AAC/H,QAAM,YAAY,mBAAmB,MAAM;AAC3C,YAAU,cAAc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AAY,CAAC,UAAa;AAC/C,aAAS,KAAK;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,CAAC;AACL,SAAO,CAAC,KAAK,QAAQ;AACvB;AAEO,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAIjD,YAAY,SAA8B;AACxC,UAAM;AAAA,QACF,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kHASwE,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA,6GAGvC,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAW1I;AAED,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ,UAAU;AAIhC,SAAK,SAAS;AAAA,EAChB;AACF;AA0BO,SAAS,aAAa,QAAiB;AAC5C,MAAI,KAAC,0BAAc,GAAG;AACpB,UAAM,IAAI,wBAAwB,EAAE,OAAO,CAAC;AAAA,EAC9C;AACF;","names":["React"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackframe/stack-shared",
3
- "version": "2.8.20",
3
+ "version": "2.8.21",
4
4
  "files": [
5
5
  "README.md",
6
6
  "dist",