@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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +438 -2
- package/dist/cjs/admit.d.ts +139 -0
- package/dist/cjs/admit.js +442 -0
- package/dist/cjs/admit.js.map +1 -0
- package/dist/cjs/attrs.d.ts +113 -0
- package/dist/cjs/attrs.js +183 -0
- package/dist/cjs/attrs.js.map +1 -0
- package/dist/cjs/config.d.ts +202 -0
- package/dist/cjs/config.js +386 -0
- package/dist/cjs/config.js.map +1 -0
- package/dist/cjs/context.d.ts +102 -0
- package/dist/cjs/context.js +234 -0
- package/dist/cjs/context.js.map +1 -0
- package/dist/cjs/control.d.ts +99 -0
- package/dist/cjs/control.js +243 -0
- package/dist/cjs/control.js.map +1 -0
- package/dist/cjs/cost.d.ts +108 -0
- package/dist/cjs/cost.js +211 -0
- package/dist/cjs/cost.js.map +1 -0
- package/dist/cjs/destination.d.ts +125 -0
- package/dist/cjs/destination.js +357 -0
- package/dist/cjs/destination.js.map +1 -0
- package/dist/cjs/experiments.d.ts +237 -0
- package/dist/cjs/experiments.js +678 -0
- package/dist/cjs/experiments.js.map +1 -0
- package/dist/cjs/export.d.ts +84 -0
- package/dist/cjs/export.js +328 -0
- package/dist/cjs/export.js.map +1 -0
- package/dist/cjs/index.d.ts +168 -0
- package/dist/cjs/index.js +581 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/instrument.d.ts +88 -0
- package/dist/cjs/instrument.js +397 -0
- package/dist/cjs/instrument.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/policy.d.ts +77 -0
- package/dist/cjs/policy.js +252 -0
- package/dist/cjs/policy.js.map +1 -0
- package/dist/cjs/prompts.d.ts +175 -0
- package/dist/cjs/prompts.js +476 -0
- package/dist/cjs/prompts.js.map +1 -0
- package/dist/cjs/propagation.d.ts +34 -0
- package/dist/cjs/propagation.js +151 -0
- package/dist/cjs/propagation.js.map +1 -0
- package/dist/cjs/req.d.ts +10 -0
- package/dist/cjs/req.js +3 -0
- package/dist/cjs/req.js.map +1 -0
- package/dist/cjs/runtime.d.ts +44 -0
- package/dist/cjs/runtime.js +67 -0
- package/dist/cjs/runtime.js.map +1 -0
- package/dist/cjs/scores.d.ts +102 -0
- package/dist/cjs/scores.js +226 -0
- package/dist/cjs/scores.js.map +1 -0
- package/dist/cjs/spans.d.ts +193 -0
- package/dist/cjs/spans.js +398 -0
- package/dist/cjs/spans.js.map +1 -0
- package/dist/cjs/vendor.d.ts +33 -0
- package/dist/cjs/vendor.js +67 -0
- package/dist/cjs/vendor.js.map +1 -0
- package/dist/esm/admit.d.ts +139 -0
- package/dist/esm/admit.js +432 -0
- package/dist/esm/admit.js.map +1 -0
- package/dist/esm/attrs.d.ts +113 -0
- package/dist/esm/attrs.js +179 -0
- package/dist/esm/attrs.js.map +1 -0
- package/dist/esm/config.d.ts +202 -0
- package/dist/esm/config.js +364 -0
- package/dist/esm/config.js.map +1 -0
- package/dist/esm/context.d.ts +102 -0
- package/dist/esm/context.js +221 -0
- package/dist/esm/context.js.map +1 -0
- package/dist/esm/control.d.ts +99 -0
- package/dist/esm/control.js +230 -0
- package/dist/esm/control.js.map +1 -0
- package/dist/esm/cost.d.ts +108 -0
- package/dist/esm/cost.js +202 -0
- package/dist/esm/cost.js.map +1 -0
- package/dist/esm/destination.d.ts +125 -0
- package/dist/esm/destination.js +346 -0
- package/dist/esm/destination.js.map +1 -0
- package/dist/esm/experiments.d.ts +237 -0
- package/dist/esm/experiments.js +666 -0
- package/dist/esm/experiments.js.map +1 -0
- package/dist/esm/export.d.ts +84 -0
- package/dist/esm/export.js +314 -0
- package/dist/esm/export.js.map +1 -0
- package/dist/esm/index.d.ts +168 -0
- package/dist/esm/index.js +500 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/instrument.d.ts +88 -0
- package/dist/esm/instrument.js +391 -0
- package/dist/esm/instrument.js.map +1 -0
- package/dist/esm/policy.d.ts +77 -0
- package/dist/esm/policy.js +240 -0
- package/dist/esm/policy.js.map +1 -0
- package/dist/esm/prompts.d.ts +175 -0
- package/dist/esm/prompts.js +460 -0
- package/dist/esm/prompts.js.map +1 -0
- package/dist/esm/propagation.d.ts +34 -0
- package/dist/esm/propagation.js +145 -0
- package/dist/esm/propagation.js.map +1 -0
- package/dist/esm/req.d.ts +10 -0
- package/dist/esm/req.js +2 -0
- package/dist/esm/req.js.map +1 -0
- package/dist/esm/runtime.d.ts +44 -0
- package/dist/esm/runtime.js +59 -0
- package/dist/esm/runtime.js.map +1 -0
- package/dist/esm/scores.d.ts +102 -0
- package/dist/esm/scores.js +219 -0
- package/dist/esm/scores.js.map +1 -0
- package/dist/esm/spans.d.ts +193 -0
- package/dist/esm/spans.js +378 -0
- package/dist/esm/spans.js.map +1 -0
- package/dist/esm/vendor.d.ts +33 -0
- package/dist/esm/vendor.js +61 -0
- package/dist/esm/vendor.js.map +1 -0
- package/package.json +130 -4
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* W3C trace-context helpers (contract sdk-api-surface.md section 4), for
|
|
3
|
+
* joining a trace across a process boundary the SDK does not instrument (a
|
|
4
|
+
* queue message, a job, a hand-rolled HTTP call). They always use the W3C
|
|
5
|
+
* propagators, whatever global propagator the host has configured.
|
|
6
|
+
*
|
|
7
|
+
* `inject()` also writes `baggage` when per-request values were set with
|
|
8
|
+
* `propagateAttributes({ ..., asBaggage: true })`; `continueTrace()` restores
|
|
9
|
+
* them into the attribute scope on the other side.
|
|
10
|
+
*/
|
|
11
|
+
import { context, propagation, trace } from "@opentelemetry/api";
|
|
12
|
+
import { W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
13
|
+
import { K } from "./attrs.js";
|
|
14
|
+
import { currentScope, runWithScope, SCALAR_KEYS } from "./context.js";
|
|
15
|
+
const traceContext = new W3CTraceContextPropagator();
|
|
16
|
+
const baggageProp = new W3CBaggagePropagator();
|
|
17
|
+
const getter = {
|
|
18
|
+
keys(c) {
|
|
19
|
+
const fe = c.forEach;
|
|
20
|
+
if (typeof c.get === "function" && typeof fe === "function") {
|
|
21
|
+
const out = [];
|
|
22
|
+
c.forEach((_v, k) => out.push(k));
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
return Object.keys(c);
|
|
26
|
+
},
|
|
27
|
+
get(c, key) {
|
|
28
|
+
if (typeof c.get === "function") {
|
|
29
|
+
return c.get(key) ?? undefined;
|
|
30
|
+
}
|
|
31
|
+
const rec = c;
|
|
32
|
+
const want = key.toLowerCase();
|
|
33
|
+
const hit = Object.keys(rec).find((k) => k.toLowerCase() === want);
|
|
34
|
+
return hit === undefined ? undefined : rec[hit];
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
function withScopeBaggage(ctx) {
|
|
38
|
+
const scope = currentScope();
|
|
39
|
+
if (!scope.baggage)
|
|
40
|
+
return ctx;
|
|
41
|
+
const entries = {};
|
|
42
|
+
for (const [k, v] of Object.entries(scope.scalars))
|
|
43
|
+
entries[k] = { value: v };
|
|
44
|
+
if (scope.tags.length)
|
|
45
|
+
entries[K.tags] = { value: scope.tags.join(",") };
|
|
46
|
+
for (const [k, v] of Object.entries(scope.metadata))
|
|
47
|
+
entries[K.metadataPrefix + k] = { value: v };
|
|
48
|
+
const existing = propagation.getBaggage(ctx);
|
|
49
|
+
let bag = existing ?? propagation.createBaggage();
|
|
50
|
+
for (const [k, e] of Object.entries(entries))
|
|
51
|
+
bag = bag.setEntry(k, e);
|
|
52
|
+
return propagation.setBaggage(ctx, bag);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Write `traceparent` (+ `tracestate`, + `baggage` when per-request values
|
|
56
|
+
* were set `asBaggage`) for the current context into `carrier` (a new object
|
|
57
|
+
* when omitted) and return it.
|
|
58
|
+
*
|
|
59
|
+
* ```ts
|
|
60
|
+
* await queue.send({ body, headers: inject() });
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export function inject(carrier) {
|
|
64
|
+
const out = (carrier ?? {});
|
|
65
|
+
try {
|
|
66
|
+
const ctx = withScopeBaggage(context.active());
|
|
67
|
+
const setter = {
|
|
68
|
+
set(c, k, v) {
|
|
69
|
+
c[k] = v;
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
traceContext.inject(ctx, out, setter);
|
|
73
|
+
baggageProp.inject(ctx, out, setter);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// never break the caller
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/** The context the W3C headers in `carrier` describe (case-insensitive); the active context when there are none. */
|
|
81
|
+
export function extract(carrier) {
|
|
82
|
+
const base = context.active();
|
|
83
|
+
try {
|
|
84
|
+
return baggageProp.extract(traceContext.extract(base, carrier ?? {}, getter), carrier ?? {}, getter);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return base;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function scopeFromBaggage(ctx) {
|
|
91
|
+
const bag = propagation.getBaggage(ctx);
|
|
92
|
+
if (!bag)
|
|
93
|
+
return null;
|
|
94
|
+
const reverse = Object.fromEntries(Object.entries(SCALAR_KEYS).map(([name, key]) => [key, name]));
|
|
95
|
+
const opts = { asBaggage: true };
|
|
96
|
+
const meta = {};
|
|
97
|
+
let any = false;
|
|
98
|
+
for (const [key, entry] of bag.getAllEntries()) {
|
|
99
|
+
if (key in reverse) {
|
|
100
|
+
opts[reverse[key]] = entry.value;
|
|
101
|
+
any = true;
|
|
102
|
+
}
|
|
103
|
+
else if (key === K.tags) {
|
|
104
|
+
opts.tags = entry.value.split(",");
|
|
105
|
+
any = true;
|
|
106
|
+
}
|
|
107
|
+
else if (key.startsWith(K.metadataPrefix)) {
|
|
108
|
+
meta[key.slice(K.metadataPrefix.length)] = entry.value;
|
|
109
|
+
any = true;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!any)
|
|
113
|
+
return null;
|
|
114
|
+
if (Object.keys(meta).length)
|
|
115
|
+
opts.metadata = meta;
|
|
116
|
+
return currentScope().merged(opts);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Run `fn` as part of the trace `carrier` names (spans inside join the
|
|
120
|
+
* caller's trace), restoring per-request values the caller sent as baggage.
|
|
121
|
+
*/
|
|
122
|
+
export function continueTrace(carrier, fn) {
|
|
123
|
+
const ctx = extract(carrier);
|
|
124
|
+
const scope = scopeFromBaggage(ctx);
|
|
125
|
+
const run = () => context.with(ctx, fn);
|
|
126
|
+
return scope ? runWithScope(scope, run) : run();
|
|
127
|
+
}
|
|
128
|
+
/** The `traceparent` value of the active span ("" outside a span). */
|
|
129
|
+
export function getTraceparent() {
|
|
130
|
+
if (!trace.getActiveSpan())
|
|
131
|
+
return "";
|
|
132
|
+
const out = {};
|
|
133
|
+
try {
|
|
134
|
+
traceContext.inject(context.active(), out, {
|
|
135
|
+
set(c, k, v) {
|
|
136
|
+
c[k] = v;
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return "";
|
|
142
|
+
}
|
|
143
|
+
return out.traceparent ?? "";
|
|
144
|
+
}
|
|
145
|
+
//# sourceMappingURL=propagation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"propagation.js","sourceRoot":"","sources":["../../src/propagation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAoC,MAAM,oBAAoB,CAAC;AACnG,OAAO,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAEtF,OAAO,EAAE,CAAC,EAAE,MAAM,YAAY,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,EAAgC,MAAM,cAAc,CAAC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;AACtE,MAAM,UAAU,cAAc;IAC5B,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE;QAAE,OAAO,EAAE,CAAC;IACtC,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,IAAI,CAAC;QACH,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE;YACzC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;gBACR,CAA4B,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YACvC,CAAC;SACF,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO,GAAG,CAAC,WAAW,IAAI,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["/**\n * W3C trace-context helpers (contract sdk-api-surface.md section 4), for\n * joining a trace across a process boundary the SDK does not instrument (a\n * queue message, a job, a hand-rolled HTTP call). They always use the W3C\n * propagators, whatever global propagator the host has configured.\n *\n * `inject()` also writes `baggage` when per-request values were set with\n * `propagateAttributes({ ..., asBaggage: true })`; `continueTrace()` restores\n * them into the attribute scope on the other side.\n */\n\nimport { context, propagation, trace, type Context, type TextMapGetter } from \"@opentelemetry/api\";\nimport { W3CBaggagePropagator, W3CTraceContextPropagator } from \"@opentelemetry/core\";\n\nimport { K } from \"./attrs.js\";\nimport { currentScope, runWithScope, SCALAR_KEYS, Scope, type PropagateOptions } from \"./context.js\";\n\nconst traceContext = new W3CTraceContextPropagator();\nconst baggageProp = new W3CBaggagePropagator();\n\n/** A header bag: a plain object (string or string[] values) or a fetch `Headers`. */\nexport type Carrier = Record<string, string | string[] | undefined> | { get(name: string): string | null };\n\nconst getter: TextMapGetter<Carrier> = {\n keys(c) {\n const fe = (c as { forEach?: unknown }).forEach;\n if (typeof (c as { get?: unknown }).get === \"function\" && typeof fe === \"function\") {\n const out: string[] = [];\n (c as unknown as { forEach(cb: (v: string, k: string) => void): void }).forEach((_v, k) => out.push(k));\n return out;\n }\n return Object.keys(c);\n },\n get(c, key) {\n if (typeof (c as { get?: unknown }).get === \"function\") {\n return (c as { get(name: string): string | null }).get(key) ?? undefined;\n }\n const rec = c as Record<string, string | string[] | undefined>;\n const want = key.toLowerCase();\n const hit = Object.keys(rec).find((k) => k.toLowerCase() === want);\n return hit === undefined ? undefined : rec[hit];\n },\n};\n\nfunction withScopeBaggage(ctx: Context): Context {\n const scope = currentScope();\n if (!scope.baggage) return ctx;\n const entries: Record<string, { value: string }> = {};\n for (const [k, v] of Object.entries(scope.scalars)) entries[k] = { value: v };\n if (scope.tags.length) entries[K.tags] = { value: scope.tags.join(\",\") };\n for (const [k, v] of Object.entries(scope.metadata)) entries[K.metadataPrefix + k] = { value: v };\n const existing = propagation.getBaggage(ctx);\n let bag = existing ?? propagation.createBaggage();\n for (const [k, e] of Object.entries(entries)) bag = bag.setEntry(k, e);\n return propagation.setBaggage(ctx, bag);\n}\n\n/**\n * Write `traceparent` (+ `tracestate`, + `baggage` when per-request values\n * were set `asBaggage`) for the current context into `carrier` (a new object\n * when omitted) and return it.\n *\n * ```ts\n * await queue.send({ body, headers: inject() });\n * ```\n */\nexport function inject<T extends Record<string, string>>(carrier?: T): T {\n const out = (carrier ?? {}) as T;\n try {\n const ctx = withScopeBaggage(context.active());\n const setter = {\n set(c: T, k: string, v: string) {\n (c as Record<string, string>)[k] = v;\n },\n };\n traceContext.inject(ctx, out, setter);\n baggageProp.inject(ctx, out, setter);\n } catch {\n // never break the caller\n }\n return out;\n}\n\n/** The context the W3C headers in `carrier` describe (case-insensitive); the active context when there are none. */\nexport function extract(carrier: Carrier): Context {\n const base = context.active();\n try {\n return baggageProp.extract(traceContext.extract(base, carrier ?? {}, getter), carrier ?? {}, getter);\n } catch {\n return base;\n }\n}\n\nfunction scopeFromBaggage(ctx: Context): Scope | null {\n const bag = propagation.getBaggage(ctx);\n if (!bag) return null;\n const reverse = Object.fromEntries(Object.entries(SCALAR_KEYS).map(([name, key]) => [key, name]));\n const opts: PropagateOptions = { asBaggage: true };\n const meta: Record<string, string> = {};\n let any = false;\n for (const [key, entry] of bag.getAllEntries()) {\n if (key in reverse) {\n (opts as Record<string, unknown>)[reverse[key]] = entry.value;\n any = true;\n } else if (key === K.tags) {\n opts.tags = entry.value.split(\",\");\n any = true;\n } else if (key.startsWith(K.metadataPrefix)) {\n meta[key.slice(K.metadataPrefix.length)] = entry.value;\n any = true;\n }\n }\n if (!any) return null;\n if (Object.keys(meta).length) opts.metadata = meta;\n return currentScope().merged(opts);\n}\n\n/**\n * Run `fn` as part of the trace `carrier` names (spans inside join the\n * caller's trace), restoring per-request values the caller sent as baggage.\n */\nexport function continueTrace<T>(carrier: Carrier, fn: () => T): T {\n const ctx = extract(carrier);\n const scope = scopeFromBaggage(ctx);\n const run = () => context.with(ctx, fn);\n return scope ? runWithScope(scope, run) : run();\n}\n\n/** The `traceparent` value of the active span (\"\" outside a span). */\nexport function getTraceparent(): string {\n if (!trace.getActiveSpan()) return \"\";\n const out: Record<string, string> = {};\n try {\n traceContext.inject(context.active(), out, {\n set(c, k, v) {\n (c as Record<string, string>)[k] = v;\n },\n });\n } catch {\n return \"\";\n }\n return out.traceparent ?? \"\";\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loading optional peer dependencies from both builds.
|
|
3
|
+
*
|
|
4
|
+
* This source is only the type-checked stand-in: `scripts/build.mjs` writes
|
|
5
|
+
* the real `dist/esm/req.js` (`createRequire(import.meta.url)`) and
|
|
6
|
+
* `dist/cjs/req.js` (the module's own `require`), because `import.meta`
|
|
7
|
+
* cannot be compiled to CommonJS.
|
|
8
|
+
*/
|
|
9
|
+
/** A `require` that resolves from this package's location. */
|
|
10
|
+
export declare const req: NodeJS.Require;
|
package/dist/esm/req.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"req.js","sourceRoot":"","sources":["../../src/req.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAI5C,8DAA8D;AAC9D,MAAM,CAAC,MAAM,GAAG,GAAmB,aAAa,CAAC,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC","sourcesContent":["/**\n * Loading optional peer dependencies from both builds.\n *\n * This source is only the type-checked stand-in: `scripts/build.mjs` writes\n * the real `dist/esm/req.js` (`createRequire(import.meta.url)`) and\n * `dist/cjs/req.js` (the module's own `require`), because `import.meta`\n * cannot be compiled to CommonJS.\n */\n\nimport { createRequire } from \"node:module\";\n\ndeclare const __filename: string | undefined;\n\n/** A `require` that resolves from this package's location. */\nexport const req: NodeJS.Require = createRequire(typeof __filename === \"string\" ? __filename : `${process.cwd()}/`);\n"]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-wide SDK runtime state shared by the modules: the resolved
|
|
3
|
+
* settings, the tracer and the content switches. One owner (init in
|
|
4
|
+
* index.ts writes it); everything else reads it.
|
|
5
|
+
*/
|
|
6
|
+
import { type Tracer, type TracerProvider } from "@opentelemetry/api";
|
|
7
|
+
import type { DestinationChoice, Settings } from "./config.js";
|
|
8
|
+
export declare const VERSION = "0.1.0";
|
|
9
|
+
export declare const TRACER_NAME = "@superbased/sdk";
|
|
10
|
+
export declare const SDK_MARKER = "superbased-typescript";
|
|
11
|
+
export interface Runtime {
|
|
12
|
+
settings: Settings | null;
|
|
13
|
+
tracer: Tracer | null;
|
|
14
|
+
captureContent: boolean;
|
|
15
|
+
maxContentChars: number;
|
|
16
|
+
/** The destination in force ("" before it is known). */
|
|
17
|
+
destination: DestinationChoice | "";
|
|
18
|
+
/** Where that destination came from: argument, env, machine, default, endpoint or exporter. */
|
|
19
|
+
destinationSource: string;
|
|
20
|
+
/** The machine's admission URL from discovery ("" when not discovered). */
|
|
21
|
+
admissionUrl: string;
|
|
22
|
+
/** The provider holding the SDK's spans (instrumentations are registered on it). */
|
|
23
|
+
provider: TracerProvider | null;
|
|
24
|
+
/**
|
|
25
|
+
* The resource `service.name` of the last span the SDK's processor saw
|
|
26
|
+
* ("" before one): what service-scoped budget caps match, read from the
|
|
27
|
+
* span because a provider's resource is not public in OTel JS 2.x.
|
|
28
|
+
*/
|
|
29
|
+
resourceService: string;
|
|
30
|
+
/**
|
|
31
|
+
* Settles once the destination is known (init's discovery answer, bounded
|
|
32
|
+
* by `discoverTimeoutMs`); never rejects. Every control call waits on it
|
|
33
|
+
* before it picks a target (review E-33), as Python resolves at init.
|
|
34
|
+
*/
|
|
35
|
+
ready: Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
export declare const runtime: Runtime;
|
|
38
|
+
/** Wait until the destination is known (see {@link Runtime.ready}). */
|
|
39
|
+
export declare function destinationKnown(): Promise<void>;
|
|
40
|
+
export declare function tracer(): Tracer;
|
|
41
|
+
export declare function truncateContent(value: string): string;
|
|
42
|
+
/** Render any value as content text (strings as-is, the rest as JSON). */
|
|
43
|
+
export declare function contentText(v: unknown): string;
|
|
44
|
+
export declare function resetRuntime(): void;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-wide SDK runtime state shared by the modules: the resolved
|
|
3
|
+
* settings, the tracer and the content switches. One owner (init in
|
|
4
|
+
* index.ts writes it); everything else reads it.
|
|
5
|
+
*/
|
|
6
|
+
import { trace } from "@opentelemetry/api";
|
|
7
|
+
export const VERSION = "0.1.0";
|
|
8
|
+
export const TRACER_NAME = "@superbased/sdk";
|
|
9
|
+
export const SDK_MARKER = "superbased-typescript";
|
|
10
|
+
export const runtime = {
|
|
11
|
+
settings: null,
|
|
12
|
+
tracer: null,
|
|
13
|
+
captureContent: true,
|
|
14
|
+
maxContentChars: 8000,
|
|
15
|
+
destination: "",
|
|
16
|
+
destinationSource: "",
|
|
17
|
+
admissionUrl: "",
|
|
18
|
+
provider: null,
|
|
19
|
+
resourceService: "",
|
|
20
|
+
ready: Promise.resolve(),
|
|
21
|
+
};
|
|
22
|
+
/** Wait until the destination is known (see {@link Runtime.ready}). */
|
|
23
|
+
export function destinationKnown() {
|
|
24
|
+
return runtime.ready;
|
|
25
|
+
}
|
|
26
|
+
export function tracer() {
|
|
27
|
+
return runtime.tracer ?? trace.getTracer(TRACER_NAME, VERSION);
|
|
28
|
+
}
|
|
29
|
+
export function truncateContent(value) {
|
|
30
|
+
const max = runtime.maxContentChars;
|
|
31
|
+
return max > 0 && value.length > max ? value.slice(0, max) + "…[truncated]" : value;
|
|
32
|
+
}
|
|
33
|
+
/** Render any value as content text (strings as-is, the rest as JSON). */
|
|
34
|
+
export function contentText(v) {
|
|
35
|
+
if (typeof v === "string")
|
|
36
|
+
return v;
|
|
37
|
+
try {
|
|
38
|
+
const s = JSON.stringify(v);
|
|
39
|
+
return s === undefined ? String(v) : s;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return String(v);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export function resetRuntime() {
|
|
46
|
+
Object.assign(runtime, {
|
|
47
|
+
settings: null,
|
|
48
|
+
tracer: null,
|
|
49
|
+
captureContent: true,
|
|
50
|
+
maxContentChars: 8000,
|
|
51
|
+
destination: "",
|
|
52
|
+
destinationSource: "",
|
|
53
|
+
admissionUrl: "",
|
|
54
|
+
provider: null,
|
|
55
|
+
resourceService: "",
|
|
56
|
+
ready: Promise.resolve(),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAoC,MAAM,oBAAoB,CAAC;AAI7E,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAC/B,MAAM,CAAC,MAAM,WAAW,GAAG,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;IACnB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,YAAY;IAC1B,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE;QACrB,QAAQ,EAAE,IAAI;QACd,MAAM,EAAE,IAAI;QACZ,cAAc,EAAE,IAAI;QACpB,eAAe,EAAE,IAAI;QACrB,WAAW,EAAE,EAAE;QACf,iBAAiB,EAAE,EAAE;QACrB,YAAY,EAAE,EAAE;QAChB,QAAQ,EAAE,IAAI;QACd,eAAe,EAAE,EAAE;QACnB,KAAK,EAAE,OAAO,CAAC,OAAO,EAAE;KACzB,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Process-wide SDK runtime state shared by the modules: the resolved\n * settings, the tracer and the content switches. One owner (init in\n * index.ts writes it); everything else reads it.\n */\n\nimport { trace, type Tracer, type TracerProvider } from \"@opentelemetry/api\";\n\nimport type { DestinationChoice, Settings } from \"./config.js\";\n\nexport const VERSION = \"0.1.0\";\nexport const TRACER_NAME = \"@superbased/sdk\";\nexport const SDK_MARKER = \"superbased-typescript\";\n\nexport interface Runtime {\n settings: Settings | null;\n tracer: Tracer | null;\n captureContent: boolean;\n maxContentChars: number;\n /** The destination in force (\"\" before it is known). */\n destination: DestinationChoice | \"\";\n /** Where that destination came from: argument, env, machine, default, endpoint or exporter. */\n destinationSource: string;\n /** The machine's admission URL from discovery (\"\" when not discovered). */\n admissionUrl: string;\n /** The provider holding the SDK's spans (instrumentations are registered on it). */\n provider: TracerProvider | null;\n /**\n * The resource `service.name` of the last span the SDK's processor saw\n * (\"\" before one): what service-scoped budget caps match, read from the\n * span because a provider's resource is not public in OTel JS 2.x.\n */\n resourceService: string;\n /**\n * Settles once the destination is known (init's discovery answer, bounded\n * by `discoverTimeoutMs`); never rejects. Every control call waits on it\n * before it picks a target (review E-33), as Python resolves at init.\n */\n ready: Promise<void>;\n}\n\nexport const runtime: Runtime = {\n settings: null,\n tracer: null,\n captureContent: true,\n maxContentChars: 8000,\n destination: \"\",\n destinationSource: \"\",\n admissionUrl: \"\",\n provider: null,\n resourceService: \"\",\n ready: Promise.resolve(),\n};\n\n/** Wait until the destination is known (see {@link Runtime.ready}). */\nexport function destinationKnown(): Promise<void> {\n return runtime.ready;\n}\n\nexport function tracer(): Tracer {\n return runtime.tracer ?? trace.getTracer(TRACER_NAME, VERSION);\n}\n\nexport function truncateContent(value: string): string {\n const max = runtime.maxContentChars;\n return max > 0 && value.length > max ? value.slice(0, max) + \"…[truncated]\" : value;\n}\n\n/** Render any value as content text (strings as-is, the rest as JSON). */\nexport function contentText(v: unknown): string {\n if (typeof v === \"string\") return v;\n try {\n const s = JSON.stringify(v);\n return s === undefined ? String(v) : s;\n } catch {\n return String(v);\n }\n}\n\nexport function resetRuntime(): void {\n Object.assign(runtime, {\n settings: null,\n tracer: null,\n captureContent: true,\n maxContentChars: 8000,\n destination: \"\",\n destinationSource: \"\",\n admissionUrl: \"\",\n provider: null,\n resourceService: \"\",\n ready: Promise.resolve(),\n });\n}\n"]}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scores and feedback (W3-1; contract `contracts/scores.md`, lane B7; the
|
|
3
|
+
* API is sdk-api-surface.md section 7.1, the same as Python's).
|
|
4
|
+
*
|
|
5
|
+
* A score is one judgement about one trace or one span: a name, a value, who
|
|
6
|
+
* produced it, an optional comment. Feedback is a score an end user of the
|
|
7
|
+
* app gave. Both are written through the SDK control API to every target of
|
|
8
|
+
* the destination in force: online `POST <org>/v1/sdk/scores` (scope
|
|
9
|
+
* `sdk:write`), local `POST <machine>/api/obs/scores`, `both` to each with
|
|
10
|
+
* the same `id`, so the stored score id is the same on both sides. They land
|
|
11
|
+
* on the existing owners (org annotations, machine `obs_eval_scores`); the
|
|
12
|
+
* SDK adds no store of its own.
|
|
13
|
+
*
|
|
14
|
+
* The id makes a write idempotent: the SDK mints `sdk_<32 hex>` when you
|
|
15
|
+
* give none and reuses it on its one retry, so a retried write never doubles
|
|
16
|
+
* a score.
|
|
17
|
+
*
|
|
18
|
+
* Nothing throws: a score the scorecore rules refuse (a bad name, a kind
|
|
19
|
+
* that disagrees with the value, no trace) resolves with `ok: false` and an
|
|
20
|
+
* error naming the contract's code, before any call; network and server
|
|
21
|
+
* failures resolve the same way. flush() waits for pending writes.
|
|
22
|
+
*/
|
|
23
|
+
import { type ControlOptions, type Route } from "./control.js";
|
|
24
|
+
export declare const SCORES_ROUTE: Route;
|
|
25
|
+
/** numeric, boolean or categorical; inferred from the value's type when not given. */
|
|
26
|
+
export type ScoreKind = "numeric" | "boolean" | "categorical";
|
|
27
|
+
export declare const SCORE_KINDS: readonly ScoreKind[];
|
|
28
|
+
export declare const DEFAULT_FEEDBACK_NAME = "user_feedback";
|
|
29
|
+
export interface ScoreOptions extends ControlOptions {
|
|
30
|
+
/** Defaults to the active trace. */
|
|
31
|
+
traceId?: string;
|
|
32
|
+
/** Score one span of the trace; unset, the score is trace-level (also inside a span, as in Python). */
|
|
33
|
+
spanId?: string;
|
|
34
|
+
comment?: string;
|
|
35
|
+
/** The value kind; must agree with the value's type (`kind_mismatch` otherwise). */
|
|
36
|
+
kind?: ScoreKind;
|
|
37
|
+
/** The automated scorer that produced the value (1-64 chars). */
|
|
38
|
+
scorer?: string;
|
|
39
|
+
/** Its version (1-32 chars; default "1" when `scorer` is set), so two versions' results coexist. */
|
|
40
|
+
scorerVersion?: string;
|
|
41
|
+
/** An experiment run id: ties the score to that run. */
|
|
42
|
+
runId?: string;
|
|
43
|
+
/** The idempotency id (default `sdk_<32 hex>`, fresh per call). */
|
|
44
|
+
scoreId?: string;
|
|
45
|
+
/** When the judgement was made (default: the server's receive time). */
|
|
46
|
+
timestamp?: Date | string;
|
|
47
|
+
}
|
|
48
|
+
/** One destination's outcome. */
|
|
49
|
+
export interface ScoreDestinationResult {
|
|
50
|
+
ok: boolean;
|
|
51
|
+
status: number;
|
|
52
|
+
/** The stored score id (`sc_...`) this destination returned ("" when it did not accept). */
|
|
53
|
+
id: string;
|
|
54
|
+
error: string;
|
|
55
|
+
}
|
|
56
|
+
export interface ScoreResult {
|
|
57
|
+
/** True when EVERY destination accepted the score (as in Python). */
|
|
58
|
+
ok: boolean;
|
|
59
|
+
/** The stored score id (`sc_...`) the first accepting destination returned. */
|
|
60
|
+
id: string;
|
|
61
|
+
/** The idempotency id that was sent. */
|
|
62
|
+
clientId: string;
|
|
63
|
+
/** Each destination's outcome, by name (`local`, `online`). */
|
|
64
|
+
destinations: Record<string, ScoreDestinationResult>;
|
|
65
|
+
/** Every problem: validation (`<code>: <message>`) or per destination (`<name>: <error>`). */
|
|
66
|
+
errors: string[];
|
|
67
|
+
}
|
|
68
|
+
/** A score the rules refuse (contract scores.md section 1; the code is the contract's). */
|
|
69
|
+
export declare class ScoreError extends Error {
|
|
70
|
+
readonly code: string;
|
|
71
|
+
constructor(code: string, message: string);
|
|
72
|
+
}
|
|
73
|
+
interface BuildOptions extends ScoreOptions {
|
|
74
|
+
source?: "sdk" | "feedback";
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The wire score object (scores.md section 1), validated with the scorecore
|
|
78
|
+
* rules. Throws ScoreError naming the contract's code (`score()` turns that
|
|
79
|
+
* into a result; this is exported for tests and advanced callers).
|
|
80
|
+
*/
|
|
81
|
+
export declare function buildScore(name: string, value: unknown, o?: BuildOptions): Record<string, unknown>;
|
|
82
|
+
/**
|
|
83
|
+
* Attach a score to a trace (or one span of it). Never throws.
|
|
84
|
+
*
|
|
85
|
+
* ```ts
|
|
86
|
+
* await score("faithfulness", 0.92, { traceId, scorer: "judge", scorerVersion: "3" });
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export declare function score(name: string, value: number | string | boolean, opts?: ScoreOptions): Promise<ScoreResult>;
|
|
90
|
+
export interface FeedbackOptions extends Omit<ScoreOptions, "kind" | "scorer" | "scorerVersion" | "runId"> {
|
|
91
|
+
/** The score name (default `user_feedback`). */
|
|
92
|
+
name?: string;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Record an end user's feedback on a trace: a score with source `feedback`.
|
|
96
|
+
* 👍/👎 as true/false, a rating as a number, or a label. Call it from the
|
|
97
|
+
* request that receives the reaction (for example the backend route the
|
|
98
|
+
* `@superbased/feedback-widget` posts to), with the trace id your app got
|
|
99
|
+
* from `getCurrentTraceId()` when it answered. Never throws.
|
|
100
|
+
*/
|
|
101
|
+
export declare function feedback(value: number | string | boolean, opts?: FeedbackOptions): Promise<ScoreResult>;
|
|
102
|
+
export {};
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scores and feedback (W3-1; contract `contracts/scores.md`, lane B7; the
|
|
3
|
+
* API is sdk-api-surface.md section 7.1, the same as Python's).
|
|
4
|
+
*
|
|
5
|
+
* A score is one judgement about one trace or one span: a name, a value, who
|
|
6
|
+
* produced it, an optional comment. Feedback is a score an end user of the
|
|
7
|
+
* app gave. Both are written through the SDK control API to every target of
|
|
8
|
+
* the destination in force: online `POST <org>/v1/sdk/scores` (scope
|
|
9
|
+
* `sdk:write`), local `POST <machine>/api/obs/scores`, `both` to each with
|
|
10
|
+
* the same `id`, so the stored score id is the same on both sides. They land
|
|
11
|
+
* on the existing owners (org annotations, machine `obs_eval_scores`); the
|
|
12
|
+
* SDK adds no store of its own.
|
|
13
|
+
*
|
|
14
|
+
* The id makes a write idempotent: the SDK mints `sdk_<32 hex>` when you
|
|
15
|
+
* give none and reuses it on its one retry, so a retried write never doubles
|
|
16
|
+
* a score.
|
|
17
|
+
*
|
|
18
|
+
* Nothing throws: a score the scorecore rules refuse (a bad name, a kind
|
|
19
|
+
* that disagrees with the value, no trace) resolves with `ok: false` and an
|
|
20
|
+
* error naming the contract's code, before any call; network and server
|
|
21
|
+
* failures resolve the same way. flush() waits for pending writes.
|
|
22
|
+
*/
|
|
23
|
+
import { apiTimeout, call, noTargetReason, retryable, targets, track } from "./control.js";
|
|
24
|
+
import { getCurrentTraceId } from "./spans.js";
|
|
25
|
+
import { destinationKnown } from "./runtime.js";
|
|
26
|
+
export const SCORES_ROUTE = { online: "/scores", local: "/api/obs/scores" };
|
|
27
|
+
export const SCORE_KINDS = ["numeric", "boolean", "categorical"];
|
|
28
|
+
export const DEFAULT_FEEDBACK_NAME = "user_feedback";
|
|
29
|
+
const NAME = /^[a-z0-9_.-]{1,64}$/;
|
|
30
|
+
const ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
31
|
+
const TRACE = /^[0-9a-f]{32}$/;
|
|
32
|
+
const SPAN = /^[0-9a-f]{16}$/;
|
|
33
|
+
const MAX_VALUE_BYTES = 120;
|
|
34
|
+
const MAX_COMMENT_BYTES = 2000;
|
|
35
|
+
const MAX_SCORER_NAME = 64;
|
|
36
|
+
const MAX_SCORER_VERSION = 32;
|
|
37
|
+
/** A score the rules refuse (contract scores.md section 1; the code is the contract's). */
|
|
38
|
+
export class ScoreError extends Error {
|
|
39
|
+
code;
|
|
40
|
+
constructor(code, message) {
|
|
41
|
+
super(`${code}: ${message}`);
|
|
42
|
+
this.code = code;
|
|
43
|
+
this.name = "ScoreError";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function kindOf(value) {
|
|
47
|
+
if (typeof value === "boolean")
|
|
48
|
+
return "boolean";
|
|
49
|
+
if (typeof value === "number")
|
|
50
|
+
return "numeric";
|
|
51
|
+
if (typeof value === "string")
|
|
52
|
+
return "categorical";
|
|
53
|
+
throw new ScoreError("invalid_value", `value must be a number, a boolean or a string, got ${value === null ? "null" : typeof value}`);
|
|
54
|
+
}
|
|
55
|
+
const bytes = (s) => new TextEncoder().encode(s).length;
|
|
56
|
+
function randomHex32() {
|
|
57
|
+
const c = globalThis.crypto;
|
|
58
|
+
const a = new Uint8Array(16);
|
|
59
|
+
if (c?.getRandomValues)
|
|
60
|
+
c.getRandomValues(a);
|
|
61
|
+
else
|
|
62
|
+
for (let i = 0; i < a.length; i++)
|
|
63
|
+
a[i] = Math.floor(Math.random() * 256);
|
|
64
|
+
return [...a].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The wire score object (scores.md section 1), validated with the scorecore
|
|
68
|
+
* rules. Throws ScoreError naming the contract's code (`score()` turns that
|
|
69
|
+
* into a result; this is exported for tests and advanced callers).
|
|
70
|
+
*/
|
|
71
|
+
export function buildScore(name, value, o = {}) {
|
|
72
|
+
const n = String(name ?? "")
|
|
73
|
+
.trim()
|
|
74
|
+
.toLowerCase();
|
|
75
|
+
if (!NAME.test(n))
|
|
76
|
+
throw new ScoreError("invalid_name", `name ${JSON.stringify(name)} must be 1-64 chars of a-z 0-9 _ . -`);
|
|
77
|
+
const inferred = kindOf(value);
|
|
78
|
+
if (o.kind !== undefined && o.kind !== inferred) {
|
|
79
|
+
if (!SCORE_KINDS.includes(o.kind))
|
|
80
|
+
throw new ScoreError("kind_mismatch", `kind ${JSON.stringify(o.kind)} is not numeric, boolean or categorical`);
|
|
81
|
+
throw new ScoreError("kind_mismatch", `kind ${o.kind} does not match a ${typeof value} value`);
|
|
82
|
+
}
|
|
83
|
+
let v = value;
|
|
84
|
+
if (inferred === "numeric" && !Number.isFinite(v))
|
|
85
|
+
throw new ScoreError("invalid_value", `value ${String(v)} is not a finite number`);
|
|
86
|
+
if (inferred === "categorical") {
|
|
87
|
+
const t = String(v).trim();
|
|
88
|
+
if (!t || bytes(t) > MAX_VALUE_BYTES || /[\r\n]/.test(t)) {
|
|
89
|
+
throw new ScoreError("invalid_value", `a categorical value must be 1-${MAX_VALUE_BYTES} bytes on one line`);
|
|
90
|
+
}
|
|
91
|
+
v = t;
|
|
92
|
+
}
|
|
93
|
+
const tid = (o.traceId || getCurrentTraceId()).trim().toLowerCase();
|
|
94
|
+
if (!tid)
|
|
95
|
+
throw new ScoreError("invalid_trace_id", "no traceId given and no current span");
|
|
96
|
+
if (!TRACE.test(tid) || /^0+$/.test(tid))
|
|
97
|
+
throw new ScoreError("invalid_trace_id", `traceId ${JSON.stringify(o.traceId)} must be 32 hex characters, not all zero`);
|
|
98
|
+
const sid = (o.spanId ?? "").trim().toLowerCase();
|
|
99
|
+
if (sid && (!SPAN.test(sid) || /^0+$/.test(sid)))
|
|
100
|
+
throw new ScoreError("invalid_span_id", `spanId ${JSON.stringify(o.spanId)} must be 16 hex characters`);
|
|
101
|
+
if (o.comment != null && bytes(String(o.comment)) > MAX_COMMENT_BYTES)
|
|
102
|
+
throw new ScoreError("comment_too_long", `comment is over ${MAX_COMMENT_BYTES} bytes`);
|
|
103
|
+
const cid = o.scoreId || `sdk_${randomHex32()}`;
|
|
104
|
+
if (!ID.test(cid))
|
|
105
|
+
throw new ScoreError("invalid_id", `scoreId ${JSON.stringify(o.scoreId)} must be 1-128 chars of A-Z a-z 0-9 _ . : -`);
|
|
106
|
+
const source = o.source ?? "sdk";
|
|
107
|
+
if (source !== "sdk" && source !== "feedback")
|
|
108
|
+
throw new ScoreError("invalid_source", `source ${JSON.stringify(source)} must be sdk or feedback`);
|
|
109
|
+
const out = { id: cid, trace_id: tid, name: n, value: v, kind: inferred, source };
|
|
110
|
+
if (sid)
|
|
111
|
+
out.span_id = sid;
|
|
112
|
+
if (o.comment)
|
|
113
|
+
out.comment = String(o.comment);
|
|
114
|
+
if (o.scorer) {
|
|
115
|
+
if (o.scorer.length > MAX_SCORER_NAME || (o.scorerVersion && o.scorerVersion.length > MAX_SCORER_VERSION)) {
|
|
116
|
+
throw new ScoreError("bad_request", "scorer name is 1-64 chars and version 1-32");
|
|
117
|
+
}
|
|
118
|
+
out.scorer = { name: o.scorer, version: o.scorerVersion || "1" };
|
|
119
|
+
}
|
|
120
|
+
if (o.runId)
|
|
121
|
+
out.run_id = String(o.runId);
|
|
122
|
+
if (o.timestamp)
|
|
123
|
+
out.timestamp = o.timestamp instanceof Date ? o.timestamp.toISOString() : o.timestamp;
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
function readAnswer(body) {
|
|
127
|
+
const b = (body && typeof body === "object" ? body : {});
|
|
128
|
+
const arr = (v) => (Array.isArray(v) ? v.filter((x) => x && typeof x === "object") : []);
|
|
129
|
+
const accepted = new Map();
|
|
130
|
+
const rejected = new Map();
|
|
131
|
+
for (const a of arr(b.accepted))
|
|
132
|
+
accepted.set(typeof a.index === "number" ? a.index : 0, typeof a.id === "string" ? a.id : "");
|
|
133
|
+
for (const r of arr(b.rejected)) {
|
|
134
|
+
const msg = `${String(r.error ?? "rejected")}: ${String(r.message ?? "")}`.replace(/: $/, "");
|
|
135
|
+
rejected.set(typeof r.index === "number" ? r.index : 0, msg);
|
|
136
|
+
}
|
|
137
|
+
return { accepted, rejected };
|
|
138
|
+
}
|
|
139
|
+
let lastLog = 0;
|
|
140
|
+
function logFailure(res) {
|
|
141
|
+
const now = Date.now();
|
|
142
|
+
if (now - lastLog < 60_000)
|
|
143
|
+
return;
|
|
144
|
+
lastLog = now;
|
|
145
|
+
try {
|
|
146
|
+
console.warn(`@superbased/sdk: a score was not stored: ${res.errors.join("; ") || "unknown"}`);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// ignore
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function write(name, value, o) {
|
|
153
|
+
let body;
|
|
154
|
+
try {
|
|
155
|
+
body = buildScore(name, value, o);
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
const res = { ok: false, id: "", clientId: "", destinations: {}, errors: [err instanceof Error ? err.message : String(err)] };
|
|
159
|
+
logFailure(res);
|
|
160
|
+
return Promise.resolve(res);
|
|
161
|
+
}
|
|
162
|
+
const res = { ok: false, id: "", clientId: body.id, destinations: {}, errors: [] };
|
|
163
|
+
// The body (and the trace it scores) is fixed now; the target waits for the
|
|
164
|
+
// destination (review E-33).
|
|
165
|
+
const work = destinationKnown().then(() => send(body, res, o));
|
|
166
|
+
return track(work);
|
|
167
|
+
}
|
|
168
|
+
function send(body, res, o) {
|
|
169
|
+
const ts = targets("write", o);
|
|
170
|
+
if (!ts.length) {
|
|
171
|
+
res.errors.push(noTargetReason());
|
|
172
|
+
logFailure(res);
|
|
173
|
+
return Promise.resolve(res);
|
|
174
|
+
}
|
|
175
|
+
const timeoutMs = apiTimeout(o);
|
|
176
|
+
return Promise.all(ts.map(async (t) => {
|
|
177
|
+
let r = await call(t, "POST", SCORES_ROUTE, { body, timeoutMs });
|
|
178
|
+
if (retryable(r))
|
|
179
|
+
r = await call(t, "POST", SCORES_ROUTE, { body, timeoutMs });
|
|
180
|
+
const ans = readAnswer(r.body);
|
|
181
|
+
const ok = r.ok && ans.accepted.has(0) && !ans.rejected.has(0);
|
|
182
|
+
const error = ok ? "" : ans.rejected.get(0) || `${r.status ? `HTTP ${r.status} ` : ""}${r.error}${r.message ? `: ${r.message}` : ""}`;
|
|
183
|
+
return { name: t.name, out: { ok, status: r.status, id: ok ? (ans.accepted.get(0) ?? "") : "", error } };
|
|
184
|
+
})).then((rows) => {
|
|
185
|
+
for (const { name: n, out } of rows) {
|
|
186
|
+
res.destinations[n] = out;
|
|
187
|
+
if (out.ok)
|
|
188
|
+
res.id = res.id || out.id;
|
|
189
|
+
else
|
|
190
|
+
res.errors.push(`${n}: ${out.error}`);
|
|
191
|
+
}
|
|
192
|
+
res.ok = rows.length > 0 && rows.every((r) => r.out.ok);
|
|
193
|
+
if (!res.ok)
|
|
194
|
+
logFailure(res);
|
|
195
|
+
return res;
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Attach a score to a trace (or one span of it). Never throws.
|
|
200
|
+
*
|
|
201
|
+
* ```ts
|
|
202
|
+
* await score("faithfulness", 0.92, { traceId, scorer: "judge", scorerVersion: "3" });
|
|
203
|
+
* ```
|
|
204
|
+
*/
|
|
205
|
+
export function score(name, value, opts = {}) {
|
|
206
|
+
return write(name, value, { ...opts, source: "sdk" });
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Record an end user's feedback on a trace: a score with source `feedback`.
|
|
210
|
+
* 👍/👎 as true/false, a rating as a number, or a label. Call it from the
|
|
211
|
+
* request that receives the reaction (for example the backend route the
|
|
212
|
+
* `@superbased/feedback-widget` posts to), with the trace id your app got
|
|
213
|
+
* from `getCurrentTraceId()` when it answered. Never throws.
|
|
214
|
+
*/
|
|
215
|
+
export function feedback(value, opts = {}) {
|
|
216
|
+
const { name, ...rest } = opts;
|
|
217
|
+
return write(name || DEFAULT_FEEDBACK_NAME, value, { ...rest, source: "feedback" });
|
|
218
|
+
}
|
|
219
|
+
//# sourceMappingURL=scores.js.map
|