inspeffct 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import * as NodeRuntime from '@effect/platform-node/NodeRuntime';
3
3
  import * as NodeServices from '@effect/platform-node/NodeServices';
4
- import * as Effect8 from 'effect/Effect';
4
+ import * as Effect10 from 'effect/Effect';
5
5
  import * as Command5 from 'effect/unstable/cli/Command';
6
6
  import * as Argument2 from 'effect/unstable/cli/Argument';
7
- import * as Context3 from 'effect/Context';
7
+ import * as Context4 from 'effect/Context';
8
8
  import * as Fiber from 'effect/Fiber';
9
9
  import * as FileSystem from 'effect/FileSystem';
10
- import * as Layer7 from 'effect/Layer';
11
- import * as Schema3 from 'effect/Schema';
10
+ import * as Layer8 from 'effect/Layer';
11
+ import * as Schema from 'effect/Schema';
12
12
  import * as Stream from 'effect/Stream';
13
13
  import * as Formatter from 'effect/Formatter';
14
14
  import * as SchemaTransformation2 from 'effect/SchemaTransformation';
@@ -20,30 +20,31 @@ import * as Queue2 from 'effect/Queue';
20
20
  import * as Socket from 'effect/unstable/socket/Socket';
21
21
  import * as Chunk from 'effect/Chunk';
22
22
  import * as Ref from 'effect/Ref';
23
+ import * as Random from 'effect/Random';
23
24
  import * as SqliteClient from '@effect/sql-sqlite-node/SqliteClient';
24
- import * as Cause from 'effect/Cause';
25
- import * as Exit from 'effect/Exit';
26
- import * as Option4 from 'effect/Option';
25
+ import * as Struct5 from 'effect/Struct';
27
26
  import * as Migrator from 'effect/unstable/sql/Migrator';
28
- import * as SqlClient7 from 'effect/unstable/sql/SqlClient';
27
+ import * as SqlClient5 from 'effect/unstable/sql/SqlClient';
29
28
  import * as SqlSchema from 'effect/unstable/sql/SqlSchema';
30
- import * as Crypto from 'crypto';
29
+ import * as SchemaGetter from 'effect/SchemaGetter';
31
30
  import { flow } from 'effect/Function';
32
31
  import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem';
33
32
  import * as NodePath from '@effect/platform-node/NodePath';
34
33
  import * as Flag3 from 'effect/unstable/cli/Flag';
35
34
  import * as NodeSocketServer from '@effect/platform-node/NodeSocketServer';
35
+ import * as crypto from 'crypto';
36
36
  import * as fs from 'fs';
37
37
  import * as os from 'os';
38
38
  import * as path from 'path';
39
+ import * as Console2 from 'effect/Console';
40
+ import * as Option3 from 'effect/Option';
39
41
  import * as ChildProcess from 'effect/unstable/process/ChildProcess';
40
- import * as Console from 'effect/Console';
41
42
  import * as Duration from 'effect/Duration';
42
43
  import * as Graph from 'effect/Graph';
43
44
 
44
- var BestEffortAny = Schema3.Any.pipe(
45
- Schema3.decodeTo(
46
- Schema3.Unknown,
45
+ var BestEffortAny = Schema.Any.pipe(
46
+ Schema.decodeTo(
47
+ Schema.Unknown,
47
48
  SchemaTransformation2.transform({
48
49
  decode: (input) => input,
49
50
  encode: (input) => {
@@ -56,221 +57,193 @@ var BestEffortAny = Schema3.Any.pipe(
56
57
  })
57
58
  )
58
59
  ).annotate({ identifier: "BestEffortAny" });
59
- var InstrumentationId = Schema3.String.annotate({ identifier: "InstrumentationId" });
60
- var RequestId = Schema3.String.annotate({ identifier: "RequestId" });
61
- var ProtocolVersion = Schema3.Literal(1).annotate({ identifier: "ProtocolVersion" });
62
- var VariableReferenceId = Schema3.TaggedStruct("VariableReference", {
60
+ var InstrumentationId = Schema.String.annotate({ identifier: "InstrumentationId" });
61
+ var RequestId = Schema.String.annotate({ identifier: "RequestId" });
62
+ var ProtocolVersion = Schema.Literal(1).annotate({ identifier: "ProtocolVersion" });
63
+ var VariableReferenceId = Schema.TaggedStruct("VariableReference", {
63
64
  instrumentationId: InstrumentationId,
64
65
  requestId: RequestId,
65
- index: Schema3.String
66
+ index: Schema.String
66
67
  }).annotate({ identifier: "VariableReferenceId" });
67
- var SpanAndTraceId = Schema3.Struct({
68
- traceId: Schema3.String,
69
- spanId: Schema3.String
70
- }).annotate({ identifier: "SpanAndTraceId" });
71
- var SpanStatusStarted = Schema3.TaggedStruct("Started", {
72
- startTime: Schema3.BigInt
68
+ var SpanStatusStarted = Schema.TaggedStruct("Started", {
69
+ startTime: Schema.BigInt
73
70
  }).annotate({ identifier: "SpanStatusStarted" });
74
- var FiberIdEncoded = Schema3.Union([
75
- Schema3.TaggedStruct("None", {}),
76
- Schema3.TaggedStruct("Runtime", {
77
- id: Schema3.Number,
78
- startTimeMillis: Schema3.Number
79
- }),
80
- Schema3.TaggedStruct("Composite", {
81
- left: Schema3.suspend(() => FiberIdEncoded),
82
- right: Schema3.suspend(() => FiberIdEncoded)
83
- })
84
- ]).annotate({ identifier: "FiberIdEncoded" });
85
- var CauseEncoded3 = Schema3.Union([
86
- Schema3.TaggedStruct("Empty", {}),
87
- Schema3.TaggedStruct("Fail", { error: BestEffortAny }),
88
- Schema3.TaggedStruct("Die", { defect: BestEffortAny }),
89
- Schema3.TaggedStruct("Interrupt", { fiberId: FiberIdEncoded }),
90
- Schema3.TaggedStruct("Sequential", {
91
- left: Schema3.suspend(() => CauseEncoded3),
92
- right: Schema3.suspend(() => CauseEncoded3)
93
- }),
94
- Schema3.TaggedStruct("Parallel", {
95
- left: Schema3.suspend(() => CauseEncoded3),
96
- right: Schema3.suspend(() => CauseEncoded3)
97
- })
98
- ]).annotate({ identifier: "CauseEncoded3" });
99
- var SpanExit = Schema3.Union([
100
- Schema3.TaggedStruct("Failure", { cause: CauseEncoded3 }),
101
- Schema3.TaggedStruct("Success", { value: BestEffortAny })
102
- ]).annotate({ identifier: "SpanExit" });
103
- var SpanStatusEnded = Schema3.TaggedStruct("Ended", {
104
- startTime: Schema3.BigInt,
105
- endTime: Schema3.BigInt,
71
+ var SpanExit = Schema.Exit(BestEffortAny, BestEffortAny, BestEffortAny).annotate({ identifier: "SpanExit" });
72
+ var SpanStatusEnded = Schema.TaggedStruct("Ended", {
73
+ startTime: Schema.BigInt,
74
+ endTime: Schema.BigInt,
106
75
  exit: SpanExit
107
76
  }).annotate({ identifier: "SpanStatusEnded" });
108
- var SpanStatus = Schema3.Union([SpanStatusStarted, SpanStatusEnded]).annotate({
77
+ var SpanStatus = Schema.Union([SpanStatusStarted, SpanStatusEnded]).annotate({
109
78
  identifier: "SpanStatus"
110
79
  });
111
- var SpanAttributes = Schema3.Array(
112
- Schema3.Tuple([Schema3.String, Schema3.Unknown])
80
+ var SpanAttributes = Schema.Array(
81
+ Schema.Tuple([Schema.String, Schema.Unknown])
113
82
  ).annotate({ identifier: "SpanAttributes" });
114
- var ExternalSpan = Schema3.TaggedStruct("ExternalSpan", {
115
- spanId: Schema3.String,
116
- traceId: Schema3.String,
117
- sampled: Schema3.Boolean
83
+ var ExternalSpan = Schema.TaggedStruct("ExternalSpan", {
84
+ spanId: Schema.String,
85
+ traceId: Schema.String,
86
+ sampled: Schema.Boolean
118
87
  }).annotate({ identifier: "ExternalSpan" });
119
- var Span = Schema3.TaggedStruct("Span", {
120
- spanId: Schema3.String,
121
- traceId: Schema3.String,
122
- name: Schema3.String,
123
- sampled: Schema3.Boolean,
88
+ var Span = Schema.TaggedStruct("Span", {
89
+ spanId: Schema.String,
90
+ traceId: Schema.String,
91
+ name: Schema.String,
92
+ sampled: Schema.Boolean,
124
93
  attributes: SpanAttributes,
125
94
  status: SpanStatus,
126
- parent: Schema3.NullOr(SpanAndTraceId)
95
+ parentSpanId: Schema.NullOr(Schema.String)
127
96
  }).annotate({ identifier: "Span" });
128
- var AnySpan = Schema3.Union([Span, ExternalSpan]).annotate({ identifier: "AnySpan" });
129
- var SpanEvent = Schema3.Struct({
130
- spanId: Schema3.String,
131
- traceId: Schema3.String,
132
- name: Schema3.String,
133
- time: Schema3.BigInt,
97
+ var AnySpan = Schema.Union([Span, ExternalSpan]).annotate({ identifier: "AnySpan" });
98
+ var SpanEvent = Schema.Struct({
99
+ spanId: Schema.String,
100
+ traceId: Schema.String,
101
+ name: Schema.String,
102
+ time: Schema.BigInt,
134
103
  attributes: SpanAttributes
135
104
  }).annotate({ identifier: "SpanEvent" });
136
- var SpanLink = Schema3.Struct({
105
+ var SpanLink = Schema.Struct({
137
106
  /** The span that has the link */
138
- spanId: Schema3.String,
139
- traceId: Schema3.String,
107
+ spanId: Schema.String,
108
+ traceId: Schema.String,
140
109
  /** The linked span */
141
- linkedSpanId: Schema3.String,
142
- linkedTraceId: Schema3.String,
110
+ linkedSpanId: Schema.String,
111
+ linkedTraceId: Schema.String,
143
112
  attributes: SpanAttributes
144
113
  }).annotate({ identifier: "SpanLink" });
145
- var FiberInfo = Schema3.TaggedStruct("FiberInfo", {
146
- id: Schema3.String,
147
- isCurrent: Schema3.Boolean,
148
- currentSpan: Schema3.NullOr(AnySpan)
114
+ var FiberInfo = Schema.TaggedStruct("FiberInfo", {
115
+ id: Schema.String,
116
+ isCurrent: Schema.Boolean,
117
+ currentSpan: Schema.NullOr(AnySpan)
149
118
  }).annotate({ identifier: "FiberInfo" });
150
119
  var commonOutFields = {
151
120
  protocolVersion: ProtocolVersion,
152
121
  instrumentationId: InstrumentationId
153
122
  };
154
- var InitNotification = Schema3.TaggedStruct("InitNotification", {
123
+ var InitNotification = Schema.TaggedStruct("InitNotification", {
155
124
  ...commonOutFields,
156
125
  /** Inspector WebSocket URL (ws://...) if available */
157
- inspectorURL: Schema3.NullOr(Schema3.String),
126
+ inspectorURL: Schema.NullOr(Schema.String),
158
127
  /** Whether the process is waiting for debugger to attach */
159
- waitingForDebugger: Schema3.Boolean
128
+ waitingForDebugger: Schema.Boolean
160
129
  }).annotate({ identifier: "InitNotification" });
161
- var PingNotification = Schema3.TaggedStruct("PingNotification", {
130
+ var PingNotification = Schema.TaggedStruct("PingNotification", {
162
131
  ...commonOutFields
163
132
  }).annotate({ identifier: "PingNotification" });
164
- var TracerSpanNotification = Schema3.TaggedStruct("TracerSpanNotification", {
133
+ var TracerSpanNotification = Schema.TaggedStruct("TracerSpanNotification", {
165
134
  ...commonOutFields,
166
135
  span: AnySpan
167
136
  }).annotate({ identifier: "TracerSpanNotification" });
168
- var TracerSpanEventNotification = Schema3.TaggedStruct("TracerSpanEventNotification", {
137
+ var TracerSpanEventNotification = Schema.TaggedStruct("TracerSpanEventNotification", {
169
138
  ...commonOutFields,
170
139
  event: SpanEvent
171
140
  }).annotate({ identifier: "TracerSpanEventNotification" });
172
- var TracerSpanLinkNotification = Schema3.TaggedStruct("TracerSpanLinkNotification", {
141
+ var TracerSpanLinkNotification = Schema.TaggedStruct("TracerSpanLinkNotification", {
173
142
  ...commonOutFields,
174
143
  link: SpanLink
175
144
  }).annotate({ identifier: "TracerSpanLinkNotification" });
176
- var VariableReferenceInfo = Schema3.TaggedStruct("VariableReferenceInfo", {
145
+ var VariableReferenceInfo = Schema.TaggedStruct("VariableReferenceInfo", {
177
146
  ...commonOutFields,
178
147
  requestId: RequestId,
179
148
  variableReferenceId: VariableReferenceId,
180
- value: Schema3.NullOr(Schema3.Struct({
181
- name: Schema3.NullOr(Schema3.String),
182
- value: Schema3.NullOr(Schema3.String),
183
- children: Schema3.Array(VariableReferenceId)
149
+ value: Schema.NullOr(Schema.Struct({
150
+ name: Schema.NullOr(Schema.String),
151
+ value: Schema.NullOr(Schema.String),
152
+ children: Schema.Array(VariableReferenceId)
184
153
  }))
185
154
  }).annotate({ identifier: "VariableReferenceInfo" });
186
- var ResourcesForRequestReleased = Schema3.TaggedStruct("ResourcesForRequestReleased", {
155
+ var ResourcesForRequestReleased = Schema.TaggedStruct("ResourcesForRequestReleased", {
187
156
  ...commonOutFields,
188
157
  requestId: RequestId,
189
- associatedRequestIds: Schema3.Array(RequestId)
158
+ associatedRequestIds: Schema.Array(RequestId)
190
159
  }).annotate({ identifier: "ResourcesForRequestReleased" });
191
- var CurrentFibersInfo = Schema3.TaggedStruct("CurrentFibersInfo", {
160
+ var CurrentFibersInfo = Schema.TaggedStruct("CurrentFibersInfo", {
192
161
  ...commonOutFields,
193
162
  requestId: RequestId,
194
- fibers: Schema3.Array(FiberInfo)
163
+ fibers: Schema.Array(FiberInfo)
195
164
  }).annotate({ identifier: "CurrentFibersInfo" });
196
- var OutMessage = Schema3.Union([
197
- InitNotification,
198
- PingNotification,
199
- TracerSpanNotification,
200
- TracerSpanEventNotification,
201
- TracerSpanLinkNotification,
202
- VariableReferenceInfo,
203
- ResourcesForRequestReleased,
204
- CurrentFibersInfo
205
- ]).annotate({ identifier: "OutMessage" });
165
+ var OutMessage = Schema.toCodecJson(
166
+ Schema.Union([
167
+ InitNotification,
168
+ PingNotification,
169
+ TracerSpanNotification,
170
+ TracerSpanEventNotification,
171
+ TracerSpanLinkNotification,
172
+ VariableReferenceInfo,
173
+ ResourcesForRequestReleased,
174
+ CurrentFibersInfo
175
+ ]).annotate({ identifier: "OutMessage" })
176
+ );
206
177
  var commonInFields = {
207
178
  protocolVersion: ProtocolVersion,
208
179
  requestId: RequestId
209
180
  };
210
- var VariableReferenceInfoRequest = Schema3.TaggedStruct("VariableReferenceInfoRequest", {
181
+ var VariableReferenceInfoRequest = Schema.TaggedStruct("VariableReferenceInfoRequest", {
211
182
  ...commonInFields,
212
183
  variableReferenceId: VariableReferenceId
213
184
  }).annotate({ identifier: "VariableReferenceInfoRequest" });
214
- var ReleaseResourcesForRequest = Schema3.TaggedStruct("ReleaseResourcesForRequest", {
185
+ var ReleaseResourcesForRequest = Schema.TaggedStruct("ReleaseResourcesForRequest", {
215
186
  ...commonInFields,
216
- associatedRequestIds: Schema3.Array(RequestId)
187
+ associatedRequestIds: Schema.Array(RequestId)
217
188
  }).annotate({ identifier: "ReleaseResourcesForRequest" });
218
- var CaptureCurrentFibersRequest = Schema3.TaggedStruct("CaptureCurrentFibersRequest", {
189
+ var CaptureCurrentFibersRequest = Schema.TaggedStruct("CaptureCurrentFibersRequest", {
219
190
  ...commonInFields
220
191
  }).annotate({ identifier: "CaptureCurrentFibersRequest" });
221
- Schema3.Union([
222
- VariableReferenceInfoRequest,
223
- ReleaseResourcesForRequest,
224
- CaptureCurrentFibersRequest
225
- ]).annotate({ identifier: "InMessage" });
226
- var BootloaderPath = class extends Context3.Service()("inspeffct/BootloaderPath") {
192
+ Schema.toCodecJson(
193
+ Schema.Union([
194
+ VariableReferenceInfoRequest,
195
+ ReleaseResourcesForRequest,
196
+ CaptureCurrentFibersRequest
197
+ ]).annotate({ identifier: "InMessage" })
198
+ );
199
+ var BootloaderPath = class extends Context4.Service()("inspeffct/BootloaderPath") {
227
200
  };
228
- var getPath = Effect8.map(BootloaderPath, (service) => service.path);
229
- var computeBootloaderPath = Effect8.gen(function* () {
201
+ var getPath = Effect10.map(BootloaderPath, (service) => service.path);
202
+ var computeBootloaderPath = Effect10.gen(function* () {
230
203
  const path2 = yield* Path.Path;
231
204
  const binDir = path2.dirname(import.meta.url.replace("file://", ""));
232
205
  return path2.join(binDir, "bootloader.cjs");
233
206
  });
234
- var layer = Layer7.effect(
207
+ var layer = Layer8.effect(
235
208
  BootloaderPath,
236
- Effect8.map(computeBootloaderPath, (path2) => BootloaderPath.of({ path: path2 }))
209
+ Effect10.map(computeBootloaderPath, (path2) => BootloaderPath.of({ path: path2 }))
237
210
  );
238
- var CdpRequest = Schema3.Struct({
239
- id: Schema3.Number,
240
- method: Schema3.String,
241
- params: Schema3.optional(Schema3.Unknown),
242
- sessionId: Schema3.optional(Schema3.String)
211
+ var CdpRequest = Schema.Struct({
212
+ id: Schema.Number,
213
+ method: Schema.String,
214
+ params: Schema.optional(Schema.Unknown),
215
+ sessionId: Schema.optional(Schema.String)
243
216
  });
244
- var BindingCalledParams = Schema3.Struct({
245
- name: Schema3.String,
246
- payload: Schema3.String,
247
- executionContextId: Schema3.Number
217
+ var BindingCalledParams = Schema.Struct({
218
+ name: Schema.String,
219
+ payload: Schema.String,
220
+ executionContextId: Schema.Number
248
221
  });
249
- var GenericCdpEvent = Schema3.Struct({
250
- method: Schema3.String,
251
- params: Schema3.optional(Schema3.Unknown),
252
- sessionId: Schema3.optional(Schema3.String)
222
+ var GenericCdpEvent = Schema.Struct({
223
+ method: Schema.String,
224
+ params: Schema.optional(Schema.Unknown),
225
+ sessionId: Schema.optional(Schema.String)
253
226
  });
254
- var BindingCalledEvent = Schema3.Struct({
255
- method: Schema3.Literal("Runtime.bindingCalled"),
227
+ var BindingCalledEvent = Schema.Struct({
228
+ method: Schema.Literal("Runtime.bindingCalled"),
256
229
  params: BindingCalledParams,
257
- sessionId: Schema3.optional(Schema3.String)
230
+ sessionId: Schema.optional(Schema.String)
258
231
  });
259
- var CdpEvent = Schema3.Union(
232
+ var CdpEvent = Schema.Union(
260
233
  [BindingCalledEvent, GenericCdpEvent]
261
234
  );
262
- var CdpError = class extends Schema3.TaggedErrorClass()("CdpError", {
263
- message: Schema3.String,
264
- code: Schema3.optional(Schema3.Number)
235
+ var CdpError = class extends Schema.TaggedErrorClass()("CdpError", {
236
+ message: Schema.String,
237
+ code: Schema.optional(Schema.Number)
265
238
  }) {
266
239
  };
267
- var CdpClient = class extends Context3.Service()("inspeffct/CdpClient") {
240
+ var CdpClient = class extends Context4.Service()("inspeffct/CdpClient") {
268
241
  };
269
242
  var isCdpEvent = (msg) => typeof msg === "object" && msg !== null && "method" in msg && typeof msg.method === "string" && !("id" in msg);
270
243
  var isCdpResponse = (msg) => typeof msg === "object" && msg !== null && "id" in msg && typeof msg.id === "number";
271
- var makeConnection = (url) => Effect8.gen(function* () {
244
+ var makeConnection = (url) => Effect10.gen(function* () {
272
245
  const socket = yield* Socket.makeWebSocket(url).pipe(
273
- Effect8.mapError((e) => new CdpError({ message: `Failed to connect to ${url}: ${e}` }))
246
+ Effect10.mapError((e) => new CdpError({ message: `Failed to connect to ${url}: ${e}` }))
274
247
  );
275
248
  const outgoing = yield* Queue2.unbounded();
276
249
  const eventsPubSub = yield* PubSub2.unbounded();
@@ -279,19 +252,19 @@ var makeConnection = (url) => Effect8.gen(function* () {
279
252
  yield* Stream.fromQueue(outgoing).pipe(
280
253
  Stream.pipeThroughChannel(
281
254
  ChannelSchema.duplexUnknown(Socket.toChannelString(socket), {
282
- inputSchema: Schema3.fromJsonString(CdpRequest),
283
- outputSchema: Schema3.fromJsonString(Schema3.Unknown)
255
+ inputSchema: Schema.fromJsonString(CdpRequest),
256
+ outputSchema: Schema.fromJsonString(Schema.Unknown)
284
257
  })
285
258
  ),
286
259
  Stream.runForEach(
287
- (msg) => Effect8.gen(function* () {
260
+ (msg) => Effect10.gen(function* () {
288
261
  if (isCdpResponse(msg)) {
289
262
  const resume = pendingRequests.get(msg.id);
290
263
  if (resume) {
291
264
  pendingRequests.delete(msg.id);
292
265
  if (msg.error) {
293
266
  resume(
294
- Effect8.fail(
267
+ Effect10.fail(
295
268
  new CdpError({
296
269
  message: msg.error.message,
297
270
  code: msg.error.code
@@ -299,28 +272,28 @@ var makeConnection = (url) => Effect8.gen(function* () {
299
272
  )
300
273
  );
301
274
  } else {
302
- resume(Effect8.succeed(msg.result));
275
+ resume(Effect10.succeed(msg.result));
303
276
  }
304
277
  }
305
278
  }
306
279
  if (isCdpEvent(msg)) {
307
- const decoded = yield* Schema3.decodeUnknownEffect(CdpEvent)(msg).pipe(
308
- Effect8.mapError((error) => new CdpError({ message: String(error) }))
280
+ const decoded = yield* Schema.decodeUnknownEffect(CdpEvent)(msg).pipe(
281
+ Effect10.mapError((error) => new CdpError({ message: String(error) }))
309
282
  );
310
283
  yield* PubSub2.publish(eventsPubSub, decoded);
311
284
  }
312
- }).pipe(Effect8.catchCause(Effect8.logDebug))
285
+ }).pipe(Effect10.catchCause(Effect10.logDebug))
313
286
  ),
314
- Effect8.ensuring(Queue2.shutdown(outgoing)),
315
- Effect8.catchCause(Effect8.logDebug),
316
- Effect8.forkScoped
287
+ Effect10.ensuring(Queue2.shutdown(outgoing)),
288
+ Effect10.catchCause(Effect10.logDebug),
289
+ Effect10.forkScoped
317
290
  );
318
291
  const request = (method, params) => {
319
292
  const id = nextId++;
320
- return Effect8.callback((resume) => {
293
+ return Effect10.callback((resume) => {
321
294
  pendingRequests.set(id, resume);
322
295
  Queue2.offerUnsafe(outgoing, { id, method, params });
323
- return Effect8.sync(() => {
296
+ return Effect10.sync(() => {
324
297
  pendingRequests.delete(id);
325
298
  });
326
299
  });
@@ -332,55 +305,169 @@ var makeConnection = (url) => Effect8.gen(function* () {
332
305
  events
333
306
  };
334
307
  });
335
- var layer2 = Layer7.effect(
308
+ var layer2 = Layer8.effect(
336
309
  CdpClient,
337
- Effect8.gen(function* () {
310
+ Effect10.gen(function* () {
338
311
  const wsConstructor = yield* Socket.WebSocketConstructor;
339
312
  return CdpClient.of({
340
313
  connect: (url) => makeConnection(url).pipe(
341
- Effect8.provideService(Socket.WebSocketConstructor, wsConstructor)
314
+ Effect10.provideService(Socket.WebSocketConstructor, wsConstructor)
342
315
  )
343
316
  });
344
317
  })
345
318
  ).pipe(
346
- Layer7.provide(NodeSocket.layerWebSocketConstructor)
319
+ Layer8.provide(NodeSocket.layerWebSocketConstructor)
347
320
  );
348
- var create_otel_tables_default = Effect8.gen(function* () {
349
- const sql = yield* SqlClient7.SqlClient;
350
- yield* sql`
351
- CREATE TABLE resources (
352
- id INTEGER PRIMARY KEY AUTOINCREMENT,
353
- attributes_hash TEXT NOT NULL UNIQUE,
354
- attributes TEXT NOT NULL DEFAULT '{}',
355
- schema_url TEXT,
356
- dropped_attributes_count INTEGER NOT NULL DEFAULT 0
357
- )
358
- `.pipe(Effect8.withSpan("create_resources_table"));
359
- yield* sql`
360
- CREATE TABLE scopes (
361
- id INTEGER PRIMARY KEY AUTOINCREMENT,
362
- name TEXT NOT NULL,
363
- version TEXT NOT NULL DEFAULT '',
364
- attributes TEXT NOT NULL DEFAULT '{}',
365
- schema_url TEXT,
366
- dropped_attributes_count INTEGER NOT NULL DEFAULT 0,
367
- UNIQUE(name, version)
368
- )
369
- `.pipe(Effect8.withSpan("create_scopes_table"));
321
+ var randomByte = Random.nextIntBetween(0, 256, { halfOpen: true });
322
+ var randomUUID = Effect10.gen(function* () {
323
+ const bytes = yield* Effect10.all(Array.from({ length: 16 }, () => randomByte));
324
+ bytes[6] = bytes[6] & 15 | 64;
325
+ bytes[8] = bytes[8] & 63 | 128;
326
+ const hex = bytes.map((byte) => byte.toString(16).padStart(2, "0"));
327
+ return [
328
+ hex.slice(0, 4).join(""),
329
+ hex.slice(4, 6).join(""),
330
+ hex.slice(6, 8).join(""),
331
+ hex.slice(8, 10).join(""),
332
+ hex.slice(10, 16).join("")
333
+ ].join("-");
334
+ });
335
+ var ExecutionId = class extends Context4.Service()("inspeffct/ExecutionId") {
336
+ };
337
+ var layer3 = Layer8.effect(ExecutionId, randomUUID);
338
+ var isSchema = (u) => typeof u === "object" && u !== null && "ast" in u;
339
+ var getMembers = (schema) => "members" in schema && Array.isArray(schema.members) ? schema.members : "cases" in schema ? Object.values(schema.cases) : [schema];
340
+ var evolveNested = (schema, evolve2) => {
341
+ if ("fields" in schema) {
342
+ return schema.mapFields((fields) => ({
343
+ ...fields,
344
+ ...Object.fromEntries(Object.entries(evolve2).filter(([key]) => Object.hasOwn(fields, key)))
345
+ }));
346
+ }
347
+ if ("members" in schema && Array.isArray(schema.members)) {
348
+ return schema.mapMembers(
349
+ (members) => members.map((member) => evolveNested(member, evolve2))
350
+ );
351
+ }
352
+ if ("cases" in schema) {
353
+ return Schema.Union(
354
+ Object.values(schema.cases).map((member) => evolveNested(member, evolve2))
355
+ );
356
+ }
357
+ return schema;
358
+ };
359
+ var encodeStruct = (config) => (self) => {
360
+ const evolve2 = config.evolve ?? {};
361
+ const rename = config.rename ?? {};
362
+ const target = self.mapFields((fields) => {
363
+ const next = { ...fields };
364
+ for (const key in evolve2) {
365
+ if (!Object.hasOwn(fields, key)) {
366
+ continue;
367
+ }
368
+ const value = evolve2[key];
369
+ if (isSchema(value)) {
370
+ next[key] = value;
371
+ } else if (typeof value === "object" && value !== null) {
372
+ next[key] = evolveNested(fields[key], value);
373
+ }
374
+ }
375
+ return next;
376
+ });
377
+ const nestedKeys = Object.entries(rename).filter(([, value]) => typeof value === "object" && value !== null).map(([key]) => key);
378
+ if (nestedKeys.length > 1) {
379
+ throw new Error("encodeStruct currently supports one unnested field");
380
+ }
381
+ const unnestedKey = nestedKeys[0];
382
+ const flatToNested = {};
383
+ const rootToFlat = {};
384
+ const addField = (fields, fieldKey, field2) => {
385
+ if (Object.hasOwn(fields, fieldKey)) {
386
+ throw new Error(`Cannot encode struct: encoded key "${fieldKey}" already exists`);
387
+ }
388
+ fields[fieldKey] = field2;
389
+ };
390
+ const makeEncodedMember = (member) => {
391
+ const fields = {};
392
+ for (const key in target.fields) {
393
+ if (key === unnestedKey) {
394
+ if (member === void 0 || !("fields" in member)) {
395
+ throw new Error(`Expected "${key}" to be a struct or union of structs`);
396
+ }
397
+ const nestedRename = rename[key];
398
+ const memberFields = member.fields;
399
+ for (const nestedKey in memberFields) {
400
+ const flatKey = String(nestedRename[nestedKey] ?? `${key}_${nestedKey}`);
401
+ addField(fields, flatKey, Schema.toEncoded(memberFields[nestedKey]));
402
+ flatToNested[flatKey] = nestedKey;
403
+ }
404
+ } else {
405
+ const flatKey = typeof rename[key] === "string" || typeof rename[key] === "number" || typeof rename[key] === "symbol" ? String(rename[key]) : key;
406
+ addField(fields, flatKey, Schema.toEncoded(target.fields[key]));
407
+ rootToFlat[key] = flatKey;
408
+ }
409
+ }
410
+ return Schema.Struct(fields);
411
+ };
412
+ const encoded = unnestedKey === void 0 ? makeEncodedMember() : (() => {
413
+ const members = getMembers(target.fields[unnestedKey]);
414
+ const encodedMembers = members.map(makeEncodedMember);
415
+ return encodedMembers.length === 1 ? encodedMembers[0] : Schema.Union(encodedMembers);
416
+ })();
417
+ return encoded.pipe(
418
+ Schema.decodeTo(target, {
419
+ decode: SchemaGetter.transform((flat) => {
420
+ const out = {};
421
+ for (const key in target.fields) {
422
+ if (key === unnestedKey) {
423
+ const nestedOut = {};
424
+ for (const flatKey in flatToNested) {
425
+ if (Object.hasOwn(flat, flatKey)) {
426
+ nestedOut[flatToNested[flatKey]] = flat[flatKey];
427
+ }
428
+ }
429
+ out[key] = nestedOut;
430
+ } else {
431
+ out[key] = flat[rootToFlat[key] ?? key];
432
+ }
433
+ }
434
+ return out;
435
+ }),
436
+ encode: SchemaGetter.transform((value) => {
437
+ const out = {};
438
+ for (const key in target.fields) {
439
+ if (key === unnestedKey) {
440
+ const nestedValue = value[key];
441
+ for (const flatKey in flatToNested) {
442
+ const nestedKey = flatToNested[flatKey];
443
+ if (Object.hasOwn(nestedValue, nestedKey)) {
444
+ out[flatKey] = nestedValue[nestedKey];
445
+ }
446
+ }
447
+ } else {
448
+ out[rootToFlat[key] ?? key] = value[key];
449
+ }
450
+ }
451
+ return out;
452
+ })
453
+ })
454
+ );
455
+ };
456
+ var create_otel_tables_default = Effect10.gen(function* () {
457
+ const sql = yield* SqlClient5.SqlClient;
370
458
  yield* sql`
371
459
  CREATE TABLE spans (
372
460
  span_id TEXT PRIMARY KEY,
373
461
  trace_id TEXT NOT NULL,
374
462
  parent_span_id TEXT,
375
- name TEXT NOT NULL,
463
+ name TEXT NOT NULL DEFAULT '',
464
+ sampled INTEGER NOT NULL DEFAULT 0,
376
465
  kind INTEGER NOT NULL DEFAULT 0,
377
- start_time INTEGER NOT NULL,
466
+ status_tag TEXT NOT NULL DEFAULT 'Started',
467
+ start_time INTEGER NOT NULL DEFAULT 0,
378
468
  end_time INTEGER,
379
- status_code INTEGER NOT NULL DEFAULT 0,
380
- status_message TEXT,
381
- attributes TEXT NOT NULL DEFAULT '{}',
382
- resource_id INTEGER NOT NULL REFERENCES resources(id),
383
- scope_id INTEGER REFERENCES scopes(id),
469
+ exit TEXT,
470
+ attributes TEXT NOT NULL DEFAULT '[]',
384
471
  flags INTEGER NOT NULL DEFAULT 0,
385
472
  trace_state TEXT,
386
473
  dropped_attributes_count INTEGER NOT NULL DEFAULT 0,
@@ -388,16 +475,15 @@ var create_otel_tables_default = Effect8.gen(function* () {
388
475
  dropped_links_count INTEGER NOT NULL DEFAULT 0,
389
476
  is_external INTEGER NOT NULL DEFAULT 0
390
477
  )
391
- `.pipe(Effect8.withSpan("create_spans_table"));
392
- yield* sql`CREATE INDEX idx_spans_trace_id ON spans(trace_id)`.pipe(Effect8.withSpan("create_idx_spans_trace_id"));
478
+ `.pipe(Effect10.withSpan("create_spans_table"));
479
+ yield* sql`CREATE INDEX idx_spans_trace_id ON spans(trace_id)`.pipe(Effect10.withSpan("create_idx_spans_trace_id"));
393
480
  yield* sql`CREATE INDEX idx_spans_start_time ON spans(start_time)`.pipe(
394
- Effect8.withSpan("create_idx_spans_start_time")
481
+ Effect10.withSpan("create_idx_spans_start_time")
395
482
  );
396
- yield* sql`CREATE INDEX idx_spans_name ON spans(name)`.pipe(Effect8.withSpan("create_idx_spans_name"));
397
- yield* sql`CREATE INDEX idx_spans_parent ON spans(parent_span_id)`.pipe(Effect8.withSpan("create_idx_spans_parent"));
398
- yield* sql`CREATE INDEX idx_spans_resource ON spans(resource_id)`.pipe(Effect8.withSpan("create_idx_spans_resource"));
483
+ yield* sql`CREATE INDEX idx_spans_name ON spans(name)`.pipe(Effect10.withSpan("create_idx_spans_name"));
484
+ yield* sql`CREATE INDEX idx_spans_parent ON spans(parent_span_id)`.pipe(Effect10.withSpan("create_idx_spans_parent"));
399
485
  yield* sql`CREATE INDEX idx_spans_running ON spans(span_id) WHERE end_time IS NULL`.pipe(
400
- Effect8.withSpan("create_idx_spans_running")
486
+ Effect10.withSpan("create_idx_spans_running")
401
487
  );
402
488
  yield* sql`
403
489
  CREATE TABLE span_events (
@@ -409,9 +495,9 @@ var create_otel_tables_default = Effect8.gen(function* () {
409
495
  attributes TEXT NOT NULL DEFAULT '{}',
410
496
  dropped_attributes_count INTEGER NOT NULL DEFAULT 0
411
497
  )
412
- `.pipe(Effect8.withSpan("create_span_events_table"));
498
+ `.pipe(Effect10.withSpan("create_span_events_table"));
413
499
  yield* sql`CREATE INDEX idx_span_events_span ON span_events(span_id)`.pipe(
414
- Effect8.withSpan("create_idx_span_events_span")
500
+ Effect10.withSpan("create_idx_span_events_span")
415
501
  );
416
502
  yield* sql`
417
503
  CREATE TABLE span_links (
@@ -423,453 +509,161 @@ var create_otel_tables_default = Effect8.gen(function* () {
423
509
  attributes TEXT NOT NULL DEFAULT '{}',
424
510
  dropped_attributes_count INTEGER NOT NULL DEFAULT 0
425
511
  )
426
- `.pipe(Effect8.withSpan("create_span_links_table"));
512
+ `.pipe(Effect10.withSpan("create_span_links_table"));
427
513
  yield* sql`CREATE INDEX idx_span_links_span ON span_links(span_id)`.pipe(
428
- Effect8.withSpan("create_idx_span_links_span")
514
+ Effect10.withSpan("create_idx_span_links_span")
429
515
  );
430
516
  });
431
- var create_span_exits_table_default = Effect8.gen(function* () {
432
- const sql = yield* SqlClient7.SqlClient;
433
- yield* sql`
434
- CREATE TABLE span_exits (
435
- trace_id TEXT NOT NULL,
436
- span_id TEXT NOT NULL,
437
- exit_tag TEXT NOT NULL,
438
- exit_value TEXT,
439
- PRIMARY KEY (trace_id, span_id)
440
- )
441
- `.pipe(Effect8.withSpan("create_span_exits_table"));
442
- yield* sql`CREATE INDEX idx_span_exits_span ON span_exits(span_id)`.pipe(
443
- Effect8.withSpan("create_idx_span_exits_span")
517
+ var create_span_exits_table_default = Effect10.void;
518
+ var simplify_span_exits_default = Effect10.void;
519
+ var add_execution_id_default = Effect10.gen(function* () {
520
+ const sql = yield* SqlClient5.SqlClient;
521
+ yield* sql`ALTER TABLE spans ADD COLUMN execution_id TEXT NOT NULL DEFAULT ''`.pipe(
522
+ Effect10.withSpan("add_spans_execution_id")
444
523
  );
445
- });
446
- var simplify_span_exits_default = Effect8.gen(function* () {
447
- const sql = yield* SqlClient7.SqlClient;
448
- yield* sql`
449
- CREATE TABLE span_exits_new (
450
- trace_id TEXT NOT NULL,
451
- span_id TEXT NOT NULL,
452
- exit TEXT NOT NULL,
453
- PRIMARY KEY (trace_id, span_id)
454
- )
455
- `.pipe(Effect8.withSpan("create_span_exits_new"));
456
- yield* sql`
457
- INSERT INTO span_exits_new (trace_id, span_id, exit)
458
- SELECT
459
- trace_id,
460
- span_id,
461
- CASE
462
- WHEN exit_tag = 'Success' THEN json_object('_tag', 'Success', 'value', json(exit_value))
463
- WHEN exit_tag = 'Failure' THEN json_object('_tag', 'Failure', 'cause', json(exit_value))
464
- ELSE json_object('_tag', exit_tag, 'value', json(exit_value))
465
- END
466
- FROM span_exits
467
- `.pipe(Effect8.withSpan("migrate_span_exits_data"));
468
- yield* sql`DROP TABLE span_exits`.pipe(Effect8.withSpan("drop_old_span_exits"));
469
- yield* sql`ALTER TABLE span_exits_new RENAME TO span_exits`.pipe(
470
- Effect8.withSpan("rename_span_exits")
471
- );
472
- yield* sql`CREATE INDEX idx_span_exits_span ON span_exits(span_id)`.pipe(
473
- Effect8.withSpan("recreate_idx_span_exits_span")
524
+ yield* sql`CREATE INDEX idx_spans_execution_id ON spans(execution_id)`.pipe(
525
+ Effect10.withSpan("create_idx_spans_execution_id")
474
526
  );
475
527
  });
476
528
 
477
529
  // src/services/Storage.ts
478
- var SpanAttributes2 = Schema3.Record(Schema3.String, Schema3.Unknown);
479
- var withDefault = (schema, value) => schema.pipe(
480
- Schema3.optional,
481
- Schema3.withDecodingDefaultType(Effect8.succeed(value))
482
- );
483
- var NumberFromBigInt = Schema3.BigInt.pipe(
484
- Schema3.decodeTo(
485
- Schema3.Number,
530
+ var SpanExitJson = Schema.toCodecJson(SpanExit);
531
+ var NumberFromBigInt = Schema.BigInt.pipe(
532
+ Schema.decodeTo(
533
+ Schema.Number,
486
534
  SchemaTransformation2.transform({
487
535
  decode: (n) => Number(n),
488
536
  encode: (n) => BigInt(n)
489
537
  })
490
538
  )
491
539
  );
492
- var SpanStatusStarted2 = class extends Schema3.TaggedClass()("Started", {
493
- startTime: Schema3.BigInt
494
- }) {
495
- };
496
- var SpanStatusEnded2 = class extends Schema3.TaggedClass()("Ended", {
497
- startTime: Schema3.BigInt,
498
- endTime: Schema3.BigInt,
499
- statusCode: withDefault(Schema3.Number, 0),
500
- statusMessage: withDefault(Schema3.NullOr(Schema3.String), null)
501
- }) {
502
- };
503
- var SpanStatusSchema = Schema3.Union([SpanStatusStarted2, SpanStatusEnded2]);
504
- var ExternalSpan2 = class extends Schema3.TaggedClass()("ExternalSpan", {
505
- traceId: Schema3.String,
506
- spanId: Schema3.String,
507
- resourceId: Schema3.Number
508
- }) {
509
- };
510
- var Span2 = class extends Schema3.TaggedClass()("Span", {
511
- traceId: Schema3.String,
512
- spanId: Schema3.String,
513
- parentSpanId: Schema3.NullOr(Schema3.String),
514
- name: Schema3.String,
515
- kind: withDefault(Schema3.Number, 0),
516
- attributes: withDefault(SpanAttributes2, {}),
517
- resourceId: Schema3.Number,
518
- scopeId: Schema3.NullOr(Schema3.Number),
519
- status: SpanStatusSchema
520
- }) {
521
- };
522
- var AnySpanSchema = Schema3.Union([Span2, ExternalSpan2]);
523
- var DbSpanRow = Schema3.Struct({
524
- span_id: Schema3.String,
525
- trace_id: Schema3.String,
526
- parent_span_id: Schema3.optional(Schema3.NullOr(Schema3.String)),
527
- name: Schema3.String,
528
- kind: Schema3.optional(Schema3.BigInt),
529
- start_time: Schema3.BigInt,
530
- end_time: Schema3.optional(Schema3.NullOr(Schema3.BigInt)),
531
- status_code: Schema3.optional(Schema3.BigInt),
532
- status_message: Schema3.optional(Schema3.NullOr(Schema3.String)),
533
- attributes: Schema3.optional(Schema3.String),
534
- resource_id: Schema3.BigInt,
535
- scope_id: Schema3.optional(Schema3.NullOr(Schema3.BigInt)),
536
- is_external: Schema3.optional(Schema3.BigInt)
537
- });
538
- var DbSpanType = Schema3.Struct({
539
- span_id: Schema3.String,
540
- trace_id: Schema3.String,
541
- parent_span_id: Schema3.NullOr(Schema3.String),
542
- name: Schema3.String,
543
- kind: Schema3.Number,
544
- start_time: Schema3.BigInt,
545
- end_time: Schema3.NullOr(Schema3.BigInt),
546
- status_code: Schema3.Number,
547
- status_message: Schema3.NullOr(Schema3.String),
548
- attributes: SpanAttributes2,
549
- resource_id: Schema3.Number,
550
- scope_id: Schema3.NullOr(Schema3.Number),
551
- is_external: Schema3.Boolean
552
- });
553
- var DbSpan = DbSpanRow.pipe(Schema3.decodeTo(
554
- DbSpanType,
555
- SchemaTransformation2.transform({
556
- decode: (row) => ({
557
- span_id: row.span_id,
558
- trace_id: row.trace_id,
559
- parent_span_id: row.parent_span_id ?? null,
560
- name: row.name,
561
- kind: Number(row.kind ?? 0n),
562
- start_time: row.start_time,
563
- end_time: row.end_time ?? null,
564
- status_code: Number(row.status_code ?? 0n),
565
- status_message: row.status_message ?? null,
566
- attributes: row.attributes === void 0 ? {} : JSON.parse(row.attributes),
567
- resource_id: Number(row.resource_id),
568
- scope_id: row.scope_id === void 0 || row.scope_id === null ? null : Number(row.scope_id),
569
- is_external: (row.is_external ?? 0n) === 1n
570
- }),
571
- encode: (span) => ({
572
- span_id: span.span_id,
573
- trace_id: span.trace_id,
574
- parent_span_id: span.parent_span_id,
575
- name: span.name,
576
- kind: BigInt(span.kind),
577
- start_time: span.start_time,
578
- end_time: span.end_time,
579
- status_code: BigInt(span.status_code),
580
- status_message: span.status_message,
581
- attributes: JSON.stringify(span.attributes),
582
- resource_id: BigInt(span.resource_id),
583
- scope_id: span.scope_id === null ? null : BigInt(span.scope_id),
584
- is_external: span.is_external ? 1n : 0n
540
+ var BooleanFromBigInt = Schema.BigInt.pipe(
541
+ Schema.decodeTo(
542
+ Schema.Boolean,
543
+ SchemaTransformation2.transform({
544
+ decode: (n) => n === 1n,
545
+ encode: (b) => b ? 1n : 0n
585
546
  })
586
- })
587
- ));
588
- var AnySpanToDbSpan = DbSpan.pipe(Schema3.decodeTo(
589
- AnySpanSchema,
590
- SchemaTransformation2.transform({
591
- decode: (db) => {
592
- if (db.is_external) {
593
- return new ExternalSpan2({
594
- traceId: db.trace_id,
595
- spanId: db.span_id,
596
- resourceId: db.resource_id
597
- });
547
+ )
548
+ );
549
+ var TagFromExternalFlag = (tag, flag) => Schema.Literal(flag).pipe(
550
+ Schema.decodeTo(
551
+ Schema.Literal(tag),
552
+ SchemaTransformation2.transform({
553
+ decode: () => tag,
554
+ encode: () => flag
555
+ })
556
+ )
557
+ );
558
+ var DbSpan = Span.pipe(
559
+ encodeStruct({
560
+ evolve: {
561
+ _tag: TagFromExternalFlag("Span", 0n),
562
+ attributes: Schema.fromJsonString(SpanAttributes),
563
+ sampled: BooleanFromBigInt,
564
+ status: {
565
+ exit: Schema.fromJsonString(SpanExitJson)
598
566
  }
599
- const status = db.end_time === null ? new SpanStatusStarted2({ startTime: db.start_time }) : new SpanStatusEnded2({
600
- startTime: db.start_time,
601
- endTime: db.end_time,
602
- statusCode: db.status_code,
603
- statusMessage: db.status_message
604
- });
605
- return new Span2({
606
- traceId: db.trace_id,
607
- spanId: db.span_id,
608
- parentSpanId: db.parent_span_id,
609
- name: db.name,
610
- kind: db.kind,
611
- attributes: db.attributes,
612
- resourceId: db.resource_id,
613
- scopeId: db.scope_id,
614
- status
615
- });
616
567
  },
617
- encode: (span) => {
618
- if (span._tag === "ExternalSpan") {
619
- return {
620
- span_id: span.spanId,
621
- trace_id: span.traceId,
622
- parent_span_id: null,
623
- name: "",
624
- kind: 0,
625
- start_time: 0n,
626
- end_time: null,
627
- status_code: 0,
628
- status_message: null,
629
- attributes: {},
630
- resource_id: span.resourceId,
631
- scope_id: null,
632
- is_external: true
633
- };
634
- }
635
- const baseRecord = {
636
- span_id: span.spanId,
637
- trace_id: span.traceId,
638
- parent_span_id: span.parentSpanId,
639
- name: span.name,
640
- kind: span.kind ?? 0,
641
- attributes: span.attributes ?? {},
642
- resource_id: span.resourceId,
643
- scope_id: span.scopeId,
644
- is_external: false
645
- };
646
- if (span.status._tag === "Started") {
647
- return {
648
- ...baseRecord,
649
- start_time: span.status.startTime,
650
- end_time: null,
651
- status_code: 0,
652
- status_message: null
653
- };
654
- }
655
- return {
656
- ...baseRecord,
657
- start_time: span.status.startTime,
658
- end_time: span.status.endTime,
659
- status_code: span.status.statusCode ?? 0,
660
- status_message: span.status.statusMessage ?? null
661
- };
568
+ rename: {
569
+ _tag: "is_external",
570
+ parentSpanId: "parent_span_id",
571
+ spanId: "span_id",
572
+ status: {
573
+ _tag: "status_tag",
574
+ endTime: "end_time",
575
+ exit: "exit",
576
+ startTime: "start_time"
577
+ },
578
+ traceId: "trace_id"
662
579
  }
663
580
  })
664
- ));
665
- var encodeExit = (exit) => {
666
- if (Exit.isExit(exit)) {
667
- if (Exit.isSuccess(exit)) {
668
- return { _tag: "Success", value: exit.value };
669
- }
670
- const reasons = exit.cause.reasons.map((reason) => {
671
- switch (reason._tag) {
672
- case "Fail":
673
- return { _tag: "Fail", error: reason.error };
674
- case "Die":
675
- return { _tag: "Die", defect: reason.defect };
676
- case "Interrupt":
677
- return {
678
- _tag: "Interrupt",
679
- fiberId: reason.fiberId === void 0 ? { _tag: "None" } : { _tag: "Runtime", id: reason.fiberId, startTimeMillis: 0 }
680
- };
681
- default:
682
- return { _tag: "Empty" };
683
- }
684
- });
685
- const accumulatedCause = reasons.reduce((acc, reason) => {
686
- if (acc === void 0) return reason;
687
- return { _tag: "Sequential", left: acc, right: reason };
688
- }, { _tag: "Empty" });
689
- return { _tag: "Failure", cause: accumulatedCause };
690
- }
691
- return exit;
692
- };
693
- var decodeExit = (exit) => {
694
- if (exit._tag === "Success") {
695
- return Exit.succeed(exit.value);
696
- }
697
- const decodeCause = (cause) => {
698
- switch (cause._tag) {
699
- case "Empty":
700
- return Cause.empty;
701
- case "Fail":
702
- return Cause.fail(cause.error);
703
- case "Die":
704
- return Cause.die(cause.defect);
705
- case "Interrupt":
706
- return Cause.interrupt(cause.fiberId._tag === "Runtime" ? cause.fiberId.id : void 0);
707
- case "Sequential":
708
- case "Parallel":
709
- return Cause.combine(decodeCause(cause.left), decodeCause(cause.right));
710
- default:
711
- return Cause.empty;
581
+ );
582
+ var DbExternalSpan = ExternalSpan.pipe(
583
+ encodeStruct({
584
+ evolve: {
585
+ _tag: TagFromExternalFlag("ExternalSpan", 1n),
586
+ sampled: BooleanFromBigInt
587
+ },
588
+ rename: {
589
+ _tag: "is_external",
590
+ spanId: "span_id",
591
+ traceId: "trace_id"
712
592
  }
713
- };
714
- return Exit.failCause(decodeCause(exit.cause));
715
- };
716
- var TraceSummary = Schema3.Struct({
717
- trace_id: Schema3.String,
593
+ })
594
+ );
595
+ var DbAnySpan = Schema.Union([DbSpan, DbExternalSpan]);
596
+ var TraceSummary = Schema.Struct({
597
+ execution_id: Schema.String,
598
+ trace_id: Schema.String,
718
599
  span_count: NumberFromBigInt,
719
- root_span_name: Schema3.NullOr(Schema3.String),
720
- service_name: Schema3.NullOr(Schema3.String),
721
- start_time: Schema3.BigInt,
722
- end_time: Schema3.NullOr(Schema3.BigInt),
600
+ root_span_name: Schema.NullOr(Schema.String),
601
+ start_time: Schema.BigInt,
602
+ end_time: Schema.NullOr(Schema.BigInt),
723
603
  status: NumberFromBigInt
724
604
  });
725
- var DbSpanLinkRow = Schema3.Struct({
726
- span_id: Schema3.String,
727
- trace_id: Schema3.String,
728
- linked_span_id: Schema3.String,
729
- linked_trace_id: Schema3.String,
730
- attributes: Schema3.String
731
- }).pipe(Schema3.decodeTo(
732
- SpanLink,
733
- SchemaTransformation2.transform({
734
- decode: (row) => ({
735
- spanId: row.span_id,
736
- traceId: row.trace_id,
737
- linkedSpanId: row.linked_span_id,
738
- linkedTraceId: row.linked_trace_id,
739
- attributes: JSON.parse(row.attributes)
740
- }),
741
- encode: (link) => ({
742
- span_id: link.spanId,
743
- trace_id: link.traceId,
744
- linked_span_id: link.linkedSpanId,
745
- linked_trace_id: link.linkedTraceId,
746
- attributes: JSON.stringify(link.attributes)
747
- })
605
+ var DbSpanLink = SpanLink.mapFields(
606
+ Struct5.evolve({
607
+ attributes: Schema.fromJsonString
748
608
  })
749
- ));
750
- var DbSpanLinkToSpanLink = DbSpanLinkRow;
751
- var Storage = class extends Context3.Service()("inspeffct/Storage") {
752
- };
753
- var hashAttributes = (attributes) => {
754
- const sorted = JSON.stringify(attributes, Object.keys(attributes).sort());
755
- return Crypto.createHash("sha256").update(sorted).digest("hex").slice(0, 32);
609
+ ).pipe(
610
+ Schema.encodeKeys({
611
+ spanId: "span_id",
612
+ traceId: "trace_id",
613
+ linkedSpanId: "linked_span_id",
614
+ linkedTraceId: "linked_trace_id"
615
+ })
616
+ );
617
+ var Storage = class extends Context4.Service()("inspeffct/Storage") {
756
618
  };
757
619
  var MigrationsLoader = Migrator.fromRecord({
758
620
  "0001_create_otel_tables": create_otel_tables_default,
759
621
  "0002_create_span_exits_table": create_span_exits_table_default,
760
- "0003_simplify_span_exits": simplify_span_exits_default
622
+ "0003_simplify_span_exits": simplify_span_exits_default,
623
+ "0004_add_execution_id": add_execution_id_default
761
624
  });
762
625
  var runMigrations = Migrator.make({})({
763
626
  loader: MigrationsLoader
764
627
  });
765
- var layer4 = (config) => Layer7.effectContext(
766
- Effect8.gen(function* () {
628
+ var layer5 = (config) => Layer8.effectContext(
629
+ Effect10.gen(function* () {
767
630
  const sql = yield* SqliteClient.SqliteClient;
768
631
  yield* runMigrations;
769
- const resourceCache = /* @__PURE__ */ new Map();
770
- const scopeCache = /* @__PURE__ */ new Map();
771
632
  const storage = Storage.of({
772
- getOrCreateResource: (attributes, schemaUrl) => Effect8.gen(function* () {
773
- const hash = hashAttributes(attributes);
774
- const cached = resourceCache.get(hash);
775
- if (cached !== void 0) {
776
- return cached;
777
- }
778
- const existing = yield* sql`
779
- SELECT id FROM resources WHERE attributes_hash = ${hash}
780
- `;
781
- if (existing.length > 0) {
782
- resourceCache.set(hash, existing[0].id);
783
- return existing[0].id;
784
- }
785
- const result = yield* sql`
786
- INSERT INTO resources (attributes_hash, attributes, schema_url)
787
- VALUES (${hash}, ${JSON.stringify(attributes)}, ${schemaUrl ?? null})
788
- RETURNING id
789
- `;
790
- const id = result[0].id;
791
- resourceCache.set(hash, id);
792
- return id;
793
- }),
794
- getOrCreateScope: (name, version = "") => Effect8.gen(function* () {
795
- const key = `${name}:${version}`;
796
- const cached = scopeCache.get(key);
797
- if (cached !== void 0) {
798
- return cached;
799
- }
800
- const existing = yield* sql`
801
- SELECT id FROM scopes WHERE name = ${name} AND version = ${version}
802
- `;
803
- if (existing.length > 0) {
804
- scopeCache.set(key, existing[0].id);
805
- return existing[0].id;
806
- }
807
- const result = yield* sql`
808
- INSERT INTO scopes (name, version)
809
- VALUES (${name}, ${version})
810
- RETURNING id
811
- `;
812
- const id = result[0].id;
813
- scopeCache.set(key, id);
814
- return id;
633
+ persistSpan: (span, executionId) => Effect10.gen(function* () {
634
+ const changed = yield* (
635
+ // @ts-ignore TS28 false positive from SqlSchema service inference
636
+ SqlSchema.findOne({
637
+ Request: DbAnySpan,
638
+ Result: Schema.Struct({ span_id: Schema.String }),
639
+ execute: (db) => {
640
+ const row = { ...db, execution_id: executionId };
641
+ return sql`
642
+ INSERT INTO spans ${sql.insert(row)}
643
+ ON CONFLICT(span_id) DO UPDATE SET
644
+ ${sql.update(row, ["span_id"])}
645
+ WHERE
646
+ is_external = 1 OR
647
+ (end_time IS NULL AND excluded.is_external = 0)
648
+ RETURNING span_id
649
+ `;
650
+ }
651
+ })(span).pipe(
652
+ Effect10.as(true),
653
+ Effect10.catch(() => Effect10.succeed(false)),
654
+ Effect10.provideService(SqlClient5.SafeIntegers, true)
655
+ )
656
+ );
657
+ return changed;
815
658
  }),
816
- persistSpan: (span) => (
817
- // @ts-ignore TS28 false positive from SqlSchema service inference
818
- SqlSchema.findOne({
819
- Request: AnySpanToDbSpan,
820
- Result: Schema3.Struct({ span_id: Schema3.String }),
821
- execute: (db) => sql`
822
- INSERT INTO spans (
823
- span_id, trace_id, parent_span_id, name, kind,
824
- start_time, end_time, status_code, status_message,
825
- attributes, resource_id, scope_id, is_external
826
- ) VALUES (
827
- ${db.span_id},
828
- ${db.trace_id},
829
- ${db.parent_span_id},
830
- ${db.name},
831
- ${db.kind},
832
- ${db.start_time},
833
- ${db.end_time},
834
- ${db.status_code},
835
- ${db.status_message},
836
- ${db.attributes},
837
- ${db.resource_id},
838
- ${db.scope_id},
839
- ${db.is_external ? 1 : 0}
840
- )
841
- ON CONFLICT(span_id) DO UPDATE SET
842
- trace_id = excluded.trace_id,
843
- parent_span_id = excluded.parent_span_id,
844
- name = excluded.name,
845
- kind = excluded.kind,
846
- start_time = excluded.start_time,
847
- end_time = COALESCE(excluded.end_time, end_time),
848
- status_code = excluded.status_code,
849
- status_message = excluded.status_message,
850
- attributes = excluded.attributes,
851
- resource_id = excluded.resource_id,
852
- scope_id = excluded.scope_id,
853
- is_external = excluded.is_external
854
- WHERE
855
- is_external = 1 OR
856
- (end_time IS NULL AND excluded.is_external = 0)
857
- RETURNING span_id
858
- `
859
- })(span).pipe(
860
- Effect8.as(true),
861
- Effect8.catch(() => Effect8.succeed(false)),
862
- Effect8.provideService(SqlClient7.SafeIntegers, true)
863
- )
864
- ),
865
659
  persistSpanEvent: flow(
866
660
  SqlSchema.void({
867
- Request: Schema3.Struct({
868
- spanId: Schema3.String,
869
- traceId: Schema3.String,
870
- name: Schema3.String,
871
- time: Schema3.BigInt,
872
- attributes: Schema3.fromJsonString(SpanAttributes)
661
+ Request: Schema.Struct({
662
+ spanId: Schema.String,
663
+ traceId: Schema.String,
664
+ name: Schema.String,
665
+ time: Schema.BigInt,
666
+ attributes: Schema.fromJsonString(SpanAttributes)
873
667
  }),
874
668
  execute: (req) => sql`
875
669
  INSERT INTO span_events (span_id, trace_id, name, time, attributes)
@@ -882,44 +676,50 @@ var layer4 = (config) => Layer7.effectContext(
882
676
  )
883
677
  `
884
678
  }),
885
- Effect8.provideService(SqlClient7.SafeIntegers, true)
679
+ Effect10.provideService(SqlClient5.SafeIntegers, true)
886
680
  ),
887
681
  getSpansByTraceId: (traceId) => (
888
682
  // @ts-ignore TS28 false positive from SqlSchema service inference
889
683
  SqlSchema.findAll({
890
- Request: Schema3.String,
891
- Result: AnySpanToDbSpan,
684
+ Request: Schema.String,
685
+ Result: DbAnySpan,
892
686
  execute: (traceId2) => sql`
893
- SELECT * FROM spans WHERE trace_id = ${traceId2} ORDER BY start_time ASC
687
+ SELECT s.*
688
+ FROM spans s
689
+ WHERE s.trace_id = ${traceId2}
690
+ ORDER BY s.start_time ASC
894
691
  `
895
692
  })(traceId).pipe(
896
- Effect8.provideService(SqlClient7.SafeIntegers, true)
693
+ Effect10.provideService(SqlClient5.SafeIntegers, true)
897
694
  )
898
695
  ),
899
696
  getRecentSpans: (limit = 100) => (
900
697
  // @ts-ignore TS28 false positive from SqlSchema service inference
901
698
  SqlSchema.findAll({
902
- Request: Schema3.Number,
903
- Result: AnySpanToDbSpan,
699
+ Request: Schema.Number,
700
+ Result: DbAnySpan,
904
701
  execute: (l) => sql`
905
- SELECT * FROM spans ORDER BY start_time DESC LIMIT ${l}
702
+ SELECT s.*
703
+ FROM spans s
704
+ ORDER BY s.start_time DESC
705
+ LIMIT ${l}
906
706
  `
907
707
  })(limit).pipe(
908
- Effect8.provideService(SqlClient7.SafeIntegers, true)
708
+ Effect10.provideService(SqlClient5.SafeIntegers, true)
909
709
  )
910
710
  ),
911
711
  getSpanEvents: flow(
912
712
  SqlSchema.findAll({
913
- Request: Schema3.Struct({
914
- traceId: Schema3.String,
915
- spanId: Schema3.String
713
+ Request: Schema.Struct({
714
+ traceId: Schema.String,
715
+ spanId: Schema.String
916
716
  }),
917
- Result: Schema3.Struct({
918
- spanId: Schema3.String,
919
- traceId: Schema3.String,
920
- name: Schema3.String,
921
- time: Schema3.BigInt,
922
- attributes: Schema3.fromJsonString(SpanAttributes)
717
+ Result: Schema.Struct({
718
+ spanId: Schema.String,
719
+ traceId: Schema.String,
720
+ name: Schema.String,
721
+ time: Schema.BigInt,
722
+ attributes: Schema.fromJsonString(SpanAttributes)
923
723
  }),
924
724
  execute: (req) => sql`
925
725
  SELECT span_id AS "spanId", trace_id AS "traceId", name, time, attributes
@@ -928,171 +728,144 @@ var layer4 = (config) => Layer7.effectContext(
928
728
  ORDER BY time ASC
929
729
  `
930
730
  }),
931
- Effect8.provideService(SqlClient7.SafeIntegers, true)
731
+ Effect10.provideService(SqlClient5.SafeIntegers, true)
932
732
  ),
933
733
  persistSpanLink: SqlSchema.void({
934
- Request: Schema3.Struct({
935
- spanId: Schema3.String,
936
- traceId: Schema3.String,
937
- linkedSpanId: Schema3.String,
938
- linkedTraceId: Schema3.String,
939
- attributes: Schema3.fromJsonString(SpanAttributes)
940
- }),
734
+ Request: DbSpanLink,
941
735
  execute: (req) => sql`
942
736
  INSERT INTO span_links (span_id, trace_id, linked_span_id, linked_trace_id, attributes)
943
737
  VALUES (
944
- ${req.spanId},
945
- ${req.traceId},
946
- ${req.linkedSpanId},
947
- ${req.linkedTraceId},
738
+ ${req.span_id},
739
+ ${req.trace_id},
740
+ ${req.linked_span_id},
741
+ ${req.linked_trace_id},
948
742
  ${req.attributes}
949
743
  )
950
744
  `
951
745
  }),
952
746
  getSpanLinks: SqlSchema.findAll({
953
- Request: Schema3.Struct({
954
- traceId: Schema3.String,
955
- spanId: Schema3.String
747
+ Request: Schema.Struct({
748
+ traceId: Schema.String,
749
+ spanId: Schema.String
956
750
  }),
957
- Result: DbSpanLinkToSpanLink,
751
+ Result: DbSpanLink,
958
752
  execute: (req) => sql`
959
753
  SELECT * FROM span_links
960
754
  WHERE trace_id = ${req.traceId} AND span_id = ${req.spanId}
961
755
  `
962
756
  }),
963
- persistSpanExit: (req) => sql`
964
- INSERT INTO span_exits (trace_id, span_id, exit)
965
- VALUES (
966
- ${req.traceId},
967
- ${req.spanId},
968
- ${JSON.stringify(encodeExit(req.exit))}
969
- )
970
- ON CONFLICT(trace_id, span_id) DO UPDATE SET
971
- exit = excluded.exit
972
- `.pipe(Effect8.asVoid),
973
- getSpanExit: (req) => sql`
974
- SELECT exit FROM span_exits
975
- WHERE trace_id = ${req.traceId} AND span_id = ${req.spanId}
976
- `.pipe(
977
- Effect8.map((rows) => rows[0]),
978
- Effect8.map((row) => row ? Option4.some(decodeExit(JSON.parse(row.exit))) : Option4.none())
979
- ),
980
757
  getTraces: (filters = {}) => SqlSchema.findAll({
981
- Request: Schema3.Struct({
982
- limit: Schema3.optional(Schema3.Number),
983
- service: Schema3.optional(Schema3.String),
984
- since: Schema3.optional(Schema3.BigInt),
985
- status: Schema3.optional(Schema3.Number)
758
+ Request: Schema.Struct({
759
+ executionId: Schema.optional(Schema.String),
760
+ limit: Schema.optional(Schema.Number),
761
+ since: Schema.optional(Schema.BigInt),
762
+ status: Schema.optional(Schema.Number)
986
763
  }),
987
764
  Result: TraceSummary,
988
765
  execute: (req) => sql`
989
766
  SELECT
767
+ s.execution_id,
990
768
  s.trace_id,
991
769
  COUNT(*) as span_count,
992
- (SELECT name FROM spans WHERE trace_id = s.trace_id AND parent_span_id IS NULL LIMIT 1) as root_span_name,
993
- (SELECT json_extract(r2.attributes, '$."service.name"')
994
- FROM spans s2
995
- JOIN resources r2 ON s2.resource_id = r2.id
996
- WHERE s2.trace_id = s.trace_id
997
- LIMIT 1) as service_name,
770
+ (
771
+ SELECT name
772
+ FROM spans
773
+ WHERE trace_id = s.trace_id
774
+ AND execution_id = s.execution_id
775
+ AND parent_span_id IS NULL
776
+ LIMIT 1
777
+ ) as root_span_name,
998
778
  MIN(s.start_time) as start_time,
999
779
  MAX(s.end_time) as end_time,
1000
- MAX(s.status_code) as status
780
+ MAX(
781
+ CASE
782
+ WHEN s.status_tag = 'Ended' AND json_extract(s.exit, '$._tag') = 'Success' THEN 1
783
+ WHEN s.status_tag = 'Ended' THEN 2
784
+ ELSE 0
785
+ END
786
+ ) as status
1001
787
  FROM spans s
1002
- LEFT JOIN resources r ON s.resource_id = r.id
1003
788
  WHERE ${sql.and([
789
+ req.executionId !== void 0 ? sql`s.execution_id = ${req.executionId}` : sql`1=1`,
1004
790
  req.since !== void 0 ? sql`s.start_time >= ${req.since}` : sql`1=1`,
1005
- req.status !== void 0 ? sql`s.status_code = ${req.status}` : sql`1=1`,
1006
- req.service !== void 0 ? sql`r.attributes LIKE ${`%"service.name":"${req.service}"%`}` : sql`1=1`
791
+ req.status !== void 0 ? sql`
792
+ CASE
793
+ WHEN s.status_tag = 'Ended' AND json_extract(s.exit, '$._tag') = 'Success' THEN 1
794
+ WHEN s.status_tag = 'Ended' THEN 2
795
+ ELSE 0
796
+ END = ${req.status}
797
+ ` : sql`1=1`
1007
798
  ])}
1008
- GROUP BY s.trace_id
799
+ GROUP BY s.execution_id, s.trace_id
1009
800
  ORDER BY start_time DESC
1010
801
  ${req.limit !== void 0 ? sql`LIMIT ${req.limit}` : sql``}
1011
802
  `
1012
803
  })(filters).pipe(
1013
- Effect8.provideService(SqlClient7.SafeIntegers, true)
804
+ Effect10.provideService(SqlClient5.SafeIntegers, true)
1014
805
  ),
1015
806
  getSpans: (filters = {}) => (
1016
807
  // @ts-ignore TS28 false positive from SqlSchema service inference
1017
808
  SqlSchema.findAll({
1018
- Request: Schema3.Struct({
1019
- limit: Schema3.optional(Schema3.Number),
1020
- minDuration: Schema3.optional(Schema3.BigInt),
1021
- name: Schema3.optional(Schema3.String),
1022
- status: Schema3.optional(Schema3.Number),
1023
- traceId: Schema3.optional(Schema3.String)
809
+ Request: Schema.Struct({
810
+ executionId: Schema.optional(Schema.String),
811
+ limit: Schema.optional(Schema.Number),
812
+ minDuration: Schema.optional(Schema.BigInt),
813
+ name: Schema.optional(Schema.String),
814
+ status: Schema.optional(Schema.Number),
815
+ traceId: Schema.optional(Schema.String)
1024
816
  }),
1025
- Result: AnySpanToDbSpan,
817
+ Result: DbAnySpan,
1026
818
  execute: (req) => sql`
1027
- SELECT * FROM spans
819
+ SELECT s.*
820
+ FROM spans s
1028
821
  WHERE ${sql.and([
1029
- req.traceId !== void 0 ? sql`trace_id = ${req.traceId}` : sql`1=1`,
1030
- req.name !== void 0 ? req.name.includes("%") ? sql`name LIKE ${req.name}` : sql`name = ${req.name}` : sql`1=1`,
1031
- req.minDuration !== void 0 ? sql`(end_time - start_time) >= ${req.minDuration}` : sql`1=1`,
1032
- req.status !== void 0 ? sql`status_code = ${req.status}` : sql`1=1`
822
+ req.executionId !== void 0 ? sql`s.execution_id = ${req.executionId}` : sql`1=1`,
823
+ req.traceId !== void 0 ? sql`s.trace_id = ${req.traceId}` : sql`1=1`,
824
+ req.name !== void 0 ? req.name.includes("%") ? sql`s.name LIKE ${req.name}` : sql`s.name = ${req.name}` : sql`1=1`,
825
+ req.minDuration !== void 0 ? sql`(s.end_time - s.start_time) >= ${req.minDuration}` : sql`1=1`,
826
+ req.status !== void 0 ? sql`
827
+ CASE
828
+ WHEN s.status_tag = 'Ended' AND json_extract(s.exit, '$._tag') = 'Success' THEN 1
829
+ WHEN s.status_tag = 'Ended' THEN 2
830
+ ELSE 0
831
+ END = ${req.status}
832
+ ` : sql`1=1`
1033
833
  ])}
1034
- ORDER BY start_time DESC
834
+ ORDER BY s.start_time DESC
1035
835
  ${req.limit !== void 0 ? sql`LIMIT ${req.limit}` : sql``}
1036
836
  `
1037
837
  })(filters).pipe(
1038
- Effect8.provideService(SqlClient7.SafeIntegers, true)
838
+ Effect10.provideService(SqlClient5.SafeIntegers, true)
1039
839
  )
1040
840
  )
1041
841
  });
1042
- return Context3.make(Storage, storage);
842
+ return Context4.make(Storage, storage);
1043
843
  })
1044
- ).pipe(Layer7.provide(SqliteClient.layer(config)));
844
+ ).pipe(Layer8.provide(SqliteClient.layer(config)));
1045
845
 
1046
846
  // src/services/EventCollector.ts
1047
- var EventCollector = class extends Context3.Service()("inspeffct/EventCollector") {
847
+ var EventCollector = class extends Context4.Service()("inspeffct/EventCollector") {
1048
848
  };
1049
- var layer5 = Layer7.effect(
849
+ var layer6 = Layer8.effect(
1050
850
  EventCollector,
1051
- Effect8.gen(function* () {
851
+ Effect10.gen(function* () {
852
+ const executionId = yield* ExecutionId;
1052
853
  const storage = yield* Storage;
1053
854
  return EventCollector.of({
1054
- collect: (message) => Effect8.gen(function* () {
855
+ collect: (message) => Effect10.gen(function* () {
1055
856
  switch (message._tag) {
1056
857
  case "InitNotification": {
1057
- yield* Effect8.logDebug(
858
+ yield* Effect10.logDebug(
1058
859
  `${message._tag} from ${message.instrumentationId} (inspectorURL: ${message.inspectorURL ?? "none"}, waitingForDebugger: ${message.waitingForDebugger})`
1059
860
  );
1060
861
  break;
1061
862
  }
1062
863
  case "TracerSpanNotification": {
1063
864
  const { instrumentationId, span } = message;
1064
- yield* Effect8.logDebug(`${message._tag} from ${instrumentationId}`);
865
+ yield* Effect10.logDebug(`${message._tag} from ${instrumentationId}`);
1065
866
  if (span._tag === "Span" && span.status._tag === "Ended") {
1066
- const resourceId = yield* storage.getOrCreateResource({
1067
- "service.name": instrumentationId
1068
- });
1069
- const scopeId = yield* storage.getOrCreateScope("effect-tracer");
1070
- const statusCode = span.status.exit._tag === "Success" ? 1 : 2;
1071
- yield* storage.persistSpan(
1072
- new Span2({
1073
- spanId: span.spanId,
1074
- traceId: span.traceId,
1075
- parentSpanId: span.parent?.spanId ?? null,
1076
- name: span.name,
1077
- kind: 0,
1078
- // INTERNAL
1079
- attributes: Object.fromEntries(span.attributes),
1080
- resourceId,
1081
- scopeId,
1082
- status: new SpanStatusEnded2({
1083
- startTime: span.status.startTime,
1084
- endTime: span.status.endTime,
1085
- statusCode,
1086
- statusMessage: null
1087
- })
1088
- })
1089
- );
1090
- yield* storage.persistSpanExit({
1091
- traceId: span.traceId,
1092
- spanId: span.spanId,
1093
- exit: span.status.exit
1094
- });
1095
- yield* Effect8.logDebug(
867
+ yield* storage.persistSpan(span, executionId);
868
+ yield* Effect10.logDebug(
1096
869
  `Persisted span ${span.name} (${span.spanId}) with exit ${span.status.exit._tag} to storage`
1097
870
  );
1098
871
  }
@@ -1100,7 +873,7 @@ var layer5 = Layer7.effect(
1100
873
  }
1101
874
  case "TracerSpanEventNotification": {
1102
875
  const { event } = message;
1103
- yield* Effect8.logDebug(`${message._tag} from ${message.instrumentationId}`);
876
+ yield* Effect10.logDebug(`${message._tag} from ${message.instrumentationId}`);
1104
877
  yield* storage.persistSpanEvent({
1105
878
  spanId: event.spanId,
1106
879
  traceId: event.traceId,
@@ -1108,14 +881,14 @@ var layer5 = Layer7.effect(
1108
881
  time: event.time,
1109
882
  attributes: event.attributes
1110
883
  });
1111
- yield* Effect8.logDebug(
884
+ yield* Effect10.logDebug(
1112
885
  `Persisted span event ${event.name} for span ${event.spanId}`
1113
886
  );
1114
887
  break;
1115
888
  }
1116
889
  case "TracerSpanLinkNotification": {
1117
890
  const { link } = message;
1118
- yield* Effect8.logDebug(`${message._tag} from ${message.instrumentationId}`);
891
+ yield* Effect10.logDebug(`${message._tag} from ${message.instrumentationId}`);
1119
892
  yield* storage.persistSpanLink({
1120
893
  spanId: link.spanId,
1121
894
  traceId: link.traceId,
@@ -1123,7 +896,7 @@ var layer5 = Layer7.effect(
1123
896
  linkedTraceId: link.linkedTraceId,
1124
897
  attributes: link.attributes
1125
898
  });
1126
- yield* Effect8.logDebug(
899
+ yield* Effect10.logDebug(
1127
900
  `Persisted span link from ${link.spanId} to ${link.linkedSpanId}`
1128
901
  );
1129
902
  break;
@@ -1132,48 +905,48 @@ var layer5 = Layer7.effect(
1132
905
  case "VariableReferenceInfo":
1133
906
  case "ResourcesForRequestReleased":
1134
907
  case "CurrentFibersInfo": {
1135
- yield* Effect8.logDebug(`${message._tag} from ${message.instrumentationId}`);
908
+ yield* Effect10.logDebug(`${message._tag} from ${message.instrumentationId}`);
1136
909
  break;
1137
910
  }
1138
911
  }
1139
- }).pipe(Effect8.catch((error) => Effect8.logWarning(`Failed to persist event: ${error}`)))
912
+ }).pipe(Effect10.catch((error) => Effect10.logWarning(`Failed to persist event: ${error}`)))
1140
913
  });
1141
914
  })
1142
915
  );
1143
- Layer7.succeed(
916
+ Layer8.succeed(
1144
917
  EventCollector,
1145
918
  EventCollector.of({
1146
919
  collect: (message) => {
1147
920
  if (message._tag === "InitNotification") {
1148
- return Effect8.logDebug(
921
+ return Effect10.logDebug(
1149
922
  `${message._tag} from ${message.instrumentationId} (inspectorURL: ${message.inspectorURL ?? "none"}, waitingForDebugger: ${message.waitingForDebugger})`
1150
923
  );
1151
924
  }
1152
- return Effect8.logDebug(`${message._tag} from ${message.instrumentationId}`);
925
+ return Effect10.logDebug(`${message._tag} from ${message.instrumentationId}`);
1153
926
  }
1154
927
  })
1155
928
  );
1156
- Layer7.effect(
929
+ Layer8.effect(
1157
930
  EventCollector,
1158
- Effect8.gen(function* () {
931
+ Effect10.gen(function* () {
1159
932
  const messagesRef = yield* Ref.make(Chunk.empty());
1160
933
  return EventCollector.of({
1161
934
  collect: (message) => Ref.update(messagesRef, Chunk.append(message)),
1162
- getMessages: Ref.get(messagesRef).pipe(Effect8.map(Chunk.toReadonlyArray))
935
+ getMessages: Ref.get(messagesRef).pipe(Effect10.map(Chunk.toReadonlyArray))
1163
936
  });
1164
937
  })
1165
938
  );
1166
939
 
1167
940
  // src/services/CdpManager.ts
1168
941
  var BINDING_NAME = "__inspeffct_bridge__";
1169
- var CdpManager = class extends Context3.Service()("inspeffct/CdpManager") {
942
+ var CdpManager = class extends Context4.Service()("inspeffct/CdpManager") {
1170
943
  };
1171
- var getBootloaderScript = Effect8.gen(function* () {
944
+ var getBootloaderScript = Effect10.gen(function* () {
1172
945
  const fs2 = yield* FileSystem.FileSystem;
1173
946
  const bootloaderPath = yield* getPath;
1174
947
  return yield* fs2.readFileString(bootloaderPath);
1175
948
  });
1176
- var connectAndListen = (url, bootloaderScript) => Effect8.gen(function* () {
949
+ var connectAndListen = (url, bootloaderScript) => Effect10.gen(function* () {
1177
950
  const cdp = yield* CdpClient;
1178
951
  const collector = yield* EventCollector;
1179
952
  const connection = yield* cdp.connect(url);
@@ -1181,21 +954,21 @@ var connectAndListen = (url, bootloaderScript) => Effect8.gen(function* () {
1181
954
  expression: bootloaderScript,
1182
955
  contextId,
1183
956
  silent: true
1184
- }).pipe(Effect8.ensuring(connection.request("Runtime.runIfWaitingForDebugger").pipe(Effect8.ignore({ log: true }))));
957
+ }).pipe(Effect10.ensuring(connection.request("Runtime.runIfWaitingForDebugger").pipe(Effect10.ignore({ log: true }))));
1185
958
  const eventFiber = yield* connection.events.pipe(
1186
959
  Stream.takeUntil(
1187
960
  (event) => event.method === "Runtime.executionContextDestroyed" || event.method === "Runtime.executionContextsCleared" || event.method === "Inspector.detached"
1188
961
  ),
1189
962
  Stream.runForEach(
1190
- (event) => Effect8.gen(function* () {
963
+ (event) => Effect10.gen(function* () {
1191
964
  if (event.method === "Runtime.bindingCalled") {
1192
965
  const params = event.params;
1193
966
  if (params.name === BINDING_NAME) {
1194
- yield* Schema3.decodeUnknownEffect(Schema3.fromJsonString(Schema3.toCodecJson(OutMessage)))(
967
+ yield* Schema.decodeUnknownEffect(Schema.fromJsonString(OutMessage))(
1195
968
  params.payload
1196
969
  ).pipe(
1197
- Effect8.flatMap((decoded) => collector.collect(decoded)),
1198
- Effect8.catch(() => Effect8.logError(`Failed to decode CDP message: ${params.payload}`))
970
+ Effect10.flatMap((decoded) => collector.collect(decoded)),
971
+ Effect10.catch(() => Effect10.logError(`Failed to decode CDP message: ${params.payload}`))
1199
972
  );
1200
973
  }
1201
974
  }
@@ -1205,44 +978,44 @@ var connectAndListen = (url, bootloaderScript) => Effect8.gen(function* () {
1205
978
  }
1206
979
  })
1207
980
  ),
1208
- Effect8.forkScoped
981
+ Effect10.forkScoped
1209
982
  );
1210
- yield* Effect8.yieldNow;
983
+ yield* Effect10.yieldNow;
1211
984
  yield* connection.request("Runtime.addBinding", { name: BINDING_NAME });
1212
985
  yield* connection.request("Runtime.enable");
1213
986
  yield* connection.request("Runtime.runIfWaitingForDebugger");
1214
- yield* Effect8.logDebug(`CDP connected: ${url}`);
987
+ yield* Effect10.logDebug(`CDP connected: ${url}`);
1215
988
  yield* Fiber.join(eventFiber);
1216
989
  });
1217
- var layer6 = Layer7.effect(
990
+ var layer7 = Layer8.effect(
1218
991
  CdpManager,
1219
- Effect8.gen(function* () {
992
+ Effect10.gen(function* () {
1220
993
  const bootloaderScript = yield* getBootloaderScript;
1221
994
  const cdpClient = yield* CdpClient;
1222
995
  const collector = yield* EventCollector;
1223
- const managerScope = yield* Effect8.scope;
996
+ const managerScope = yield* Effect10.scope;
1224
997
  const activeConnections = /* @__PURE__ */ new Map();
1225
998
  return CdpManager.of({
1226
- connect: (url) => Effect8.gen(function* () {
999
+ connect: (url) => Effect10.gen(function* () {
1227
1000
  if (activeConnections.has(url)) {
1228
1001
  return;
1229
1002
  }
1230
1003
  activeConnections.set(url, true);
1231
- yield* Effect8.logDebug(`Connecting to CDP: ${url}`);
1004
+ yield* Effect10.logDebug(`Connecting to CDP: ${url}`);
1232
1005
  yield* connectAndListen(url, bootloaderScript).pipe(
1233
- Effect8.provideService(CdpClient, cdpClient),
1234
- Effect8.provideService(EventCollector, collector),
1235
- Effect8.scoped,
1236
- Effect8.catchCause((cause) => Effect8.logError(`CDP connection failed for ${url}: ${cause}`)),
1006
+ Effect10.provideService(CdpClient, cdpClient),
1007
+ Effect10.provideService(EventCollector, collector),
1008
+ Effect10.scoped,
1009
+ Effect10.catchCause((cause) => Effect10.logError(`CDP connection failed for ${url}: ${cause}`)),
1237
1010
  // Always remove from tracking when done (success, failure, or interruption)
1238
- Effect8.ensuring(
1239
- Effect8.sync(() => {
1011
+ Effect10.ensuring(
1012
+ Effect10.sync(() => {
1240
1013
  activeConnections.delete(url);
1241
1014
  }).pipe(
1242
- Effect8.tap(() => Effect8.logDebug(`CDP disconnected: ${url}`))
1015
+ Effect10.tap(() => Effect10.logDebug(`CDP disconnected: ${url}`))
1243
1016
  )
1244
1017
  ),
1245
- Effect8.forkIn(managerScope)
1018
+ Effect10.forkIn(managerScope)
1246
1019
  );
1247
1020
  })
1248
1021
  });
@@ -1250,12 +1023,12 @@ var layer6 = Layer7.effect(
1250
1023
  );
1251
1024
  var namedSocketDirectory = os.platform() === "win32" ? "\\\\.\\pipe\\" : os.tmpdir();
1252
1025
  var pipeCounter = 0;
1253
- var generateIpcPath = Effect8.sync(() => {
1254
- const randomHex = Crypto.randomBytes(4).toString("hex");
1026
+ var generateIpcPath = Effect10.sync(() => {
1027
+ const randomHex = crypto.randomBytes(4).toString("hex");
1255
1028
  const pipeName = `inspeffct.${process.pid}-${randomHex}-${pipeCounter++}.sock`;
1256
1029
  return path.join(namedSocketDirectory, pipeName);
1257
1030
  });
1258
- var cleanupSocketFile = (socketPath) => Effect8.sync(() => {
1031
+ var cleanupSocketFile = (socketPath) => Effect10.sync(() => {
1259
1032
  if (os.platform() !== "win32") {
1260
1033
  try {
1261
1034
  fs.unlinkSync(socketPath);
@@ -1263,25 +1036,25 @@ var cleanupSocketFile = (socketPath) => Effect8.sync(() => {
1263
1036
  }
1264
1037
  }
1265
1038
  });
1266
- var IpcServer = class extends Context3.Service()("inspeffct/IpcServer") {
1039
+ var IpcServer = class extends Context4.Service()("inspeffct/IpcServer") {
1267
1040
  };
1268
1041
  var tryParseMessage = (message) => {
1269
1042
  try {
1270
1043
  const parsed = JSON.parse(message);
1271
- return Schema3.decodeUnknownSync(OutMessage)(parsed);
1044
+ return Schema.decodeUnknownSync(OutMessage)(parsed);
1272
1045
  } catch {
1273
1046
  return null;
1274
1047
  }
1275
1048
  };
1276
1049
  var ACK_SUCCESS = new Uint8Array([0]);
1277
1050
  var parseMessages = (socket) => Stream.unwrap(
1278
- Effect8.gen(function* () {
1051
+ Effect10.gen(function* () {
1279
1052
  const write = yield* socket.writer;
1280
1053
  const decoder = new TextDecoder();
1281
1054
  let buffer = "";
1282
1055
  return Stream.callback(
1283
1056
  (queue) => socket.run(
1284
- (data) => Effect8.gen(function* () {
1057
+ (data) => Effect10.gen(function* () {
1285
1058
  buffer += decoder.decode(data);
1286
1059
  let nullIndex;
1287
1060
  while ((nullIndex = buffer.indexOf("\0")) !== -1) {
@@ -1296,13 +1069,13 @@ var parseMessages = (socket) => Stream.unwrap(
1296
1069
  }
1297
1070
  }
1298
1071
  }),
1299
- { onOpen: Effect8.void }
1072
+ { onOpen: Effect10.void }
1300
1073
  ).pipe(
1301
- Effect8.andThen(() => {
1074
+ Effect10.andThen(() => {
1302
1075
  if (buffer.length > 0) {
1303
1076
  const decoded = tryParseMessage(buffer);
1304
1077
  if (decoded) {
1305
- return Queue2.offer(queue, decoded).pipe(Effect8.andThen(Queue2.end(queue)));
1078
+ return Queue2.offer(queue, decoded).pipe(Effect10.andThen(Queue2.end(queue)));
1306
1079
  }
1307
1080
  }
1308
1081
  return Queue2.end(queue);
@@ -1311,18 +1084,18 @@ var parseMessages = (socket) => Stream.unwrap(
1311
1084
  );
1312
1085
  })
1313
1086
  );
1314
- var layer7 = Layer7.effect(
1087
+ var layer8 = Layer8.effect(
1315
1088
  IpcServer,
1316
- Effect8.gen(function* () {
1089
+ Effect10.gen(function* () {
1317
1090
  const ipcPath = yield* generateIpcPath;
1318
- yield* Effect8.addFinalizer(() => cleanupSocketFile(ipcPath));
1091
+ yield* Effect10.addFinalizer(() => cleanupSocketFile(ipcPath));
1319
1092
  const server = yield* NodeSocketServer.make({ path: ipcPath });
1320
1093
  const pubsub = yield* PubSub2.unbounded();
1321
1094
  yield* server.run(
1322
1095
  (socket) => parseMessages(socket).pipe(
1323
1096
  Stream.runForEach((message) => PubSub2.publish(pubsub, message))
1324
1097
  )
1325
- ).pipe(Effect8.catchCause(Effect8.logDebug), Effect8.forkScoped);
1098
+ ).pipe(Effect10.catchCause(Effect10.logDebug), Effect10.forkScoped);
1326
1099
  const messages = Stream.fromPubSub(pubsub);
1327
1100
  const subscribe3 = PubSub2.subscribe(pubsub);
1328
1101
  return IpcServer.of({
@@ -1332,9 +1105,9 @@ var layer7 = Layer7.effect(
1332
1105
  });
1333
1106
  })
1334
1107
  );
1335
- Effect8.map(IpcServer, (server) => server.path);
1336
- Effect8.map(IpcServer, (server) => server.messages);
1337
- Effect8.flatMap(IpcServer, (server) => server.subscribe);
1108
+ Effect10.map(IpcServer, (server) => server.path);
1109
+ Effect10.map(IpcServer, (server) => server.messages);
1110
+ Effect10.flatMap(IpcServer, (server) => server.subscribe);
1338
1111
 
1339
1112
  // src/cli/options.ts
1340
1113
  var dataOption = Flag3.string("data").pipe(
@@ -1366,23 +1139,28 @@ var buildEnv = (bootloaderPath, ipcPath) => {
1366
1139
  };
1367
1140
  };
1368
1141
  var makeServicesLayer = (dataPath) => {
1369
- const storageLayer = layer4({ filename: dataPath });
1370
- const eventCollectorLayer = layer5.pipe(Layer7.provide(storageLayer));
1371
- const bootloaderPathLayer = layer.pipe(Layer7.provide(NodePath.layer));
1372
- return Layer7.mergeAll(
1373
- layer7,
1374
- eventCollectorLayer,
1142
+ const executionIdLayer = layer3;
1143
+ const storageLayer = layer5({ filename: dataPath });
1144
+ const eventCollectorLayer = layer6.pipe(
1145
+ Layer8.provide(executionIdLayer),
1146
+ Layer8.provide(storageLayer)
1147
+ );
1148
+ const bootloaderPathLayer = layer.pipe(Layer8.provide(NodePath.layer));
1149
+ return Layer8.mergeAll(
1150
+ executionIdLayer,
1151
+ layer8,
1375
1152
  bootloaderPathLayer,
1376
- layer6.pipe(
1377
- Layer7.provide(eventCollectorLayer),
1378
- Layer7.provide(layer2),
1379
- Layer7.provide(bootloaderPathLayer),
1380
- Layer7.provide(NodeFileSystem.layer),
1381
- Layer7.provide(NodePath.layer)
1153
+ layer7.pipe(
1154
+ Layer8.provide(layer2),
1155
+ Layer8.provide(bootloaderPathLayer),
1156
+ Layer8.provide(NodeFileSystem.layer),
1157
+ Layer8.provide(NodePath.layer)
1382
1158
  )
1159
+ ).pipe(
1160
+ Layer8.provideMerge(eventCollectorLayer)
1383
1161
  );
1384
1162
  };
1385
- var makeReadOnlyLayer = (dataPath) => layer4({ filename: dataPath });
1163
+ var makeReadOnlyLayer = (dataPath) => layer5({ filename: dataPath });
1386
1164
 
1387
1165
  // src/cli/connect.ts
1388
1166
  var command = Command5.make(
@@ -1393,16 +1171,16 @@ var command = Command5.make(
1393
1171
  Argument2.withDescription("WebSocket URL of the inspector (ws://...)")
1394
1172
  )
1395
1173
  },
1396
- ({ data, url }) => Effect8.gen(function* () {
1397
- yield* Effect8.logDebug(`Connecting to URL: ${url}`);
1398
- yield* Effect8.logDebug(`Data file: ${data}`);
1174
+ ({ data, url }) => Effect10.gen(function* () {
1175
+ yield* Effect10.logDebug(`Connecting to URL: ${url}`);
1176
+ yield* Effect10.logDebug(`Data file: ${data}`);
1399
1177
  const cdpManager = yield* CdpManager;
1400
1178
  yield* cdpManager.connect(url);
1401
- yield* Effect8.logInfo(`Connected to ${url}`);
1402
- return yield* Effect8.never;
1179
+ yield* Effect10.logInfo(`Connected to ${url}`);
1180
+ return yield* Effect10.never;
1403
1181
  }).pipe(
1404
- Effect8.scoped,
1405
- Effect8.provide(makeServicesLayer(data))
1182
+ Effect10.scoped,
1183
+ Effect10.provide(makeServicesLayer(data))
1406
1184
  )
1407
1185
  ).pipe(Command5.withDescription("Connect to an existing inspector endpoint"));
1408
1186
  var NODE_INSPECTOR_REGEX = /Debugger listening on (ws:\/\/[^\s]+)/;
@@ -1432,26 +1210,28 @@ var command2 = Command5.make(
1432
1210
  Argument2.variadic({ min: 0 })
1433
1211
  )
1434
1212
  },
1435
- ({ args, data, encodedCommand }) => Effect8.gen(function* () {
1436
- const resolvedArgs = Option4.isSome(encodedCommand) ? JSON.parse(Buffer.from(encodedCommand.value, "base64url").toString("utf8")) : args;
1213
+ ({ args, data, encodedCommand }) => Effect10.gen(function* () {
1214
+ const resolvedArgs = Option3.isSome(encodedCommand) ? JSON.parse(Buffer.from(encodedCommand.value, "base64url").toString("utf8")) : args;
1437
1215
  const [rawExecutable, ...commandArgs] = resolvedArgs;
1438
1216
  const executable = rawExecutable === "node" ? process.execPath : rawExecutable;
1439
- yield* Effect8.logDebug(`Running: ${executable} ${commandArgs.join(" ")}`);
1440
- yield* Effect8.logDebug(`Data file: ${data}`);
1217
+ const executionId = yield* ExecutionId;
1218
+ yield* Console2.log(`Execution ID: ${executionId}`);
1219
+ yield* Effect10.logDebug(`Running: ${executable} ${commandArgs.join(" ")}`);
1220
+ yield* Effect10.logDebug(`Data file: ${data}`);
1441
1221
  const bootloaderPath = yield* getPath;
1442
- yield* Effect8.logDebug(`Bootloader: ${bootloaderPath}`);
1222
+ yield* Effect10.logDebug(`Bootloader: ${bootloaderPath}`);
1443
1223
  const ipcServer = yield* IpcServer;
1444
- yield* Effect8.logDebug(`IPC socket: ${ipcServer.path}`);
1224
+ yield* Effect10.logDebug(`IPC socket: ${ipcServer.path}`);
1445
1225
  const collector = yield* EventCollector;
1446
1226
  const cdpManager = yield* CdpManager;
1447
1227
  const env = buildEnv(bootloaderPath, ipcServer.path);
1448
- yield* Effect8.logDebug(`NODE_OPTIONS: ${env.NODE_OPTIONS}`);
1449
- yield* Stream.runForEach(ipcServer.messages, (message) => Effect8.gen(function* () {
1228
+ yield* Effect10.logDebug(`NODE_OPTIONS: ${env.NODE_OPTIONS}`);
1229
+ yield* Stream.runForEach(ipcServer.messages, (message) => Effect10.gen(function* () {
1450
1230
  yield* collector.collect(message);
1451
1231
  if (message._tag === "InitNotification" && message.inspectorURL) {
1452
1232
  yield* cdpManager.connect(message.inspectorURL);
1453
1233
  }
1454
- })).pipe(Effect8.forkScoped);
1234
+ })).pipe(Effect10.forkScoped);
1455
1235
  const cmd = ChildProcess.make(executable, commandArgs, {
1456
1236
  env,
1457
1237
  extendEnv: true,
@@ -1460,33 +1240,33 @@ var command2 = Command5.make(
1460
1240
  stdout: "inherit"
1461
1241
  });
1462
1242
  const childProcess = yield* cmd;
1463
- yield* Effect8.logDebug(`Started process with PID: ${childProcess.pid}`);
1243
+ yield* Effect10.logDebug(`Started process with PID: ${childProcess.pid}`);
1464
1244
  const textDecoder = new TextDecoder();
1465
1245
  yield* Stream.runForEach(
1466
1246
  childProcess.stderr,
1467
- (chunk) => Effect8.gen(function* () {
1468
- yield* Effect8.sync(() => process.stderr.write(chunk));
1247
+ (chunk) => Effect10.gen(function* () {
1248
+ yield* Effect10.sync(() => process.stderr.write(chunk));
1469
1249
  const inspectorUrl = parseInspectorUrl(chunk, textDecoder);
1470
1250
  if (inspectorUrl) {
1471
- yield* Effect8.logDebug(`Detected inspector URL from stderr: ${inspectorUrl}`);
1251
+ yield* Effect10.logDebug(`Detected inspector URL from stderr: ${inspectorUrl}`);
1472
1252
  yield* cdpManager.connect(inspectorUrl);
1473
1253
  }
1474
1254
  })
1475
- ).pipe(Effect8.forkScoped);
1476
- const forwardSignal = (signal) => Effect8.sync(() => {
1255
+ ).pipe(Effect10.forkScoped);
1256
+ const forwardSignal = (signal) => Effect10.sync(() => {
1477
1257
  process.on(signal, () => {
1478
- Effect8.runPromise(childProcess.kill({ killSignal: signal }).pipe(Effect8.ignore));
1258
+ Effect10.runPromise(childProcess.kill({ killSignal: signal }).pipe(Effect10.ignore));
1479
1259
  });
1480
1260
  });
1481
1261
  yield* forwardSignal("SIGTERM");
1482
1262
  yield* forwardSignal("SIGINT");
1483
1263
  yield* forwardSignal("SIGHUP");
1484
1264
  const exitCode = yield* childProcess.exitCode;
1485
- yield* Effect8.logDebug(`Process exited with code: ${exitCode}`);
1486
- yield* Effect8.sync(() => process.exitCode = exitCode);
1265
+ yield* Effect10.logDebug(`Process exited with code: ${exitCode}`);
1266
+ yield* Effect10.sync(() => process.exitCode = exitCode);
1487
1267
  }).pipe(
1488
- Effect8.scoped,
1489
- Effect8.provide(makeServicesLayer(data))
1268
+ Effect10.scoped,
1269
+ Effect10.provide(makeServicesLayer(data))
1490
1270
  )
1491
1271
  ).pipe(Command5.withDescription("Run a command with Effect instrumentation"));
1492
1272
  var getSpanId = (span) => span.spanId;
@@ -1501,16 +1281,17 @@ var getEndTime = (span) => {
1501
1281
  };
1502
1282
  var getStatusCode = (span) => {
1503
1283
  if (span._tag === "ExternalSpan") return 0;
1504
- return span.status._tag === "Ended" ? span.status.statusCode ?? 0 : 0;
1284
+ if (span.status._tag === "Started") return 0;
1285
+ return span.status.statusCode ?? (span.status.exit._tag === "Success" ? 1 : 2);
1505
1286
  };
1506
1287
  var getStatusMessage = (span) => {
1507
1288
  if (span._tag === "ExternalSpan") return null;
1508
1289
  return span.status._tag === "Ended" ? span.status.statusMessage ?? null : null;
1509
1290
  };
1510
- var getAttributes = (span) => span._tag === "Span" ? span.attributes ?? {} : {};
1291
+ var getAttributes = (span) => span._tag === "Span" ? Object.fromEntries(span.attributes ?? []) : {};
1511
1292
  var isExternalSpan = (span) => span._tag === "ExternalSpan";
1512
1293
  var parseDurationToNanos = (input) => {
1513
- const duration = Schema3.decodeUnknownSync(Schema3.Duration)(input);
1294
+ const duration = Schema.decodeUnknownSync(Schema.Duration)(input);
1514
1295
  return BigInt(Duration.toMillis(duration)) * 1000000n;
1515
1296
  };
1516
1297
  var formatDuration = (nanos) => {
@@ -1581,12 +1362,12 @@ var formatSpanLine = (span) => {
1581
1362
  };
1582
1363
  var renderGraphNode = (graph, nodeIndex, prefix, isLast, isRoot) => {
1583
1364
  const spanOpt = Graph.getNode(graph, nodeIndex);
1584
- if (Option4.isNone(spanOpt)) return "";
1365
+ if (Option3.isNone(spanOpt)) return "";
1585
1366
  const span = spanOpt.value;
1586
1367
  const children = [];
1587
1368
  for (const childIndex of Graph.neighbors(graph, nodeIndex)) {
1588
1369
  const childSpanOpt = Graph.getNode(graph, childIndex);
1589
- if (Option4.isSome(childSpanOpt)) {
1370
+ if (Option3.isSome(childSpanOpt)) {
1590
1371
  children.push({ index: childIndex, span: childSpanOpt.value });
1591
1372
  }
1592
1373
  }
@@ -1617,6 +1398,10 @@ var command3 = Command5.make(
1617
1398
  "spans",
1618
1399
  {
1619
1400
  data: dataOption,
1401
+ executionId: Flag3.string("execution-id").pipe(
1402
+ Flag3.withDescription("Filter by execution ID"),
1403
+ Flag3.optional
1404
+ ),
1620
1405
  json: jsonOption,
1621
1406
  limit: limitOption,
1622
1407
  minDuration: Flag3.string("min-duration").pipe(
@@ -1637,10 +1422,10 @@ var command3 = Command5.make(
1637
1422
  Flag3.optional
1638
1423
  )
1639
1424
  },
1640
- ({ data, json, limit, minDuration, name, status, trace }) => Effect8.gen(function* () {
1425
+ ({ data, executionId, json, limit, minDuration, name, status, trace }) => Effect10.gen(function* () {
1641
1426
  const storage = yield* Storage;
1642
1427
  let statusCode;
1643
- if (Option4.isSome(status)) {
1428
+ if (Option3.isSome(status)) {
1644
1429
  switch (status.value) {
1645
1430
  case "ok":
1646
1431
  statusCode = 1;
@@ -1652,15 +1437,16 @@ var command3 = Command5.make(
1652
1437
  statusCode = 0;
1653
1438
  break;
1654
1439
  default:
1655
- yield* Effect8.logWarning(`Unknown status: ${status.value}, ignoring filter`);
1440
+ yield* Effect10.logWarning(`Unknown status: ${status.value}, ignoring filter`);
1656
1441
  }
1657
1442
  }
1658
1443
  const filters = {
1659
- ...Option4.isSome(trace) ? { traceId: trace.value } : {},
1660
- ...Option4.isSome(name) ? { name: name.value } : {},
1444
+ ...Option3.isSome(executionId) ? { executionId: executionId.value } : {},
1445
+ ...Option3.isSome(trace) ? { traceId: trace.value } : {},
1446
+ ...Option3.isSome(name) ? { name: name.value } : {},
1661
1447
  ...statusCode !== void 0 ? { status: statusCode } : {},
1662
- ...Option4.isSome(minDuration) ? { minDuration: parseDurationToNanos(minDuration.value) } : {},
1663
- ...Option4.isSome(limit) ? { limit: limit.value } : {}
1448
+ ...Option3.isSome(minDuration) ? { minDuration: parseDurationToNanos(minDuration.value) } : {},
1449
+ ...Option3.isSome(limit) ? { limit: limit.value } : {}
1664
1450
  };
1665
1451
  const spans = yield* storage.getSpans(filters);
1666
1452
  if (json) {
@@ -1682,10 +1468,10 @@ var command3 = Command5.make(
1682
1468
  isExternal: isExternalSpan(s)
1683
1469
  };
1684
1470
  });
1685
- yield* Console.log(JSON.stringify(output, null, 2));
1471
+ yield* Console2.log(JSON.stringify(output, null, 2));
1686
1472
  } else {
1687
1473
  if (spans.length === 0) {
1688
- yield* Console.log("No spans found.");
1474
+ yield* Console2.log("No spans found.");
1689
1475
  } else {
1690
1476
  const spanItems = spans.map((s) => {
1691
1477
  const endTime = getEndTime(s);
@@ -1715,12 +1501,12 @@ var command3 = Command5.make(
1715
1501
  "",
1716
1502
  ...spanItems
1717
1503
  ].join("\n");
1718
- yield* Console.log(renderDoc(doc));
1504
+ yield* Console2.log(renderDoc(doc));
1719
1505
  }
1720
1506
  }
1721
1507
  }).pipe(
1722
- Effect8.scoped,
1723
- Effect8.provide(makeReadOnlyLayer(data))
1508
+ Effect10.scoped,
1509
+ Effect10.provide(makeReadOnlyLayer(data))
1724
1510
  )
1725
1511
  ).pipe(Command5.withDescription("List spans with optional filters"));
1726
1512
  var command4 = Command5.make(
@@ -1732,11 +1518,11 @@ var command4 = Command5.make(
1732
1518
  Argument2.withDescription("The trace ID to display")
1733
1519
  )
1734
1520
  },
1735
- ({ data, json, traceId }) => Effect8.gen(function* () {
1521
+ ({ data, json, traceId }) => Effect10.gen(function* () {
1736
1522
  const storage = yield* Storage;
1737
1523
  const spans = yield* storage.getSpans({ traceId });
1738
1524
  if (spans.length === 0) {
1739
- yield* Console.log(`No spans found for trace: ${traceId}`);
1525
+ yield* Console2.log(`No spans found for trace: ${traceId}`);
1740
1526
  return;
1741
1527
  }
1742
1528
  const traces = yield* storage.getTraces({ limit: 1 });
@@ -1745,7 +1531,7 @@ var command4 = Command5.make(
1745
1531
  if (json) {
1746
1532
  const buildJsonTree = (g, nodeIndex) => {
1747
1533
  const spanOpt = Graph.getNode(g, nodeIndex);
1748
- if (Option4.isNone(spanOpt)) return {};
1534
+ if (Option3.isNone(spanOpt)) return {};
1749
1535
  const span = spanOpt.value;
1750
1536
  const endTime = getEndTime(span);
1751
1537
  const startTime = getStartTime(span);
@@ -1753,7 +1539,7 @@ var command4 = Command5.make(
1753
1539
  const children = [];
1754
1540
  for (const childIndex of Graph.neighbors(g, nodeIndex)) {
1755
1541
  const childSpanOpt = Graph.getNode(g, childIndex);
1756
- if (Option4.isSome(childSpanOpt)) {
1542
+ if (Option3.isSome(childSpanOpt)) {
1757
1543
  children.push({ index: childIndex, span: childSpanOpt.value });
1758
1544
  }
1759
1545
  }
@@ -1774,25 +1560,23 @@ var command4 = Command5.make(
1774
1560
  roots.sort((a, b) => Number(getStartTime(a.span) - getStartTime(b.span)));
1775
1561
  const output = {
1776
1562
  traceId,
1777
- serviceName: traceSummary?.service_name ?? null,
1778
1563
  startTime: traceSummary ? formatTimestamp(traceSummary.start_time) : null,
1779
1564
  spanCount: spans.length,
1780
1565
  spans: roots.map((r) => buildJsonTree(graph, r.index))
1781
1566
  };
1782
- yield* Console.log(JSON.stringify(output, null, 2));
1567
+ yield* Console2.log(JSON.stringify(output, null, 2));
1783
1568
  } else {
1784
1569
  const header = [
1785
1570
  field("Trace", traceId),
1786
- field("Service", traceSummary?.service_name ?? "(unknown)"),
1787
1571
  field("Started", traceSummary ? formatTimestamp(traceSummary.start_time) : "(unknown)"),
1788
1572
  ""
1789
1573
  ].join("\n");
1790
1574
  const treeDoc = renderSpanGraph(graph);
1791
- yield* Console.log(renderDoc([header, treeDoc].filter((line) => line.length > 0).join("\n")));
1575
+ yield* Console2.log(renderDoc([header, treeDoc].filter((line) => line.length > 0).join("\n")));
1792
1576
  }
1793
1577
  }).pipe(
1794
- Effect8.scoped,
1795
- Effect8.provide(makeReadOnlyLayer(data))
1578
+ Effect10.scoped,
1579
+ Effect10.provide(makeReadOnlyLayer(data))
1796
1580
  )
1797
1581
  ).pipe(Command5.withDescription("Show a trace as a tree view"));
1798
1582
  var command5 = Command5.make(
@@ -1800,12 +1584,11 @@ var command5 = Command5.make(
1800
1584
  {
1801
1585
  data: dataOption,
1802
1586
  json: jsonOption,
1803
- limit: limitOption,
1804
- service: Flag3.string("service").pipe(
1805
- Flag3.withAlias("s"),
1806
- Flag3.withDescription("Filter by service name"),
1587
+ executionId: Flag3.string("execution-id").pipe(
1588
+ Flag3.withDescription("Filter by execution ID"),
1807
1589
  Flag3.optional
1808
1590
  ),
1591
+ limit: limitOption,
1809
1592
  since: Flag3.string("since").pipe(
1810
1593
  Flag3.withDescription("Filter by time range (e.g., '1h', '30m')"),
1811
1594
  Flag3.optional
@@ -1815,10 +1598,10 @@ var command5 = Command5.make(
1815
1598
  Flag3.optional
1816
1599
  )
1817
1600
  },
1818
- ({ data, json, limit, service, since, status }) => Effect8.gen(function* () {
1601
+ ({ data, executionId, json, limit, since, status }) => Effect10.gen(function* () {
1819
1602
  const storage = yield* Storage;
1820
1603
  let statusCode;
1821
- if (Option4.isSome(status)) {
1604
+ if (Option3.isSome(status)) {
1822
1605
  switch (status.value) {
1823
1606
  case "ok":
1824
1607
  statusCode = 1;
@@ -1830,44 +1613,42 @@ var command5 = Command5.make(
1830
1613
  statusCode = 0;
1831
1614
  break;
1832
1615
  default:
1833
- yield* Effect8.logWarning(`Unknown status: ${status.value}, ignoring filter`);
1616
+ yield* Effect10.logWarning(`Unknown status: ${status.value}, ignoring filter`);
1834
1617
  }
1835
1618
  }
1836
1619
  let sinceNanos;
1837
- if (Option4.isSome(since)) {
1620
+ if (Option3.isSome(since)) {
1838
1621
  const nowNanos = BigInt(Date.now()) * 1000000n;
1839
1622
  const durationNanos = parseDurationToNanos(since.value);
1840
1623
  sinceNanos = nowNanos - durationNanos;
1841
1624
  }
1842
1625
  const filters = {
1843
- ...Option4.isSome(service) ? { service: service.value } : {},
1626
+ ...Option3.isSome(executionId) ? { executionId: executionId.value } : {},
1844
1627
  ...statusCode !== void 0 ? { status: statusCode } : {},
1845
1628
  ...sinceNanos !== void 0 ? { since: sinceNanos } : {},
1846
- ...Option4.isSome(limit) ? { limit: limit.value } : {}
1629
+ ...Option3.isSome(limit) ? { limit: limit.value } : {}
1847
1630
  };
1848
1631
  const traces = yield* storage.getTraces(filters);
1849
1632
  if (json) {
1850
1633
  const output = traces.map((t) => ({
1851
1634
  traceId: t.trace_id,
1852
1635
  rootSpanName: t.root_span_name,
1853
- serviceName: t.service_name,
1854
1636
  spanCount: t.span_count,
1855
1637
  status: t.status,
1856
1638
  startTime: formatTimestamp(t.start_time),
1857
1639
  endTime: t.end_time ? formatTimestamp(t.end_time) : null,
1858
1640
  durationMs: t.end_time ? Number((t.end_time - t.start_time) / 1000000n) : null
1859
1641
  }));
1860
- yield* Console.log(JSON.stringify(output, null, 2));
1642
+ yield* Console2.log(JSON.stringify(output, null, 2));
1861
1643
  } else {
1862
1644
  if (traces.length === 0) {
1863
- yield* Console.log("No traces found.");
1645
+ yield* Console2.log("No traces found.");
1864
1646
  } else {
1865
1647
  const traceItems = traces.map((t) => {
1866
1648
  const duration = t.end_time ? formatDuration(t.end_time - t.start_time) : "running";
1867
1649
  return [
1868
1650
  t.trace_id,
1869
1651
  ` ${field("Name", t.root_span_name ?? "(no root span)")}`,
1870
- ` ${field("Service", t.service_name ?? "(unknown)")}`,
1871
1652
  ` ${field("Spans", String(t.span_count))}`,
1872
1653
  ` ${field("Status", formatStatusDoc(t.status))}`,
1873
1654
  ` ${field("Started", formatTimestamp(t.start_time))}`,
@@ -1879,12 +1660,12 @@ var command5 = Command5.make(
1879
1660
  "",
1880
1661
  ...traceItems
1881
1662
  ].join("\n");
1882
- yield* Console.log(renderDoc(doc));
1663
+ yield* Console2.log(renderDoc(doc));
1883
1664
  }
1884
1665
  }
1885
1666
  }).pipe(
1886
- Effect8.scoped,
1887
- Effect8.provide(makeReadOnlyLayer(data))
1667
+ Effect10.scoped,
1668
+ Effect10.provide(makeReadOnlyLayer(data))
1888
1669
  )
1889
1670
  ).pipe(Command5.withDescription("List traces with optional filters"));
1890
1671
 
@@ -1910,6 +1691,6 @@ var run = (args) => cli(encodeRunSeparator(args));
1910
1691
 
1911
1692
  // src/bin.ts
1912
1693
  run(process.argv.slice(2)).pipe(
1913
- Effect8.provide(NodeServices.layer),
1694
+ Effect10.provide(NodeServices.layer),
1914
1695
  NodeRuntime.runMain
1915
1696
  );