@hexclave/shared 1.0.0 → 1.0.2
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.
- package/dist/ai/llms/llms.d.ts +17 -0
- package/dist/ai/llms/llms.d.ts.map +1 -0
- package/dist/ai/llms/llms.js +36 -0
- package/dist/ai/llms/llms.js.map +1 -0
- package/dist/ai/unified-prompts/reminders.js +2 -2
- package/dist/ai/unified-prompts/reminders.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js +3 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts +7 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.js +6 -5
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts +172 -0
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts.map +1 -0
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js +280 -0
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js.map +1 -0
- package/dist/ai/unified-prompts/skill-site-prompt.d.ts +2 -1
- package/dist/ai/unified-prompts/skill-site-prompt.d.ts.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt.js +36 -32
- package/dist/ai/unified-prompts/skill-site-prompt.js.map +1 -1
- package/dist/config/schema-fuzzer.test.js +1 -0
- package/dist/config/schema-fuzzer.test.js.map +1 -1
- package/dist/config/schema.d.ts +201 -197
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +6 -0
- package/dist/config/schema.js.map +1 -1
- package/dist/config-authoring.d.ts +5 -1
- package/dist/config-authoring.d.ts.map +1 -1
- package/dist/config-authoring.js +5 -0
- package/dist/config-authoring.js.map +1 -1
- package/dist/config-rendering.d.ts +6 -6
- package/dist/config-rendering.d.ts.map +1 -1
- package/dist/config-rendering.js +25 -17
- package/dist/config-rendering.js.map +1 -1
- package/dist/esm/ai/llms/llms.d.ts +17 -0
- package/dist/esm/ai/llms/llms.d.ts.map +1 -0
- package/dist/esm/ai/llms/llms.js +30 -0
- package/dist/esm/ai/llms/llms.js.map +1 -0
- package/dist/esm/ai/unified-prompts/reminders.js +2 -2
- package/dist/esm/ai/unified-prompts/reminders.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js +3 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts +7 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.js +4 -4
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts +173 -0
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts.map +1 -0
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js +279 -0
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js.map +1 -0
- package/dist/esm/ai/unified-prompts/skill-site-prompt.d.ts +2 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt.d.ts.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt.js +36 -33
- package/dist/esm/ai/unified-prompts/skill-site-prompt.js.map +1 -1
- package/dist/esm/config/schema-fuzzer.test.js +1 -0
- package/dist/esm/config/schema-fuzzer.test.js.map +1 -1
- package/dist/esm/config/schema.d.ts +201 -197
- package/dist/esm/config/schema.d.ts.map +1 -1
- package/dist/esm/config/schema.js +6 -0
- package/dist/esm/config/schema.js.map +1 -1
- package/dist/esm/config-authoring.d.ts +5 -1
- package/dist/esm/config-authoring.d.ts.map +1 -1
- package/dist/esm/config-authoring.js +5 -1
- package/dist/esm/config-authoring.js.map +1 -1
- package/dist/esm/config-rendering.d.ts +6 -6
- package/dist/esm/config-rendering.d.ts.map +1 -1
- package/dist/esm/config-rendering.js +25 -17
- package/dist/esm/config-rendering.js.map +1 -1
- package/dist/esm/hooks/use-hover.d.ts +1 -1
- package/dist/esm/hooks/use-hover.d.ts.map +1 -1
- package/dist/esm/hooks/use-hover.js.map +1 -1
- package/dist/esm/interface/admin-interface.js +1 -1
- package/dist/esm/interface/admin-metrics.d.ts +8 -8
- package/dist/esm/interface/client-interface.js +1 -1
- package/dist/esm/interface/conversations.d.ts +32 -32
- package/dist/esm/interface/crud/current-user.d.ts +8 -8
- package/dist/esm/interface/crud/email-outbox.d.ts +218 -218
- package/dist/esm/interface/crud/products.d.ts +20 -20
- package/dist/esm/interface/crud/products.d.ts.map +1 -1
- package/dist/esm/interface/crud/project-api-keys.d.ts +3 -3
- package/dist/esm/interface/crud/projects.d.ts +36 -36
- package/dist/esm/interface/crud/team-member-profiles.d.ts +16 -16
- package/dist/esm/interface/crud/transactions.d.ts +23 -23
- package/dist/esm/interface/crud/transactions.d.ts.map +1 -1
- package/dist/esm/interface/crud/users.d.ts +14 -14
- package/dist/esm/interface/server-interface.js +1 -1
- package/dist/esm/interface/webhooks.d.ts +4 -4
- package/dist/esm/known-errors.d.ts +7 -7
- package/dist/esm/schema-fields.d.ts +7 -6
- package/dist/esm/schema-fields.d.ts.map +1 -1
- package/dist/esm/schema-fields.js +5 -1
- package/dist/esm/schema-fields.js.map +1 -1
- package/dist/esm/stack-config-file.js.map +1 -1
- package/dist/esm/utils/cloud-hosts.d.ts +42 -0
- package/dist/esm/utils/cloud-hosts.d.ts.map +1 -0
- package/dist/esm/utils/cloud-hosts.js +92 -0
- package/dist/esm/utils/cloud-hosts.js.map +1 -0
- package/dist/esm/utils/errors.d.ts +9 -2
- package/dist/esm/utils/errors.d.ts.map +1 -1
- package/dist/esm/utils/errors.js +16 -5
- package/dist/esm/utils/errors.js.map +1 -1
- package/dist/esm/utils/promises.js +1 -1
- package/dist/esm/utils/react.d.ts.map +1 -1
- package/dist/esm/utils/react.js +4 -4
- package/dist/esm/utils/react.js.map +1 -1
- package/dist/esm/utils/redirect-urls.d.ts.map +1 -1
- package/dist/esm/utils/redirect-urls.js +3 -3
- package/dist/esm/utils/redirect-urls.js.map +1 -1
- package/dist/esm/utils/urls.d.ts.map +1 -1
- package/dist/esm/utils/urls.js +2 -2
- package/dist/esm/utils/urls.js.map +1 -1
- package/dist/hooks/use-hover.d.ts +1 -1
- package/dist/hooks/use-hover.d.ts.map +1 -1
- package/dist/hooks/use-hover.js.map +1 -1
- package/dist/{index-D9ysacya.d.ts → index-fQbeILq7.d.ts} +1 -1
- package/dist/{index-D9ysacya.d.ts.map → index-fQbeILq7.d.ts.map} +1 -1
- package/dist/interface/admin-interface.js +1 -1
- package/dist/interface/admin-metrics.d.ts +8 -8
- package/dist/interface/client-interface.d.ts +1 -1
- package/dist/interface/client-interface.js +1 -1
- package/dist/interface/conversations.d.ts +32 -32
- package/dist/interface/crud/current-user.d.ts +8 -8
- package/dist/interface/crud/email-outbox.d.ts +218 -218
- package/dist/interface/crud/products.d.ts +20 -20
- package/dist/interface/crud/products.d.ts.map +1 -1
- package/dist/interface/crud/project-api-keys.d.ts +3 -3
- package/dist/interface/crud/projects.d.ts +36 -36
- package/dist/interface/crud/team-member-profiles.d.ts +16 -16
- package/dist/interface/crud/transactions.d.ts +23 -23
- package/dist/interface/crud/transactions.d.ts.map +1 -1
- package/dist/interface/crud/users.d.ts +14 -14
- package/dist/interface/server-interface.js +1 -1
- package/dist/interface/webhooks.d.ts +4 -4
- package/dist/known-errors.d.ts +7 -7
- package/dist/schema-fields.d.ts +7 -6
- package/dist/schema-fields.d.ts.map +1 -1
- package/dist/schema-fields.js +5 -0
- package/dist/schema-fields.js.map +1 -1
- package/dist/stack-config-file.js.map +1 -1
- package/dist/utils/cloud-hosts.d.ts +42 -0
- package/dist/utils/cloud-hosts.d.ts.map +1 -0
- package/dist/utils/cloud-hosts.js +97 -0
- package/dist/utils/cloud-hosts.js.map +1 -0
- package/dist/utils/errors.d.ts +9 -2
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/errors.js +16 -4
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/passkey.d.ts +1 -1
- package/dist/utils/promises.js +1 -1
- package/dist/utils/react.d.ts.map +1 -1
- package/dist/utils/react.js +4 -4
- package/dist/utils/react.js.map +1 -1
- package/dist/utils/redirect-urls.d.ts.map +1 -1
- package/dist/utils/redirect-urls.js +3 -3
- package/dist/utils/redirect-urls.js.map +1 -1
- package/dist/utils/urls.d.ts.map +1 -1
- package/dist/utils/urls.js +2 -2
- package/dist/utils/urls.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloud-hosts.js","names":[],"sources":["../../src/utils/cloud-hosts.tsx"],"sourcesContent":["/**\n * Single source of truth for the stack-auth ↔ hexclave host pairs that the\n * cloud deployment treats as equivalent siblings. Each\n * `[stackAuthHost, hexclaveHost]` pair is consumed in a few places:\n *\n * 1. `CLOUD_API_HOST_BY_REQUEST_HOST` in the backend's `request-api-url.ts` —\n * the allowlist of request hosts we resolve into a JWT `iss` claim.\n * 2. `issuerHostAliases` in `tokens.tsx` — the bidirectional validator alias\n * map, so a token issued under either host validates against the other.\n * 3. `getCloudApiUrlSiblings` below — resolves the branded base URLs used for\n * OAuth `redirect_uri` callbacks (both at runtime and in the dashboard).\n *\n * Deriving all of these from this one list prevents drift.\n */\nexport const CLOUD_HOST_PAIRS: ReadonlyArray<readonly [string, string]> = [\n [\"api.stack-auth.com\", \"api.hexclave.com\"],\n [\"api.dev.stack-auth.com\", \"api.dev.hexclave.com\"],\n [\"api.staging.stack-auth.com\", \"api.staging.hexclave.com\"],\n];\n\nfunction hostFromApiUrlOrHost(input: string): string | undefined {\n try {\n return new URL(input).host.split(\":\")[0].toLowerCase();\n } catch {\n const firstHost = input.split(\",\")[0]?.trim();\n if (!firstHost) return undefined;\n return firstHost.split(\":\")[0].toLowerCase();\n }\n}\n\n/**\n * Given an API URL (or bare host), if its host belongs to a known\n * stack-auth ↔ hexclave cloud pair, return both branded base URLs. Returns\n * null for unknown hosts (localhost, vercel previews, self-host custom\n * domains).\n */\nexport function getCloudApiUrlSiblings(apiUrlOrHost: string | undefined | null): { stackAuth: string, hexclave: string } | null {\n if (!apiUrlOrHost) return null;\n const host = hostFromApiUrlOrHost(apiUrlOrHost);\n if (!host) return null;\n for (const [stackAuthHost, hexclaveHost] of CLOUD_HOST_PAIRS) {\n if (host === stackAuthHost || host === hexclaveHost) {\n return { stackAuth: `https://${stackAuthHost}`, hexclave: `https://${hexclaveHost}` };\n }\n }\n return null;\n}\n\n/**\n * The stack-auth-branded base URL for the given deployment API URL. Used as the\n * OAuth `redirect_uri` base for shared providers and for custom providers that\n * predate `customCallbackUrl` (so existing flows keep hitting\n * `api.stack-auth.com`). Unknown hosts fall back to the input unchanged.\n */\nexport function getStackAuthApiBaseUrl(apiUrl: string): string {\n return getCloudApiUrlSiblings(apiUrl)?.stackAuth ?? apiUrl;\n}\n\n/**\n * The hexclave-branded base URL for the given deployment API URL. Used when a\n * new custom OAuth provider is set up, so its `customCallbackUrl` points at the\n * hexclave brand. Unknown hosts fall back to the input unchanged.\n */\nexport function getHexclaveApiBaseUrl(apiUrl: string): string {\n return getCloudApiUrlSiblings(apiUrl)?.hexclave ?? apiUrl;\n}\n\nimport.meta.vitest?.test(\"getCloudApiUrlSiblings maps both sides of each cloud pair\", ({ expect }) => {\n for (const [stackAuthHost, hexclaveHost] of CLOUD_HOST_PAIRS) {\n const expected = { stackAuth: `https://${stackAuthHost}`, hexclave: `https://${hexclaveHost}` };\n for (const host of [stackAuthHost, hexclaveHost]) {\n expect(getCloudApiUrlSiblings(host)).toEqual(expected);\n expect(getCloudApiUrlSiblings(`https://${host}`)).toEqual(expected);\n expect(getCloudApiUrlSiblings(`https://${host.toUpperCase()}:443`)).toEqual(expected);\n }\n }\n});\n\nimport.meta.vitest?.test(\"getCloudApiUrlSiblings returns null for unknown hosts\", ({ expect }) => {\n expect(getCloudApiUrlSiblings(\"http://localhost:8102\")).toBeNull();\n expect(getCloudApiUrlSiblings(\"https://my-app.vercel.app\")).toBeNull();\n expect(getCloudApiUrlSiblings(undefined)).toBeNull();\n expect(getCloudApiUrlSiblings(\"\")).toBeNull();\n});\n\nimport.meta.vitest?.test(\"getStackAuthApiBaseUrl / getHexclaveApiBaseUrl resolve brands and fall back\", ({ expect }) => {\n expect(getStackAuthApiBaseUrl(\"https://api.hexclave.com\")).toBe(\"https://api.stack-auth.com\");\n expect(getHexclaveApiBaseUrl(\"https://api.stack-auth.com\")).toBe(\"https://api.hexclave.com\");\n expect(getStackAuthApiBaseUrl(\"https://api.dev.stack-auth.com\")).toBe(\"https://api.dev.stack-auth.com\");\n expect(getHexclaveApiBaseUrl(\"http://localhost:8102\")).toBe(\"http://localhost:8102\");\n expect(getStackAuthApiBaseUrl(\"http://localhost:8102\")).toBe(\"http://localhost:8102\");\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,MAAa,mBAA6D;CACxE,CAAC,sBAAsB,mBAAmB;CAC1C,CAAC,0BAA0B,uBAAuB;CAClD,CAAC,8BAA8B,2BAA2B;CAC3D;AAED,SAAS,qBAAqB,OAAmC;AAC/D,KAAI;AACF,SAAO,IAAI,IAAI,MAAM,CAAC,KAAK,MAAM,IAAI,CAAC,GAAG,aAAa;SAChD;EACN,MAAM,YAAY,MAAM,MAAM,IAAI,CAAC,IAAI,MAAM;A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C7F,QAAO,sBAAsB,6BAA6B,CAAC,CAAC,KAAK,2BAA2B;AAC5F,QAAO,uBAAuB,iCAAiC,CAAC,CAAC,KAAK,iCAAiC;AACvG,QAAO,sBAAsB,wBAAwB,CAAC,CAAC,KAAK,wBAAwB;AACpF,QAAO,uBAAuB,wBAAwB,CAAC,CAAC,KAAK,wBAAwB;EACrF"}
|
package/dist/utils/errors.d.ts
CHANGED
|
@@ -33,7 +33,9 @@ declare class HexclaveAssertionError extends Error {
|
|
|
33
33
|
constructor(message: string, extraData?: (Record<string, any> & ErrorOptions) | undefined);
|
|
34
34
|
}
|
|
35
35
|
declare function errorToNiceString(error: unknown): string;
|
|
36
|
-
|
|
36
|
+
type CaptureLevel = "error" | "warning";
|
|
37
|
+
type ErrorSink = (location: string, error: unknown, level: CaptureLevel, ...extraArgs: unknown[]) => void;
|
|
38
|
+
declare function registerErrorSink(sink: ErrorSink): void;
|
|
37
39
|
/**
|
|
38
40
|
* Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are
|
|
39
41
|
* supposed to be seen by an engineer, so they should be actionable and important.
|
|
@@ -44,6 +46,11 @@ declare function registerErrorSink(sink: (location: string, error: unknown) => v
|
|
|
44
46
|
* Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.
|
|
45
47
|
*/
|
|
46
48
|
declare function captureError(location: string, error: unknown): void;
|
|
49
|
+
/**
|
|
50
|
+
* Like captureError, but logs at warning level. Use for issues that an engineer should know about but that aren't
|
|
51
|
+
* severe enough to be treated as an error (e.g. recoverable failures in background tasks).
|
|
52
|
+
*/
|
|
53
|
+
declare function captureWarning(location: string, error: unknown): void;
|
|
47
54
|
type Status = {
|
|
48
55
|
statusCode: number;
|
|
49
56
|
message: string;
|
|
@@ -227,5 +234,5 @@ declare class StatusError extends Error {
|
|
|
227
234
|
toHttpJson(): Json;
|
|
228
235
|
}
|
|
229
236
|
//#endregion
|
|
230
|
-
export { HexclaveAssertionError, StatusError, captureError, concatStacktraces, errorToNiceString, registerErrorSink, throwErr };
|
|
237
|
+
export { CaptureLevel, HexclaveAssertionError, StatusError, captureError, captureWarning, concatStacktraces, errorToNiceString, registerErrorSink, throwErr };
|
|
231
238
|
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/utils/errors.tsx"],"mappings":";;;iBAMgB,QAAA,CAAS,YAAA,UAAsB,SAAA;AAAA,iBAC/B,QAAA,CAAS,KAAA,EAAO,KAAA;AAAA,iBAChB,QAAA,CAAA,GAAY,IAAA,EAAM,gCAAA;;;;;AADlC;;;;;AACA;;;;;AA0CA;;;;;;;;;iBAAgB,iBAAA,CAAkB,KAAA,EAAO,KAAA,KAAU,MAAA,EAAQ,KAAA;AAAA,cAkB9C,sBAAA,SAA+B,KAAA;EAAA,SACG,SAAA,IAAY,MAAA,gBAAsB,YAAA;cAAnE,OAAA,UAAiC,SAAA,IAAY,MAAA,gBAAsB,YAAA;AAAA;AAAA,iBAqBjE,iBAAA,CAAkB,KAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/utils/errors.tsx"],"mappings":";;;iBAMgB,QAAA,CAAS,YAAA,UAAsB,SAAA;AAAA,iBAC/B,QAAA,CAAS,KAAA,EAAO,KAAA;AAAA,iBAChB,QAAA,CAAA,GAAY,IAAA,EAAM,gCAAA;;;;;AADlC;;;;;AACA;;;;;AA0CA;;;;;;;;;iBAAgB,iBAAA,CAAkB,KAAA,EAAO,KAAA,KAAU,MAAA,EAAQ,KAAA;AAAA,cAkB9C,sBAAA,SAA+B,KAAA;EAAA,SACG,SAAA,IAAY,MAAA,gBAAsB,YAAA;cAAnE,OAAA,UAAiC,SAAA,IAAY,MAAA,gBAAsB,YAAA;AAAA;AAAA,iBAqBjE,iBAAA,CAAkB,KAAA;AAAA,KAMtB,YAAA;AAAA,KAEP,SAAA,IAAa,QAAA,UAAkB,KAAA,WAAgB,KAAA,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;;;;EAWrB,UAAA,CAAA,GAAc,IAAA;AAAA"}
|
package/dist/utils/errors.js
CHANGED
|
@@ -69,17 +69,21 @@ function registerErrorSink(sink) {
|
|
|
69
69
|
if (errorSinks.has(sink)) return;
|
|
70
70
|
errorSinks.add(sink);
|
|
71
71
|
}
|
|
72
|
-
registerErrorSink((location, error, ...extraArgs) => {
|
|
73
|
-
console.error(
|
|
72
|
+
registerErrorSink((location, error, level, ...extraArgs) => {
|
|
73
|
+
(level === "warning" ? console.warn : console.error)(`${level === "warning" ? "\x1B[43m" : "\x1B[41m"}Captured ${level === "warning" ? "warning" : "error"} in ${location}:`, errorToNiceString(error), ...extraArgs, "\x1B[0m");
|
|
74
74
|
});
|
|
75
|
-
registerErrorSink((location, error, ...extraArgs) => {
|
|
75
|
+
registerErrorSink((location, error, level, ...extraArgs) => {
|
|
76
76
|
__globals_js.globalVar.stackCapturedErrors = __globals_js.globalVar.stackCapturedErrors ?? [];
|
|
77
77
|
__globals_js.globalVar.stackCapturedErrors.push({
|
|
78
78
|
location,
|
|
79
79
|
error,
|
|
80
|
+
level,
|
|
80
81
|
extraArgs
|
|
81
82
|
});
|
|
82
83
|
});
|
|
84
|
+
function dispatchToSinks(location, error, level) {
|
|
85
|
+
for (const sink of errorSinks) sink(location, error, level, ...error && (typeof error === "object" || typeof error === "function") && "customCaptureExtraArgs" in error && Array.isArray(error.customCaptureExtraArgs) ? error.customCaptureExtraArgs : []);
|
|
86
|
+
}
|
|
83
87
|
/**
|
|
84
88
|
* Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are
|
|
85
89
|
* supposed to be seen by an engineer, so they should be actionable and important.
|
|
@@ -90,7 +94,14 @@ registerErrorSink((location, error, ...extraArgs) => {
|
|
|
90
94
|
* Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.
|
|
91
95
|
*/
|
|
92
96
|
function captureError(location, error) {
|
|
93
|
-
|
|
97
|
+
dispatchToSinks(location, error, "error");
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Like captureError, but logs at warning level. Use for issues that an engineer should know about but that aren't
|
|
101
|
+
* severe enough to be treated as an error (e.g. recoverable failures in background tasks).
|
|
102
|
+
*/
|
|
103
|
+
function captureWarning(location, error) {
|
|
104
|
+
dispatchToSinks(location, error, "warning");
|
|
94
105
|
}
|
|
95
106
|
var StatusError = class extends Error {
|
|
96
107
|
static {
|
|
@@ -386,6 +397,7 @@ StatusError.prototype.name = "StatusError";
|
|
|
386
397
|
exports.HexclaveAssertionError = HexclaveAssertionError;
|
|
387
398
|
exports.StatusError = StatusError;
|
|
388
399
|
exports.captureError = captureError;
|
|
400
|
+
exports.captureWarning = captureWarning;
|
|
389
401
|
exports.concatStacktraces = concatStacktraces;
|
|
390
402
|
exports.errorToNiceString = errorToNiceString;
|
|
391
403
|
exports.registerErrorSink = registerErrorSink;
|
package/dist/utils/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["globalVar"],"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 HexclaveAssertionError(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 * Note: Very often, the concatStacktracesIfRejected function in promises.tsx is an easier way to use this function.\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); // 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 HexclaveAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Hexclave. 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 // Use literal dot-form (guarded with `typeof process`) so Next.js / webpack\n // DefinePlugin can inline the value at build time. See getProcessEnv in ./env.\n if ((typeof process !== \"undefined\" ? process.env.NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR : undefined) === \"true\") {\n debugger;\n }\n }\n}\nHexclaveAssertionError.prototype.name = \"HexclaveAssertionError\";\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\n/**\n * Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are\n * supposed to be seen by an engineer, so they should be actionable and important.\n *\n * The location string is a machine-readable ID, and should hence not contain spaces or anything like that. Good\n * examples are: \"api-route-handler\", \"renderPart()\", etc.\n *\n * Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.\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 HexclaveAssertionError(\"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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;AAClB,MAAI,CAAC,QACH,OAAM,IAAI,uBAAuB,0EAA0E,EAAE,OAAO,MAAM,CAAC;;CAI/H,OAAc,cAAc,OAAsC;AAEhE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,6BAA6B,SAAS,MAAM,4BAA4B;;CAGhI,AAAO,gBAAgB;AACrB,SAAO,KAAK,cAAc,OAAO,KAAK,aAAa;;CAGrD,AAAO,gBAAgB;AACrB,SAAO,CAAC,KAAK,eAAe;;CAG9B,AAAO,gBAAwB;AAC7B,SAAO,KAAK;;CAGd,AAAO,UAAsB;AAC3B,SAAO,IAAI,aAAa,CAAC,OAAO,KAAK,QAAQ;;CAG/C,AAAO,aAAuC;AAC5C,SAAO,EACL,gBAAgB,CAAC,4BAA4B,EAC9C;;CAGH,AAAO,oBAA0B;AAC/B,SAAO;GACL,aAAa,KAAK,eAAe;GACjC,SAAS,KAAK;GACd,SAAS,KAAK,YAAY;GAC3B;;;;;CAMH,AAAO,aAAmB;AACxB,SAAO;GACL,aAAa,KAAK;GAClB,MAAM,KAAK;GACX,SAAS,KAAK,YAAY;GAC3B;;;AAGL,YAAY,UAAU,OAAO"}
|
|
1
|
+
{"version":3,"file":"errors.js","names":["globalVar"],"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 HexclaveAssertionError(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 * Note: Very often, the concatStacktracesIfRejected function in promises.tsx is an easier way to use this function.\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); // 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 HexclaveAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Hexclave. 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 // Use literal dot-form (guarded with `typeof process`) so Next.js / webpack\n // DefinePlugin can inline the value at build time. See getProcessEnv in ./env.\n if ((typeof process !== \"undefined\" ? process.env.NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR : undefined) === \"true\") {\n debugger;\n }\n }\n}\nHexclaveAssertionError.prototype.name = \"HexclaveAssertionError\";\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\nexport type CaptureLevel = \"error\" | \"warning\";\n\ntype ErrorSink = (location: string, error: unknown, level: CaptureLevel, ...extraArgs: unknown[]) => void;\n\nconst errorSinks = new Set<ErrorSink>();\nexport function registerErrorSink(sink: ErrorSink): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, level, ...extraArgs) => {\n const logger = level === \"warning\" ? console.warn : console.error;\n const colorCode = level === \"warning\" ? \"\\x1b[43m\" : \"\\x1b[41m\";\n const label = level === \"warning\" ? \"warning\" : \"error\";\n logger(\n `${colorCode}Captured ${label} 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, level, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, level, extraArgs });\n});\n\nfunction dispatchToSinks(location: string, error: unknown, level: CaptureLevel): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n level,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n/**\n * Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are\n * supposed to be seen by an engineer, so they should be actionable and important.\n *\n * The location string is a machine-readable ID, and should hence not contain spaces or anything like that. Good\n * examples are: \"api-route-handler\", \"renderPart()\", etc.\n *\n * Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.\n */\nexport function captureError(location: string, error: unknown): void {\n dispatchToSinks(location, error, \"error\");\n}\n\n/**\n * Like captureError, but logs at warning level. Use for issues that an engineer should know about but that aren't\n * severe enough to be treated as an error (e.g. recoverable failures in background tasks).\n */\nexport function captureWarning(location: string, error: unknown): void {\n dispatchToSinks(location, error, \"warning\");\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 HexclaveAssertionError(\"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":";;;;;;;AASA,SAAgB,SAAS,GAAG,MAAoB;AAC9C,KAAI,OAAO,KAAK,OAAO,SACrB,OAAM,IAAI,uBAAuB,KAAK,IAAI,KAAK,GAAG;UACzC,KAAK,cAAc,MAC5B,OAAM,KAAK;KAGX,OAAM,IAAI,YAAY,GAAG,KAAK;;AAIlC,SAAS,yBAAyB,OAAuB;CAEvD,MAAM,gCAAe,IAAI,OAAO,EAAC,OAAO,WAAW,UAAU;AAC7D,QAAO,MAAM,MAAM,KAAK,CAAC,MAAM,eAAe,IAAI,EAAE,CAAC,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;AA2BjE,SAAgB,kBAAkB,OAAc,GAAG,QAAuB;CAExE,MAAM,qBAAqB,MAAM,OAAO,SAAS,KAAK;CAMtD,MAAM,YAAY,0CAAyB,IAAI,OAAO,EAAC,SAAS,GAAG,CAAC,MAAM,KAAK,CAAC;AAGhF,MAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,yBAAyB,MAAM,SAAS,GAAG;AAC5D,QAAM,UAAU,qBAAqB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O,aAAuC;AAC5C,SAAO,EACL,gBAAgB,CAAC,4BAA4B,EAC9C;;CAGH,AAAO,oBAA0B;AAC/B,SAAO;GACL,aAAa,KAAK,eAAe;GACjC,SAAS,KAAK;GACd,SAAS,KAAK,YAAY;GAC3B;;;;;CAMH,AAAO,aAAmB;AACxB,SAAO;GACL,aAAa,KAAK;GAClB,MAAM,KAAK;GACX,SAAS,KAAK,YAAY;GAC3B;;;AAGL,YAAY,UAAU,OAAO"}
|
package/dist/utils/passkey.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as RegistrationResponseJSON, i as PublicKeyCredentialRequestOptionsJSON, n as AuthenticatorAttestationResponseJSON, r as PublicKeyCredentialCreationOptionsJSON, t as AuthenticationResponseJSON } from "../index-
|
|
1
|
+
import { a as RegistrationResponseJSON, i as PublicKeyCredentialRequestOptionsJSON, n as AuthenticatorAttestationResponseJSON, r as PublicKeyCredentialCreationOptionsJSON, t as AuthenticationResponseJSON } from "../index-fQbeILq7.js";
|
|
2
2
|
export { type AuthenticationResponseJSON, type AuthenticatorAttestationResponseJSON, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialRequestOptionsJSON, type RegistrationResponseJSON };
|
package/dist/utils/promises.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_chunk = require('../chunk-BE-pF4vm.js');
|
|
3
|
+
let ___index_js = require("../index.js");
|
|
3
4
|
let __errors_js = require("./errors.js");
|
|
4
5
|
let __env_js = require("./env.js");
|
|
5
6
|
let __maps_js = require("./maps.js");
|
|
6
7
|
let __results_js = require("./results.js");
|
|
7
8
|
let __telemetry_js = require("./telemetry.js");
|
|
8
|
-
let ___index_js = require("../index.js");
|
|
9
9
|
let __uuids_js = require("./uuids.js");
|
|
10
10
|
|
|
11
11
|
//#region src/utils/promises.tsx
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3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iBA4BhD,2BAAA,CAA4B,KAAA;AAAA,cAI/B,uBAAA,SAAgC,KAAA;EAC3C,MAAA;EACA,MAAA;EACA,4BAAA;cAEY,OAAA;IAAW,MAAA;EAAA;AAAA;;AA7NxB;;iBAiSe,YAAA,CAAa,MAAA"}
|
package/dist/utils/react.js
CHANGED
|
@@ -52,7 +52,7 @@ function getNodeText(node) {
|
|
|
52
52
|
if (["number", "string"].includes(typeof node)) return `${node}`;
|
|
53
53
|
if (!node) return "";
|
|
54
54
|
if (Array.isArray(node)) return node.map(getNodeText).join("");
|
|
55
|
-
if (
|
|
55
|
+
if (react.default.isValidElement(node)) return getNodeText(node.props.children);
|
|
56
56
|
throw new Error(`Unknown node type: ${typeof node}`);
|
|
57
57
|
}
|
|
58
58
|
(void 0)?.test("getNodeText", ({ expect }) => {
|
|
@@ -75,9 +75,9 @@ function getNodeText(node) {
|
|
|
75
75
|
42,
|
|
76
76
|
null
|
|
77
77
|
])).toBe("hello42");
|
|
78
|
-
expect(getNodeText(
|
|
79
|
-
expect(getNodeText(
|
|
80
|
-
expect(getNodeText([
|
|
78
|
+
expect(getNodeText(react.default.createElement("span", null, "child text"))).toBe("child text");
|
|
79
|
+
expect(getNodeText(react.default.createElement("div", null, react.default.createElement("span", null, "nested text")))).toBe("nested text");
|
|
80
|
+
expect(getNodeText([react.default.createElement("span", null, "first"), react.default.createElement("span", null, "second")])).toBe("firstsecond");
|
|
81
81
|
});
|
|
82
82
|
/**
|
|
83
83
|
* Suspends the currently rendered component indefinitely. Will not unsuspend unless the component rerenders.
|
package/dist/utils/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.js","names":[],"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React, { SetStateAction } from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve, runAsynchronously } from \"./promises\";\nimport { AsyncResult } from \"./results\";\nimport { ensureMonkeyPatch, NO_SUSPENSE_BOUNDARY_ERROR_SENTINEL } from \"./monkey-patch\";\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\nconst react18PromiseCache = new WeakMap<Promise<unknown>, AsyncResult<unknown, unknown>>();\nexport function use<T>(promise: Promise<T>): T {\n if (\"use\" in React) {\n return React.use(promise);\n } else {\n if (react18PromiseCache.has(promise)) {\n const result = react18PromiseCache.get(promise)!;\n if (result.status === \"pending\") {\n throw promise;\n } else if (result.status === \"ok\") {\n return result.data as T;\n } else {\n throw result.error;\n }\n } else {\n react18PromiseCache.set(promise, { \"status\": \"pending\", progress: undefined });\n runAsynchronously(async () => {\n try {\n const res = await promise;\n react18PromiseCache.set(promise, { \"status\": \"ok\", data: res });\n } catch (e) {\n react18PromiseCache.set(promise, { \"status\": \"error\", error: e });\n }\n });\n throw promise;\n }\n }\n}\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}\nimport.meta.vitest?.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 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\nexport type RefState<T> = ReadonlyRef<T> & {\n set: (updater: SetStateAction<T>) => void,\n};\n\n/**\n * Like useState, but its value is immediately available on refState.current after being set.\n *\n * Like useRef, but setting the value will cause a rerender.\n *\n * Note that useRefState returns a new object every time a rerender happens due to a value change, which is intentional\n * as it allows you to specify it in a dependency array like this:\n *\n * ```tsx\n * useEffect(() => {\n * // do something with refState.current\n * }, [refState]); // instead of refState.current\n * ```\n *\n * If you don't want this, you can wrap the result in a useMemo call.\n */\nexport function useRefState<T>(initialValue: T | (() => T)): RefState<T> {\n // Support lazy initialization like React.useState does: if initialValue is a function,\n // call it once to get the actual initial value (React.useRef does NOT do this automatically).\n const lazyInitRef = React.useRef<{ v: T } | null>(null);\n if (lazyInitRef.current === null) {\n lazyInitRef.current = {\n v: typeof initialValue === \"function\" ? (initialValue as () => T)() : initialValue,\n };\n }\n const resolvedInitialValue = lazyInitRef.current.v;\n const [, setState] = React.useState<T>(() => resolvedInitialValue);\n const ref = React.useRef(resolvedInitialValue);\n const setValue = React.useCallback((updater: SetStateAction<T>) => {\n const value: T = typeof updater === \"function\" ? (updater as any)(ref.current) : updater;\n ref.current = value;\n setState(value);\n }, []);\n const res = React.useMemo(() => ({\n get current() {\n return ref.current;\n },\n set: setValue,\n }), [setValue]);\n return res;\n}\n\nexport function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = refState.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n set(updater: SetStateAction<R>) {\n const value: R = typeof updater === \"function\" ? (updater as any)(this.current) : updater;\n refState.set(reverseMapper(refState.current, value));\n },\n };\n}\n\nexport function useQueryState(key: string, defaultValue?: string) {\n const getValue = () => new URLSearchParams(window.location.search).get(key) ?? defaultValue ?? null;\n\n const [value, setValue] = React.useState(getValue);\n\n React.useEffect(() => {\n const onPopState = () => setValue(getValue());\n window.addEventListener(\"popstate\", onPopState);\n return () => window.removeEventListener(\"popstate\", onPopState);\n }, []);\n\n const update = (next: string | null) => {\n const params = new URLSearchParams(window.location.search);\n if (next !== null) {\n params.set(key, next);\n } else {\n params.delete(key);\n }\n const newUrl = params.toString()\n ? `${window.location.pathname}?${params.toString()}`\n : window.location.pathname;\n window.history.pushState(null, \"\", newUrl);\n setValue(next);\n };\n\n return [value, update] as const;\n}\n\nexport function shouldRethrowRenderingError(error: unknown): boolean {\n return !!error && typeof error === \"object\" && \"digest\" in error && error.digest === \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n __noSuspenseBoundarySentinel = NO_SUSPENSE_BOUNDARY_ERROR_SENTINEL;\n\n constructor(options: { caller?: string }) {\n ensureMonkeyPatch();\n\n super(deindent`\n Suspense boundary not found! Read the error message below carefully (or paste it into your AI agent).\n\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 There are several potential causes:\n \n 1. [Next.js] 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. [React] You are missing a <Suspense> boundary in your component. Fix it by wrapping your component (or the entire app) in a <Suspense> component.\n\n 3. [Next.js] 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 4. 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 5. Your version of Hexclave is too old. Upgrade to the latest version to see if that fixes the issue.\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}\nimport.meta.vitest?.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":";;;;;;;;;;AAOA,SAAgB,iBAGd,aAAqB,QAA0G;CAC/H,MAAM,YAAY,mBAAmB,OA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
1
|
+
{"version":3,"file":"react.js","names":[],"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React, { SetStateAction } from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve, runAsynchronously } from \"./promises\";\nimport { AsyncResult } from \"./results\";\nimport { ensureMonkeyPatch, NO_SUSPENSE_BOUNDARY_ERROR_SENTINEL } from \"./monkey-patch\";\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\nconst react18PromiseCache = new WeakMap<Promise<unknown>, AsyncResult<unknown, unknown>>();\nexport function use<T>(promise: Promise<T>): T {\n if (\"use\" in React) {\n return React.use(promise);\n } else {\n if (react18PromiseCache.has(promise)) {\n const result = react18PromiseCache.get(promise)!;\n if (result.status === \"pending\") {\n throw promise;\n } else if (result.status === \"ok\") {\n return result.data as T;\n } else {\n throw result.error;\n }\n } else {\n react18PromiseCache.set(promise, { \"status\": \"pending\", progress: undefined });\n runAsynchronously(async () => {\n try {\n const res = await promise;\n react18PromiseCache.set(promise, { \"status\": \"ok\", data: res });\n } catch (e) {\n react18PromiseCache.set(promise, { \"status\": \"error\", error: e });\n }\n });\n throw promise;\n }\n }\n}\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 (React.isValidElement<{ children?: React.ReactNode }>(node)) {\n return getNodeText(node.props.children);\n }\n throw new Error(`Unknown node type: ${typeof node}`);\n}\nimport.meta.vitest?.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\n const mockElement = React.createElement(\"span\", null, \"child text\");\n expect(getNodeText(mockElement)).toBe(\"child text\");\n\n // Test with nested React elements\n const nestedElement = React.createElement(\"div\", null, React.createElement(\"span\", null, \"nested text\"));\n expect(getNodeText(nestedElement)).toBe(\"nested text\");\n\n // Test with array of React elements\n const arrayOfElements = [\n React.createElement(\"span\", null, \"first\"),\n React.createElement(\"span\", null, \"second\"),\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 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\nexport type RefState<T> = ReadonlyRef<T> & {\n set: (updater: SetStateAction<T>) => void,\n};\n\n/**\n * Like useState, but its value is immediately available on refState.current after being set.\n *\n * Like useRef, but setting the value will cause a rerender.\n *\n * Note that useRefState returns a new object every time a rerender happens due to a value change, which is intentional\n * as it allows you to specify it in a dependency array like this:\n *\n * ```tsx\n * useEffect(() => {\n * // do something with refState.current\n * }, [refState]); // instead of refState.current\n * ```\n *\n * If you don't want this, you can wrap the result in a useMemo call.\n */\nexport function useRefState<T>(initialValue: T | (() => T)): RefState<T> {\n // Support lazy initialization like React.useState does: if initialValue is a function,\n // call it once to get the actual initial value (React.useRef does NOT do this automatically).\n const lazyInitRef = React.useRef<{ v: T } | null>(null);\n if (lazyInitRef.current === null) {\n lazyInitRef.current = {\n v: typeof initialValue === \"function\" ? (initialValue as () => T)() : initialValue,\n };\n }\n const resolvedInitialValue = lazyInitRef.current.v;\n const [, setState] = React.useState<T>(() => resolvedInitialValue);\n const ref = React.useRef(resolvedInitialValue);\n const setValue = React.useCallback((updater: SetStateAction<T>) => {\n const value: T = typeof updater === \"function\" ? (updater as any)(ref.current) : updater;\n ref.current = value;\n setState(value);\n }, []);\n const res = React.useMemo(() => ({\n get current() {\n return ref.current;\n },\n set: setValue,\n }), [setValue]);\n return res;\n}\n\nexport function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = refState.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n set(updater: SetStateAction<R>) {\n const value: R = typeof updater === \"function\" ? (updater as any)(this.current) : updater;\n refState.set(reverseMapper(refState.current, value));\n },\n };\n}\n\nexport function useQueryState(key: string, defaultValue?: string) {\n const getValue = () => new URLSearchParams(window.location.search).get(key) ?? defaultValue ?? null;\n\n const [value, setValue] = React.useState(getValue);\n\n React.useEffect(() => {\n const onPopState = () => setValue(getValue());\n window.addEventListener(\"popstate\", onPopState);\n return () => window.removeEventListener(\"popstate\", onPopState);\n }, []);\n\n const update = (next: string | null) => {\n const params = new URLSearchParams(window.location.search);\n if (next !== null) {\n params.set(key, next);\n } else {\n params.delete(key);\n }\n const newUrl = params.toString()\n ? `${window.location.pathname}?${params.toString()}`\n : window.location.pathname;\n window.history.pushState(null, \"\", newUrl);\n setValue(next);\n };\n\n return [value, update] as const;\n}\n\nexport function shouldRethrowRenderingError(error: unknown): boolean {\n return !!error && typeof error === \"object\" && \"digest\" in error && error.digest === \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n __noSuspenseBoundarySentinel = NO_SUSPENSE_BOUNDARY_ERROR_SENTINEL;\n\n constructor(options: { caller?: string }) {\n ensureMonkeyPatch();\n\n super(deindent`\n Suspense boundary not found! Read the error message below carefully (or paste it into your AI agent).\n\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 There are several potential causes:\n \n 1. [Next.js] 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. [React] You are missing a <Suspense> boundary in your component. Fix it by wrapping your component (or the entire app) in a <Suspense> component.\n\n 3. [Next.js] 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 4. 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 5. Your version of Hexclave is too old. Upgrade to the latest version to see if that fixes the issue.\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}\nimport.meta.vitest?.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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e;AACrD,QAAO,YAAY,QAAQ,CAAC,UAAU,qEAAqE;EAC3G;;;;AAMF,SAAgB,aAAa,QAAiB;AAC5C,KAAI,8BAAgB,CAClB,OAAM,IAAI,wBAAwB,EAAE,QAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect-urls.d.ts","names":[],"sources":["../../src/utils/redirect-urls.tsx"],"mappings":";KAGK,mBAAA;EACH,cAAA;EACA,cAAA;AAAA;AAAA,iBAgCc,6BAAA,CAA8B,OAAA;EAC5C,SAAA;EACA,yBAAA;EACA,wBAAA;EACA,eAAA;AAAA;AAAA,iBAQc,6BAAA,CAA8B,OAAA;EAC5C,SAAA;EACA,UAAA;EACA,yBAAA;EACA,wBAAA;EACA,eAAA;AAAA;AAAA,iBA0Bc,qCAAA,CAAsC,OAAA;EACpD,SAAA;EACA,yBAAA;EACA,wBAAA;EACA,eAAA;AAAA;AAAA,iBA0Ec,sBAAA,CAAuB,WAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"redirect-urls.d.ts","names":[],"sources":["../../src/utils/redirect-urls.tsx"],"mappings":";KAGK,mBAAA;EACH,cAAA;EACA,cAAA;AAAA;AAAA,iBAgCc,6BAAA,CAA8B,OAAA;EAC5C,SAAA;EACA,yBAAA;EACA,wBAAA;EACA,eAAA;AAAA;AAAA,iBAQc,6BAAA,CAA8B,OAAA;EAC5C,SAAA;EACA,UAAA;EACA,yBAAA;EACA,wBAAA;EACA,eAAA;AAAA;AAAA,iBA0Bc,qCAAA,CAAsC,OAAA;EACpD,SAAA;EACA,yBAAA;EACA,wBAAA;EACA,eAAA;AAAA;AAAA,iBA0Ec,sBAAA,CAAuB,WAAA;AAAA,iBASvB,mBAAA,CACd,WAAA,WAAsB,GAAA,EACtB,MAAA,EAAQ,mBAAA;AAAA,iBAYM,sBAAA,CAAuB,aAAA,UAAuB,cAAA"}
|
|
@@ -12,7 +12,7 @@ const hostedHandlerTemplateProjectIdA = "00000000-0000-4000-8000-000000000000";
|
|
|
12
12
|
const hostedHandlerTemplateProjectIdB = "11111111-1111-4111-8111-111111111111";
|
|
13
13
|
function replaceStackPortPrefix(input, stackPortPrefix) {
|
|
14
14
|
if (input == null) return void 0;
|
|
15
|
-
return stackPortPrefix ? input.replace(/\$\{
|
|
15
|
+
return stackPortPrefix ? input.replace(/\$\{NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81\}/g, stackPortPrefix) : input;
|
|
16
16
|
}
|
|
17
17
|
function getHostedHandlerUrlFromTemplate(template, projectId, hostedPath) {
|
|
18
18
|
return template.replaceAll(hostedHandlerProjectIdPlaceholder, projectId).replaceAll(hostedHandlerPathPlaceholder, hostedPath);
|
|
@@ -100,7 +100,7 @@ function matchesTrustedDomain(testUrl, pattern) {
|
|
|
100
100
|
function isAcceptedNativeAppUrl(urlOrString) {
|
|
101
101
|
const url = (0, __urls_js.createUrlIfValid)(urlOrString);
|
|
102
102
|
if (!url) return false;
|
|
103
|
-
return url.protocol === "stack-auth-mobile-oauth-url:";
|
|
103
|
+
return url.protocol === "stack-auth-mobile-oauth-url:" || url.protocol === "hexclave-mobile-oauth-url:";
|
|
104
104
|
}
|
|
105
105
|
function validateRedirectUrl(urlOrString, config) {
|
|
106
106
|
const url = (0, __urls_js.createUrlIfValid)(urlOrString);
|
|
@@ -150,7 +150,7 @@ function getTrustedParentDomain(currentDomain, trustedDomains) {
|
|
|
150
150
|
allowLocalhost: false,
|
|
151
151
|
trustedDomains: getImplicitlyTrustedDomainsForProject({
|
|
152
152
|
projectId,
|
|
153
|
-
hostedHandlerUrlTemplate: "http://{projectId}.localhost:${
|
|
153
|
+
hostedHandlerUrlTemplate: "http://{projectId}.localhost:${NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81}09/{hostedPath}",
|
|
154
154
|
stackPortPrefix: "92"
|
|
155
155
|
})
|
|
156
156
|
})).toBe(true);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect-urls.js","names":[],"sources":["../../src/utils/redirect-urls.tsx"],"sourcesContent":["import { HexclaveAssertionError, captureError } from \"./errors\";\nimport { createUrlIfValid, isLocalhost, matchHostnamePattern } from \"./urls\";\n\ntype TrustedDomainConfig = {\n allowLocalhost?: boolean,\n trustedDomains: readonly (string | null | undefined)[],\n};\n\nconst defaultHostedHandlerDomainSuffix = \".built-with-stack-auth.com\";\nconst hostedHandlerProjectIdPlaceholder = \"{projectId}\";\nconst hostedHandlerPathPlaceholder = \"{hostedPath}\";\nconst defaultPorts = new Map<string, string>([['https:', '443'], ['http:', '80']]);\nconst hostedHandlerTemplateProjectIdA = \"00000000-0000-4000-8000-000000000000\";\nconst hostedHandlerTemplateProjectIdB = \"11111111-1111-4111-8111-111111111111\";\n\nfunction replaceStackPortPrefix(input: string | undefined, stackPortPrefix: string | undefined): string | undefined {\n if (input == null) return undefined;\n return stackPortPrefix ? input.replace(/\\$\\{NEXT_PUBLIC_STACK_PORT_PREFIX:-81\\}/g, stackPortPrefix) : input;\n}\n\nfunction getHostedHandlerUrlFromTemplate(template: string, projectId: string, hostedPath: string): string {\n return template\n .replaceAll(hostedHandlerProjectIdPlaceholder, projectId)\n .replaceAll(hostedHandlerPathPlaceholder, hostedPath);\n}\n\nfunction assertHostedHandlerTemplateHasProjectOrigin(template: string): void {\n const projectUrlA = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdA, \"handler\"));\n const projectUrlB = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdB, \"handler\"));\n if (projectUrlA.origin === projectUrlB.origin || !projectUrlA.hostname.includes(hostedHandlerTemplateProjectIdA)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must put {projectId} in the hostname.\", {\n hostedHandlerUrlTemplate: template,\n hint: \"Use a project-specific origin like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}', not a shared-origin path like 'https://example.com/{projectId}/{hostedPath}'.\",\n });\n }\n}\n\nexport function getHostedHandlerTrustedDomain(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string {\n return new URL(getHostedHandlerUrlFromConfig({\n ...options,\n hostedPath: \"handler\",\n })).origin;\n}\n\nexport function getHostedHandlerUrlFromConfig(options: {\n projectId: string,\n hostedPath: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string {\n const configuredTemplate = replaceStackPortPrefix(options.hostedHandlerUrlTemplate, options.stackPortPrefix);\n return configuredTemplate == null\n ? (() => {\n const domainSuffix = replaceStackPortPrefix(options.hostedHandlerDomainSuffix, options.stackPortPrefix) ?? defaultHostedHandlerDomainSuffix;\n if (!domainSuffix.startsWith(\".\")) {\n throw new HexclaveAssertionError(\"The hosted handler domain suffix must start with a dot.\", {\n domainSuffix,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_DOMAIN_SUFFIX to a value like '.built-with-stack-auth.com'.\",\n });\n }\n return `https://${options.projectId}${domainSuffix}/${options.hostedPath}`;\n })()\n : (() => {\n if (!configuredTemplate.includes(hostedHandlerProjectIdPlaceholder) || !configuredTemplate.includes(hostedHandlerPathPlaceholder)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must contain {projectId} and {hostedPath}.\", {\n hostedHandlerUrlTemplate: configuredTemplate,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_URL_TEMPLATE to a value like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}'.\",\n });\n }\n assertHostedHandlerTemplateHasProjectOrigin(configuredTemplate);\n return getHostedHandlerUrlFromTemplate(configuredTemplate, options.projectId, options.hostedPath);\n })();\n}\n\nexport function getImplicitlyTrustedDomainsForProject(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string[] {\n return [getHostedHandlerTrustedDomain(options)];\n}\n\nfunction normalizePort(url: URL): string {\n const port = url.port || defaultPorts.get(url.protocol) || '';\n return port ? `${url.hostname}:${port}` : url.hostname;\n}\n\nfunction isDefaultPort(url: URL): boolean {\n return !url.port ||\n (url.protocol === 'https:' && url.port === '443') ||\n (url.protocol === 'http:' && url.port === '80');\n}\n\nfunction portsMatch(url1: URL, url2: URL): boolean {\n return normalizePort(url1) === normalizePort(url2);\n}\n\nfunction parseWildcardUrlPattern(pattern: string): { protocol: string, hostPattern: string } | null {\n const protocolSeparatorIndex = pattern.indexOf(\"://\");\n if (protocolSeparatorIndex === -1) return null;\n\n const protocol = `${pattern.slice(0, protocolSeparatorIndex)}:`;\n const hostAndPath = pattern.slice(protocolSeparatorIndex + \"://\".length);\n const pathStartIndex = hostAndPath.indexOf(\"/\");\n const hostPattern = pathStartIndex === -1 ? hostAndPath : hostAndPath.slice(0, pathStartIndex);\n if (hostPattern === \"\") return null;\n return { protocol, hostPattern };\n}\n\nfunction hostPatternWithoutPort(hostPattern: string): string {\n if (!hostPatternHasExplicitPort(hostPattern)) {\n return hostPattern;\n }\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n return hostPattern.slice(0, portSeparatorIndex);\n}\n\nfunction hostPatternHasExplicitPort(hostPattern: string): boolean {\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n if (portSeparatorIndex === -1) {\n return false;\n }\n const port = hostPattern.slice(portSeparatorIndex + 1);\n return port === \"*\" || (port !== \"\" && [...port].every(char => char >= \"0\" && char <= \"9\"));\n}\n\nfunction matchesTrustedDomain(testUrl: URL, pattern: string): boolean {\n const baseUrl = createUrlIfValid(pattern);\n\n if (baseUrl != null && !pattern.includes('*')) {\n return baseUrl.protocol === testUrl.protocol &&\n baseUrl.hostname === testUrl.hostname &&\n portsMatch(baseUrl, testUrl);\n }\n\n const parsedPattern = parseWildcardUrlPattern(pattern);\n if (parsedPattern == null) {\n captureError(\"invalid-redirect-domain\", new HexclaveAssertionError(\"Invalid domain pattern\", { pattern }));\n return false;\n }\n\n if (testUrl.protocol !== parsedPattern.protocol) {\n return false;\n }\n\n const hasPortInPattern = hostPatternHasExplicitPort(parsedPattern.hostPattern);\n return hasPortInPattern\n ? matchHostnamePattern(parsedPattern.hostPattern, normalizePort(testUrl))\n : matchHostnamePattern(parsedPattern.hostPattern, testUrl.hostname) && isDefaultPort(testUrl);\n}\n\nexport function isAcceptedNativeAppUrl(urlOrString: string): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n return url.protocol === 'stack-auth-mobile-oauth-url:';\n}\n\nexport function validateRedirectUrl(\n urlOrString: string | URL,\n config: TrustedDomainConfig,\n): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n if (config.allowLocalhost === true && isLocalhost(url)) {\n return true;\n }\n\n return config.trustedDomains.some(domain => domain != null && matchesTrustedDomain(url, domain));\n}\n\nexport function getTrustedParentDomain(currentDomain: string, trustedDomains: readonly (string | null | undefined)[]): string | null {\n const hostPatterns = trustedDomains\n .filter((domain): domain is string => domain != null)\n .map((domain) => {\n const url = createUrlIfValid(domain);\n if (url != null && !domain.includes(\"*\")) {\n return url.hostname.toLowerCase();\n }\n const parsedPattern = parseWildcardUrlPattern(domain);\n return parsedPattern == null ? null : hostPatternWithoutPort(parsedPattern.hostPattern).toLowerCase();\n })\n .filter((domain): domain is string => domain != null);\n\n const parts = currentDomain.toLowerCase().split('.');\n for (let i = parts.length - 2; i >= 0; i--) {\n const parentDomain = parts.slice(i).join('.');\n if (hostPatterns.includes(parentDomain) && hostPatterns.includes(`**.${parentDomain}`)) {\n return parentDomain;\n }\n }\n\n return null;\n}\n\nimport.meta.vitest?.test(\"validateRedirectUrl matches exact and wildcard trusted domains\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.v2.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(false);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl trusts implicit hosted handler domains\", ({ expect }) => {\n const projectId = \"12345678-1234-4234-8234-123456789abc\";\n expect(validateRedirectUrl(`https://${projectId}.built-with-stack-auth.com/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(true);\n expect(validateRedirectUrl(\"https://other-project.built-with-stack-auth.com/anything\", {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(false);\n expect(validateRedirectUrl(`http://${projectId}.localhost:9209/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({\n projectId,\n hostedHandlerUrlTemplate: \"http://{projectId}.localhost:${NEXT_PUBLIC_STACK_PORT_PREFIX:-81}09/{hostedPath}\",\n stackPortPrefix: \"92\",\n }),\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"getImplicitlyTrustedDomainsForProject rejects shared-origin hosted templates\", ({ expect }) => {\n expect(() => getImplicitlyTrustedDomainsForProject({\n projectId: \"12345678-1234-4234-8234-123456789abc\",\n hostedHandlerUrlTemplate: \"https://host.example.com/{projectId}/{hostedPath}\",\n })).toThrowErrorMatchingInlineSnapshot(`\n [HexclaveAssertionError: The hosted handler URL template must put {projectId} in the hostname.\n\n This is likely an error in Hexclave. Please make sure you are running the newest version and report it.]\n `);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects default and explicit ports\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com:443/path\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com:3000\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(false);\n expect(validateRedirectUrl(\"http://api.example.com:1234\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:*\"],\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects localhost allowance and invalid patterns\", ({ expect }) => {\n const originalConsoleError = console.error;\n console.error = () => {};\n try {\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: true,\n trustedDomains: [],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: false,\n trustedDomains: [],\n })).toBe(false);\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"not a url\"],\n })).toBe(false);\n } finally {\n console.error = originalConsoleError;\n }\n});\n\nimport.meta.vitest?.test(\"getTrustedParentDomain ignores empty entries and strips ports\", ({ expect }) => {\n expect(getTrustedParentDomain(\"app.example.com\", [\n null,\n undefined,\n \"https://example.com\",\n \"https://**.example.com:*\",\n ])).toBe(\"example.com\");\n});\n"],"mappings":";;;;;;AAQA,MAAM,mCAAmC;AACzC,MAAM,oCAAoC;AAC1C,MAAM,+BAA+B;AACrC,MAAM,eAAe,IAAI,IAAoB,CAAC,CAAC,UAAU,MAAM,EAAE,CAAC,SAAS,KAAK,CAAC,CAAC;AAClF,MAAM,kCAAkC;AACxC,MAAM,kCAAkC;AAExC,SAAS,uBAAuB,OAA2B,iBAAyD;AAClH,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,kBAAkB,MAAM,QAAQ,4CAA4C,gBAAgB,GAAG;;AAGxG,SAAS,gCAAgC,UAAkB,WAAmB,YAA4B;AACxG,QAAO,SACJ,WAAW,mCAAmC,UAAS,CACvD,WAAW,8BAA8B,WAAW;;AAGzD,SAAS,4CAA4C,UAAwB;CAC3E,MAAM,cAAc,IAAI,IAAI,gCAAgC,UAAU,iCAAiC,UAAU,CAAC;CAClH,MAAM,cAAc,IAAI,IAAI,gCAAgC,UAAU,iCAAiC,U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AK;EACd;CAEF,SAAW,KAAC,0EAA2E,EAAA,aAAc;CACnG,MAAM,uBAAuB,QAAQ;AACrC,SAAQ,cAAc;AACtB,KAAI;AACF,SAAO,oBAAoB,yBAAyB;GAClD,gBAAgB;GAChB,gBAAgB,EAAE;GACnB,CAAC,CAAC,CAAC,KAAK,KAAK;AACd,SAAO,oBAAoB,yBAAyB;GAClD,gBAAgB;GAChB,gBAAgB,EAAE;GACnB,CAAC,CAAC,CAAC,KAAK,MAAM;AACf,SAAO,oBAAoB,uBAAuB;GAChD,gBAAgB;GAChB,gBAAgB,CAAC,YAAY;GAC9B,CAAC,CAAC,CAAC,KAAK,MAAM;WACP;AACR,UAAQ,QAAQ;;EAElB;CAEF,SAAW,KAAC,kEAAsE,EAAA,aAAW;AAC3F,QAAO,uBAAuB,mBAAmB;EAC/C;EACA;EACA;EACA;EACD,CAAC,CAAC,CAAC,KAAK,cAAc;EACvB"}
|
|
1
|
+
{"version":3,"file":"redirect-urls.js","names":[],"sources":["../../src/utils/redirect-urls.tsx"],"sourcesContent":["import { HexclaveAssertionError, captureError } from \"./errors\";\nimport { createUrlIfValid, isLocalhost, matchHostnamePattern } from \"./urls\";\n\ntype TrustedDomainConfig = {\n allowLocalhost?: boolean,\n trustedDomains: readonly (string | null | undefined)[],\n};\n\nconst defaultHostedHandlerDomainSuffix = \".built-with-stack-auth.com\";\nconst hostedHandlerProjectIdPlaceholder = \"{projectId}\";\nconst hostedHandlerPathPlaceholder = \"{hostedPath}\";\nconst defaultPorts = new Map<string, string>([['https:', '443'], ['http:', '80']]);\nconst hostedHandlerTemplateProjectIdA = \"00000000-0000-4000-8000-000000000000\";\nconst hostedHandlerTemplateProjectIdB = \"11111111-1111-4111-8111-111111111111\";\n\nfunction replaceStackPortPrefix(input: string | undefined, stackPortPrefix: string | undefined): string | undefined {\n if (input == null) return undefined;\n return stackPortPrefix ? input.replace(/\\$\\{NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81\\}/g, stackPortPrefix) : input;\n}\n\nfunction getHostedHandlerUrlFromTemplate(template: string, projectId: string, hostedPath: string): string {\n return template\n .replaceAll(hostedHandlerProjectIdPlaceholder, projectId)\n .replaceAll(hostedHandlerPathPlaceholder, hostedPath);\n}\n\nfunction assertHostedHandlerTemplateHasProjectOrigin(template: string): void {\n const projectUrlA = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdA, \"handler\"));\n const projectUrlB = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdB, \"handler\"));\n if (projectUrlA.origin === projectUrlB.origin || !projectUrlA.hostname.includes(hostedHandlerTemplateProjectIdA)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must put {projectId} in the hostname.\", {\n hostedHandlerUrlTemplate: template,\n hint: \"Use a project-specific origin like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}', not a shared-origin path like 'https://example.com/{projectId}/{hostedPath}'.\",\n });\n }\n}\n\nexport function getHostedHandlerTrustedDomain(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string {\n return new URL(getHostedHandlerUrlFromConfig({\n ...options,\n hostedPath: \"handler\",\n })).origin;\n}\n\nexport function getHostedHandlerUrlFromConfig(options: {\n projectId: string,\n hostedPath: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string {\n const configuredTemplate = replaceStackPortPrefix(options.hostedHandlerUrlTemplate, options.stackPortPrefix);\n return configuredTemplate == null\n ? (() => {\n const domainSuffix = replaceStackPortPrefix(options.hostedHandlerDomainSuffix, options.stackPortPrefix) ?? defaultHostedHandlerDomainSuffix;\n if (!domainSuffix.startsWith(\".\")) {\n throw new HexclaveAssertionError(\"The hosted handler domain suffix must start with a dot.\", {\n domainSuffix,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_DOMAIN_SUFFIX to a value like '.built-with-stack-auth.com'.\",\n });\n }\n return `https://${options.projectId}${domainSuffix}/${options.hostedPath}`;\n })()\n : (() => {\n if (!configuredTemplate.includes(hostedHandlerProjectIdPlaceholder) || !configuredTemplate.includes(hostedHandlerPathPlaceholder)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must contain {projectId} and {hostedPath}.\", {\n hostedHandlerUrlTemplate: configuredTemplate,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_URL_TEMPLATE to a value like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}'.\",\n });\n }\n assertHostedHandlerTemplateHasProjectOrigin(configuredTemplate);\n return getHostedHandlerUrlFromTemplate(configuredTemplate, options.projectId, options.hostedPath);\n })();\n}\n\nexport function getImplicitlyTrustedDomainsForProject(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string[] {\n return [getHostedHandlerTrustedDomain(options)];\n}\n\nfunction normalizePort(url: URL): string {\n const port = url.port || defaultPorts.get(url.protocol) || '';\n return port ? `${url.hostname}:${port}` : url.hostname;\n}\n\nfunction isDefaultPort(url: URL): boolean {\n return !url.port ||\n (url.protocol === 'https:' && url.port === '443') ||\n (url.protocol === 'http:' && url.port === '80');\n}\n\nfunction portsMatch(url1: URL, url2: URL): boolean {\n return normalizePort(url1) === normalizePort(url2);\n}\n\nfunction parseWildcardUrlPattern(pattern: string): { protocol: string, hostPattern: string } | null {\n const protocolSeparatorIndex = pattern.indexOf(\"://\");\n if (protocolSeparatorIndex === -1) return null;\n\n const protocol = `${pattern.slice(0, protocolSeparatorIndex)}:`;\n const hostAndPath = pattern.slice(protocolSeparatorIndex + \"://\".length);\n const pathStartIndex = hostAndPath.indexOf(\"/\");\n const hostPattern = pathStartIndex === -1 ? hostAndPath : hostAndPath.slice(0, pathStartIndex);\n if (hostPattern === \"\") return null;\n return { protocol, hostPattern };\n}\n\nfunction hostPatternWithoutPort(hostPattern: string): string {\n if (!hostPatternHasExplicitPort(hostPattern)) {\n return hostPattern;\n }\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n return hostPattern.slice(0, portSeparatorIndex);\n}\n\nfunction hostPatternHasExplicitPort(hostPattern: string): boolean {\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n if (portSeparatorIndex === -1) {\n return false;\n }\n const port = hostPattern.slice(portSeparatorIndex + 1);\n return port === \"*\" || (port !== \"\" && [...port].every(char => char >= \"0\" && char <= \"9\"));\n}\n\nfunction matchesTrustedDomain(testUrl: URL, pattern: string): boolean {\n const baseUrl = createUrlIfValid(pattern);\n\n if (baseUrl != null && !pattern.includes('*')) {\n return baseUrl.protocol === testUrl.protocol &&\n baseUrl.hostname === testUrl.hostname &&\n portsMatch(baseUrl, testUrl);\n }\n\n const parsedPattern = parseWildcardUrlPattern(pattern);\n if (parsedPattern == null) {\n captureError(\"invalid-redirect-domain\", new HexclaveAssertionError(\"Invalid domain pattern\", { pattern }));\n return false;\n }\n\n if (testUrl.protocol !== parsedPattern.protocol) {\n return false;\n }\n\n const hasPortInPattern = hostPatternHasExplicitPort(parsedPattern.hostPattern);\n return hasPortInPattern\n ? matchHostnamePattern(parsedPattern.hostPattern, normalizePort(testUrl))\n : matchHostnamePattern(parsedPattern.hostPattern, testUrl.hostname) && isDefaultPort(testUrl);\n}\n\nexport function isAcceptedNativeAppUrl(urlOrString: string): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n // Legacy scheme accepted indefinitely; baked into already-shipped Swift SDK binaries.\n return url.protocol === 'stack-auth-mobile-oauth-url:'\n || url.protocol === 'hexclave-mobile-oauth-url:';\n}\n\nexport function validateRedirectUrl(\n urlOrString: string | URL,\n config: TrustedDomainConfig,\n): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n if (config.allowLocalhost === true && isLocalhost(url)) {\n return true;\n }\n\n return config.trustedDomains.some(domain => domain != null && matchesTrustedDomain(url, domain));\n}\n\nexport function getTrustedParentDomain(currentDomain: string, trustedDomains: readonly (string | null | undefined)[]): string | null {\n const hostPatterns = trustedDomains\n .filter((domain): domain is string => domain != null)\n .map((domain) => {\n const url = createUrlIfValid(domain);\n if (url != null && !domain.includes(\"*\")) {\n return url.hostname.toLowerCase();\n }\n const parsedPattern = parseWildcardUrlPattern(domain);\n return parsedPattern == null ? null : hostPatternWithoutPort(parsedPattern.hostPattern).toLowerCase();\n })\n .filter((domain): domain is string => domain != null);\n\n const parts = currentDomain.toLowerCase().split('.');\n for (let i = parts.length - 2; i >= 0; i--) {\n const parentDomain = parts.slice(i).join('.');\n if (hostPatterns.includes(parentDomain) && hostPatterns.includes(`**.${parentDomain}`)) {\n return parentDomain;\n }\n }\n\n return null;\n}\n\nimport.meta.vitest?.test(\"validateRedirectUrl matches exact and wildcard trusted domains\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.v2.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(false);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl trusts implicit hosted handler domains\", ({ expect }) => {\n const projectId = \"12345678-1234-4234-8234-123456789abc\";\n expect(validateRedirectUrl(`https://${projectId}.built-with-stack-auth.com/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(true);\n expect(validateRedirectUrl(\"https://other-project.built-with-stack-auth.com/anything\", {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(false);\n expect(validateRedirectUrl(`http://${projectId}.localhost:9209/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({\n projectId,\n hostedHandlerUrlTemplate: \"http://{projectId}.localhost:${NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81}09/{hostedPath}\",\n stackPortPrefix: \"92\",\n }),\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"getImplicitlyTrustedDomainsForProject rejects shared-origin hosted templates\", ({ expect }) => {\n expect(() => getImplicitlyTrustedDomainsForProject({\n projectId: \"12345678-1234-4234-8234-123456789abc\",\n hostedHandlerUrlTemplate: \"https://host.example.com/{projectId}/{hostedPath}\",\n })).toThrowErrorMatchingInlineSnapshot(`\n [HexclaveAssertionError: The hosted handler URL template must put {projectId} in the hostname.\n\n This is likely an error in Hexclave. Please make sure you are running the newest version and report it.]\n `);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects default and explicit ports\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com:443/path\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com:3000\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(false);\n expect(validateRedirectUrl(\"http://api.example.com:1234\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:*\"],\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects localhost allowance and invalid patterns\", ({ expect }) => {\n const originalConsoleError = console.error;\n console.error = () => {};\n try {\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: true,\n trustedDomains: [],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: false,\n trustedDomains: [],\n })).toBe(false);\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"not a url\"],\n })).toBe(false);\n } finally {\n console.error = originalConsoleError;\n }\n});\n\nimport.meta.vitest?.test(\"getTrustedParentDomain ignores empty entries and strips ports\", ({ expect }) => {\n expect(getTrustedParentDomain(\"app.example.com\", [\n null,\n undefined,\n \"https://example.com\",\n \"https://**.example.com:*\",\n ])).toBe(\"example.com\");\n});\n"],"mappings":";;;;;;AAQA,MAAM,mCAAmC;AACzC,MAAM,oCAAoC;AAC1C,MAAM,+BAA+B;AACrC,MAAM,eAAe,IAAI,IAAoB,CAAC,CAAC,UAAU,MAAM,EAAE,CAAC,SAAS,KAAK,CAAC,CAAC;AAClF,MAAM,kCAAkC;AACxC,MAAM,kCAAkC;AAExC,SAAS,uBAAuB,OAA2B,iBAAyD;AAClH,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,kBAAkB,MAAM,QAAQ,+CAA+C,gBAAgB,GAAG;;AAG3G,SAAS,gCAAgC,UAAkB,WAAmB,YAA4B;AACxG,QAAO,SACJ,WAAW,mCAAmC,UAAS,CACvD,WAAW,8BAA8B,WAAW;;AAGzD,SAAS,4CAA4C,UAAwB;CAC3E,MAAM,cAAc,IAAI,IAAI,gCAAgC,UAAU,iCAAiC,UAAU,CAAC;CAClH,MAAM,cAAc,IAAI,IAAI,gCAAgC,UAAU,iCAAiC,UAAU,CAAC;AAClH,KAAI,YAAY,WAAW,YAAY,UAAU,CAAC,YAAY,SAAS,SAAS,gCAAgC,CAC9G,OAAM,IAAI,mCAAuB,yEAAyE;EACxG,0BAA0B;EAC1B,MAAM;EACP,CAAC;;AAIN,SAAgB,8BAA8B,SAKnC;AACT,QAAO,IAAI,IAAI,8BAA8B;EAC3C,GAAG;EACH,YAAY;EACb,CAAC,CAAC,CAAC;;AAGN,SAAgB,8BAA8B,SAMnC;CACT,MAAM,qBAAqB,uBAAuB,QAAQ,0BAA0B,QAAQ,gBAAgB;AAC5G,QAAO,sBAAsB,cAClB;EACP,MAAM,eAAe,uBAAuB,QAAQ,2BAA2B,QAAQ,gBAAgB,IAAI;AAC3G,MAAI,CAAC,aAAa,WAAW,IAAI,CAC/B,OAAM,IAAI,mCAAuB,2DAA2D;GAC1F;GACA,M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EAC/C;EACA;EACA;EACA;EACD,CAAC,CAAC,CAAC,KAAK,cAAc;EACvB"}
|
package/dist/utils/urls.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"urls.d.ts","names":[],"sources":["../../src/utils/urls.tsx"],"mappings":";iBAGgB,gBAAA,CAAA,GAAoB,IAAA,EAAM,qBAAA,QAA6B,GAAA,IAAI,GAAA;AAAA,iBAmB3D,UAAA,CAAW,GAAA;AAAA,iBAeX,eAAA,CAAgB,QAAA;AAAA,iBAwBhB,4BAAA,CAA6B,QAAA;AAAA,iBAkF7B,oBAAA,CAAqB,OAAA,UAAiB,QAAA;AAAA,iBAuDtC,wBAAA,CAAyB,cAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"urls.d.ts","names":[],"sources":["../../src/utils/urls.tsx"],"mappings":";iBAGgB,gBAAA,CAAA,GAAoB,IAAA,EAAM,qBAAA,QAA6B,GAAA,IAAI,GAAA;AAAA,iBAmB3D,UAAA,CAAW,GAAA;AAAA,iBAeX,eAAA,CAAgB,QAAA;AAAA,iBAwBhB,4BAAA,CAA6B,QAAA;AAAA,iBAkF7B,oBAAA,CAAqB,OAAA,UAAiB,QAAA;AAAA,iBAuDtC,wBAAA,CAAyB,cAAA;AAAA,iBAyBzB,iBAAA,CAAkB,cAAA;AAAA,iBAIlB,WAAA,CAAY,WAAA,WAAsB,GAAA;AAAA,iBA+BlC,UAAA,CAAW,GAAA;AAAA,iBA4BX,eAAA,CAAgB,GAAA,EAAK,GAAA;;;;;;iBAsBrB,GAAA,CAAI,OAAA,EAAS,oBAAA,yBAA6C,MAAA,kCAAwC,GAAA;;;;;AA/QlH;iBAmTgB,SAAA,CAAU,OAAA,EAAS,oBAAA,yBAA6C,MAAA;AAAA,iBAyBhE,UAAA,CAAW,SAAA,EAAW,GAAA,EAAK,aAAA,EAAe,GAAA;AAAA,iBAsB1C,WAAA,CAAY,UAAA,UAAoB,cAAA"}
|
package/dist/utils/urls.js
CHANGED
|
@@ -114,10 +114,10 @@ function matchHostnamePattern(pattern, hostname) {
|
|
|
114
114
|
expect(matchHostnamePattern("*.*.org", "example.org")).toBe(false);
|
|
115
115
|
});
|
|
116
116
|
function getHardcodedFallbackUrls(primaryBaseUrl) {
|
|
117
|
-
if (primaryBaseUrl === "https://api.hexclave.com") return ["https://api1.hexclave.com", "https://api2.hexclave.com"];
|
|
118
|
-
if (primaryBaseUrl === "https://api.dev.hexclave.com") return ["https://api1.dev.hexclave.com", "https://api2.dev.hexclave.com"];
|
|
119
117
|
if (primaryBaseUrl === "https://api.stack-auth.com") return ["https://api1.stack-auth.com", "https://api2.stack-auth.com"];
|
|
120
118
|
if (primaryBaseUrl === "https://api.dev.stack-auth.com") return ["https://api1.dev.stack-auth.com", "https://api2.dev.stack-auth.com"];
|
|
119
|
+
if (primaryBaseUrl === "https://api.hexclave.com") return ["https://api1.hexclave.com", "https://api2.hexclave.com"];
|
|
120
|
+
if (primaryBaseUrl === "https://api.dev.hexclave.com") return ["https://api1.dev.hexclave.com", "https://api2.dev.hexclave.com"];
|
|
121
121
|
const localhostMatch = primaryBaseUrl.match(/^http:\/\/localhost:(\d+)02$/);
|
|
122
122
|
if (localhostMatch) return [`http://localhost:${localhostMatch[1]}10`];
|
|
123
123
|
return [];
|