@eeshaai/code 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE.md +115 -0
  2. package/README.md +322 -0
  3. package/dist/THIRD-PARTY-NOTICES.md +23 -0
  4. package/dist/claude-agent-sdk/LICENSE.md +1 -0
  5. package/dist/claude-agent-sdk/sdk.mjs +156 -0
  6. package/dist/cli.js +23 -0
  7. package/dist/pluginWorker.js +1610 -0
  8. package/dist/resources/styles/custom/instructions/design.md +284 -0
  9. package/dist/resources/styles/custom/instructions/requirements.md +161 -0
  10. package/dist/resources/styles/custom/instructions/tasks-implement.md +90 -0
  11. package/dist/resources/styles/custom/instructions/tasks.md +159 -0
  12. package/dist/resources/styles/custom/process.md +49 -0
  13. package/dist/resources/styles/custom/prompts/first.md +29 -0
  14. package/dist/resources/styles/custom/prompts/implement.md +27 -0
  15. package/dist/resources/styles/custom/prompts/rewrite-note.md +40 -0
  16. package/dist/resources/styles/custom/prompts/rewrite.md +32 -0
  17. package/dist/resources/styles/custom/style.yml +46 -0
  18. package/dist/resources/styles/grammar.md +731 -0
  19. package/dist/server.js +839 -0
  20. package/dist/web/chunks/abnfDiagram-VCTEODGH-6KC3BO47.js +2 -0
  21. package/dist/web/chunks/architecture-7GRP2DOG-JLXNDD4H.js +2 -0
  22. package/dist/web/chunks/architectureDiagram-5GKGNRK7-QKPCVOD2.js +37 -0
  23. package/dist/web/chunks/blockDiagram-I7D4REHJ-4XZWNXLB.js +130 -0
  24. package/dist/web/chunks/c4Diagram-7LVT6UL2-4HJHKNE3.js +39 -0
  25. package/dist/web/chunks/chunk-2DLEMZHM.js +33 -0
  26. package/dist/web/chunks/chunk-2RFQIKC6.js +232 -0
  27. package/dist/web/chunks/chunk-37NHO5VO.js +2 -0
  28. package/dist/web/chunks/chunk-46RPN6IE.js +3 -0
  29. package/dist/web/chunks/chunk-4IPDIKAU.js +2 -0
  30. package/dist/web/chunks/chunk-4KP3BIPB.js +2 -0
  31. package/dist/web/chunks/chunk-4S2DRQJ6.js +340 -0
  32. package/dist/web/chunks/chunk-4TORDSRR.js +2 -0
  33. package/dist/web/chunks/chunk-5KNOHX5X.js +15 -0
  34. package/dist/web/chunks/chunk-6FQEBIA3.js +133 -0
  35. package/dist/web/chunks/chunk-6KSWTVXD.js +3 -0
  36. package/dist/web/chunks/chunk-6TGTE6CF.js +2 -0
  37. package/dist/web/chunks/chunk-6URXM4C4.js +2 -0
  38. package/dist/web/chunks/chunk-6VRLULJH.js +2 -0
  39. package/dist/web/chunks/chunk-7XAOOQR4.js +2 -0
  40. package/dist/web/chunks/chunk-BUZPUGIT.js +2 -0
  41. package/dist/web/chunks/chunk-DIRT34TZ.js +2 -0
  42. package/dist/web/chunks/chunk-FGASMJTA.js +4 -0
  43. package/dist/web/chunks/chunk-FNIFXWXL.js +2 -0
  44. package/dist/web/chunks/chunk-FPLIRG3U.js +73 -0
  45. package/dist/web/chunks/chunk-GQPX4EIC.js +11 -0
  46. package/dist/web/chunks/chunk-HAKJ3AUV.js +2 -0
  47. package/dist/web/chunks/chunk-HBEUVMXY.js +2 -0
  48. package/dist/web/chunks/chunk-HNYXDXPN.js +63 -0
  49. package/dist/web/chunks/chunk-HX7W7GSO.js +2 -0
  50. package/dist/web/chunks/chunk-II6WN3ZG.js +2 -0
  51. package/dist/web/chunks/chunk-JOSXY3EP.js +169 -0
  52. package/dist/web/chunks/chunk-L34PKG4P.js +2 -0
  53. package/dist/web/chunks/chunk-LDXBIOBF.js +2 -0
  54. package/dist/web/chunks/chunk-LHNPPNB7.js +3 -0
  55. package/dist/web/chunks/chunk-LQ6CTWX6.js +2 -0
  56. package/dist/web/chunks/chunk-LSVIQRSY.js +2 -0
  57. package/dist/web/chunks/chunk-M3SWKTLZ.js +2 -0
  58. package/dist/web/chunks/chunk-MBZYSJFT.js +2 -0
  59. package/dist/web/chunks/chunk-MZEMPN3C.js +2 -0
  60. package/dist/web/chunks/chunk-OODDZ447.js +2 -0
  61. package/dist/web/chunks/chunk-OXLTOJNY.js +3 -0
  62. package/dist/web/chunks/chunk-PR453BYT.js +2 -0
  63. package/dist/web/chunks/chunk-QNEZP2TE.js +179 -0
  64. package/dist/web/chunks/chunk-R7TFKRNM.js +2 -0
  65. package/dist/web/chunks/chunk-T4HEWXAQ.js +2 -0
  66. package/dist/web/chunks/chunk-TPXX77KB.js +2 -0
  67. package/dist/web/chunks/chunk-TPYBIPJG.js +2 -0
  68. package/dist/web/chunks/chunk-TXNHMPKM.js +89 -0
  69. package/dist/web/chunks/chunk-VAKN3BTM.js +2 -0
  70. package/dist/web/chunks/chunk-VY4GEFSG.js +2 -0
  71. package/dist/web/chunks/chunk-XBYCKXUJ.js +207 -0
  72. package/dist/web/chunks/chunk-YM7LHP34.js +16 -0
  73. package/dist/web/chunks/classDiagram-ZZMXUADV-4J5HHZD6.js +2 -0
  74. package/dist/web/chunks/classDiagram-v2-VYDZK3BY-X6WY2DAS.js +2 -0
  75. package/dist/web/chunks/cose-bilkent-JH36ORCC-ZPRW5JRW.js +2 -0
  76. package/dist/web/chunks/cynefin-OW5HDTMX-SVVTQRRB.js +2 -0
  77. package/dist/web/chunks/cynefinDiagram-5FMLGOSQ-O7GURHJG.js +63 -0
  78. package/dist/web/chunks/dagre-GXQ25YYZ-WK67O4N6.js +5 -0
  79. package/dist/web/chunks/diagram-S7CK7UJ4-2CEO2EN2.js +31 -0
  80. package/dist/web/chunks/diagram-UQ7AKVKN-2Z4VHGF3.js +42 -0
  81. package/dist/web/chunks/diagram-VSXAHHWV-AN4BOWYB.js +4 -0
  82. package/dist/web/chunks/diagram-VX7I27RA-VEZ2GXCM.js +25 -0
  83. package/dist/web/chunks/diagram-Z3DM3KII-TGGNDSLW.js +25 -0
  84. package/dist/web/chunks/ebnfDiagram-PWID7BFC-7RM57IJV.js +2 -0
  85. package/dist/web/chunks/erDiagram-RLTQ6QDP-LCATC3YT.js +100 -0
  86. package/dist/web/chunks/eventmodeling-NTZA5JFV-2SR57JAH.js +2 -0
  87. package/dist/web/chunks/flowDiagram-HODETNUW-HU6Y2EYQ.js +2 -0
  88. package/dist/web/chunks/ganttDiagram-EL5Y4UJY-5VPBBF2V.js +293 -0
  89. package/dist/web/chunks/gitGraph-4MIJSDKK-25JPIQP7.js +2 -0
  90. package/dist/web/chunks/gitGraphDiagram-WWUBYQGX-HZMAGPIJ.js +107 -0
  91. package/dist/web/chunks/info-A6RAGUB7-72MROTVX.js +2 -0
  92. package/dist/web/chunks/infoDiagram-27XIBGKW-BQYTPGNG.js +3 -0
  93. package/dist/web/chunks/ishikawaDiagram-5VMMS53U-A54WWBPX.js +71 -0
  94. package/dist/web/chunks/journeyDiagram-3NMN7TZE-XRCTMTR7.js +140 -0
  95. package/dist/web/chunks/kanban-definition-UXKFOSKX-UW2PQXZF.js +90 -0
  96. package/dist/web/chunks/katex-B7HWCVTN.js +258 -0
  97. package/dist/web/chunks/mermaid.core-VL5SQK5M.js +19 -0
  98. package/dist/web/chunks/mindmap-definition-YA3MSWOX-2H2Z6CVN.js +97 -0
  99. package/dist/web/chunks/packet-AYTQ26CC-NEGDW4B6.js +2 -0
  100. package/dist/web/chunks/pegDiagram-XKGWAZYB-KC4BYUN7.js +2 -0
  101. package/dist/web/chunks/pie-WAS4IAKB-OT3EMGHT.js +2 -0
  102. package/dist/web/chunks/pieDiagram-E7YTZNPT-54T6XSU5.js +40 -0
  103. package/dist/web/chunks/quadrantDiagram-AXDQQJYC-3G3RXSTE.js +8 -0
  104. package/dist/web/chunks/radar-RG4KPBEZ-DCHU5FOQ.js +2 -0
  105. package/dist/web/chunks/railroad-74A4TZTK-RZX6D7H6.js +2 -0
  106. package/dist/web/chunks/railroad-abnf-HS5TGJTU-STTFN7R4.js +2 -0
  107. package/dist/web/chunks/railroad-ebnf-LZEXJU2U-RBXU3IBK.js +2 -0
  108. package/dist/web/chunks/railroad-peg-WCYAUIDC-OD5BXOH6.js +2 -0
  109. package/dist/web/chunks/railroadDiagram-O6MQD6OU-3LHKFF5N.js +2 -0
  110. package/dist/web/chunks/requirementDiagram-BXWQKSXE-M4LF54YT.js +85 -0
  111. package/dist/web/chunks/sankeyDiagram-P5KCCOFB-USCKKKNT.js +41 -0
  112. package/dist/web/chunks/sequenceDiagram-WJ2MYXX4-QZ2O4KWV.js +163 -0
  113. package/dist/web/chunks/sizeCapture-INFHLROL-DZI5JWEV.js +2 -0
  114. package/dist/web/chunks/stateDiagram-D77RDMKH-EQJNTBF3.js +2 -0
  115. package/dist/web/chunks/stateDiagram-v2-MP3YSRHH-WSCDKLG6.js +2 -0
  116. package/dist/web/chunks/swimlanes-42K2YHIH-H7SZ2HG6.js +2 -0
  117. package/dist/web/chunks/swimlanesDiagram-VR7AAH4N-DFYTBPVS.js +9 -0
  118. package/dist/web/chunks/timeline-definition-24CTP7MA-4Q2ARIQ6.js +121 -0
  119. package/dist/web/chunks/treeView-Q6P3EWNA-ADCP6RPT.js +2 -0
  120. package/dist/web/chunks/treemap-WGGIJYW6-NEV7DUDY.js +2 -0
  121. package/dist/web/chunks/vennDiagram-4TSXK5OY-WMJVK74C.js +35 -0
  122. package/dist/web/chunks/wardley-WFR3VGLG-4QZOFDI5.js +2 -0
  123. package/dist/web/chunks/wardleyDiagram-VM6X3IG4-CLB324RQ.js +79 -0
  124. package/dist/web/chunks/xychartDiagram-S5SC5T6Z-G5C2R7C2.js +8 -0
  125. package/dist/web/index.html +24 -0
  126. package/dist/web/page.css +2 -0
  127. package/dist/web/page.js +210 -0
  128. package/package.json +62 -10
  129. package/cli.js +0 -2
@@ -0,0 +1,1610 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
15
+ };
16
+ var __commonJS = (cb, mod) => function __require() {
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
22
+ };
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
36
+ // If the importer is in node compatibility mode or this is not an ESM
37
+ // file that has been converted to a CommonJS file using a Babel-
38
+ // compatible transform (i.e. "__esModule" has not been set), then set
39
+ // "default" to the CommonJS "module.exports" for node compatibility.
40
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
41
+ mod
42
+ ));
43
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
44
+
45
+ // <define:__SDD_PROMPTS__>
46
+ var init_define_SDD_PROMPTS = __esm({
47
+ "<define:__SDD_PROMPTS__>"() {
48
+ }
49
+ });
50
+
51
+ // node_modules/serilogger/dist/serilogger.js
52
+ var require_serilogger = __commonJS({
53
+ "node_modules/serilogger/dist/serilogger.js"(exports2, module2) {
54
+ init_define_SDD_PROMPTS();
55
+ (function(global, factory) {
56
+ typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.serilogger = {}));
57
+ })(exports2, (function(exports3) {
58
+ "use strict";
59
+ exports3.LogEventLevel = void 0;
60
+ (function(LogEventLevel2) {
61
+ LogEventLevel2[LogEventLevel2["off"] = 0] = "off";
62
+ LogEventLevel2[LogEventLevel2["fatal"] = 1] = "fatal";
63
+ LogEventLevel2[LogEventLevel2["error"] = 3] = "error";
64
+ LogEventLevel2[LogEventLevel2["warning"] = 7] = "warning";
65
+ LogEventLevel2[LogEventLevel2["information"] = 15] = "information";
66
+ LogEventLevel2[LogEventLevel2["debug"] = 31] = "debug";
67
+ LogEventLevel2[LogEventLevel2["verbose"] = 63] = "verbose";
68
+ })(exports3.LogEventLevel || (exports3.LogEventLevel = {}));
69
+ function isEnabled(level, target) {
70
+ return typeof level === "undefined" || (level & target) === target;
71
+ }
72
+ var LogEvent2 = (
73
+ /** @class */
74
+ /* @__PURE__ */ (function() {
75
+ function LogEvent3(timestamp, level, messageTemplate, properties, error) {
76
+ this.timestamp = timestamp;
77
+ this.level = level;
78
+ this.messageTemplate = messageTemplate;
79
+ this.properties = properties || {};
80
+ this.error = error || void 0;
81
+ }
82
+ return LogEvent3;
83
+ })()
84
+ );
85
+ var deepClone = function(obj) {
86
+ return JSON.parse(JSON.stringify(obj));
87
+ };
88
+ var EnrichStage = (
89
+ /** @class */
90
+ (function() {
91
+ function EnrichStage2(enricher) {
92
+ this.enricher = enricher;
93
+ }
94
+ EnrichStage2.prototype.emit = function(events) {
95
+ for (var i = 0; i < events.length; ++i) {
96
+ var extraProperties = this.enricher instanceof Function ? this.enricher(deepClone(events[i].properties)) : this.enricher;
97
+ Object.assign(events[i].properties, extraProperties);
98
+ }
99
+ return events;
100
+ };
101
+ EnrichStage2.prototype.flush = function() {
102
+ return Promise.resolve();
103
+ };
104
+ return EnrichStage2;
105
+ })()
106
+ );
107
+ var tokenizer = /{@?\w+}/g;
108
+ var MessageTemplate = (
109
+ /** @class */
110
+ (function() {
111
+ function MessageTemplate2(messageTemplate) {
112
+ this.jsonTemplateStringMaxLength = 70;
113
+ if (messageTemplate === null || !messageTemplate.length) {
114
+ throw new Error('Argument "messageTemplate" is required.');
115
+ }
116
+ this.raw = messageTemplate;
117
+ this.tokens = this.tokenize(messageTemplate);
118
+ }
119
+ MessageTemplate2.prototype.render = function(properties) {
120
+ if (!this.tokens.length) {
121
+ return this.raw;
122
+ }
123
+ properties = properties || {};
124
+ var result = [];
125
+ for (var i = 0; i < this.tokens.length; ++i) {
126
+ var token = this.tokens[i];
127
+ if (typeof token.name === "string") {
128
+ if (properties.hasOwnProperty(token.name)) {
129
+ result.push(this.toText(properties[token.name]));
130
+ } else {
131
+ result.push(token.raw);
132
+ }
133
+ } else {
134
+ result.push(token.text);
135
+ }
136
+ }
137
+ return result.join("");
138
+ };
139
+ MessageTemplate2.prototype.bindProperties = function(positionalArgs) {
140
+ var result = {};
141
+ var nextArg = 0;
142
+ for (var i = 0; i < this.tokens.length && nextArg < positionalArgs.length; ++i) {
143
+ var token = this.tokens[i];
144
+ if (typeof token.name === "string") {
145
+ var p = positionalArgs[nextArg];
146
+ result[token.name] = this.capture(p, token.destructure);
147
+ nextArg++;
148
+ }
149
+ }
150
+ while (nextArg < positionalArgs.length) {
151
+ var arg = positionalArgs[nextArg];
152
+ if (typeof arg !== "undefined") {
153
+ result["a" + nextArg] = this.capture(arg);
154
+ }
155
+ nextArg++;
156
+ }
157
+ return result;
158
+ };
159
+ MessageTemplate2.prototype.tokenize = function(template) {
160
+ var tokens = [];
161
+ var result;
162
+ var textStart = 0;
163
+ while ((result = tokenizer.exec(template)) !== null) {
164
+ if (result.index !== textStart) {
165
+ tokens.push({ text: template.slice(textStart, result.index) });
166
+ }
167
+ var destructure = false;
168
+ var token = result[0].slice(1, -1);
169
+ if (token.indexOf("@") === 0) {
170
+ token = token.slice(1);
171
+ destructure = true;
172
+ }
173
+ tokens.push({
174
+ name: token,
175
+ destructure,
176
+ raw: result[0]
177
+ });
178
+ textStart = tokenizer.lastIndex;
179
+ }
180
+ if (textStart >= 0 && textStart < template.length) {
181
+ tokens.push({ text: template.slice(textStart) });
182
+ }
183
+ return tokens;
184
+ };
185
+ MessageTemplate2.prototype.toText = function(property) {
186
+ if (typeof property === "undefined")
187
+ return "undefined";
188
+ if (property === null)
189
+ return "null";
190
+ if (typeof property === "string")
191
+ return property;
192
+ if (typeof property === "number")
193
+ return property.toString();
194
+ if (typeof property === "boolean")
195
+ return property.toString();
196
+ if (typeof property.toISOString === "function")
197
+ return property.toISOString();
198
+ if (typeof property === "object") {
199
+ var s = JSON.stringify(property);
200
+ if (this.jsonTemplateStringMaxLength === -1)
201
+ return s;
202
+ if (s.length > this.jsonTemplateStringMaxLength) {
203
+ s = s.slice(0, 67) + "...";
204
+ }
205
+ return s;
206
+ }
207
+ return property.toString();
208
+ };
209
+ MessageTemplate2.prototype.capture = function(property, destructure) {
210
+ if (typeof property === "function") {
211
+ return property.toString();
212
+ }
213
+ if (typeof property === "object") {
214
+ if (property === null) {
215
+ return property;
216
+ }
217
+ if (destructure || typeof property.toISOString === "function") {
218
+ return property;
219
+ }
220
+ return property.toString();
221
+ }
222
+ return property;
223
+ };
224
+ return MessageTemplate2;
225
+ })()
226
+ );
227
+ var Pipeline = (
228
+ /** @class */
229
+ (function() {
230
+ function Pipeline2() {
231
+ this.stages = [];
232
+ this.eventQueue = [];
233
+ this.flushInProgress = false;
234
+ }
235
+ Pipeline2.prototype.addStage = function(stage) {
236
+ this.stages.push(stage);
237
+ };
238
+ Pipeline2.prototype.emit = function(events) {
239
+ var _this = this;
240
+ if (this.flushInProgress) {
241
+ this.eventQueue = this.eventQueue.concat(events);
242
+ return this.flushPromise;
243
+ } else {
244
+ if (!this.stages.length || !events.length) {
245
+ return Promise.resolve();
246
+ }
247
+ var promise = Promise.resolve(this.stages[0].emit(events));
248
+ var _loop_1 = function(i2) {
249
+ promise = promise.then(function(events2) {
250
+ return _this.stages[i2].emit(events2);
251
+ });
252
+ };
253
+ for (var i = 1; i < this.stages.length; ++i) {
254
+ _loop_1(i);
255
+ }
256
+ return promise;
257
+ }
258
+ };
259
+ Pipeline2.prototype.flush = function() {
260
+ var _this = this;
261
+ if (this.flushInProgress) {
262
+ return this.flushPromise;
263
+ }
264
+ this.flushInProgress = true;
265
+ return this.flushPromise = Promise.resolve().then(function() {
266
+ if (_this.stages.length === 0) {
267
+ return;
268
+ }
269
+ var promise = _this.stages[0].flush();
270
+ var _loop_2 = function(i2) {
271
+ promise = promise.then(function() {
272
+ return _this.stages[i2].flush();
273
+ });
274
+ };
275
+ for (var i = 1; i < _this.stages.length; ++i) {
276
+ _loop_2(i);
277
+ }
278
+ return promise;
279
+ }).then(function() {
280
+ _this.flushInProgress = false;
281
+ var queuedEvents = _this.eventQueue.slice();
282
+ _this.eventQueue = [];
283
+ return _this.emit(queuedEvents);
284
+ });
285
+ };
286
+ return Pipeline2;
287
+ })()
288
+ );
289
+ var SinkStage = (
290
+ /** @class */
291
+ (function() {
292
+ function SinkStage2(sink) {
293
+ this.sink = sink;
294
+ }
295
+ SinkStage2.prototype.emit = function(events) {
296
+ this.sink.emit(events);
297
+ return events;
298
+ };
299
+ SinkStage2.prototype.flush = function() {
300
+ return this.sink.flush();
301
+ };
302
+ return SinkStage2;
303
+ })()
304
+ );
305
+ var Logger2 = (
306
+ /** @class */
307
+ (function() {
308
+ function Logger3(pipeline, suppressErrors) {
309
+ this.suppressErrors = true;
310
+ this._jsonTemplateStringMaxLength = 70;
311
+ this.pipeline = pipeline;
312
+ this.suppressErrors = typeof suppressErrors === "undefined" || suppressErrors;
313
+ }
314
+ Logger3.prototype.setJSONTemplateStringMaxLength = function(length) {
315
+ this._jsonTemplateStringMaxLength = length;
316
+ };
317
+ Logger3.prototype.createChild = function(enricher) {
318
+ if (enricher instanceof Function || enricher instanceof Object) {
319
+ var currentStages = this.pipeline["stages"];
320
+ var stages_1 = [];
321
+ var sinkStages_1 = [];
322
+ currentStages.forEach(function(stage) {
323
+ if (stage instanceof SinkStage) {
324
+ sinkStages_1.push(stage);
325
+ } else {
326
+ stages_1.push(stage);
327
+ }
328
+ });
329
+ stages_1.push(new EnrichStage(enricher));
330
+ var newPipeline_1 = new Pipeline();
331
+ stages_1.forEach(function(stage) {
332
+ return newPipeline_1.addStage(stage);
333
+ });
334
+ sinkStages_1.forEach(function(stage) {
335
+ return newPipeline_1.addStage(stage);
336
+ });
337
+ return new Logger3(newPipeline_1, this.suppressErrors);
338
+ } else {
339
+ throw new TypeError('Argument "enricher" must be either a function or an object.');
340
+ }
341
+ };
342
+ Logger3.prototype.fatal = function(errorOrMessageTemplate) {
343
+ var properties = [];
344
+ for (var _i = 1; _i < arguments.length; _i++) {
345
+ properties[_i - 1] = arguments[_i];
346
+ }
347
+ try {
348
+ if (errorOrMessageTemplate instanceof Error) {
349
+ this.write(exports3.LogEventLevel.fatal, properties[0], properties.slice(1), errorOrMessageTemplate);
350
+ } else {
351
+ this.write(exports3.LogEventLevel.fatal, errorOrMessageTemplate, properties);
352
+ }
353
+ } catch (error) {
354
+ if (!this.suppressErrors) {
355
+ throw error;
356
+ }
357
+ }
358
+ };
359
+ Logger3.prototype.error = function(errorOrMessageTemplate) {
360
+ var properties = [];
361
+ for (var _i = 1; _i < arguments.length; _i++) {
362
+ properties[_i - 1] = arguments[_i];
363
+ }
364
+ try {
365
+ if (errorOrMessageTemplate instanceof Error) {
366
+ this.write(exports3.LogEventLevel.error, properties[0], properties.slice(1), errorOrMessageTemplate);
367
+ } else {
368
+ this.write(exports3.LogEventLevel.error, errorOrMessageTemplate, properties);
369
+ }
370
+ } catch (error) {
371
+ if (!this.suppressErrors) {
372
+ throw error;
373
+ }
374
+ }
375
+ };
376
+ Logger3.prototype.warn = function(errorOrMessageTemplate) {
377
+ var properties = [];
378
+ for (var _i = 1; _i < arguments.length; _i++) {
379
+ properties[_i - 1] = arguments[_i];
380
+ }
381
+ try {
382
+ if (errorOrMessageTemplate instanceof Error) {
383
+ this.write(exports3.LogEventLevel.warning, properties[0], properties.slice(1), errorOrMessageTemplate);
384
+ } else {
385
+ this.write(exports3.LogEventLevel.warning, errorOrMessageTemplate, properties);
386
+ }
387
+ } catch (error) {
388
+ if (!this.suppressErrors) {
389
+ throw error;
390
+ }
391
+ }
392
+ };
393
+ Logger3.prototype.info = function(errorOrMessageTemplate) {
394
+ var properties = [];
395
+ for (var _i = 1; _i < arguments.length; _i++) {
396
+ properties[_i - 1] = arguments[_i];
397
+ }
398
+ try {
399
+ if (errorOrMessageTemplate instanceof Error) {
400
+ this.write(exports3.LogEventLevel.information, properties[0], properties.slice(1), errorOrMessageTemplate);
401
+ } else {
402
+ this.write(exports3.LogEventLevel.information, errorOrMessageTemplate, properties);
403
+ }
404
+ } catch (error) {
405
+ if (!this.suppressErrors) {
406
+ throw error;
407
+ }
408
+ }
409
+ };
410
+ Logger3.prototype.debug = function(errorOrMessageTemplate) {
411
+ var properties = [];
412
+ for (var _i = 1; _i < arguments.length; _i++) {
413
+ properties[_i - 1] = arguments[_i];
414
+ }
415
+ try {
416
+ if (errorOrMessageTemplate instanceof Error) {
417
+ this.write(exports3.LogEventLevel.debug, properties[0], properties.slice(1), errorOrMessageTemplate);
418
+ } else {
419
+ this.write(exports3.LogEventLevel.debug, errorOrMessageTemplate, properties);
420
+ }
421
+ } catch (error) {
422
+ if (!this.suppressErrors) {
423
+ throw error;
424
+ }
425
+ }
426
+ };
427
+ Logger3.prototype.verbose = function(errorOrMessageTemplate) {
428
+ var properties = [];
429
+ for (var _i = 1; _i < arguments.length; _i++) {
430
+ properties[_i - 1] = arguments[_i];
431
+ }
432
+ try {
433
+ if (errorOrMessageTemplate instanceof Error) {
434
+ this.write(exports3.LogEventLevel.verbose, properties[0], properties.slice(1), errorOrMessageTemplate);
435
+ } else {
436
+ this.write(exports3.LogEventLevel.verbose, errorOrMessageTemplate, properties);
437
+ }
438
+ } catch (error) {
439
+ if (!this.suppressErrors) {
440
+ throw error;
441
+ }
442
+ }
443
+ };
444
+ Logger3.prototype.flush = function() {
445
+ return this.suppressErrors ? this.pipeline.flush().catch(function() {
446
+ }) : this.pipeline.flush();
447
+ };
448
+ Logger3.prototype.emit = function(events) {
449
+ try {
450
+ this.pipeline.emit(events);
451
+ return events;
452
+ } catch (error) {
453
+ if (!this.suppressErrors) {
454
+ throw error;
455
+ }
456
+ return [];
457
+ }
458
+ };
459
+ Logger3.prototype.write = function(level, rawMessageTemplate, unboundProperties, error) {
460
+ var messageTemplate = new MessageTemplate(rawMessageTemplate);
461
+ messageTemplate.jsonTemplateStringMaxLength = this._jsonTemplateStringMaxLength;
462
+ var properties = messageTemplate.bindProperties(unboundProperties);
463
+ var logEvent = new LogEvent2((/* @__PURE__ */ new Date()).toISOString(), level, messageTemplate, properties, error);
464
+ this.pipeline.emit([logEvent]);
465
+ };
466
+ return Logger3;
467
+ })()
468
+ );
469
+ var extendStatics = function(d, b) {
470
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
471
+ d2.__proto__ = b2;
472
+ } || function(d2, b2) {
473
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
474
+ };
475
+ return extendStatics(d, b);
476
+ };
477
+ function __extends(d, b) {
478
+ if (typeof b !== "function" && b !== null)
479
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
480
+ extendStatics(d, b);
481
+ function __() {
482
+ this.constructor = d;
483
+ }
484
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
485
+ }
486
+ var __assign = function() {
487
+ __assign = Object.assign || function __assign2(t) {
488
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
489
+ s = arguments[i];
490
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
491
+ }
492
+ return t;
493
+ };
494
+ return __assign.apply(this, arguments);
495
+ };
496
+ function __awaiter(thisArg, _arguments, P, generator) {
497
+ function adopt(value) {
498
+ return value instanceof P ? value : new P(function(resolve2) {
499
+ resolve2(value);
500
+ });
501
+ }
502
+ return new (P || (P = Promise))(function(resolve2, reject) {
503
+ function fulfilled(value) {
504
+ try {
505
+ step(generator.next(value));
506
+ } catch (e) {
507
+ reject(e);
508
+ }
509
+ }
510
+ function rejected(value) {
511
+ try {
512
+ step(generator["throw"](value));
513
+ } catch (e) {
514
+ reject(e);
515
+ }
516
+ }
517
+ function step(result) {
518
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
519
+ }
520
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
521
+ });
522
+ }
523
+ function __generator(thisArg, body) {
524
+ var _ = { label: 0, sent: function() {
525
+ if (t[0] & 1) throw t[1];
526
+ return t[1];
527
+ }, trys: [], ops: [] }, f, y, t, g;
528
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
529
+ return this;
530
+ }), g;
531
+ function verb(n) {
532
+ return function(v) {
533
+ return step([n, v]);
534
+ };
535
+ }
536
+ function step(op) {
537
+ if (f) throw new TypeError("Generator is already executing.");
538
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
539
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
540
+ if (y = 0, t) op = [op[0] & 2, t.value];
541
+ switch (op[0]) {
542
+ case 0:
543
+ case 1:
544
+ t = op;
545
+ break;
546
+ case 4:
547
+ _.label++;
548
+ return { value: op[1], done: false };
549
+ case 5:
550
+ _.label++;
551
+ y = op[1];
552
+ op = [0];
553
+ continue;
554
+ case 7:
555
+ op = _.ops.pop();
556
+ _.trys.pop();
557
+ continue;
558
+ default:
559
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
560
+ _ = 0;
561
+ continue;
562
+ }
563
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
564
+ _.label = op[1];
565
+ break;
566
+ }
567
+ if (op[0] === 6 && _.label < t[1]) {
568
+ _.label = t[1];
569
+ t = op;
570
+ break;
571
+ }
572
+ if (t && _.label < t[2]) {
573
+ _.label = t[2];
574
+ _.ops.push(op);
575
+ break;
576
+ }
577
+ if (t[2]) _.ops.pop();
578
+ _.trys.pop();
579
+ continue;
580
+ }
581
+ op = body.call(thisArg, _);
582
+ } catch (e) {
583
+ op = [6, e];
584
+ y = 0;
585
+ } finally {
586
+ f = t = 0;
587
+ }
588
+ if (op[0] & 5) throw op[1];
589
+ return { value: op[0] ? op[1] : void 0, done: true };
590
+ }
591
+ }
592
+ function __spreadArray(to, from, pack) {
593
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
594
+ if (ar || !(i in from)) {
595
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
596
+ ar[i] = from[i];
597
+ }
598
+ }
599
+ return to.concat(ar || Array.prototype.slice.call(from));
600
+ }
601
+ var defaultConsoleSinkOptions = {
602
+ removeLogLevelPrefix: false,
603
+ includeTimestamps: false,
604
+ includeProperties: false
605
+ };
606
+ var ConsoleSink2 = (
607
+ /** @class */
608
+ (function() {
609
+ function ConsoleSink3(options) {
610
+ this.options = __assign(__assign({}, defaultConsoleSinkOptions), options || {});
611
+ var internalConsole = this.options.console || typeof console !== "undefined" && console || null;
612
+ var stub = function() {
613
+ };
614
+ var nodeConsole = !this.options.console && typeof process !== "undefined" && process.versions && process.versions.node;
615
+ this.console = {
616
+ error: internalConsole && (internalConsole.error || internalConsole.log) || stub,
617
+ warn: internalConsole && (internalConsole.warn || internalConsole.log) || stub,
618
+ info: internalConsole && (internalConsole.info || internalConsole.log) || stub,
619
+ debug: internalConsole && (!nodeConsole && internalConsole.debug || internalConsole.log) || stub,
620
+ log: internalConsole && internalConsole.log || stub
621
+ };
622
+ }
623
+ ConsoleSink3.prototype.emit = function(events) {
624
+ for (var i = 0; i < events.length; ++i) {
625
+ var e = events[i];
626
+ if (!isEnabled(this.options.restrictedToMinimumLevel, e.level))
627
+ continue;
628
+ switch (e.level) {
629
+ case exports3.LogEventLevel.fatal:
630
+ this.writeToConsole(this.console.error, "Fatal", e);
631
+ break;
632
+ case exports3.LogEventLevel.error:
633
+ this.writeToConsole(this.console.error, "Error", e);
634
+ break;
635
+ case exports3.LogEventLevel.warning:
636
+ this.writeToConsole(this.console.warn, "Warning", e);
637
+ break;
638
+ case exports3.LogEventLevel.information:
639
+ this.writeToConsole(this.console.info, "Information", e);
640
+ break;
641
+ case exports3.LogEventLevel.debug:
642
+ this.writeToConsole(this.console.debug, "Debug", e);
643
+ break;
644
+ case exports3.LogEventLevel.verbose:
645
+ this.writeToConsole(this.console.debug, "Verbose", e);
646
+ break;
647
+ default:
648
+ this.writeToConsole(this.console.log, "Log", e);
649
+ break;
650
+ }
651
+ }
652
+ return null;
653
+ };
654
+ ConsoleSink3.prototype.flush = function() {
655
+ return Promise.resolve();
656
+ };
657
+ ConsoleSink3.prototype.writeToConsole = function(logMethod, prefix, e) {
658
+ var output = "" + e.messageTemplate.render(e.properties);
659
+ if (!this.options.removeLogLevelPrefix)
660
+ output = "[" + prefix + "] " + output;
661
+ if (this.options.includeTimestamps)
662
+ output = e.timestamp + " " + output;
663
+ var values = [];
664
+ if (this.options.includeProperties) {
665
+ for (var key in e.properties) {
666
+ if (e.properties.hasOwnProperty(key)) {
667
+ values.push(e.properties[key]);
668
+ }
669
+ }
670
+ }
671
+ if (e.error instanceof Error) {
672
+ values.push("\n", e.error);
673
+ }
674
+ logMethod.apply(void 0, __spreadArray([output], values));
675
+ };
676
+ return ConsoleSink3;
677
+ })()
678
+ );
679
+ var ColoredConsoleSink = (
680
+ /** @class */
681
+ (function(_super) {
682
+ __extends(ColoredConsoleSink2, _super);
683
+ function ColoredConsoleSink2() {
684
+ return _super !== null && _super.apply(this, arguments) || this;
685
+ }
686
+ ColoredConsoleSink2.prototype.writeToConsole = function(logMethod, prefix, e) {
687
+ var output = "" + e.messageTemplate.render(e.properties);
688
+ if (!this.options.removeLogLevelPrefix)
689
+ output = "[" + prefix + "] " + output;
690
+ output = "" + this.logLevelToColor(e.level) + output + "\x1B[0m";
691
+ if (this.options.includeTimestamps)
692
+ output = e.timestamp + " " + output;
693
+ var values = [];
694
+ if (this.options.includeProperties) {
695
+ for (var key in e.properties) {
696
+ if (e.properties.hasOwnProperty(key)) {
697
+ values.push(e.properties[key]);
698
+ }
699
+ }
700
+ }
701
+ if (e.error instanceof Error) {
702
+ values.push("\n", e.error);
703
+ }
704
+ logMethod.apply(void 0, __spreadArray([output], values));
705
+ };
706
+ ColoredConsoleSink2.prototype.logLevelToColor = function(level) {
707
+ switch (level) {
708
+ case exports3.LogEventLevel.verbose:
709
+ case exports3.LogEventLevel.debug:
710
+ return "\x1B[2m";
711
+ case exports3.LogEventLevel.warning:
712
+ return "\x1B[31m";
713
+ case exports3.LogEventLevel.fatal:
714
+ return "\x1B[37m\x1B[41m";
715
+ default:
716
+ return "";
717
+ }
718
+ };
719
+ return ColoredConsoleSink2;
720
+ })(ConsoleSink2)
721
+ );
722
+ var defaultBatchedSinkOptions = {
723
+ maxSize: 100,
724
+ period: 5,
725
+ durableStore: void 0
726
+ };
727
+ var BatchedSink = (
728
+ /** @class */
729
+ (function() {
730
+ function BatchedSink2(innerSink, options) {
731
+ this.durableStorageKey = "serilogger-batched-sink-durable-cache";
732
+ this.batchKey = "";
733
+ this.shouldCycleContinue = true;
734
+ this.innerSink = innerSink || void 0;
735
+ this.options = __assign(__assign({}, defaultBatchedSinkOptions), options || {});
736
+ this.batchedEvents = [];
737
+ this.cycleBatch();
738
+ if (this.options.durableStore) {
739
+ var initialBatch = [];
740
+ for (var key in this.options.durableStore) {
741
+ if (key.indexOf(this.durableStorageKey) === 0) {
742
+ var storedEvents = JSON.parse(this.options.durableStore.getItem(key)).map(function(e) {
743
+ e.messageTemplate = new MessageTemplate(e.messageTemplate.raw);
744
+ return e;
745
+ });
746
+ initialBatch = initialBatch.concat(storedEvents);
747
+ this.options.durableStore.removeItem(key);
748
+ }
749
+ }
750
+ this.emit(initialBatch);
751
+ }
752
+ }
753
+ BatchedSink2.prototype.emit = function(events) {
754
+ var _a, _b, _c;
755
+ if (this.batchedEvents.length + events.length <= this.options.maxSize) {
756
+ (_a = this.batchedEvents).push.apply(_a, events);
757
+ this.storeEvents();
758
+ } else {
759
+ var cursor = this.options.maxSize - this.batchedEvents.length < 0 ? 0 : this.options.maxSize - this.batchedEvents.length;
760
+ (_b = this.batchedEvents).push.apply(_b, events.slice(0, cursor));
761
+ this.storeEvents();
762
+ while (cursor < events.length) {
763
+ this.cycleBatch();
764
+ (_c = this.batchedEvents).push.apply(_c, events.slice(cursor, cursor = cursor + this.options.maxSize));
765
+ this.storeEvents();
766
+ }
767
+ }
768
+ return events;
769
+ };
770
+ BatchedSink2.prototype.flush = function() {
771
+ this.cycleBatch();
772
+ var corePromise = this.flushCore();
773
+ return corePromise instanceof Promise ? corePromise : Promise.resolve();
774
+ };
775
+ BatchedSink2.prototype.emitCore = function(events) {
776
+ return this.innerSink ? this.innerSink.emit(events) : null;
777
+ };
778
+ BatchedSink2.prototype.flushCore = function() {
779
+ return this.innerSink ? this.innerSink.flush() : Promise.resolve();
780
+ };
781
+ BatchedSink2.prototype.cycleBatch = function() {
782
+ var _this = this;
783
+ if (this.batchTimeout)
784
+ clearTimeout(this.batchTimeout);
785
+ if (!this.shouldCycleContinue)
786
+ return;
787
+ if (this.batchedEvents.length) {
788
+ var processEvents_1 = this.batchedEvents.slice(0);
789
+ this.batchedEvents.length = 0;
790
+ var previousBatchKey_1 = this.batchKey;
791
+ var emitPromise = this.emitCore(processEvents_1);
792
+ (emitPromise instanceof Promise ? emitPromise : Promise.resolve()).then(function() {
793
+ if (_this.options.durableStore) {
794
+ return _this.options.durableStore.removeItem(previousBatchKey_1);
795
+ }
796
+ }).catch(function() {
797
+ var _a;
798
+ (_a = _this.batchedEvents).unshift.apply(_a, processEvents_1);
799
+ });
800
+ }
801
+ this.batchKey = this.durableStorageKey + "-" + (/* @__PURE__ */ new Date()).getTime();
802
+ if (!isNaN(this.options.period) && this.options.period > 0) {
803
+ this.batchTimeout = setTimeout(function() {
804
+ return _this.cycleBatch();
805
+ }, this.options.period * 1e3);
806
+ }
807
+ };
808
+ BatchedSink2.prototype.storeEvents = function() {
809
+ if (this.options.durableStore) {
810
+ this.options.durableStore.setItem(this.batchKey, JSON.stringify(this.batchedEvents));
811
+ }
812
+ };
813
+ return BatchedSink2;
814
+ })()
815
+ );
816
+ var FilterStage = (
817
+ /** @class */
818
+ (function() {
819
+ function FilterStage2(predicate) {
820
+ this.predicate = predicate;
821
+ }
822
+ FilterStage2.prototype.emit = function(events) {
823
+ return events.filter(this.predicate);
824
+ };
825
+ FilterStage2.prototype.flush = function() {
826
+ return Promise.resolve();
827
+ };
828
+ return FilterStage2;
829
+ })()
830
+ );
831
+ var DynamicLevelSwitch = (
832
+ /** @class */
833
+ (function() {
834
+ function DynamicLevelSwitch2(defaultLevel) {
835
+ this.flushDelegate = function() {
836
+ return Promise.resolve();
837
+ };
838
+ this.minLevel = defaultLevel;
839
+ }
840
+ DynamicLevelSwitch2.prototype.fatal = function() {
841
+ return __awaiter(this, void 0, void 0, function() {
842
+ return __generator(this, function(_a) {
843
+ switch (_a.label) {
844
+ case 0:
845
+ return [4, this.flushDelegate()];
846
+ case 1:
847
+ _a.sent();
848
+ return [2, this.minLevel = exports3.LogEventLevel.fatal];
849
+ }
850
+ });
851
+ });
852
+ };
853
+ DynamicLevelSwitch2.prototype.error = function() {
854
+ return __awaiter(this, void 0, void 0, function() {
855
+ return __generator(this, function(_a) {
856
+ switch (_a.label) {
857
+ case 0:
858
+ return [4, this.flushDelegate()];
859
+ case 1:
860
+ _a.sent();
861
+ return [2, this.minLevel = exports3.LogEventLevel.error];
862
+ }
863
+ });
864
+ });
865
+ };
866
+ DynamicLevelSwitch2.prototype.warning = function() {
867
+ return __awaiter(this, void 0, void 0, function() {
868
+ return __generator(this, function(_a) {
869
+ switch (_a.label) {
870
+ case 0:
871
+ return [4, this.flushDelegate()];
872
+ case 1:
873
+ _a.sent();
874
+ return [2, this.minLevel = exports3.LogEventLevel.warning];
875
+ }
876
+ });
877
+ });
878
+ };
879
+ DynamicLevelSwitch2.prototype.information = function() {
880
+ return __awaiter(this, void 0, void 0, function() {
881
+ return __generator(this, function(_a) {
882
+ switch (_a.label) {
883
+ case 0:
884
+ return [4, this.flushDelegate()];
885
+ case 1:
886
+ _a.sent();
887
+ return [2, this.minLevel = exports3.LogEventLevel.information];
888
+ }
889
+ });
890
+ });
891
+ };
892
+ DynamicLevelSwitch2.prototype.debug = function() {
893
+ return __awaiter(this, void 0, void 0, function() {
894
+ return __generator(this, function(_a) {
895
+ switch (_a.label) {
896
+ case 0:
897
+ return [4, this.flushDelegate()];
898
+ case 1:
899
+ _a.sent();
900
+ return [2, this.minLevel = exports3.LogEventLevel.debug];
901
+ }
902
+ });
903
+ });
904
+ };
905
+ DynamicLevelSwitch2.prototype.verbose = function() {
906
+ return __awaiter(this, void 0, void 0, function() {
907
+ return __generator(this, function(_a) {
908
+ switch (_a.label) {
909
+ case 0:
910
+ return [4, this.flushDelegate()];
911
+ case 1:
912
+ _a.sent();
913
+ return [2, this.minLevel = exports3.LogEventLevel.verbose];
914
+ }
915
+ });
916
+ });
917
+ };
918
+ DynamicLevelSwitch2.prototype.off = function() {
919
+ return __awaiter(this, void 0, void 0, function() {
920
+ return __generator(this, function(_a) {
921
+ switch (_a.label) {
922
+ case 0:
923
+ return [4, this.flushDelegate()];
924
+ case 1:
925
+ _a.sent();
926
+ return [2, this.minLevel = exports3.LogEventLevel.off];
927
+ }
928
+ });
929
+ });
930
+ };
931
+ DynamicLevelSwitch2.prototype.set = function(level) {
932
+ return __awaiter(this, void 0, void 0, function() {
933
+ return __generator(this, function(_a) {
934
+ switch (_a.label) {
935
+ case 0:
936
+ return [4, this.flushDelegate()];
937
+ case 1:
938
+ _a.sent();
939
+ return [2, this.minLevel = level];
940
+ }
941
+ });
942
+ });
943
+ };
944
+ DynamicLevelSwitch2.prototype.isEnabled = function(level) {
945
+ return this.minLevel === void 0 || isEnabled(this.minLevel, level);
946
+ };
947
+ return DynamicLevelSwitch2;
948
+ })()
949
+ );
950
+ var DynamicLevelSwitchStage = (
951
+ /** @class */
952
+ (function(_super) {
953
+ __extends(DynamicLevelSwitchStage2, _super);
954
+ function DynamicLevelSwitchStage2(dynamicLevelSwitch) {
955
+ var _this = _super.call(this, function(e) {
956
+ return dynamicLevelSwitch.isEnabled(e.level);
957
+ }) || this;
958
+ _this.dynamicLevelSwitch = dynamicLevelSwitch;
959
+ return _this;
960
+ }
961
+ DynamicLevelSwitchStage2.prototype.setFlushDelegate = function(flushDelegate) {
962
+ this.dynamicLevelSwitch.flushDelegate = flushDelegate;
963
+ };
964
+ return DynamicLevelSwitchStage2;
965
+ })(FilterStage)
966
+ );
967
+ var ApiSink = (
968
+ /** @class */
969
+ (function() {
970
+ function ApiSink2(options) {
971
+ var _this = this;
972
+ this.url = null;
973
+ this.headers = null;
974
+ this.durable = false;
975
+ this.compact = false;
976
+ this.levelSwitch = null;
977
+ this.refreshLevelSwitchTimeoutId = null;
978
+ this.refreshLevelSwitchTimeoutInterval = 2 * 60 * 1e3;
979
+ this.suppressErrors = true;
980
+ if (!options) {
981
+ throw new Error("'options' parameter is required.");
982
+ }
983
+ if (!options.url || options.url === "") {
984
+ throw new Error("'options.url' parameter is required.");
985
+ }
986
+ this.url = options.url.replace(/\/$/, "");
987
+ this.levelSwitch = options.levelSwitch || null;
988
+ this.suppressErrors = options.suppressErrors !== false;
989
+ if (options.durable && typeof localStorage === "undefined") {
990
+ if (typeof console !== "undefined" && console.warn) {
991
+ console.warn("'options.durable' parameter was set to true, but 'localStorage' is not available.");
992
+ }
993
+ this.durable = false;
994
+ } else {
995
+ this.durable = !!options.durable;
996
+ }
997
+ this.compact = !!options.compact;
998
+ if (this.durable) {
999
+ var requests = {};
1000
+ var _loop_1 = function(i2) {
1001
+ var storageKey = localStorage.key(i2);
1002
+ if (storageKey.indexOf("serilogger-" + this_1.toString()) !== 0) {
1003
+ return "continue";
1004
+ }
1005
+ var body = localStorage.getItem(storageKey);
1006
+ requests[storageKey] = this_1.postToLogger(this_1.url, body).then(function() {
1007
+ return localStorage.removeItem(storageKey);
1008
+ }).catch(function(reason) {
1009
+ if (_this.suppressErrors)
1010
+ _this.logSuppressedError(reason);
1011
+ throw new Error(reason);
1012
+ });
1013
+ };
1014
+ var this_1 = this;
1015
+ for (var i = 0; i < localStorage.length; ++i) {
1016
+ _loop_1(i);
1017
+ }
1018
+ }
1019
+ if (this.levelSwitch !== null) {
1020
+ this.refreshLevelSwitchTimeoutId = setTimeout(function() {
1021
+ return _this.sendToServer([]);
1022
+ }, this.refreshLevelSwitchTimeoutInterval);
1023
+ }
1024
+ if (this.headers !== null) {
1025
+ this.headers = options.headers;
1026
+ }
1027
+ }
1028
+ ApiSink2.prototype.toString = function() {
1029
+ return "ApiSink";
1030
+ };
1031
+ ApiSink2.prototype.emit = function(events) {
1032
+ var _this = this;
1033
+ var filteredEvents = this.levelSwitch ? events.filter(function(e) {
1034
+ return _this.levelSwitch.isEnabled(e.level);
1035
+ }) : events;
1036
+ if (!filteredEvents.length) {
1037
+ return Promise.resolve();
1038
+ }
1039
+ return this.sendToServer(filteredEvents);
1040
+ };
1041
+ ApiSink2.prototype.flush = function() {
1042
+ return Promise.resolve();
1043
+ };
1044
+ ApiSink2.prototype.sendToServer = function(events) {
1045
+ return __awaiter(this, void 0, void 0, function() {
1046
+ var seqEvents, body, storageKey, response, json, reason_1;
1047
+ var _this = this;
1048
+ return __generator(this, function(_a) {
1049
+ switch (_a.label) {
1050
+ case 0:
1051
+ seqEvents = this.compact ? events.reduce(function(s, e) {
1052
+ var mappedEvent = __assign({ "@l": _this.mapLogLevel(e.level), "@mt": e.messageTemplate.raw, "@t": e.timestamp }, e.properties);
1053
+ if (e.error instanceof Error && e.error.stack) {
1054
+ mappedEvent["@x"] = e.error.stack;
1055
+ }
1056
+ return "" + s + JSON.stringify(mappedEvent) + "\n";
1057
+ }, "").replace(/\s+$/g, "") : events.map(function(e) {
1058
+ var mappedEvent = {
1059
+ Level: _this.mapLogLevel(e.level),
1060
+ MessageTemplate: e.messageTemplate.raw,
1061
+ Properties: e.properties,
1062
+ Timestamp: e.timestamp
1063
+ };
1064
+ if (e.error instanceof Error && e.error.stack) {
1065
+ mappedEvent["Exception"] = e.error.stack;
1066
+ }
1067
+ return mappedEvent;
1068
+ });
1069
+ body = this.compact ? seqEvents : JSON.stringify({
1070
+ Events: seqEvents
1071
+ });
1072
+ if (this.durable) {
1073
+ storageKey = "serilogger-" + this.toString() + "-" + (/* @__PURE__ */ new Date()).getTime() + "-" + (Math.floor(Math.random() * 1e6) + 1);
1074
+ localStorage.setItem(storageKey, body);
1075
+ }
1076
+ _a.label = 1;
1077
+ case 1:
1078
+ _a.trys.push([1, 4, , 5]);
1079
+ return [4, this.postToLogger(this.url, body)];
1080
+ case 2:
1081
+ response = _a.sent();
1082
+ return [4, response.json()];
1083
+ case 3:
1084
+ json = _a.sent();
1085
+ this.updateLogLevel(json);
1086
+ if (storageKey)
1087
+ localStorage.removeItem(storageKey);
1088
+ return [3, 5];
1089
+ case 4:
1090
+ reason_1 = _a.sent();
1091
+ return [2, this.suppressErrors ? this.logSuppressedError(reason_1) : Promise.reject(reason_1)];
1092
+ case 5:
1093
+ return [
1094
+ 2
1095
+ /*return*/
1096
+ ];
1097
+ }
1098
+ });
1099
+ });
1100
+ };
1101
+ ApiSink2.prototype.updateLogLevel = function(response) {
1102
+ var _this = this;
1103
+ if (!this.levelSwitch)
1104
+ return;
1105
+ if (this.refreshLevelSwitchTimeoutId) {
1106
+ clearTimeout(this.refreshLevelSwitchTimeoutId);
1107
+ this.refreshLevelSwitchTimeoutId = setTimeout(function() {
1108
+ return _this.sendToServer([]);
1109
+ }, this.refreshLevelSwitchTimeoutInterval);
1110
+ }
1111
+ if (response && response.MinimumLevelAccepted) {
1112
+ switch (response.MinimumLevelAccepted) {
1113
+ case "Fatal":
1114
+ this.levelSwitch.fatal();
1115
+ break;
1116
+ case "Error":
1117
+ this.levelSwitch.error();
1118
+ break;
1119
+ case "Warning":
1120
+ this.levelSwitch.warning();
1121
+ break;
1122
+ case "Information":
1123
+ this.levelSwitch.information();
1124
+ break;
1125
+ case "Debug":
1126
+ this.levelSwitch.debug();
1127
+ break;
1128
+ case "Verbose":
1129
+ this.levelSwitch.verbose();
1130
+ break;
1131
+ }
1132
+ }
1133
+ };
1134
+ ApiSink2.prototype.logSuppressedError = function(reason) {
1135
+ if (typeof console !== "undefined" && console.warn) {
1136
+ console.warn("Suppressed error when logging to " + this.toString() + ": " + reason);
1137
+ }
1138
+ };
1139
+ ApiSink2.prototype.mapLogLevel = function(logLevel) {
1140
+ if (logLevel === 1) {
1141
+ return "Fatal";
1142
+ } else if (logLevel === 3) {
1143
+ return "Error";
1144
+ } else if (logLevel === 7) {
1145
+ return "Warning";
1146
+ } else if (logLevel === 31) {
1147
+ return "Debug";
1148
+ } else if (logLevel === 63) {
1149
+ return "Verbose";
1150
+ }
1151
+ return "Information";
1152
+ };
1153
+ ApiSink2.prototype.postToLogger = function(url, body) {
1154
+ var promise = fetch("" + url, {
1155
+ headers: this.headers || {},
1156
+ method: "POST",
1157
+ body
1158
+ });
1159
+ return promise;
1160
+ };
1161
+ return ApiSink2;
1162
+ })()
1163
+ );
1164
+ var SeqSink = (
1165
+ /** @class */
1166
+ (function(_super) {
1167
+ __extends(SeqSink2, _super);
1168
+ function SeqSink2(options) {
1169
+ var _this = _super.call(this, {
1170
+ compact: options.compact || false,
1171
+ durable: options.durable || false,
1172
+ levelSwitch: options.levelSwitch,
1173
+ suppressErrors: options.suppressErrors || true,
1174
+ url: options.url,
1175
+ headers: null
1176
+ }) || this;
1177
+ _this.apiKey = null;
1178
+ _this.apiKey = options.apiKey;
1179
+ return _this;
1180
+ }
1181
+ SeqSink2.prototype.toString = function() {
1182
+ return "SeqSink";
1183
+ };
1184
+ SeqSink2.prototype.postToLogger = function(url, body) {
1185
+ var apiKeyParameter = this.apiKey ? "?apiKey=" + this.apiKey : "";
1186
+ var promise = fetch(url + "/api/events/raw" + apiKeyParameter, {
1187
+ headers: {
1188
+ "content-type": this.compact ? "application/vnd.serilog.clef" : "application/json"
1189
+ },
1190
+ method: "POST",
1191
+ body
1192
+ });
1193
+ return promise;
1194
+ };
1195
+ return SeqSink2;
1196
+ })(ApiSink)
1197
+ );
1198
+ var LoggerConfiguration2 = (
1199
+ /** @class */
1200
+ (function() {
1201
+ function LoggerConfiguration3() {
1202
+ var _this = this;
1203
+ this.minLevel = Object.assign(function(levelOrSwitch) {
1204
+ if (typeof levelOrSwitch === "undefined" || levelOrSwitch === null) {
1205
+ throw new TypeError('Argument "levelOrSwitch" is not a valid LogEventLevel value or DynamicLevelSwitch instance.');
1206
+ } else if (levelOrSwitch instanceof DynamicLevelSwitch) {
1207
+ var switchStage = new DynamicLevelSwitchStage(levelOrSwitch);
1208
+ switchStage.setFlushDelegate(function() {
1209
+ return _this._stages.flush();
1210
+ });
1211
+ _this._stages.addStage(switchStage);
1212
+ return _this;
1213
+ } else if (typeof levelOrSwitch === "string") {
1214
+ var level_1 = exports3.LogEventLevel[levelOrSwitch.toLowerCase()];
1215
+ if (typeof level_1 === "undefined" || level_1 === null) {
1216
+ throw new TypeError('Argument "levelOrSwitch" is not a valid LogEventLevel value.');
1217
+ }
1218
+ return _this.filter(function(e) {
1219
+ return isEnabled(level_1, e.level);
1220
+ });
1221
+ } else {
1222
+ return _this.filter(function(e) {
1223
+ return isEnabled(levelOrSwitch, e.level);
1224
+ });
1225
+ }
1226
+ }, {
1227
+ fatal: function() {
1228
+ return _this.minLevel(exports3.LogEventLevel.fatal);
1229
+ },
1230
+ error: function() {
1231
+ return _this.minLevel(exports3.LogEventLevel.error);
1232
+ },
1233
+ warning: function() {
1234
+ return _this.minLevel(exports3.LogEventLevel.warning);
1235
+ },
1236
+ information: function() {
1237
+ return _this.minLevel(exports3.LogEventLevel.information);
1238
+ },
1239
+ debug: function() {
1240
+ return _this.minLevel(exports3.LogEventLevel.debug);
1241
+ },
1242
+ verbose: function() {
1243
+ return _this.minLevel(exports3.LogEventLevel.verbose);
1244
+ }
1245
+ });
1246
+ this._stages = new Pipeline();
1247
+ this._sinks = [];
1248
+ this._suppressErrors = true;
1249
+ }
1250
+ LoggerConfiguration3.prototype.writeTo = function(sink) {
1251
+ this._sinks.push(new SinkStage(sink));
1252
+ return this;
1253
+ };
1254
+ LoggerConfiguration3.prototype.filter = function(predicate) {
1255
+ if (predicate instanceof Function) {
1256
+ this._stages.addStage(new FilterStage(predicate));
1257
+ } else {
1258
+ throw new TypeError('Argument "predicate" must be a function.');
1259
+ }
1260
+ return this;
1261
+ };
1262
+ LoggerConfiguration3.prototype.enrich = function(enricher) {
1263
+ if (enricher instanceof Function || enricher instanceof Object) {
1264
+ this._stages.addStage(new EnrichStage(enricher));
1265
+ } else {
1266
+ throw new TypeError('Argument "enricher" must be either a function or an object.');
1267
+ }
1268
+ return this;
1269
+ };
1270
+ LoggerConfiguration3.prototype.suppressErrors = function(suppress) {
1271
+ this._suppressErrors = typeof suppress === "undefined" || suppress;
1272
+ return this;
1273
+ };
1274
+ LoggerConfiguration3.prototype.readFromConfiguration = function(config, keyName) {
1275
+ var _a, _b;
1276
+ if (keyName === void 0) {
1277
+ keyName = "serilogger";
1278
+ }
1279
+ if (config === null || config === void 0)
1280
+ throw new TypeError('Argument "config" cannot be null or undefined');
1281
+ if (!config[keyName])
1282
+ throw new TypeError('Argument "config" must contain a property of "' + keyName + '"');
1283
+ config = config[keyName];
1284
+ if (!config["writeTo"])
1285
+ throw new TypeError('Argument "config" must contain a sub-property of "writeTo"');
1286
+ if (!(config["writeTo"] instanceof Array))
1287
+ throw new TypeError('"writeTo" property must be an Array');
1288
+ if (config["writeTo"].length === 0)
1289
+ throw new TypeError('"writeTo" property must have at least one element');
1290
+ var writeToItems = config["writeTo"];
1291
+ for (var _i = 0, writeToItems_1 = writeToItems; _i < writeToItems_1.length; _i++) {
1292
+ var item = writeToItems_1[_i];
1293
+ if (!item["name"])
1294
+ continue;
1295
+ switch (item["name"].toLowerCase()) {
1296
+ case "console":
1297
+ this._sinks.push(new SinkStage(new ConsoleSink2((_a = item["args"]) !== null && _a !== void 0 ? _a : null)));
1298
+ break;
1299
+ case "coloredconsole":
1300
+ this._sinks.push(new SinkStage(new ColoredConsoleSink((_b = item["args"]) !== null && _b !== void 0 ? _b : null)));
1301
+ break;
1302
+ case "seq":
1303
+ if (!item["args"])
1304
+ throw new TypeError("Seq sink requires input arguments");
1305
+ this._sinks.push(new SinkStage(new SeqSink(item["args"])));
1306
+ break;
1307
+ default:
1308
+ throw new TypeError("Unknown WriteTo Type: " + item["name"]);
1309
+ }
1310
+ }
1311
+ return this;
1312
+ };
1313
+ LoggerConfiguration3.prototype.create = function() {
1314
+ var _this = this;
1315
+ this._sinks.forEach(function(sink) {
1316
+ return _this._stages.addStage(sink);
1317
+ });
1318
+ return new Logger2(this._stages, this._suppressErrors);
1319
+ };
1320
+ return LoggerConfiguration3;
1321
+ })()
1322
+ );
1323
+ function configure2() {
1324
+ return new LoggerConfiguration2();
1325
+ }
1326
+ exports3.ApiSink = ApiSink;
1327
+ exports3.BatchedSink = BatchedSink;
1328
+ exports3.ColoredConsoleSink = ColoredConsoleSink;
1329
+ exports3.ConsoleSink = ConsoleSink2;
1330
+ exports3.DynamicLevelSwitch = DynamicLevelSwitch;
1331
+ exports3.LogEvent = LogEvent2;
1332
+ exports3.Logger = Logger2;
1333
+ exports3.LoggerConfiguration = LoggerConfiguration2;
1334
+ exports3.SeqSink = SeqSink;
1335
+ exports3.configure = configure2;
1336
+ }));
1337
+ }
1338
+ });
1339
+
1340
+ // src/core/plugins/sandbox/pluginWorker.ts
1341
+ var pluginWorker_exports = {};
1342
+ __export(pluginWorker_exports, {
1343
+ confinementRootOf: () => confinementRootOf
1344
+ });
1345
+ module.exports = __toCommonJS(pluginWorker_exports);
1346
+ init_define_SDD_PROMPTS();
1347
+ var path = __toESM(require("path"));
1348
+
1349
+ // src/core/logging/logger.ts
1350
+ init_define_SDD_PROMPTS();
1351
+ var import_serilogger = __toESM(require_serilogger());
1352
+ var MESSAGE_TEMPLATE = "{Message}";
1353
+ var CATEGORY_PROPERTY = "category";
1354
+ function consolePipeline() {
1355
+ return (0, import_serilogger.configure)().minLevel.verbose().writeTo(new import_serilogger.ConsoleSink());
1356
+ }
1357
+ var engine = consolePipeline().create();
1358
+ function flushLogs() {
1359
+ return engine.flush();
1360
+ }
1361
+ function facade(category) {
1362
+ const target = () => category ? engine.createChild({ [CATEGORY_PROPERTY]: category }) : engine;
1363
+ return {
1364
+ info: (message) => target().info(MESSAGE_TEMPLATE, message),
1365
+ warning: (message) => target().warn(MESSAGE_TEMPLATE, message),
1366
+ error: (message) => target().error(MESSAGE_TEMPLATE, message),
1367
+ critical: (message) => target().fatal(MESSAGE_TEMPLATE, message)
1368
+ };
1369
+ }
1370
+ var logger = facade();
1371
+ function getLogger(category) {
1372
+ return facade(category);
1373
+ }
1374
+ function messageOf(error) {
1375
+ return error instanceof Error ? error.message : String(error);
1376
+ }
1377
+
1378
+ // src/core/plugins/sandbox/pluginWorker.ts
1379
+ var logger2 = getLogger("PluginWorker");
1380
+ var ALLOWED_MODULES = /* @__PURE__ */ new Set([
1381
+ "assert",
1382
+ "buffer",
1383
+ "crypto",
1384
+ "events",
1385
+ "path",
1386
+ "punycode",
1387
+ "querystring",
1388
+ "string_decoder",
1389
+ "url",
1390
+ "util",
1391
+ "zlib"
1392
+ ]);
1393
+ var EXPLAINED = /* @__PURE__ */ new Map([
1394
+ ["fs", "read and write files"],
1395
+ ["fs/promises", "read and write files"],
1396
+ ["child_process", "run other programs"],
1397
+ ["net", "open network connections"],
1398
+ ["http", "open network connections"],
1399
+ ["https", "open network connections"],
1400
+ ["dgram", "open network connections"],
1401
+ ["dns", "resolve host names"],
1402
+ ["worker_threads", "start threads"],
1403
+ ["vm", "compile code"],
1404
+ ["module", "reach around the loader"],
1405
+ ["inspector", "attach a debugger"]
1406
+ ]);
1407
+ function denialFor(request) {
1408
+ const capability = EXPLAINED.get(bare(request));
1409
+ return capability ? `A plugin cannot require '${request}' - it would let the plugin ${capability}, which the sandbox exists to prevent. Ask the engine for what you need through the plugin context instead.` : `A plugin cannot require '${request}'. Allowed modules: ${[...ALLOWED_MODULES].sort().join(", ")}.`;
1410
+ }
1411
+ var bare = (request) => request.replace(/^node:/, "");
1412
+ function isBuiltin(request) {
1413
+ return request.startsWith("node:") || require("module").builtinModules.includes(bare(request));
1414
+ }
1415
+ function resolveDependency(request, from) {
1416
+ try {
1417
+ return require.resolve(request, { paths: [path.dirname(from)] });
1418
+ } catch {
1419
+ return void 0;
1420
+ }
1421
+ }
1422
+ function inside(root, candidate) {
1423
+ const relative2 = path.relative(root, candidate);
1424
+ return relative2 === "" || !relative2.startsWith("..") && !path.isAbsolute(relative2);
1425
+ }
1426
+ function lockLoader(pluginRoot) {
1427
+ const Module = require("module");
1428
+ const load = Module._load;
1429
+ Module._load = function(request, parent, isMain) {
1430
+ const from = parent?.filename;
1431
+ if (!from || !inside(pluginRoot, from))
1432
+ return load.call(this, request, parent, isMain);
1433
+ const relative2 = request.startsWith(".") || path.isAbsolute(request);
1434
+ if (!relative2) {
1435
+ if (ALLOWED_MODULES.has(bare(request)))
1436
+ return load.call(this, request, parent, isMain);
1437
+ if (isBuiltin(request))
1438
+ throw new Error(denialFor(request));
1439
+ const dependency = resolveDependency(request, from);
1440
+ if (!dependency || !inside(pluginRoot, dependency))
1441
+ throw new Error(
1442
+ `A plugin cannot require '${request}' - it is not a permitted builtin, and it was not found in the plugin's own node_modules. Install it beside the plugin and ship it with it.`
1443
+ );
1444
+ return load.call(this, request, parent, isMain);
1445
+ }
1446
+ const resolved = path.resolve(path.dirname(from), request);
1447
+ if (!inside(pluginRoot, resolved))
1448
+ throw new Error(
1449
+ `A plugin cannot require '${request}' - it resolves outside the plugin's own directory.`
1450
+ );
1451
+ return load.call(this, request, parent, isMain);
1452
+ };
1453
+ }
1454
+ function confinementRootOf(argv, modulePath) {
1455
+ const flag = argv.indexOf("--root");
1456
+ return flag >= 0 && argv[flag + 1] ? argv[flag + 1] : path.dirname(modulePath);
1457
+ }
1458
+ function loadPlugin(modulePath) {
1459
+ lockLoader(confinementRootOf(process.argv, modulePath));
1460
+ const loaded = require(modulePath);
1461
+ const candidate = loaded?.default ?? loaded;
1462
+ if (!candidate || typeof candidate !== "object")
1463
+ throw new Error(`${path.basename(modulePath)} did not export a plugin object.`);
1464
+ if (typeof candidate.execute !== "function")
1465
+ throw new Error(`${path.basename(modulePath)} must export an 'execute(args, ctx)' function.`);
1466
+ return candidate;
1467
+ }
1468
+ function permissionModelActive() {
1469
+ const permission = process.permission;
1470
+ if (!permission || typeof permission.has !== "function")
1471
+ return false;
1472
+ return !permission.has("fs.write") && !permission.has("child") && !permission.has("fs.read", "/");
1473
+ }
1474
+ function describe(modulePath) {
1475
+ const plugin = loadPlugin(modulePath);
1476
+ return {
1477
+ enforced: permissionModelActive(),
1478
+ id: plugin.id,
1479
+ version: plugin.version,
1480
+ description: plugin.description,
1481
+ args: plugin.args,
1482
+ artifacts: plugin.artifacts,
1483
+ artifactsFrom: plugin.artifactsFrom,
1484
+ secrets: plugin.secrets,
1485
+ secretsFrom: plugin.secretsFrom,
1486
+ ui: plugin.ui,
1487
+ hasHandle: typeof plugin.handle === "function"
1488
+ };
1489
+ }
1490
+ function send(message) {
1491
+ process.send?.(message);
1492
+ }
1493
+ var pendingDb = /* @__PURE__ */ new Map();
1494
+ var nextDbId = 0;
1495
+ function dbProxy() {
1496
+ const ask = (op, sql, params) => new Promise((resolve2, reject) => {
1497
+ const id = ++nextDbId;
1498
+ pendingDb.set(id, { resolve: resolve2, reject });
1499
+ send({ type: "db", id, op, sql: String(sql), params });
1500
+ });
1501
+ return {
1502
+ run: (sql, params) => ask("run", sql, params),
1503
+ get: (sql, params) => ask("get", sql, params),
1504
+ all: (sql, params) => ask("all", sql, params)
1505
+ };
1506
+ }
1507
+ function settleDb(message) {
1508
+ const waiting = pendingDb.get(message.id);
1509
+ if (!waiting)
1510
+ return;
1511
+ pendingDb.delete(message.id);
1512
+ if (message.ok)
1513
+ waiting.resolve(message.value);
1514
+ else
1515
+ waiting.reject(new Error(message.error ?? "The database call failed."));
1516
+ }
1517
+ function buildHandleContext(data) {
1518
+ return {
1519
+ cwd: data.cwd,
1520
+ root: data.root,
1521
+ env: Object.freeze({ ...data.env }),
1522
+ secret: (name) => {
1523
+ const value = data.secrets[name];
1524
+ if (value === void 0)
1525
+ send({
1526
+ type: "log",
1527
+ text: `Plugin asked for the secret '${name}', which it does not declare. Add it to the plugin's 'secrets' list to receive it.
1528
+ `,
1529
+ stream: "system"
1530
+ });
1531
+ return value;
1532
+ },
1533
+ log: (text, stream = "stdout") => send({ type: "log", text: String(text), stream }),
1534
+ ...data.hasDb ? { db: dbProxy() } : {}
1535
+ };
1536
+ }
1537
+ function buildContext(data, cancel) {
1538
+ return {
1539
+ ...buildHandleContext(data),
1540
+ runId: data.runId,
1541
+ taskId: data.taskId,
1542
+ attempt: data.attempt,
1543
+ // Sent as a message; a callback could not survive the fork.
1544
+ reportSession: (id) => send({ type: "session", id: String(id) }),
1545
+ get cancelled() {
1546
+ return cancel.cancelled;
1547
+ },
1548
+ onCancel: (handler) => cancel.handlers.push(handler)
1549
+ };
1550
+ }
1551
+ async function reportCrash(kind, error) {
1552
+ logger2.critical(`${kind}: ${messageOf(error)}`);
1553
+ await flushLogs();
1554
+ send({ type: "failed", message: messageOf(error) });
1555
+ process.exitCode = 1;
1556
+ }
1557
+ function main() {
1558
+ process.on("uncaughtException", (error) => void reportCrash("Uncaught exception", error));
1559
+ process.on("unhandledRejection", (reason) => void reportCrash("Unhandled rejection", reason));
1560
+ const describeIndex = process.argv.indexOf("--describe");
1561
+ if (describeIndex >= 0) {
1562
+ process.stdout.write(JSON.stringify(describe(process.argv[describeIndex + 1])));
1563
+ return;
1564
+ }
1565
+ const modulePath = process.argv[2];
1566
+ const cancel = { cancelled: false, handlers: [] };
1567
+ process.on("message", (message) => {
1568
+ if (message.type === "cancel") {
1569
+ cancel.cancelled = true;
1570
+ for (const handler of cancel.handlers)
1571
+ try {
1572
+ handler();
1573
+ } catch {
1574
+ }
1575
+ return;
1576
+ }
1577
+ if (message.type === "dbResult")
1578
+ return settleDb(message);
1579
+ if (message.type === "handle")
1580
+ return void handle(modulePath, message);
1581
+ void run(modulePath, message, cancel);
1582
+ });
1583
+ send({ type: "ready" });
1584
+ }
1585
+ async function run(modulePath, message, cancel) {
1586
+ try {
1587
+ const plugin = loadPlugin(modulePath);
1588
+ const result = await plugin.execute(message.args, buildContext(message.context, cancel));
1589
+ send({ type: "result", result });
1590
+ } catch (error) {
1591
+ send({ type: "failed", message: error instanceof Error ? error.message : String(error) });
1592
+ }
1593
+ }
1594
+ async function handle(modulePath, message) {
1595
+ try {
1596
+ const plugin = loadPlugin(modulePath);
1597
+ if (typeof plugin.handle !== "function")
1598
+ throw new Error(`${path.basename(modulePath)} does not export a 'handle(request, ctx)' function, so its tab has nothing to call.`);
1599
+ const value = await plugin.handle(message.request, buildHandleContext(message.context));
1600
+ send({ type: "handled", value: value === void 0 ? null : value });
1601
+ } catch (error) {
1602
+ send({ type: "failed", message: error instanceof Error ? error.message : String(error) });
1603
+ }
1604
+ }
1605
+ main();
1606
+ // Annotate the CommonJS export names for ESM import in node:
1607
+ 0 && (module.exports = {
1608
+ confinementRootOf
1609
+ });
1610
+ //# sourceMappingURL=pluginWorker.js.map