@quatronic/sdk 0.8.0-rc.9 → 0.8.0-test.3e82420

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.
Files changed (101) hide show
  1. package/dist/chunk-5RAO3LPF.js +116 -0
  2. package/dist/chunk-5RAO3LPF.js.map +1 -0
  3. package/dist/{chunk-G7VPNC6M.js → chunk-IFESUTF2.js} +21 -100
  4. package/dist/chunk-IFESUTF2.js.map +1 -0
  5. package/dist/{chunk-2AYDFLKR.js → chunk-NMJOF3ZM.js} +6 -104
  6. package/dist/chunk-NMJOF3ZM.js.map +1 -0
  7. package/dist/chunk-P7HNHLW7.js +65 -0
  8. package/dist/chunk-P7HNHLW7.js.map +1 -0
  9. package/dist/chunk-POZI4OKJ.js +20 -0
  10. package/dist/chunk-POZI4OKJ.js.map +1 -0
  11. package/dist/chunk-TPBRMW5N.js +197 -0
  12. package/dist/chunk-TPBRMW5N.js.map +1 -0
  13. package/dist/chunk-YFZB5EW6.js +107 -0
  14. package/dist/chunk-YFZB5EW6.js.map +1 -0
  15. package/dist/cli/legacy/qdc-sourcemaps.js +16 -6
  16. package/dist/cli/skills-postinstall.js +4 -3
  17. package/dist/cli/skills.js +4 -3
  18. package/dist/cli/sourcemaps.js +16 -6
  19. package/dist/integrations/index.d.ts +3 -75
  20. package/dist/integrations/index.js +6 -4
  21. package/dist/mail/index.d.ts +9 -0
  22. package/dist/mail/index.js +26 -0
  23. package/dist/mail/index.js.map +1 -0
  24. package/dist/next/auth/index.js +2 -152
  25. package/dist/next/auth/index.js.map +1 -1
  26. package/dist/next/boot/index.d.ts +39 -0
  27. package/dist/next/boot/index.js +22 -0
  28. package/dist/next/boot/index.js.map +1 -0
  29. package/dist/next/db/index.d.ts +27 -1
  30. package/dist/next/db/index.js +45 -3
  31. package/dist/next/db/index.js.map +1 -1
  32. package/dist/next/global-error/index.d.ts +9 -0
  33. package/dist/next/global-error/index.js +17 -0
  34. package/dist/next/global-error/index.js.map +1 -0
  35. package/dist/next/integrations/index.d.ts +2 -1
  36. package/dist/next/integrations/index.js +6 -4
  37. package/dist/next/platform/index.d.ts +19 -0
  38. package/dist/next/platform/index.js +44 -0
  39. package/dist/next/platform/index.js.map +1 -0
  40. package/dist/next/security/index.d.ts +23 -1
  41. package/dist/next/security/index.js +40 -57
  42. package/dist/next/security/index.js.map +1 -1
  43. package/dist/next/security/testing.js +10 -1
  44. package/dist/next/security/testing.js.map +1 -1
  45. package/dist/next/sentry/client.js +2 -1
  46. package/dist/next/sentry/client.js.map +1 -1
  47. package/dist/next/sentry/index.d.ts +1 -0
  48. package/dist/next/sentry/index.js +5 -1
  49. package/dist/next/sentry/index.js.map +1 -1
  50. package/dist/next/sentry/register.js +6 -13
  51. package/dist/next/sentry/register.js.map +1 -1
  52. package/dist/node/boot/index.d.ts +9 -0
  53. package/dist/node/boot/index.js +13 -0
  54. package/dist/node/boot/index.js.map +1 -0
  55. package/dist/node/integrations/index.d.ts +2 -1
  56. package/dist/node/integrations/index.js +6 -4
  57. package/dist/node/sentry/index.d.ts +3 -0
  58. package/dist/node/sentry/index.js +7 -0
  59. package/dist/node/sentry/index.js.map +1 -0
  60. package/dist/node/sentry/register.js +2 -1
  61. package/dist/node/sentry/register.js.map +1 -1
  62. package/dist/node-YQDRNIYH.js +33 -0
  63. package/dist/node-YQDRNIYH.js.map +1 -0
  64. package/dist/types-Cl7g4ego.d.ts +80 -0
  65. package/migrations/bootstrap-qore-env/codemod.mjs +77 -0
  66. package/migrations/bootstrap-qore-env/instructions.md +28 -0
  67. package/migrations/bootstrap-qore-env/meta.json +7 -0
  68. package/migrations/global-error/codemod.mjs +28 -0
  69. package/migrations/global-error/instructions.md +26 -0
  70. package/migrations/global-error/meta.json +7 -0
  71. package/migrations/local-db-port/codemod.mjs +61 -0
  72. package/migrations/local-db-port/instructions.md +45 -0
  73. package/migrations/local-db-port/meta.json +7 -0
  74. package/migrations/mail-reexport/codemod.mjs +64 -0
  75. package/migrations/mail-reexport/instructions.md +27 -0
  76. package/migrations/mail-reexport/meta.json +7 -0
  77. package/migrations/no-raw-fetch/meta.json +1 -1
  78. package/migrations/platform-routes/codemod.mjs +45 -0
  79. package/migrations/platform-routes/instructions.md +30 -0
  80. package/migrations/platform-routes/meta.json +7 -0
  81. package/migrations/qore-boot/codemod.mjs +271 -0
  82. package/migrations/qore-boot/instructions.md +74 -0
  83. package/migrations/qore-boot/meta.json +7 -0
  84. package/migrations/qore-proxy/codemod.mjs +88 -0
  85. package/migrations/qore-proxy/instructions.md +56 -0
  86. package/migrations/qore-proxy/meta.json +7 -0
  87. package/migrations/run.mjs +334 -0
  88. package/migrations/sourcemaps-finalize/codemod.mjs +63 -0
  89. package/migrations/sourcemaps-finalize/instructions.md +56 -0
  90. package/migrations/sourcemaps-finalize/meta.json +7 -0
  91. package/package.json +27 -2
  92. package/skills/catalog.json +1 -0
  93. package/skills/qore-add-env-key/SKILL.md +57 -0
  94. package/skills/qore-add-integration/SKILL.next.md +13 -7
  95. package/skills/qore-add-integration/SKILL.node.md +13 -7
  96. package/skills/qore-author-skill/SKILL.md +1 -0
  97. package/workspace-requirements.json +4 -0
  98. package/dist/chunk-2AYDFLKR.js.map +0 -1
  99. package/dist/chunk-BJN7YE63.js +0 -46
  100. package/dist/chunk-BJN7YE63.js.map +0 -1
  101. package/dist/chunk-G7VPNC6M.js.map +0 -1
@@ -0,0 +1,116 @@
1
+ import {
2
+ defaultEnv,
3
+ normalizeAlias
4
+ } from "./chunk-5XMTUPIY.js";
5
+
6
+ // src/integrations-core/types.ts
7
+ function defineIntegrations(map) {
8
+ return map;
9
+ }
10
+ var AUTH_ENV_FIELDS = {
11
+ none: [],
12
+ api_key_header: ["apiKey"],
13
+ bearer_static: ["token"],
14
+ basic: ["username", "password"],
15
+ oauth2_client_credentials: ["tokenUrl", "clientId", "clientSecret", "scope", "audience"]
16
+ };
17
+ var AUTH_SECRET_FIELDS = [
18
+ "apiKey",
19
+ "token",
20
+ "username",
21
+ "password",
22
+ "clientId",
23
+ "clientSecret"
24
+ ];
25
+ var RESERVED_KEY_PREFIX = "QORE_INTEGRATION_";
26
+
27
+ // src/integrations-core/env.ts
28
+ function refKey(ref) {
29
+ return typeof ref === "string" ? ref : ref.key;
30
+ }
31
+ function refOptional(ref) {
32
+ return typeof ref !== "string" && (ref.optional === true || ref.default !== void 0);
33
+ }
34
+ function authKeys(def) {
35
+ const auth = def.auth;
36
+ return AUTH_ENV_FIELDS[def.auth.kind].map((field) => auth[field]).filter((key) => typeof key === "string" && key !== "");
37
+ }
38
+ function requiredKeys(def) {
39
+ const keys = [def.baseUrl, ...authKeys(def)];
40
+ for (const ref of Object.values(def.config ?? {})) {
41
+ if (!refOptional(ref)) keys.push(refKey(ref));
42
+ }
43
+ return [...new Set(keys)];
44
+ }
45
+ function allKeys(def) {
46
+ const keys = [def.baseUrl, ...authKeys(def)];
47
+ for (const ref of Object.values(def.config ?? {})) keys.push(refKey(ref));
48
+ return [...new Set(keys)];
49
+ }
50
+ function readRef(env, ref) {
51
+ const value = env[refKey(ref)];
52
+ if (value !== void 0 && value !== "") return value;
53
+ return typeof ref === "string" ? void 0 : ref.default;
54
+ }
55
+ function loggingKey(alias) {
56
+ return `${RESERVED_KEY_PREFIX}${normalizeAlias(alias)}_LOGGING`;
57
+ }
58
+ function loggingEnabled(env, alias) {
59
+ const value = env[loggingKey(alias)];
60
+ return value === "1" || value?.toLowerCase() === "true";
61
+ }
62
+
63
+ // src/integrations-core/assertIntegrations.ts
64
+ var ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/;
65
+ function assertIntegrations(map, opts = {}) {
66
+ const env = opts.env ?? defaultEnv();
67
+ const warn = opts.warn ?? ((message) => console.warn(message));
68
+ const problems = [];
69
+ for (const [alias, def] of Object.entries(map)) {
70
+ for (const key of allKeys(def)) {
71
+ let why;
72
+ if (key.startsWith(RESERVED_KEY_PREFIX)) {
73
+ why = `${RESERVED_KEY_PREFIX}* keys are reserved by the platform`;
74
+ } else if (key.startsWith("CONN_")) {
75
+ why = "CONN_* keys belong to module connections, not integrations";
76
+ } else if (!ENV_KEY_RE.test(key)) {
77
+ why = "an env key is uppercase letters, digits and underscores";
78
+ }
79
+ if (why) {
80
+ problems.push({
81
+ alias,
82
+ key,
83
+ code: "reserved_key",
84
+ message: `Integration "${alias}" declares env key "${key}": ${why}`
85
+ });
86
+ }
87
+ }
88
+ for (const key of requiredKeys(def)) {
89
+ const value = env[key];
90
+ if (value === void 0 || value === "") {
91
+ problems.push({
92
+ alias,
93
+ key,
94
+ code: "missing_env",
95
+ message: `Integration "${alias}" is missing env key "${key}"; calls to it will fail until it is set`
96
+ });
97
+ }
98
+ }
99
+ }
100
+ for (const p of problems) warn(`[integrations] ${p.message}`);
101
+ return problems;
102
+ }
103
+
104
+ export {
105
+ defineIntegrations,
106
+ AUTH_ENV_FIELDS,
107
+ AUTH_SECRET_FIELDS,
108
+ RESERVED_KEY_PREFIX,
109
+ requiredKeys,
110
+ allKeys,
111
+ readRef,
112
+ loggingKey,
113
+ loggingEnabled,
114
+ assertIntegrations
115
+ };
116
+ //# sourceMappingURL=chunk-5RAO3LPF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/integrations-core/types.ts","../src/integrations-core/env.ts","../src/integrations-core/assertIntegrations.ts"],"sourcesContent":["/**\n * How an integration authenticates. Every field except `header` and\n * `credentialsIn` names an **env key** — the SDK reads the value from the\n * environment at call time, never from the declaration — so a declaration can\n * sit in source control and carry no secret.\n */\nexport type AuthKind =\n | \"none\"\n | \"api_key_header\"\n | \"bearer_static\"\n | \"basic\"\n | \"oauth2_client_credentials\"\n\n/** What the API speaks. Informational for the portal; the client sends bytes either way. */\nexport type Protocol = \"rest\" | \"odata\" | \"soap\" | \"graphql\"\n\n/** The name of an env var, e.g. `SAP_BASE_URL`. */\nexport type EnvKey = string\n\n/**\n * A reference to an env var. The short form is required; the object form can\n * be optional and carry a default the app falls back on when the key is unset.\n */\nexport type EnvRef =\n | EnvKey\n | { key: EnvKey; optional?: boolean; default?: string | number | boolean }\n\nexport type IntegrationAuth =\n | { kind: \"none\" }\n | { kind: \"api_key_header\"; header: string; apiKey: EnvKey }\n | { kind: \"bearer_static\"; token: EnvKey }\n | { kind: \"basic\"; username: EnvKey; password: EnvKey }\n | {\n kind: \"oauth2_client_credentials\"\n tokenUrl: EnvKey\n clientId: EnvKey\n clientSecret: EnvKey\n scope?: EnvKey\n audience?: EnvKey\n /** Where the client credentials go on the token request. Default `\"header\"`. */\n credentialsIn?: \"header\" | \"body\"\n }\n\nexport interface IntegrationDefinition {\n /** Human name shown in the portal, e.g. \"SAP S/4HANA Cloud\". */\n label: string\n protocol: Protocol\n /** Env key holding the base URL for this environment. */\n baseUrl: EnvKey\n auth: IntegrationAuth\n /** Further env the app reads for this integration, by logical name. */\n config?: Record<string, EnvRef>\n}\n\nexport type IntegrationMap = Record<string, IntegrationDefinition>\n\n/**\n * Identity function that pins the literal types of the map, so an alias typo\n * at a call site is a compile error (`keyof M`) rather than a runtime\n * `not_declared`. Same shape as `definePermissions` in `auth-core`.\n */\nexport function defineIntegrations<const M extends IntegrationMap>(map: M): M {\n return map\n}\n\n/**\n * Which fields of each auth kind name an env key. Shared with the manifest\n * extractor and the portal, which derive the required-env list from a\n * declaration without evaluating app code.\n */\nexport const AUTH_ENV_FIELDS: Record<AuthKind, readonly string[]> = {\n none: [],\n api_key_header: [\"apiKey\"],\n bearer_static: [\"token\"],\n basic: [\"username\", \"password\"],\n oauth2_client_credentials: [\"tokenUrl\", \"clientId\", \"clientSecret\", \"scope\", \"audience\"],\n}\n\n/**\n * Auth fields whose env value is a secret, so the portal locks it whatever\n * `env.ts` labels it. The identifier of a login counts with its secret:\n * `username` sits with `password` and `clientId` with `clientSecret`, because\n * that is where a person looks for them and they are replaced together.\n */\nexport const AUTH_SECRET_FIELDS = [\n \"apiKey\",\n \"token\",\n \"username\",\n \"password\",\n \"clientId\",\n \"clientSecret\",\n] as const\n\n/**\n * Env keys under this prefix belong to the platform\n * (`QORE_INTEGRATION_<ALIAS>_LOGGING` today). A declaration may not claim one.\n */\nexport const RESERVED_KEY_PREFIX = \"QORE_INTEGRATION_\"\n","import { normalizeAlias, type Env } from \"../connections-core/env\"\nimport {\n AUTH_ENV_FIELDS,\n RESERVED_KEY_PREFIX,\n type EnvRef,\n type IntegrationDefinition,\n} from \"./types\"\n\nexport type { Env }\n\nexport function refKey(ref: EnvRef): string {\n return typeof ref === \"string\" ? ref : ref.key\n}\n\nfunction refOptional(ref: EnvRef): boolean {\n return typeof ref !== \"string\" && (ref.optional === true || ref.default !== undefined)\n}\n\n/** The auth fields of `def` that are set, as env keys. */\nfunction authKeys(def: IntegrationDefinition): string[] {\n const auth = def.auth as unknown as Record<string, unknown>\n return AUTH_ENV_FIELDS[def.auth.kind]\n .map((field) => auth[field])\n .filter((key): key is string => typeof key === \"string\" && key !== \"\")\n}\n\n/**\n * Every env key the integration cannot run without: the base URL, every auth\n * field that is set, and every config ref that is neither optional nor\n * defaulted. Order is stable so an error message reads the same twice.\n */\nexport function requiredKeys(def: IntegrationDefinition): string[] {\n const keys = [def.baseUrl, ...authKeys(def)]\n for (const ref of Object.values(def.config ?? {})) {\n if (!refOptional(ref)) keys.push(refKey(ref))\n }\n return [...new Set(keys)]\n}\n\n/** Every env key the declaration names, required or not. */\nexport function allKeys(def: IntegrationDefinition): string[] {\n const keys = [def.baseUrl, ...authKeys(def)]\n for (const ref of Object.values(def.config ?? {})) keys.push(refKey(ref))\n return [...new Set(keys)]\n}\n\n/**\n * Read one ref from `env`, applying its default when the key is unset or\n * empty. A default comes back as declared (a number or boolean stays typed);\n * an env value is always a string.\n */\nexport function readRef(env: Env, ref: EnvRef): string | number | boolean | undefined {\n const value = env[refKey(ref)]\n if (value !== undefined && value !== \"\") return value\n return typeof ref === \"string\" ? undefined : ref.default\n}\n\n/** `QORE_INTEGRATION_<ALIAS>_LOGGING` — the one reserved key v1 reads. */\nexport function loggingKey(alias: string): string {\n return `${RESERVED_KEY_PREFIX}${normalizeAlias(alias)}_LOGGING`\n}\n\n/** Whether the per-call JSON log line is switched on for this alias (\"1\" or \"true\"). */\nexport function loggingEnabled(env: Env, alias: string): boolean {\n const value = env[loggingKey(alias)]\n return value === \"1\" || value?.toLowerCase() === \"true\"\n}\n","import { defaultEnv, type Env } from \"../connections-core/env\"\nimport { allKeys, requiredKeys } from \"./env\"\nimport { RESERVED_KEY_PREFIX, type IntegrationMap } from \"./types\"\n\nconst ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/\n\nexport interface IntegrationProblem {\n alias: string\n key: string\n /** `missing_env`: a required key is unset or empty. `reserved_key`: the declaration claims a key it may not. */\n code: \"missing_env\" | \"reserved_key\"\n message: string\n}\n\n/**\n * Report, at app startup, what is wrong with the declared integrations: a\n * required env key that is unset, or a key the declaration may not claim.\n * **It never throws.** Integrations are a visibility tool: an API key that is\n * not set (an obsolete integration, a vendor not contracted in this\n * environment) must cost the calls to that one integration — they fail with\n * `missing_env` — never the boot of the whole app. Each problem is logged as\n * one warning and returned, so a caller may act on them if it chooses.\n */\nexport function assertIntegrations(\n map: IntegrationMap,\n opts: { env?: Env; warn?: (message: string) => void } = {},\n): IntegrationProblem[] {\n const env = opts.env ?? defaultEnv()\n const warn = opts.warn ?? ((message: string) => console.warn(message))\n const problems: IntegrationProblem[] = []\n\n for (const [alias, def] of Object.entries(map)) {\n for (const key of allKeys(def)) {\n let why: string | undefined\n if (key.startsWith(RESERVED_KEY_PREFIX)) {\n why = `${RESERVED_KEY_PREFIX}* keys are reserved by the platform`\n } else if (key.startsWith(\"CONN_\")) {\n why = \"CONN_* keys belong to module connections, not integrations\"\n } else if (!ENV_KEY_RE.test(key)) {\n why = \"an env key is uppercase letters, digits and underscores\"\n }\n if (why) {\n problems.push({\n alias,\n key,\n code: \"reserved_key\",\n message: `Integration \"${alias}\" declares env key \"${key}\": ${why}`,\n })\n }\n }\n for (const key of requiredKeys(def)) {\n const value = env[key]\n if (value === undefined || value === \"\") {\n problems.push({\n alias,\n key,\n code: \"missing_env\",\n message: `Integration \"${alias}\" is missing env key \"${key}\"; calls to it will fail until it is set`,\n })\n }\n }\n }\n\n for (const p of problems) warn(`[integrations] ${p.message}`)\n return problems\n}\n"],"mappings":";;;;;;AA6DO,SAAS,mBAAmD,KAAW;AAC5E,SAAO;AACT;AAOO,IAAM,kBAAuD;AAAA,EAClE,MAAM,CAAC;AAAA,EACP,gBAAgB,CAAC,QAAQ;AAAA,EACzB,eAAe,CAAC,OAAO;AAAA,EACvB,OAAO,CAAC,YAAY,UAAU;AAAA,EAC9B,2BAA2B,CAAC,YAAY,YAAY,gBAAgB,SAAS,UAAU;AACzF;AAQO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMO,IAAM,sBAAsB;;;ACvF5B,SAAS,OAAO,KAAqB;AAC1C,SAAO,OAAO,QAAQ,WAAW,MAAM,IAAI;AAC7C;AAEA,SAAS,YAAY,KAAsB;AACzC,SAAO,OAAO,QAAQ,aAAa,IAAI,aAAa,QAAQ,IAAI,YAAY;AAC9E;AAGA,SAAS,SAAS,KAAsC;AACtD,QAAM,OAAO,IAAI;AACjB,SAAO,gBAAgB,IAAI,KAAK,IAAI,EACjC,IAAI,CAAC,UAAU,KAAK,KAAK,CAAC,EAC1B,OAAO,CAAC,QAAuB,OAAO,QAAQ,YAAY,QAAQ,EAAE;AACzE;AAOO,SAAS,aAAa,KAAsC;AACjE,QAAM,OAAO,CAAC,IAAI,SAAS,GAAG,SAAS,GAAG,CAAC;AAC3C,aAAW,OAAO,OAAO,OAAO,IAAI,UAAU,CAAC,CAAC,GAAG;AACjD,QAAI,CAAC,YAAY,GAAG,EAAG,MAAK,KAAK,OAAO,GAAG,CAAC;AAAA,EAC9C;AACA,SAAO,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC;AAC1B;AAGO,SAAS,QAAQ,KAAsC;AAC5D,QAAM,OAAO,CAAC,IAAI,SAAS,G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GAAG,GAAG;AACnC,YAAM,QAAQ,IAAI,GAAG;AACrB,UAAI,UAAU,UAAa,UAAU,IAAI;AACvC,iBAAS,KAAK;AAAA,UACZ;AAAA,UACA;AAAA,UACA,MAAM;AAAA,UACN,SAAS,gBAAgB,KAAK,yBAAyB,GAAG;AAAA,QAC5D,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,aAAW,KAAK,SAAU,MAAK,kBAAkB,EAAE,OAAO,EAAE;AAC5D,SAAO;AACT;","names":[]}
@@ -1,46 +1,7 @@
1
- import {
2
- setTelemetryHooks
3
- } from "./chunk-MET4SIMB.js";
4
- import {
5
- makeDevSinkTransport
6
- } from "./chunk-7ASQHY7O.js";
7
-
8
- // src/sentry-core/noise.ts
9
- var NOISE_EXACT = /* @__PURE__ */ new Set(["/favicon.ico", "/api/auth/me"]);
10
- var RSC_QUERY_RE = /[?&]_rsc=/;
11
- function isNoisePath(rawUrl, opts = {}) {
12
- if (RSC_QUERY_RE.test(rawUrl)) return true;
13
- const path = (rawUrl.split("?")[0] ?? "").trim();
14
- if (!path) return false;
15
- if (NOISE_EXACT.has(path)) return true;
16
- if (path.endsWith(".map")) return true;
17
- if (path.startsWith("/_next/")) return true;
18
- if ((opts.noisePrefixes ?? []).some((p) => path.startsWith(p))) return true;
19
- if (opts.healthPath && path === opts.healthPath) return true;
20
- return false;
21
- }
22
-
23
- // src/sentry-core/sampler.ts
24
- var MUTATIONS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
25
- var str = (v) => typeof v === "string" && v ? v : void 0;
26
- function pathOf(ctx) {
27
- const a = ctx.attributes ?? {};
28
- return str(a["url.path"]) ?? str(a["http.target"]) ?? ctx.name.split(" ")[1];
29
- }
30
- function createTracesSampler(policy) {
31
- return (ctx) => {
32
- const path = pathOf(ctx);
33
- if (path && isNoisePath(path, { healthPath: policy.healthPath })) return 0;
34
- const a = ctx.attributes ?? {};
35
- const method = (str(a["http.request.method"]) ?? str(a["http.method"]) ?? "").toUpperCase();
36
- if (MUTATIONS.has(method)) return 1;
37
- return ctx.inheritOrSampleWith(policy.production ? policy.readRate : 1);
38
- };
39
- }
40
-
41
1
  // src/sentry-core/scrub.ts
42
2
  var REDACTED = "\u25CF\u25CF\u25CF";
43
3
  var EMAIL = /(?<![A-Z0-9._%+-])[A-Z0-9._%+-]{1,64}@[A-Z0-9-]+(?:\.[A-Z0-9-]+)*\.[A-Z]{2,}/gi;
4
+ var URL_USERINFO = /\b([a-z][a-z0-9+.-]{0,31}:\/\/)[^/\s:@]+(?::[^/\s@]*)?@/gi;
44
5
  var JWT = /eyJ[\w-]+\.[\w-]+\.[\w-]+/g;
45
6
  var AUTH_SCHEME = /\b(Bearer|Basic)\s+\S+/gi;
46
7
  var PARAMS_TAIL = /\bparams:\s.*$/s;
@@ -61,8 +22,21 @@ var REDACT_PREFIXES = ["net.peer.", "net.sock.", "net.host.", "network.peer.", "
61
22
  var DROP_SPAN_KEYS = /* @__PURE__ */ new Set(["user_agent.original", "http.user_agent", "client.address", "http.client_ip"]);
62
23
  var DROP_SPAN_PREFIXES = ["http.request.header.", "http.response.header."];
63
24
  var URL_SPAN_KEYS = /* @__PURE__ */ new Set(["url.full", "http.url", "url", "http.target", "url.query", "http.query"]);
25
+ var SECRETS = /* @__PURE__ */ Symbol.for("@quatronic/sdk.sentry-secret-values");
26
+ var secretHolder = globalThis;
27
+ function secretState() {
28
+ return secretHolder[SECRETS] ??= { values: /* @__PURE__ */ new Set(), longestFirst: [] };
29
+ }
30
+ function registerSecretValues(values) {
31
+ const state = secretState();
32
+ for (const v of values) if (typeof v === "string" && v.length >= 8) state.values.add(v);
33
+ state.longestFirst = [...state.values].sort((a, b) => b.length - a.length);
34
+ }
35
+ function maskSecretValues(s) {
36
+ return secretState().longestFirst.reduce((acc, v) => acc.replaceAll(v, REDACTED), s);
37
+ }
64
38
  function redactText(s) {
65
- return s.replace(PARAMS_TAIL, "params: [redacted]").replace(AUTH_SCHEME, "$1 [redacted]").replace(JWT, "[jwt]").replace(EMAIL, "[email]");
39
+ return maskSecretValues(s).replace(URL_USERINFO, `$1${REDACTED}@`).replace(PARAMS_TAIL, "params: [redacted]").replace(AUTH_SCHEME, "$1 [redacted]").replace(JWT, "[jwt]").replace(EMAIL, "[email]");
66
40
  }
67
41
  function redactQuery(query) {
68
42
  return query.split("&").map((pair) => {
@@ -127,64 +101,11 @@ function scrubSpan(s) {
127
101
  return s;
128
102
  }
129
103
 
130
- // src/sentry-core/options.ts
131
- function isTty() {
132
- try {
133
- return typeof process !== "undefined" && process.stdout?.isTTY === true;
134
- } catch {
135
- return false;
136
- }
137
- }
138
- function buildOptions(runtime, cfg) {
139
- return {
140
- dsn: cfg.dsn,
141
- environment: cfg.environment,
142
- release: cfg.release,
143
- sendDefaultPii: false,
144
- dataCollection: {
145
- userInfo: false,
146
- cookies: false,
147
- httpHeaders: { request: false, response: false },
148
- httpBodies: [],
149
- databaseQueryData: false,
150
- stackFrameVariables: false,
151
- genAI: { inputs: false, outputs: false },
152
- urlQueryParams: { deny: [...SECRET_PARAMS] }
153
- },
154
- enableLogs: true,
155
- tracesSampler: createTracesSampler({
156
- production: cfg.environment === "production",
157
- readRate: cfg.readSampleRate,
158
- healthPath: cfg.healthPath
159
- }),
160
- tracePropagationTargets: runtime === "browser" ? [/^\//] : cfg.connOrigins,
161
- beforeSend: scrubEvent,
162
- beforeSendTransaction: scrubEvent,
163
- beforeSendLog: scrubLog,
164
- beforeSendSpan: scrubSpan,
165
- initialScope: { tags: cfg.tags },
166
- ...cfg.local ? { transport: makeDevSinkTransport({ traces: cfg.devTraces ?? "line", color: runtime !== "browser" && isTty() }) } : {}
167
- };
168
- }
169
-
170
- // src/sentry-core/init.ts
171
- var DONE = /* @__PURE__ */ Symbol.for("@quatronic/sdk.sentry-initialised");
172
- var holder = globalThis;
173
- function initSentry(sentry, runtime, cfg, extra = {}) {
174
- if (!cfg || holder[DONE]) return false;
175
- holder[DONE] = true;
176
- try {
177
- const extras = typeof extra === "function" ? extra() : extra;
178
- sentry.init({ ...extras, ...buildOptions(runtime, cfg) });
179
- } catch (err) {
180
- console.error("[qore] Sentry init failed", err);
181
- return false;
182
- }
183
- setTelemetryHooks({ log: sentry.logger, setUser: (u) => sentry.setUser(u) });
184
- return true;
185
- }
186
-
187
104
  export {
188
- initSentry
105
+ SECRET_PARAMS,
106
+ registerSecretValues,
107
+ scrubEvent,
108
+ scrubLog,
109
+ scrubSpan
189
110
  };
190
- //# sourceMappingURL=chunk-G7VPNC6M.js.map
111
+ //# sourceMappingURL=chunk-IFESUTF2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sentry-core/scrub.ts"],"sourcesContent":["export const REDACTED = \"●●●\"\n\n// Bounded and anchored (`(?<![...])` + `{1,64}` local part, no `.` in the\n// domain-char class) so it cannot backtrack catastrophically on long runs of\n// email-charset bytes — see the fix-round-1 report for the O(n²) it replaced.\nconst EMAIL = /(?<![A-Z0-9._%+-])[A-Z0-9._%+-]{1,64}@[A-Z0-9-]+(?:\\.[A-Z0-9-]+)*\\.[A-Z]{2,}/gi\nconst URL_USERINFO = /\\b([a-z][a-z0-9+.-]{0,31}:\\/\\/)[^/\\s:@]+(?::[^/\\s@]*)?@/gi\nconst JWT = /eyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+/g\nconst AUTH_SCHEME = /\\b(Bearer|Basic)\\s+\\S+/gi\nconst PARAMS_TAIL = /\\bparams:\\s.*$/s\nexport const SECRET_PARAMS: ReadonlySet<string> = new Set([\"token\", \"code\", \"state\", \"password\", \"secret\", \"key\", \"session\", \"access_token\", \"refresh_token\", \"id_token\"])\nconst SECRET_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-qdc-connection-token\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"forwarded\",\n \"user-agent\",\n])\nconst DROP_LOG_ATTRS = new Set([\"ip\", \"ip_address\", \"user_agent\", \"email\", \"user_email\", \"server.address\"])\nconst REDACT_KEYS = new Set([\"db.connection_string\", \"db.user\"])\nconst REDACT_PREFIXES = [\"net.peer.\", \"net.sock.\", \"net.host.\", \"network.peer.\", \"network.local.\"]\nconst DROP_SPAN_KEYS = new Set([\"user_agent.original\", \"http.user_agent\", \"client.address\", \"http.client_ip\"])\nconst DROP_SPAN_PREFIXES = [\"http.request.header.\", \"http.response.header.\"]\nconst URL_SPAN_KEYS = new Set([\"url.full\", \"http.url\", \"url\", \"http.target\", \"url.query\", \"http.query\"])\n\nconst SECRETS = Symbol.for(\"@quatronic/sdk.sentry-secret-values\")\ntype SecretHolder = { [SECRETS]?: { values: Set<string>; longestFirst: string[] } }\nconst secretHolder = globalThis as SecretHolder\n\n// On globalThis because a Next app can bundle this module twice: the copy\n// serverEnv() registers into is not necessarily the one beforeSend reads.\nfunction secretState(): NonNullable<SecretHolder[typeof SECRETS]> {\n return (secretHolder[SECRETS] ??= { values: new Set(), longestFirst: [] })\n}\n\nexport function registerSecretValues(values: Iterable<unknown>): void {\n const state = secretState()\n for (const v of values) if (typeof v === \"string\" && v.length >= 8) state.values.add(v)\n state.longestFirst = [...state.values].sort((a, b) => b.length - a.length)\n}\n\nfunction maskSecretValues(s: string): string {\n return secretState().longestFirst.reduce((acc, v) => acc.replaceAll(v, REDACTED), s)\n}\n\nexport function redactText(s: string): string {\n return maskSecretValues(s)\n .replace(URL_USERINFO, `$1${REDACTED}@`)\n .replace(PARAMS_TAIL, \"params: [redacted]\")\n .replace(AUTH_SCHEME, \"$1 [redacted]\")\n .replace(JWT, \"[jwt]\")\n .replace(EMAIL, \"[email]\")\n}\n\nfunction redactQuery(query: string): string {\n return query\n .split(\"&\")\n .map((pair) => {\n const [k, v] = pair.split(\"=\", 2)\n return v !== undefined && SECRET_PARAMS.has(k!.toLowerCase()) ? `${k}=[redacted]` : pair\n })\n .join(\"&\")\n}\n\nfunction redactUrl(url: string): string {\n const i = url.indexOf(\"?\")\n return i < 0 ? url : url.slice(0, i + 1) + redactQuery(url.slice(i + 1))\n}\n\n// For values that are either a URL/path or a bare query string (no `?`).\nfunction redactUrlOrQuery(v: string): string {\n return v.includes(\"?\") ? redactUrl(v) : redactQuery(v)\n}\n\ntype Dict = Record<string, unknown>\n\nexport interface SentryEventLike {\n server_name?: string\n user?: Dict\n request?: { url?: string; query_string?: unknown; cookies?: unknown; headers?: Record<string, string>; data?: unknown }\n message?: string\n exception?: { values?: Array<{ type?: string; value?: string }> }\n breadcrumbs?: Array<{ message?: string; data?: Dict }>\n contexts?: { nextjs?: Dict } & Dict\n}\n\nexport function scrubEvent<E extends SentryEventLike>(e: E): E {\n delete e.server_name\n if (e.user) e.user = e.user.id ? { id: e.user.id } : {}\n if (e.request) {\n delete e.request.cookies\n delete e.request.data\n if (e.request.url) e.request.url = redactUrl(e.request.url)\n if (typeof e.request.query_string === \"string\") e.request.query_string = redactQuery(e.request.query_string)\n if (e.request.headers) {\n e.request.headers = Object.fromEntries(\n Object.entries(e.request.headers).filter(([k]) => !SECRET_HEADERS.has(k.toLowerCase())),\n )\n }\n }\n const nextjs = e.contexts?.nextjs\n if (typeof nextjs?.request_path === \"string\") nextjs.request_path = redactUrl(nextjs.request_path)\n if (e.message) e.message = redactText(e.message)\n for (const v of e.exception?.values ?? []) if (v.value) v.value = redactText(v.value)\n for (const b of e.breadcrumbs ?? []) {\n if (b.message) b.message = redactText(b.message)\n const d = b.data\n if (!d) continue\n for (const k of [\"url\", \"from\", \"to\"]) if (typeof d[k] === \"string\") d[k] = redactUrl(d[k])\n if (typeof d[\"http.query\"] === \"string\") d[\"http.query\"] = redactUrlOrQuery(d[\"http.query\"])\n if (Array.isArray(d.arguments)) d.arguments = d.arguments.map((a) => (typeof a === \"string\" ? redactText(a) : a))\n }\n return e\n}\n\nexport interface SentryLogLike {\n message: string\n attributes?: Dict\n}\n\nexport function scrubLog<L extends SentryLogLike>(l: L): L {\n l.message = redactText(l.message)\n if (l.attributes) {\n const out: Dict = {}\n for (const [k, v] of Object.entries(l.attributes)) {\n if (DROP_LOG_ATTRS.has(k)) continue\n out[k] = typeof v === \"string\" ? redactText(v) : v\n }\n l.attributes = out\n }\n return l\n}\n\nexport interface SentrySpanLike {\n description?: string\n data?: Dict\n}\n\nexport function scrubSpan<S extends SentrySpanLike>(s: S): S {\n // Browser page-metric spans are described by the full page URL.\n if (typeof s.description === \"string\") s.description = redactUrl(s.description)\n for (const [k, v] of Object.entries(s.data ?? {})) {\n if (DROP_SPAN_KEYS.has(k) || DROP_SPAN_PREFIXES.some((p) => k.startsWith(p))) delete s.data![k]\n else if (REDACT_KEYS.has(k) || REDACT_PREFIXES.some((p) => k.startsWith(p))) s.data![k] = REDACTED\n else if (typeof v === \"string\" && URL_SPAN_KEYS.has(k)) s.data![k] = redactUrlOrQuery(v)\n }\n return s\n}\n"],"mappings":";AAAO,IAAM,WAAW;AAKxB,IAAM,QAAQ;AACd,IAAM,eAAe;AACrB,IAAM,MAAM;AACZ,IAAM,cAAc;AACpB,IAAM,cAAc;AACb,IAAM,gBAAqC,oBAAI,IAAI,CAAC,SAAS,QAAQ,SAAS,YAAY,UAAU,OAAO,WAAW,gBAAgB,iBAAiB,UAAU,CAAC;AACzK,IAAM,iBAAiB,oBAAI,IAAI;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,iBAAiB,oBAAI,IAAI,CAAC,MAAM,cAAc,cAAc,SAAS,cAAc,gBAAgB,CAAC;AAC1G,IAAM,cAAc,oBAAI,IAAI,CAAC,wBAAwB,SAAS,CAAC;AAC/D,IAAM,kBAAkB,CAAC,aAAa,aAAa,aAAa,iBAAiB,gBAAgB;AACjG,IAAM,iBAAiB,oBAAI,IAAI,CAAC,uBAAuB,mBAAmB,kBAAkB,gBAAgB,CAAC;AAC7G,IAAM,qBAAqB,CAAC,wBAAwB,uBAAuB;AAC3E,IAAM,gBAAgB,oBAAI,IAAI,CAAC,YAAY,YAAY,OAAO,eAA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";
5
8
 
6
- // src/integrations-core/types.ts
7
- function defineIntegrations(map) {
8
- return map;
9
- }
10
- var AUTH_ENV_FIELDS = {
11
- none: [],
12
- api_key_header: ["apiKey"],
13
- bearer_static: ["token"],
14
- basic: ["username", "password"],
15
- oauth2_client_credentials: ["tokenUrl", "clientId", "clientSecret", "scope", "audience"]
16
- };
17
- var AUTH_SECRET_FIELDS = ["apiKey", "token", "password", "clientSecret"];
18
- var RESERVED_KEY_PREFIX = "QORE_INTEGRATION_";
19
-
20
- // src/integrations-core/env.ts
21
- function refKey(ref) {
22
- return typeof ref === "string" ? ref : ref.key;
23
- }
24
- function refOptional(ref) {
25
- return typeof ref !== "string" && (ref.optional === true || ref.default !== void 0);
26
- }
27
- function authKeys(def) {
28
- const auth = def.auth;
29
- return AUTH_ENV_FIELDS[def.auth.kind].map((field) => auth[field]).filter((key) => typeof key === "string" && key !== "");
30
- }
31
- function requiredKeys(def) {
32
- const keys = [def.baseUrl, ...authKeys(def)];
33
- for (const ref of Object.values(def.config ?? {})) {
34
- if (!refOptional(ref)) keys.push(refKey(ref));
35
- }
36
- return [...new Set(keys)];
37
- }
38
- function allKeys(def) {
39
- const keys = [def.baseUrl, ...authKeys(def)];
40
- for (const ref of Object.values(def.config ?? {})) keys.push(refKey(ref));
41
- return [...new Set(keys)];
42
- }
43
- function readRef(env, ref) {
44
- const value = env[refKey(ref)];
45
- if (value !== void 0 && value !== "") return value;
46
- return typeof ref === "string" ? void 0 : ref.default;
47
- }
48
- function loggingKey(alias) {
49
- return `${RESERVED_KEY_PREFIX}${normalizeAlias(alias)}_LOGGING`;
50
- }
51
- function loggingEnabled(env, alias) {
52
- const value = env[loggingKey(alias)];
53
- return value === "1" || value?.toLowerCase() === "true";
54
- }
55
-
56
- // src/integrations-core/assertIntegrations.ts
57
- var ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/;
58
- function assertIntegrations(map, opts = {}) {
59
- const env = opts.env ?? defaultEnv();
60
- const warn = opts.warn ?? ((message) => console.warn(message));
61
- const problems = [];
62
- for (const [alias, def] of Object.entries(map)) {
63
- for (const key of allKeys(def)) {
64
- let why;
65
- if (key.startsWith(RESERVED_KEY_PREFIX)) {
66
- why = `${RESERVED_KEY_PREFIX}* keys are reserved by the platform`;
67
- } else if (key.startsWith("CONN_")) {
68
- why = "CONN_* keys belong to module connections, not integrations";
69
- } else if (!ENV_KEY_RE.test(key)) {
70
- why = "an env key is uppercase letters, digits and underscores";
71
- }
72
- if (why) {
73
- problems.push({
74
- alias,
75
- key,
76
- code: "reserved_key",
77
- message: `Integration "${alias}" declares env key "${key}": ${why}`
78
- });
79
- }
80
- }
81
- for (const key of requiredKeys(def)) {
82
- const value = env[key];
83
- if (value === void 0 || value === "") {
84
- problems.push({
85
- alias,
86
- key,
87
- code: "missing_env",
88
- message: `Integration "${alias}" is missing env key "${key}"; calls to it will fail until it is set`
89
- });
90
- }
91
- }
92
- }
93
- for (const p of problems) warn(`[integrations] ${p.message}`);
94
- return problems;
95
- }
96
-
97
9
  // src/integrations-core/constants.ts
98
10
  var DEFAULT_INTEGRATION_TIMEOUT_MS = 1e4;
99
11
  var INTEGRATION_SPAN_TYPE = "integration_call";
@@ -426,16 +338,6 @@ function createHandle(alias, definition, envOf) {
426
338
  }
427
339
 
428
340
  export {
429
- defineIntegrations,
430
- AUTH_ENV_FIELDS,
431
- AUTH_SECRET_FIELDS,
432
- RESERVED_KEY_PREFIX,
433
- requiredKeys,
434
- allKeys,
435
- readRef,
436
- loggingKey,
437
- loggingEnabled,
438
- assertIntegrations,
439
341
  DEFAULT_INTEGRATION_TIMEOUT_MS,
440
342
  INTEGRATION_SPAN_TYPE,
441
343
  INTEGRATION_ALIAS_ATTR,
@@ -444,4 +346,4 @@ export {
444
346
  IntegrationError,
445
347
  createIntegrationClient
446
348
  };
447
- //# sourceMappingURL=chunk-2AYDFLKR.js.map
349
+ //# sourceMappingURL=chunk-NMJOF3ZM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/integrations-core/constants.ts","../src/integrations-core/errors.ts","../src/integrations-core/client.ts","../src/integrations-core/base64.ts","../src/integrations-core/oauth2.ts"],"sourcesContent":["/** Default request timeout for integration(alias).request, overridable per call. */\nexport const DEFAULT_INTEGRATION_TIMEOUT_MS = 10_000\n\n/** `qore.span.type` value on an integration call's span. */\nexport const INTEGRATION_SPAN_TYPE = \"integration_call\"\n\n/** OTel span attribute carrying the declared alias, which the portal maps to the integration. */\nexport const INTEGRATION_ALIAS_ATTR = \"qore.integration.alias\"\n\n/** OTel span attribute naming the span's kind, shared with connections (`outbound_call`). */\nexport const INTEGRATION_SPAN_TYPE_ATTR = \"qore.span.type\"\n\n/** A cached OAuth2 token is refreshed this long before it expires. */\nexport const OAUTH_REFRESH_SKEW_MS = 30_000\n","/** Why an integration call refused. */\nexport type IntegrationErrorCode =\n | \"not_declared\" // alias is not a key of the declared map\n | \"missing_env\" // a required env key for the alias is unset or empty\n | \"reserved_key\" // unused since assertIntegrations reports instead of throwing; kept so the type does not narrow\n | \"absolute_url\" // request() was given a full URL, which would bypass the declared base\n | \"missing_param\" // a `{name}` in the path template has no value in `params`\n | \"token_failed\" // the OAuth2 token endpoint refused, or answered without an access_token\n\n/**\n * Single error shape for the integrations subpath, mirroring ConnectionError.\n * Every code here is a configuration or programming error on the app's side,\n * so `status` defaults to 500.\n */\nexport class IntegrationError extends Error {\n readonly code: IntegrationErrorCode\n readonly status: number\n\n constructor(code: IntegrationErrorCode, opts?: { message?: string; status?: number }) {\n super(opts?.message ?? code)\n this.name = \"IntegrationError\"\n this.code = code\n this.status = opts?.status ?? 500\n }\n}\n","import { SpanStatusCode, trace } from \"@opentelemetry/api\"\nimport { defaultEnv, type Env } from \"../connections-core/env\"\nimport { toBase64 } from \"./base64\"\nimport {\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n INTEGRATION_ALIAS_ATTR,\n INTEGRATION_SPAN_TYPE,\n INTEGRATION_SPAN_TYPE_ATTR,\n} from \"./constants\"\nimport { loggingEnabled, readRef } from \"./env\"\nimport { IntegrationError } from \"./errors\"\nimport { getClientCredentialsToken } from \"./oauth2\"\nimport type { EnvRef, IntegrationDefinition, IntegrationMap } from \"./types\"\n\nexport type ParamValue = string | number | boolean\n\nexport interface IntegrationRequest {\n /** Values for the `{name}` placeholders in the path template; each is URI-encoded. */\n params?: Record<string, ParamValue>\n /** Query string, appended with URLSearchParams; `undefined` entries are skipped. */\n query?: Record<string, ParamValue | undefined>\n /**\n * Request body. A string, FormData, Blob, ArrayBuffer, typed array or\n * URLSearchParams is sent as is; anything else is JSON-encoded with\n * `content-type: application/json` unless the caller set one.\n */\n body?: unknown\n headers?: HeadersInit\n timeoutMs?: number\n signal?: AbortSignal\n}\n\n/** The resolved values of a definition's `config` refs, by their logical name. */\nexport type IntegrationConfig<D extends IntegrationDefinition> = D extends {\n config: infer C extends Record<string, EnvRef>\n}\n ? { [K in keyof C]: string | number | boolean | undefined }\n : Record<string, never>\n\nexport interface IntegrationHandle<D extends IntegrationDefinition = IntegrationDefinition> {\n readonly alias: string\n readonly definition: D\n /** The `config` refs read from env, defaults applied. */\n config(): IntegrationConfig<D>\n /**\n * One call against the declared base URL. `pathTemplate` is relative and\n * may hold `{name}` placeholders filled from `params`; an absolute URL is\n * refused so the integration cannot be pointed somewhere else per call.\n */\n request(method: string, pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n get(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n post(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n put(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n patch(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n delete(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n}\n\n/**\n * `integration(alias)`, typed against the declared map so an alias that is\n * not a key fails to compile.\n */\nexport type IntegrationClient<M extends IntegrationMap> = <K extends keyof M & string>(\n alias: K,\n) => IntegrationHandle<M[K]>\n\nconst PLACEHOLDER_RE = /\\{([^{}]+)\\}/g\n\nfunction isRawBody(body: unknown): body is BodyInit {\n if (typeof body === \"string\") return true\n if (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) return true\n if (typeof FormData !== \"undefined\" && body instanceof FormData) return true\n if (typeof Blob !== \"undefined\" && body instanceof Blob) return true\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return true\n return false\n}\n\n/**\n * Bind a declared map to an env. The app calls this once in\n * `src/config/integrations.ts` and exports the result as `integration`:\n *\n * export const integrations = defineIntegrations({ sap: { ... } })\n * export const integration = createIntegrationClient(integrations)\n *\n * const res = await integration(\"sap\").get(\"/A_SalesOrder('{id}')\", { params: { id } })\n *\n * There is no global registry on purpose: a handle only exists for an alias\n * the map declares, which is what lets the portal trust the declaration.\n */\nexport function createIntegrationClient<M extends IntegrationMap>(\n map: M,\n opts: { env?: Env } = {},\n): IntegrationClient<M> {\n const envOf = (): Env => opts.env ?? defaultEnv()\n\n return <K extends keyof M & string>(alias: K): IntegrationHandle<M[K]> => {\n const definition = map[alias]\n if (!definition) {\n throw new IntegrationError(\"not_declared\", {\n message: `Integration \"${alias}\" is not declared; declared: ${Object.keys(map).join(\", \") || \"(none)\"}`,\n })\n }\n return createHandle(alias, definition, envOf)\n }\n}\n\nfunction createHandle<D extends IntegrationDefinition>(\n alias: string,\n definition: D,\n envOf: () => Env,\n): IntegrationHandle<D> {\n function required(env: Env, key: string): string {\n const value = env[key]\n if (value === undefined || value === \"\") {\n throw new IntegrationError(\"missing_env\", {\n message: `Integration \"${alias}\" is missing ${key}`,\n })\n }\n return value\n }\n\n async function authHeaders(env: Env, headers: Headers, timeoutMs: number): Promise<void> {\n const auth = definition.auth\n switch (auth.kind) {\n case \"none\":\n return\n case \"api_key_header\":\n headers.set(auth.header, required(env, auth.apiKey))\n return\n case \"bearer_static\":\n headers.set(\"authorization\", `Bearer ${required(env, auth.token)}`)\n return\n case \"basic\":\n headers.set(\n \"authorization\",\n `Basic ${toBase64(`${required(env, auth.username)}:${required(env, auth.password)}`)}`,\n )\n return\n case \"oauth2_client_credentials\": {\n const token = await getClientCredentialsToken(alias, auth, env, timeoutMs)\n headers.set(\"authorization\", `Bearer ${token}`)\n return\n }\n }\n }\n\n async function request(\n method: string,\n pathTemplate: string,\n req: IntegrationRequest = {},\n ): Promise<Response> {\n const env = envOf()\n const METHOD = method.toUpperCase()\n const base = required(env, definition.baseUrl)\n\n // The declaration is the one place that says where this integration\n // lives. A full URL per call would make the handle an arbitrary-request\n // primitive that carries the integration's credentials to whatever host\n // it names, so unlike connection().fetch this refuses from day one.\n if (/^https?:\\/\\//i.test(pathTemplate)) {\n throw new IntegrationError(\"absolute_url\", {\n message: `Integration \"${alias}\" was given an absolute URL; pass a path relative to ${definition.baseUrl}`,\n })\n }\n\n const path = pathTemplate.replace(PLACEHOLDER_RE, (_match, name: string) => {\n const value = req.params?.[name]\n if (value === undefined) {\n throw new IntegrationError(\"missing_param\", {\n message: `Integration \"${alias}\": path \"${pathTemplate}\" needs params.${name}`,\n })\n }\n return encodeURIComponent(String(value))\n })\n\n let url = base.replace(/\\/+$/, \"\") + \"/\" + path.replace(/^\\/+/, \"\")\n if (req.query) {\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(req.query)) {\n if (value !== undefined) search.append(key, String(value))\n }\n const qs = search.toString()\n if (qs) url += (url.includes(\"?\") ? \"&\" : \"?\") + qs\n }\n\n const { timeoutMs = DEFAULT_INTEGRATION_TIMEOUT_MS, signal: caller } = req\n const headers = new Headers(req.headers)\n\n let body: BodyInit | undefined\n if (req.body !== undefined) {\n if (isRawBody(req.body)) {\n body = req.body\n } else {\n body = JSON.stringify(req.body)\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n }\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n if (caller) {\n if (caller.aborted) controller.abort()\n else caller.addEventListener(\"abort\", () => controller.abort(), { once: true })\n }\n\n const log = loggingEnabled(env, alias)\n const startedAt = Date.now()\n const tracer = trace.getTracer(\"@quatronic/sdk\")\n // Named after the template, not the expanded path, so the portal can group\n // calls per endpoint; the alias attribute is what it maps to the declaration.\n return tracer.startActiveSpan(\n `→ ${alias} ${METHOD} ${pathTemplate}`,\n {\n attributes: {\n [INTEGRATION_SPAN_TYPE_ATTR]: INTEGRATION_SPAN_TYPE,\n [INTEGRATION_ALIAS_ATTR]: alias,\n \"url.template\": pathTemplate,\n \"http.request.method\": METHOD,\n },\n },\n async (span) => {\n try {\n await authHeaders(env, headers, timeoutMs)\n const res = await fetch(url, { method: METHOD, headers, body, signal: controller.signal })\n span.setAttribute(\"http.response.status_code\", res.status)\n if (res.status >= 500) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${res.status}` })\n }\n if (log) {\n // Alias, method, template, status, duration. Never the URL (it may\n // carry ids), never headers (credentials), never a body.\n console.info(\n JSON.stringify({\n level: \"info\",\n event: \"qore.integration.call\",\n alias,\n method: METHOD,\n template: pathTemplate,\n status: res.status,\n durationMs: Date.now() - startedAt,\n }),\n )\n }\n return res\n } catch (err) {\n span.recordException(err as Error)\n span.setStatus({ code: SpanStatusCode.ERROR })\n if (log) {\n console.info(\n JSON.stringify({\n level: \"info\",\n event: \"qore.integration.call\",\n alias,\n method: METHOD,\n template: pathTemplate,\n status: null,\n error: (err as Error)?.name ?? \"Error\",\n durationMs: Date.now() - startedAt,\n }),\n )\n }\n throw err\n } finally {\n span.end()\n clearTimeout(timer)\n }\n },\n )\n }\n\n return {\n alias,\n definition,\n config() {\n const env = envOf()\n const out: Record<string, string | number | boolean | undefined> = {}\n for (const [name, ref] of Object.entries(definition.config ?? {})) {\n out[name] = readRef(env, ref)\n }\n return out as IntegrationConfig<D>\n },\n request,\n get: (path, req) => request(\"GET\", path, req),\n post: (path, req) => request(\"POST\", path, req),\n put: (path, req) => request(\"PUT\", path, req),\n patch: (path, req) => request(\"PATCH\", path, req),\n delete: (path, req) => request(\"DELETE\", path, req),\n }\n}\n","/**\n * Base64 for the `Authorization: Basic` header. `Buffer` on Node, which is\n * where an integration call runs (a route handler, a server action, a backend\n * job); `btoa` as the edge fallback, which is Latin-1 only — a credential with\n * characters outside that range needs the node runtime.\n */\nexport function toBase64(text: string): string {\n if (typeof Buffer !== \"undefined\") return Buffer.from(text, \"utf8\").toString(\"base64\")\n return btoa(text)\n}\n","import { SpanStatusCode, trace } from \"@opentelemetry/api\"\nimport type { Env } from \"../connections-core/env\"\nimport { toBase64 } from \"./base64\"\nimport {\n INTEGRATION_ALIAS_ATTR,\n INTEGRATION_SPAN_TYPE,\n INTEGRATION_SPAN_TYPE_ATTR,\n OAUTH_REFRESH_SKEW_MS,\n} from \"./constants\"\nimport { IntegrationError } from \"./errors\"\nimport type { IntegrationAuth } from \"./types\"\n\nexport type OAuth2ClientCredentials = Extract<IntegrationAuth, { kind: \"oauth2_client_credentials\" }>\n\ninterface CacheEntry {\n accessToken?: string\n expiresAt: number\n inFlight?: Promise<string>\n}\n\n/** When `expires_in` is absent, assume a short-lived token rather than a permanent one. */\nconst DEFAULT_EXPIRES_IN_S = 300\n\n/**\n * One cache per process, keyed on what makes a token distinct. Two aliases\n * pointing at the same token endpoint with the same client share one token,\n * which is what the issuer would hand out anyway.\n */\nconst cache = new Map<string, CacheEntry>()\n\n/** Test-only: forget every cached token. Not exported from the public barrels. */\nexport function __resetIntegrationTokenCache(): void {\n cache.clear()\n}\n\nfunction required(env: Env, alias: string, key: string): string {\n const value = env[key]\n if (value === undefined || value === \"\") {\n throw new IntegrationError(\"missing_env\", {\n message: `Integration \"${alias}\" is missing ${key}`,\n })\n }\n return value\n}\n\nfunction optional(env: Env, key: string | undefined): string | undefined {\n if (!key) return undefined\n const value = env[key]\n return value === \"\" ? undefined : value\n}\n\n/**\n * A bearer token for an OAuth2 client-credentials integration: cached until\n * shortly before it expires, fetched once when several calls race for it.\n * The token request gets its own span (`→ <alias> token`) so a slow or\n * refusing issuer shows up as itself, not as a slow API call.\n */\nexport async function getClientCredentialsToken(\n alias: string,\n auth: OAuth2ClientCredentials,\n env: Env,\n timeoutMs: number,\n): Promise<string> {\n const tokenUrl = required(env, alias, auth.tokenUrl)\n const clientId = required(env, alias, auth.clientId)\n const clientSecret = required(env, alias, auth.clientSecret)\n const scope = optional(env, auth.scope)\n const audience = optional(env, auth.audience)\n\n const key = `${tokenUrl}|${clientId}|${scope ?? \"\"}|${audience ?? \"\"}`\n const entry = cache.get(key)\n if (entry?.accessToken && entry.expiresAt - OAUTH_REFRESH_SKEW_MS > Date.now()) {\n return entry.accessToken\n }\n if (entry?.inFlight) return entry.inFlight\n\n const inFlight = fetchToken(alias, {\n tokenUrl,\n clientId,\n clientSecret,\n scope,\n audience,\n credentialsIn: auth.credentialsIn ?? \"header\",\n timeoutMs,\n })\n .then((token) => {\n cache.set(key, { accessToken: token.accessToken, expiresAt: token.expiresAt })\n return token.accessToken\n })\n .catch((err: unknown) => {\n // Keep whatever was cached (possibly still usable within the skew), drop the in-flight marker.\n const current = cache.get(key)\n if (current?.inFlight === inFlight) {\n if (current.accessToken) cache.set(key, { accessToken: current.accessToken, expiresAt: current.expiresAt })\n else cache.delete(key)\n }\n throw err\n })\n cache.set(key, { ...(entry ?? { expiresAt: 0 }), inFlight })\n return inFlight\n}\n\ninterface TokenRequest {\n tokenUrl: string\n clientId: string\n clientSecret: string\n scope?: string\n audience?: string\n credentialsIn: \"header\" | \"body\"\n timeoutMs: number\n}\n\nasync function fetchToken(\n alias: string,\n req: TokenRequest,\n): Promise<{ accessToken: string; expiresAt: number }> {\n const form = new URLSearchParams({ grant_type: \"client_credentials\" })\n if (req.scope) form.set(\"scope\", req.scope)\n if (req.audience) form.set(\"audience\", req.audience)\n const headers = new Headers({\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\",\n })\n if (req.credentialsIn === \"body\") {\n form.set(\"client_id\", req.clientId)\n form.set(\"client_secret\", req.clientSecret)\n } else {\n headers.set(\"authorization\", `Basic ${toBase64(`${req.clientId}:${req.clientSecret}`)}`)\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), req.timeoutMs)\n\n const tracer = trace.getTracer(\"@quatronic/sdk\")\n return tracer.startActiveSpan(\n `→ ${alias} token`,\n {\n attributes: {\n [INTEGRATION_SPAN_TYPE_ATTR]: INTEGRATION_SPAN_TYPE,\n [INTEGRATION_ALIAS_ATTR]: alias,\n \"http.request.method\": \"POST\",\n },\n },\n async (span) => {\n try {\n const res = await fetch(req.tokenUrl, {\n method: \"POST\",\n headers,\n body: form.toString(),\n signal: controller.signal,\n })\n span.setAttribute(\"http.response.status_code\", res.status)\n if (!res.ok) {\n // Status only. The issuer's body can echo the request, credentials included.\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${res.status}` })\n throw new IntegrationError(\"token_failed\", {\n message: `OAuth2 token request for \"${alias}\" failed with HTTP ${res.status}`,\n })\n }\n let payload: unknown\n try {\n payload = await res.json()\n } catch {\n payload = undefined\n }\n const body = (payload ?? {}) as { access_token?: unknown; expires_in?: unknown }\n if (typeof body.access_token !== \"string\" || body.access_token === \"\") {\n span.setStatus({ code: SpanStatusCode.ERROR, message: \"no access_token\" })\n throw new IntegrationError(\"token_failed\", {\n message: `OAuth2 token response for \"${alias}\" carried no access_token`,\n })\n }\n const expiresIn = Number(body.expires_in)\n const seconds = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : DEFAULT_EXPIRES_IN_S\n return { accessToken: body.access_token, expiresAt: Date.now() + seconds * 1000 }\n } catch (err) {\n if (!(err instanceof IntegrationError)) {\n span.recordException(err as Error)\n span.setStatus({ code: SpanStatusCode.ERROR })\n }\n throw err\n } finally {\n span.end()\n clearTimeout(timer)\n }\n },\n )\n}\n"],"mappings":";;;;;;;;;AACO,IAAM,iCAAiC;AAGvC,IAAM,wBAAwB;AAG9B,IAAM,yBAAyB;AAG/B,IAAM,6BAA6B;AAGnC,IAAM,wBAAwB;;;ACC9B,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACA;AAAA,EAET,YAAY,MAA4B,MAA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AO,QAAQ,WAAW,UAAU,CAAC,CAAC,GAAG;AACjE,YAAI,IAAI,IAAI,QAAQ,KAAK,GAAG;AAAA,MAC9B;AACA,aAAO;AAAA,IACT;AAAA,IACA;AAAA,IACA,KAAK,CAAC,MAAM,QAAQ,QAAQ,OAAO,MAAM,GAAG;AAAA,IAC5C,MAAM,CAAC,MAAM,QAAQ,QAAQ,QAAQ,MAAM,GAAG;AAAA,IAC9C,KAAK,CAAC,MAAM,QAAQ,QAAQ,OAAO,MAAM,GAAG;AAAA,IAC5C,OAAO,CAAC,MAAM,QAAQ,QAAQ,SAAS,MAAM,GAAG;AAAA,IAChD,QAAQ,CAAC,MAAM,QAAQ,QAAQ,UAAU,MAAM,GAAG;AAAA,EACpD;AACF;","names":["SpanStatusCode","trace","required","trace","SpanStatusCode"]}
@@ -0,0 +1,65 @@
1
+ import {
2
+ parseJsonBounded
3
+ } from "./chunk-FUPTRHT7.js";
4
+
5
+ // src/security-core/cspReport.ts
6
+ var DEFAULT_MAX_BYTES = 16 * 1024;
7
+ function asRecord(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
9
+ }
10
+ function asString(value) {
11
+ return typeof value === "string" && value.length > 0 ? value.slice(0, 500) : void 0;
12
+ }
13
+ function collectReports(payload) {
14
+ const single = asRecord(payload);
15
+ if (single) {
16
+ const nested = asRecord(single["csp-report"]);
17
+ return nested ? [nested] : [single];
18
+ }
19
+ if (Array.isArray(payload)) {
20
+ return payload.map((entry) => asRecord(asRecord(entry)?.["body"])).filter((report) => report !== void 0);
21
+ }
22
+ return [];
23
+ }
24
+ function readCspReport(report) {
25
+ return {
26
+ documentUri: asString(report["document-uri"] ?? report["documentURL"]),
27
+ blockedUri: asString(report["blocked-uri"] ?? report["blockedURL"]),
28
+ effectiveDirective: asString(report["effective-directive"] ?? report["effectiveDirective"]),
29
+ disposition: asString(report["disposition"])
30
+ };
31
+ }
32
+ var QORE_CSP_REPORT_URI = "/api/qore/csp-report";
33
+ function createCspReportRoute(options) {
34
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
35
+ const log = options.log;
36
+ return async function POST(request) {
37
+ const noContent = () => new Response(null, { status: 204 });
38
+ let body;
39
+ try {
40
+ body = await request.text();
41
+ } catch {
42
+ return noContent();
43
+ }
44
+ if (body.length === 0 || body.length > maxBytes) {
45
+ return noContent();
46
+ }
47
+ let payload;
48
+ try {
49
+ payload = parseJsonBounded(body, { maxBytes, maxDepth: 8 });
50
+ } catch {
51
+ return noContent();
52
+ }
53
+ for (const report of collectReports(payload)) {
54
+ log.warn({ event: "csp.violation", ...readCspReport(report) });
55
+ }
56
+ return noContent();
57
+ };
58
+ }
59
+
60
+ export {
61
+ readCspReport,
62
+ QORE_CSP_REPORT_URI,
63
+ createCspReportRoute
64
+ };
65
+ //# sourceMappingURL=chunk-P7HNHLW7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security-core/cspReport.ts"],"sourcesContent":["import { parseJsonBounded } from \"./parse\"\n\n/**\n * The `report-uri` endpoint for the QDC Content-Security-Policy.\n *\n * The policy ships report-only for its first release, so this endpoint is the\n * evidence: it records what the policy *would* have blocked, so the policy can\n * be corrected before it enforces. It collects and nothing else — one log line\n * per report, forwarded nowhere.\n *\n * It is unauthenticated by necessity: a browser posts a report with no session\n * and no CSRF token. So it reads a small bounded body and logs a fixed set of\n * fields rather than whatever the report happens to contain, and it answers 204\n * whatever happens — an error status only teaches a caller that the endpoint is\n * worth probing.\n */\n\n/** A report is a few hundred bytes. Anything near this is not a browser. */\nconst DEFAULT_MAX_BYTES = 16 * 1024\n\n/** Just enough of a logger. `@/lib/log` in a generated app satisfies it. */\nexport interface CspReportLogger {\n warn(fields: Record<string, unknown>): void\n}\n\n/** The fields read off a violation report, whichever wire format it arrived in. */\nexport interface CspReportFields {\n documentUri?: string\n blockedUri?: string\n effectiveDirective?: string\n disposition?: string\n}\n\nexport interface CspReportRouteOptions {\n /** Where the violations go. One `warn` per report, `event: \"csp.violation\"`. */\n log: CspReportLogger\n /** Request bodies above this are dropped unread. Default: 16 KiB. */\n maxBytes?: number\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value.slice(0, 500) : undefined\n}\n\n/** Both wire formats: `report-uri`'s `{\"csp-report\": {…}}` and `report-to`'s array. */\nfunction collectReports(payload: unknown): Record<string, unknown>[] {\n const single = asRecord(payload)\n if (single) {\n const nested = asRecord(single[\"csp-report\"])\n return nested ? [nested] : [single]\n }\n if (Array.isArray(payload)) {\n return payload\n .map((entry) => asRecord(asRecord(entry)?.[\"body\"]))\n .filter((report): report is Record<string, unknown> => report !== undefined)\n }\n return []\n}\n\n/** The two field namings, hyphenated (`report-uri`) and camel (`report-to`). */\nexport function readCspReport(report: Record<string, unknown>): CspReportFields {\n return {\n documentUri: asString(report[\"document-uri\"] ?? report[\"documentURL\"]),\n blockedUri: asString(report[\"blocked-uri\"] ?? report[\"blockedURL\"]),\n effectiveDirective: asString(report[\"effective-directive\"] ?? report[\"effectiveDirective\"]),\n disposition: asString(report[\"disposition\"]),\n }\n}\n\n/** Where the platform's catch-all route (`@quatronic/sdk/next/platform`) receives CSP reports. */\nexport const QORE_CSP_REPORT_URI = \"/api/qore/csp-report\"\n\n/**\n * Build the `POST` handler for `src/app/api/csp-report/route.ts`.\n *\n * The route file still declares `runtime` and `dynamic` itself: Next reads\n * those two exports statically, off the route module, and does not follow them\n * through a package boundary.\n */\nexport function createCspReportRoute(\n options: CspReportRouteOptions,\n): (request: Request) => Promise<Response> {\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES\n const log = options.log\n\n return async function POST(request: Request): Promise<Response> {\n const noContent = () => new Response(null, { status: 204 })\n\n let body: string\n try {\n body = await request.text()\n } catch {\n return noContent()\n }\n if (body.length === 0 || body.length > maxBytes) {\n return noContent()\n }\n\n let payload: unknown\n try {\n payload = parseJsonBounded(body, { maxBytes, maxDepth: 8 })\n } catch {\n return noContent()\n }\n\n for (const report of collectReports(payload)) {\n log.warn({ event: \"csp.violation\", ...readCspReport(report) })\n }\n return noContent()\n }\n}\n"],"mappings":";;;;;AAkBA,IAAM,oBAAoB,KAAK;AAsB/B,SAAS,SAAS,OAAqD;AACrE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IACrE,QACD;AACN;AAEA,SAAS,SAAS,OAAoC;AACpD,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,MAAM,MAAM,GAAG,GAAG,IAAI;AAC/E;AAGA,SAAS,eAAe,SAA6C;AACnE,QAAM,SAAS,SAAS,OAAO;AAC/B,MAAI,QAAQ;AACV,UAAM,SAAS,SAAS,OAAO,YAAY,CAAC;AAC5C,WAAO,SAAS,CAAC,MAAM,IAAI,CAAC,MAAM;AAAA,EACpC;AACA,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,WAAO,QACJ,IAAI,CAAC,UAAU,SAAS,SAAS,KAAK,IAAI,MAAM,CAAC,CAAC,EAClD,OAAO,CAAC,WAA8C,WAAW,MAAS;AAAA,EAC/E;AACA,SAAO,CAAC;AACV;AAGO,SAAS,cAAc,QAAkD;AAC9E,SAAO;AAAA,IACL,aAAa,SAAS,OAAO,cAAc,KAAK,OAAO,aAAa,CAAC;AAAA,IACrE,YAAY,SAAS,OAAO,aAAa,KAAK,OAAO,YAAY,CAAC;AAAA,IAClE,oBAAoB,SAAS,OAAO,qBAAqB,KAAK,OAAO,oBAAoB,CAAC;AAAA,IAC1F,aAAa,SAAS,OAAO,aAAa,CAAC;AAAA,EAC7C;AACF;AAGO,IAAM,sBAAsB;AAS5B,SAAS,qBACd,SACyC;AACzC,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,MAAM,QAAQ;AAEpB,SAAO,eAAe,KAAK,SAAqC;AAC9D,UAAM,YAAY,MAAM,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAE1D,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,QAAQ,KAAK;AAAA,IAC5B,QAAQ;AACN,aAAO,UAAU;AAAA,IACnB;AACA,QAAI,KAAK,WAAW,KAAK,KAAK,SAAS,UAAU;AAC/C,aAAO,UAAU;AAAA,IACnB;AAEA,QAAI;AACJ,QAAI;AACF,gBAAU,iBAAiB,MAAM,EAAE,UAAU,UAAU,EAAE,CAAC;AAAA,IAC5D,QAAQ;AACN,aAAO,UAAU;AAAA,IACnB;AAEA,eAAW,UAAU,eAAe,OAAO,GAAG;AAC5C,UAAI,KAAK,EAAE,OAAO,iBAAiB,GAAG,cAAc,MAAM,EAAE,CAAC;AAAA,IAC/D;AACA,WAAO,UAAU;AAAA,EACnB;AACF;","names":[]}
@@ -0,0 +1,20 @@
1
+ import {
2
+ initSentry
3
+ } from "./chunk-YFZB5EW6.js";
4
+ import {
5
+ readSentryConfig
6
+ } from "./chunk-7ASQHY7O.js";
7
+
8
+ // src/next/sentry/register.ts
9
+ import * as Sentry from "@sentry/nextjs";
10
+ async function register() {
11
+ const runtime = process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
12
+ initSentry(Sentry, runtime, readSentryConfig(process.env, { frontend: true }));
13
+ }
14
+ var onRequestError = Sentry.captureRequestError;
15
+
16
+ export {
17
+ register,
18
+ onRequestError
19
+ };
20
+ //# sourceMappingURL=chunk-POZI4OKJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next/sentry/register.ts"],"sourcesContent":["import * as Sentry from \"@sentry/nextjs\"\nimport { readSentryConfig } from \"../../sentry-core/env\"\nimport { initSentry } from \"../../sentry-core/init\"\n\nexport async function register(): Promise<void> {\n const runtime = process.env.NEXT_RUNTIME === \"edge\" ? \"edge\" : \"node\"\n initSentry(Sentry, runtime, readSentryConfig(process.env, { frontend: true }))\n}\n\nexport const onRequestError = Sentry.captureRequestError\n"],"mappings":";;;;;;;;AAAA,YAAY,YAAY;AAIxB,eAAsB,WAA0B;AAC9C,QAAM,UAAU,QAAQ,IAAI,iBAAiB,SAAS,SAAS;AAC/D,aAAW,QAAQ,SAAS,iBAAiB,QAAQ,KAAK,EAAE,UAAU,KAAK,CAAC,CAAC;AAC/E;AAEO,IAAM,iBAAwB;","names":[]}