iii-sdk 0.8.3 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -11
- package/dist/index.cjs +278 -142
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +177 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +177 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +259 -125
- package/dist/index.mjs.map +1 -1
- package/dist/state.cjs +7 -5
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +38 -13
- package/dist/state.d.cts.map +1 -1
- package/dist/state.d.mts +38 -13
- package/dist/state.d.mts.map +1 -1
- package/dist/state.mjs +6 -5
- package/dist/state.mjs.map +1 -1
- package/dist/stream-C1zUjhzk.d.mts +145 -0
- package/dist/stream-C1zUjhzk.d.mts.map +1 -0
- package/dist/stream-lxenNA3s.d.cts +145 -0
- package/dist/stream-lxenNA3s.d.cts.map +1 -0
- package/dist/stream.d.cts +1 -1
- package/dist/stream.d.mts +1 -1
- package/dist/telemetry.cjs +6 -5
- package/dist/telemetry.d.cts +10 -11
- package/dist/telemetry.d.cts.map +1 -1
- package/dist/telemetry.d.mts +10 -11
- package/dist/telemetry.d.mts.map +1 -1
- package/dist/telemetry.mjs +1 -1
- package/dist/utils-BvWlFlLq.d.cts +839 -0
- package/dist/utils-BvWlFlLq.d.cts.map +1 -0
- package/dist/{utils-BJTjoUdq.cjs → utils-C6yTT4Js.cjs} +311 -282
- package/dist/utils-C6yTT4Js.cjs.map +1 -0
- package/dist/utils-_zSeatp1.d.mts +839 -0
- package/dist/utils-_zSeatp1.d.mts.map +1 -0
- package/dist/{utils-coGqiBHT.mjs → utils-xBUm8n1P.mjs} +246 -217
- package/dist/utils-xBUm8n1P.mjs.map +1 -0
- package/package.json +5 -3
- package/typedoc.json +8 -0
- package/vitest.config.ts +4 -4
- package/dist/stream-BEp3rjfm.d.cts +0 -97
- package/dist/stream-BEp3rjfm.d.cts.map +0 -1
- package/dist/stream-Bzpo5JNV.d.mts +0 -97
- package/dist/stream-Bzpo5JNV.d.mts.map +0 -1
- package/dist/utils-BJTjoUdq.cjs.map +0 -1
- package/dist/utils-BaGgUfjl.d.cts +0 -524
- package/dist/utils-BaGgUfjl.d.cts.map +0 -1
- package/dist/utils-CMrMD5Ij.d.mts +0 -524
- package/dist/utils-CMrMD5Ij.d.mts.map +0 -1
- package/dist/utils-coGqiBHT.mjs.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
//#region \0rolldown/runtime.js
|
|
2
3
|
var __create = Object.create;
|
|
3
4
|
var __defProp = Object.defineProperty;
|
|
4
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -25,16 +26,33 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
25
26
|
}) : target, mod));
|
|
26
27
|
|
|
27
28
|
//#endregion
|
|
28
|
-
const require_utils = require('./utils-
|
|
29
|
-
let
|
|
29
|
+
const require_utils = require('./utils-C6yTT4Js.cjs');
|
|
30
|
+
let node_stream = require("node:stream");
|
|
31
|
+
let ws = require("ws");
|
|
32
|
+
let _opentelemetry_api = require("@opentelemetry/api");
|
|
30
33
|
let node_module = require("node:module");
|
|
31
34
|
let node_os = require("node:os");
|
|
32
35
|
node_os = __toESM(node_os);
|
|
33
|
-
let
|
|
34
|
-
let node_stream = require("node:stream");
|
|
35
|
-
let __opentelemetry_api_logs = require("@opentelemetry/api-logs");
|
|
36
|
+
let _opentelemetry_api_logs = require("@opentelemetry/api-logs");
|
|
36
37
|
|
|
37
38
|
//#region src/channels.ts
|
|
39
|
+
/**
|
|
40
|
+
* Write end of a streaming channel. Provides both a Node.js `Writable` stream
|
|
41
|
+
* and a `sendMessage` method for sending structured text messages.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```typescript
|
|
45
|
+
* const channel = await iii.createChannel()
|
|
46
|
+
*
|
|
47
|
+
* // Stream binary data
|
|
48
|
+
* channel.writer.stream.write(Buffer.from('hello'))
|
|
49
|
+
* channel.writer.stream.end()
|
|
50
|
+
*
|
|
51
|
+
* // Or send text messages
|
|
52
|
+
* channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' }))
|
|
53
|
+
* channel.writer.close()
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
38
56
|
var ChannelWriter = class ChannelWriter {
|
|
39
57
|
static {
|
|
40
58
|
this.FRAME_SIZE = 64 * 1024;
|
|
@@ -54,9 +72,12 @@ var ChannelWriter = class ChannelWriter {
|
|
|
54
72
|
callback();
|
|
55
73
|
return;
|
|
56
74
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
75
|
+
const doClose = () => {
|
|
76
|
+
if (this.ws) this.ws.close(1e3, "stream_complete");
|
|
77
|
+
callback();
|
|
78
|
+
};
|
|
79
|
+
if (this.wsReady) setTimeout(doClose, 10);
|
|
80
|
+
else this.ws.on("open", () => setTimeout(doClose, 10));
|
|
60
81
|
},
|
|
61
82
|
destroy: (err, callback) => {
|
|
62
83
|
if (this.ws) this.ws.terminate();
|
|
@@ -79,16 +100,21 @@ var ChannelWriter = class ChannelWriter {
|
|
|
79
100
|
if (!this.stream.destroyed) this.stream.destroy();
|
|
80
101
|
});
|
|
81
102
|
}
|
|
103
|
+
/** Send a text message through the channel. */
|
|
82
104
|
sendMessage(msg) {
|
|
83
105
|
this.ensureConnected();
|
|
84
106
|
this.sendRaw(msg, (err) => {
|
|
85
107
|
if (err) this.stream.destroy(err);
|
|
86
108
|
});
|
|
87
109
|
}
|
|
110
|
+
/** Close the channel writer. */
|
|
88
111
|
close() {
|
|
89
112
|
if (!this.ws) return;
|
|
90
|
-
|
|
91
|
-
|
|
113
|
+
const doClose = () => {
|
|
114
|
+
if (this.ws) this.ws.close(1e3, "channel_close");
|
|
115
|
+
};
|
|
116
|
+
if (this.wsReady) doClose();
|
|
117
|
+
else this.ws.on("open", () => doClose());
|
|
92
118
|
}
|
|
93
119
|
sendChunked(data, callback) {
|
|
94
120
|
let offset = 0;
|
|
@@ -117,6 +143,21 @@ var ChannelWriter = class ChannelWriter {
|
|
|
117
143
|
});
|
|
118
144
|
}
|
|
119
145
|
};
|
|
146
|
+
/**
|
|
147
|
+
* Read end of a streaming channel. Provides both a Node.js `Readable` stream
|
|
148
|
+
* for binary data and an `onMessage` callback for structured text messages.
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```typescript
|
|
152
|
+
* const channel = await iii.createChannel()
|
|
153
|
+
*
|
|
154
|
+
* // Stream binary data
|
|
155
|
+
* channel.reader.stream.on('data', (chunk) => console.log(chunk))
|
|
156
|
+
*
|
|
157
|
+
* // Or receive text messages
|
|
158
|
+
* channel.reader.onMessage((msg) => console.log('Got:', msg))
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
120
161
|
var ChannelReader = class {
|
|
121
162
|
constructor(engineWsBase, ref) {
|
|
122
163
|
this.ws = null;
|
|
@@ -159,9 +200,19 @@ var ChannelReader = class {
|
|
|
159
200
|
this.stream.destroy(err);
|
|
160
201
|
});
|
|
161
202
|
}
|
|
203
|
+
/** Register a callback to receive text messages from the channel. */
|
|
162
204
|
onMessage(callback) {
|
|
163
205
|
this.messageCallbacks.push(callback);
|
|
164
206
|
}
|
|
207
|
+
async readAll() {
|
|
208
|
+
this.ensureConnected();
|
|
209
|
+
const chunks = [];
|
|
210
|
+
for await (const chunk of this.stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
211
|
+
return Buffer.concat(chunks);
|
|
212
|
+
}
|
|
213
|
+
close() {
|
|
214
|
+
if (this.ws && this.ws.readyState !== ws.WebSocket.CLOSED) this.ws.close(1e3, "channel_close");
|
|
215
|
+
}
|
|
165
216
|
};
|
|
166
217
|
function buildChannelUrl(engineWsBase, channelId, accessKey, direction) {
|
|
167
218
|
return `${engineWsBase.replace(/\/$/, "")}/ws/channels/${channelId}?key=${encodeURIComponent(accessKey)}&dir=${direction}`;
|
|
@@ -169,19 +220,19 @@ function buildChannelUrl(engineWsBase, channelId, accessKey, direction) {
|
|
|
169
220
|
|
|
170
221
|
//#endregion
|
|
171
222
|
//#region src/iii-types.ts
|
|
172
|
-
let MessageType = /* @__PURE__ */ function(MessageType
|
|
173
|
-
MessageType
|
|
174
|
-
MessageType
|
|
175
|
-
MessageType
|
|
176
|
-
MessageType
|
|
177
|
-
MessageType
|
|
178
|
-
MessageType
|
|
179
|
-
MessageType
|
|
180
|
-
MessageType
|
|
181
|
-
MessageType
|
|
182
|
-
MessageType
|
|
183
|
-
MessageType
|
|
184
|
-
return MessageType
|
|
223
|
+
let MessageType = /* @__PURE__ */ function(MessageType) {
|
|
224
|
+
MessageType["RegisterFunction"] = "registerfunction";
|
|
225
|
+
MessageType["UnregisterFunction"] = "unregisterfunction";
|
|
226
|
+
MessageType["RegisterService"] = "registerservice";
|
|
227
|
+
MessageType["InvokeFunction"] = "invokefunction";
|
|
228
|
+
MessageType["InvocationResult"] = "invocationresult";
|
|
229
|
+
MessageType["RegisterTriggerType"] = "registertriggertype";
|
|
230
|
+
MessageType["RegisterTrigger"] = "registertrigger";
|
|
231
|
+
MessageType["UnregisterTrigger"] = "unregistertrigger";
|
|
232
|
+
MessageType["UnregisterTriggerType"] = "unregistertriggertype";
|
|
233
|
+
MessageType["TriggerRegistrationResult"] = "triggerregistrationresult";
|
|
234
|
+
MessageType["WorkerRegistered"] = "workerregistered";
|
|
235
|
+
return MessageType;
|
|
185
236
|
}({});
|
|
186
237
|
|
|
187
238
|
//#endregion
|
|
@@ -203,11 +254,9 @@ var Sdk = class {
|
|
|
203
254
|
this.triggers = /* @__PURE__ */ new Map();
|
|
204
255
|
this.triggerTypes = /* @__PURE__ */ new Map();
|
|
205
256
|
this.functionsAvailableCallbacks = /* @__PURE__ */ new Set();
|
|
206
|
-
this.logCallbacks = /* @__PURE__ */ new Map();
|
|
207
257
|
this.messagesToSend = [];
|
|
208
258
|
this.reconnectAttempt = 0;
|
|
209
259
|
this.connectionState = "disconnected";
|
|
210
|
-
this.stateCallbacks = /* @__PURE__ */ new Set();
|
|
211
260
|
this.isShuttingDown = false;
|
|
212
261
|
this.registerTriggerType = (triggerType, handler) => {
|
|
213
262
|
this.sendMessage(MessageType.RegisterTriggerType, triggerType, true);
|
|
@@ -219,9 +268,6 @@ var Sdk = class {
|
|
|
219
268
|
handler
|
|
220
269
|
});
|
|
221
270
|
};
|
|
222
|
-
this.on = (event, callback) => {
|
|
223
|
-
this.ws?.on(event, callback);
|
|
224
|
-
};
|
|
225
271
|
this.unregisterTriggerType = (triggerType) => {
|
|
226
272
|
this.sendMessage(MessageType.UnregisterTriggerType, triggerType, true);
|
|
227
273
|
this.triggerTypes.delete(triggerType.id);
|
|
@@ -270,16 +316,16 @@ var Sdk = class {
|
|
|
270
316
|
handler: async (input, traceparent, baggage) => {
|
|
271
317
|
if (require_utils.getTracer()) {
|
|
272
318
|
const parentContext = require_utils.extractContext(traceparent, baggage);
|
|
273
|
-
return
|
|
319
|
+
return _opentelemetry_api.context.with(parentContext, () => require_utils.withSpan(`call ${message.id}`, { kind: _opentelemetry_api.SpanKind.SERVER }, async () => await handler(input)));
|
|
274
320
|
}
|
|
275
321
|
const traceId = crypto.randomUUID().replace(/-/g, "");
|
|
276
322
|
const spanId = crypto.randomUUID().replace(/-/g, "").slice(0, 16);
|
|
277
|
-
const syntheticSpan =
|
|
323
|
+
const syntheticSpan = _opentelemetry_api.trace.wrapSpanContext({
|
|
278
324
|
traceId,
|
|
279
325
|
spanId,
|
|
280
326
|
traceFlags: 1
|
|
281
327
|
});
|
|
282
|
-
return
|
|
328
|
+
return _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), syntheticSpan), async () => await handler(input));
|
|
283
329
|
}
|
|
284
330
|
});
|
|
285
331
|
} else this.functions.set(message.id, { message: fullMessage });
|
|
@@ -292,14 +338,21 @@ var Sdk = class {
|
|
|
292
338
|
};
|
|
293
339
|
};
|
|
294
340
|
this.registerService = (message) => {
|
|
295
|
-
|
|
296
|
-
this.services.set(message.id, {
|
|
341
|
+
const msg = {
|
|
297
342
|
...message,
|
|
343
|
+
name: message.name ?? message.id
|
|
344
|
+
};
|
|
345
|
+
this.sendMessage(MessageType.RegisterService, msg, true);
|
|
346
|
+
this.services.set(message.id, {
|
|
347
|
+
...msg,
|
|
298
348
|
message_type: MessageType.RegisterService
|
|
299
349
|
});
|
|
300
350
|
};
|
|
301
351
|
this.createChannel = async (bufferSize) => {
|
|
302
|
-
const result = await this.
|
|
352
|
+
const result = await this.trigger({
|
|
353
|
+
function_id: "engine::channels::create",
|
|
354
|
+
payload: { buffer_size: bufferSize }
|
|
355
|
+
});
|
|
303
356
|
return {
|
|
304
357
|
writer: new ChannelWriter(this.address, result.writer),
|
|
305
358
|
reader: new ChannelReader(this.address, result.reader),
|
|
@@ -307,11 +360,24 @@ var Sdk = class {
|
|
|
307
360
|
readerRef: result.reader
|
|
308
361
|
};
|
|
309
362
|
};
|
|
310
|
-
this.trigger = async (
|
|
363
|
+
this.trigger = async (request) => {
|
|
364
|
+
const { function_id, payload, action, timeoutMs } = request;
|
|
365
|
+
const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
|
|
366
|
+
if (action?.type === "void") {
|
|
367
|
+
const traceparent = require_utils.injectTraceparent();
|
|
368
|
+
const baggage = require_utils.injectBaggage();
|
|
369
|
+
this.sendMessage(MessageType.InvokeFunction, {
|
|
370
|
+
function_id,
|
|
371
|
+
data: payload,
|
|
372
|
+
traceparent,
|
|
373
|
+
baggage,
|
|
374
|
+
action
|
|
375
|
+
});
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
311
378
|
const invocation_id = crypto.randomUUID();
|
|
312
379
|
const traceparent = require_utils.injectTraceparent();
|
|
313
380
|
const baggage = require_utils.injectBaggage();
|
|
314
|
-
const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
|
|
315
381
|
return new Promise((resolve, reject) => {
|
|
316
382
|
const timeout = setTimeout(() => {
|
|
317
383
|
if (this.invocations.get(invocation_id)) {
|
|
@@ -333,29 +399,30 @@ var Sdk = class {
|
|
|
333
399
|
this.sendMessage(MessageType.InvokeFunction, {
|
|
334
400
|
invocation_id,
|
|
335
401
|
function_id,
|
|
336
|
-
data,
|
|
402
|
+
data: payload,
|
|
337
403
|
traceparent,
|
|
338
|
-
baggage
|
|
404
|
+
baggage,
|
|
405
|
+
action
|
|
339
406
|
});
|
|
340
407
|
});
|
|
341
408
|
};
|
|
342
|
-
this.triggerVoid = (function_id, data) => {
|
|
343
|
-
const traceparent = require_utils.injectTraceparent();
|
|
344
|
-
const baggage = require_utils.injectBaggage();
|
|
345
|
-
this.sendMessage(MessageType.InvokeFunction, {
|
|
346
|
-
function_id,
|
|
347
|
-
data,
|
|
348
|
-
traceparent,
|
|
349
|
-
baggage
|
|
350
|
-
});
|
|
351
|
-
};
|
|
352
|
-
this.call = async (function_id, data, timeoutMs) => this.trigger(function_id, data, timeoutMs);
|
|
353
|
-
this.callVoid = (function_id, data) => this.triggerVoid(function_id, data);
|
|
354
409
|
this.listFunctions = async () => {
|
|
355
|
-
return (await this.trigger(
|
|
410
|
+
return (await this.trigger({
|
|
411
|
+
function_id: require_utils.EngineFunctions.LIST_FUNCTIONS,
|
|
412
|
+
payload: {}
|
|
413
|
+
})).functions;
|
|
356
414
|
};
|
|
357
415
|
this.listWorkers = async () => {
|
|
358
|
-
return (await this.trigger(
|
|
416
|
+
return (await this.trigger({
|
|
417
|
+
function_id: require_utils.EngineFunctions.LIST_WORKERS,
|
|
418
|
+
payload: {}
|
|
419
|
+
})).workers;
|
|
420
|
+
};
|
|
421
|
+
this.listTriggers = async (includeInternal = false) => {
|
|
422
|
+
return (await this.trigger({
|
|
423
|
+
function_id: require_utils.EngineFunctions.LIST_TRIGGERS,
|
|
424
|
+
payload: { include_internal: includeInternal }
|
|
425
|
+
})).triggers;
|
|
359
426
|
};
|
|
360
427
|
this.createStream = (streamName, stream) => {
|
|
361
428
|
this.registerFunction({ id: `stream::get(${streamName})` }, stream.get.bind(stream));
|
|
@@ -389,48 +456,6 @@ var Sdk = class {
|
|
|
389
456
|
}
|
|
390
457
|
};
|
|
391
458
|
};
|
|
392
|
-
this.onLog = (callback, config) => {
|
|
393
|
-
const effectiveConfig = config ?? { level: "all" };
|
|
394
|
-
this.logCallbacks.set(callback, effectiveConfig);
|
|
395
|
-
if (!this.logTrigger) {
|
|
396
|
-
if (!this.logFunctionPath) this.logFunctionPath = `engine.on_log.${crypto.randomUUID()}`;
|
|
397
|
-
const function_id = this.logFunctionPath;
|
|
398
|
-
if (!this.functions.has(function_id)) this.registerFunction({ id: function_id }, async (log) => {
|
|
399
|
-
this.logCallbacks.forEach((cfg, handler) => {
|
|
400
|
-
try {
|
|
401
|
-
const minSeverity = this.severityTextToNumber(cfg.level ?? "all");
|
|
402
|
-
if (cfg.level === "all" || log.severity_number >= minSeverity) handler(log);
|
|
403
|
-
} catch (error) {
|
|
404
|
-
this.logError("Log callback handler threw an exception", error);
|
|
405
|
-
}
|
|
406
|
-
});
|
|
407
|
-
return null;
|
|
408
|
-
});
|
|
409
|
-
this.logTrigger = this.registerTrigger({
|
|
410
|
-
type: require_utils.EngineTriggers.LOG,
|
|
411
|
-
function_id,
|
|
412
|
-
config: {
|
|
413
|
-
level: "all",
|
|
414
|
-
severity_min: 0
|
|
415
|
-
}
|
|
416
|
-
});
|
|
417
|
-
}
|
|
418
|
-
return () => {
|
|
419
|
-
this.logCallbacks.delete(callback);
|
|
420
|
-
if (this.logCallbacks.size === 0 && this.logTrigger) {
|
|
421
|
-
this.logTrigger.unregister();
|
|
422
|
-
this.logTrigger = void 0;
|
|
423
|
-
}
|
|
424
|
-
};
|
|
425
|
-
};
|
|
426
|
-
this.getConnectionState = () => {
|
|
427
|
-
return this.connectionState;
|
|
428
|
-
};
|
|
429
|
-
this.onConnectionStateChange = (callback) => {
|
|
430
|
-
this.stateCallbacks.add(callback);
|
|
431
|
-
callback(this.connectionState);
|
|
432
|
-
return () => this.stateCallbacks.delete(callback);
|
|
433
|
-
};
|
|
434
459
|
this.shutdown = async () => {
|
|
435
460
|
this.isShuttingDown = true;
|
|
436
461
|
this.stopMetricsReporting();
|
|
@@ -446,12 +471,11 @@ var Sdk = class {
|
|
|
446
471
|
this.ws.close();
|
|
447
472
|
this.ws = void 0;
|
|
448
473
|
}
|
|
449
|
-
this.stateCallbacks.clear();
|
|
450
474
|
this.setConnectionState("disconnected");
|
|
451
475
|
};
|
|
452
476
|
this.workerName = options?.workerName ?? getDefaultWorkerName();
|
|
453
477
|
this.metricsReportingEnabled = options?.enableMetricsReporting ?? true;
|
|
454
|
-
this.invocationTimeoutMs = options?.invocationTimeoutMs ??
|
|
478
|
+
this.invocationTimeoutMs = options?.invocationTimeoutMs ?? 3e4;
|
|
455
479
|
this.reconnectionConfig = {
|
|
456
480
|
...require_utils.DEFAULT_BRIDGE_RECONNECTION_CONFIG,
|
|
457
481
|
...options?.reconnectionConfig
|
|
@@ -465,29 +489,26 @@ var Sdk = class {
|
|
|
465
489
|
registerWorkerMetadata() {
|
|
466
490
|
const telemetryOpts = this.options?.telemetry;
|
|
467
491
|
const language = telemetryOpts?.language ?? Intl.DateTimeFormat().resolvedOptions().locale ?? process.env.LANG?.split(".")[0];
|
|
468
|
-
this.
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
492
|
+
this.trigger({
|
|
493
|
+
function_id: require_utils.EngineFunctions.REGISTER_WORKER,
|
|
494
|
+
payload: {
|
|
495
|
+
runtime: "node",
|
|
496
|
+
version: SDK_VERSION,
|
|
497
|
+
name: this.workerName,
|
|
498
|
+
os: getOsInfo(),
|
|
499
|
+
pid: process.pid,
|
|
500
|
+
telemetry: {
|
|
501
|
+
language,
|
|
502
|
+
project_name: telemetryOpts?.project_name,
|
|
503
|
+
framework: telemetryOpts?.framework,
|
|
504
|
+
amplitude_api_key: telemetryOpts?.amplitude_api_key
|
|
505
|
+
}
|
|
506
|
+
},
|
|
507
|
+
action: { type: "void" }
|
|
480
508
|
});
|
|
481
509
|
}
|
|
482
510
|
setConnectionState(state) {
|
|
483
|
-
if (this.connectionState !== state)
|
|
484
|
-
this.connectionState = state;
|
|
485
|
-
for (const callback of this.stateCallbacks) try {
|
|
486
|
-
callback(state);
|
|
487
|
-
} catch (error) {
|
|
488
|
-
this.logError("Error in connection state callback", error);
|
|
489
|
-
}
|
|
490
|
-
}
|
|
511
|
+
if (this.connectionState !== state) this.connectionState = state;
|
|
491
512
|
}
|
|
492
513
|
connect() {
|
|
493
514
|
if (this.isShuttingDown) return;
|
|
@@ -627,23 +648,11 @@ var Sdk = class {
|
|
|
627
648
|
const otelLogger = require_utils.getLogger();
|
|
628
649
|
const errorMessage = error instanceof Error ? error.message : String(error ?? "");
|
|
629
650
|
if (otelLogger) otelLogger.emit({
|
|
630
|
-
severityNumber:
|
|
651
|
+
severityNumber: _opentelemetry_api_logs.SeverityNumber.ERROR,
|
|
631
652
|
body: `[iii] ${message}${errorMessage ? `: ${errorMessage}` : ""}`
|
|
632
653
|
});
|
|
633
654
|
else console.error(`[iii] ${message}`, error ?? "");
|
|
634
655
|
}
|
|
635
|
-
severityTextToNumber(level) {
|
|
636
|
-
switch (level) {
|
|
637
|
-
case "trace": return 1;
|
|
638
|
-
case "debug": return 5;
|
|
639
|
-
case "info": return 9;
|
|
640
|
-
case "warn": return 13;
|
|
641
|
-
case "error": return 17;
|
|
642
|
-
case "fatal": return 21;
|
|
643
|
-
case "all": return 0;
|
|
644
|
-
default: return 0;
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
656
|
onInvocationResult(invocation_id, result, error) {
|
|
648
657
|
const invocation = this.invocations.get(invocation_id);
|
|
649
658
|
if (invocation) {
|
|
@@ -686,12 +695,14 @@ var Sdk = class {
|
|
|
686
695
|
baggage: getResponseBaggage()
|
|
687
696
|
});
|
|
688
697
|
} catch (error) {
|
|
698
|
+
const isError = error instanceof Error;
|
|
689
699
|
this.sendMessage(MessageType.InvocationResult, {
|
|
690
700
|
invocation_id,
|
|
691
701
|
function_id,
|
|
692
702
|
error: {
|
|
693
703
|
code: "invocation_failed",
|
|
694
|
-
message: error.message
|
|
704
|
+
message: isError ? error.message : String(error),
|
|
705
|
+
stacktrace: isError ? error.stack : void 0
|
|
695
706
|
},
|
|
696
707
|
traceparent: getResponseTraceparent(),
|
|
697
708
|
baggage: getResponseBaggage()
|
|
@@ -777,10 +788,82 @@ var Sdk = class {
|
|
|
777
788
|
}
|
|
778
789
|
}
|
|
779
790
|
};
|
|
791
|
+
/**
|
|
792
|
+
* Factory object that constructs routing actions for {@link ISdk.trigger}.
|
|
793
|
+
*
|
|
794
|
+
* @example
|
|
795
|
+
* ```typescript
|
|
796
|
+
* import { TriggerAction } from 'iii-sdk'
|
|
797
|
+
*
|
|
798
|
+
* // Enqueue to a named queue
|
|
799
|
+
* iii.trigger({
|
|
800
|
+
* function_id: 'process',
|
|
801
|
+
* payload: { data: 'hello' },
|
|
802
|
+
* action: TriggerAction.Enqueue({ queue: 'jobs' }),
|
|
803
|
+
* })
|
|
804
|
+
*
|
|
805
|
+
* // Fire-and-forget
|
|
806
|
+
* iii.trigger({
|
|
807
|
+
* function_id: 'notify',
|
|
808
|
+
* payload: {},
|
|
809
|
+
* action: TriggerAction.Void(),
|
|
810
|
+
* })
|
|
811
|
+
* ```
|
|
812
|
+
*/
|
|
813
|
+
const TriggerAction = {
|
|
814
|
+
Enqueue: (opts) => ({
|
|
815
|
+
type: "enqueue",
|
|
816
|
+
...opts
|
|
817
|
+
}),
|
|
818
|
+
Void: () => ({ type: "void" })
|
|
819
|
+
};
|
|
820
|
+
/**
|
|
821
|
+
* Creates and returns a connected SDK instance. The WebSocket connection is
|
|
822
|
+
* established automatically -- there is no separate `connect()` call.
|
|
823
|
+
*
|
|
824
|
+
* @param address - WebSocket URL of the III engine (e.g. `ws://localhost:49134`).
|
|
825
|
+
* @param options - Optional {@link InitOptions} for worker name, timeouts, reconnection, and OTel.
|
|
826
|
+
* @returns A connected {@link ISdk} instance.
|
|
827
|
+
*
|
|
828
|
+
* @example
|
|
829
|
+
* ```typescript
|
|
830
|
+
* import { registerWorker } from 'iii-sdk'
|
|
831
|
+
*
|
|
832
|
+
* const iii = registerWorker(process.env.III_URL ?? 'ws://localhost:49134', {
|
|
833
|
+
* workerName: 'my-worker',
|
|
834
|
+
* })
|
|
835
|
+
* ```
|
|
836
|
+
*/
|
|
780
837
|
const registerWorker = (address, options) => new Sdk(address, options);
|
|
781
838
|
|
|
782
839
|
//#endregion
|
|
783
840
|
//#region src/logger.ts
|
|
841
|
+
/**
|
|
842
|
+
* Structured logger that emits logs as OpenTelemetry LogRecords.
|
|
843
|
+
*
|
|
844
|
+
* Every log call automatically captures the active trace and span context,
|
|
845
|
+
* correlating your logs with distributed traces without any manual wiring.
|
|
846
|
+
* When OTel is not initialized, Logger gracefully falls back to `console.*`.
|
|
847
|
+
*
|
|
848
|
+
* Pass structured data as the second argument to any log method. Using an
|
|
849
|
+
* object of key-value pairs (instead of string interpolation) lets you
|
|
850
|
+
* filter, aggregate, and build dashboards in your observability backend.
|
|
851
|
+
*
|
|
852
|
+
* @example
|
|
853
|
+
* ```typescript
|
|
854
|
+
* import { Logger } from 'iii-sdk'
|
|
855
|
+
*
|
|
856
|
+
* const logger = new Logger()
|
|
857
|
+
*
|
|
858
|
+
* // Basic logging — trace context is injected automatically
|
|
859
|
+
* logger.info('Worker connected')
|
|
860
|
+
*
|
|
861
|
+
* // Structured context for dashboards and alerting
|
|
862
|
+
* logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })
|
|
863
|
+
* logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })
|
|
864
|
+
* logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })
|
|
865
|
+
* ```
|
|
866
|
+
*/
|
|
784
867
|
var Logger = class {
|
|
785
868
|
get otelLogger() {
|
|
786
869
|
if (!this._otelLogger) this._otelLogger = require_utils.getLogger();
|
|
@@ -806,32 +889,84 @@ var Logger = class {
|
|
|
806
889
|
attributes: Object.keys(attributes).length > 0 ? attributes : void 0
|
|
807
890
|
});
|
|
808
891
|
else switch (severity) {
|
|
809
|
-
case
|
|
892
|
+
case _opentelemetry_api_logs.SeverityNumber.DEBUG:
|
|
810
893
|
console.debug(message, data);
|
|
811
894
|
break;
|
|
812
|
-
case
|
|
895
|
+
case _opentelemetry_api_logs.SeverityNumber.INFO:
|
|
813
896
|
console.info(message, data);
|
|
814
897
|
break;
|
|
815
|
-
case
|
|
898
|
+
case _opentelemetry_api_logs.SeverityNumber.WARN:
|
|
816
899
|
console.warn(message, data);
|
|
817
900
|
break;
|
|
818
|
-
case
|
|
901
|
+
case _opentelemetry_api_logs.SeverityNumber.ERROR:
|
|
819
902
|
console.error(message, data);
|
|
820
903
|
break;
|
|
821
904
|
default: console.log(message, data);
|
|
822
905
|
}
|
|
823
906
|
}
|
|
907
|
+
/**
|
|
908
|
+
* Log an info-level message.
|
|
909
|
+
*
|
|
910
|
+
* @param message - Human-readable log message.
|
|
911
|
+
* @param data - Structured context attached as OTel log attributes.
|
|
912
|
+
* Use key-value objects to enable filtering and aggregation in your
|
|
913
|
+
* observability backend (e.g. Grafana, Datadog, New Relic).
|
|
914
|
+
*
|
|
915
|
+
* @example
|
|
916
|
+
* ```typescript
|
|
917
|
+
* logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })
|
|
918
|
+
* ```
|
|
919
|
+
*/
|
|
824
920
|
info(message, data) {
|
|
825
|
-
this.emit(message,
|
|
826
|
-
}
|
|
921
|
+
this.emit(message, _opentelemetry_api_logs.SeverityNumber.INFO, data);
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Log a warning-level message.
|
|
925
|
+
*
|
|
926
|
+
* @param message - Human-readable log message.
|
|
927
|
+
* @param data - Structured context attached as OTel log attributes.
|
|
928
|
+
* Use key-value objects to enable filtering and aggregation in your
|
|
929
|
+
* observability backend (e.g. Grafana, Datadog, New Relic).
|
|
930
|
+
*
|
|
931
|
+
* @example
|
|
932
|
+
* ```typescript
|
|
933
|
+
* logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })
|
|
934
|
+
* ```
|
|
935
|
+
*/
|
|
827
936
|
warn(message, data) {
|
|
828
|
-
this.emit(message,
|
|
829
|
-
}
|
|
937
|
+
this.emit(message, _opentelemetry_api_logs.SeverityNumber.WARN, data);
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Log an error-level message.
|
|
941
|
+
*
|
|
942
|
+
* @param message - Human-readable log message.
|
|
943
|
+
* @param data - Structured context attached as OTel log attributes.
|
|
944
|
+
* Use key-value objects to enable filtering and aggregation in your
|
|
945
|
+
* observability backend (e.g. Grafana, Datadog, New Relic).
|
|
946
|
+
*
|
|
947
|
+
* @example
|
|
948
|
+
* ```typescript
|
|
949
|
+
* logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })
|
|
950
|
+
* ```
|
|
951
|
+
*/
|
|
830
952
|
error(message, data) {
|
|
831
|
-
this.emit(message,
|
|
832
|
-
}
|
|
953
|
+
this.emit(message, _opentelemetry_api_logs.SeverityNumber.ERROR, data);
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Log a debug-level message.
|
|
957
|
+
*
|
|
958
|
+
* @param message - Human-readable log message.
|
|
959
|
+
* @param data - Structured context attached as OTel log attributes.
|
|
960
|
+
* Use key-value objects to enable filtering and aggregation in your
|
|
961
|
+
* observability backend (e.g. Grafana, Datadog, New Relic).
|
|
962
|
+
*
|
|
963
|
+
* @example
|
|
964
|
+
* ```typescript
|
|
965
|
+
* logger.debug('Cache lookup', { key: 'user:42', hit: false })
|
|
966
|
+
* ```
|
|
967
|
+
*/
|
|
833
968
|
debug(message, data) {
|
|
834
|
-
this.emit(message,
|
|
969
|
+
this.emit(message, _opentelemetry_api_logs.SeverityNumber.DEBUG, data);
|
|
835
970
|
}
|
|
836
971
|
};
|
|
837
972
|
|
|
@@ -839,6 +974,7 @@ var Logger = class {
|
|
|
839
974
|
exports.ChannelReader = ChannelReader;
|
|
840
975
|
exports.ChannelWriter = ChannelWriter;
|
|
841
976
|
exports.Logger = Logger;
|
|
977
|
+
exports.TriggerAction = TriggerAction;
|
|
842
978
|
exports.__toESM = __toESM;
|
|
843
979
|
exports.http = require_utils.http;
|
|
844
980
|
exports.registerWorker = registerWorker;
|