braintrust 0.2.6 → 0.3.7

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.
@@ -0,0 +1,1264 @@
1
+ // util/db_fields.ts
2
+ var TRANSACTION_ID_FIELD = "_xact_id";
3
+ var OBJECT_DELETE_FIELD = "_object_delete";
4
+ var CREATED_FIELD = "created";
5
+ var ID_FIELD = "id";
6
+ var IS_MERGE_FIELD = "_is_merge";
7
+ var MERGE_PATHS_FIELD = "_merge_paths";
8
+ var AUDIT_SOURCE_FIELD = "_audit_source";
9
+ var AUDIT_METADATA_FIELD = "_audit_metadata";
10
+ var VALID_SOURCES = ["app", "api", "external"];
11
+ var PARENT_ID_FIELD = "_parent_id";
12
+ var ASYNC_SCORING_CONTROL_FIELD = "_async_scoring_control";
13
+ var SKIP_ASYNC_SCORING_FIELD = "_skip_async_scoring";
14
+
15
+ // util/span_identifier_v3.ts
16
+ import * as uuid3 from "uuid";
17
+
18
+ // util/span_identifier_v2.ts
19
+ import * as uuid2 from "uuid";
20
+
21
+ // util/span_identifier_v1.ts
22
+ import * as uuid from "uuid";
23
+ import { z } from "zod/v3";
24
+ function tryMakeUuid(s) {
25
+ try {
26
+ const ret = uuid.parse(s);
27
+ if (ret.length !== 16) {
28
+ throw new Error();
29
+ }
30
+ return { bytes: Buffer.from(ret), isUUID: true };
31
+ } catch (e) {
32
+ return { bytes: Buffer.from(s, "utf-8"), isUUID: false };
33
+ }
34
+ }
35
+ var ENCODING_VERSION_NUMBER = 1;
36
+ var INVALID_ENCODING_ERRMSG = "SpanComponents string is not properly encoded. This may be due to a version mismatch between the SDK library used to export the span and the library used to decode it. Please make sure you are using the same SDK version across the board";
37
+ var SpanObjectTypeV1 = /* @__PURE__ */ ((SpanObjectTypeV12) => {
38
+ SpanObjectTypeV12[SpanObjectTypeV12["EXPERIMENT"] = 1] = "EXPERIMENT";
39
+ SpanObjectTypeV12[SpanObjectTypeV12["PROJECT_LOGS"] = 2] = "PROJECT_LOGS";
40
+ return SpanObjectTypeV12;
41
+ })(SpanObjectTypeV1 || {});
42
+ var SpanObjectTypeV1EnumSchema = z.nativeEnum(SpanObjectTypeV1);
43
+ var SpanRowIdsV1 = class {
44
+ rowId;
45
+ spanId;
46
+ rootSpanId;
47
+ constructor(args) {
48
+ this.rowId = args.rowId;
49
+ this.spanId = args.spanId;
50
+ this.rootSpanId = args.rootSpanId;
51
+ if (!this.rowId) {
52
+ throw new Error("rowId must be nonempty string");
53
+ }
54
+ if (!this.spanId) {
55
+ throw new Error("spanId must be nonempty string");
56
+ }
57
+ if (!this.rootSpanId) {
58
+ throw new Error("rootSpanId must be nonempty string");
59
+ }
60
+ }
61
+ toObject() {
62
+ return {
63
+ rowId: this.rowId,
64
+ spanId: this.spanId,
65
+ rootSpanId: this.rootSpanId
66
+ };
67
+ }
68
+ };
69
+ var SpanComponentsV1 = class _SpanComponentsV1 {
70
+ objectType;
71
+ objectId;
72
+ rowIds;
73
+ constructor(args) {
74
+ this.objectType = args.objectType;
75
+ this.objectId = args.objectId;
76
+ this.rowIds = args.rowIds;
77
+ }
78
+ toStr() {
79
+ const allBuffers = [];
80
+ const { bytes: rowIdBytes, isUUID: rowIdIsUUID } = this.rowIds ? tryMakeUuid(this.rowIds.rowId) : { bytes: Buffer.from(""), isUUID: false };
81
+ allBuffers.push(
82
+ Buffer.from([
83
+ ENCODING_VERSION_NUMBER,
84
+ this.objectType,
85
+ this.rowIds ? 1 : 0,
86
+ rowIdIsUUID ? 1 : 0
87
+ ])
88
+ );
89
+ const { bytes: objectIdBytes, isUUID: objectIdIsUUID } = tryMakeUuid(
90
+ this.objectId
91
+ );
92
+ if (!objectIdIsUUID) {
93
+ throw new Error("object_id component must be a valid UUID");
94
+ }
95
+ allBuffers.push(objectIdBytes);
96
+ if (this.rowIds) {
97
+ const { bytes: spanIdBytes, isUUID: spanIdIsUUID } = tryMakeUuid(
98
+ this.rowIds.spanId
99
+ );
100
+ if (!spanIdIsUUID) {
101
+ throw new Error("span_id component must be a valid UUID");
102
+ }
103
+ const { bytes: rootSpanIdBytes, isUUID: rootSpanIdIsUUID } = tryMakeUuid(
104
+ this.rowIds.rootSpanId
105
+ );
106
+ if (!rootSpanIdIsUUID) {
107
+ throw new Error("root_span_id component must be a valid UUID");
108
+ }
109
+ allBuffers.push(spanIdBytes, rootSpanIdBytes, rowIdBytes);
110
+ }
111
+ return Buffer.concat(allBuffers).toString("base64");
112
+ }
113
+ static fromStr(s) {
114
+ try {
115
+ const rawBytes = Buffer.from(s, "base64");
116
+ if (rawBytes[0] !== ENCODING_VERSION_NUMBER) {
117
+ throw new Error();
118
+ }
119
+ const objectType = SpanObjectTypeV1EnumSchema.parse(rawBytes[1]);
120
+ if (![0, 1].includes(rawBytes[2])) {
121
+ throw new Error();
122
+ }
123
+ if (![0, 1].includes(rawBytes[3])) {
124
+ throw new Error();
125
+ }
126
+ const hasRowId = rawBytes[2] == 1;
127
+ const rowIdIsUUID = rawBytes[3] == 1;
128
+ const objectId = uuid.stringify(rawBytes.subarray(4, 20));
129
+ const rowIds = (() => {
130
+ if (!hasRowId) {
131
+ return void 0;
132
+ }
133
+ const spanId = uuid.stringify(rawBytes.subarray(20, 36));
134
+ const rootSpanId = uuid.stringify(rawBytes.subarray(36, 52));
135
+ const rowId = rowIdIsUUID ? uuid.stringify(rawBytes.subarray(52)) : rawBytes.subarray(52).toString("utf-8");
136
+ return new SpanRowIdsV1({ rowId, spanId, rootSpanId });
137
+ })();
138
+ return new _SpanComponentsV1({ objectType, objectId, rowIds });
139
+ } catch (e) {
140
+ throw new Error(INVALID_ENCODING_ERRMSG);
141
+ }
142
+ }
143
+ objectIdFields() {
144
+ switch (this.objectType) {
145
+ case 1 /* EXPERIMENT */:
146
+ return { experiment_id: this.objectId };
147
+ case 2 /* PROJECT_LOGS */:
148
+ return { project_id: this.objectId, log_id: "g" };
149
+ default:
150
+ throw new Error("Impossible");
151
+ }
152
+ }
153
+ toObject() {
154
+ return {
155
+ objectType: this.objectType,
156
+ objectId: this.objectId,
157
+ rowIds: this.rowIds?.toObject()
158
+ };
159
+ }
160
+ };
161
+
162
+ // util/span_identifier_v2.ts
163
+ import { z as z2 } from "zod/v3";
164
+ function tryMakeUuid2(s) {
165
+ try {
166
+ const ret = uuid2.parse(s);
167
+ if (ret.length !== 16) {
168
+ throw new Error();
169
+ }
170
+ return { bytes: Buffer.from(ret), isUUID: true };
171
+ } catch (e) {
172
+ return { bytes: Buffer.from(s, "utf-8"), isUUID: false };
173
+ }
174
+ }
175
+ var ENCODING_VERSION_NUMBER2 = 2;
176
+ var INVALID_ENCODING_ERRMSG2 = `SpanComponents string is not properly encoded. This library only supports encoding versions up to ${ENCODING_VERSION_NUMBER2}. Please make sure the SDK library used to decode the SpanComponents is at least as new as any library used to encode it.`;
177
+ var INTEGER_ENCODING_NUM_BYTES = 4;
178
+ var SpanObjectTypeV2 = /* @__PURE__ */ ((SpanObjectTypeV22) => {
179
+ SpanObjectTypeV22[SpanObjectTypeV22["EXPERIMENT"] = 1] = "EXPERIMENT";
180
+ SpanObjectTypeV22[SpanObjectTypeV22["PROJECT_LOGS"] = 2] = "PROJECT_LOGS";
181
+ return SpanObjectTypeV22;
182
+ })(SpanObjectTypeV2 || {});
183
+ var SpanObjectTypeV2EnumSchema = z2.nativeEnum(SpanObjectTypeV2);
184
+ var SpanRowIdsV2 = class {
185
+ rowId;
186
+ spanId;
187
+ rootSpanId;
188
+ constructor(args) {
189
+ this.rowId = args.rowId;
190
+ this.spanId = args.spanId;
191
+ this.rootSpanId = args.rootSpanId;
192
+ if (!this.rowId) {
193
+ throw new Error("rowId must be nonempty string");
194
+ }
195
+ if (!this.spanId) {
196
+ throw new Error("spanId must be nonempty string");
197
+ }
198
+ if (!this.rootSpanId) {
199
+ throw new Error("rootSpanId must be nonempty string");
200
+ }
201
+ }
202
+ toObject() {
203
+ return {
204
+ rowId: this.rowId,
205
+ spanId: this.spanId,
206
+ rootSpanId: this.rootSpanId
207
+ };
208
+ }
209
+ };
210
+ var SpanComponentsV2 = class _SpanComponentsV2 {
211
+ objectType;
212
+ objectId;
213
+ computeObjectMetadataArgs;
214
+ rowIds;
215
+ constructor(args) {
216
+ this.objectType = args.objectType;
217
+ this.objectId = args.objectId;
218
+ this.computeObjectMetadataArgs = args.computeObjectMetadataArgs;
219
+ this.rowIds = args.rowIds;
220
+ if (!(this.objectId || this.computeObjectMetadataArgs)) {
221
+ throw new Error(
222
+ "Must provide either objectId or computeObjectMetadataArgs"
223
+ );
224
+ }
225
+ }
226
+ toStr() {
227
+ const allBuffers = [];
228
+ const { bytes: rowIdBytes, isUUID: rowIdIsUUID } = this.rowIds ? tryMakeUuid2(this.rowIds.rowId) : { bytes: Buffer.from(""), isUUID: false };
229
+ allBuffers.push(
230
+ Buffer.from([
231
+ ENCODING_VERSION_NUMBER2,
232
+ this.objectType,
233
+ this.objectId ? 1 : 0,
234
+ this.computeObjectMetadataArgs ? 1 : 0,
235
+ this.rowIds ? 1 : 0,
236
+ rowIdIsUUID ? 1 : 0
237
+ ])
238
+ );
239
+ if (this.objectId) {
240
+ const { bytes: objectIdBytes, isUUID: objectIdIsUUID } = tryMakeUuid2(
241
+ this.objectId
242
+ );
243
+ if (!objectIdIsUUID) {
244
+ throw new Error("object_id component must be a valid UUID");
245
+ }
246
+ allBuffers.push(objectIdBytes);
247
+ }
248
+ if (this.computeObjectMetadataArgs) {
249
+ const computeObjectMetadataBytes = Buffer.from(
250
+ JSON.stringify(this.computeObjectMetadataArgs),
251
+ "utf-8"
252
+ );
253
+ const serializedLenBytes = Buffer.alloc(INTEGER_ENCODING_NUM_BYTES);
254
+ serializedLenBytes.writeInt32BE(computeObjectMetadataBytes.length);
255
+ allBuffers.push(serializedLenBytes, computeObjectMetadataBytes);
256
+ }
257
+ if (this.rowIds) {
258
+ const { bytes: spanIdBytes, isUUID: spanIdIsUUID } = tryMakeUuid2(
259
+ this.rowIds.spanId
260
+ );
261
+ if (!spanIdIsUUID) {
262
+ throw new Error("span_id component must be a valid UUID");
263
+ }
264
+ const { bytes: rootSpanIdBytes, isUUID: rootSpanIdIsUUID } = tryMakeUuid2(
265
+ this.rowIds.rootSpanId
266
+ );
267
+ if (!rootSpanIdIsUUID) {
268
+ throw new Error("root_span_id component must be a valid UUID");
269
+ }
270
+ allBuffers.push(spanIdBytes, rootSpanIdBytes, rowIdBytes);
271
+ }
272
+ return Buffer.concat(allBuffers).toString("base64");
273
+ }
274
+ static fromStr(s) {
275
+ try {
276
+ const rawBytes = Buffer.from(s, "base64");
277
+ if (rawBytes[0] < ENCODING_VERSION_NUMBER2) {
278
+ const spanComponentsOld = SpanComponentsV1.fromStr(s);
279
+ return new _SpanComponentsV2({
280
+ objectType: SpanObjectTypeV2EnumSchema.parse(
281
+ spanComponentsOld.objectType
282
+ ),
283
+ objectId: spanComponentsOld.objectId,
284
+ rowIds: spanComponentsOld.rowIds ? new SpanRowIdsV2({
285
+ rowId: spanComponentsOld.rowIds.rowId,
286
+ spanId: spanComponentsOld.rowIds.spanId,
287
+ rootSpanId: spanComponentsOld.rowIds.rootSpanId
288
+ }) : void 0
289
+ });
290
+ }
291
+ if (rawBytes[0] !== ENCODING_VERSION_NUMBER2) {
292
+ throw new Error();
293
+ }
294
+ const objectType = SpanObjectTypeV2EnumSchema.parse(rawBytes[1]);
295
+ for (let i = 2; i < 6; ++i) {
296
+ if (![0, 1].includes(rawBytes[i])) {
297
+ throw new Error();
298
+ }
299
+ }
300
+ const hasObjectId = rawBytes[2] == 1;
301
+ const hasComputeObjectMetadataArgs = rawBytes[3] == 1;
302
+ const hasRowId = rawBytes[4] == 1;
303
+ const rowIdIsUUID = rawBytes[5] == 1;
304
+ let byteCursor = 6;
305
+ let objectId = void 0;
306
+ if (hasObjectId) {
307
+ const nextByteCursor = byteCursor + 16;
308
+ objectId = uuid2.stringify(
309
+ rawBytes.subarray(byteCursor, nextByteCursor)
310
+ );
311
+ byteCursor = nextByteCursor;
312
+ }
313
+ let computeObjectMetadataArgs;
314
+ if (hasComputeObjectMetadataArgs) {
315
+ let nextByteCursor = byteCursor + INTEGER_ENCODING_NUM_BYTES;
316
+ const serializedLenBytes = rawBytes.readInt32BE(byteCursor);
317
+ byteCursor = nextByteCursor;
318
+ nextByteCursor = byteCursor + serializedLenBytes;
319
+ computeObjectMetadataArgs = JSON.parse(
320
+ rawBytes.subarray(byteCursor, nextByteCursor).toString("utf-8")
321
+ );
322
+ byteCursor = nextByteCursor;
323
+ }
324
+ const rowIds = (() => {
325
+ if (!hasRowId) {
326
+ return void 0;
327
+ }
328
+ let nextByteCursor = byteCursor + 16;
329
+ const spanId = uuid2.stringify(
330
+ rawBytes.subarray(byteCursor, nextByteCursor)
331
+ );
332
+ byteCursor = nextByteCursor;
333
+ nextByteCursor = byteCursor + 16;
334
+ const rootSpanId = uuid2.stringify(
335
+ rawBytes.subarray(byteCursor, nextByteCursor)
336
+ );
337
+ byteCursor = nextByteCursor;
338
+ const rowId = rowIdIsUUID ? uuid2.stringify(rawBytes.subarray(byteCursor)) : rawBytes.subarray(byteCursor).toString("utf-8");
339
+ return new SpanRowIdsV2({ rowId, spanId, rootSpanId });
340
+ })();
341
+ return new _SpanComponentsV2({
342
+ objectType,
343
+ objectId,
344
+ computeObjectMetadataArgs,
345
+ rowIds
346
+ });
347
+ } catch (e) {
348
+ throw new Error(INVALID_ENCODING_ERRMSG2);
349
+ }
350
+ }
351
+ objectIdFields() {
352
+ if (!this.objectId) {
353
+ throw new Error(
354
+ "Impossible: cannot invoke `object_id_fields` unless SpanComponentsV2 is initialized with an `object_id`"
355
+ );
356
+ }
357
+ switch (this.objectType) {
358
+ case 1 /* EXPERIMENT */:
359
+ return { experiment_id: this.objectId };
360
+ case 2 /* PROJECT_LOGS */:
361
+ return { project_id: this.objectId, log_id: "g" };
362
+ default:
363
+ throw new Error("Impossible");
364
+ }
365
+ }
366
+ toObject() {
367
+ return {
368
+ objectType: this.objectType,
369
+ objectId: this.objectId,
370
+ computeObjectMetadataArgs: this.computeObjectMetadataArgs,
371
+ rowIds: this.rowIds?.toObject()
372
+ };
373
+ }
374
+ };
375
+
376
+ // util/span_identifier_v3.ts
377
+ import { z as z3 } from "zod/v3";
378
+
379
+ // util/bytes.ts
380
+ function concatUint8Arrays(...arrays) {
381
+ const totalLength = arrays.reduce((acc, arr) => acc + arr.length, 0);
382
+ const result = new Uint8Array(totalLength);
383
+ let offset = 0;
384
+ for (const arr of arrays) {
385
+ result.set(arr, offset);
386
+ offset += arr.length;
387
+ }
388
+ return result;
389
+ }
390
+ function uint8ArrayToBase64(uint8Array) {
391
+ let binary = "";
392
+ for (let i = 0; i < uint8Array.length; i++) {
393
+ binary += String.fromCharCode(uint8Array[i]);
394
+ }
395
+ return btoa(binary);
396
+ }
397
+ function base64ToUint8Array(base64) {
398
+ const binary = atob(base64);
399
+ const uint8Array = new Uint8Array(binary.length);
400
+ for (let i = 0; i < binary.length; i++) {
401
+ uint8Array[i] = binary.charCodeAt(i);
402
+ }
403
+ return uint8Array;
404
+ }
405
+ function uint8ArrayToString(uint8Array) {
406
+ const decoder = new TextDecoder("utf-8");
407
+ return decoder.decode(uint8Array);
408
+ }
409
+ function stringToUint8Array(str) {
410
+ const encoder = new TextEncoder();
411
+ return encoder.encode(str);
412
+ }
413
+
414
+ // util/span_identifier_v3.ts
415
+ function tryMakeUuid3(s) {
416
+ try {
417
+ const ret = uuid3.parse(s);
418
+ if (ret.length !== 16) {
419
+ throw new Error();
420
+ }
421
+ return { bytes: new Uint8Array(ret), isUUID: true };
422
+ } catch {
423
+ return { bytes: void 0, isUUID: false };
424
+ }
425
+ }
426
+ var ENCODING_VERSION_NUMBER3 = 3;
427
+ var INVALID_ENCODING_ERRMSG3 = `SpanComponents string is not properly encoded. This library only supports encoding versions up to ${ENCODING_VERSION_NUMBER3}. Please make sure the SDK library used to decode the SpanComponents is at least as new as any library used to encode it.`;
428
+ var SpanObjectTypeV3 = /* @__PURE__ */ ((SpanObjectTypeV32) => {
429
+ SpanObjectTypeV32[SpanObjectTypeV32["EXPERIMENT"] = 1] = "EXPERIMENT";
430
+ SpanObjectTypeV32[SpanObjectTypeV32["PROJECT_LOGS"] = 2] = "PROJECT_LOGS";
431
+ SpanObjectTypeV32[SpanObjectTypeV32["PLAYGROUND_LOGS"] = 3] = "PLAYGROUND_LOGS";
432
+ return SpanObjectTypeV32;
433
+ })(SpanObjectTypeV3 || {});
434
+ var spanObjectTypeV3EnumSchema = z3.nativeEnum(SpanObjectTypeV3);
435
+ function spanObjectTypeV3ToString(objectType) {
436
+ switch (objectType) {
437
+ case 1 /* EXPERIMENT */:
438
+ return "experiment";
439
+ case 2 /* PROJECT_LOGS */:
440
+ return "project_logs";
441
+ case 3 /* PLAYGROUND_LOGS */:
442
+ return "playground_logs";
443
+ default:
444
+ const x = objectType;
445
+ throw new Error(`Unknown SpanObjectTypeV3: ${x}`);
446
+ }
447
+ }
448
+ var InternalSpanComponentUUIDFields = /* @__PURE__ */ ((InternalSpanComponentUUIDFields2) => {
449
+ InternalSpanComponentUUIDFields2[InternalSpanComponentUUIDFields2["OBJECT_ID"] = 1] = "OBJECT_ID";
450
+ InternalSpanComponentUUIDFields2[InternalSpanComponentUUIDFields2["ROW_ID"] = 2] = "ROW_ID";
451
+ InternalSpanComponentUUIDFields2[InternalSpanComponentUUIDFields2["SPAN_ID"] = 3] = "SPAN_ID";
452
+ InternalSpanComponentUUIDFields2[InternalSpanComponentUUIDFields2["ROOT_SPAN_ID"] = 4] = "ROOT_SPAN_ID";
453
+ return InternalSpanComponentUUIDFields2;
454
+ })(InternalSpanComponentUUIDFields || {});
455
+ var internalSpanComponentUUIDFieldsEnumSchema = z3.nativeEnum(
456
+ InternalSpanComponentUUIDFields
457
+ );
458
+ var _INTERNAL_SPAN_COMPONENT_UUID_FIELDS_ID_TO_NAME = {
459
+ [1 /* OBJECT_ID */]: "object_id",
460
+ [2 /* ROW_ID */]: "row_id",
461
+ [3 /* SPAN_ID */]: "span_id",
462
+ [4 /* ROOT_SPAN_ID */]: "root_span_id"
463
+ };
464
+ var spanComponentsV3Schema = z3.object({
465
+ object_type: spanObjectTypeV3EnumSchema,
466
+ // TODO(manu): We should have a more elaborate zod schema for
467
+ // `propagated_event`. This will required zod-ifying the contents of
468
+ // sdk/js/util/object.ts.
469
+ propagated_event: z3.record(z3.unknown()).nullish()
470
+ }).and(
471
+ z3.union([
472
+ // Must provide one or the other.
473
+ z3.object({
474
+ object_id: z3.string().nullish(),
475
+ compute_object_metadata_args: z3.optional(z3.null())
476
+ }),
477
+ z3.object({
478
+ object_id: z3.optional(z3.null()),
479
+ compute_object_metadata_args: z3.record(z3.unknown())
480
+ })
481
+ ])
482
+ ).and(
483
+ z3.union([
484
+ // Either all of these must be provided or none.
485
+ z3.object({
486
+ row_id: z3.string(),
487
+ span_id: z3.string(),
488
+ root_span_id: z3.string()
489
+ }),
490
+ z3.object({
491
+ row_id: z3.optional(z3.null()),
492
+ span_id: z3.optional(z3.null()),
493
+ root_span_id: z3.optional(z3.null())
494
+ })
495
+ ])
496
+ );
497
+ var SpanComponentsV3 = class _SpanComponentsV3 {
498
+ constructor(data) {
499
+ this.data = data;
500
+ }
501
+ toStr() {
502
+ const jsonObj = {
503
+ compute_object_metadata_args: this.data.compute_object_metadata_args || void 0,
504
+ propagated_event: this.data.propagated_event || void 0
505
+ };
506
+ const allBuffers = [];
507
+ allBuffers.push(
508
+ new Uint8Array([ENCODING_VERSION_NUMBER3, this.data.object_type])
509
+ );
510
+ const uuidEntries = [];
511
+ function addUuidField(origVal, fieldId) {
512
+ const ret = tryMakeUuid3(origVal);
513
+ if (ret.isUUID) {
514
+ uuidEntries.push(
515
+ concatUint8Arrays(new Uint8Array([fieldId]), ret.bytes)
516
+ );
517
+ } else {
518
+ jsonObj[_INTERNAL_SPAN_COMPONENT_UUID_FIELDS_ID_TO_NAME[fieldId]] = origVal;
519
+ }
520
+ }
521
+ if (this.data.object_id) {
522
+ addUuidField(
523
+ this.data.object_id,
524
+ 1 /* OBJECT_ID */
525
+ );
526
+ }
527
+ if (this.data.row_id) {
528
+ addUuidField(this.data.row_id, 2 /* ROW_ID */);
529
+ }
530
+ if (this.data.span_id) {
531
+ addUuidField(this.data.span_id, 3 /* SPAN_ID */);
532
+ }
533
+ if (this.data.root_span_id) {
534
+ addUuidField(
535
+ this.data.root_span_id,
536
+ 4 /* ROOT_SPAN_ID */
537
+ );
538
+ }
539
+ if (uuidEntries.length > 255) {
540
+ throw new Error("Impossible: too many UUID entries to encode");
541
+ }
542
+ allBuffers.push(new Uint8Array([uuidEntries.length]));
543
+ allBuffers.push(...uuidEntries);
544
+ if (Object.keys(jsonObj).length > 0) {
545
+ allBuffers.push(stringToUint8Array(JSON.stringify(jsonObj)));
546
+ }
547
+ return uint8ArrayToBase64(concatUint8Arrays(...allBuffers));
548
+ }
549
+ static fromStr(s) {
550
+ try {
551
+ const rawBytes = base64ToUint8Array(s);
552
+ const jsonObj = {};
553
+ if (rawBytes[0] < ENCODING_VERSION_NUMBER3) {
554
+ const spanComponentsOld = SpanComponentsV2.fromStr(s);
555
+ jsonObj["object_type"] = spanComponentsOld.objectType;
556
+ jsonObj["object_id"] = spanComponentsOld.objectId;
557
+ jsonObj["compute_object_metadata_args"] = spanComponentsOld.computeObjectMetadataArgs;
558
+ if (spanComponentsOld.rowIds) {
559
+ jsonObj["row_id"] = spanComponentsOld.rowIds.rowId;
560
+ jsonObj["span_id"] = spanComponentsOld.rowIds.spanId;
561
+ jsonObj["root_span_id"] = spanComponentsOld.rowIds.rootSpanId;
562
+ }
563
+ } else {
564
+ jsonObj["object_type"] = rawBytes[1];
565
+ const numUuidEntries = rawBytes[2];
566
+ let byteOffset = 3;
567
+ for (let i = 0; i < numUuidEntries; ++i) {
568
+ const fieldId = internalSpanComponentUUIDFieldsEnumSchema.parse(
569
+ rawBytes[byteOffset]
570
+ );
571
+ const fieldBytes = rawBytes.subarray(byteOffset + 1, byteOffset + 17);
572
+ byteOffset += 17;
573
+ jsonObj[_INTERNAL_SPAN_COMPONENT_UUID_FIELDS_ID_TO_NAME[fieldId]] = uuid3.stringify(fieldBytes);
574
+ }
575
+ if (byteOffset < rawBytes.length) {
576
+ const remainingJsonObj = JSON.parse(
577
+ uint8ArrayToString(rawBytes.subarray(byteOffset))
578
+ );
579
+ Object.assign(jsonObj, remainingJsonObj);
580
+ }
581
+ }
582
+ return _SpanComponentsV3.fromJsonObj(jsonObj);
583
+ } catch {
584
+ throw new Error(INVALID_ENCODING_ERRMSG3);
585
+ }
586
+ }
587
+ objectIdFields() {
588
+ if (!this.data.object_id) {
589
+ throw new Error(
590
+ "Impossible: cannot invoke `objectIdFields` unless SpanComponentsV3 is initialized with an `object_id`"
591
+ );
592
+ }
593
+ switch (this.data.object_type) {
594
+ case 1 /* EXPERIMENT */:
595
+ return { experiment_id: this.data.object_id };
596
+ case 2 /* PROJECT_LOGS */:
597
+ return { project_id: this.data.object_id, log_id: "g" };
598
+ case 3 /* PLAYGROUND_LOGS */:
599
+ return { prompt_session_id: this.data.object_id, log_id: "x" };
600
+ default:
601
+ const _ = this.data.object_type;
602
+ throw new Error("Impossible");
603
+ }
604
+ }
605
+ async export() {
606
+ return this.toStr();
607
+ }
608
+ static fromJsonObj(jsonObj) {
609
+ return new _SpanComponentsV3(spanComponentsV3Schema.parse(jsonObj));
610
+ }
611
+ };
612
+ function parseParent(parent) {
613
+ return typeof parent === "string" ? parent : parent ? new SpanComponentsV3({
614
+ object_type: parent.object_type === "experiment" ? 1 /* EXPERIMENT */ : parent.object_type === "playground_logs" ? 3 /* PLAYGROUND_LOGS */ : 2 /* PROJECT_LOGS */,
615
+ object_id: parent.object_id,
616
+ ...parent.row_ids ? {
617
+ row_id: parent.row_ids.id,
618
+ span_id: parent.row_ids.span_id,
619
+ root_span_id: parent.row_ids.root_span_id
620
+ } : {
621
+ row_id: void 0,
622
+ span_id: void 0,
623
+ root_span_id: void 0
624
+ },
625
+ propagated_event: parent.propagated_event
626
+ }).toStr() : void 0;
627
+ }
628
+
629
+ // util/http_headers.ts
630
+ var BT_FOUND_EXISTING_HEADER = "x-bt-found-existing";
631
+ var BT_CURSOR_HEADER = "x-bt-cursor";
632
+ var BT_IMPERSONATE_USER = "x-bt-impersonate-user";
633
+ var BT_PARENT = "x-bt-parent";
634
+ var EXPERIMENT_ID_PREFIX = "experiment_id:";
635
+ var PROJECT_ID_PREFIX = "project_id:";
636
+ var PROJECT_NAME_PREFIX = "project_name:";
637
+ var PLAYGROUND_ID_PREFIX = "playground_id:";
638
+ function resolveParentHeader(header) {
639
+ if (header.startsWith(EXPERIMENT_ID_PREFIX)) {
640
+ return new SpanComponentsV3({
641
+ object_type: 1 /* EXPERIMENT */,
642
+ object_id: header.substring(EXPERIMENT_ID_PREFIX.length)
643
+ });
644
+ } else if (header.startsWith(PROJECT_ID_PREFIX)) {
645
+ return new SpanComponentsV3({
646
+ object_type: 2 /* PROJECT_LOGS */,
647
+ object_id: header.substring(PROJECT_ID_PREFIX.length)
648
+ });
649
+ } else if (header.startsWith(PLAYGROUND_ID_PREFIX)) {
650
+ return new SpanComponentsV3({
651
+ object_type: 3 /* PLAYGROUND_LOGS */,
652
+ object_id: header.substring(PLAYGROUND_ID_PREFIX.length)
653
+ });
654
+ } else if (header.startsWith(PROJECT_NAME_PREFIX)) {
655
+ const projectName = header.substring(PROJECT_NAME_PREFIX.length);
656
+ return new SpanComponentsV3({
657
+ object_type: 2 /* PROJECT_LOGS */,
658
+ compute_object_metadata_args: {
659
+ project_name: projectName
660
+ }
661
+ });
662
+ }
663
+ return SpanComponentsV3.fromStr(header);
664
+ }
665
+
666
+ // util/type_util.ts
667
+ function isObject(value) {
668
+ return value instanceof Object && !(value instanceof Array);
669
+ }
670
+ function isArray(value) {
671
+ return value instanceof Array;
672
+ }
673
+ function isObjectOrArray(value) {
674
+ return value instanceof Object;
675
+ }
676
+ function isEmpty(a) {
677
+ return a === void 0 || a === null;
678
+ }
679
+ function notEmpty(a) {
680
+ if (!isEmpty(a)) {
681
+ return a;
682
+ } else {
683
+ throw new Error(`Unexpected empty value ${a}`);
684
+ }
685
+ }
686
+ function isNumber(a) {
687
+ return typeof a === "number" || typeof a === "bigint";
688
+ }
689
+
690
+ // util/object_util.ts
691
+ function mergeDictsWithPaths({
692
+ mergeInto,
693
+ mergeFrom,
694
+ mergePaths
695
+ }) {
696
+ const mergePathsSerialized = new Set(
697
+ mergePaths.map((p) => JSON.stringify(p))
698
+ );
699
+ return mergeDictsWithPathsHelper({
700
+ mergeInto,
701
+ mergeFrom,
702
+ path: [],
703
+ mergePaths: mergePathsSerialized
704
+ });
705
+ }
706
+ function mergeDictsWithPathsHelper({
707
+ mergeInto,
708
+ mergeFrom,
709
+ path,
710
+ mergePaths
711
+ }) {
712
+ Object.entries(mergeFrom).forEach(([k, mergeFromV]) => {
713
+ const fullPath = path.concat([k]);
714
+ const fullPathSerialized = JSON.stringify(fullPath);
715
+ const mergeIntoV = recordFind(mergeInto, k);
716
+ if (isObject(mergeIntoV) && isObject(mergeFromV) && !mergePaths.has(fullPathSerialized)) {
717
+ mergeDictsWithPathsHelper({
718
+ mergeInto: mergeIntoV,
719
+ mergeFrom: mergeFromV,
720
+ path: fullPath,
721
+ mergePaths
722
+ });
723
+ } else {
724
+ mergeInto[k] = mergeFromV;
725
+ }
726
+ });
727
+ return mergeInto;
728
+ }
729
+ function mergeDicts(mergeInto, mergeFrom) {
730
+ return mergeDictsWithPaths({ mergeInto, mergeFrom, mergePaths: [] });
731
+ }
732
+ function forEachMissingKey({
733
+ lhs,
734
+ rhs,
735
+ fn
736
+ }) {
737
+ function helper(lhs2, rhs2, path) {
738
+ if (lhs2 instanceof Object) {
739
+ if (!(rhs2 instanceof Object)) {
740
+ return;
741
+ }
742
+ const lhsRec = lhs2;
743
+ const rhsRec = rhs2;
744
+ for (const [k, v] of Object.entries(rhsRec)) {
745
+ if (!(k in lhsRec)) {
746
+ fn({ lhs: lhsRec, k, v, path });
747
+ } else {
748
+ helper(lhsRec[k], rhsRec[k], [...path, k]);
749
+ }
750
+ }
751
+ }
752
+ }
753
+ helper(lhs, rhs, []);
754
+ }
755
+ function mapAt(m, k) {
756
+ const ret = m.get(k);
757
+ if (ret === void 0) {
758
+ throw new Error(`Map does not contain key ${k}`);
759
+ }
760
+ return ret;
761
+ }
762
+ function mapSetDefault(m, k, _default) {
763
+ const ret = m.get(k);
764
+ if (ret === void 0) {
765
+ m.set(k, _default);
766
+ return _default;
767
+ } else {
768
+ return ret;
769
+ }
770
+ }
771
+ function mapSetNotPresent(m, k, v) {
772
+ if (m.has(k)) {
773
+ throw new Error(`Map already contains key ${k}`);
774
+ }
775
+ return m.set(k, v);
776
+ }
777
+ function recordFind(m, k) {
778
+ return m[k];
779
+ }
780
+ function recordAt(m, k) {
781
+ const ret = recordFind(m, k);
782
+ if (ret === void 0) {
783
+ throw new Error(`Record does not contain key ${String(k)}`);
784
+ }
785
+ return ret;
786
+ }
787
+ function recordSetDefault(m, k, _default) {
788
+ const ret = recordFind(m, k);
789
+ if (ret === void 0) {
790
+ m[k] = _default;
791
+ return _default;
792
+ } else {
793
+ return ret;
794
+ }
795
+ }
796
+ function getRecordKeys(obj) {
797
+ return Object.keys(obj);
798
+ }
799
+ function getObjValueByPath(row, path) {
800
+ let curr = row;
801
+ for (const p of path) {
802
+ if (!isObjectOrArray(curr)) {
803
+ return null;
804
+ }
805
+ curr = curr[p];
806
+ }
807
+ return curr;
808
+ }
809
+
810
+ // util/graph_util.ts
811
+ function depthFirstSearch(args) {
812
+ const { graph, firstVisitF, lastVisitF } = args;
813
+ for (const vs of graph.values()) {
814
+ for (const v of vs.values()) {
815
+ if (!graph.has(v)) {
816
+ throw new Error(`Outgoing vertex ${v} must be a key in the graph`);
817
+ }
818
+ }
819
+ }
820
+ const firstVisitedVertices = /* @__PURE__ */ new Set();
821
+ const visitationOrder = args.visitationOrder ?? [...graph.keys()];
822
+ const events = visitationOrder.map((vertex) => ({ eventType: "first", vertex, extras: {} })).reverse();
823
+ while (events.length) {
824
+ const { eventType, vertex, extras } = events.pop();
825
+ if (eventType === "last") {
826
+ lastVisitF?.(vertex);
827
+ continue;
828
+ }
829
+ if (firstVisitedVertices.has(vertex)) {
830
+ continue;
831
+ }
832
+ firstVisitedVertices.add(vertex);
833
+ firstVisitF?.(vertex, { parentVertex: extras.parentVertex });
834
+ events.push({ eventType: "last", vertex, extras: {} });
835
+ mapAt(graph, vertex).forEach((child) => {
836
+ events.push({
837
+ eventType: "first",
838
+ vertex: child,
839
+ extras: { parentVertex: vertex }
840
+ });
841
+ });
842
+ }
843
+ }
844
+ function undirectedConnectedComponents(graph) {
845
+ const directedGraph = new Map(
846
+ [...graph.vertices].map((v) => [v, /* @__PURE__ */ new Set()])
847
+ );
848
+ for (const [i, j] of graph.edges) {
849
+ mapAt(directedGraph, i).add(j);
850
+ mapAt(directedGraph, j).add(i);
851
+ }
852
+ let labelCounter = 0;
853
+ const vertexLabels = /* @__PURE__ */ new Map();
854
+ const firstVisitF = (vertex, args) => {
855
+ const label = args?.parentVertex !== void 0 ? mapAt(vertexLabels, args?.parentVertex) : labelCounter++;
856
+ vertexLabels.set(vertex, label);
857
+ };
858
+ depthFirstSearch({ graph: directedGraph, firstVisitF });
859
+ const output = Array.from({ length: labelCounter }).map(() => []);
860
+ for (const [vertex, label] of vertexLabels.entries()) {
861
+ output[label].push(vertex);
862
+ }
863
+ return output;
864
+ }
865
+ function topologicalSort(graph, visitationOrder) {
866
+ const reverseOrdering = [];
867
+ const lastVisitF = (vertex) => {
868
+ reverseOrdering.push(vertex);
869
+ };
870
+ depthFirstSearch({ graph, lastVisitF, visitationOrder });
871
+ return reverseOrdering.reverse();
872
+ }
873
+
874
+ // util/merge_row_batch.ts
875
+ function generateMergedRowKey(row, useParentIdForId) {
876
+ return JSON.stringify(
877
+ [
878
+ "org_id",
879
+ "project_id",
880
+ "experiment_id",
881
+ "dataset_id",
882
+ "prompt_session_id",
883
+ "log_id",
884
+ useParentIdForId ?? false ? PARENT_ID_FIELD : "id"
885
+ ].map((k) => row[k])
886
+ );
887
+ }
888
+ var MERGE_ROW_SKIP_FIELDS = [
889
+ "created",
890
+ "span_id",
891
+ "root_span_id",
892
+ "span_parents",
893
+ "_parent_id"
894
+ // TODO: handle merge paths.
895
+ ];
896
+ function popMergeRowSkipFields(row) {
897
+ const popped = {};
898
+ for (const field of MERGE_ROW_SKIP_FIELDS) {
899
+ if (field in row) {
900
+ popped[field] = row[field];
901
+ delete row[field];
902
+ }
903
+ }
904
+ return popped;
905
+ }
906
+ function restoreMergeRowSkipFields(row, skipFields) {
907
+ for (const field of MERGE_ROW_SKIP_FIELDS) {
908
+ delete row[field];
909
+ if (field in skipFields) {
910
+ row[field] = skipFields[field];
911
+ }
912
+ }
913
+ }
914
+ function mergeRowBatch(rows) {
915
+ for (const row of rows) {
916
+ if (row.id === void 0) {
917
+ throw new Error(
918
+ "Logged row is missing an id. This is an internal braintrust error. Please contact us at info@braintrust.dev for help"
919
+ );
920
+ }
921
+ }
922
+ const rowGroups = /* @__PURE__ */ new Map();
923
+ for (const row of rows) {
924
+ const key = generateMergedRowKey(row);
925
+ const existingRow = rowGroups.get(key);
926
+ if (existingRow !== void 0 && row[IS_MERGE_FIELD]) {
927
+ const skipFields = popMergeRowSkipFields(existingRow);
928
+ const preserveNoMerge = !existingRow[IS_MERGE_FIELD];
929
+ mergeDicts(existingRow, row);
930
+ restoreMergeRowSkipFields(existingRow, skipFields);
931
+ if (preserveNoMerge) {
932
+ delete existingRow[IS_MERGE_FIELD];
933
+ }
934
+ } else {
935
+ rowGroups.set(key, row);
936
+ }
937
+ }
938
+ const merged = [...rowGroups.values()];
939
+ const rowToLabel = new Map(
940
+ merged.map((r, i) => [generateMergedRowKey(r), i])
941
+ );
942
+ const graph = new Map(
943
+ Array.from({ length: merged.length }).map((_, i) => [i, /* @__PURE__ */ new Set()])
944
+ );
945
+ merged.forEach((r, i) => {
946
+ const parentId = r[PARENT_ID_FIELD];
947
+ if (!parentId) {
948
+ return;
949
+ }
950
+ const parentRowKey = generateMergedRowKey(
951
+ r,
952
+ true
953
+ /* useParentIdForId */
954
+ );
955
+ const parentLabel = rowToLabel.get(parentRowKey);
956
+ if (parentLabel !== void 0) {
957
+ mapAt(graph, parentLabel).add(i);
958
+ }
959
+ });
960
+ const connectedComponents = undirectedConnectedComponents({
961
+ vertices: new Set(graph.keys()),
962
+ edges: new Set(
963
+ [...graph.entries()].flatMap(
964
+ ([k, vs]) => [...vs].map((v) => {
965
+ const ret = [k, v];
966
+ return ret;
967
+ })
968
+ )
969
+ )
970
+ });
971
+ const buckets = connectedComponents.map(
972
+ (cc) => topologicalSort(
973
+ graph,
974
+ cc
975
+ /* visitationOrder */
976
+ )
977
+ );
978
+ return buckets.map((bucket) => bucket.map((i) => merged[i]));
979
+ }
980
+ function batchItems(args) {
981
+ let { items } = args;
982
+ const batchMaxNumItems = args.batchMaxNumItems ?? Number.POSITIVE_INFINITY;
983
+ const batchMaxNumBytes = args.batchMaxNumBytes ?? Number.POSITIVE_INFINITY;
984
+ const output = [];
985
+ let nextItems = [];
986
+ let batchSet = [];
987
+ let batch = [];
988
+ let batchLen = 0;
989
+ function addToBatch(item) {
990
+ batch.push(item);
991
+ batchLen += item.length;
992
+ }
993
+ function flushBatch() {
994
+ batchSet.push(batch);
995
+ batch = [];
996
+ batchLen = 0;
997
+ }
998
+ while (items.length) {
999
+ for (const bucket of items) {
1000
+ let i = 0;
1001
+ for (const item of bucket) {
1002
+ if (batch.length === 0 || item.length + batchLen < batchMaxNumBytes && batch.length < batchMaxNumItems) {
1003
+ addToBatch(item);
1004
+ } else if (i === 0) {
1005
+ flushBatch();
1006
+ addToBatch(item);
1007
+ } else {
1008
+ break;
1009
+ }
1010
+ ++i;
1011
+ }
1012
+ if (i < bucket.length) {
1013
+ nextItems.push(bucket.slice(i));
1014
+ }
1015
+ if (batchLen >= batchMaxNumBytes || batch.length > batchMaxNumItems) {
1016
+ flushBatch();
1017
+ }
1018
+ }
1019
+ if (batch.length) {
1020
+ flushBatch();
1021
+ }
1022
+ if (batchSet.length) {
1023
+ output.push(batchSet);
1024
+ batchSet = [];
1025
+ }
1026
+ items = nextItems;
1027
+ nextItems = [];
1028
+ }
1029
+ return output;
1030
+ }
1031
+
1032
+ // util/object.ts
1033
+ var DEFAULT_IS_LEGACY_DATASET = false;
1034
+ function ensureDatasetRecord(r, legacy) {
1035
+ if (legacy) {
1036
+ return ensureLegacyDatasetRecord(r);
1037
+ } else {
1038
+ return ensureNewDatasetRecord(r);
1039
+ }
1040
+ }
1041
+ function ensureLegacyDatasetRecord(r) {
1042
+ if ("output" in r) {
1043
+ return r;
1044
+ }
1045
+ const row = {
1046
+ ...r,
1047
+ output: r.expected
1048
+ };
1049
+ delete row.expected;
1050
+ return row;
1051
+ }
1052
+ function ensureNewDatasetRecord(r) {
1053
+ if ("expected" in r) {
1054
+ return r;
1055
+ }
1056
+ const row = {
1057
+ ...r,
1058
+ tags: null,
1059
+ expected: r.output
1060
+ };
1061
+ delete row.output;
1062
+ return row;
1063
+ }
1064
+
1065
+ // util/json_util.ts
1066
+ function deterministicReplacer(_key, value) {
1067
+ return value instanceof Object && !(value instanceof Array) ? Object.keys(value).sort().reduce((sorted, key) => {
1068
+ sorted[key] = value[key];
1069
+ return sorted;
1070
+ }, {}) : value;
1071
+ }
1072
+ function constructJsonArray(items) {
1073
+ return `[${items.join(",")}]`;
1074
+ }
1075
+
1076
+ // util/string_util.ts
1077
+ function _urljoin(...parts) {
1078
+ return parts.map(
1079
+ (x, i) => x.replace(/^\//, "").replace(i < parts.length - 1 ? /\/$/ : "", "")
1080
+ ).filter((x) => x.trim() !== "").join("/");
1081
+ }
1082
+ function capitalize(s, sep) {
1083
+ const items = sep ? s.split(sep) : [s];
1084
+ return items.map((s2) => s2 ? s2.charAt(0).toUpperCase() + s2.slice(1) : s2).join(sep || "");
1085
+ }
1086
+ function lowercase(s, sep) {
1087
+ const items = sep ? s.split(sep) : [s];
1088
+ return items.map((s2) => s2 ? s2.charAt(0).toLowerCase() + s2.slice(1) : s2).join(sep || "");
1089
+ }
1090
+ function snakeToCamelCase(s) {
1091
+ return s.split("_").map((s2) => capitalize(s2)).join("");
1092
+ }
1093
+ function snakeToTitleCase(s) {
1094
+ return capitalize(s, "_").replace("_", " ");
1095
+ }
1096
+ function camelToSnakeCase(s) {
1097
+ return s.replace(/([A-Z])/g, (m) => "_" + m.toLowerCase()).replace(/^_/, "");
1098
+ }
1099
+
1100
+ // util/span_types.ts
1101
+ var spanTypeAttributeValues = [
1102
+ "llm",
1103
+ "score",
1104
+ "function",
1105
+ "eval",
1106
+ "task",
1107
+ "tool"
1108
+ ];
1109
+ var SpanTypeAttribute = /* @__PURE__ */ ((SpanTypeAttribute2) => {
1110
+ SpanTypeAttribute2["LLM"] = "llm";
1111
+ SpanTypeAttribute2["SCORE"] = "score";
1112
+ SpanTypeAttribute2["FUNCTION"] = "function";
1113
+ SpanTypeAttribute2["EVAL"] = "eval";
1114
+ SpanTypeAttribute2["TASK"] = "task";
1115
+ SpanTypeAttribute2["TOOL"] = "tool";
1116
+ return SpanTypeAttribute2;
1117
+ })(SpanTypeAttribute || {});
1118
+ var spanPurposeAttributeValues = ["scorer"];
1119
+
1120
+ // util/git_fields.ts
1121
+ function mergeGitMetadataSettings(s1, s2) {
1122
+ if (s1.collect === "all") {
1123
+ return s2;
1124
+ } else if (s2.collect === "all") {
1125
+ return s1;
1126
+ } else if (s1.collect === "none") {
1127
+ return s1;
1128
+ } else if (s2.collect === "none") {
1129
+ return s2;
1130
+ }
1131
+ const fields = (s1.fields ?? []).filter((f) => (s2.fields ?? []).includes(f));
1132
+ const collect = fields.length > 0 ? "some" : "none";
1133
+ return { collect, fields };
1134
+ }
1135
+
1136
+ // util/xact-ids.ts
1137
+ var TOP_BITS = BigInt("0x0DE1") << BigInt(48);
1138
+ var MOD = BigInt(1) << BigInt(64);
1139
+ var COPRIME = BigInt("205891132094649");
1140
+ var COPRIME_INVERSE = BigInt("1522336535492693385");
1141
+ function modularMultiply(value, prime) {
1142
+ return value * prime % MOD;
1143
+ }
1144
+ function prettifyXact(valueString) {
1145
+ const value = BigInt(valueString);
1146
+ const encoded = modularMultiply(value, COPRIME);
1147
+ return encoded.toString(16).padStart(16, "0");
1148
+ }
1149
+ function loadPrettyXact(encodedHex) {
1150
+ if (encodedHex.length !== 16) {
1151
+ return encodedHex;
1152
+ }
1153
+ const value = BigInt(`0x${encodedHex}`);
1154
+ const multipliedInverse = modularMultiply(value, COPRIME_INVERSE);
1155
+ const withTopBits = TOP_BITS | multipliedInverse;
1156
+ return withTopBits.toString();
1157
+ }
1158
+
1159
+ // util/zod_util.ts
1160
+ import { z as z4 } from "zod/v3";
1161
+ var ExtraFieldsError = class extends Error {
1162
+ constructor(key, path) {
1163
+ super(
1164
+ `Extraneous key ${JSON.stringify(key)} at path ${JSON.stringify(path)}`
1165
+ );
1166
+ this.key = key;
1167
+ this.path = path;
1168
+ }
1169
+ };
1170
+ function parseNoStrip(schema, input) {
1171
+ const output = schema.parse(input);
1172
+ forEachMissingKey({
1173
+ lhs: output,
1174
+ rhs: input,
1175
+ fn: ({ k, path }) => {
1176
+ throw new ExtraFieldsError(k, path);
1177
+ }
1178
+ });
1179
+ return output;
1180
+ }
1181
+ function objectNullish(object) {
1182
+ return new z4.ZodObject({
1183
+ ...object._def,
1184
+ shape: () => Object.fromEntries(
1185
+ Object.entries(object.shape).map(([k, v]) => [k, v.nullish()])
1186
+ )
1187
+ });
1188
+ }
1189
+ export {
1190
+ ASYNC_SCORING_CONTROL_FIELD,
1191
+ AUDIT_METADATA_FIELD,
1192
+ AUDIT_SOURCE_FIELD,
1193
+ BT_CURSOR_HEADER,
1194
+ BT_FOUND_EXISTING_HEADER,
1195
+ BT_IMPERSONATE_USER,
1196
+ BT_PARENT,
1197
+ CREATED_FIELD,
1198
+ DEFAULT_IS_LEGACY_DATASET,
1199
+ ExtraFieldsError,
1200
+ ID_FIELD,
1201
+ IS_MERGE_FIELD,
1202
+ MERGE_PATHS_FIELD,
1203
+ OBJECT_DELETE_FIELD,
1204
+ PARENT_ID_FIELD,
1205
+ SKIP_ASYNC_SCORING_FIELD,
1206
+ SpanComponentsV1,
1207
+ SpanComponentsV2,
1208
+ SpanComponentsV3,
1209
+ SpanObjectTypeV1,
1210
+ SpanObjectTypeV2,
1211
+ SpanObjectTypeV3,
1212
+ SpanRowIdsV1,
1213
+ SpanRowIdsV2,
1214
+ SpanTypeAttribute,
1215
+ TRANSACTION_ID_FIELD,
1216
+ VALID_SOURCES,
1217
+ _urljoin,
1218
+ base64ToUint8Array,
1219
+ batchItems,
1220
+ camelToSnakeCase,
1221
+ capitalize,
1222
+ concatUint8Arrays,
1223
+ constructJsonArray,
1224
+ deterministicReplacer,
1225
+ ensureDatasetRecord,
1226
+ ensureLegacyDatasetRecord,
1227
+ ensureNewDatasetRecord,
1228
+ forEachMissingKey,
1229
+ getObjValueByPath,
1230
+ getRecordKeys,
1231
+ isArray,
1232
+ isEmpty,
1233
+ isNumber,
1234
+ isObject,
1235
+ isObjectOrArray,
1236
+ loadPrettyXact,
1237
+ lowercase,
1238
+ mapAt,
1239
+ mapSetDefault,
1240
+ mapSetNotPresent,
1241
+ mergeDicts,
1242
+ mergeDictsWithPaths,
1243
+ mergeGitMetadataSettings,
1244
+ mergeRowBatch,
1245
+ notEmpty,
1246
+ objectNullish,
1247
+ parseNoStrip,
1248
+ parseParent,
1249
+ prettifyXact,
1250
+ recordAt,
1251
+ recordFind,
1252
+ recordSetDefault,
1253
+ resolveParentHeader,
1254
+ snakeToCamelCase,
1255
+ snakeToTitleCase,
1256
+ spanComponentsV3Schema,
1257
+ spanObjectTypeV3EnumSchema,
1258
+ spanObjectTypeV3ToString,
1259
+ spanPurposeAttributeValues,
1260
+ spanTypeAttributeValues,
1261
+ stringToUint8Array,
1262
+ uint8ArrayToBase64,
1263
+ uint8ArrayToString
1264
+ };