@superbased/sdk 0.0.0-stage → 0.1.0

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 (119) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +438 -2
  4. package/dist/cjs/admit.d.ts +139 -0
  5. package/dist/cjs/admit.js +442 -0
  6. package/dist/cjs/admit.js.map +1 -0
  7. package/dist/cjs/attrs.d.ts +113 -0
  8. package/dist/cjs/attrs.js +183 -0
  9. package/dist/cjs/attrs.js.map +1 -0
  10. package/dist/cjs/config.d.ts +202 -0
  11. package/dist/cjs/config.js +386 -0
  12. package/dist/cjs/config.js.map +1 -0
  13. package/dist/cjs/context.d.ts +102 -0
  14. package/dist/cjs/context.js +234 -0
  15. package/dist/cjs/context.js.map +1 -0
  16. package/dist/cjs/control.d.ts +99 -0
  17. package/dist/cjs/control.js +243 -0
  18. package/dist/cjs/control.js.map +1 -0
  19. package/dist/cjs/cost.d.ts +108 -0
  20. package/dist/cjs/cost.js +211 -0
  21. package/dist/cjs/cost.js.map +1 -0
  22. package/dist/cjs/destination.d.ts +125 -0
  23. package/dist/cjs/destination.js +357 -0
  24. package/dist/cjs/destination.js.map +1 -0
  25. package/dist/cjs/experiments.d.ts +237 -0
  26. package/dist/cjs/experiments.js +678 -0
  27. package/dist/cjs/experiments.js.map +1 -0
  28. package/dist/cjs/export.d.ts +84 -0
  29. package/dist/cjs/export.js +328 -0
  30. package/dist/cjs/export.js.map +1 -0
  31. package/dist/cjs/index.d.ts +168 -0
  32. package/dist/cjs/index.js +581 -0
  33. package/dist/cjs/index.js.map +1 -0
  34. package/dist/cjs/instrument.d.ts +88 -0
  35. package/dist/cjs/instrument.js +397 -0
  36. package/dist/cjs/instrument.js.map +1 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/policy.d.ts +77 -0
  39. package/dist/cjs/policy.js +252 -0
  40. package/dist/cjs/policy.js.map +1 -0
  41. package/dist/cjs/prompts.d.ts +175 -0
  42. package/dist/cjs/prompts.js +476 -0
  43. package/dist/cjs/prompts.js.map +1 -0
  44. package/dist/cjs/propagation.d.ts +34 -0
  45. package/dist/cjs/propagation.js +151 -0
  46. package/dist/cjs/propagation.js.map +1 -0
  47. package/dist/cjs/req.d.ts +10 -0
  48. package/dist/cjs/req.js +3 -0
  49. package/dist/cjs/req.js.map +1 -0
  50. package/dist/cjs/runtime.d.ts +44 -0
  51. package/dist/cjs/runtime.js +67 -0
  52. package/dist/cjs/runtime.js.map +1 -0
  53. package/dist/cjs/scores.d.ts +102 -0
  54. package/dist/cjs/scores.js +226 -0
  55. package/dist/cjs/scores.js.map +1 -0
  56. package/dist/cjs/spans.d.ts +193 -0
  57. package/dist/cjs/spans.js +398 -0
  58. package/dist/cjs/spans.js.map +1 -0
  59. package/dist/cjs/vendor.d.ts +33 -0
  60. package/dist/cjs/vendor.js +67 -0
  61. package/dist/cjs/vendor.js.map +1 -0
  62. package/dist/esm/admit.d.ts +139 -0
  63. package/dist/esm/admit.js +432 -0
  64. package/dist/esm/admit.js.map +1 -0
  65. package/dist/esm/attrs.d.ts +113 -0
  66. package/dist/esm/attrs.js +179 -0
  67. package/dist/esm/attrs.js.map +1 -0
  68. package/dist/esm/config.d.ts +202 -0
  69. package/dist/esm/config.js +364 -0
  70. package/dist/esm/config.js.map +1 -0
  71. package/dist/esm/context.d.ts +102 -0
  72. package/dist/esm/context.js +221 -0
  73. package/dist/esm/context.js.map +1 -0
  74. package/dist/esm/control.d.ts +99 -0
  75. package/dist/esm/control.js +230 -0
  76. package/dist/esm/control.js.map +1 -0
  77. package/dist/esm/cost.d.ts +108 -0
  78. package/dist/esm/cost.js +202 -0
  79. package/dist/esm/cost.js.map +1 -0
  80. package/dist/esm/destination.d.ts +125 -0
  81. package/dist/esm/destination.js +346 -0
  82. package/dist/esm/destination.js.map +1 -0
  83. package/dist/esm/experiments.d.ts +237 -0
  84. package/dist/esm/experiments.js +666 -0
  85. package/dist/esm/experiments.js.map +1 -0
  86. package/dist/esm/export.d.ts +84 -0
  87. package/dist/esm/export.js +314 -0
  88. package/dist/esm/export.js.map +1 -0
  89. package/dist/esm/index.d.ts +168 -0
  90. package/dist/esm/index.js +500 -0
  91. package/dist/esm/index.js.map +1 -0
  92. package/dist/esm/instrument.d.ts +88 -0
  93. package/dist/esm/instrument.js +391 -0
  94. package/dist/esm/instrument.js.map +1 -0
  95. package/dist/esm/policy.d.ts +77 -0
  96. package/dist/esm/policy.js +240 -0
  97. package/dist/esm/policy.js.map +1 -0
  98. package/dist/esm/prompts.d.ts +175 -0
  99. package/dist/esm/prompts.js +460 -0
  100. package/dist/esm/prompts.js.map +1 -0
  101. package/dist/esm/propagation.d.ts +34 -0
  102. package/dist/esm/propagation.js +145 -0
  103. package/dist/esm/propagation.js.map +1 -0
  104. package/dist/esm/req.d.ts +10 -0
  105. package/dist/esm/req.js +2 -0
  106. package/dist/esm/req.js.map +1 -0
  107. package/dist/esm/runtime.d.ts +44 -0
  108. package/dist/esm/runtime.js +59 -0
  109. package/dist/esm/runtime.js.map +1 -0
  110. package/dist/esm/scores.d.ts +102 -0
  111. package/dist/esm/scores.js +219 -0
  112. package/dist/esm/scores.js.map +1 -0
  113. package/dist/esm/spans.d.ts +193 -0
  114. package/dist/esm/spans.js +378 -0
  115. package/dist/esm/spans.js.map +1 -0
  116. package/dist/esm/vendor.d.ts +33 -0
  117. package/dist/esm/vendor.js +61 -0
  118. package/dist/esm/vendor.js.map +1 -0
  119. package/package.json +130 -4
@@ -0,0 +1,386 @@
1
+ "use strict";
2
+ /**
3
+ * SDK settings: one options object, each field mapped to an env var.
4
+ *
5
+ * Resolution for every field: explicit `init()` option, then the
6
+ * `SUPERBASED_*` variable, then the standard OpenTelemetry variable (where
7
+ * one exists), then (destination, gateway URL and credential only) what the
8
+ * local Observer advertises, then the default. Pure over an env record, so it
9
+ * is testable without touching `process.env`.
10
+ *
11
+ * Export goes to a list of destinations (endpoint, headers, timeout each):
12
+ * this machine's Observer, the org or SaaS gateway, or both (D18, contract
13
+ * `contracts/destination.md`). `destinations()` turns the resolved choice
14
+ * into that list; destination.ts makes the choice.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ONLINE_FIX = exports.DESTINATION_CHOICES = exports.TRACES_PATH = exports.DEFAULT_PROMPT_CACHE_TTL_MS = exports.DEFAULT_API_TIMEOUT_MS = exports.DEFAULT_DISCOVER_TIMEOUT_MS = exports.DEFAULT_NODE_URL = exports.DEFAULT_SHUTDOWN_TIMEOUT_MS = exports.DEFAULT_EXPORT_TIMEOUT_MS = exports.DEFAULT_MAX_CONTENT_CHARS = exports.DEFAULT_SERVICE_NAME = exports.DEFAULT_ENDPOINT = void 0;
18
+ exports.envFlag = envFlag;
19
+ exports.parseKvList = parseKvList;
20
+ exports.parseList = parseList;
21
+ exports.resolveEndpoint = resolveEndpoint;
22
+ exports.resolveEndpointWithSource = resolveEndpointWithSource;
23
+ exports.resolveHeaders = resolveHeaders;
24
+ exports.resolveServiceName = resolveServiceName;
25
+ exports.resolveSampling = resolveSampling;
26
+ exports.resolveDestinationChoice = resolveDestinationChoice;
27
+ exports.trimSlash = trimSlash;
28
+ exports.resolveSettings = resolveSettings;
29
+ exports.onlineTracesUrl = onlineTracesUrl;
30
+ exports.localTracesUrl = localTracesUrl;
31
+ exports.localEndpointNamed = localEndpointNamed;
32
+ exports.onlineUsable = onlineUsable;
33
+ exports.localCarriesKey = localCarriesKey;
34
+ exports.isLoopbackHost = isLoopbackHost;
35
+ exports.destinations = destinations;
36
+ exports.destinationProblems = destinationProblems;
37
+ exports.DEFAULT_ENDPOINT = "http://127.0.0.1:4318/v1/traces";
38
+ exports.DEFAULT_SERVICE_NAME = "custom-app";
39
+ exports.DEFAULT_MAX_CONTENT_CHARS = 8000;
40
+ exports.DEFAULT_EXPORT_TIMEOUT_MS = 5000;
41
+ exports.DEFAULT_SHUTDOWN_TIMEOUT_MS = 2000;
42
+ /** This machine's Observer dashboard API (admission, discovery, the local control API). */
43
+ exports.DEFAULT_NODE_URL = "http://127.0.0.1:8081";
44
+ /** Discovery timeout (contract destination.md section 4: 500 ms total, one attempt). */
45
+ exports.DEFAULT_DISCOVER_TIMEOUT_MS = 500;
46
+ exports.DEFAULT_API_TIMEOUT_MS = 5000;
47
+ exports.DEFAULT_PROMPT_CACHE_TTL_MS = 60_000;
48
+ exports.TRACES_PATH = "/v1/traces";
49
+ const FALSE_WORDS = ["0", "false", "no", "off", ""];
50
+ exports.DESTINATION_CHOICES = ["local", "online", "both"];
51
+ /** Parse the first set boolean-ish env var in `names`; none set gives `def`. */
52
+ function envFlag(env, names, def) {
53
+ for (const name of names) {
54
+ const raw = env[name];
55
+ if (raw != null)
56
+ return !FALSE_WORDS.includes(raw.trim().toLowerCase());
57
+ }
58
+ return def;
59
+ }
60
+ function envStr(env, ...names) {
61
+ for (const name of names) {
62
+ const v = (env[name] ?? "").trim();
63
+ if (v)
64
+ return v;
65
+ }
66
+ return "";
67
+ }
68
+ function envNum(env, ...names) {
69
+ for (const name of names) {
70
+ const raw = (env[name] ?? "").trim();
71
+ if (raw) {
72
+ const n = Number(raw);
73
+ if (Number.isFinite(n) && n >= 0)
74
+ return n;
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+ function safeDecode(s) {
80
+ try {
81
+ return decodeURIComponent(s);
82
+ }
83
+ catch {
84
+ return s;
85
+ }
86
+ }
87
+ /** Parse the OTel `k1=v1,k2=v2` list (percent-decoded); malformed members skipped. */
88
+ function parseKvList(raw) {
89
+ const out = {};
90
+ if (!raw)
91
+ return out;
92
+ for (const member of raw.split(",")) {
93
+ const i = member.indexOf("=");
94
+ if (i < 0)
95
+ continue;
96
+ const key = safeDecode(member.slice(0, i).trim());
97
+ if (key)
98
+ out[key] = safeDecode(member.slice(i + 1).trim());
99
+ }
100
+ return out;
101
+ }
102
+ /** Parse a comma list (empty members dropped). */
103
+ function parseList(raw) {
104
+ return (raw ?? "")
105
+ .split(",")
106
+ .map((t) => t.trim())
107
+ .filter(Boolean);
108
+ }
109
+ function resolveEndpoint(explicit, env) {
110
+ return resolveEndpointWithSource(explicit, env)[0];
111
+ }
112
+ /** The endpoint and where it came from (see `Settings.endpoint`). */
113
+ function resolveEndpointWithSource(explicit, env) {
114
+ if (explicit)
115
+ return [explicit, "argument"];
116
+ const sb = envStr(env, "SUPERBASED_OTLP_ENDPOINT");
117
+ if (sb)
118
+ return [sb, "env"];
119
+ const full = envStr(env, "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT");
120
+ if (full)
121
+ return [full, "otel"];
122
+ const base = envStr(env, "OTEL_EXPORTER_OTLP_ENDPOINT");
123
+ if (base)
124
+ return [base.replace(/\/+$/, "") + exports.TRACES_PATH, "otel"];
125
+ return [exports.DEFAULT_ENDPOINT, "default"];
126
+ }
127
+ function resolveHeaders(explicit, env) {
128
+ const out = {};
129
+ for (const name of ["OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS", "SUPERBASED_OTLP_HEADERS"]) {
130
+ Object.assign(out, parseKvList(env[name]));
131
+ }
132
+ if (explicit)
133
+ for (const [k, v] of Object.entries(explicit))
134
+ out[String(k)] = String(v);
135
+ return out;
136
+ }
137
+ function resolveOnlineHeaders(explicit, env) {
138
+ const out = { ...parseKvList(env.SUPERBASED_OTLP_HEADERS) };
139
+ if (explicit)
140
+ for (const [k, v] of Object.entries(explicit))
141
+ out[String(k)] = String(v);
142
+ return out;
143
+ }
144
+ function resolveServiceName(explicit, env) {
145
+ if (explicit)
146
+ return explicit;
147
+ const v = envStr(env, "SUPERBASED_SERVICE_NAME", "OTEL_SERVICE_NAME");
148
+ if (v)
149
+ return v;
150
+ return (parseKvList(env.OTEL_RESOURCE_ATTRIBUTES)["service.name"] ?? "").trim() || exports.DEFAULT_SERVICE_NAME;
151
+ }
152
+ const SAMPLERS = {
153
+ always_on: [1, false],
154
+ always_off: [0, false],
155
+ traceidratio: [undefined, false],
156
+ parentbased_always_on: [1, true],
157
+ parentbased_always_off: [0, true],
158
+ parentbased_traceidratio: [undefined, true],
159
+ };
160
+ /** A sampling ratio from text: a number in 0..1, else undefined. */
161
+ function ratio(raw) {
162
+ if (!raw)
163
+ return undefined;
164
+ const n = Number(raw);
165
+ return Number.isFinite(n) && n >= 0 && n <= 1 ? n : undefined;
166
+ }
167
+ /**
168
+ * The head sampling rate and whether it is parent-based: the option,
169
+ * SUPERBASED_SAMPLE_RATE, then the standard OTEL_TRACES_SAMPLER (+ _ARG). An
170
+ * explicit rate outside 0..1 is a programmer error (RangeError); a bad
171
+ * environment value is ignored and named in `invalid` (review E-38; as
172
+ * Python), so a stray host variable never stops the app.
173
+ */
174
+ function resolveSampling(explicit, env) {
175
+ if (explicit !== undefined && explicit !== null) {
176
+ if (typeof explicit !== "number" || !Number.isFinite(explicit) || explicit < 0 || explicit > 1) {
177
+ throw new RangeError(`@superbased/sdk: sampleRate must be between 0 and 1, not ${String(explicit)}`);
178
+ }
179
+ return { rate: explicit, parentBased: true, invalid: "" };
180
+ }
181
+ const bad = [];
182
+ const raw = envStr(env, "SUPERBASED_SAMPLE_RATE");
183
+ const own = ratio(raw);
184
+ if (raw && own === undefined)
185
+ bad.push(`SUPERBASED_SAMPLE_RATE=${JSON.stringify(raw)}`);
186
+ const invalid = () => (bad.length ? `${bad.join(" and ")} is not a number in 0..1; ignored` : "");
187
+ if (own !== undefined)
188
+ return { rate: own, parentBased: true, invalid: invalid() };
189
+ const row = SAMPLERS[envStr(env, "OTEL_TRACES_SAMPLER").toLowerCase()];
190
+ if (row) {
191
+ let [rate] = row;
192
+ if (rate === undefined) {
193
+ const argRaw = envStr(env, "OTEL_TRACES_SAMPLER_ARG");
194
+ rate = ratio(argRaw);
195
+ if (argRaw && rate === undefined)
196
+ bad.push(`OTEL_TRACES_SAMPLER_ARG=${JSON.stringify(argRaw)}`);
197
+ rate ??= 1;
198
+ }
199
+ return { rate, parentBased: row[1], invalid: invalid() };
200
+ }
201
+ return { rate: 1, parentBased: true, invalid: invalid() };
202
+ }
203
+ /**
204
+ * The destination from the option, then SUPERBASED_DESTINATION. An invalid
205
+ * value is refused loudly (reported in `invalid`) and the next source is
206
+ * used (contract destination.md section 1).
207
+ */
208
+ function resolveDestinationChoice(explicit, env) {
209
+ const sources = [
210
+ ["argument", explicit],
211
+ ["env", env.SUPERBASED_DESTINATION],
212
+ ];
213
+ const bad = [];
214
+ for (const [source, raw] of sources) {
215
+ const v = (raw ?? "").trim().toLowerCase();
216
+ if (!v)
217
+ continue;
218
+ if (exports.DESTINATION_CHOICES.includes(v)) {
219
+ return { choice: v, source, invalid: bad.join("; ") };
220
+ }
221
+ bad.push(`destination ${JSON.stringify(raw)} (${source}) is not local, online or both; ignored`);
222
+ }
223
+ return { choice: "", source: "", invalid: bad.join("; ") };
224
+ }
225
+ function trimSlash(u) {
226
+ return u.replace(/\/+$/, "");
227
+ }
228
+ const KNOWN = [
229
+ "endpoint", "headers", "apiKey", "serviceName", "resourceAttributes", "tenant", "user", "sessionId",
230
+ "captureContent", "maxContentChars", "exportTimeoutMs", "shutdownTimeoutMs", "exitHook", "debug",
231
+ "release", "environment", "tags", "metadata", "sampleRate", "destination", "orgUrl",
232
+ "nodeUrl", "discover", "discoverTimeoutMs", "apiTimeoutMs", "promptCacheTtlMs",
233
+ ];
234
+ /** Build settings from explicit options (undefined = unset) over env. */
235
+ function resolveSettings(env, explicit = {}) {
236
+ for (const k of Object.keys(explicit)) {
237
+ if (!KNOWN.includes(k))
238
+ throw new TypeError(`unknown @superbased/sdk setting: ${k}`);
239
+ }
240
+ const pick = (v, d) => (v === undefined || v === null ? d : v);
241
+ const sampling = resolveSampling(explicit.sampleRate, env);
242
+ const dest = resolveDestinationChoice(explicit.destination, env);
243
+ const [endpoint, endpointSource] = resolveEndpointWithSource(explicit.endpoint, env);
244
+ const apiKey = pick(explicit.apiKey, envStr(env, "SUPERBASED_API_KEY"));
245
+ return {
246
+ endpoint,
247
+ endpointSource,
248
+ headers: resolveHeaders(explicit.headers, env),
249
+ apiKey,
250
+ credentialSource: !apiKey ? "" : explicit.apiKey ? "argument" : "env",
251
+ serviceName: resolveServiceName(explicit.serviceName, env),
252
+ resourceAttributes: { ...parseKvList(env.OTEL_RESOURCE_ATTRIBUTES), ...(explicit.resourceAttributes ?? {}) },
253
+ tenant: pick(explicit.tenant, envStr(env, "SUPERBASED_TENANT")),
254
+ user: pick(explicit.user, envStr(env, "SUPERBASED_USER")),
255
+ sessionId: pick(explicit.sessionId, envStr(env, "SUPERBASED_SESSION_ID")),
256
+ captureContent: pick(explicit.captureContent, envFlag(env, ["SUPERBASED_CAPTURE_CONTENT", "OBSERVER_CAPTURE_CONTENT"], true)),
257
+ maxContentChars: pick(explicit.maxContentChars, envNum(env, "SUPERBASED_MAX_CONTENT_CHARS") ?? exports.DEFAULT_MAX_CONTENT_CHARS),
258
+ exportTimeoutMs: Math.max(1, pick(explicit.exportTimeoutMs, envNum(env, "SUPERBASED_EXPORT_TIMEOUT_MS", "OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "OTEL_EXPORTER_OTLP_TIMEOUT") ??
259
+ exports.DEFAULT_EXPORT_TIMEOUT_MS)),
260
+ shutdownTimeoutMs: Math.max(0, pick(explicit.shutdownTimeoutMs, envNum(env, "SUPERBASED_SHUTDOWN_TIMEOUT_MS") ?? exports.DEFAULT_SHUTDOWN_TIMEOUT_MS)),
261
+ exitHook: pick(explicit.exitHook, envFlag(env, ["SUPERBASED_EXIT_HOOK"], true)),
262
+ debug: pick(explicit.debug, envFlag(env, ["SUPERBASED_DEBUG"], false)),
263
+ release: pick(explicit.release, envStr(env, "SUPERBASED_RELEASE")),
264
+ environment: pick(explicit.environment, envStr(env, "SUPERBASED_ENVIRONMENT")),
265
+ tags: pick(explicit.tags, parseList(env.SUPERBASED_TAGS)),
266
+ metadata: pick(explicit.metadata, parseKvList(env.SUPERBASED_METADATA)),
267
+ sampleRate: sampling.rate,
268
+ parentBased: sampling.parentBased,
269
+ destination: dest.choice,
270
+ destinationInvalid: dest.invalid,
271
+ samplingInvalid: sampling.invalid,
272
+ advertisedEndpoint: "",
273
+ orgUrl: trimSlash(pick(explicit.orgUrl, envStr(env, "SUPERBASED_ORG_URL"))),
274
+ onlineHeaders: resolveOnlineHeaders(explicit.headers, env),
275
+ nodeUrl: trimSlash(pick(explicit.nodeUrl, envStr(env, "SUPERBASED_NODE_URL")) || exports.DEFAULT_NODE_URL),
276
+ discover: pick(explicit.discover, envFlag(env, ["SUPERBASED_DISCOVER"], true)),
277
+ discoverTimeoutMs: Math.max(0, pick(explicit.discoverTimeoutMs, envNum(env, "SUPERBASED_DISCOVER_TIMEOUT_MS") ?? exports.DEFAULT_DISCOVER_TIMEOUT_MS)),
278
+ apiTimeoutMs: Math.max(1, pick(explicit.apiTimeoutMs, envNum(env, "SUPERBASED_API_TIMEOUT_MS") ?? exports.DEFAULT_API_TIMEOUT_MS)),
279
+ promptCacheTtlMs: Math.max(0, pick(explicit.promptCacheTtlMs, envNum(env, "SUPERBASED_PROMPT_CACHE_TTL_MS") ?? exports.DEFAULT_PROMPT_CACHE_TTL_MS)),
280
+ endpointExplicit: endpointSource !== "default",
281
+ };
282
+ }
283
+ function hasAuthHeader(h) {
284
+ return Object.keys(h).some((k) => k.toLowerCase() === "authorization");
285
+ }
286
+ /** The online OTLP traces URL ("" when no gateway is configured). */
287
+ function onlineTracesUrl(s) {
288
+ return s.orgUrl ? s.orgUrl + exports.TRACES_PATH : "";
289
+ }
290
+ /**
291
+ * The local OTLP traces URL for a destination choice: the `endpoint` option
292
+ * or SUPERBASED_OTLP_ENDPOINT as given; an OTEL_* endpoint only when the
293
+ * destination is `local` (so an app's existing OTEL variables, pointing at
294
+ * another vendor, never replace the machine under `both`); else what the
295
+ * machine advertised; else the built-in receiver.
296
+ */
297
+ function localTracesUrl(s, choice = s.destination) {
298
+ if (localEndpointNamed(s, choice))
299
+ return s.endpoint;
300
+ return s.advertisedEndpoint || exports.DEFAULT_ENDPOINT;
301
+ }
302
+ /**
303
+ * Whether the app named the local destination's endpoint itself (the
304
+ * first rungs of `localTracesUrl`), so the machine's advertised receiver is
305
+ * not needed.
306
+ */
307
+ function localEndpointNamed(s, choice = s.destination) {
308
+ return s.endpointSource === "argument" || s.endpointSource === "env" || (s.endpointSource === "otel" && choice === "local");
309
+ }
310
+ /** Whether the online destination is usable: a gateway URL and a credential. */
311
+ function onlineUsable(s) {
312
+ return !!onlineTracesUrl(s) && !!s.apiKey;
313
+ }
314
+ /**
315
+ * Whether the local exporter may carry the credential: only to a collector
316
+ * the app named itself (the `endpoint` option or SUPERBASED_OTLP_ENDPOINT)
317
+ * that is not on loopback. Never to this machine, and never to an endpoint
318
+ * that came from OTEL_EXPORTER_OTLP_* (an app exporting to another vendor
319
+ * must not leak the superbased key there; review finding R-B26).
320
+ */
321
+ function localCarriesKey(s, endpoint) {
322
+ // The machine's file credential goes only to the gateway (contract destination.md section 6).
323
+ return !!s.apiKey && s.credentialSource !== "file" && (s.endpointSource === "argument" || s.endpointSource === "env") && !isLoopbackHost(endpoint);
324
+ }
325
+ /** Whether a URL's host is loopback. */
326
+ function isLoopbackHost(url) {
327
+ try {
328
+ const h = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
329
+ return h === "localhost" || h === "::1" || /^127\.\d+\.\d+\.\d+$/.test(h);
330
+ }
331
+ catch {
332
+ return false;
333
+ }
334
+ }
335
+ /**
336
+ * Where spans are exported, for a destination choice (D18).
337
+ *
338
+ * - `local`: this machine's Observer (or the collector `endpoint` names).
339
+ * Headers: the OTEL_* ones (destination `local` only), SUPERBASED_OTLP_HEADERS
340
+ * and the `headers` option. The credential only per `localCarriesKey`.
341
+ * - `online`: the gateway with `apiKey` as the bearer, configured only from
342
+ * the SDK's own settings (an app's OTEL_* variables never redirect it).
343
+ * - `both`: one exporter for each; one failing never blocks the other.
344
+ *
345
+ * The degraded cases (contract destination.md section 7): `online` with no
346
+ * usable gateway exports nothing, `both` exports to the machine only; the
347
+ * caller reports why (`destinationProblems`).
348
+ */
349
+ function destinations(s, choice = s.destination) {
350
+ const out = [];
351
+ const c = choice || "local";
352
+ if (c === "local" || c === "both") {
353
+ const endpoint = localTracesUrl(s, c);
354
+ const headers = c === "local" ? { ...s.headers } : { ...s.onlineHeaders };
355
+ if (localCarriesKey(s, endpoint) && !hasAuthHeader(headers))
356
+ headers.Authorization = `Bearer ${s.apiKey}`;
357
+ out.push({ name: "local", endpoint, headers, timeoutMs: s.exportTimeoutMs });
358
+ }
359
+ if ((c === "online" || c === "both") && onlineUsable(s)) {
360
+ const headers = { ...s.onlineHeaders };
361
+ // The SDK credential always wins over a user or env Authorization header.
362
+ for (const k of Object.keys(headers))
363
+ if (k.toLowerCase() === "authorization")
364
+ delete headers[k];
365
+ headers.Authorization = `Bearer ${s.apiKey}`;
366
+ out.push({ name: "online", endpoint: onlineTracesUrl(s), headers, timeoutMs: s.exportTimeoutMs });
367
+ }
368
+ return out;
369
+ }
370
+ /** The fix to name when the online destination is not usable (the verb is `observer sdk sign-in`, R-B17). */
371
+ exports.ONLINE_FIX = "run `observer sdk sign-in`, or set SUPERBASED_ORG_URL and SUPERBASED_API_KEY";
372
+ /** Why a destination choice cannot be honoured in full (empty = fine). */
373
+ function destinationProblems(s, choice) {
374
+ if (choice !== "online" && choice !== "both")
375
+ return [];
376
+ const missing = [];
377
+ if (!onlineTracesUrl(s))
378
+ missing.push("a gateway URL");
379
+ if (!s.apiKey)
380
+ missing.push("an SDK credential");
381
+ if (!missing.length)
382
+ return [];
383
+ const effect = choice === "online" ? "nothing is exported" : "exporting to this machine only";
384
+ return [`destination ${choice} is missing ${missing.join(" and ")}; ${effect}. To fix: ${exports.ONLINE_FIX}`];
385
+ }
386
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;AAsHH,0BAMC;AA8BD,kCAUC;AAGD,8BAKC;AAED,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,MAAM,KAAK,MAAM;QAAE,OAAO,EAAE,CAAC;IACxD,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IACvD,IAAI,CAAC,CAAC,CAAC,MAAM;QAAE,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACjD,IAAI,CAAC,OAAO,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,gCAAgC,CAAC;IAC9F,OAAO,CAAC,eAAe,MAAM,eAAe,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,MAAM,aAAa,kBAAU,EAAE,CAAC,CAAC;AACzG,CAAC","sourcesContent":["/**\n * SDK settings: one options object, each field mapped to an env var.\n *\n * Resolution for every field: explicit `init()` option, then the\n * `SUPERBASED_*` variable, then the standard OpenTelemetry variable (where\n * one exists), then (destination, gateway URL and credential only) what the\n * local Observer advertises, then the default. Pure over an env record, so it\n * is testable without touching `process.env`.\n *\n * Export goes to a list of destinations (endpoint, headers, timeout each):\n * this machine's Observer, the org or SaaS gateway, or both (D18, contract\n * `contracts/destination.md`). `destinations()` turns the resolved choice\n * into that list; destination.ts makes the choice.\n */\n\nexport type Env = Record<string, string | undefined>;\n\nexport const DEFAULT_ENDPOINT = \"http://127.0.0.1:4318/v1/traces\";\nexport const DEFAULT_SERVICE_NAME = \"custom-app\";\nexport const DEFAULT_MAX_CONTENT_CHARS = 8000;\nexport const DEFAULT_EXPORT_TIMEOUT_MS = 5000;\nexport const DEFAULT_SHUTDOWN_TIMEOUT_MS = 2000;\n/** This machine's Observer dashboard API (admission, discovery, the local control API). */\nexport const DEFAULT_NODE_URL = \"http://127.0.0.1:8081\";\n/** Discovery timeout (contract destination.md section 4: 500 ms total, one attempt). */\nexport const DEFAULT_DISCOVER_TIMEOUT_MS = 500;\nexport const DEFAULT_API_TIMEOUT_MS = 5000;\nexport const DEFAULT_PROMPT_CACHE_TTL_MS = 60_000;\nexport const TRACES_PATH = \"/v1/traces\";\nconst FALSE_WORDS = [\"0\", \"false\", \"no\", \"off\", \"\"];\n\n/** Where SDK data is saved (D18). */\nexport type DestinationChoice = \"local\" | \"online\" | \"both\";\nexport const DESTINATION_CHOICES: readonly DestinationChoice[] = [\"local\", \"online\", \"both\"];\n\n/** One OTLP/HTTP export target. */\nexport interface Destination {\n /** `local` (this machine, or the collector `endpoint` names) or `online` (the org or SaaS gateway). */\n name: \"local\" | \"online\";\n endpoint: string;\n headers: Record<string, string>;\n timeoutMs: number;\n}\n\n/** Every SDK option, fully resolved. See the README's settings table. */\nexport interface Settings {\n /**\n * The local destination's OTLP traces URL: the option > SUPERBASED_OTLP_ENDPOINT >\n * (destination `local` only) OTEL_EXPORTER_OTLP_TRACES_ENDPOINT > OTEL_EXPORTER_OTLP_ENDPOINT\n * (+ /v1/traces) > what the machine advertises > the built-in receiver.\n * This field holds the first of the option / env values (or the default);\n * `localTracesUrl(settings, choice)` applies the rest.\n */\n endpoint: string;\n /** Where `endpoint` came from: `argument`, `env` (SUPERBASED_OTLP_ENDPOINT), `otel` (an OTEL_* variable) or `default`. */\n endpointSource: \"argument\" | \"env\" | \"otel\" | \"default\";\n /** OTEL_EXPORTER_OTLP_HEADERS, OTEL_EXPORTER_OTLP_TRACES_HEADERS, SUPERBASED_OTLP_HEADERS (merged, option on top). The OTEL ones go to the local destination only when it is `local`. */\n headers: Record<string, string>;\n /** SUPERBASED_API_KEY, sent as `Authorization: Bearer` to the gateway only. */\n apiKey: string;\n /** SUPERBASED_SERVICE_NAME > OTEL_SERVICE_NAME > service.name in OTEL_RESOURCE_ATTRIBUTES. */\n serviceName: string;\n /** OTEL_RESOURCE_ATTRIBUTES. */\n resourceAttributes: Record<string, string>;\n /** SUPERBASED_TENANT. */\n tenant: string;\n /** SUPERBASED_USER. */\n user: string;\n /** SUPERBASED_SESSION_ID. */\n sessionId: string;\n /** SUPERBASED_CAPTURE_CONTENT (legacy OBSERVER_CAPTURE_CONTENT). */\n captureContent: boolean;\n /** SUPERBASED_MAX_CONTENT_CHARS. */\n maxContentChars: number;\n /** SUPERBASED_EXPORT_TIMEOUT_MS > OTEL_EXPORTER_OTLP_TRACES_TIMEOUT > OTEL_EXPORTER_OTLP_TIMEOUT. */\n exportTimeoutMs: number;\n /** SUPERBASED_SHUTDOWN_TIMEOUT_MS: bound on flush() and shutdown(). */\n shutdownTimeoutMs: number;\n /** SUPERBASED_EXIT_HOOK: flush pending spans on process `beforeExit`. */\n exitHook: boolean;\n /** SUPERBASED_DEBUG: log each failure to the console (default: at most one line a minute). */\n debug: boolean;\n /** SUPERBASED_RELEASE: the app's release, on the resource as `service.version`. */\n release: string;\n /** SUPERBASED_ENVIRONMENT: the app's environment, on the resource as `deployment.environment.name`. */\n environment: string;\n /** SUPERBASED_TAGS (comma list): tags on every trace (`sbo.tags`). */\n tags: string[];\n /** SUPERBASED_METADATA (`k=v,k2=v2`): metadata on every trace (`sbo.metadata.<k>`). */\n metadata: Record<string, string>;\n /** SUPERBASED_SAMPLE_RATE (0..1), else OTEL_TRACES_SAMPLER[_ARG]. Whole traces are kept or dropped. */\n sampleRate: number;\n /** Whether the sampler is parent-based (a sampled parent keeps its children). */\n parentBased: boolean;\n /** SUPERBASED_DESTINATION: local, online or both. Empty = not chosen (ask the machine, then local). */\n destination: DestinationChoice | \"\";\n /** Why an explicit destination value was refused (\"\" when none was, or it was valid). */\n destinationInvalid: string;\n /** Why an environment sampling value was ignored (\"\" when none was). */\n samplingInvalid: string;\n /** The OTLP traces URL the machine advertised in discovery (\"\" when none). Internal. */\n advertisedEndpoint: string;\n /** SUPERBASED_ORG_URL: base URL of the org or SaaS gateway (OTLP at `/v1/traces`, control API at `/v1/sdk`). */\n orgUrl: string;\n /** Headers for the gateway: the `headers` option and SUPERBASED_OTLP_HEADERS, never the OTEL_* ones. */\n onlineHeaders: Record<string, string>;\n /** SUPERBASED_NODE_URL: this machine's Observer dashboard API (scheme, host and port). */\n nodeUrl: string;\n /** SUPERBASED_DISCOVER: ask the machine for its destination default. */\n discover: boolean;\n /** SUPERBASED_DISCOVER_TIMEOUT_MS: bound on that request. */\n discoverTimeoutMs: number;\n /** SUPERBASED_API_TIMEOUT_MS: bound on each control API call (scores, prompts, datasets, experiments). */\n apiTimeoutMs: number;\n /** SUPERBASED_PROMPT_CACHE_TTL_MS: how long a fetched prompt is fresh. */\n promptCacheTtlMs: number;\n /** True when `endpoint` was set explicitly (option, SUPERBASED_OTLP_ENDPOINT or an OTEL_* variable). */\n endpointExplicit: boolean;\n /** Where `apiKey` came from: `argument`, `env`, `file` (the machine's credential file) or \"\". */\n credentialSource: \"argument\" | \"env\" | \"file\" | \"\";\n}\n\n/** The subset a caller may pass to `init()`; unset fields come from env. */\nexport type SettingsInput = Partial<\n Omit<\n Settings,\n \"endpointExplicit\" | \"endpointSource\" | \"onlineHeaders\" | \"destinationInvalid\" | \"samplingInvalid\" | \"parentBased\" | \"destination\" | \"advertisedEndpoint\" | \"credentialSource\"\n >\n> & { destination?: string };\n\n/** Parse the first set boolean-ish env var in `names`; none set gives `def`. */\nexport function envFlag(env: Env, names: string[], def: boolean): boolean {\n for (const name of names) {\n const raw = env[name];\n if (raw != null) return !FALSE_WORDS.includes(raw.trim().toLowerCase());\n }\n return def;\n}\n\nfunction envStr(env: Env, ...names: string[]): string {\n for (const name of names) {\n const v = (env[name] ?? \"\").trim();\n if (v) return v;\n }\n return \"\";\n}\n\nfunction envNum(env: Env, ...names: string[]): number | undefined {\n for (const name of names) {\n const raw = (env[name] ?? \"\").trim();\n if (raw) {\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return n;\n }\n }\n return undefined;\n}\n\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\n/** Parse the OTel `k1=v1,k2=v2` list (percent-decoded); malformed members skipped. */\nexport function parseKvList(raw: string | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!raw) return out;\n for (const member of raw.split(\",\")) {\n const i = member.indexOf(\"=\");\n if (i < 0) continue;\n const key = safeDecode(member.slice(0, i).trim());\n if (key) out[key] = safeDecode(member.slice(i + 1).trim());\n }\n return out;\n}\n\n/** Parse a comma list (empty members dropped). */\nexport function parseList(raw: string | undefined): string[] {\n return (raw ?? \"\")\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n}\n\nexport function resolveEndpoint(explicit: string | undefined, env: Env): string {\n return resolveEndpointWithSource(explicit, env)[0];\n}\n\n/** The endpoint and where it came from (see `Settings.endpoint`). */\nexport function resolveEndpointWithSource(explicit: string | undefined, env: Env): [string, Settings[\"endpointSource\"]] {\n if (explicit) return [explicit, \"argument\"];\n const sb = envStr(env, \"SUPERBASED_OTLP_ENDPOINT\");\n if (sb) return [sb, \"env\"];\n const full = envStr(env, \"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT\");\n if (full) return [full, \"otel\"];\n const base = envStr(env, \"OTEL_EXPORTER_OTLP_ENDPOINT\");\n if (base) return [base.replace(/\\/+$/, \"\") + TRACES_PATH, \"otel\"];\n return [DEFAULT_ENDPOINT, \"default\"];\n}\n\nexport function resolveHeaders(explicit: Record<string, string> | undefined, env: Env): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of [\"OTEL_EXPORTER_OTLP_HEADERS\", \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\", \"SUPERBASED_OTLP_HEADERS\"]) {\n Object.assign(out, parseKvList(env[name]));\n }\n if (explicit) for (const [k, v] of Object.entries(explicit)) out[String(k)] = String(v);\n return out;\n}\n\nfunction resolveOnlineHeaders(explicit: Record<string, string> | undefined, env: Env): Record<string, string> {\n const out: Record<string, string> = { ...parseKvList(env.SUPERBASED_OTLP_HEADERS) };\n if (explicit) for (const [k, v] of Object.entries(explicit)) out[String(k)] = String(v);\n return out;\n}\n\nexport function resolveServiceName(explicit: string | undefined, env: Env): string {\n if (explicit) return explicit;\n const v = envStr(env, \"SUPERBASED_SERVICE_NAME\", \"OTEL_SERVICE_NAME\");\n if (v) return v;\n return (parseKvList(env.OTEL_RESOURCE_ATTRIBUTES)[\"service.name\"] ?? \"\").trim() || DEFAULT_SERVICE_NAME;\n}\n\nconst SAMPLERS: Record<string, [number | undefined, boolean]> = {\n always_on: [1, false],\n always_off: [0, false],\n traceidratio: [undefined, false],\n parentbased_always_on: [1, true],\n parentbased_always_off: [0, true],\n parentbased_traceidratio: [undefined, true],\n};\n\n/** A sampling ratio from text: a number in 0..1, else undefined. */\nfunction ratio(raw: string): number | undefined {\n if (!raw) return undefined;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 && n <= 1 ? n : undefined;\n}\n\n/**\n * The head sampling rate and whether it is parent-based: the option,\n * SUPERBASED_SAMPLE_RATE, then the standard OTEL_TRACES_SAMPLER (+ _ARG). An\n * explicit rate outside 0..1 is a programmer error (RangeError); a bad\n * environment value is ignored and named in `invalid` (review E-38; as\n * Python), so a stray host variable never stops the app.\n */\nexport function resolveSampling(explicit: number | undefined, env: Env): { rate: number; parentBased: boolean; invalid: string } {\n if (explicit !== undefined && explicit !== null) {\n if (typeof explicit !== \"number\" || !Number.isFinite(explicit) || explicit < 0 || explicit > 1) {\n throw new RangeError(`@superbased/sdk: sampleRate must be between 0 and 1, not ${String(explicit)}`);\n }\n return { rate: explicit, parentBased: true, invalid: \"\" };\n }\n const bad: string[] = [];\n const raw = envStr(env, \"SUPERBASED_SAMPLE_RATE\");\n const own = ratio(raw);\n if (raw && own === undefined) bad.push(`SUPERBASED_SAMPLE_RATE=${JSON.stringify(raw)}`);\n const invalid = () => (bad.length ? `${bad.join(\" and \")} is not a number in 0..1; ignored` : \"\");\n if (own !== undefined) return { rate: own, parentBased: true, invalid: invalid() };\n const row = SAMPLERS[envStr(env, \"OTEL_TRACES_SAMPLER\").toLowerCase()];\n if (row) {\n let [rate] = row;\n if (rate === undefined) {\n const argRaw = envStr(env, \"OTEL_TRACES_SAMPLER_ARG\");\n rate = ratio(argRaw);\n if (argRaw && rate === undefined) bad.push(`OTEL_TRACES_SAMPLER_ARG=${JSON.stringify(argRaw)}`);\n rate ??= 1;\n }\n return { rate, parentBased: row[1], invalid: invalid() };\n }\n return { rate: 1, parentBased: true, invalid: invalid() };\n}\n\n/**\n * The destination from the option, then SUPERBASED_DESTINATION. An invalid\n * value is refused loudly (reported in `invalid`) and the next source is\n * used (contract destination.md section 1).\n */\nexport function resolveDestinationChoice(explicit: string | undefined, env: Env): { choice: DestinationChoice | \"\"; source: string; invalid: string } {\n const sources: Array<[string, string | undefined]> = [\n [\"argument\", explicit],\n [\"env\", env.SUPERBASED_DESTINATION],\n ];\n const bad: string[] = [];\n for (const [source, raw] of sources) {\n const v = (raw ?? \"\").trim().toLowerCase();\n if (!v) continue;\n if ((DESTINATION_CHOICES as readonly string[]).includes(v)) {\n return { choice: v as DestinationChoice, source, invalid: bad.join(\"; \") };\n }\n bad.push(`destination ${JSON.stringify(raw)} (${source}) is not local, online or both; ignored`);\n }\n return { choice: \"\", source: \"\", invalid: bad.join(\"; \") };\n}\n\nexport function trimSlash(u: string): string {\n return u.replace(/\\/+$/, \"\");\n}\n\nconst KNOWN: ReadonlyArray<string> = [\n \"endpoint\", \"headers\", \"apiKey\", \"serviceName\", \"resourceAttributes\", \"tenant\", \"user\", \"sessionId\",\n \"captureContent\", \"maxContentChars\", \"exportTimeoutMs\", \"shutdownTimeoutMs\", \"exitHook\", \"debug\",\n \"release\", \"environment\", \"tags\", \"metadata\", \"sampleRate\", \"destination\", \"orgUrl\",\n \"nodeUrl\", \"discover\", \"discoverTimeoutMs\", \"apiTimeoutMs\", \"promptCacheTtlMs\",\n];\n\n/** Build settings from explicit options (undefined = unset) over env. */\nexport function resolveSettings(env: Env, explicit: SettingsInput = {}): Settings {\n for (const k of Object.keys(explicit)) {\n if (!KNOWN.includes(k)) throw new TypeError(`unknown @superbased/sdk setting: ${k}`);\n }\n const pick = <T>(v: T | undefined, d: T): T => (v === undefined || v === null ? d : v);\n const sampling = resolveSampling(explicit.sampleRate, env);\n const dest = resolveDestinationChoice(explicit.destination, env);\n const [endpoint, endpointSource] = resolveEndpointWithSource(explicit.endpoint, env);\n const apiKey = pick(explicit.apiKey, envStr(env, \"SUPERBASED_API_KEY\"));\n return {\n endpoint,\n endpointSource,\n headers: resolveHeaders(explicit.headers, env),\n apiKey,\n credentialSource: !apiKey ? \"\" : explicit.apiKey ? \"argument\" : \"env\",\n serviceName: resolveServiceName(explicit.serviceName, env),\n resourceAttributes: { ...parseKvList(env.OTEL_RESOURCE_ATTRIBUTES), ...(explicit.resourceAttributes ?? {}) },\n tenant: pick(explicit.tenant, envStr(env, \"SUPERBASED_TENANT\")),\n user: pick(explicit.user, envStr(env, \"SUPERBASED_USER\")),\n sessionId: pick(explicit.sessionId, envStr(env, \"SUPERBASED_SESSION_ID\")),\n captureContent: pick(\n explicit.captureContent,\n envFlag(env, [\"SUPERBASED_CAPTURE_CONTENT\", \"OBSERVER_CAPTURE_CONTENT\"], true),\n ),\n maxContentChars: pick(explicit.maxContentChars, envNum(env, \"SUPERBASED_MAX_CONTENT_CHARS\") ?? DEFAULT_MAX_CONTENT_CHARS),\n exportTimeoutMs: Math.max(\n 1,\n pick(\n explicit.exportTimeoutMs,\n envNum(env, \"SUPERBASED_EXPORT_TIMEOUT_MS\", \"OTEL_EXPORTER_OTLP_TRACES_TIMEOUT\", \"OTEL_EXPORTER_OTLP_TIMEOUT\") ??\n DEFAULT_EXPORT_TIMEOUT_MS,\n ),\n ),\n shutdownTimeoutMs: Math.max(\n 0,\n pick(explicit.shutdownTimeoutMs, envNum(env, \"SUPERBASED_SHUTDOWN_TIMEOUT_MS\") ?? DEFAULT_SHUTDOWN_TIMEOUT_MS),\n ),\n exitHook: pick(explicit.exitHook, envFlag(env, [\"SUPERBASED_EXIT_HOOK\"], true)),\n debug: pick(explicit.debug, envFlag(env, [\"SUPERBASED_DEBUG\"], false)),\n release: pick(explicit.release, envStr(env, \"SUPERBASED_RELEASE\")),\n environment: pick(explicit.environment, envStr(env, \"SUPERBASED_ENVIRONMENT\")),\n tags: pick(explicit.tags, parseList(env.SUPERBASED_TAGS)),\n metadata: pick(explicit.metadata, parseKvList(env.SUPERBASED_METADATA)),\n sampleRate: sampling.rate,\n parentBased: sampling.parentBased,\n destination: dest.choice,\n destinationInvalid: dest.invalid,\n samplingInvalid: sampling.invalid,\n advertisedEndpoint: \"\",\n orgUrl: trimSlash(pick(explicit.orgUrl, envStr(env, \"SUPERBASED_ORG_URL\"))),\n onlineHeaders: resolveOnlineHeaders(explicit.headers, env),\n nodeUrl: trimSlash(pick(explicit.nodeUrl, envStr(env, \"SUPERBASED_NODE_URL\")) || DEFAULT_NODE_URL),\n discover: pick(explicit.discover, envFlag(env, [\"SUPERBASED_DISCOVER\"], true)),\n discoverTimeoutMs: Math.max(\n 0,\n pick(explicit.discoverTimeoutMs, envNum(env, \"SUPERBASED_DISCOVER_TIMEOUT_MS\") ?? DEFAULT_DISCOVER_TIMEOUT_MS),\n ),\n apiTimeoutMs: Math.max(1, pick(explicit.apiTimeoutMs, envNum(env, \"SUPERBASED_API_TIMEOUT_MS\") ?? DEFAULT_API_TIMEOUT_MS)),\n promptCacheTtlMs: Math.max(\n 0,\n pick(explicit.promptCacheTtlMs, envNum(env, \"SUPERBASED_PROMPT_CACHE_TTL_MS\") ?? DEFAULT_PROMPT_CACHE_TTL_MS),\n ),\n endpointExplicit: endpointSource !== \"default\",\n };\n}\n\nfunction hasAuthHeader(h: Record<string, string>): boolean {\n return Object.keys(h).some((k) => k.toLowerCase() === \"authorization\");\n}\n\n/** The online OTLP traces URL (\"\" when no gateway is configured). */\nexport function onlineTracesUrl(s: Settings): string {\n return s.orgUrl ? s.orgUrl + TRACES_PATH : \"\";\n}\n\n/**\n * The local OTLP traces URL for a destination choice: the `endpoint` option\n * or SUPERBASED_OTLP_ENDPOINT as given; an OTEL_* endpoint only when the\n * destination is `local` (so an app's existing OTEL variables, pointing at\n * another vendor, never replace the machine under `both`); else what the\n * machine advertised; else the built-in receiver.\n */\nexport function localTracesUrl(s: Settings, choice: DestinationChoice | \"\" = s.destination): string {\n if (localEndpointNamed(s, choice)) return s.endpoint;\n return s.advertisedEndpoint || DEFAULT_ENDPOINT;\n}\n\n/**\n * Whether the app named the local destination's endpoint itself (the\n * first rungs of `localTracesUrl`), so the machine's advertised receiver is\n * not needed.\n */\nexport function localEndpointNamed(s: Settings, choice: DestinationChoice | \"\" = s.destination): boolean {\n return s.endpointSource === \"argument\" || s.endpointSource === \"env\" || (s.endpointSource === \"otel\" && choice === \"local\");\n}\n\n/** Whether the online destination is usable: a gateway URL and a credential. */\nexport function onlineUsable(s: Settings): boolean {\n return !!onlineTracesUrl(s) && !!s.apiKey;\n}\n\n/**\n * Whether the local exporter may carry the credential: only to a collector\n * the app named itself (the `endpoint` option or SUPERBASED_OTLP_ENDPOINT)\n * that is not on loopback. Never to this machine, and never to an endpoint\n * that came from OTEL_EXPORTER_OTLP_* (an app exporting to another vendor\n * must not leak the superbased key there; review finding R-B26).\n */\nexport function localCarriesKey(s: Settings, endpoint: string): boolean {\n // The machine's file credential goes only to the gateway (contract destination.md section 6).\n return !!s.apiKey && s.credentialSource !== \"file\" && (s.endpointSource === \"argument\" || s.endpointSource === \"env\") && !isLoopbackHost(endpoint);\n}\n\n/** Whether a URL's host is loopback. */\nexport function isLoopbackHost(url: string): boolean {\n try {\n const h = new URL(url).hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n return h === \"localhost\" || h === \"::1\" || /^127\\.\\d+\\.\\d+\\.\\d+$/.test(h);\n } catch {\n return false;\n }\n}\n\n/**\n * Where spans are exported, for a destination choice (D18).\n *\n * - `local`: this machine's Observer (or the collector `endpoint` names).\n * Headers: the OTEL_* ones (destination `local` only), SUPERBASED_OTLP_HEADERS\n * and the `headers` option. The credential only per `localCarriesKey`.\n * - `online`: the gateway with `apiKey` as the bearer, configured only from\n * the SDK's own settings (an app's OTEL_* variables never redirect it).\n * - `both`: one exporter for each; one failing never blocks the other.\n *\n * The degraded cases (contract destination.md section 7): `online` with no\n * usable gateway exports nothing, `both` exports to the machine only; the\n * caller reports why (`destinationProblems`).\n */\nexport function destinations(s: Settings, choice: DestinationChoice | \"\" = s.destination): Destination[] {\n const out: Destination[] = [];\n const c = choice || \"local\";\n if (c === \"local\" || c === \"both\") {\n const endpoint = localTracesUrl(s, c);\n const headers = c === \"local\" ? { ...s.headers } : { ...s.onlineHeaders };\n if (localCarriesKey(s, endpoint) && !hasAuthHeader(headers)) headers.Authorization = `Bearer ${s.apiKey}`;\n out.push({ name: \"local\", endpoint, headers, timeoutMs: s.exportTimeoutMs });\n }\n if ((c === \"online\" || c === \"both\") && onlineUsable(s)) {\n const headers = { ...s.onlineHeaders };\n // The SDK credential always wins over a user or env Authorization header.\n for (const k of Object.keys(headers)) if (k.toLowerCase() === \"authorization\") delete headers[k];\n headers.Authorization = `Bearer ${s.apiKey}`;\n out.push({ name: \"online\", endpoint: onlineTracesUrl(s), headers, timeoutMs: s.exportTimeoutMs });\n }\n return out;\n}\n\n/** The fix to name when the online destination is not usable (the verb is `observer sdk sign-in`, R-B17). */\nexport const ONLINE_FIX = \"run `observer sdk sign-in`, or set SUPERBASED_ORG_URL and SUPERBASED_API_KEY\";\n\n/** Why a destination choice cannot be honoured in full (empty = fine). */\nexport function destinationProblems(s: Settings, choice: DestinationChoice | \"\"): string[] {\n if (choice !== \"online\" && choice !== \"both\") return [];\n const missing: string[] = [];\n if (!onlineTracesUrl(s)) missing.push(\"a gateway URL\");\n if (!s.apiKey) missing.push(\"an SDK credential\");\n if (!missing.length) return [];\n const effect = choice === \"online\" ? \"nothing is exported\" : \"exporting to this machine only\";\n return [`destination ${choice} is missing ${missing.join(\" and \")}; ${effect}. To fix: ${ONLINE_FIX}`];\n}\n"]}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Per-request trace attributes (end user, session, tenant, tags, metadata,
3
+ * release, environment) carried through async work with AsyncLocalStorage
4
+ * (contract sdk-api-surface.md section 2).
5
+ *
6
+ * Every span started while attributes are in scope gets them, whether the
7
+ * SDK, an `instrument()` instrumentation or your own OTel code started it:
8
+ * the SDK's span processor stamps them at span start, never over a value the
9
+ * span already carries. The span active when you call `identify` or
10
+ * `propagateAttributes` gets the values you just set too.
11
+ *
12
+ * Merge rules (inner over outer): scalars, inner wins, `undefined` leaves
13
+ * the outer value and `""` clears it; tags, union (trimmed, de-duplicated,
14
+ * sorted, at most 32 of 128 chars); metadata, per key, inner wins, a `null`
15
+ * value removes the key, non-strings JSON-encoded, at most 32 keys (the
16
+ * lexically smallest kept), key 128 and value 512 chars. These are
17
+ * `otelident.NormalizeTags` / `NormalizeMetadata`.
18
+ */
19
+ import { type AttributeValue } from "@opentelemetry/api";
20
+ /** Per-trace attributes: who and what a request belongs to. */
21
+ export interface TraceAttributes {
22
+ /** The app's end user (PII; `sbo.user`). */
23
+ user?: string;
24
+ /** The app's conversation or user session (`session.id`). */
25
+ sessionId?: string;
26
+ /** The app's own customer / tenant (`sbo.tenant`). */
27
+ tenant?: string;
28
+ /** Tags (`sbo.tags`); unioned with tags already in scope. */
29
+ tags?: string[];
30
+ /** Metadata (`sbo.metadata.<key>`); merged over metadata already in scope. */
31
+ metadata?: Record<string, unknown>;
32
+ /** The app's release / build label (`sbo.release`). */
33
+ release?: string;
34
+ /** The app's deployment environment (`sbo.environment`). */
35
+ environment?: string;
36
+ }
37
+ export interface PropagateOptions extends TraceAttributes {
38
+ /**
39
+ * Also carry the values in W3C baggage, so `inject()` sends them to
40
+ * downstream services, which restore them in `continueTrace()`. Baggage
41
+ * travels in request headers: only use it for values those services may see.
42
+ */
43
+ asBaggage?: boolean;
44
+ }
45
+ /** Option name -> span attribute, for the scalar options. */
46
+ export declare const SCALAR_KEYS: {
47
+ readonly user: "sbo.user";
48
+ readonly sessionId: "session.id";
49
+ readonly tenant: "sbo.tenant";
50
+ readonly release: "sbo.release";
51
+ readonly environment: "sbo.environment";
52
+ };
53
+ /** otelident.NormalizeTags: trimmed, clamped, de-duplicated, sorted, capped. */
54
+ export declare function normalizeTags(...lists: Array<Iterable<unknown> | string | undefined | null>): string[];
55
+ /** otelident.NormalizeMetadata, later maps winning; a null value removes the key. */
56
+ export declare function normalizeMetadata(...maps: Array<Record<string, unknown> | undefined | null>): Record<string, string>;
57
+ /** An immutable set of per-request values (one level of nesting). */
58
+ export declare class Scope {
59
+ readonly scalars: Readonly<Record<string, string>>;
60
+ readonly tags: readonly string[];
61
+ readonly metadata: Readonly<Record<string, string>>;
62
+ readonly baggage: boolean;
63
+ constructor(scalars?: Readonly<Record<string, string>>, tags?: readonly string[], metadata?: Readonly<Record<string, string>>, baggage?: boolean);
64
+ /** This scope with `opts` on top. */
65
+ merged(opts: PropagateOptions): Scope;
66
+ /** The span attributes this scope writes. */
67
+ attributes(): Record<string, AttributeValue>;
68
+ /** The option-named view (`getCurrentAttributes`). */
69
+ public(): TraceAttributes;
70
+ }
71
+ export declare function currentScope(): Scope;
72
+ /** The span attributes in effect for a span started here. */
73
+ export declare function scopeAttributes(): Record<string, AttributeValue>;
74
+ /** The per-request values in effect here, by option name. */
75
+ export declare function getCurrentAttributes(): TraceAttributes;
76
+ /**
77
+ * Run `fn` with `attrs` merged over the attributes already in scope. Every
78
+ * span started inside, at any async depth, carries them. Returns `fn`'s value
79
+ * (sync stays sync; a promise for an async `fn`).
80
+ *
81
+ * ```ts
82
+ * app.post("/chat", (req, res) =>
83
+ * propagateAttributes({ user: req.user.id, sessionId: req.body.thread }, () => handle(req, res)));
84
+ * ```
85
+ */
86
+ export declare function propagateAttributes<T>(attrs: PropagateOptions, fn: () => T): T;
87
+ /** The handle `identify()` returns. */
88
+ export interface AttributeScope {
89
+ /** Undo this identify (restore what was in scope before it). */
90
+ reset(): void;
91
+ }
92
+ /**
93
+ * Set trace attributes for the rest of the current async context (the
94
+ * remainder of this request handler and everything it awaits or starts),
95
+ * and on the active span. Returns a handle whose `reset()` undoes it. Prefer
96
+ * {@link propagateAttributes} when you can wrap the work in a callback.
97
+ */
98
+ export declare function identify(attrs: TraceAttributes): AttributeScope;
99
+ /** Run `fn` with `scope` in effect (continueTrace). */
100
+ export declare function runWithScope<T>(scope: Scope, fn: () => T): T;
101
+ /** Forget scoped attributes (tests only). */
102
+ export declare function _resetContextForTests(): void;