apps 0.0.1-beta.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 (135) hide show
  1. package/README.md +191 -0
  2. package/check-publish.mjs +10 -0
  3. package/framework-reference.json +1 -0
  4. package/js/chunk-22WRQZT7.js +389 -0
  5. package/js/chunk-2OTCEKL2.js +29480 -0
  6. package/js/chunk-36DNRFZQ.js +34 -0
  7. package/js/chunk-3ANFZFCV.js +1799 -0
  8. package/js/chunk-7JXHF5IF.js +138 -0
  9. package/js/chunk-BCSNKUAC.js +0 -0
  10. package/js/chunk-BKVL7XAJ.js +47 -0
  11. package/js/chunk-BPEFS4YF.js +1323 -0
  12. package/js/chunk-C24KEZXR.js +59 -0
  13. package/js/chunk-D6BKYP2L.js +877 -0
  14. package/js/chunk-EP6AEUZO.js +19 -0
  15. package/js/chunk-HP7E42X6.js +1719 -0
  16. package/js/chunk-KWTCHVLT.js +284 -0
  17. package/js/chunk-LOKGDT6B.js +28 -0
  18. package/js/chunk-MLKGABMK.js +9 -0
  19. package/js/chunk-OWD2YICM.js +2486 -0
  20. package/js/chunk-Q2FD5IBM.js +899 -0
  21. package/js/chunk-R6JMJSVT.js +590 -0
  22. package/js/chunk-SBKHUC5L.js +56 -0
  23. package/js/chunk-VFUZI3NY.js +75 -0
  24. package/js/chunk-W7Q5EOTS.js +4375 -0
  25. package/js/chunk-WIDTG42X.js +171 -0
  26. package/js/chunk-X3YBZCJW.js +246 -0
  27. package/js/chunk-YDR4CPJA.js +2357 -0
  28. package/js/client.js +1023 -0
  29. package/js/contracts.js +163 -0
  30. package/js/effect.js +44 -0
  31. package/js/graphql.js +392 -0
  32. package/js/host.js +193 -0
  33. package/js/index.js +284 -0
  34. package/js/mcp/effect.js +23 -0
  35. package/js/mcp/stdio.js +123 -0
  36. package/js/mcp.js +37 -0
  37. package/js/openapi.js +246 -0
  38. package/js/operations/approval.js +9 -0
  39. package/js/react.js +37 -0
  40. package/js/storage/facet.js +546 -0
  41. package/js/ui/auth/contracts.js +19 -0
  42. package/js/ui/auth.js +28 -0
  43. package/js/ui/contracts.js +24 -0
  44. package/js/ui/serving.js +286 -0
  45. package/package.json +116 -0
  46. package/runtime.json +1 -0
  47. package/types/app-data/src/contracts/database.d.ts +193 -0
  48. package/types/app-data/src/implementation/cursor.d.ts +10 -0
  49. package/types/app-data/src/implementation/index-key.d.ts +7 -0
  50. package/types/app-data/src/implementation/promise.d.ts +68 -0
  51. package/types/app-data/src/implementation/range.d.ts +8 -0
  52. package/types/app-data/src/implementation/schema.d.ts +33 -0
  53. package/types/app-data/src/implementation/sqlite.d.ts +11 -0
  54. package/types/app-data/src/index.d.ts +4 -0
  55. package/types/apps/src/approval.d.ts +10 -0
  56. package/types/apps/src/client.d.ts +5 -0
  57. package/types/apps/src/contracts/app.d.ts +58 -0
  58. package/types/apps/src/contracts/approval.d.ts +14 -0
  59. package/types/apps/src/contracts/context.d.ts +25 -0
  60. package/types/apps/src/contracts/elicitation.d.ts +86 -0
  61. package/types/apps/src/contracts/graphql.d.ts +102 -0
  62. package/types/apps/src/contracts/host.d.ts +568 -0
  63. package/types/apps/src/contracts/http.d.ts +20 -0
  64. package/types/apps/src/contracts/live.d.ts +26 -0
  65. package/types/apps/src/contracts/mcp.d.ts +93 -0
  66. package/types/apps/src/contracts/openapi.d.ts +105 -0
  67. package/types/apps/src/contracts/operations.d.ts +30 -0
  68. package/types/apps/src/contracts/optimistic.d.ts +22 -0
  69. package/types/apps/src/contracts/provider.d.ts +96 -0
  70. package/types/apps/src/contracts/schedules.d.ts +51 -0
  71. package/types/apps/src/contracts/schema.d.ts +20 -0
  72. package/types/apps/src/contracts/storage.d.ts +68 -0
  73. package/types/apps/src/contracts/tools.d.ts +11 -0
  74. package/types/apps/src/contracts/ui-auth.d.ts +28 -0
  75. package/types/apps/src/contracts/ui.d.ts +90 -0
  76. package/types/apps/src/contracts/webhook-protocol.d.ts +102 -0
  77. package/types/apps/src/contracts/webhooks.d.ts +53 -0
  78. package/types/apps/src/contracts/workflows.d.ts +277 -0
  79. package/types/apps/src/effect.d.ts +10 -0
  80. package/types/apps/src/facet.d.ts +5 -0
  81. package/types/apps/src/graphql.d.ts +10 -0
  82. package/types/apps/src/host.d.ts +16 -0
  83. package/types/apps/src/implementation/account-operations.d.ts +32 -0
  84. package/types/apps/src/implementation/app.d.ts +40 -0
  85. package/types/apps/src/implementation/authoring.d.ts +12 -0
  86. package/types/apps/src/implementation/elicitation.d.ts +103 -0
  87. package/types/apps/src/implementation/graphql.d.ts +5 -0
  88. package/types/apps/src/implementation/host.d.ts +3 -0
  89. package/types/apps/src/implementation/http.d.ts +5 -0
  90. package/types/apps/src/implementation/live.d.ts +18 -0
  91. package/types/apps/src/implementation/mcp-call.d.ts +19 -0
  92. package/types/apps/src/implementation/mcp-client.d.ts +50 -0
  93. package/types/apps/src/implementation/mcp-stdio.d.ts +4 -0
  94. package/types/apps/src/implementation/mcp-tools.d.ts +6 -0
  95. package/types/apps/src/implementation/mcp.d.ts +4 -0
  96. package/types/apps/src/implementation/openapi-request.d.ts +11 -0
  97. package/types/apps/src/implementation/openapi.d.ts +5 -0
  98. package/types/apps/src/implementation/operations.d.ts +65 -0
  99. package/types/apps/src/implementation/optimistic.d.ts +30 -0
  100. package/types/apps/src/implementation/protocol-operations.d.ts +24 -0
  101. package/types/apps/src/implementation/provider.d.ts +16 -0
  102. package/types/apps/src/implementation/query-commit.d.ts +10 -0
  103. package/types/apps/src/implementation/schedules.d.ts +16 -0
  104. package/types/apps/src/implementation/schema.d.ts +93 -0
  105. package/types/apps/src/implementation/storage.d.ts +13 -0
  106. package/types/apps/src/implementation/ui-auth.d.ts +13 -0
  107. package/types/apps/src/implementation/ui-client.d.ts +16 -0
  108. package/types/apps/src/implementation/ui-errors.d.ts +2 -0
  109. package/types/apps/src/implementation/ui-serving.d.ts +16 -0
  110. package/types/apps/src/implementation/ui-watch.d.ts +2 -0
  111. package/types/apps/src/implementation/webhooks.d.ts +29 -0
  112. package/types/apps/src/implementation/workflow-context.d.ts +8 -0
  113. package/types/apps/src/implementation/workflow-rpc.d.ts +5 -0
  114. package/types/apps/src/implementation/workflows.d.ts +27 -0
  115. package/types/apps/src/index.d.ts +58 -0
  116. package/types/apps/src/mcp-stdio.d.ts +8 -0
  117. package/types/apps/src/mcp.d.ts +10 -0
  118. package/types/apps/src/openapi.d.ts +10 -0
  119. package/types/apps/src/react.d.ts +7 -0
  120. package/types/apps/src/ui-auth.d.ts +3 -0
  121. package/types/apps/src/ui-serving.d.ts +3 -0
  122. package/types/telemetry/src/browser-operations.d.ts +16 -0
  123. package/types/telemetry/src/browser-performance.d.ts +11 -0
  124. package/types/telemetry/src/browser-request-timing.d.ts +2 -0
  125. package/types/telemetry/src/browser.d.ts +27 -0
  126. package/types/telemetry/src/config.d.ts +83 -0
  127. package/types/telemetry/src/context.d.ts +14 -0
  128. package/types/telemetry/src/index.d.ts +9 -0
  129. package/types/telemetry/src/layer.d.ts +7 -0
  130. package/types/telemetry/src/measurements.d.ts +8 -0
  131. package/types/telemetry/src/pending-span.d.ts +7 -0
  132. package/types/telemetry/src/relay.d.ts +28 -0
  133. package/types/telemetry/src/span-attributes.d.ts +29 -0
  134. package/types/telemetry/src/trace-context.d.ts +20 -0
  135. package/types/telemetry/src/transport.d.ts +6 -0
@@ -0,0 +1,2486 @@
1
+ import {
2
+ FetchHttpClient_exports
3
+ } from "./chunk-VFUZI3NY.js";
4
+ import {
5
+ HttpBody_exports,
6
+ HttpClient,
7
+ HttpClientError_exports,
8
+ HttpClientRequest_exports,
9
+ HttpClient_exports,
10
+ HttpServerResponse_exports,
11
+ HttpTraceContext_exports,
12
+ TracerPropagationEnabled,
13
+ filterStatusOk,
14
+ isHttpClientError,
15
+ jsonUnsafe,
16
+ post,
17
+ retryTransient,
18
+ setBody,
19
+ transformResponse,
20
+ uint8Array
21
+ } from "./chunk-W7Q5EOTS.js";
22
+ import {
23
+ Array as Array2,
24
+ Boolean2 as Boolean,
25
+ Clock,
26
+ Clock_exports,
27
+ Context_exports,
28
+ CurrentLogAnnotations,
29
+ CurrentLogSpans,
30
+ Effect_exports,
31
+ Exit_exports,
32
+ FiberSet_exports,
33
+ Headers_exports,
34
+ Int2 as Int,
35
+ Layer_exports,
36
+ Literals2 as Literals,
37
+ Logger_exports,
38
+ Metric_exports,
39
+ Option_exports,
40
+ Record2 as Record,
41
+ Redacted_exports,
42
+ Schema_exports,
43
+ Scope,
44
+ Semaphore_exports,
45
+ Service,
46
+ Stream_exports,
47
+ String as String2,
48
+ String2 as String3,
49
+ StringFromUriComponent,
50
+ Tracer,
51
+ Tracer_exports,
52
+ URL as URL2,
53
+ UndefinedOr,
54
+ addDelay,
55
+ addFinalizer,
56
+ all,
57
+ allocate,
58
+ andThen,
59
+ annotateLogs,
60
+ asVoid,
61
+ awaitEmpty,
62
+ await_,
63
+ catchCause,
64
+ context,
65
+ effect,
66
+ effectDiscard,
67
+ ensure,
68
+ firstSomeOf,
69
+ flatMap,
70
+ flatMap2,
71
+ flow,
72
+ fnUntraced,
73
+ forEach,
74
+ forever,
75
+ forever2,
76
+ forkIn,
77
+ format,
78
+ fromInput2 as fromInput,
79
+ fromInputUnsafe,
80
+ fromRecordUnsafe,
81
+ fromUndefinedOr,
82
+ gen,
83
+ get,
84
+ getOrUndefined,
85
+ hasInterruptsOnly,
86
+ identity,
87
+ ignore,
88
+ interruptible,
89
+ isSome,
90
+ layer,
91
+ logDebug,
92
+ make2 as make,
93
+ make7 as make2,
94
+ make8 as make3,
95
+ map,
96
+ map3 as map2,
97
+ map5 as map3,
98
+ max,
99
+ merge3 as merge,
100
+ millis,
101
+ option,
102
+ orDie,
103
+ orElse,
104
+ parse,
105
+ passthrough,
106
+ pretty,
107
+ prettyErrors,
108
+ provideMerge,
109
+ provideService,
110
+ randomHex,
111
+ run2 as run,
112
+ runtime,
113
+ schema,
114
+ seconds,
115
+ sleep,
116
+ snapshotUnsafe,
117
+ succeed3 as succeed,
118
+ succeed4 as succeed2,
119
+ suspend,
120
+ sync,
121
+ sync2,
122
+ timeoutOption,
123
+ unwrap,
124
+ void_2 as void_,
125
+ withDefault2 as withDefault,
126
+ withTracerEnabled,
127
+ zero
128
+ } from "./chunk-2OTCEKL2.js";
129
+ import {
130
+ __export
131
+ } from "./chunk-MLKGABMK.js";
132
+
133
+ // ../telemetry/src/context.ts
134
+ var captureTelemetry = Effect_exports.gen(function* () {
135
+ let context2 = Context_exports.make(Tracer_exports.Tracer, yield* Tracer_exports.Tracer).pipe(
136
+ Context_exports.add(Logger_exports.CurrentLoggers, yield* Logger_exports.CurrentLoggers),
137
+ Context_exports.add(Metric_exports.MetricRegistry, yield* Metric_exports.MetricRegistry)
138
+ );
139
+ const span = yield* Effect_exports.currentSpan.pipe(Effect_exports.option);
140
+ if (Option_exports.isSome(span)) context2 = Context_exports.add(context2, Tracer_exports.ParentSpan, span.value);
141
+ return { context: context2 };
142
+ });
143
+ var traceHeaders = Effect_exports.currentSpan.pipe(
144
+ Effect_exports.map(HttpTraceContext_exports.toHeaders),
145
+ Effect_exports.orElseSucceed(() => ({}))
146
+ );
147
+ var withRemoteSpan = (request, name) => (effect2) => effect2.pipe(
148
+ Effect_exports.withSpan(name, {
149
+ kind: "server",
150
+ parent: Option_exports.getOrUndefined(
151
+ HttpTraceContext_exports.fromHeaders(
152
+ Headers_exports.fromInput({ traceparent: request.headers.get("traceparent") ?? void 0 })
153
+ )
154
+ )
155
+ })
156
+ );
157
+ var invocationFetch = (signal) => Effect_exports.gen(function* () {
158
+ const { context: context2 } = yield* captureTelemetry;
159
+ return (input, init) => Effect_exports.runPromiseWith(context2)(
160
+ Effect_exports.gen(function* () {
161
+ const request = yield* Effect_exports.try(() => new Request(input, init));
162
+ const client = yield* HttpClient_exports.HttpClient;
163
+ const response = yield* client.execute(HttpClientRequest_exports.fromWeb(request)).pipe(
164
+ Effect_exports.withSpan("provider.http.request", {
165
+ attributes: { "http.request.method": request.method }
166
+ }),
167
+ Effect_exports.provideService(FetchHttpClient_exports.RequestInit, {
168
+ cache: request.cache,
169
+ credentials: request.credentials,
170
+ integrity: request.integrity,
171
+ keepalive: request.keepalive,
172
+ mode: request.mode,
173
+ redirect: request.redirect,
174
+ referrer: request.referrer,
175
+ referrerPolicy: request.referrerPolicy
176
+ }),
177
+ Effect_exports.provideService(
178
+ FetchHttpClient_exports.Fetch,
179
+ (url, options) => globalThis.fetch(url, {
180
+ ...options,
181
+ signal: AbortSignal.any([
182
+ signal,
183
+ request.signal,
184
+ ...options?.signal ? [options.signal] : []
185
+ ])
186
+ })
187
+ )
188
+ );
189
+ const streamed = HttpServerResponse_exports.fromClientResponse(response);
190
+ const body = streamed.body;
191
+ const traced = body instanceof HttpBody_exports.Stream ? HttpServerResponse_exports.setBody(
192
+ streamed,
193
+ HttpBody_exports.stream(
194
+ body.stream.pipe(
195
+ Stream_exports.withSpan("provider.http.response.read", {
196
+ attributes: { "http.response.status_code": response.status }
197
+ })
198
+ ),
199
+ body.contentType,
200
+ body.contentLength
201
+ )
202
+ ) : streamed;
203
+ return HttpServerResponse_exports.toWeb(traced, {
204
+ withoutBody: request.method === "HEAD",
205
+ context: context2
206
+ });
207
+ }).pipe(Effect_exports.provide(FetchHttpClient_exports.layer)),
208
+ { signal }
209
+ );
210
+ });
211
+
212
+ // ../telemetry/src/config.ts
213
+ var Endpoint = Schema_exports.String.check(
214
+ Schema_exports.makeFilter(
215
+ (value) => {
216
+ const url = URL.parse(value);
217
+ return url !== null && ["http:", "https:"].includes(url.protocol) && url.username === "" && url.password === "";
218
+ },
219
+ { message: "Expected an HTTP telemetry endpoint without URL credentials" }
220
+ )
221
+ );
222
+ var TelemetryTarget = Schema_exports.Struct({
223
+ url: Endpoint,
224
+ headers: Schema_exports.optional(Schema_exports.RedactedFromValue(Schema_exports.Record(Schema_exports.String, Schema_exports.String)))
225
+ });
226
+ var TelemetryConfig = Schema_exports.Struct({
227
+ service: Schema_exports.NonEmptyString,
228
+ version: Schema_exports.NonEmptyString,
229
+ environment: Schema_exports.NonEmptyString,
230
+ clock: Schema_exports.optional(Schema_exports.Literals(["system", "cloudflare-io"])),
231
+ traces: Schema_exports.optional(TelemetryTarget),
232
+ logs: Schema_exports.optional(TelemetryTarget),
233
+ metrics: Schema_exports.optional(TelemetryTarget),
234
+ metricsProtocol: Schema_exports.optional(Schema_exports.Literals(["http/json", "http/protobuf"]))
235
+ });
236
+ var CurrentTelemetryConfig = Context_exports.Reference(
237
+ "executor/TelemetryConfig",
238
+ { defaultValue: () => void 0 }
239
+ );
240
+
241
+ // ../../node_modules/.bun/@bufbuild+protobuf@2.11.0/node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js
242
+ function varint64read() {
243
+ let lowBits = 0;
244
+ let highBits = 0;
245
+ for (let shift = 0; shift < 28; shift += 7) {
246
+ let b = this.buf[this.pos++];
247
+ lowBits |= (b & 127) << shift;
248
+ if ((b & 128) == 0) {
249
+ this.assertBounds();
250
+ return [lowBits, highBits];
251
+ }
252
+ }
253
+ let middleByte = this.buf[this.pos++];
254
+ lowBits |= (middleByte & 15) << 28;
255
+ highBits = (middleByte & 112) >> 4;
256
+ if ((middleByte & 128) == 0) {
257
+ this.assertBounds();
258
+ return [lowBits, highBits];
259
+ }
260
+ for (let shift = 3; shift <= 31; shift += 7) {
261
+ let b = this.buf[this.pos++];
262
+ highBits |= (b & 127) << shift;
263
+ if ((b & 128) == 0) {
264
+ this.assertBounds();
265
+ return [lowBits, highBits];
266
+ }
267
+ }
268
+ throw new Error("invalid varint");
269
+ }
270
+ var TWO_PWR_32_DBL = 4294967296;
271
+ function int64FromString(dec) {
272
+ const minus = dec[0] === "-";
273
+ if (minus) {
274
+ dec = dec.slice(1);
275
+ }
276
+ const base = 1e6;
277
+ let lowBits = 0;
278
+ let highBits = 0;
279
+ function add1e6digit(begin, end) {
280
+ const digit1e6 = Number(dec.slice(begin, end));
281
+ highBits *= base;
282
+ lowBits = lowBits * base + digit1e6;
283
+ if (lowBits >= TWO_PWR_32_DBL) {
284
+ highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0);
285
+ lowBits = lowBits % TWO_PWR_32_DBL;
286
+ }
287
+ }
288
+ add1e6digit(-24, -18);
289
+ add1e6digit(-18, -12);
290
+ add1e6digit(-12, -6);
291
+ add1e6digit(-6);
292
+ return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);
293
+ }
294
+ function int64ToString(lo, hi) {
295
+ let bits = newBits(lo, hi);
296
+ const negative = bits.hi & 2147483648;
297
+ if (negative) {
298
+ bits = negate(bits.lo, bits.hi);
299
+ }
300
+ const result = uInt64ToString(bits.lo, bits.hi);
301
+ return negative ? "-" + result : result;
302
+ }
303
+ function uInt64ToString(lo, hi) {
304
+ ({ lo, hi } = toUnsigned(lo, hi));
305
+ if (hi <= 2097151) {
306
+ return String(TWO_PWR_32_DBL * hi + lo);
307
+ }
308
+ const low = lo & 16777215;
309
+ const mid = (lo >>> 24 | hi << 8) & 16777215;
310
+ const high = hi >> 16 & 65535;
311
+ let digitA = low + mid * 6777216 + high * 6710656;
312
+ let digitB = mid + high * 8147497;
313
+ let digitC = high * 2;
314
+ const base = 1e7;
315
+ if (digitA >= base) {
316
+ digitB += Math.floor(digitA / base);
317
+ digitA %= base;
318
+ }
319
+ if (digitB >= base) {
320
+ digitC += Math.floor(digitB / base);
321
+ digitB %= base;
322
+ }
323
+ return digitC.toString() + decimalFrom1e7WithLeadingZeros(digitB) + decimalFrom1e7WithLeadingZeros(digitA);
324
+ }
325
+ function toUnsigned(lo, hi) {
326
+ return { lo: lo >>> 0, hi: hi >>> 0 };
327
+ }
328
+ function newBits(lo, hi) {
329
+ return { lo: lo | 0, hi: hi | 0 };
330
+ }
331
+ function negate(lowBits, highBits) {
332
+ highBits = ~highBits;
333
+ if (lowBits) {
334
+ lowBits = ~lowBits + 1;
335
+ } else {
336
+ highBits += 1;
337
+ }
338
+ return newBits(lowBits, highBits);
339
+ }
340
+ var decimalFrom1e7WithLeadingZeros = (digit1e7) => {
341
+ const partial = String(digit1e7);
342
+ return "0000000".slice(partial.length) + partial;
343
+ };
344
+ function varint32read() {
345
+ let b = this.buf[this.pos++];
346
+ let result = b & 127;
347
+ if ((b & 128) == 0) {
348
+ this.assertBounds();
349
+ return result;
350
+ }
351
+ b = this.buf[this.pos++];
352
+ result |= (b & 127) << 7;
353
+ if ((b & 128) == 0) {
354
+ this.assertBounds();
355
+ return result;
356
+ }
357
+ b = this.buf[this.pos++];
358
+ result |= (b & 127) << 14;
359
+ if ((b & 128) == 0) {
360
+ this.assertBounds();
361
+ return result;
362
+ }
363
+ b = this.buf[this.pos++];
364
+ result |= (b & 127) << 21;
365
+ if ((b & 128) == 0) {
366
+ this.assertBounds();
367
+ return result;
368
+ }
369
+ b = this.buf[this.pos++];
370
+ result |= (b & 15) << 28;
371
+ for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++)
372
+ b = this.buf[this.pos++];
373
+ if ((b & 128) != 0)
374
+ throw new Error("invalid varint");
375
+ this.assertBounds();
376
+ return result >>> 0;
377
+ }
378
+
379
+ // ../../node_modules/.bun/@bufbuild+protobuf@2.11.0/node_modules/@bufbuild/protobuf/dist/esm/proto-int64.js
380
+ var protoInt64 = /* @__PURE__ */ makeInt64Support();
381
+ function makeInt64Support() {
382
+ const dv = new DataView(new ArrayBuffer(8));
383
+ const ok = typeof BigInt === "function" && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function" && (!!globalThis.Deno || typeof process != "object" || typeof process.env != "object" || process.env.BUF_BIGINT_DISABLE !== "1");
384
+ if (ok) {
385
+ const MIN = BigInt("-9223372036854775808");
386
+ const MAX = BigInt("9223372036854775807");
387
+ const UMIN = BigInt("0");
388
+ const UMAX = BigInt("18446744073709551615");
389
+ return {
390
+ zero: BigInt(0),
391
+ supported: true,
392
+ parse(value) {
393
+ const bi = typeof value == "bigint" ? value : BigInt(value);
394
+ if (bi > MAX || bi < MIN) {
395
+ throw new Error(`invalid int64: ${value}`);
396
+ }
397
+ return bi;
398
+ },
399
+ uParse(value) {
400
+ const bi = typeof value == "bigint" ? value : BigInt(value);
401
+ if (bi > UMAX || bi < UMIN) {
402
+ throw new Error(`invalid uint64: ${value}`);
403
+ }
404
+ return bi;
405
+ },
406
+ enc(value) {
407
+ dv.setBigInt64(0, this.parse(value), true);
408
+ return {
409
+ lo: dv.getInt32(0, true),
410
+ hi: dv.getInt32(4, true)
411
+ };
412
+ },
413
+ uEnc(value) {
414
+ dv.setBigInt64(0, this.uParse(value), true);
415
+ return {
416
+ lo: dv.getInt32(0, true),
417
+ hi: dv.getInt32(4, true)
418
+ };
419
+ },
420
+ dec(lo, hi) {
421
+ dv.setInt32(0, lo, true);
422
+ dv.setInt32(4, hi, true);
423
+ return dv.getBigInt64(0, true);
424
+ },
425
+ uDec(lo, hi) {
426
+ dv.setInt32(0, lo, true);
427
+ dv.setInt32(4, hi, true);
428
+ return dv.getBigUint64(0, true);
429
+ }
430
+ };
431
+ }
432
+ return {
433
+ zero: "0",
434
+ supported: false,
435
+ parse(value) {
436
+ if (typeof value != "string") {
437
+ value = value.toString();
438
+ }
439
+ assertInt64String(value);
440
+ return value;
441
+ },
442
+ uParse(value) {
443
+ if (typeof value != "string") {
444
+ value = value.toString();
445
+ }
446
+ assertUInt64String(value);
447
+ return value;
448
+ },
449
+ enc(value) {
450
+ if (typeof value != "string") {
451
+ value = value.toString();
452
+ }
453
+ assertInt64String(value);
454
+ return int64FromString(value);
455
+ },
456
+ uEnc(value) {
457
+ if (typeof value != "string") {
458
+ value = value.toString();
459
+ }
460
+ assertUInt64String(value);
461
+ return int64FromString(value);
462
+ },
463
+ dec(lo, hi) {
464
+ return int64ToString(lo, hi);
465
+ },
466
+ uDec(lo, hi) {
467
+ return uInt64ToString(lo, hi);
468
+ }
469
+ };
470
+ }
471
+ function assertInt64String(value) {
472
+ if (!/^-?[0-9]+$/.test(value)) {
473
+ throw new Error("invalid int64: " + value);
474
+ }
475
+ }
476
+ function assertUInt64String(value) {
477
+ if (!/^[0-9]+$/.test(value)) {
478
+ throw new Error("invalid uint64: " + value);
479
+ }
480
+ }
481
+
482
+ // ../../node_modules/.bun/@bufbuild+protobuf@2.11.0/node_modules/@bufbuild/protobuf/dist/esm/wire/text-encoding.js
483
+ var symbol = /* @__PURE__ */ Symbol.for("@bufbuild/protobuf/text-encoding");
484
+ function getTextEncoding() {
485
+ if (globalThis[symbol] == void 0) {
486
+ const te = new globalThis.TextEncoder();
487
+ const td = new globalThis.TextDecoder();
488
+ globalThis[symbol] = {
489
+ encodeUtf8(text) {
490
+ return te.encode(text);
491
+ },
492
+ decodeUtf8(bytes) {
493
+ return td.decode(bytes);
494
+ },
495
+ checkUtf8(text) {
496
+ try {
497
+ encodeURIComponent(text);
498
+ return true;
499
+ } catch (_) {
500
+ return false;
501
+ }
502
+ }
503
+ };
504
+ }
505
+ return globalThis[symbol];
506
+ }
507
+
508
+ // ../../node_modules/.bun/@bufbuild+protobuf@2.11.0/node_modules/@bufbuild/protobuf/dist/esm/wire/binary-encoding.js
509
+ var WireType;
510
+ (function(WireType3) {
511
+ WireType3[WireType3["Varint"] = 0] = "Varint";
512
+ WireType3[WireType3["Bit64"] = 1] = "Bit64";
513
+ WireType3[WireType3["LengthDelimited"] = 2] = "LengthDelimited";
514
+ WireType3[WireType3["StartGroup"] = 3] = "StartGroup";
515
+ WireType3[WireType3["EndGroup"] = 4] = "EndGroup";
516
+ WireType3[WireType3["Bit32"] = 5] = "Bit32";
517
+ })(WireType || (WireType = {}));
518
+ var BinaryReader = class {
519
+ constructor(buf, decodeUtf8 = getTextEncoding().decodeUtf8) {
520
+ this.decodeUtf8 = decodeUtf8;
521
+ this.varint64 = varint64read;
522
+ this.uint32 = varint32read;
523
+ this.buf = buf;
524
+ this.len = buf.length;
525
+ this.pos = 0;
526
+ this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
527
+ }
528
+ /**
529
+ * Reads a tag - field number and wire type.
530
+ */
531
+ tag() {
532
+ let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
533
+ if (fieldNo <= 0 || wireType < 0 || wireType > 5)
534
+ throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
535
+ return [fieldNo, wireType];
536
+ }
537
+ /**
538
+ * Skip one element and return the skipped data.
539
+ *
540
+ * When skipping StartGroup, provide the tags field number to check for
541
+ * matching field number in the EndGroup tag.
542
+ */
543
+ skip(wireType, fieldNo) {
544
+ let start = this.pos;
545
+ switch (wireType) {
546
+ case WireType.Varint:
547
+ while (this.buf[this.pos++] & 128) {
548
+ }
549
+ break;
550
+ // @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
551
+ case WireType.Bit64:
552
+ this.pos += 4;
553
+ case WireType.Bit32:
554
+ this.pos += 4;
555
+ break;
556
+ case WireType.LengthDelimited:
557
+ let len = this.uint32();
558
+ this.pos += len;
559
+ break;
560
+ case WireType.StartGroup:
561
+ for (; ; ) {
562
+ const [fn, wt] = this.tag();
563
+ if (wt === WireType.EndGroup) {
564
+ if (fieldNo !== void 0 && fn !== fieldNo) {
565
+ throw new Error("invalid end group tag");
566
+ }
567
+ break;
568
+ }
569
+ this.skip(wt, fn);
570
+ }
571
+ break;
572
+ default:
573
+ throw new Error("cant skip wire type " + wireType);
574
+ }
575
+ this.assertBounds();
576
+ return this.buf.subarray(start, this.pos);
577
+ }
578
+ /**
579
+ * Throws error if position in byte array is out of range.
580
+ */
581
+ assertBounds() {
582
+ if (this.pos > this.len)
583
+ throw new RangeError("premature EOF");
584
+ }
585
+ /**
586
+ * Read a `int32` field, a signed 32 bit varint.
587
+ */
588
+ int32() {
589
+ return this.uint32() | 0;
590
+ }
591
+ /**
592
+ * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
593
+ */
594
+ sint32() {
595
+ let zze = this.uint32();
596
+ return zze >>> 1 ^ -(zze & 1);
597
+ }
598
+ /**
599
+ * Read a `int64` field, a signed 64-bit varint.
600
+ */
601
+ int64() {
602
+ return protoInt64.dec(...this.varint64());
603
+ }
604
+ /**
605
+ * Read a `uint64` field, an unsigned 64-bit varint.
606
+ */
607
+ uint64() {
608
+ return protoInt64.uDec(...this.varint64());
609
+ }
610
+ /**
611
+ * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
612
+ */
613
+ sint64() {
614
+ let [lo, hi] = this.varint64();
615
+ let s = -(lo & 1);
616
+ lo = (lo >>> 1 | (hi & 1) << 31) ^ s;
617
+ hi = hi >>> 1 ^ s;
618
+ return protoInt64.dec(lo, hi);
619
+ }
620
+ /**
621
+ * Read a `bool` field, a variant.
622
+ */
623
+ bool() {
624
+ let [lo, hi] = this.varint64();
625
+ return lo !== 0 || hi !== 0;
626
+ }
627
+ /**
628
+ * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
629
+ */
630
+ fixed32() {
631
+ return this.view.getUint32((this.pos += 4) - 4, true);
632
+ }
633
+ /**
634
+ * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
635
+ */
636
+ sfixed32() {
637
+ return this.view.getInt32((this.pos += 4) - 4, true);
638
+ }
639
+ /**
640
+ * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
641
+ */
642
+ fixed64() {
643
+ return protoInt64.uDec(this.sfixed32(), this.sfixed32());
644
+ }
645
+ /**
646
+ * Read a `fixed64` field, a signed, fixed-length 64-bit integer.
647
+ */
648
+ sfixed64() {
649
+ return protoInt64.dec(this.sfixed32(), this.sfixed32());
650
+ }
651
+ /**
652
+ * Read a `float` field, 32-bit floating point number.
653
+ */
654
+ float() {
655
+ return this.view.getFloat32((this.pos += 4) - 4, true);
656
+ }
657
+ /**
658
+ * Read a `double` field, a 64-bit floating point number.
659
+ */
660
+ double() {
661
+ return this.view.getFloat64((this.pos += 8) - 8, true);
662
+ }
663
+ /**
664
+ * Read a `bytes` field, length-delimited arbitrary data.
665
+ */
666
+ bytes() {
667
+ let len = this.uint32(), start = this.pos;
668
+ this.pos += len;
669
+ this.assertBounds();
670
+ return this.buf.subarray(start, start + len);
671
+ }
672
+ /**
673
+ * Read a `string` field, length-delimited data converted to UTF-8 text.
674
+ */
675
+ string() {
676
+ return this.decodeUtf8(this.bytes());
677
+ }
678
+ };
679
+
680
+ // ../telemetry/src/measurements.ts
681
+ var boundaries = [1, 5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4, 3e4];
682
+ var responseReady = Metric_exports.histogram("executor.http.response_ready_ms", {
683
+ boundaries,
684
+ attributes: { unit: "ms" },
685
+ description: "Handler entry to response headers in milliseconds; excludes streamed body lifetime."
686
+ });
687
+ var requests = Metric_exports.counter("executor.http.requests", { incremental: true });
688
+ var exportFailures = Metric_exports.counter("executor.telemetry.export_failures", { incremental: true });
689
+ var rejectedRecords = Metric_exports.counter("executor.telemetry.rejected_records", {
690
+ incremental: true
691
+ });
692
+ var workerCpu = Metric_exports.histogram("executor.worker.cpu_ms", {
693
+ boundaries,
694
+ attributes: { unit: "ms" },
695
+ description: "Native Worker CPU time in milliseconds."
696
+ });
697
+ var workerWall = Metric_exports.histogram("executor.worker.wall_ms", {
698
+ boundaries,
699
+ attributes: { unit: "ms" },
700
+ description: "Native Worker invocation wall time, including stream and cleanup lifetime, in milliseconds."
701
+ });
702
+ var recordExportFailure = (path, reason = "transport", records = 0) => {
703
+ const signal = path.endsWith("/traces") ? "traces" : path.endsWith("/logs") ? "logs" : path.endsWith("/metrics") ? "metrics" : "other";
704
+ return Metric_exports.update(Metric_exports.withAttributes(exportFailures, { signal, reason }), 1).pipe(
705
+ Effect_exports.andThen(
706
+ Metric_exports.update(Metric_exports.withAttributes(rejectedRecords, { signal, reason }), records)
707
+ ),
708
+ Effect_exports.andThen(
709
+ Effect_exports.logWarning("Telemetry export failed").pipe(
710
+ Effect_exports.annotateLogs({
711
+ "executor.telemetry.signal": signal,
712
+ "executor.telemetry.failure": reason,
713
+ "executor.telemetry.rejected_records": records
714
+ })
715
+ )
716
+ )
717
+ );
718
+ };
719
+
720
+ // ../telemetry/src/transport.ts
721
+ var CurrentTelemetryClient = Context_exports.Reference(
722
+ "executor/TelemetryClient",
723
+ { defaultValue: () => void 0 }
724
+ );
725
+ var selectedClient = Layer_exports.unwrap(
726
+ CurrentTelemetryClient.pipe(
727
+ Effect_exports.map(
728
+ (client) => client === void 0 ? FetchHttpClient_exports.layer : Layer_exports.succeed(HttpClient_exports.HttpClient, client)
729
+ )
730
+ )
731
+ );
732
+ var Count = Schema_exports.Union([Schema_exports.Number, Schema_exports.NumberFromString]).check(
733
+ Schema_exports.isInt(),
734
+ Schema_exports.isGreaterThanOrEqualTo(0),
735
+ Schema_exports.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)
736
+ );
737
+ var Acknowledgement = Schema_exports.Struct({
738
+ partialSuccess: Schema_exports.optional(
739
+ Schema_exports.Struct({
740
+ rejectedSpans: Schema_exports.optional(Count),
741
+ rejectedLogRecords: Schema_exports.optional(Count),
742
+ rejectedDataPoints: Schema_exports.optional(Count),
743
+ errorMessage: Schema_exports.optional(Schema_exports.String)
744
+ })
745
+ )
746
+ });
747
+ var protobufAcknowledgement = (bytes) => {
748
+ const reader = new BinaryReader(bytes);
749
+ let rejected = "0";
750
+ let message = "";
751
+ while (reader.pos < reader.len) {
752
+ const [field, wire] = reader.tag();
753
+ if (field !== 1 || wire !== WireType.LengthDelimited) {
754
+ reader.skip(wire, field);
755
+ continue;
756
+ }
757
+ const partial = new BinaryReader(reader.bytes());
758
+ while (partial.pos < partial.len) {
759
+ const [field2, wire2] = partial.tag();
760
+ if (field2 === 1 && wire2 === WireType.Varint) rejected = String(partial.int64());
761
+ else if (field2 === 2 && wire2 === WireType.LengthDelimited) message = partial.string();
762
+ else partial.skip(wire2, field2);
763
+ }
764
+ }
765
+ return { partialSuccess: { rejectedDataPoints: rejected, errorMessage: message } };
766
+ };
767
+ var acknowledge = (response) => Effect_exports.gen(function* () {
768
+ const bytes = new Uint8Array(yield* response.arrayBuffer);
769
+ const decoded = yield* Effect_exports.try({
770
+ try: () => {
771
+ if (bytes.byteLength === 0) return {};
772
+ if (response.headers["content-type"]?.includes("application/x-protobuf")) {
773
+ return protobufAcknowledgement(bytes);
774
+ }
775
+ return JSON.parse(new TextDecoder().decode(bytes));
776
+ },
777
+ catch: () => new HttpClientError_exports.HttpClientError({
778
+ reason: new HttpClientError_exports.DecodeError({
779
+ request: response.request,
780
+ response,
781
+ description: "Invalid OTLP acknowledgement"
782
+ })
783
+ })
784
+ });
785
+ const acknowledgement = yield* Schema_exports.decodeUnknownEffect(Acknowledgement)(decoded).pipe(
786
+ Effect_exports.mapError(
787
+ () => new HttpClientError_exports.HttpClientError({
788
+ reason: new HttpClientError_exports.DecodeError({
789
+ request: response.request,
790
+ response,
791
+ description: "Invalid OTLP acknowledgement"
792
+ })
793
+ })
794
+ )
795
+ );
796
+ const partial = acknowledgement.partialSuccess;
797
+ if (partial === void 0) return;
798
+ const rejected = (partial.rejectedSpans ?? 0) + (partial.rejectedLogRecords ?? 0) + (partial.rejectedDataPoints ?? 0);
799
+ if (rejected > 0 || partial.errorMessage)
800
+ yield* recordExportFailure(
801
+ new URL(response.request.url).pathname,
802
+ "partial-success",
803
+ rejected
804
+ );
805
+ });
806
+ var telemetryHttpClient = Layer_exports.effect(
807
+ HttpClient_exports.HttpClient,
808
+ HttpClient_exports.HttpClient.pipe(
809
+ Effect_exports.map(
810
+ (client) => client.pipe(
811
+ HttpClient_exports.filterStatusOk,
812
+ HttpClient_exports.transform(
813
+ (response, request) => response.pipe(
814
+ Effect_exports.tap(acknowledge),
815
+ Effect_exports.tapError(
816
+ (error) => recordExportFailure(
817
+ new URL(request.url).pathname,
818
+ HttpClientError_exports.isHttpClientError(error) && error.reason instanceof HttpClientError_exports.DecodeError ? "acknowledgement" : "transport"
819
+ )
820
+ ),
821
+ Effect_exports.onInterrupt(
822
+ () => recordExportFailure(new URL(request.url).pathname, "interrupted")
823
+ )
824
+ )
825
+ ),
826
+ HttpClient_exports.withScope,
827
+ HttpClient_exports.transformResponse(Effect_exports.scoped)
828
+ )
829
+ )
830
+ )
831
+ ).pipe(Layer_exports.provide(selectedClient));
832
+
833
+ // ../telemetry/src/span-attributes.ts
834
+ var LogicalOperationFailed = class extends Schema_exports.TaggedError()(
835
+ "LogicalOperationFailed",
836
+ {}
837
+ ) {
838
+ };
839
+ var httpNamespaces = ["http.", "url.", "server.", "client.", "user_agent."];
840
+ var httpSpanAttributeAllowlist = /* @__PURE__ */ new Set([
841
+ "http.request.method",
842
+ "http.response.status_code",
843
+ "server.address",
844
+ "url.scheme",
845
+ // Path only. `url.full` and `url.query` carry the query string, so neither is listed.
846
+ "url.path",
847
+ "http.request.header.content-type",
848
+ "http.request.header.content-length",
849
+ "http.request.header.user-agent",
850
+ "http.response.header.content-type",
851
+ "http.response.header.content-length",
852
+ // The server tracer records the user agent a second time under its own name.
853
+ "user_agent.original"
854
+ ]);
855
+ var spanAttributeAllowed = (key) => {
856
+ const name = key.toLowerCase();
857
+ return !httpNamespaces.some((namespace) => name.startsWith(namespace)) || httpSpanAttributeAllowlist.has(name);
858
+ };
859
+ var allowedEntries = (attributes) => Object.fromEntries(Object.entries(attributes).filter(([key]) => spanAttributeAllowed(key)));
860
+ var allowlistedSpan = (span) => ({
861
+ _tag: "Span",
862
+ get name() {
863
+ return span.name;
864
+ },
865
+ get spanId() {
866
+ return span.spanId;
867
+ },
868
+ get traceId() {
869
+ return span.traceId;
870
+ },
871
+ get parent() {
872
+ return span.parent;
873
+ },
874
+ get annotations() {
875
+ return span.annotations;
876
+ },
877
+ get status() {
878
+ return span.status;
879
+ },
880
+ get attributes() {
881
+ return span.attributes;
882
+ },
883
+ get links() {
884
+ return span.links;
885
+ },
886
+ get sampled() {
887
+ return span.sampled;
888
+ },
889
+ get kind() {
890
+ return span.kind;
891
+ },
892
+ // A successful transport can carry a failed domain operation. The producer
893
+ // explicitly marks that outcome; arbitrary result payloads are never inspected.
894
+ end: (endTime, exit) => span.end(
895
+ endTime,
896
+ Exit_exports.isSuccess(exit) && span.attributes.get("executor.outcome") === "failed" ? Exit_exports.fail(new LogicalOperationFailed()) : exit
897
+ ),
898
+ attribute: (key, value) => {
899
+ if (spanAttributeAllowed(key)) span.attribute(key, value);
900
+ },
901
+ event: (name, startTime, attributes) => span.event(name, startTime, attributes === void 0 ? void 0 : allowedEntries(attributes)),
902
+ addLinks: (links) => span.addLinks(links)
903
+ });
904
+ var spanAttributes = (clock, recordAll = false) => Layer_exports.effect(Tracer_exports.Tracer)(
905
+ Tracer_exports.Tracer.pipe(
906
+ Effect_exports.map((tracer) => ({
907
+ ...tracer,
908
+ span: (options) => {
909
+ const span = allowlistedSpan(
910
+ tracer.span(recordAll ? { ...options, sampled: true } : options)
911
+ );
912
+ if (recordAll && Option_exports.isSome(options.parent) && options.parent.value._tag === "ExternalSpan")
913
+ span.attribute("executor.trace.parent_sampled", options.parent.value.sampled);
914
+ if (clock !== void 0) span.attribute("executor.clock.type", clock);
915
+ return span;
916
+ }
917
+ }))
918
+ )
919
+ );
920
+ var allowlistedSpans = spanAttributes();
921
+
922
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpLogger.js
923
+ var OtlpLogger_exports = {};
924
+ __export(OtlpLogger_exports, {
925
+ layer: () => layer2,
926
+ layerFromConfig: () => layerFromConfig,
927
+ make: () => make6
928
+ });
929
+
930
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/internal/otlpEnv.js
931
+ var exporterList = (path) => Array2(String2, path).pipe(map3((_) => _.map((_2) => _2.toLowerCase().trim()).filter((_2) => _2 !== "")));
932
+ var headersRecord = (path) => Record(String2, StringFromUriComponent, path);
933
+ var headers = (signal) => headersRecord(`OTEL_EXPORTER_OTLP_${signal}_HEADERS`).pipe(orElse(() => headersRecord("OTEL_EXPORTER_OTLP_HEADERS")), withDefault(void 0));
934
+ var endpoint = (signal) => URL2(`OTEL_EXPORTER_OTLP_${signal}_ENDPOINT`).pipe(orElse(() => URL2("OTEL_EXPORTER_OTLP_ENDPOINT").pipe(map3((url) => {
935
+ const slash = url.pathname.endsWith("/") ? "" : "/";
936
+ url.pathname += `${slash}v1/${signal.toLowerCase()}`;
937
+ return url;
938
+ }))), withDefault(void 0));
939
+ var exporters = (signal) => exporterList(`OTEL_${signal}_EXPORTER`).pipe(withDefault([]));
940
+
941
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpExporter.js
942
+ var OtlpExporter_exports = {};
943
+ __export(OtlpExporter_exports, {
944
+ Flusher: () => Flusher,
945
+ layerFlusher: () => layerFlusher,
946
+ make: () => make4
947
+ });
948
+ var retryAfterDelay = (value) => {
949
+ const seconds2 = fromUndefinedOr(value).pipe(flatMap(parse));
950
+ if (isSome(seconds2)) {
951
+ return succeed2(seconds(seconds2.value));
952
+ }
953
+ if (value === void 0) {
954
+ return succeed2(seconds(5));
955
+ }
956
+ const timestamp = Date.parse(value);
957
+ if (Number.isNaN(timestamp)) {
958
+ return succeed2(seconds(5));
959
+ }
960
+ return map2(Clock, (clock) => millis(Math.max(timestamp - clock.currentTimeMillisUnsafe(), 1)));
961
+ };
962
+ var policy = /* @__PURE__ */ forever.pipe(passthrough, /* @__PURE__ */ addDelay(({
963
+ output: error
964
+ }) => {
965
+ if (isHttpClientError(error) && error.reason._tag === "StatusCodeError" && error.reason.response.status === 429) {
966
+ return retryAfterDelay(error.reason.response.headers["retry-after"]);
967
+ }
968
+ return succeed2(seconds(1));
969
+ }));
970
+ var Flusher = class extends (/* @__PURE__ */ Service()("effect/observability/OtlpExporter/Flusher")) {
971
+ };
972
+ var layerFlusher = /* @__PURE__ */ sync(Flusher, () => {
973
+ const registry = /* @__PURE__ */ new Set();
974
+ return {
975
+ flush: suspend(() => {
976
+ if (registry.size === 0) {
977
+ return void_;
978
+ }
979
+ return forEach(registry, identity, {
980
+ concurrency: "unbounded",
981
+ discard: true
982
+ });
983
+ }),
984
+ register: (run2) => flatMap2(Scope, (scope) => {
985
+ registry.add(run2);
986
+ return addFinalizer(scope, sync2(() => registry.delete(run2)));
987
+ })
988
+ };
989
+ });
990
+ var make4 = /* @__PURE__ */ fnUntraced(function* (options) {
991
+ const services = yield* context();
992
+ const clock = get(services, Clock);
993
+ const scope = get(services, Scope);
994
+ const exportInterval = max(fromInputUnsafe(options.exportInterval), zero);
995
+ let disabledUntil = void 0;
996
+ const client = filterStatusOk(get(services, HttpClient)).pipe(transformResponse(provideService(TracerPropagationEnabled, false)), retryTransient({
997
+ schedule: policy,
998
+ times: 3
999
+ }));
1000
+ let headers2 = fromRecordUnsafe({
1001
+ "user-agent": `effect-opentelemetry-${options.label}/0.0.0`
1002
+ });
1003
+ if (options.headers) {
1004
+ headers2 = merge(fromInput(options.headers), headers2);
1005
+ }
1006
+ const request = post(options.url, {
1007
+ headers: headers2
1008
+ });
1009
+ let buffer = [];
1010
+ const runExport = suspend(() => {
1011
+ if (disabledUntil !== void 0 && clock.currentTimeMillisUnsafe() < disabledUntil) {
1012
+ return void_;
1013
+ } else if (disabledUntil !== void 0) {
1014
+ disabledUntil = void 0;
1015
+ }
1016
+ if (buffer.length === 0 && (options.maxBatchSize !== "disabled" || options.exportEmpty !== true)) {
1017
+ return void_;
1018
+ }
1019
+ const items = buffer;
1020
+ buffer = [];
1021
+ const [body, onSuccess] = options.body(items);
1022
+ return client.execute(setBody(request, body)).pipe(andThen(onSuccess), asVoid, withTracerEnabled(false));
1023
+ }).pipe(catchCause((cause) => {
1024
+ if (disabledUntil !== void 0) return void_;
1025
+ disabledUntil = clock.currentTimeMillisUnsafe() + 6e4;
1026
+ buffer = [];
1027
+ return logDebug("Disabling exporter for 60 seconds", cause);
1028
+ }), annotateLogs({
1029
+ package: "@effect/opentelemetry",
1030
+ module: options.label
1031
+ }));
1032
+ const exportFibers = yield* make2();
1033
+ const runExportFork = yield* runtime(exportFibers)();
1034
+ const flusher = yield* Flusher;
1035
+ yield* flusher.register(runExport);
1036
+ yield* addFinalizer(scope, suspend(() => {
1037
+ if (disabledUntil !== void 0) return void_;
1038
+ runExportFork(runExport);
1039
+ return awaitEmpty(exportFibers);
1040
+ }).pipe(ignore, interruptible, timeoutOption(options.shutdownTimeout)));
1041
+ yield* sleep(exportInterval).pipe(andThen(run(exportFibers, runExport)), flatMap2(await_), forever2, forkIn(scope));
1042
+ return {
1043
+ push(data) {
1044
+ if (disabledUntil !== void 0) return;
1045
+ buffer.push(data);
1046
+ if (options.maxBatchSize !== "disabled" && buffer.length >= options.maxBatchSize) {
1047
+ runExportFork(runExport);
1048
+ }
1049
+ }
1050
+ };
1051
+ });
1052
+
1053
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpResource.js
1054
+ var make5 = (options) => {
1055
+ const resourceAttributes = options.attributes ? entriesToAttributes(Object.entries(options.attributes)) : [];
1056
+ resourceAttributes.push({
1057
+ key: "service.name",
1058
+ value: {
1059
+ stringValue: options.serviceName
1060
+ }
1061
+ });
1062
+ if (options.serviceVersion) {
1063
+ resourceAttributes.push({
1064
+ key: "service.version",
1065
+ value: {
1066
+ stringValue: options.serviceVersion
1067
+ }
1068
+ });
1069
+ }
1070
+ return {
1071
+ attributes: resourceAttributes,
1072
+ droppedAttributesCount: 0
1073
+ };
1074
+ };
1075
+ var fromConfig = /* @__PURE__ */ fnUntraced(function* (options) {
1076
+ const env = yield* Record(StringFromUriComponent, StringFromUriComponent, "OTEL_RESOURCE_ATTRIBUTES").pipe(withDefault(void 0));
1077
+ const serviceName = options?.serviceName ?? options?.attributes?.["service.name"] ?? (yield* schema(UndefinedOr(String2), "OTEL_SERVICE_NAME")) ?? env?.["service.name"] ?? (yield* String3("OTEL_SERVICE_NAME"));
1078
+ const serviceVersion = options?.serviceVersion ?? options?.attributes?.["service.version"] ?? (yield* schema(UndefinedOr(String2), "OTEL_SERVICE_VERSION")) ?? env?.["service.version"];
1079
+ const attributes = {
1080
+ ...env,
1081
+ ...options?.attributes
1082
+ };
1083
+ delete attributes["service.name"];
1084
+ delete attributes["service.version"];
1085
+ return make5({
1086
+ serviceName,
1087
+ serviceVersion,
1088
+ attributes
1089
+ });
1090
+ }, orDie);
1091
+ var serviceNameUnsafe = (resource) => {
1092
+ const serviceNameAttribute = resource.attributes.find((attr) => attr.key === "service.name");
1093
+ if (!serviceNameAttribute || !serviceNameAttribute.value.stringValue) {
1094
+ throw new Error("Resource does not contain a service name");
1095
+ }
1096
+ return serviceNameAttribute.value.stringValue;
1097
+ };
1098
+ var entriesToAttributes = (entries) => {
1099
+ const attributes = [];
1100
+ for (const [key, value] of entries) {
1101
+ attributes.push({
1102
+ key,
1103
+ value: unknownToAttributeValue(value)
1104
+ });
1105
+ }
1106
+ return attributes;
1107
+ };
1108
+ var unknownToAttributeValue = (value) => {
1109
+ if (Array.isArray(value)) {
1110
+ return {
1111
+ arrayValue: {
1112
+ values: value.map(unknownToAttributeValue)
1113
+ }
1114
+ };
1115
+ }
1116
+ switch (typeof value) {
1117
+ case "string":
1118
+ return {
1119
+ stringValue: value
1120
+ };
1121
+ case "bigint":
1122
+ return {
1123
+ intValue: String(value)
1124
+ };
1125
+ case "number":
1126
+ return Number.isInteger(value) ? {
1127
+ intValue: value
1128
+ } : {
1129
+ doubleValue: value
1130
+ };
1131
+ case "boolean":
1132
+ return {
1133
+ boolValue: value
1134
+ };
1135
+ default:
1136
+ return {
1137
+ stringValue: format(value)
1138
+ };
1139
+ }
1140
+ };
1141
+
1142
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpSerialization.js
1143
+ var OtlpSerialization_exports = {};
1144
+ __export(OtlpSerialization_exports, {
1145
+ OtlpSerialization: () => OtlpSerialization,
1146
+ layerJson: () => layerJson,
1147
+ layerProtobuf: () => layerProtobuf
1148
+ });
1149
+
1150
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/internal/protobuf.js
1151
+ var WireType2 = {
1152
+ Varint: 0,
1153
+ Fixed64: 1,
1154
+ LengthDelimited: 2,
1155
+ Fixed32: 5
1156
+ };
1157
+ var encodeTag = (fieldNumber, wireType) => fieldNumber << 3 | wireType;
1158
+ var encodeVarint = (value) => {
1159
+ const bytes = [];
1160
+ let n = typeof value === "bigint" ? value : BigInt(value);
1161
+ if (n < BigInt(0)) {
1162
+ n = BigInt.asUintN(64, n);
1163
+ }
1164
+ while (n > BigInt(127)) {
1165
+ bytes.push(Number(n & BigInt(127)) | 128);
1166
+ n >>= BigInt(7);
1167
+ }
1168
+ bytes.push(Number(n));
1169
+ return new Uint8Array(bytes);
1170
+ };
1171
+ var encodeFixed64 = (value) => {
1172
+ const bytes = new Uint8Array(8);
1173
+ const view = new DataView(bytes.buffer);
1174
+ view.setBigUint64(0, value, true);
1175
+ return bytes;
1176
+ };
1177
+ var encodeFixed32 = (value) => {
1178
+ const bytes = new Uint8Array(4);
1179
+ const view = new DataView(bytes.buffer);
1180
+ view.setUint32(0, value, true);
1181
+ return bytes;
1182
+ };
1183
+ var encodeDouble = (value) => {
1184
+ const bytes = new Uint8Array(8);
1185
+ const view = new DataView(bytes.buffer);
1186
+ view.setFloat64(0, value, true);
1187
+ return bytes;
1188
+ };
1189
+ var encodeString = (value) => new TextEncoder().encode(value);
1190
+ var encodeHexBytes = (hex) => {
1191
+ const bytes = new Uint8Array(hex.length / 2);
1192
+ for (let i = 0; i < hex.length; i += 2) {
1193
+ bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
1194
+ }
1195
+ return bytes;
1196
+ };
1197
+ var concat = (...arrays) => {
1198
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
1199
+ const result = new Uint8Array(totalLength);
1200
+ let offset = 0;
1201
+ for (const arr of arrays) {
1202
+ result.set(arr, offset);
1203
+ offset += arr.length;
1204
+ }
1205
+ return result;
1206
+ };
1207
+ var varintField = (fieldNumber, value) => concat(encodeVarint(encodeTag(fieldNumber, WireType2.Varint)), encodeVarint(value));
1208
+ var boolField = (fieldNumber, value) => varintField(fieldNumber, value ? 1 : 0);
1209
+ var fixed64Field = (fieldNumber, value) => concat(encodeVarint(encodeTag(fieldNumber, WireType2.Fixed64)), encodeFixed64(value));
1210
+ var fixed32Field = (fieldNumber, value) => concat(encodeVarint(encodeTag(fieldNumber, WireType2.Fixed32)), encodeFixed32(value));
1211
+ var doubleField = (fieldNumber, value) => concat(encodeVarint(encodeTag(fieldNumber, WireType2.Fixed64)), encodeDouble(value));
1212
+ var lengthDelimitedField = (fieldNumber, value) => concat(encodeVarint(encodeTag(fieldNumber, WireType2.LengthDelimited)), encodeVarint(value.length), value);
1213
+ var stringField = (fieldNumber, value) => lengthDelimitedField(fieldNumber, encodeString(value));
1214
+ var bytesFieldFromHex = (fieldNumber, hex) => lengthDelimitedField(fieldNumber, encodeHexBytes(hex));
1215
+ var messageField = (fieldNumber, message) => lengthDelimitedField(fieldNumber, message);
1216
+ var repeatedField = (fieldNumber, values, encode) => concat(...values.map((v) => messageField(fieldNumber, encode(v))));
1217
+ var optionalStringField = (fieldNumber, value) => value !== void 0 && value !== "" ? stringField(fieldNumber, value) : new Uint8Array(0);
1218
+
1219
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/internal/otlpProtobuf.js
1220
+ var encodeAnyValue = (value) => {
1221
+ if (value.stringValue !== void 0 && value.stringValue !== null) {
1222
+ return stringField(1, value.stringValue);
1223
+ }
1224
+ if (value.boolValue !== void 0 && value.boolValue !== null) {
1225
+ return boolField(2, value.boolValue);
1226
+ }
1227
+ if (value.intValue !== void 0 && value.intValue !== null) {
1228
+ return varintField(3, BigInt(value.intValue));
1229
+ }
1230
+ if (value.doubleValue !== void 0 && value.doubleValue !== null) {
1231
+ return doubleField(4, value.doubleValue);
1232
+ }
1233
+ if (value.arrayValue !== void 0) {
1234
+ return messageField(5, encodeArrayValue(value.arrayValue));
1235
+ }
1236
+ if (value.kvlistValue !== void 0) {
1237
+ return messageField(6, encodeKeyValueList(value.kvlistValue));
1238
+ }
1239
+ if (value.bytesValue !== void 0) {
1240
+ return lengthDelimitedField(7, value.bytesValue);
1241
+ }
1242
+ return new Uint8Array(0);
1243
+ };
1244
+ var encodeArrayValue = (value) => repeatedField(1, value.values, encodeAnyValue);
1245
+ var encodeKeyValueList = (value) => repeatedField(1, value.values, encodeKeyValue);
1246
+ var encodeKeyValue = (kv) => concat(stringField(1, kv.key), messageField(2, encodeAnyValue(kv.value)));
1247
+ var encodeInstrumentationScope = (scope) => concat(stringField(1, scope.name), optionalStringField(2, scope.version), scope.attributes ? repeatedField(3, scope.attributes, encodeKeyValue) : new Uint8Array(0), scope.droppedAttributesCount ? varintField(4, scope.droppedAttributesCount) : new Uint8Array(0));
1248
+ var encodeResource = (resource) => concat(repeatedField(1, resource.attributes, encodeKeyValue), resource.droppedAttributesCount > 0 ? varintField(2, resource.droppedAttributesCount) : new Uint8Array(0));
1249
+ var encodeStatus = (status) => concat(optionalStringField(2, status.message), varintField(3, status.code));
1250
+ var encodeEvent = (event) => concat(fixed64Field(1, BigInt(event.timeUnixNano)), stringField(2, event.name), repeatedField(3, event.attributes, encodeKeyValue), event.droppedAttributesCount > 0 ? varintField(4, event.droppedAttributesCount) : new Uint8Array(0));
1251
+ var encodeLink = (link) => concat(bytesFieldFromHex(1, link.traceId), bytesFieldFromHex(2, link.spanId), optionalStringField(3, link.traceState), repeatedField(4, link.attributes, encodeKeyValue), link.droppedAttributesCount > 0 ? varintField(5, link.droppedAttributesCount) : new Uint8Array(0), link.flags !== void 0 ? fixed32Field(6, link.flags) : new Uint8Array(0));
1252
+ var encodeSpan = (span) => concat(bytesFieldFromHex(1, span.traceId), bytesFieldFromHex(2, span.spanId), optionalStringField(3, span.traceState), span.parentSpanId !== void 0 ? bytesFieldFromHex(4, span.parentSpanId) : new Uint8Array(0), stringField(5, span.name), varintField(6, span.kind), fixed64Field(7, BigInt(span.startTimeUnixNano)), fixed64Field(8, BigInt(span.endTimeUnixNano)), repeatedField(9, span.attributes, encodeKeyValue), span.droppedAttributesCount > 0 ? varintField(10, span.droppedAttributesCount) : new Uint8Array(0), repeatedField(11, span.events, encodeEvent), span.droppedEventsCount > 0 ? varintField(12, span.droppedEventsCount) : new Uint8Array(0), repeatedField(13, span.links, encodeLink), span.droppedLinksCount > 0 ? varintField(14, span.droppedLinksCount) : new Uint8Array(0), messageField(15, encodeStatus(span.status)), span.flags !== void 0 ? fixed32Field(16, span.flags) : new Uint8Array(0));
1253
+ var encodeScopeSpans = (scopeSpans) => concat(messageField(1, encodeInstrumentationScope(scopeSpans.scope)), repeatedField(2, scopeSpans.spans, encodeSpan), optionalStringField(3, scopeSpans.schemaUrl));
1254
+ var encodeResourceSpans = (resourceSpans) => concat(messageField(1, encodeResource(resourceSpans.resource)), repeatedField(2, resourceSpans.scopeSpans, encodeScopeSpans), optionalStringField(3, resourceSpans.schemaUrl));
1255
+ var encodeTracesData = (tracesData) => repeatedField(1, tracesData.resourceSpans, encodeResourceSpans);
1256
+ var encodeNumberDataPoint = (point) => concat(fixed64Field(2, BigInt(point.startTimeUnixNano)), fixed64Field(3, BigInt(point.timeUnixNano)), point.asDouble !== void 0 ? doubleField(4, point.asDouble) : new Uint8Array(0), point.asInt !== void 0 ? fixed64Field(6, BigInt(point.asInt)) : new Uint8Array(0), repeatedField(7, point.attributes, encodeKeyValue), point.flags !== void 0 ? varintField(8, point.flags) : new Uint8Array(0));
1257
+ var encodeHistogramDataPoint = (point) => {
1258
+ const bucketCountsEncoded = concat(...point.bucketCounts.map((count) => fixed64Field(6, BigInt(count))));
1259
+ const explicitBoundsEncoded = concat(...point.explicitBounds.map((bound) => doubleField(7, bound)));
1260
+ return concat(fixed64Field(2, BigInt(point.startTimeUnixNano)), fixed64Field(3, BigInt(point.timeUnixNano)), fixed64Field(4, BigInt(point.count)), point.sum !== void 0 ? doubleField(5, point.sum) : new Uint8Array(0), bucketCountsEncoded, explicitBoundsEncoded, repeatedField(9, point.attributes, encodeKeyValue), point.flags !== void 0 ? varintField(10, point.flags) : new Uint8Array(0), point.min !== void 0 ? doubleField(11, point.min) : new Uint8Array(0), point.max !== void 0 ? doubleField(12, point.max) : new Uint8Array(0));
1261
+ };
1262
+ var encodeGauge = (gauge) => repeatedField(1, gauge.dataPoints, encodeNumberDataPoint);
1263
+ var encodeSum = (sum) => concat(repeatedField(1, sum.dataPoints, encodeNumberDataPoint), varintField(2, sum.aggregationTemporality), boolField(3, sum.isMonotonic));
1264
+ var encodeHistogram = (histogram) => concat(repeatedField(1, histogram.dataPoints, encodeHistogramDataPoint), varintField(2, histogram.aggregationTemporality));
1265
+ var encodeMetric = (metric) => concat(stringField(1, metric.name), optionalStringField(2, metric.description), optionalStringField(3, metric.unit), metric.gauge !== void 0 ? messageField(5, encodeGauge(metric.gauge)) : new Uint8Array(0), metric.sum !== void 0 ? messageField(7, encodeSum(metric.sum)) : new Uint8Array(0), metric.histogram !== void 0 ? messageField(9, encodeHistogram(metric.histogram)) : new Uint8Array(0));
1266
+ var encodeScopeMetrics = (scopeMetrics) => concat(messageField(1, encodeInstrumentationScope(scopeMetrics.scope)), repeatedField(2, scopeMetrics.metrics, encodeMetric), optionalStringField(3, scopeMetrics.schemaUrl));
1267
+ var encodeResourceMetrics = (resourceMetrics) => concat(messageField(1, encodeResource(resourceMetrics.resource)), repeatedField(2, resourceMetrics.scopeMetrics, encodeScopeMetrics), optionalStringField(3, resourceMetrics.schemaUrl));
1268
+ var encodeMetricsData = (metricsData) => repeatedField(1, metricsData.resourceMetrics, encodeResourceMetrics);
1269
+ var encodeLogRecord = (record) => concat(fixed64Field(1, BigInt(record.timeUnixNano)), record.severityNumber !== void 0 ? varintField(2, record.severityNumber) : new Uint8Array(0), optionalStringField(3, record.severityText), record.body !== void 0 ? messageField(5, encodeAnyValue(record.body)) : new Uint8Array(0), repeatedField(6, record.attributes, encodeKeyValue), record.droppedAttributesCount !== void 0 && record.droppedAttributesCount > 0 ? varintField(7, record.droppedAttributesCount) : new Uint8Array(0), record.flags !== void 0 ? fixed32Field(8, record.flags) : new Uint8Array(0), record.traceId !== void 0 && record.traceId !== "" ? bytesFieldFromHex(9, record.traceId) : new Uint8Array(0), record.spanId !== void 0 && record.spanId !== "" ? bytesFieldFromHex(10, record.spanId) : new Uint8Array(0), record.observedTimeUnixNano !== void 0 ? fixed64Field(11, BigInt(record.observedTimeUnixNano)) : new Uint8Array(0));
1270
+ var encodeScopeLogs = (scopeLogs) => concat(messageField(1, encodeInstrumentationScope(scopeLogs.scope)), repeatedField(2, scopeLogs.logRecords, encodeLogRecord), optionalStringField(3, scopeLogs.schemaUrl));
1271
+ var encodeResourceLogs = (resourceLogs) => concat(messageField(1, encodeResource(resourceLogs.resource)), repeatedField(2, resourceLogs.scopeLogs, encodeScopeLogs), optionalStringField(3, resourceLogs.schemaUrl));
1272
+ var encodeLogsData = (logsData) => repeatedField(1, logsData.resourceLogs, encodeResourceLogs);
1273
+
1274
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpSerialization.js
1275
+ var OtlpSerialization = class extends (/* @__PURE__ */ Service()("effect/observability/OtlpSerialization")) {
1276
+ };
1277
+ var layerJson = /* @__PURE__ */ succeed(OtlpSerialization, {
1278
+ traces: (spans) => jsonUnsafe(spans),
1279
+ metrics: (metrics) => jsonUnsafe(metrics),
1280
+ logs: (logs) => jsonUnsafe(logs)
1281
+ });
1282
+ var layerProtobuf = /* @__PURE__ */ succeed(OtlpSerialization, {
1283
+ traces: (spans) => uint8Array(encodeTracesData(spans), "application/x-protobuf"),
1284
+ metrics: (metrics) => uint8Array(encodeMetricsData(metrics), "application/x-protobuf"),
1285
+ logs: (logs) => uint8Array(encodeLogsData(logs), "application/x-protobuf")
1286
+ });
1287
+
1288
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpLogger.js
1289
+ var make6 = /* @__PURE__ */ fnUntraced(function* (options) {
1290
+ const serialization = yield* OtlpSerialization;
1291
+ const otelResource = yield* fromConfig(options.resource);
1292
+ const scope = {
1293
+ name: serviceNameUnsafe(otelResource)
1294
+ };
1295
+ const exporter = yield* make4({
1296
+ label: "OtlpLogger",
1297
+ url: options.url,
1298
+ headers: options.headers,
1299
+ maxBatchSize: options.maxBatchSize ?? 1e3,
1300
+ exportInterval: options.exportInterval ?? seconds(1),
1301
+ body: (data) => [serialization.logs({
1302
+ resourceLogs: [{
1303
+ resource: otelResource,
1304
+ scopeLogs: [{
1305
+ scope,
1306
+ logRecords: data
1307
+ }]
1308
+ }]
1309
+ }), void_],
1310
+ shutdownTimeout: options.shutdownTimeout ?? seconds(3)
1311
+ });
1312
+ const opts = {
1313
+ excludeLogSpans: options.excludeLogSpans ?? false,
1314
+ clock: yield* Clock
1315
+ };
1316
+ return make3((options2) => {
1317
+ exporter.push(makeLogRecord(options2, opts));
1318
+ });
1319
+ });
1320
+ var layer2 = (options) => layer([make6(options)], {
1321
+ mergeWithExisting: options.mergeWithExisting ?? true
1322
+ }).pipe(provideMerge(layerFlusher));
1323
+ var layerFromConfig = (options) => gen(function* () {
1324
+ const {
1325
+ disabled,
1326
+ endpoint: endpoint2,
1327
+ exporters: exporters2
1328
+ } = yield* all({
1329
+ disabled: Boolean("OTEL_SDK_DISABLED").pipe(withDefault(false)),
1330
+ endpoint: endpoint("LOGS"),
1331
+ exporters: exporters("LOGS")
1332
+ });
1333
+ if (disabled || !endpoint2 || !exporters2.includes("otlp")) {
1334
+ return layerFlusher;
1335
+ }
1336
+ const {
1337
+ baseTimeout,
1338
+ logsTimeout,
1339
+ exportTimeout,
1340
+ scheduleDelay,
1341
+ maxBatchSize
1342
+ } = yield* all({
1343
+ baseTimeout: option(Int("OTEL_EXPORTER_OTLP_TIMEOUT")),
1344
+ logsTimeout: option(Int("OTEL_EXPORTER_OTLP_LOGS_TIMEOUT")),
1345
+ exportTimeout: option(Int("OTEL_BLRP_EXPORT_TIMEOUT")),
1346
+ scheduleDelay: option(Int("OTEL_BLRP_SCHEDULE_DELAY")),
1347
+ maxBatchSize: option(Int("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE"))
1348
+ });
1349
+ const shutdownTimeout = firstSomeOf([logsTimeout, baseTimeout, exportTimeout]).pipe(map((_) => millis(_)));
1350
+ const exportInterval = map(scheduleDelay, (_) => millis(_));
1351
+ return layer2({
1352
+ url: endpoint2.toString(),
1353
+ resource: options?.resource,
1354
+ headers: options?.headers ?? (yield* headers("LOGS")),
1355
+ exportInterval: getOrUndefined(exportInterval),
1356
+ maxBatchSize: getOrUndefined(maxBatchSize),
1357
+ shutdownTimeout: getOrUndefined(shutdownTimeout),
1358
+ excludeLogSpans: options?.excludeLogSpans,
1359
+ mergeWithExisting: options?.mergeWithExisting
1360
+ });
1361
+ }).pipe(orDie, unwrap);
1362
+ var makeLogRecord = (options, opts) => {
1363
+ const now = opts.clock.currentTimeNanosUnsafe();
1364
+ const nanosString = now.toString();
1365
+ const nowMillis = options.date.getTime();
1366
+ const attributes = entriesToAttributes(Object.entries(options.fiber.getRef(CurrentLogAnnotations)));
1367
+ attributes.push({
1368
+ key: "fiberId",
1369
+ value: {
1370
+ intValue: options.fiber.id
1371
+ }
1372
+ });
1373
+ if (!opts.excludeLogSpans) {
1374
+ for (const [label, startTime] of options.fiber.getRef(CurrentLogSpans)) {
1375
+ attributes.push({
1376
+ key: `logSpan.${label}`,
1377
+ value: {
1378
+ stringValue: `${nowMillis - startTime}ms`
1379
+ }
1380
+ });
1381
+ }
1382
+ }
1383
+ if (options.cause.reasons.length > 0) {
1384
+ attributes.push({
1385
+ key: "log.error",
1386
+ value: {
1387
+ stringValue: pretty(options.cause)
1388
+ }
1389
+ });
1390
+ }
1391
+ const message = ensure(options.message);
1392
+ const logRecord = {
1393
+ severityNumber: logLevelToSeverityNumber(options.logLevel),
1394
+ severityText: options.logLevel,
1395
+ timeUnixNano: nanosString,
1396
+ observedTimeUnixNano: nanosString,
1397
+ attributes,
1398
+ body: unknownToAttributeValue(message.length === 1 ? message[0] : message),
1399
+ droppedAttributesCount: 0
1400
+ };
1401
+ if (options.fiber.cache.span) {
1402
+ logRecord.traceId = options.fiber.cache.span.traceId;
1403
+ logRecord.spanId = options.fiber.cache.span.spanId;
1404
+ }
1405
+ return logRecord;
1406
+ };
1407
+ var logLevelToSeverityNumber = (logLevel) => {
1408
+ switch (logLevel) {
1409
+ case "Trace":
1410
+ return ESeverityNumber.SEVERITY_NUMBER_TRACE;
1411
+ case "Debug":
1412
+ return ESeverityNumber.SEVERITY_NUMBER_DEBUG;
1413
+ case "Info":
1414
+ return ESeverityNumber.SEVERITY_NUMBER_INFO;
1415
+ case "Warn":
1416
+ return ESeverityNumber.SEVERITY_NUMBER_WARN;
1417
+ case "Error":
1418
+ return ESeverityNumber.SEVERITY_NUMBER_ERROR;
1419
+ case "Fatal":
1420
+ return ESeverityNumber.SEVERITY_NUMBER_FATAL;
1421
+ default:
1422
+ return ESeverityNumber.SEVERITY_NUMBER_UNSPECIFIED;
1423
+ }
1424
+ };
1425
+ var ESeverityNumber = {
1426
+ /** Unspecified. Do NOT use as default */
1427
+ SEVERITY_NUMBER_UNSPECIFIED: 0,
1428
+ SEVERITY_NUMBER_TRACE: 1,
1429
+ SEVERITY_NUMBER_TRACE2: 2,
1430
+ SEVERITY_NUMBER_TRACE3: 3,
1431
+ SEVERITY_NUMBER_TRACE4: 4,
1432
+ SEVERITY_NUMBER_DEBUG: 5,
1433
+ SEVERITY_NUMBER_DEBUG2: 6,
1434
+ SEVERITY_NUMBER_DEBUG3: 7,
1435
+ SEVERITY_NUMBER_DEBUG4: 8,
1436
+ SEVERITY_NUMBER_INFO: 9,
1437
+ SEVERITY_NUMBER_INFO2: 10,
1438
+ SEVERITY_NUMBER_INFO3: 11,
1439
+ SEVERITY_NUMBER_INFO4: 12,
1440
+ SEVERITY_NUMBER_WARN: 13,
1441
+ SEVERITY_NUMBER_WARN2: 14,
1442
+ SEVERITY_NUMBER_WARN3: 15,
1443
+ SEVERITY_NUMBER_WARN4: 16,
1444
+ SEVERITY_NUMBER_ERROR: 17,
1445
+ SEVERITY_NUMBER_ERROR2: 18,
1446
+ SEVERITY_NUMBER_ERROR3: 19,
1447
+ SEVERITY_NUMBER_ERROR4: 20,
1448
+ SEVERITY_NUMBER_FATAL: 21,
1449
+ SEVERITY_NUMBER_FATAL2: 22,
1450
+ SEVERITY_NUMBER_FATAL3: 23,
1451
+ SEVERITY_NUMBER_FATAL4: 24
1452
+ };
1453
+
1454
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpMetrics.js
1455
+ var OtlpMetrics_exports = {};
1456
+ __export(OtlpMetrics_exports, {
1457
+ layer: () => layer3,
1458
+ layerFromConfig: () => layerFromConfig2,
1459
+ make: () => make7
1460
+ });
1461
+ var make7 = /* @__PURE__ */ fnUntraced(function* (options) {
1462
+ const clock = yield* Clock;
1463
+ const serialization = yield* OtlpSerialization;
1464
+ const startTimeNanos = yield* clock.currentTimeNanos;
1465
+ const startTime = String(startTimeNanos);
1466
+ const temporality = options.temporality ?? "cumulative";
1467
+ const resource = yield* fromConfig(options.resource);
1468
+ const metricsScope = {
1469
+ name: serviceNameUnsafe(resource)
1470
+ };
1471
+ const services = yield* context();
1472
+ let previousExportTimeNanos = startTimeNanos;
1473
+ let previousCounterState = /* @__PURE__ */ new Map();
1474
+ let previousHistogramState = /* @__PURE__ */ new Map();
1475
+ let previousFrequencyState = /* @__PURE__ */ new Map();
1476
+ let previousSummaryState = /* @__PURE__ */ new Map();
1477
+ let snapshotSequence = 0;
1478
+ let committedSnapshotSequence = -1;
1479
+ const snapshot = () => {
1480
+ const snapshot2 = snapshotUnsafe(services);
1481
+ const currentSnapshotSequence = snapshotSequence++;
1482
+ const nowNanos = clock.currentTimeNanosUnsafe();
1483
+ const nowTime = String(nowNanos);
1484
+ const nextCounterState = new Map(previousCounterState);
1485
+ const nextHistogramState = new Map(previousHistogramState);
1486
+ const nextFrequencyState = new Map(previousFrequencyState);
1487
+ const nextSummaryState = new Map(previousSummaryState);
1488
+ const metricData = [];
1489
+ const metricDataByName = /* @__PURE__ */ new Map();
1490
+ const addMetricData = (data) => {
1491
+ metricData.push(data);
1492
+ metricDataByName.set(data.name, data);
1493
+ };
1494
+ const isDelta = temporality === "delta";
1495
+ const aggregationTemporalityEnum = isDelta ? EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA : EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE;
1496
+ const intervalStartTime = isDelta ? String(previousExportTimeNanos) : startTime;
1497
+ for (let i = 0, len = snapshot2.length; i < len; i++) {
1498
+ const state = snapshot2[i];
1499
+ const unit = state.attributes?.unit ?? state.attributes?.time_unit ?? "1";
1500
+ const attributes = state.attributes ? entriesToAttributes(Object.entries(state.attributes)) : [];
1501
+ const metricKey = makeMetricKey(state.id, state.attributes);
1502
+ switch (state.type) {
1503
+ case "Counter": {
1504
+ const currentCount = state.state.count;
1505
+ let reportValue = currentCount;
1506
+ if (isDelta) {
1507
+ const previousCount = previousCounterState.get(metricKey);
1508
+ if (previousCount !== void 0) {
1509
+ if (typeof currentCount === "bigint" && typeof previousCount === "bigint") {
1510
+ reportValue = currentCount - previousCount;
1511
+ if (state.state.incremental && reportValue < BigInt(0)) {
1512
+ reportValue = currentCount;
1513
+ }
1514
+ } else {
1515
+ const curr = Number(currentCount);
1516
+ const prev = Number(previousCount);
1517
+ reportValue = curr - prev;
1518
+ if (state.state.incremental && reportValue < 0) {
1519
+ reportValue = curr;
1520
+ }
1521
+ }
1522
+ }
1523
+ nextCounterState.set(metricKey, currentCount);
1524
+ }
1525
+ const dataPoint = {
1526
+ attributes,
1527
+ startTimeUnixNano: intervalStartTime,
1528
+ timeUnixNano: nowTime
1529
+ };
1530
+ if (typeof reportValue === "bigint") {
1531
+ dataPoint.asInt = Number(reportValue);
1532
+ } else {
1533
+ dataPoint.asDouble = reportValue;
1534
+ }
1535
+ if (metricDataByName.has(state.id)) {
1536
+ metricDataByName.get(state.id).sum.dataPoints.push(dataPoint);
1537
+ } else {
1538
+ addMetricData({
1539
+ name: state.id,
1540
+ description: state.description,
1541
+ unit,
1542
+ sum: {
1543
+ aggregationTemporality: aggregationTemporalityEnum,
1544
+ isMonotonic: state.state.incremental,
1545
+ dataPoints: [dataPoint]
1546
+ }
1547
+ });
1548
+ }
1549
+ break;
1550
+ }
1551
+ case "Gauge": {
1552
+ const dataPoint = {
1553
+ attributes,
1554
+ startTimeUnixNano: startTime,
1555
+ timeUnixNano: nowTime
1556
+ };
1557
+ if (typeof state.state.value === "bigint") {
1558
+ dataPoint.asInt = Number(state.state.value);
1559
+ } else {
1560
+ dataPoint.asDouble = state.state.value;
1561
+ }
1562
+ if (metricDataByName.has(state.id)) {
1563
+ metricDataByName.get(state.id).gauge.dataPoints.push(dataPoint);
1564
+ } else {
1565
+ addMetricData({
1566
+ name: state.id,
1567
+ description: state.description,
1568
+ unit,
1569
+ gauge: {
1570
+ dataPoints: [dataPoint]
1571
+ }
1572
+ });
1573
+ }
1574
+ break;
1575
+ }
1576
+ case "Histogram": {
1577
+ const size = state.state.buckets.length;
1578
+ const currentBuckets = {
1579
+ boundaries: allocate(size - 1),
1580
+ counts: allocate(size)
1581
+ };
1582
+ let idx = 0;
1583
+ let prev = 0;
1584
+ for (const [boundary, value] of state.state.buckets) {
1585
+ if (idx < size - 1) {
1586
+ currentBuckets.boundaries[idx] = boundary;
1587
+ }
1588
+ currentBuckets.counts[idx] = value - prev;
1589
+ prev = value;
1590
+ idx++;
1591
+ }
1592
+ let reportCount = state.state.count;
1593
+ let reportSum = state.state.sum;
1594
+ let reportBucketCounts = currentBuckets.counts;
1595
+ const reportMin = state.state.min;
1596
+ const reportMax = state.state.max;
1597
+ if (isDelta) {
1598
+ const previousState = previousHistogramState.get(metricKey);
1599
+ if (previousState !== void 0) {
1600
+ reportCount = state.state.count - previousState.count;
1601
+ reportSum = state.state.sum - previousState.sum;
1602
+ reportBucketCounts = currentBuckets.counts.map((c, i2) => Math.max(0, c - (previousState.bucketCounts[i2] ?? 0)));
1603
+ }
1604
+ nextHistogramState.set(metricKey, {
1605
+ count: state.state.count,
1606
+ sum: state.state.sum,
1607
+ bucketCounts: currentBuckets.counts.slice(),
1608
+ min: state.state.min,
1609
+ max: state.state.max
1610
+ });
1611
+ }
1612
+ const dataPoint = {
1613
+ attributes,
1614
+ startTimeUnixNano: intervalStartTime,
1615
+ timeUnixNano: nowTime,
1616
+ count: reportCount,
1617
+ min: reportMin,
1618
+ max: reportMax,
1619
+ sum: reportSum,
1620
+ bucketCounts: reportBucketCounts,
1621
+ explicitBounds: currentBuckets.boundaries
1622
+ };
1623
+ if (metricDataByName.has(state.id)) {
1624
+ metricDataByName.get(state.id).histogram.dataPoints.push(dataPoint);
1625
+ } else {
1626
+ addMetricData({
1627
+ name: state.id,
1628
+ description: state.description,
1629
+ unit,
1630
+ histogram: {
1631
+ aggregationTemporality: aggregationTemporalityEnum,
1632
+ dataPoints: [dataPoint]
1633
+ }
1634
+ });
1635
+ }
1636
+ break;
1637
+ }
1638
+ case "Frequency": {
1639
+ const dataPoints = [];
1640
+ const currentOccurrences = /* @__PURE__ */ new Map();
1641
+ for (const [freqKey, value] of state.state.occurrences) {
1642
+ currentOccurrences.set(freqKey, value);
1643
+ let reportValue = value;
1644
+ if (isDelta) {
1645
+ const previousOccurrences = previousFrequencyState.get(metricKey);
1646
+ if (previousOccurrences !== void 0) {
1647
+ const previousValue = previousOccurrences.get(freqKey) ?? 0;
1648
+ reportValue = Math.max(0, value - previousValue);
1649
+ }
1650
+ }
1651
+ dataPoints.push({
1652
+ attributes: [...attributes, {
1653
+ key: "key",
1654
+ value: {
1655
+ stringValue: freqKey
1656
+ }
1657
+ }],
1658
+ startTimeUnixNano: intervalStartTime,
1659
+ timeUnixNano: nowTime,
1660
+ asInt: reportValue
1661
+ });
1662
+ }
1663
+ if (isDelta) {
1664
+ nextFrequencyState.set(metricKey, currentOccurrences);
1665
+ }
1666
+ if (metricDataByName.has(state.id)) {
1667
+ metricDataByName.get(state.id).sum.dataPoints.push(...dataPoints);
1668
+ } else {
1669
+ addMetricData({
1670
+ name: state.id,
1671
+ description: state.description,
1672
+ unit,
1673
+ sum: {
1674
+ aggregationTemporality: aggregationTemporalityEnum,
1675
+ isMonotonic: true,
1676
+ dataPoints
1677
+ }
1678
+ });
1679
+ }
1680
+ break;
1681
+ }
1682
+ case "Summary": {
1683
+ const dataPoints = [{
1684
+ attributes: [...attributes, {
1685
+ key: "quantile",
1686
+ value: {
1687
+ stringValue: "min"
1688
+ }
1689
+ }],
1690
+ startTimeUnixNano: intervalStartTime,
1691
+ timeUnixNano: nowTime,
1692
+ asDouble: state.state.min
1693
+ }];
1694
+ for (const [quantile, value] of state.state.quantiles) {
1695
+ dataPoints.push({
1696
+ attributes: [...attributes, {
1697
+ key: "quantile",
1698
+ value: {
1699
+ stringValue: quantile.toString()
1700
+ }
1701
+ }],
1702
+ startTimeUnixNano: intervalStartTime,
1703
+ timeUnixNano: nowTime,
1704
+ asDouble: value ?? 0
1705
+ });
1706
+ }
1707
+ dataPoints.push({
1708
+ attributes: [...attributes, {
1709
+ key: "quantile",
1710
+ value: {
1711
+ stringValue: "max"
1712
+ }
1713
+ }],
1714
+ startTimeUnixNano: intervalStartTime,
1715
+ timeUnixNano: nowTime,
1716
+ asDouble: state.state.max
1717
+ });
1718
+ let reportCount = state.state.count;
1719
+ let reportSum = state.state.sum;
1720
+ if (isDelta) {
1721
+ const previousState = previousSummaryState.get(metricKey);
1722
+ if (previousState !== void 0) {
1723
+ reportCount = state.state.count - previousState.count;
1724
+ reportSum = state.state.sum - previousState.sum;
1725
+ }
1726
+ nextSummaryState.set(metricKey, {
1727
+ count: state.state.count,
1728
+ sum: state.state.sum
1729
+ });
1730
+ }
1731
+ const countDataPoint = {
1732
+ attributes,
1733
+ startTimeUnixNano: intervalStartTime,
1734
+ timeUnixNano: nowTime,
1735
+ asInt: reportCount
1736
+ };
1737
+ const sumDataPoint = {
1738
+ attributes,
1739
+ startTimeUnixNano: intervalStartTime,
1740
+ timeUnixNano: nowTime,
1741
+ asDouble: reportSum
1742
+ };
1743
+ if (metricDataByName.has(`${state.id}_quantiles`)) {
1744
+ metricDataByName.get(`${state.id}_quantiles`).sum.dataPoints.push(...dataPoints);
1745
+ metricDataByName.get(`${state.id}_count`).sum.dataPoints.push(countDataPoint);
1746
+ metricDataByName.get(`${state.id}_sum`).sum.dataPoints.push(sumDataPoint);
1747
+ } else {
1748
+ addMetricData({
1749
+ name: `${state.id}_quantiles`,
1750
+ description: state.description,
1751
+ unit,
1752
+ sum: {
1753
+ aggregationTemporality: aggregationTemporalityEnum,
1754
+ isMonotonic: false,
1755
+ dataPoints
1756
+ }
1757
+ });
1758
+ addMetricData({
1759
+ name: `${state.id}_count`,
1760
+ description: state.description,
1761
+ unit: "1",
1762
+ sum: {
1763
+ aggregationTemporality: aggregationTemporalityEnum,
1764
+ isMonotonic: true,
1765
+ dataPoints: [countDataPoint]
1766
+ }
1767
+ });
1768
+ addMetricData({
1769
+ name: `${state.id}_sum`,
1770
+ description: state.description,
1771
+ unit: "1",
1772
+ sum: {
1773
+ aggregationTemporality: aggregationTemporalityEnum,
1774
+ isMonotonic: true,
1775
+ dataPoints: [sumDataPoint]
1776
+ }
1777
+ });
1778
+ }
1779
+ break;
1780
+ }
1781
+ }
1782
+ }
1783
+ const body = serialization.metrics({
1784
+ resourceMetrics: [{
1785
+ resource,
1786
+ scopeMetrics: [{
1787
+ scope: metricsScope,
1788
+ metrics: metricData
1789
+ }]
1790
+ }]
1791
+ });
1792
+ const onSuccess = isDelta ? sync2(() => {
1793
+ if (currentSnapshotSequence < committedSnapshotSequence) return;
1794
+ previousCounterState = nextCounterState;
1795
+ previousHistogramState = nextHistogramState;
1796
+ previousFrequencyState = nextFrequencyState;
1797
+ previousSummaryState = nextSummaryState;
1798
+ previousExportTimeNanos = nowNanos;
1799
+ committedSnapshotSequence = currentSnapshotSequence;
1800
+ }) : void_;
1801
+ return [body, onSuccess];
1802
+ };
1803
+ yield* make4({
1804
+ label: "OtlpMetrics",
1805
+ url: options.url,
1806
+ headers: options.headers,
1807
+ maxBatchSize: "disabled",
1808
+ exportEmpty: true,
1809
+ exportInterval: options.exportInterval ?? seconds(10),
1810
+ body: snapshot,
1811
+ shutdownTimeout: options.shutdownTimeout ?? seconds(3)
1812
+ });
1813
+ });
1814
+ var layer3 = (options) => effectDiscard(make7(options)).pipe(provideMerge(layerFlusher));
1815
+ var layerFromConfig2 = (options) => gen(function* () {
1816
+ const {
1817
+ disabled,
1818
+ endpoint: endpoint2,
1819
+ exporters: exporters2
1820
+ } = yield* all({
1821
+ disabled: Boolean("OTEL_SDK_DISABLED").pipe(withDefault(false)),
1822
+ endpoint: endpoint("METRICS"),
1823
+ exporters: exporters("METRICS")
1824
+ });
1825
+ if (disabled || !endpoint2 || !exporters2.includes("otlp")) {
1826
+ return layerFlusher;
1827
+ }
1828
+ const {
1829
+ baseTimeout,
1830
+ metricsTimeout,
1831
+ exportTimeout,
1832
+ exportInterval,
1833
+ temporalityPreference
1834
+ } = yield* all({
1835
+ baseTimeout: option(Int("OTEL_EXPORTER_OTLP_TIMEOUT")),
1836
+ metricsTimeout: option(Int("OTEL_EXPORTER_OTLP_METRICS_TIMEOUT")),
1837
+ exportTimeout: option(Int("OTEL_METRIC_EXPORT_TIMEOUT")),
1838
+ exportInterval: option(Int("OTEL_METRIC_EXPORT_INTERVAL").pipe(map3(millis))),
1839
+ temporalityPreference: option(Literals(["delta", "cumulative"], "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE"))
1840
+ });
1841
+ const shutdownTimeout = firstSomeOf([metricsTimeout, baseTimeout, exportTimeout]).pipe(map((_) => millis(_)));
1842
+ return layer3({
1843
+ url: endpoint2.toString(),
1844
+ resource: options?.resource,
1845
+ headers: options?.headers ?? (yield* headers("METRICS")),
1846
+ exportInterval: getOrUndefined(exportInterval),
1847
+ shutdownTimeout: getOrUndefined(shutdownTimeout),
1848
+ temporality: getOrUndefined(temporalityPreference)
1849
+ });
1850
+ }).pipe(orDie, unwrap);
1851
+ var makeMetricKey = (id, attributes) => {
1852
+ if (attributes === void 0 || Object.keys(attributes).length === 0) {
1853
+ return id;
1854
+ }
1855
+ const sortedEntries = Object.entries(attributes).sort((a, b) => a[0].localeCompare(b[0]));
1856
+ return `${id}:${JSON.stringify(sortedEntries)}`;
1857
+ };
1858
+ var EAggregationTemporality = {
1859
+ AGGREGATION_TEMPORALITY_UNSPECIFIED: 0,
1860
+ /** DELTA is an AggregationTemporality for a metric aggregator which reports
1861
+ changes since last report time. Successive metrics contain aggregation of
1862
+ values from continuous and non-overlapping intervals.
1863
+ The values for a DELTA metric are based only on the time interval
1864
+ associated with one measurement cycle. There is no dependency on
1865
+ previous measurements like is the case for CUMULATIVE metrics.
1866
+ For example, consider a system measuring the number of requests that
1867
+ it receives and reports the sum of these requests every second as a
1868
+ DELTA metric:
1869
+ 1. The system starts receiving at time=t_0.
1870
+ 2. A request is received, the system measures 1 request.
1871
+ 3. A request is received, the system measures 1 request.
1872
+ 4. A request is received, the system measures 1 request.
1873
+ 5. The 1 second collection cycle ends. A metric is exported for the
1874
+ number of requests received over the interval of time t_0 to
1875
+ t_0+1 with a value of 3.
1876
+ 6. A request is received, the system measures 1 request.
1877
+ 7. A request is received, the system measures 1 request.
1878
+ 8. The 1 second collection cycle ends. A metric is exported for the
1879
+ number of requests received over the interval of time t_0+1 to
1880
+ t_0+2 with a value of 2. */
1881
+ AGGREGATION_TEMPORALITY_DELTA: 1,
1882
+ /** CUMULATIVE is an AggregationTemporality for a metric aggregator which
1883
+ reports changes since a fixed start time. This means that current values
1884
+ of a CUMULATIVE metric depend on all previous measurements since the
1885
+ start time. Because of this, the sender is required to retain this state
1886
+ in some form. If this state is lost or invalidated, the CUMULATIVE metric
1887
+ values MUST be reset and a new fixed start time following the last
1888
+ reported measurement time sent MUST be used.
1889
+ For example, consider a system measuring the number of requests that
1890
+ it receives and reports the sum of these requests every second as a
1891
+ CUMULATIVE metric:
1892
+ 1. The system starts receiving at time=t_0.
1893
+ 2. A request is received, the system measures 1 request.
1894
+ 3. A request is received, the system measures 1 request.
1895
+ 4. A request is received, the system measures 1 request.
1896
+ 5. The 1 second collection cycle ends. A metric is exported for the
1897
+ number of requests received over the interval of time t_0 to
1898
+ t_0+1 with a value of 3.
1899
+ 6. A request is received, the system measures 1 request.
1900
+ 7. A request is received, the system measures 1 request.
1901
+ 8. The 1 second collection cycle ends. A metric is exported for the
1902
+ number of requests received over the interval of time t_0 to
1903
+ t_0+2 with a value of 5.
1904
+ 9. The system experiences a fault and loses state.
1905
+ 10. The system recovers and resumes receiving at time=t_1.
1906
+ 11. A request is received, the system measures 1 request.
1907
+ 12. The 1 second collection cycle ends. A metric is exported for the
1908
+ number of requests received over the interval of time t_1 to
1909
+ t_0+1 with a value of 1.
1910
+ Note: Even though, when reporting changes since last report time, using
1911
+ CUMULATIVE is valid, it is not recommended. This may cause problems for
1912
+ systems that do not use start_time to determine when the aggregation
1913
+ value was reset (e.g. Prometheus). */
1914
+ AGGREGATION_TEMPORALITY_CUMULATIVE: 2
1915
+ };
1916
+
1917
+ // ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect+effect@c7d1ffff31a3e2ae0b0b0796b742bddeb797269d/node_modules/effect/dist/unstable/observability/OtlpTracer.js
1918
+ var OtlpTracer_exports = {};
1919
+ __export(OtlpTracer_exports, {
1920
+ layer: () => layer4,
1921
+ layerFromConfig: () => layerFromConfig3,
1922
+ make: () => make8
1923
+ });
1924
+ var make8 = /* @__PURE__ */ fnUntraced(function* (options) {
1925
+ const otelResource = yield* fromConfig(options.resource);
1926
+ const serialization = yield* OtlpSerialization;
1927
+ const scope = {
1928
+ name: serviceNameUnsafe(otelResource)
1929
+ };
1930
+ const exporter = yield* make4({
1931
+ label: "OtlpTracer",
1932
+ url: options.url,
1933
+ headers: options.headers,
1934
+ exportInterval: options.exportInterval ?? seconds(5),
1935
+ maxBatchSize: options.maxBatchSize ?? 1e3,
1936
+ body(spans) {
1937
+ const data = {
1938
+ resourceSpans: [{
1939
+ resource: otelResource,
1940
+ scopeSpans: [{
1941
+ scope,
1942
+ spans
1943
+ }]
1944
+ }]
1945
+ };
1946
+ return [serialization.traces(data), void_];
1947
+ },
1948
+ shutdownTimeout: options.shutdownTimeout ?? seconds(3)
1949
+ });
1950
+ function exportFn(span) {
1951
+ if (!span.sampled) return;
1952
+ exporter.push(makeOtlpSpan(span));
1953
+ }
1954
+ return make({
1955
+ span(options2) {
1956
+ return new SpanImpl(options2, exportFn);
1957
+ },
1958
+ context: options.context ? function(primitive, fiber) {
1959
+ if (fiber.cache.span === void 0) {
1960
+ return primitive["~effect/Effect/evaluate"](fiber);
1961
+ }
1962
+ return options.context(primitive, fiber.cache.span);
1963
+ } : void 0
1964
+ });
1965
+ });
1966
+ var layer4 = /* @__PURE__ */ flow(make8, /* @__PURE__ */ effect(Tracer), /* @__PURE__ */ provideMerge(layerFlusher));
1967
+ var layerFromConfig3 = (options) => gen(function* () {
1968
+ const {
1969
+ disabled,
1970
+ endpoint: endpoint2,
1971
+ exporters: exporters2
1972
+ } = yield* all({
1973
+ disabled: Boolean("OTEL_SDK_DISABLED").pipe(withDefault(false)),
1974
+ endpoint: endpoint("TRACES"),
1975
+ exporters: exporters("TRACES")
1976
+ });
1977
+ if (disabled || !endpoint2 || !exporters2.includes("otlp")) {
1978
+ return layerFlusher;
1979
+ }
1980
+ const {
1981
+ baseTimeout,
1982
+ tracesTimeout,
1983
+ exportTimeout,
1984
+ scheduleDelay,
1985
+ maxBatchSize
1986
+ } = yield* all({
1987
+ baseTimeout: option(Int("OTEL_EXPORTER_OTLP_TIMEOUT")),
1988
+ tracesTimeout: option(Int("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT")),
1989
+ exportTimeout: option(Int("OTEL_BSP_EXPORT_TIMEOUT")),
1990
+ scheduleDelay: option(Int("OTEL_BSP_SCHEDULE_DELAY").pipe(map3(millis))),
1991
+ maxBatchSize: option(Int("OTEL_BSP_MAX_EXPORT_BATCH_SIZE"))
1992
+ });
1993
+ const shutdownTimeout = firstSomeOf([tracesTimeout, baseTimeout, exportTimeout]).pipe(map((_) => millis(_)));
1994
+ return layer4({
1995
+ url: endpoint2.toString(),
1996
+ resource: options?.resource,
1997
+ headers: options?.headers ?? (yield* headers("TRACES")),
1998
+ exportInterval: getOrUndefined(scheduleDelay),
1999
+ maxBatchSize: getOrUndefined(maxBatchSize),
2000
+ context: options?.context,
2001
+ shutdownTimeout: getOrUndefined(shutdownTimeout)
2002
+ });
2003
+ }).pipe(orDie, unwrap);
2004
+ var SpanImpl = class {
2005
+ _tag = "Span";
2006
+ name;
2007
+ parent;
2008
+ annotations;
2009
+ links;
2010
+ kind;
2011
+ sampled;
2012
+ export;
2013
+ status;
2014
+ _traceId = void 0;
2015
+ _spanId = void 0;
2016
+ _attributes = void 0;
2017
+ _events = void 0;
2018
+ constructor(options, exportFn) {
2019
+ this.name = options.name;
2020
+ this.parent = options.parent;
2021
+ this.annotations = options.annotations;
2022
+ this.links = options.links;
2023
+ this.kind = options.kind;
2024
+ this.sampled = options.sampled;
2025
+ this.export = exportFn;
2026
+ this.status = {
2027
+ _tag: "Started",
2028
+ startTime: options.startTime
2029
+ };
2030
+ }
2031
+ get traceId() {
2032
+ return this._traceId ??= isSome(this.parent) ? this.parent.value.traceId : randomHex(32);
2033
+ }
2034
+ get spanId() {
2035
+ return this._spanId ??= randomHex(16);
2036
+ }
2037
+ get attributes() {
2038
+ return this._attributes ??= /* @__PURE__ */ new Map();
2039
+ }
2040
+ get events() {
2041
+ return this._events ??= [];
2042
+ }
2043
+ end(endTime, exit) {
2044
+ this.status = {
2045
+ _tag: "Ended",
2046
+ startTime: this.status.startTime,
2047
+ endTime,
2048
+ exit
2049
+ };
2050
+ this.export(this);
2051
+ }
2052
+ attribute(key, value) {
2053
+ this.attributes.set(key, value);
2054
+ }
2055
+ event(name, startTime, attributes) {
2056
+ this.events.push([name, startTime, attributes]);
2057
+ }
2058
+ addLinks(links) {
2059
+ this.links.push(...links);
2060
+ }
2061
+ };
2062
+ var makeOtlpSpan = (self) => {
2063
+ const status = self.status;
2064
+ const attributes = self._attributes === void 0 ? [] : entriesToAttributes(self._attributes);
2065
+ const events = [];
2066
+ if (self._events !== void 0) {
2067
+ for (let i = 0; i < self._events.length; i++) {
2068
+ const [name, startTime, attributes2] = self._events[i];
2069
+ events.push({
2070
+ name,
2071
+ timeUnixNano: String(startTime),
2072
+ attributes: attributes2 ? entriesToAttributes(Object.entries(attributes2)) : [],
2073
+ droppedAttributesCount: 0
2074
+ });
2075
+ }
2076
+ }
2077
+ let otelStatus;
2078
+ if (status.exit._tag === "Success") {
2079
+ otelStatus = {
2080
+ code: StatusCode.Ok
2081
+ };
2082
+ } else if (hasInterruptsOnly(status.exit.cause)) {
2083
+ otelStatus = {
2084
+ code: StatusCode.Ok,
2085
+ message: "Interrupted"
2086
+ };
2087
+ attributes.push({
2088
+ key: "span.label",
2089
+ value: {
2090
+ stringValue: "\u26A0\uFE0E Interrupted"
2091
+ }
2092
+ }, {
2093
+ key: "status.interrupted",
2094
+ value: {
2095
+ boolValue: true
2096
+ }
2097
+ });
2098
+ } else {
2099
+ const errors = prettyErrors(status.exit.cause, {
2100
+ includeCauseInStack: true
2101
+ });
2102
+ otelStatus = {
2103
+ code: StatusCode.Error
2104
+ };
2105
+ if (errors.length > 0) {
2106
+ otelStatus.message = errors[0].message;
2107
+ for (const error of errors) {
2108
+ events.push({
2109
+ name: "exception",
2110
+ timeUnixNano: String(status.endTime),
2111
+ droppedAttributesCount: 0,
2112
+ attributes: [{
2113
+ "key": "exception.type",
2114
+ "value": {
2115
+ "stringValue": error.name
2116
+ }
2117
+ }, {
2118
+ "key": "exception.message",
2119
+ "value": {
2120
+ "stringValue": error.message
2121
+ }
2122
+ }, {
2123
+ "key": "exception.stacktrace",
2124
+ "value": {
2125
+ "stringValue": error.stack ?? "No stack trace available"
2126
+ }
2127
+ }]
2128
+ });
2129
+ }
2130
+ }
2131
+ }
2132
+ const links = [];
2133
+ for (let i = 0; i < self.links.length; i++) {
2134
+ const link = self.links[i];
2135
+ links.push({
2136
+ traceId: link.span.traceId,
2137
+ spanId: link.span.spanId,
2138
+ attributes: entriesToAttributes(Object.entries(link.attributes)),
2139
+ droppedAttributesCount: 0
2140
+ });
2141
+ }
2142
+ return {
2143
+ traceId: self.traceId,
2144
+ spanId: self.spanId,
2145
+ parentSpanId: isSome(self.parent) ? self.parent.value.spanId : void 0,
2146
+ name: self.name,
2147
+ kind: SpanKind[self.kind],
2148
+ startTimeUnixNano: String(status.startTime),
2149
+ endTimeUnixNano: String(status.endTime),
2150
+ attributes,
2151
+ droppedAttributesCount: 0,
2152
+ events,
2153
+ droppedEventsCount: 0,
2154
+ status: otelStatus,
2155
+ links,
2156
+ droppedLinksCount: 0
2157
+ };
2158
+ };
2159
+ var StatusCode = {
2160
+ Unset: 0,
2161
+ Ok: 1,
2162
+ Error: 2
2163
+ };
2164
+ var SpanKind = {
2165
+ unspecified: 0,
2166
+ internal: 1,
2167
+ server: 2,
2168
+ client: 3,
2169
+ producer: 4,
2170
+ consumer: 5
2171
+ };
2172
+
2173
+ // ../telemetry/src/layer.ts
2174
+ var telemetryLayer = (config, lifetime = "process", logger = Logger_exports.withConsoleError(Logger_exports.formatJson)) => {
2175
+ const resource = {
2176
+ serviceName: config.service,
2177
+ serviceVersion: config.version,
2178
+ attributes: { "deployment.environment.name": config.environment }
2179
+ };
2180
+ const signal = (target) => ({
2181
+ url: target.url,
2182
+ resource,
2183
+ ...target.headers === void 0 ? {} : { headers: Redacted_exports.value(target.headers) },
2184
+ exportInterval: lifetime === "event" ? "1 hour" : "1 second",
2185
+ shutdownTimeout: "3 seconds"
2186
+ });
2187
+ const console = Logger_exports.layer([logger]);
2188
+ return Layer_exports.mergeAll(
2189
+ Layer_exports.succeed(CurrentTelemetryConfig, config),
2190
+ config.traces === void 0 ? Layer_exports.empty : (
2191
+ // Credentials travel in provider headers and query strings this product does
2192
+ // not choose, so every exported span records only allowlisted HTTP attributes.
2193
+ // Record every operation. Caller-supplied sampling is correlation metadata,
2194
+ // not authority to suppress server diagnostics.
2195
+ spanAttributes(config.clock, true).pipe(
2196
+ Layer_exports.provideMerge(
2197
+ OtlpTracer_exports.layer(signal(config.traces)).pipe(
2198
+ Layer_exports.provide(OtlpSerialization_exports.layerJson)
2199
+ )
2200
+ )
2201
+ )
2202
+ ),
2203
+ config.logs === void 0 ? console : OtlpLogger_exports.layer({
2204
+ ...signal(config.logs),
2205
+ mergeWithExisting: true
2206
+ }).pipe(Layer_exports.provide(OtlpSerialization_exports.layerJson), Layer_exports.provideMerge(console)),
2207
+ config.metrics === void 0 ? Layer_exports.empty : OtlpMetrics_exports.layer({
2208
+ ...signal(config.metrics),
2209
+ exportInterval: "30 seconds",
2210
+ temporality: "delta"
2211
+ }).pipe(
2212
+ Layer_exports.provide(
2213
+ config.metricsProtocol === "http/json" ? OtlpSerialization_exports.layerJson : OtlpSerialization_exports.layerProtobuf
2214
+ )
2215
+ )
2216
+ ).pipe(
2217
+ Layer_exports.provide(telemetryHttpClient),
2218
+ // Export fibers capture services during construction. Their failure evidence
2219
+ // must reach the host logger even after the remote log exporter is closed.
2220
+ Layer_exports.provide(console),
2221
+ // Each event exports only its own measurements; process hosts share a process registry.
2222
+ Layer_exports.provideMerge(Layer_exports.sync(Metric_exports.MetricRegistry, () => /* @__PURE__ */ new Map()))
2223
+ );
2224
+ };
2225
+
2226
+ // ../telemetry/src/relay.ts
2227
+ var makeTelemetryForwarder = Effect_exports.gen(function* () {
2228
+ const fibers = yield* FiberSet_exports.make();
2229
+ const pending = yield* Semaphore_exports.make(16);
2230
+ const sender = yield* Semaphore_exports.make(1);
2231
+ const failed = (reason) => recordExportFailure("app").pipe(Effect_exports.annotateLogs({ "executor.telemetry.failure": reason }));
2232
+ yield* Effect_exports.addFinalizer(
2233
+ () => FiberSet_exports.awaitEmpty(fibers).pipe(
2234
+ Effect_exports.timeoutOption("3 seconds"),
2235
+ Effect_exports.flatMap((drained) => Option_exports.isNone(drained) ? failed("shutdown") : Effect_exports.void)
2236
+ )
2237
+ );
2238
+ return (batch, traceId, build) => FiberSet_exports.run(
2239
+ fibers,
2240
+ sender.withPermits(1)(
2241
+ forwardTelemetry(batch, traceId, build).pipe(Effect_exports.catch(() => failed("relay")))
2242
+ ).pipe(
2243
+ pending.withPermitsIfAvailable(1),
2244
+ Effect_exports.flatMap(
2245
+ (accepted) => Option_exports.isNone(accepted) ? failed("capacity") : Effect_exports.void
2246
+ )
2247
+ )
2248
+ ).pipe(Effect_exports.asVoid);
2249
+ });
2250
+ var payloadBytes = 262144;
2251
+ var encoder = new TextEncoder();
2252
+ var Payload = Schema_exports.String.check(
2253
+ Schema_exports.isMaxLength(payloadBytes),
2254
+ Schema_exports.makeFilter((body) => encoder.encode(body).byteLength <= payloadBytes)
2255
+ );
2256
+ var TelemetryBatch = Schema_exports.Struct({
2257
+ traces: Schema_exports.Array(Payload).check(Schema_exports.isMaxLength(4)),
2258
+ logs: Schema_exports.Array(Payload).check(Schema_exports.isMaxLength(4)),
2259
+ dropped: Schema_exports.Int.check(Schema_exports.isGreaterThanOrEqualTo(0))
2260
+ });
2261
+ var collectTelemetry = (effect2) => Effect_exports.gen(function* () {
2262
+ const traces = [];
2263
+ const logs = [];
2264
+ let dropped = 0;
2265
+ const capture = async (input, init) => {
2266
+ const request = new Request(input, init);
2267
+ const body = await request.text();
2268
+ if (new URL(request.url).pathname === "/v1/traces") {
2269
+ const payload = Schema_exports.decodeUnknownSync(TracePayload)(body);
2270
+ dropped += packRecords(
2271
+ payload.resourceSpans.flatMap(
2272
+ (resource) => resource.scopeSpans.flatMap((scope) => scope.spans)
2273
+ ),
2274
+ traces,
2275
+ '{"resourceSpans":[{"scopeSpans":[{"spans":[',
2276
+ "]}]}]}"
2277
+ );
2278
+ } else {
2279
+ const payload = Schema_exports.decodeUnknownSync(LogPayload)(body);
2280
+ dropped += packRecords(
2281
+ payload.resourceLogs.flatMap(
2282
+ (resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords)
2283
+ ),
2284
+ logs,
2285
+ '{"resourceLogs":[{"scopeLogs":[{"logRecords":[',
2286
+ "]}]}]}"
2287
+ );
2288
+ }
2289
+ return Response.json({});
2290
+ };
2291
+ const value = yield* effect2.pipe(
2292
+ Effect_exports.provide(
2293
+ telemetryLayer(
2294
+ {
2295
+ service: "executor-app",
2296
+ version: "invocation",
2297
+ environment: "isolated",
2298
+ clock: "WebSocketPair" in globalThis ? "cloudflare-io" : "system",
2299
+ traces: { url: "http://telemetry.internal/v1/traces" },
2300
+ logs: { url: "http://telemetry.internal/v1/logs" }
2301
+ },
2302
+ "event"
2303
+ )
2304
+ ),
2305
+ Effect_exports.provideService(FetchHttpClient_exports.Fetch, capture)
2306
+ );
2307
+ return { value, telemetry: { traces, logs, dropped } };
2308
+ });
2309
+ var packRecords = (records, target, prefix, suffix) => {
2310
+ let parts = [];
2311
+ const overhead = encoder.encode(prefix + suffix).byteLength;
2312
+ let bytes = overhead;
2313
+ let dropped = 0;
2314
+ const flush = () => {
2315
+ if (parts.length === 0) return;
2316
+ target.push(prefix + parts.join(",") + suffix);
2317
+ parts = [];
2318
+ bytes = overhead;
2319
+ };
2320
+ for (const record of records) {
2321
+ const encoded = JSON.stringify(record);
2322
+ const size = encoder.encode(encoded).byteLength;
2323
+ if (size + overhead > payloadBytes || target.length >= 4) {
2324
+ dropped++;
2325
+ continue;
2326
+ }
2327
+ if (bytes + size + (parts.length > 0 ? 1 : 0) > payloadBytes) flush();
2328
+ if (target.length >= 4) {
2329
+ dropped++;
2330
+ continue;
2331
+ }
2332
+ bytes += size + (parts.length > 0 ? 1 : 0);
2333
+ parts.push(encoded);
2334
+ }
2335
+ flush();
2336
+ return dropped;
2337
+ };
2338
+ var HexTrace = Schema_exports.String.check(Schema_exports.isPattern(/^[a-f0-9]{32}$/));
2339
+ var HexSpan = Schema_exports.String.check(Schema_exports.isPattern(/^[a-f0-9]{16}$/));
2340
+ var Span = Schema_exports.StructWithRest(Schema_exports.Struct({ traceId: HexTrace, spanId: HexSpan }), [
2341
+ Schema_exports.Record(Schema_exports.String, Schema_exports.Json)
2342
+ ]);
2343
+ var LogRecord = Schema_exports.StructWithRest(
2344
+ Schema_exports.Struct({ traceId: Schema_exports.optional(HexTrace), spanId: Schema_exports.optional(HexSpan) }),
2345
+ [Schema_exports.Record(Schema_exports.String, Schema_exports.Json)]
2346
+ );
2347
+ var TracePayload = Schema_exports.fromJsonString(
2348
+ Schema_exports.Struct({
2349
+ resourceSpans: Schema_exports.Array(
2350
+ Schema_exports.Struct({
2351
+ scopeSpans: Schema_exports.Array(
2352
+ Schema_exports.Struct({ spans: Schema_exports.Array(Span).check(Schema_exports.isMaxLength(1e3)) })
2353
+ )
2354
+ })
2355
+ )
2356
+ })
2357
+ );
2358
+ var LogPayload = Schema_exports.fromJsonString(
2359
+ Schema_exports.Struct({
2360
+ resourceLogs: Schema_exports.Array(
2361
+ Schema_exports.Struct({
2362
+ scopeLogs: Schema_exports.Array(
2363
+ Schema_exports.Struct({ logRecords: Schema_exports.Array(LogRecord).check(Schema_exports.isMaxLength(1e3)) })
2364
+ )
2365
+ })
2366
+ )
2367
+ })
2368
+ );
2369
+ var forwardTelemetry = (batch, traceId, build, service = "executor-app") => Effect_exports.gen(function* () {
2370
+ const config = yield* CurrentTelemetryConfig;
2371
+ if (config === void 0) return;
2372
+ const resource = {
2373
+ attributes: [
2374
+ { key: "service.name", value: { stringValue: service } },
2375
+ { key: "service.version", value: { stringValue: config.version } },
2376
+ { key: "deployment.environment.name", value: { stringValue: config.environment } },
2377
+ ...build === void 0 ? [] : [{ key: "executor.build.id", value: { stringValue: build } }]
2378
+ ]
2379
+ };
2380
+ const client = yield* HttpClient_exports.HttpClient;
2381
+ if (batch.dropped > 0) yield* recordExportFailure("app", "capacity", batch.dropped);
2382
+ for (const signal of ["traces", "logs"]) {
2383
+ const target = config[signal];
2384
+ if (target === void 0) continue;
2385
+ for (const body of batch[signal]) {
2386
+ const data = signal === "traces" ? yield* Schema_exports.decodeUnknownEffect(TracePayload)(body).pipe(
2387
+ Effect_exports.map((payload) => ({
2388
+ resourceSpans: [
2389
+ {
2390
+ resource,
2391
+ scopeSpans: [
2392
+ {
2393
+ scope: { name: service },
2394
+ spans: payload.resourceSpans.flatMap((r) => r.scopeSpans.flatMap((s) => s.spans)).filter((span) => traceId === void 0 || span.traceId === traceId)
2395
+ }
2396
+ ]
2397
+ }
2398
+ ]
2399
+ }))
2400
+ ) : yield* Schema_exports.decodeUnknownEffect(LogPayload)(body).pipe(
2401
+ Effect_exports.map((payload) => ({
2402
+ resourceLogs: [
2403
+ {
2404
+ resource,
2405
+ scopeLogs: [
2406
+ {
2407
+ scope: { name: service },
2408
+ logRecords: payload.resourceLogs.flatMap((r) => r.scopeLogs.flatMap((s) => s.logRecords)).filter((log) => traceId === void 0 || log.traceId === traceId)
2409
+ }
2410
+ ]
2411
+ }
2412
+ ]
2413
+ }))
2414
+ );
2415
+ yield* client.pipe(HttpClient_exports.filterStatusOk).execute(
2416
+ HttpClientRequest_exports.post(target.url).pipe(
2417
+ HttpClientRequest_exports.setHeaders(
2418
+ target.headers === void 0 ? {} : Redacted_exports.value(target.headers)
2419
+ ),
2420
+ HttpClientRequest_exports.bodyJsonUnsafe(data)
2421
+ )
2422
+ );
2423
+ }
2424
+ }
2425
+ }).pipe(
2426
+ Effect_exports.provide(telemetryHttpClient),
2427
+ Effect_exports.provideService(Tracer_exports.DisablePropagation, true),
2428
+ Effect_exports.timeout("3 seconds")
2429
+ );
2430
+
2431
+ // ../telemetry/src/trace-context.ts
2432
+ var TraceContext = Schema_exports.Struct({
2433
+ traceId: Schema_exports.String.check(Schema_exports.isPattern(/^(?!0{32}$)[a-f0-9]{32}$/)),
2434
+ spanId: Schema_exports.String.check(Schema_exports.isPattern(/^(?!0{16}$)[a-f0-9]{16}$/)),
2435
+ sampled: Schema_exports.Boolean
2436
+ });
2437
+ var currentTraceContext = Effect_exports.currentSpan.pipe(
2438
+ Effect_exports.option,
2439
+ Effect_exports.map(
2440
+ Option_exports.map((span) => ({
2441
+ traceId: span.traceId,
2442
+ spanId: span.spanId,
2443
+ sampled: span.sampled
2444
+ }))
2445
+ ),
2446
+ Effect_exports.map(Option_exports.getOrUndefined)
2447
+ );
2448
+ var externalTrace = (input) => Schema_exports.decodeUnknownOption(TraceContext)(input).pipe(
2449
+ Option_exports.map((trace) => Tracer_exports.externalSpan(trace))
2450
+ );
2451
+ var traceLinks = (input, relationship) => {
2452
+ const span = externalTrace(input);
2453
+ return Option_exports.isSome(span) ? [{ span: span.value, attributes: { "executor.link.kind": relationship } }] : [];
2454
+ };
2455
+
2456
+ // ../telemetry/src/pending-span.ts
2457
+ var pendingSpan = (name, options) => Effect_exports.gen(function* () {
2458
+ const span = yield* Effect_exports.makeSpan(name, options);
2459
+ const clock = yield* Clock_exports.Clock;
2460
+ let pending = true;
2461
+ const close = (exit, reached) => Effect_exports.sync(() => {
2462
+ if (!pending) return;
2463
+ pending = false;
2464
+ span.attribute("executor.milestone.reached", reached);
2465
+ span.end(clock.currentTimeNanosUnsafe(), exit);
2466
+ });
2467
+ yield* Effect_exports.addFinalizer((exit) => close(exit, false));
2468
+ return {
2469
+ span,
2470
+ finish: (exit) => close(exit, Exit_exports.isSuccess(exit))
2471
+ };
2472
+ });
2473
+
2474
+ export {
2475
+ CurrentTelemetryConfig,
2476
+ OtlpExporter_exports,
2477
+ telemetryLayer,
2478
+ captureTelemetry,
2479
+ withRemoteSpan,
2480
+ invocationFetch,
2481
+ collectTelemetry,
2482
+ TraceContext,
2483
+ externalTrace,
2484
+ traceLinks,
2485
+ pendingSpan
2486
+ };