iii-sdk 0.12.0-next.1 → 0.14.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE.spdx +13 -10
  2. package/README.md +17 -28
  3. package/dist/index.cjs +119 -107
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +29 -2
  6. package/dist/index.d.cts.map +1 -1
  7. package/dist/index.d.mts +29 -2
  8. package/dist/index.d.mts.map +1 -1
  9. package/dist/index.mjs +95 -58
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/state.cjs.map +1 -1
  12. package/dist/state.d.cts +8 -1
  13. package/dist/state.d.cts.map +1 -1
  14. package/dist/state.d.mts +8 -1
  15. package/dist/state.d.mts.map +1 -1
  16. package/dist/state.mjs.map +1 -1
  17. package/dist/{stream-BkrU83KD.d.mts → stream-0aOn-1J0.d.cts} +99 -11
  18. package/dist/stream-0aOn-1J0.d.cts.map +1 -0
  19. package/dist/{stream-CJdvFip3.d.cts → stream-R8MrPAf1.d.mts} +99 -11
  20. package/dist/stream-R8MrPAf1.d.mts.map +1 -0
  21. package/dist/stream.d.cts +2 -2
  22. package/dist/stream.d.mts +2 -2
  23. package/dist/{utils-D15-mMqf.mjs → telemetry-system-CFshsuNv.mjs} +248 -76
  24. package/dist/telemetry-system-CFshsuNv.mjs.map +1 -0
  25. package/dist/{utils-zW5CJdUp.cjs → telemetry-system-IPGWo6Uk.cjs} +348 -76
  26. package/dist/telemetry-system-IPGWo6Uk.cjs.map +1 -0
  27. package/dist/telemetry.cjs +37 -28
  28. package/dist/telemetry.d.cts +2 -2
  29. package/dist/telemetry.d.mts +2 -2
  30. package/dist/telemetry.mjs +2 -2
  31. package/dist/{utils-B6IYL9lX.d.mts → utils-CeudjtzM.d.mts} +53 -64
  32. package/dist/utils-CeudjtzM.d.mts.map +1 -0
  33. package/dist/{utils-BkIiccFQ.d.cts → utils-pbn8jUT-.d.cts} +53 -64
  34. package/dist/utils-pbn8jUT-.d.cts.map +1 -0
  35. package/package.json +1 -1
  36. package/dist/stream-BkrU83KD.d.mts.map +0 -1
  37. package/dist/stream-CJdvFip3.d.cts.map +0 -1
  38. package/dist/utils-B6IYL9lX.d.mts.map +0 -1
  39. package/dist/utils-BkIiccFQ.d.cts.map +0 -1
  40. package/dist/utils-D15-mMqf.mjs.map +0 -1
  41. package/dist/utils-zW5CJdUp.cjs.map +0 -1
package/LICENSE.spdx CHANGED
@@ -1,19 +1,22 @@
1
- SPDXVersion: SPDX-2.1
1
+ SPDXVersion: SPDX-2.3
2
2
  DataLicense: CC0-1.0
3
+ SPDXID: SPDXRef-DOCUMENT
4
+ DocumentName: iii
5
+ DocumentNamespace: https://iii.dev/spdx/iii
3
6
  PackageName: iii
4
- DataFormat: SPDXRef-1
7
+ SPDXID: SPDXRef-Package
5
8
  PackageSupplier: Organization: Motia LLC
6
9
  PackageHomePage: https://iii.dev
7
- PackageLicenseDeclared: Elastic-2.0
8
- PackageLicenseDeclared: Apache-2.0
10
+ PackageLicenseDeclared: Apache-2.0 AND Elastic-2.0
11
+ PackageLicenseConcluded: Apache-2.0 AND Elastic-2.0
9
12
  PackageCopyrightText: 2024-present, Motia LLC
10
- PackageSummary: <text>iii is a single engine with three primitives (Function, Trigger, Discovery)
11
- that replaces API frameworks, task queues, cron schedulers, pub/sub, state stores,
12
- and observability pipelines.
13
+ PackageSummary: <text>iii turns distributed backend complexity into a
14
+ simple set of real-time, interoperable primitives called Workers,
15
+ Triggers, and Functions. The result is coordinated execution
16
+ that behaves as if it were a single runtime.
13
17
  </text>
14
- PackageComment: <text>The engine runtime (engine/) is licensed under Elastic License 2.0.
15
- All other components (sdk/, cli/, console/, frameworks/, docs/, website/)
16
- are licensed under Apache License 2.0.
18
+ PackageComment: <text>Inbound contributions from external
19
+ contributors are accepted under Apache-2.0 only; see CONTRIBUTING.md.
17
20
  </text>
18
21
  Created: 2024-01-01T00:00:00Z
19
22
  PackageDownloadLocation: git://github.com/iii-hq/iii
package/README.md CHANGED
@@ -8,7 +8,8 @@ Node.js / TypeScript SDK for the [iii engine](https://github.com/iii-hq/iii).
8
8
  ## Install
9
9
 
10
10
  ```bash
11
- npm install iii-sdk
11
+ pnpm add iii-sdk
12
+ # or: npm install iii-sdk
12
13
  ```
13
14
 
14
15
  ## Hello World
@@ -18,33 +19,34 @@ import { registerWorker } from 'iii-sdk'
18
19
 
19
20
  const iii = registerWorker('ws://localhost:49134')
20
21
 
21
- iii.registerFunction('greet', async (input) => {
22
+ iii.registerFunction('hello::greet', async (input) => {
22
23
  return { message: `Hello, ${input.name}!` }
23
24
  })
24
25
 
25
26
  iii.registerTrigger({
26
27
  type: 'http',
27
- function_id: 'greet',
28
+ function_id: 'hello::greet',
28
29
  config: { api_path: '/greet', http_method: 'POST' },
29
30
  })
30
31
 
31
- const result = await iii.trigger({ function_id: 'greet', payload: { name: 'world' } })
32
+ const result = await iii.trigger({ function_id: 'hello::greet', payload: { name: 'world' } })
32
33
  ```
33
34
 
34
35
  ## API
35
36
 
36
- | Operation | Signature | Description |
37
- | ------------------------ | ---------------------------------------------------- | ------------------------------------------------------------ |
38
- | Initialize | `registerWorker(url, options?)` | Create and connect to the engine. Returns an `ISdk` instance |
39
- | Register function | `iii.registerFunction(id, handler, options?)` | Register a function that can be invoked by name |
40
- | Register trigger | `iii.registerTrigger({ type, function_id, config })` | Bind a trigger (HTTP, cron, queue, etc.) to a function |
41
- | Invoke (await) | `await iii.trigger({ function_id, payload })` | Invoke a function and wait for the result |
42
- | Invoke (fire-and-forget) | `iii.trigger({ function_id, payload, action: TriggerAction.Void() })` | Invoke without waiting |
37
+ | Operation | Signature | Description |
38
+ | ------------------------ | --------------------------------------------------------------------------------- | ------------------------------------------------------------ |
39
+ | Initialize | `registerWorker(url, options?)` | Create and connect to the engine. Returns an `ISdk` instance |
40
+ | Register function | `iii.registerFunction(id, handler, options?)` | Register a function that can be invoked by name |
41
+ | Register trigger | `iii.registerTrigger({ type, function_id, config })` | Bind a trigger (HTTP, cron, queue, etc.) to a function |
42
+ | Invoke (await) | `await iii.trigger({ function_id, payload })` | Invoke a function and wait for the result |
43
+ | Invoke (fire-and-forget) | `iii.trigger({ function_id, payload, action: TriggerAction.Void() })` | Invoke without waiting |
44
+ | Invoke (enqueue) | `iii.trigger({ function_id, payload, action: TriggerAction.Enqueue({ queue }) })` | Route invocation through a named queue |
43
45
 
44
46
  ### Registering Functions
45
47
 
46
48
  ```javascript
47
- iii.registerFunction('orders.create', async (input) => {
49
+ iii.registerFunction('orders::create', async (input) => {
48
50
  return { status_code: 201, body: { id: '123', item: input.body.item } }
49
51
  })
50
52
  ```
@@ -54,7 +56,7 @@ iii.registerFunction('orders.create', async (input) => {
54
56
  ```javascript
55
57
  iii.registerTrigger({
56
58
  type: 'http',
57
- function_id: 'orders.create',
59
+ function_id: 'orders::create',
58
60
  config: { api_path: '/orders', http_method: 'POST' },
59
61
  })
60
62
  ```
@@ -66,24 +68,11 @@ import { registerWorker, TriggerAction } from 'iii-sdk'
66
68
 
67
69
  const iii = registerWorker('ws://localhost:49134')
68
70
 
69
- const result = await iii.trigger({ function_id: 'orders.create', payload: { item: 'widget' } })
71
+ const result = await iii.trigger({ function_id: 'orders::create', payload: { item: 'widget' } })
70
72
 
71
- iii.trigger({ function_id: 'analytics.track', payload: { event: 'page_view' }, action: TriggerAction.Void() })
73
+ iii.trigger({ function_id: 'analytics::track', payload: { event: 'page_view' }, action: TriggerAction.Void() })
72
74
  ```
73
75
 
74
- ## Node Modules
75
-
76
- | Import | What it provides |
77
- | ------------------- | ------------------------------------- |
78
- | `iii-sdk` | Core SDK (`registerWorker`, types) |
79
- | `iii-sdk/stream` | Stream client for real-time state |
80
- | `iii-sdk/state` | State client for key-value operations |
81
- | `iii-sdk/telemetry` | OpenTelemetry integration |
82
-
83
- ## Removed methods
84
-
85
- `call`, `callVoid`, and `triggerVoid` have been removed. Use `trigger()` for all invocations. For fire-and-forget, use `trigger({ function_id, payload, action: TriggerAction.Void() })`.
86
-
87
76
  ## Resources
88
77
 
89
78
  - [Documentation](https://iii.dev/docs)
package/dist/index.cjs CHANGED
@@ -1,38 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- //#region \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
- key = keys[i];
13
- if (!__hasOwnProp.call(to, key) && key !== except) {
14
- __defProp(to, key, {
15
- get: ((k) => from[k]).bind(null, key),
16
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
- });
18
- }
19
- }
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
- value: mod,
25
- enumerable: true
26
- }) : target, mod));
27
-
28
- //#endregion
29
- const require_utils = require('./utils-zW5CJdUp.cjs');
2
+ const require_telemetry_system = require('./telemetry-system-IPGWo6Uk.cjs');
30
3
  let node_stream = require("node:stream");
31
4
  let ws = require("ws");
32
5
  let _opentelemetry_api = require("@opentelemetry/api");
33
6
  let node_module = require("node:module");
34
7
  let node_os = require("node:os");
35
- node_os = __toESM(node_os);
8
+ node_os = require_telemetry_system.__toESM(node_os);
36
9
  let _opentelemetry_api_logs = require("@opentelemetry/api-logs");
37
10
 
38
11
  //#region src/channels.ts
@@ -218,6 +191,29 @@ function buildChannelUrl(engineWsBase, channelId, accessKey, direction) {
218
191
  return `${engineWsBase.replace(/\/$/, "")}/ws/channels/${channelId}?key=${encodeURIComponent(accessKey)}&dir=${direction}`;
219
192
  }
220
193
 
194
+ //#endregion
195
+ //#region src/errors.ts
196
+ var IIIInvocationError = class extends Error {
197
+ constructor(init) {
198
+ super(`${init.code}: ${init.message}`);
199
+ this.name = "IIIInvocationError";
200
+ this.code = init.code;
201
+ this.function_id = init.function_id;
202
+ this.stacktrace = init.stacktrace;
203
+ }
204
+ };
205
+ /**
206
+ * True when `value` looks like the wire `ErrorBody` the engine sends in
207
+ * `InvocationResult.error`: `{ code: string, message: string, stacktrace?: string }`.
208
+ * Used to distinguish an engine rejection (which we wrap in
209
+ * {@link IIIInvocationError}) from a JS `Error` thrown elsewhere.
210
+ */
211
+ function isErrorBody(value) {
212
+ if (typeof value !== "object" || value === null) return false;
213
+ const v = value;
214
+ return typeof v.code === "string" && typeof v.message === "string" && (v.stacktrace === void 0 || typeof v.stacktrace === "string");
215
+ }
216
+
221
217
  //#endregion
222
218
  //#region src/iii-types.ts
223
219
  let MessageType = /* @__PURE__ */ function(MessageType) {
@@ -253,7 +249,6 @@ var Sdk = class {
253
249
  this.invocations = /* @__PURE__ */ new Map();
254
250
  this.triggers = /* @__PURE__ */ new Map();
255
251
  this.triggerTypes = /* @__PURE__ */ new Map();
256
- this.functionsAvailableCallbacks = /* @__PURE__ */ new Set();
257
252
  this.messagesToSend = [];
258
253
  this.reconnectAttempt = 0;
259
254
  this.connectionState = "disconnected";
@@ -340,9 +335,42 @@ var Sdk = class {
340
335
  this.functions.set(functionId, {
341
336
  message: fullMessage,
342
337
  handler: async (input, traceparent, baggage) => {
343
- if (require_utils.getTracer()) {
344
- const parentContext = require_utils.extractContext(traceparent, baggage);
345
- return _opentelemetry_api.context.with(parentContext, () => require_utils.withSpan(`call ${functionId}`, { kind: _opentelemetry_api.SpanKind.SERVER }, async () => await handler(input)));
338
+ const tracePayloads = !(process.env.III_DISABLE_TRACE_PAYLOADS === "1" || process.env.III_DISABLE_TRACE_PAYLOADS?.toLowerCase() === "true");
339
+ const payloadMaxBytes = require_telemetry_system.resolveMaxBytesFromEnv();
340
+ const runHandler = async () => {
341
+ if (tracePayloads) {
342
+ const { json, truncated } = require_telemetry_system.redactAndTruncate(input, payloadMaxBytes);
343
+ require_telemetry_system.recordSpanEvent("iii.invocation.input", {
344
+ "iii.payload.json": json,
345
+ "iii.payload.truncated": truncated
346
+ });
347
+ }
348
+ try {
349
+ const result = await handler(input);
350
+ if (tracePayloads) {
351
+ const { json, truncated } = require_telemetry_system.redactAndTruncate(result, payloadMaxBytes);
352
+ require_telemetry_system.recordSpanEvent("iii.invocation.output", {
353
+ "iii.payload.json": json,
354
+ "iii.payload.truncated": truncated,
355
+ "iii.payload.ok": true
356
+ });
357
+ }
358
+ return result;
359
+ } catch (err) {
360
+ if (tracePayloads) {
361
+ const { json, truncated } = require_telemetry_system.redactAndTruncate({ error: err instanceof Error ? err.message : String(err) }, payloadMaxBytes);
362
+ require_telemetry_system.recordSpanEvent("iii.invocation.output", {
363
+ "iii.payload.json": json,
364
+ "iii.payload.truncated": truncated,
365
+ "iii.payload.ok": false
366
+ });
367
+ }
368
+ throw err;
369
+ }
370
+ };
371
+ if (require_telemetry_system.getTracer()) {
372
+ const parentContext = require_telemetry_system.extractContext(traceparent, baggage);
373
+ return _opentelemetry_api.context.with(parentContext, () => require_telemetry_system.withSpan(`call ${functionId}`, { kind: _opentelemetry_api.SpanKind.SERVER }, async () => await runHandler()));
346
374
  }
347
375
  const traceId = crypto.randomUUID().replace(/-/g, "");
348
376
  const spanId = crypto.randomUUID().replace(/-/g, "").slice(0, 16);
@@ -351,7 +379,7 @@ var Sdk = class {
351
379
  spanId,
352
380
  traceFlags: 1
353
381
  });
354
- return _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), syntheticSpan), async () => await handler(input));
382
+ return _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), syntheticSpan), async () => await runHandler());
355
383
  }
356
384
  });
357
385
  } else this.functions.set(functionId, { message: fullMessage });
@@ -390,8 +418,8 @@ var Sdk = class {
390
418
  const { function_id, payload, action, timeoutMs } = request;
391
419
  const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
392
420
  if (action?.type === "void") {
393
- const traceparent = require_utils.injectTraceparent();
394
- const baggage = require_utils.injectBaggage();
421
+ const traceparent = require_telemetry_system.injectTraceparent();
422
+ const baggage = require_telemetry_system.injectBaggage();
395
423
  this.sendMessage(MessageType.InvokeFunction, {
396
424
  function_id,
397
425
  data: payload,
@@ -402,13 +430,17 @@ var Sdk = class {
402
430
  return;
403
431
  }
404
432
  const invocation_id = crypto.randomUUID();
405
- const traceparent = require_utils.injectTraceparent();
406
- const baggage = require_utils.injectBaggage();
433
+ const traceparent = require_telemetry_system.injectTraceparent();
434
+ const baggage = require_telemetry_system.injectBaggage();
407
435
  return new Promise((resolve, reject) => {
408
436
  const timeout = setTimeout(() => {
409
437
  if (this.invocations.get(invocation_id)) {
410
438
  this.invocations.delete(invocation_id);
411
- reject(/* @__PURE__ */ new Error(`Invocation timeout after ${effectiveTimeout}ms: ${function_id}`));
439
+ reject(new IIIInvocationError({
440
+ code: "TIMEOUT",
441
+ message: `invocation timed out after ${effectiveTimeout}ms`,
442
+ function_id
443
+ }));
412
444
  }
413
445
  }, effectiveTimeout);
414
446
  this.invocations.set(invocation_id, {
@@ -420,6 +452,7 @@ var Sdk = class {
420
452
  clearTimeout(timeout);
421
453
  reject(error);
422
454
  },
455
+ function_id,
423
456
  timeout
424
457
  });
425
458
  this.sendMessage(MessageType.InvokeFunction, {
@@ -432,30 +465,6 @@ var Sdk = class {
432
465
  });
433
466
  });
434
467
  };
435
- this.listFunctions = async () => {
436
- return (await this.trigger({
437
- function_id: require_utils.EngineFunctions.LIST_FUNCTIONS,
438
- payload: {}
439
- })).functions;
440
- };
441
- this.listWorkers = async () => {
442
- return (await this.trigger({
443
- function_id: require_utils.EngineFunctions.LIST_WORKERS,
444
- payload: {}
445
- })).workers;
446
- };
447
- this.listTriggers = async (includeInternal = false) => {
448
- return (await this.trigger({
449
- function_id: require_utils.EngineFunctions.LIST_TRIGGERS,
450
- payload: { include_internal: includeInternal }
451
- })).triggers;
452
- };
453
- this.listTriggerTypes = async (includeInternal = false) => {
454
- return (await this.trigger({
455
- function_id: require_utils.EngineFunctions.LIST_TRIGGER_TYPES,
456
- payload: { include_internal: includeInternal }
457
- })).trigger_types;
458
- };
459
468
  this.createStream = (streamName, stream) => {
460
469
  this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream));
461
470
  this.registerFunction(`stream::set(${streamName})`, stream.set.bind(stream));
@@ -463,35 +472,10 @@ var Sdk = class {
463
472
  this.registerFunction(`stream::list(${streamName})`, stream.list.bind(stream));
464
473
  this.registerFunction(`stream::list_groups(${streamName})`, stream.listGroups.bind(stream));
465
474
  };
466
- this.onFunctionsAvailable = (callback) => {
467
- this.functionsAvailableCallbacks.add(callback);
468
- if (!this.functionsAvailableTrigger) {
469
- if (!this.functionsAvailableFunctionPath) this.functionsAvailableFunctionPath = `engine.on_functions_available.${crypto.randomUUID()}`;
470
- const function_id = this.functionsAvailableFunctionPath;
471
- if (!this.functions.has(function_id)) this.registerFunction(function_id, async ({ functions }) => {
472
- this.functionsAvailableCallbacks.forEach((handler) => {
473
- handler(functions);
474
- });
475
- return null;
476
- });
477
- this.functionsAvailableTrigger = this.registerTrigger({
478
- type: require_utils.EngineTriggers.FUNCTIONS_AVAILABLE,
479
- function_id,
480
- config: {}
481
- });
482
- }
483
- return () => {
484
- this.functionsAvailableCallbacks.delete(callback);
485
- if (this.functionsAvailableCallbacks.size === 0 && this.functionsAvailableTrigger) {
486
- this.functionsAvailableTrigger.unregister();
487
- this.functionsAvailableTrigger = void 0;
488
- }
489
- };
490
- };
491
475
  this.shutdown = async () => {
492
476
  this.isShuttingDown = true;
493
477
  this.stopMetricsReporting();
494
- await require_utils.shutdownOtel();
478
+ await require_telemetry_system.shutdownOtel();
495
479
  this.clearReconnectTimeout();
496
480
  for (const [_id, invocation] of this.invocations) {
497
481
  if (invocation.timeout) clearTimeout(invocation.timeout);
@@ -500,7 +484,10 @@ var Sdk = class {
500
484
  this.invocations.clear();
501
485
  if (this.ws) {
502
486
  this.ws.removeAllListeners();
503
- this.ws.close();
487
+ this.ws.on("error", () => {});
488
+ try {
489
+ this.ws.close();
490
+ } catch {}
504
491
  this.ws = void 0;
505
492
  }
506
493
  this.setConnectionState("disconnected");
@@ -509,10 +496,10 @@ var Sdk = class {
509
496
  this.metricsReportingEnabled = options?.enableMetricsReporting ?? true;
510
497
  this.invocationTimeoutMs = options?.invocationTimeoutMs ?? 3e4;
511
498
  this.reconnectionConfig = {
512
- ...require_utils.DEFAULT_BRIDGE_RECONNECTION_CONFIG,
499
+ ...require_telemetry_system.DEFAULT_BRIDGE_RECONNECTION_CONFIG,
513
500
  ...options?.reconnectionConfig
514
501
  };
515
- require_utils.initOtel({
502
+ require_telemetry_system.initOtel({
516
503
  ...options?.otel,
517
504
  engineWsUrl: this.address
518
505
  });
@@ -522,16 +509,17 @@ var Sdk = class {
522
509
  const telemetryOpts = this.options?.telemetry;
523
510
  const language = telemetryOpts?.language ?? Intl.DateTimeFormat().resolvedOptions().locale ?? process.env.LANG?.split(".")[0];
524
511
  this.trigger({
525
- function_id: require_utils.EngineFunctions.REGISTER_WORKER,
512
+ function_id: require_telemetry_system.EngineFunctions.REGISTER_WORKER,
526
513
  payload: {
527
514
  runtime: "node",
528
515
  version: SDK_VERSION,
529
516
  name: this.workerName,
530
517
  os: getOsInfo(),
531
518
  pid: process.pid,
519
+ isolation: process.env.III_ISOLATION || null,
532
520
  telemetry: {
533
521
  language,
534
- project_name: telemetryOpts?.project_name,
522
+ project_name: telemetryOpts?.project_name ?? require_telemetry_system.detectProjectName(),
535
523
  framework: telemetryOpts?.framework?.trim() || "iii-node",
536
524
  amplitude_api_key: telemetryOpts?.amplitude_api_key
537
525
  }
@@ -582,18 +570,18 @@ var Sdk = class {
582
570
  }
583
571
  startMetricsReporting() {
584
572
  if (!this.metricsReportingEnabled || !this.workerId) return;
585
- const meter = require_utils.getMeter();
573
+ const meter = require_telemetry_system.getMeter();
586
574
  if (!meter) {
587
575
  console.warn("[iii] Worker metrics disabled: OpenTelemetry not initialized. Call initOtel() with metricsEnabled: true before creating the iii.");
588
576
  return;
589
577
  }
590
- require_utils.registerWorkerGauges(meter, {
578
+ require_telemetry_system.registerWorkerGauges(meter, {
591
579
  workerId: this.workerId,
592
580
  workerName: this.workerName
593
581
  });
594
582
  }
595
583
  stopMetricsReporting() {
596
- require_utils.stopWorkerGauges();
584
+ require_telemetry_system.stopWorkerGauges();
597
585
  }
598
586
  onSocketClose() {
599
587
  this.ws?.removeAllListeners();
@@ -677,7 +665,7 @@ var Sdk = class {
677
665
  else if (!skipIfClosed) this.messagesToSend.push(wireMessage);
678
666
  }
679
667
  logError(message, error) {
680
- const otelLogger = require_utils.getLogger();
668
+ const otelLogger = require_telemetry_system.getLogger();
681
669
  const errorMessage = error instanceof Error ? error.message : String(error ?? "");
682
670
  if (otelLogger) otelLogger.emit({
683
671
  severityNumber: _opentelemetry_api_logs.SeverityNumber.ERROR,
@@ -689,12 +677,34 @@ var Sdk = class {
689
677
  const invocation = this.invocations.get(invocation_id);
690
678
  if (invocation) {
691
679
  if (invocation.timeout) clearTimeout(invocation.timeout);
692
- error ? invocation.reject(error) : invocation.resolve(result);
680
+ if (error) invocation.reject(this.toInvocationError(error, invocation.function_id));
681
+ else invocation.resolve(result);
693
682
  }
694
683
  this.invocations.delete(invocation_id);
695
684
  }
685
+ /**
686
+ * Wrap a wire-format `ErrorBody` in {@link IIIInvocationError} so callers get
687
+ * a real `Error` with a readable `.message` and a typed `.code`. Pass-through
688
+ * for values that are already `Error` subclasses. Everything else is wrapped
689
+ * under an `UNKNOWN` code so `String(err) !== '[object Object]'` holds for
690
+ * every rejection path.
691
+ */
692
+ toInvocationError(error, function_id) {
693
+ if (error instanceof Error) return error;
694
+ if (isErrorBody(error)) return new IIIInvocationError({
695
+ code: error.code,
696
+ message: error.message,
697
+ function_id,
698
+ stacktrace: error.stacktrace
699
+ });
700
+ return new IIIInvocationError({
701
+ code: "UNKNOWN",
702
+ message: typeof error === "string" ? error : JSON.stringify(error) ?? String(error),
703
+ function_id
704
+ });
705
+ }
696
706
  resolveChannelValue(value) {
697
- if (require_utils.isChannelRef(value)) return value.direction === "read" ? new ChannelReader(this.address, value) : new ChannelWriter(this.address, value);
707
+ if (require_telemetry_system.isChannelRef(value)) return value.direction === "read" ? new ChannelReader(this.address, value) : new ChannelWriter(this.address, value);
698
708
  if (Array.isArray(value)) return value.map((item) => this.resolveChannelValue(item));
699
709
  if (value !== null && typeof value === "object") {
700
710
  const out = {};
@@ -705,8 +715,8 @@ var Sdk = class {
705
715
  }
706
716
  async onInvokeFunction(invocation_id, function_id, input, traceparent, baggage) {
707
717
  const fn = this.functions.get(function_id);
708
- const getResponseTraceparent = () => require_utils.injectTraceparent() ?? traceparent;
709
- const getResponseBaggage = () => require_utils.injectBaggage() ?? baggage;
718
+ const getResponseTraceparent = () => require_telemetry_system.injectTraceparent() ?? traceparent;
719
+ const getResponseBaggage = () => require_telemetry_system.injectBaggage() ?? baggage;
710
720
  const resolvedInput = this.resolveChannelValue(input);
711
721
  if (fn?.handler) {
712
722
  if (!invocation_id) {
@@ -899,7 +909,7 @@ const registerWorker = (address, options) => new Sdk(address, options);
899
909
  */
900
910
  var Logger = class {
901
911
  get otelLogger() {
902
- if (!this._otelLogger) this._otelLogger = require_utils.getLogger();
912
+ if (!this._otelLogger) this._otelLogger = require_telemetry_system.getLogger();
903
913
  return this._otelLogger;
904
914
  }
905
915
  constructor(traceId, serviceName, spanId) {
@@ -910,8 +920,8 @@ var Logger = class {
910
920
  }
911
921
  emit(message, severity, data) {
912
922
  const attributes = {};
913
- const traceId = this.traceId ?? require_utils.currentTraceId();
914
- const spanId = this.spanId ?? require_utils.currentSpanId();
923
+ const traceId = this.traceId ?? require_telemetry_system.currentTraceId();
924
+ const spanId = this.spanId ?? require_telemetry_system.currentSpanId();
915
925
  if (traceId) attributes.trace_id = traceId;
916
926
  if (spanId) attributes.span_id = spanId;
917
927
  if (this.serviceName) attributes["service.name"] = this.serviceName;
@@ -1006,9 +1016,11 @@ var Logger = class {
1006
1016
  //#endregion
1007
1017
  exports.ChannelReader = ChannelReader;
1008
1018
  exports.ChannelWriter = ChannelWriter;
1019
+ exports.EngineFunctions = require_telemetry_system.EngineFunctions;
1020
+ exports.EngineTriggers = require_telemetry_system.EngineTriggers;
1021
+ exports.IIIInvocationError = IIIInvocationError;
1009
1022
  exports.Logger = Logger;
1010
1023
  exports.TriggerAction = TriggerAction;
1011
- exports.__toESM = __toESM;
1012
- exports.http = require_utils.http;
1024
+ exports.http = require_telemetry_system.http;
1013
1025
  exports.registerWorker = registerWorker;
1014
1026
  //# sourceMappingURL=index.cjs.map