@superbased/sdk 0.0.1-placeholder.0 → 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 (118) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +434 -5
  3. package/dist/cjs/admit.d.ts +139 -0
  4. package/dist/cjs/admit.js +442 -0
  5. package/dist/cjs/admit.js.map +1 -0
  6. package/dist/cjs/attrs.d.ts +113 -0
  7. package/dist/cjs/attrs.js +183 -0
  8. package/dist/cjs/attrs.js.map +1 -0
  9. package/dist/cjs/config.d.ts +202 -0
  10. package/dist/cjs/config.js +386 -0
  11. package/dist/cjs/config.js.map +1 -0
  12. package/dist/cjs/context.d.ts +102 -0
  13. package/dist/cjs/context.js +234 -0
  14. package/dist/cjs/context.js.map +1 -0
  15. package/dist/cjs/control.d.ts +99 -0
  16. package/dist/cjs/control.js +243 -0
  17. package/dist/cjs/control.js.map +1 -0
  18. package/dist/cjs/cost.d.ts +108 -0
  19. package/dist/cjs/cost.js +211 -0
  20. package/dist/cjs/cost.js.map +1 -0
  21. package/dist/cjs/destination.d.ts +125 -0
  22. package/dist/cjs/destination.js +357 -0
  23. package/dist/cjs/destination.js.map +1 -0
  24. package/dist/cjs/experiments.d.ts +237 -0
  25. package/dist/cjs/experiments.js +678 -0
  26. package/dist/cjs/experiments.js.map +1 -0
  27. package/dist/cjs/export.d.ts +84 -0
  28. package/dist/cjs/export.js +328 -0
  29. package/dist/cjs/export.js.map +1 -0
  30. package/dist/cjs/index.d.ts +168 -0
  31. package/dist/cjs/index.js +581 -0
  32. package/dist/cjs/index.js.map +1 -0
  33. package/dist/cjs/instrument.d.ts +88 -0
  34. package/dist/cjs/instrument.js +397 -0
  35. package/dist/cjs/instrument.js.map +1 -0
  36. package/dist/cjs/package.json +1 -0
  37. package/dist/cjs/policy.d.ts +77 -0
  38. package/dist/cjs/policy.js +252 -0
  39. package/dist/cjs/policy.js.map +1 -0
  40. package/dist/cjs/prompts.d.ts +175 -0
  41. package/dist/cjs/prompts.js +476 -0
  42. package/dist/cjs/prompts.js.map +1 -0
  43. package/dist/cjs/propagation.d.ts +34 -0
  44. package/dist/cjs/propagation.js +151 -0
  45. package/dist/cjs/propagation.js.map +1 -0
  46. package/dist/cjs/req.d.ts +10 -0
  47. package/dist/cjs/req.js +3 -0
  48. package/dist/cjs/req.js.map +1 -0
  49. package/dist/cjs/runtime.d.ts +44 -0
  50. package/dist/cjs/runtime.js +67 -0
  51. package/dist/cjs/runtime.js.map +1 -0
  52. package/dist/cjs/scores.d.ts +102 -0
  53. package/dist/cjs/scores.js +226 -0
  54. package/dist/cjs/scores.js.map +1 -0
  55. package/dist/cjs/spans.d.ts +193 -0
  56. package/dist/cjs/spans.js +398 -0
  57. package/dist/cjs/spans.js.map +1 -0
  58. package/dist/cjs/vendor.d.ts +33 -0
  59. package/dist/cjs/vendor.js +67 -0
  60. package/dist/cjs/vendor.js.map +1 -0
  61. package/dist/esm/admit.d.ts +139 -0
  62. package/dist/esm/admit.js +432 -0
  63. package/dist/esm/admit.js.map +1 -0
  64. package/dist/esm/attrs.d.ts +113 -0
  65. package/dist/esm/attrs.js +179 -0
  66. package/dist/esm/attrs.js.map +1 -0
  67. package/dist/esm/config.d.ts +202 -0
  68. package/dist/esm/config.js +364 -0
  69. package/dist/esm/config.js.map +1 -0
  70. package/dist/esm/context.d.ts +102 -0
  71. package/dist/esm/context.js +221 -0
  72. package/dist/esm/context.js.map +1 -0
  73. package/dist/esm/control.d.ts +99 -0
  74. package/dist/esm/control.js +230 -0
  75. package/dist/esm/control.js.map +1 -0
  76. package/dist/esm/cost.d.ts +108 -0
  77. package/dist/esm/cost.js +202 -0
  78. package/dist/esm/cost.js.map +1 -0
  79. package/dist/esm/destination.d.ts +125 -0
  80. package/dist/esm/destination.js +346 -0
  81. package/dist/esm/destination.js.map +1 -0
  82. package/dist/esm/experiments.d.ts +237 -0
  83. package/dist/esm/experiments.js +666 -0
  84. package/dist/esm/experiments.js.map +1 -0
  85. package/dist/esm/export.d.ts +84 -0
  86. package/dist/esm/export.js +314 -0
  87. package/dist/esm/export.js.map +1 -0
  88. package/dist/esm/index.d.ts +168 -0
  89. package/dist/esm/index.js +500 -0
  90. package/dist/esm/index.js.map +1 -0
  91. package/dist/esm/instrument.d.ts +88 -0
  92. package/dist/esm/instrument.js +391 -0
  93. package/dist/esm/instrument.js.map +1 -0
  94. package/dist/esm/policy.d.ts +77 -0
  95. package/dist/esm/policy.js +240 -0
  96. package/dist/esm/policy.js.map +1 -0
  97. package/dist/esm/prompts.d.ts +175 -0
  98. package/dist/esm/prompts.js +460 -0
  99. package/dist/esm/prompts.js.map +1 -0
  100. package/dist/esm/propagation.d.ts +34 -0
  101. package/dist/esm/propagation.js +145 -0
  102. package/dist/esm/propagation.js.map +1 -0
  103. package/dist/esm/req.d.ts +10 -0
  104. package/dist/esm/req.js +2 -0
  105. package/dist/esm/req.js.map +1 -0
  106. package/dist/esm/runtime.d.ts +44 -0
  107. package/dist/esm/runtime.js +59 -0
  108. package/dist/esm/runtime.js.map +1 -0
  109. package/dist/esm/scores.d.ts +102 -0
  110. package/dist/esm/scores.js +219 -0
  111. package/dist/esm/scores.js.map +1 -0
  112. package/dist/esm/spans.d.ts +193 -0
  113. package/dist/esm/spans.js +378 -0
  114. package/dist/esm/spans.js.map +1 -0
  115. package/dist/esm/vendor.d.ts +33 -0
  116. package/dist/esm/vendor.js +61 -0
  117. package/dist/esm/vendor.js.map +1 -0
  118. package/package.json +121 -4
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * W3C trace-context helpers (contract sdk-api-surface.md section 4), for
4
+ * joining a trace across a process boundary the SDK does not instrument (a
5
+ * queue message, a job, a hand-rolled HTTP call). They always use the W3C
6
+ * propagators, whatever global propagator the host has configured.
7
+ *
8
+ * `inject()` also writes `baggage` when per-request values were set with
9
+ * `propagateAttributes({ ..., asBaggage: true })`; `continueTrace()` restores
10
+ * them into the attribute scope on the other side.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.inject = inject;
14
+ exports.extract = extract;
15
+ exports.continueTrace = continueTrace;
16
+ exports.getTraceparent = getTraceparent;
17
+ const api_1 = require("@opentelemetry/api");
18
+ const core_1 = require("@opentelemetry/core");
19
+ const attrs_js_1 = require("./attrs.js");
20
+ const context_js_1 = require("./context.js");
21
+ const traceContext = new core_1.W3CTraceContextPropagator();
22
+ const baggageProp = new core_1.W3CBaggagePropagator();
23
+ const getter = {
24
+ keys(c) {
25
+ const fe = c.forEach;
26
+ if (typeof c.get === "function" && typeof fe === "function") {
27
+ const out = [];
28
+ c.forEach((_v, k) => out.push(k));
29
+ return out;
30
+ }
31
+ return Object.keys(c);
32
+ },
33
+ get(c, key) {
34
+ if (typeof c.get === "function") {
35
+ return c.get(key) ?? undefined;
36
+ }
37
+ const rec = c;
38
+ const want = key.toLowerCase();
39
+ const hit = Object.keys(rec).find((k) => k.toLowerCase() === want);
40
+ return hit === undefined ? undefined : rec[hit];
41
+ },
42
+ };
43
+ function withScopeBaggage(ctx) {
44
+ const scope = (0, context_js_1.currentScope)();
45
+ if (!scope.baggage)
46
+ return ctx;
47
+ const entries = {};
48
+ for (const [k, v] of Object.entries(scope.scalars))
49
+ entries[k] = { value: v };
50
+ if (scope.tags.length)
51
+ entries[attrs_js_1.K.tags] = { value: scope.tags.join(",") };
52
+ for (const [k, v] of Object.entries(scope.metadata))
53
+ entries[attrs_js_1.K.metadataPrefix + k] = { value: v };
54
+ const existing = api_1.propagation.getBaggage(ctx);
55
+ let bag = existing ?? api_1.propagation.createBaggage();
56
+ for (const [k, e] of Object.entries(entries))
57
+ bag = bag.setEntry(k, e);
58
+ return api_1.propagation.setBaggage(ctx, bag);
59
+ }
60
+ /**
61
+ * Write `traceparent` (+ `tracestate`, + `baggage` when per-request values
62
+ * were set `asBaggage`) for the current context into `carrier` (a new object
63
+ * when omitted) and return it.
64
+ *
65
+ * ```ts
66
+ * await queue.send({ body, headers: inject() });
67
+ * ```
68
+ */
69
+ function inject(carrier) {
70
+ const out = (carrier ?? {});
71
+ try {
72
+ const ctx = withScopeBaggage(api_1.context.active());
73
+ const setter = {
74
+ set(c, k, v) {
75
+ c[k] = v;
76
+ },
77
+ };
78
+ traceContext.inject(ctx, out, setter);
79
+ baggageProp.inject(ctx, out, setter);
80
+ }
81
+ catch {
82
+ // never break the caller
83
+ }
84
+ return out;
85
+ }
86
+ /** The context the W3C headers in `carrier` describe (case-insensitive); the active context when there are none. */
87
+ function extract(carrier) {
88
+ const base = api_1.context.active();
89
+ try {
90
+ return baggageProp.extract(traceContext.extract(base, carrier ?? {}, getter), carrier ?? {}, getter);
91
+ }
92
+ catch {
93
+ return base;
94
+ }
95
+ }
96
+ function scopeFromBaggage(ctx) {
97
+ const bag = api_1.propagation.getBaggage(ctx);
98
+ if (!bag)
99
+ return null;
100
+ const reverse = Object.fromEntries(Object.entries(context_js_1.SCALAR_KEYS).map(([name, key]) => [key, name]));
101
+ const opts = { asBaggage: true };
102
+ const meta = {};
103
+ let any = false;
104
+ for (const [key, entry] of bag.getAllEntries()) {
105
+ if (key in reverse) {
106
+ opts[reverse[key]] = entry.value;
107
+ any = true;
108
+ }
109
+ else if (key === attrs_js_1.K.tags) {
110
+ opts.tags = entry.value.split(",");
111
+ any = true;
112
+ }
113
+ else if (key.startsWith(attrs_js_1.K.metadataPrefix)) {
114
+ meta[key.slice(attrs_js_1.K.metadataPrefix.length)] = entry.value;
115
+ any = true;
116
+ }
117
+ }
118
+ if (!any)
119
+ return null;
120
+ if (Object.keys(meta).length)
121
+ opts.metadata = meta;
122
+ return (0, context_js_1.currentScope)().merged(opts);
123
+ }
124
+ /**
125
+ * Run `fn` as part of the trace `carrier` names (spans inside join the
126
+ * caller's trace), restoring per-request values the caller sent as baggage.
127
+ */
128
+ function continueTrace(carrier, fn) {
129
+ const ctx = extract(carrier);
130
+ const scope = scopeFromBaggage(ctx);
131
+ const run = () => api_1.context.with(ctx, fn);
132
+ return scope ? (0, context_js_1.runWithScope)(scope, run) : run();
133
+ }
134
+ /** The `traceparent` value of the active span ("" outside a span). */
135
+ function getTraceparent() {
136
+ if (!api_1.trace.getActiveSpan())
137
+ return "";
138
+ const out = {};
139
+ try {
140
+ traceContext.inject(api_1.context.active(), out, {
141
+ set(c, k, v) {
142
+ c[k] = v;
143
+ },
144
+ });
145
+ }
146
+ catch {
147
+ return "";
148
+ }
149
+ return out.traceparent ?? "";
150
+ }
151
+ //# sourceMappingURL=propagation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"propagation.js","sourceRoot":"","sources":["../../src/propagation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;AAyDH,wBAeC;AAGD,0BAOC;AA8BD,sCAKC;AAGD,wCAaC;AAnID,4CAAmG;AACnG,8CAAsF;AAEtF,yCAA+B;AAC/B,6CAAqG;AAErG,MAAM,YAAY,GAAG,IAAI,gCAAyB,EAAE,CAAC;AACrD,MAAM,WAAW,GAAG,IAAI,2BAAoB,EAAE,CAAC;AAK/C,MAAM,MAAM,GAA2B;IACrC,IAAI,CAAC,CAAC;QACJ,MAAM,EAAE,GAAI,CAA2B,CAAC,OAAO,CAAC;QAChD,IAAI,OAAQ,CAAuB,CAAC,GAAG,KAAK,UAAU,IAAI,OAAO,EAAE,KAAK,UAAU,EAAE,CAAC;YACnF,MAAM,GAAG,GAAa,EAAE,CAAC;YACxB,CAAsE,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YACxG,OAAO,GAAG,CAAC;QACb,CAAC;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACxB,CAAC;IACD,GAAG,CAAC,CAAC,EAAE,GAAG;QACR,IAAI,OAAQ,CAAuB,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;YACvD,OAAQ,CAA0C,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,SA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AC,MAAM;QAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACnD,OAAO,IAAA,yBAAY,GAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACrC,CAAC;AAED;;;GAGG;AACH,SAAgB,aAAa,CAAI,OAAgB,EAAE,EAAW;IAC5D,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7B,MAAM,KAAK,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC;IACpC,MAAM,GAAG,GAAG,GAAG,EAAE,CAAC,aAAO,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACxC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAA,yBAAY,EAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AAClD,CAAC;AAED,sEAAsE;AACtE,SAAgB,cAAc;IAC5B,IAAI,CAAC,WAAK,CAAC,aAAa,EAAE;QAAE,OAAO,EAAE,CAAC;IACtC,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,IAAI,CAAC;QACH,YAAY,CAAC,MAAM,CAAC,aAAO,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;
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.req = require;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"req.js","sourceRoot":"","sources":["../../src/req.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAEH,6CAA4C;AAI5C,8DAA8D;AACjD,QAAA,GAAG,GAAmB,IAAA,2BAAa,EAAC,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,67 @@
1
+ "use strict";
2
+ /**
3
+ * Process-wide SDK runtime state shared by the modules: the resolved
4
+ * settings, the tracer and the content switches. One owner (init in
5
+ * index.ts writes it); everything else reads it.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.runtime = exports.SDK_MARKER = exports.TRACER_NAME = exports.VERSION = void 0;
9
+ exports.destinationKnown = destinationKnown;
10
+ exports.tracer = tracer;
11
+ exports.truncateContent = truncateContent;
12
+ exports.contentText = contentText;
13
+ exports.resetRuntime = resetRuntime;
14
+ const api_1 = require("@opentelemetry/api");
15
+ exports.VERSION = "0.1.0";
16
+ exports.TRACER_NAME = "@superbased/sdk";
17
+ exports.SDK_MARKER = "superbased-typescript";
18
+ exports.runtime = {
19
+ settings: null,
20
+ tracer: null,
21
+ captureContent: true,
22
+ maxContentChars: 8000,
23
+ destination: "",
24
+ destinationSource: "",
25
+ admissionUrl: "",
26
+ provider: null,
27
+ resourceService: "",
28
+ ready: Promise.resolve(),
29
+ };
30
+ /** Wait until the destination is known (see {@link Runtime.ready}). */
31
+ function destinationKnown() {
32
+ return exports.runtime.ready;
33
+ }
34
+ function tracer() {
35
+ return exports.runtime.tracer ?? api_1.trace.getTracer(exports.TRACER_NAME, exports.VERSION);
36
+ }
37
+ function truncateContent(value) {
38
+ const max = exports.runtime.maxContentChars;
39
+ return max > 0 && value.length > max ? value.slice(0, max) + "…[truncated]" : value;
40
+ }
41
+ /** Render any value as content text (strings as-is, the rest as JSON). */
42
+ function contentText(v) {
43
+ if (typeof v === "string")
44
+ return v;
45
+ try {
46
+ const s = JSON.stringify(v);
47
+ return s === undefined ? String(v) : s;
48
+ }
49
+ catch {
50
+ return String(v);
51
+ }
52
+ }
53
+ function resetRuntime() {
54
+ Object.assign(exports.runtime, {
55
+ settings: null,
56
+ tracer: null,
57
+ captureContent: true,
58
+ maxContentChars: 8000,
59
+ destination: "",
60
+ destinationSource: "",
61
+ admissionUrl: "",
62
+ provider: null,
63
+ resourceService: "",
64
+ ready: Promise.resolve(),
65
+ });
66
+ }
67
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/runtime.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAmDH,4CAEC;AAED,wBAEC;AAED,0CAGC;AAGD,kCAQC;AAED,oCAaC;AAtFD,4CAA6E;AAIhE,QAAA,OAAO,GAAG,OAAO,CAAC;AAClB,QAAA,WAAW,GAAG,iBAAiB,CAAC;AAChC,QAAA,UAAU,GAAG,uBAAuB,CAAC;AA6BrC,QAAA,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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,226 @@
1
+ "use strict";
2
+ /**
3
+ * Scores and feedback (W3-1; contract `contracts/scores.md`, lane B7; the
4
+ * API is sdk-api-surface.md section 7.1, the same as Python's).
5
+ *
6
+ * A score is one judgement about one trace or one span: a name, a value, who
7
+ * produced it, an optional comment. Feedback is a score an end user of the
8
+ * app gave. Both are written through the SDK control API to every target of
9
+ * the destination in force: online `POST <org>/v1/sdk/scores` (scope
10
+ * `sdk:write`), local `POST <machine>/api/obs/scores`, `both` to each with
11
+ * the same `id`, so the stored score id is the same on both sides. They land
12
+ * on the existing owners (org annotations, machine `obs_eval_scores`); the
13
+ * SDK adds no store of its own.
14
+ *
15
+ * The id makes a write idempotent: the SDK mints `sdk_<32 hex>` when you
16
+ * give none and reuses it on its one retry, so a retried write never doubles
17
+ * a score.
18
+ *
19
+ * Nothing throws: a score the scorecore rules refuse (a bad name, a kind
20
+ * that disagrees with the value, no trace) resolves with `ok: false` and an
21
+ * error naming the contract's code, before any call; network and server
22
+ * failures resolve the same way. flush() waits for pending writes.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.ScoreError = exports.DEFAULT_FEEDBACK_NAME = exports.SCORE_KINDS = exports.SCORES_ROUTE = void 0;
26
+ exports.buildScore = buildScore;
27
+ exports.score = score;
28
+ exports.feedback = feedback;
29
+ const control_js_1 = require("./control.js");
30
+ const spans_js_1 = require("./spans.js");
31
+ const runtime_js_1 = require("./runtime.js");
32
+ exports.SCORES_ROUTE = { online: "/scores", local: "/api/obs/scores" };
33
+ exports.SCORE_KINDS = ["numeric", "boolean", "categorical"];
34
+ exports.DEFAULT_FEEDBACK_NAME = "user_feedback";
35
+ const NAME = /^[a-z0-9_.-]{1,64}$/;
36
+ const ID = /^[A-Za-z0-9_.:-]{1,128}$/;
37
+ const TRACE = /^[0-9a-f]{32}$/;
38
+ const SPAN = /^[0-9a-f]{16}$/;
39
+ const MAX_VALUE_BYTES = 120;
40
+ const MAX_COMMENT_BYTES = 2000;
41
+ const MAX_SCORER_NAME = 64;
42
+ const MAX_SCORER_VERSION = 32;
43
+ /** A score the rules refuse (contract scores.md section 1; the code is the contract's). */
44
+ class ScoreError extends Error {
45
+ code;
46
+ constructor(code, message) {
47
+ super(`${code}: ${message}`);
48
+ this.code = code;
49
+ this.name = "ScoreError";
50
+ }
51
+ }
52
+ exports.ScoreError = ScoreError;
53
+ function kindOf(value) {
54
+ if (typeof value === "boolean")
55
+ return "boolean";
56
+ if (typeof value === "number")
57
+ return "numeric";
58
+ if (typeof value === "string")
59
+ return "categorical";
60
+ throw new ScoreError("invalid_value", `value must be a number, a boolean or a string, got ${value === null ? "null" : typeof value}`);
61
+ }
62
+ const bytes = (s) => new TextEncoder().encode(s).length;
63
+ function randomHex32() {
64
+ const c = globalThis.crypto;
65
+ const a = new Uint8Array(16);
66
+ if (c?.getRandomValues)
67
+ c.getRandomValues(a);
68
+ else
69
+ for (let i = 0; i < a.length; i++)
70
+ a[i] = Math.floor(Math.random() * 256);
71
+ return [...a].map((b) => b.toString(16).padStart(2, "0")).join("");
72
+ }
73
+ /**
74
+ * The wire score object (scores.md section 1), validated with the scorecore
75
+ * rules. Throws ScoreError naming the contract's code (`score()` turns that
76
+ * into a result; this is exported for tests and advanced callers).
77
+ */
78
+ function buildScore(name, value, o = {}) {
79
+ const n = String(name ?? "")
80
+ .trim()
81
+ .toLowerCase();
82
+ if (!NAME.test(n))
83
+ throw new ScoreError("invalid_name", `name ${JSON.stringify(name)} must be 1-64 chars of a-z 0-9 _ . -`);
84
+ const inferred = kindOf(value);
85
+ if (o.kind !== undefined && o.kind !== inferred) {
86
+ if (!exports.SCORE_KINDS.includes(o.kind))
87
+ throw new ScoreError("kind_mismatch", `kind ${JSON.stringify(o.kind)} is not numeric, boolean or categorical`);
88
+ throw new ScoreError("kind_mismatch", `kind ${o.kind} does not match a ${typeof value} value`);
89
+ }
90
+ let v = value;
91
+ if (inferred === "numeric" && !Number.isFinite(v))
92
+ throw new ScoreError("invalid_value", `value ${String(v)} is not a finite number`);
93
+ if (inferred === "categorical") {
94
+ const t = String(v).trim();
95
+ if (!t || bytes(t) > MAX_VALUE_BYTES || /[\r\n]/.test(t)) {
96
+ throw new ScoreError("invalid_value", `a categorical value must be 1-${MAX_VALUE_BYTES} bytes on one line`);
97
+ }
98
+ v = t;
99
+ }
100
+ const tid = (o.traceId || (0, spans_js_1.getCurrentTraceId)()).trim().toLowerCase();
101
+ if (!tid)
102
+ throw new ScoreError("invalid_trace_id", "no traceId given and no current span");
103
+ if (!TRACE.test(tid) || /^0+$/.test(tid))
104
+ throw new ScoreError("invalid_trace_id", `traceId ${JSON.stringify(o.traceId)} must be 32 hex characters, not all zero`);
105
+ const sid = (o.spanId ?? "").trim().toLowerCase();
106
+ if (sid && (!SPAN.test(sid) || /^0+$/.test(sid)))
107
+ throw new ScoreError("invalid_span_id", `spanId ${JSON.stringify(o.spanId)} must be 16 hex characters`);
108
+ if (o.comment != null && bytes(String(o.comment)) > MAX_COMMENT_BYTES)
109
+ throw new ScoreError("comment_too_long", `comment is over ${MAX_COMMENT_BYTES} bytes`);
110
+ const cid = o.scoreId || `sdk_${randomHex32()}`;
111
+ if (!ID.test(cid))
112
+ throw new ScoreError("invalid_id", `scoreId ${JSON.stringify(o.scoreId)} must be 1-128 chars of A-Z a-z 0-9 _ . : -`);
113
+ const source = o.source ?? "sdk";
114
+ if (source !== "sdk" && source !== "feedback")
115
+ throw new ScoreError("invalid_source", `source ${JSON.stringify(source)} must be sdk or feedback`);
116
+ const out = { id: cid, trace_id: tid, name: n, value: v, kind: inferred, source };
117
+ if (sid)
118
+ out.span_id = sid;
119
+ if (o.comment)
120
+ out.comment = String(o.comment);
121
+ if (o.scorer) {
122
+ if (o.scorer.length > MAX_SCORER_NAME || (o.scorerVersion && o.scorerVersion.length > MAX_SCORER_VERSION)) {
123
+ throw new ScoreError("bad_request", "scorer name is 1-64 chars and version 1-32");
124
+ }
125
+ out.scorer = { name: o.scorer, version: o.scorerVersion || "1" };
126
+ }
127
+ if (o.runId)
128
+ out.run_id = String(o.runId);
129
+ if (o.timestamp)
130
+ out.timestamp = o.timestamp instanceof Date ? o.timestamp.toISOString() : o.timestamp;
131
+ return out;
132
+ }
133
+ function readAnswer(body) {
134
+ const b = (body && typeof body === "object" ? body : {});
135
+ const arr = (v) => (Array.isArray(v) ? v.filter((x) => x && typeof x === "object") : []);
136
+ const accepted = new Map();
137
+ const rejected = new Map();
138
+ for (const a of arr(b.accepted))
139
+ accepted.set(typeof a.index === "number" ? a.index : 0, typeof a.id === "string" ? a.id : "");
140
+ for (const r of arr(b.rejected)) {
141
+ const msg = `${String(r.error ?? "rejected")}: ${String(r.message ?? "")}`.replace(/: $/, "");
142
+ rejected.set(typeof r.index === "number" ? r.index : 0, msg);
143
+ }
144
+ return { accepted, rejected };
145
+ }
146
+ let lastLog = 0;
147
+ function logFailure(res) {
148
+ const now = Date.now();
149
+ if (now - lastLog < 60_000)
150
+ return;
151
+ lastLog = now;
152
+ try {
153
+ console.warn(`@superbased/sdk: a score was not stored: ${res.errors.join("; ") || "unknown"}`);
154
+ }
155
+ catch {
156
+ // ignore
157
+ }
158
+ }
159
+ function write(name, value, o) {
160
+ let body;
161
+ try {
162
+ body = buildScore(name, value, o);
163
+ }
164
+ catch (err) {
165
+ const res = { ok: false, id: "", clientId: "", destinations: {}, errors: [err instanceof Error ? err.message : String(err)] };
166
+ logFailure(res);
167
+ return Promise.resolve(res);
168
+ }
169
+ const res = { ok: false, id: "", clientId: body.id, destinations: {}, errors: [] };
170
+ // The body (and the trace it scores) is fixed now; the target waits for the
171
+ // destination (review E-33).
172
+ const work = (0, runtime_js_1.destinationKnown)().then(() => send(body, res, o));
173
+ return (0, control_js_1.track)(work);
174
+ }
175
+ function send(body, res, o) {
176
+ const ts = (0, control_js_1.targets)("write", o);
177
+ if (!ts.length) {
178
+ res.errors.push((0, control_js_1.noTargetReason)());
179
+ logFailure(res);
180
+ return Promise.resolve(res);
181
+ }
182
+ const timeoutMs = (0, control_js_1.apiTimeout)(o);
183
+ return Promise.all(ts.map(async (t) => {
184
+ let r = await (0, control_js_1.call)(t, "POST", exports.SCORES_ROUTE, { body, timeoutMs });
185
+ if ((0, control_js_1.retryable)(r))
186
+ r = await (0, control_js_1.call)(t, "POST", exports.SCORES_ROUTE, { body, timeoutMs });
187
+ const ans = readAnswer(r.body);
188
+ const ok = r.ok && ans.accepted.has(0) && !ans.rejected.has(0);
189
+ const error = ok ? "" : ans.rejected.get(0) || `${r.status ? `HTTP ${r.status} ` : ""}${r.error}${r.message ? `: ${r.message}` : ""}`;
190
+ return { name: t.name, out: { ok, status: r.status, id: ok ? (ans.accepted.get(0) ?? "") : "", error } };
191
+ })).then((rows) => {
192
+ for (const { name: n, out } of rows) {
193
+ res.destinations[n] = out;
194
+ if (out.ok)
195
+ res.id = res.id || out.id;
196
+ else
197
+ res.errors.push(`${n}: ${out.error}`);
198
+ }
199
+ res.ok = rows.length > 0 && rows.every((r) => r.out.ok);
200
+ if (!res.ok)
201
+ logFailure(res);
202
+ return res;
203
+ });
204
+ }
205
+ /**
206
+ * Attach a score to a trace (or one span of it). Never throws.
207
+ *
208
+ * ```ts
209
+ * await score("faithfulness", 0.92, { traceId, scorer: "judge", scorerVersion: "3" });
210
+ * ```
211
+ */
212
+ function score(name, value, opts = {}) {
213
+ return write(name, value, { ...opts, source: "sdk" });
214
+ }
215
+ /**
216
+ * Record an end user's feedback on a trace: a score with source `feedback`.
217
+ * 👍/👎 as true/false, a rating as a number, or a label. Call it from the
218
+ * request that receives the reaction (for example the backend route the
219
+ * `@superbased/feedback-widget` posts to), with the trace id your app got
220
+ * from `getCurrentTraceId()` when it answered. Never throws.
221
+ */
222
+ function feedback(value, opts = {}) {
223
+ const { name, ...rest } = opts;
224
+ return write(name || exports.DEFAULT_FEEDBACK_NAME, value, { ...rest, source: "feedback" });
225
+ }
226
+ //# sourceMappingURL=scores.js.map