kimaki 0.0.3 → 0.1.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/dist/plugin.js ADDED
@@ -0,0 +1,1414 @@
1
+ // @bun
2
+ // src/plugin-v2.ts
3
+ import { spawn } from "child_process";
4
+
5
+ // node_modules/superjson/dist/double-indexed-kv.js
6
+ class DoubleIndexedKV {
7
+ constructor() {
8
+ this.keyToValue = new Map;
9
+ this.valueToKey = new Map;
10
+ }
11
+ set(key, value) {
12
+ this.keyToValue.set(key, value);
13
+ this.valueToKey.set(value, key);
14
+ }
15
+ getByKey(key) {
16
+ return this.keyToValue.get(key);
17
+ }
18
+ getByValue(value) {
19
+ return this.valueToKey.get(value);
20
+ }
21
+ clear() {
22
+ this.keyToValue.clear();
23
+ this.valueToKey.clear();
24
+ }
25
+ }
26
+
27
+ // node_modules/superjson/dist/registry.js
28
+ class Registry {
29
+ constructor(generateIdentifier) {
30
+ this.generateIdentifier = generateIdentifier;
31
+ this.kv = new DoubleIndexedKV;
32
+ }
33
+ register(value, identifier) {
34
+ if (this.kv.getByValue(value)) {
35
+ return;
36
+ }
37
+ if (!identifier) {
38
+ identifier = this.generateIdentifier(value);
39
+ }
40
+ this.kv.set(identifier, value);
41
+ }
42
+ clear() {
43
+ this.kv.clear();
44
+ }
45
+ getIdentifier(value) {
46
+ return this.kv.getByValue(value);
47
+ }
48
+ getValue(identifier) {
49
+ return this.kv.getByKey(identifier);
50
+ }
51
+ }
52
+
53
+ // node_modules/superjson/dist/class-registry.js
54
+ class ClassRegistry extends Registry {
55
+ constructor() {
56
+ super((c) => c.name);
57
+ this.classToAllowedProps = new Map;
58
+ }
59
+ register(value, options) {
60
+ if (typeof options === "object") {
61
+ if (options.allowProps) {
62
+ this.classToAllowedProps.set(value, options.allowProps);
63
+ }
64
+ super.register(value, options.identifier);
65
+ } else {
66
+ super.register(value, options);
67
+ }
68
+ }
69
+ getAllowedProps(value) {
70
+ return this.classToAllowedProps.get(value);
71
+ }
72
+ }
73
+
74
+ // node_modules/superjson/dist/util.js
75
+ function valuesOfObj(record) {
76
+ if ("values" in Object) {
77
+ return Object.values(record);
78
+ }
79
+ const values = [];
80
+ for (const key in record) {
81
+ if (record.hasOwnProperty(key)) {
82
+ values.push(record[key]);
83
+ }
84
+ }
85
+ return values;
86
+ }
87
+ function find(record, predicate) {
88
+ const values = valuesOfObj(record);
89
+ if ("find" in values) {
90
+ return values.find(predicate);
91
+ }
92
+ const valuesNotNever = values;
93
+ for (let i = 0;i < valuesNotNever.length; i++) {
94
+ const value = valuesNotNever[i];
95
+ if (predicate(value)) {
96
+ return value;
97
+ }
98
+ }
99
+ return;
100
+ }
101
+ function forEach(record, run) {
102
+ Object.entries(record).forEach(([key, value]) => run(value, key));
103
+ }
104
+ function includes(arr, value) {
105
+ return arr.indexOf(value) !== -1;
106
+ }
107
+ function findArr(record, predicate) {
108
+ for (let i = 0;i < record.length; i++) {
109
+ const value = record[i];
110
+ if (predicate(value)) {
111
+ return value;
112
+ }
113
+ }
114
+ return;
115
+ }
116
+
117
+ // node_modules/superjson/dist/custom-transformer-registry.js
118
+ class CustomTransformerRegistry {
119
+ constructor() {
120
+ this.transfomers = {};
121
+ }
122
+ register(transformer) {
123
+ this.transfomers[transformer.name] = transformer;
124
+ }
125
+ findApplicable(v) {
126
+ return find(this.transfomers, (transformer) => transformer.isApplicable(v));
127
+ }
128
+ findByName(name) {
129
+ return this.transfomers[name];
130
+ }
131
+ }
132
+
133
+ // node_modules/superjson/dist/is.js
134
+ var getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
135
+ var isUndefined = (payload) => typeof payload === "undefined";
136
+ var isNull = (payload) => payload === null;
137
+ var isPlainObject = (payload) => {
138
+ if (typeof payload !== "object" || payload === null)
139
+ return false;
140
+ if (payload === Object.prototype)
141
+ return false;
142
+ if (Object.getPrototypeOf(payload) === null)
143
+ return true;
144
+ return Object.getPrototypeOf(payload) === Object.prototype;
145
+ };
146
+ var isEmptyObject = (payload) => isPlainObject(payload) && Object.keys(payload).length === 0;
147
+ var isArray = (payload) => Array.isArray(payload);
148
+ var isString = (payload) => typeof payload === "string";
149
+ var isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
150
+ var isBoolean = (payload) => typeof payload === "boolean";
151
+ var isRegExp = (payload) => payload instanceof RegExp;
152
+ var isMap = (payload) => payload instanceof Map;
153
+ var isSet = (payload) => payload instanceof Set;
154
+ var isSymbol = (payload) => getType(payload) === "Symbol";
155
+ var isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
156
+ var isError = (payload) => payload instanceof Error;
157
+ var isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
158
+ var isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
159
+ var isBigint = (payload) => typeof payload === "bigint";
160
+ var isInfinite = (payload) => payload === Infinity || payload === -Infinity;
161
+ var isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
162
+ var isURL = (payload) => payload instanceof URL;
163
+
164
+ // node_modules/superjson/dist/pathstringifier.js
165
+ var escapeKey = (key) => key.replace(/\./g, "\\.");
166
+ var stringifyPath = (path) => path.map(String).map(escapeKey).join(".");
167
+ var parsePath = (string) => {
168
+ const result = [];
169
+ let segment = "";
170
+ for (let i = 0;i < string.length; i++) {
171
+ let char = string.charAt(i);
172
+ const isEscapedDot = char === "\\" && string.charAt(i + 1) === ".";
173
+ if (isEscapedDot) {
174
+ segment += ".";
175
+ i++;
176
+ continue;
177
+ }
178
+ const isEndOfSegment = char === ".";
179
+ if (isEndOfSegment) {
180
+ result.push(segment);
181
+ segment = "";
182
+ continue;
183
+ }
184
+ segment += char;
185
+ }
186
+ const lastSegment = segment;
187
+ result.push(lastSegment);
188
+ return result;
189
+ };
190
+
191
+ // node_modules/superjson/dist/transformer.js
192
+ function simpleTransformation(isApplicable, annotation, transform, untransform) {
193
+ return {
194
+ isApplicable,
195
+ annotation,
196
+ transform,
197
+ untransform
198
+ };
199
+ }
200
+ var simpleRules = [
201
+ simpleTransformation(isUndefined, "undefined", () => null, () => {
202
+ return;
203
+ }),
204
+ simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
205
+ if (typeof BigInt !== "undefined") {
206
+ return BigInt(v);
207
+ }
208
+ console.error("Please add a BigInt polyfill.");
209
+ return v;
210
+ }),
211
+ simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
212
+ simpleTransformation(isError, "Error", (v, superJson) => {
213
+ const baseError = {
214
+ name: v.name,
215
+ message: v.message
216
+ };
217
+ superJson.allowedErrorProps.forEach((prop) => {
218
+ baseError[prop] = v[prop];
219
+ });
220
+ return baseError;
221
+ }, (v, superJson) => {
222
+ const e = new Error(v.message);
223
+ e.name = v.name;
224
+ e.stack = v.stack;
225
+ superJson.allowedErrorProps.forEach((prop) => {
226
+ e[prop] = v[prop];
227
+ });
228
+ return e;
229
+ }),
230
+ simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
231
+ const body = regex.slice(1, regex.lastIndexOf("/"));
232
+ const flags = regex.slice(regex.lastIndexOf("/") + 1);
233
+ return new RegExp(body, flags);
234
+ }),
235
+ simpleTransformation(isSet, "set", (v) => [...v.values()], (v) => new Set(v)),
236
+ simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
237
+ simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
238
+ if (isNaNValue(v)) {
239
+ return "NaN";
240
+ }
241
+ if (v > 0) {
242
+ return "Infinity";
243
+ } else {
244
+ return "-Infinity";
245
+ }
246
+ }, Number),
247
+ simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
248
+ return "-0";
249
+ }, Number),
250
+ simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
251
+ ];
252
+ function compositeTransformation(isApplicable, annotation, transform, untransform) {
253
+ return {
254
+ isApplicable,
255
+ annotation,
256
+ transform,
257
+ untransform
258
+ };
259
+ }
260
+ var symbolRule = compositeTransformation((s, superJson) => {
261
+ if (isSymbol(s)) {
262
+ const isRegistered = !!superJson.symbolRegistry.getIdentifier(s);
263
+ return isRegistered;
264
+ }
265
+ return false;
266
+ }, (s, superJson) => {
267
+ const identifier = superJson.symbolRegistry.getIdentifier(s);
268
+ return ["symbol", identifier];
269
+ }, (v) => v.description, (_, a, superJson) => {
270
+ const value = superJson.symbolRegistry.getValue(a[1]);
271
+ if (!value) {
272
+ throw new Error("Trying to deserialize unknown symbol");
273
+ }
274
+ return value;
275
+ });
276
+ var constructorToName = [
277
+ Int8Array,
278
+ Uint8Array,
279
+ Int16Array,
280
+ Uint16Array,
281
+ Int32Array,
282
+ Uint32Array,
283
+ Float32Array,
284
+ Float64Array,
285
+ Uint8ClampedArray
286
+ ].reduce((obj, ctor) => {
287
+ obj[ctor.name] = ctor;
288
+ return obj;
289
+ }, {});
290
+ var typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a) => {
291
+ const ctor = constructorToName[a[1]];
292
+ if (!ctor) {
293
+ throw new Error("Trying to deserialize unknown typed array");
294
+ }
295
+ return new ctor(v);
296
+ });
297
+ function isInstanceOfRegisteredClass(potentialClass, superJson) {
298
+ if (potentialClass?.constructor) {
299
+ const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
300
+ return isRegistered;
301
+ }
302
+ return false;
303
+ }
304
+ var classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
305
+ const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
306
+ return ["class", identifier];
307
+ }, (clazz, superJson) => {
308
+ const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
309
+ if (!allowedProps) {
310
+ return { ...clazz };
311
+ }
312
+ const result = {};
313
+ allowedProps.forEach((prop) => {
314
+ result[prop] = clazz[prop];
315
+ });
316
+ return result;
317
+ }, (v, a, superJson) => {
318
+ const clazz = superJson.classRegistry.getValue(a[1]);
319
+ if (!clazz) {
320
+ throw new Error(`Trying to deserialize unknown class '${a[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);
321
+ }
322
+ return Object.assign(Object.create(clazz.prototype), v);
323
+ });
324
+ var customRule = compositeTransformation((value, superJson) => {
325
+ return !!superJson.customTransformerRegistry.findApplicable(value);
326
+ }, (value, superJson) => {
327
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
328
+ return ["custom", transformer.name];
329
+ }, (value, superJson) => {
330
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
331
+ return transformer.serialize(value);
332
+ }, (v, a, superJson) => {
333
+ const transformer = superJson.customTransformerRegistry.findByName(a[1]);
334
+ if (!transformer) {
335
+ throw new Error("Trying to deserialize unknown custom value");
336
+ }
337
+ return transformer.deserialize(v);
338
+ });
339
+ var compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
340
+ var transformValue = (value, superJson) => {
341
+ const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
342
+ if (applicableCompositeRule) {
343
+ return {
344
+ value: applicableCompositeRule.transform(value, superJson),
345
+ type: applicableCompositeRule.annotation(value, superJson)
346
+ };
347
+ }
348
+ const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
349
+ if (applicableSimpleRule) {
350
+ return {
351
+ value: applicableSimpleRule.transform(value, superJson),
352
+ type: applicableSimpleRule.annotation
353
+ };
354
+ }
355
+ return;
356
+ };
357
+ var simpleRulesByAnnotation = {};
358
+ simpleRules.forEach((rule) => {
359
+ simpleRulesByAnnotation[rule.annotation] = rule;
360
+ });
361
+ var untransformValue = (json, type, superJson) => {
362
+ if (isArray(type)) {
363
+ switch (type[0]) {
364
+ case "symbol":
365
+ return symbolRule.untransform(json, type, superJson);
366
+ case "class":
367
+ return classRule.untransform(json, type, superJson);
368
+ case "custom":
369
+ return customRule.untransform(json, type, superJson);
370
+ case "typed-array":
371
+ return typedArrayRule.untransform(json, type, superJson);
372
+ default:
373
+ throw new Error("Unknown transformation: " + type);
374
+ }
375
+ } else {
376
+ const transformation = simpleRulesByAnnotation[type];
377
+ if (!transformation) {
378
+ throw new Error("Unknown transformation: " + type);
379
+ }
380
+ return transformation.untransform(json, superJson);
381
+ }
382
+ };
383
+
384
+ // node_modules/superjson/dist/accessDeep.js
385
+ var getNthKey = (value, n) => {
386
+ if (n > value.size)
387
+ throw new Error("index out of bounds");
388
+ const keys = value.keys();
389
+ while (n > 0) {
390
+ keys.next();
391
+ n--;
392
+ }
393
+ return keys.next().value;
394
+ };
395
+ function validatePath(path) {
396
+ if (includes(path, "__proto__")) {
397
+ throw new Error("__proto__ is not allowed as a property");
398
+ }
399
+ if (includes(path, "prototype")) {
400
+ throw new Error("prototype is not allowed as a property");
401
+ }
402
+ if (includes(path, "constructor")) {
403
+ throw new Error("constructor is not allowed as a property");
404
+ }
405
+ }
406
+ var getDeep = (object, path) => {
407
+ validatePath(path);
408
+ for (let i = 0;i < path.length; i++) {
409
+ const key = path[i];
410
+ if (isSet(object)) {
411
+ object = getNthKey(object, +key);
412
+ } else if (isMap(object)) {
413
+ const row = +key;
414
+ const type = +path[++i] === 0 ? "key" : "value";
415
+ const keyOfRow = getNthKey(object, row);
416
+ switch (type) {
417
+ case "key":
418
+ object = keyOfRow;
419
+ break;
420
+ case "value":
421
+ object = object.get(keyOfRow);
422
+ break;
423
+ }
424
+ } else {
425
+ object = object[key];
426
+ }
427
+ }
428
+ return object;
429
+ };
430
+ var setDeep = (object, path, mapper) => {
431
+ validatePath(path);
432
+ if (path.length === 0) {
433
+ return mapper(object);
434
+ }
435
+ let parent = object;
436
+ for (let i = 0;i < path.length - 1; i++) {
437
+ const key = path[i];
438
+ if (isArray(parent)) {
439
+ const index = +key;
440
+ parent = parent[index];
441
+ } else if (isPlainObject(parent)) {
442
+ parent = parent[key];
443
+ } else if (isSet(parent)) {
444
+ const row = +key;
445
+ parent = getNthKey(parent, row);
446
+ } else if (isMap(parent)) {
447
+ const isEnd = i === path.length - 2;
448
+ if (isEnd) {
449
+ break;
450
+ }
451
+ const row = +key;
452
+ const type = +path[++i] === 0 ? "key" : "value";
453
+ const keyOfRow = getNthKey(parent, row);
454
+ switch (type) {
455
+ case "key":
456
+ parent = keyOfRow;
457
+ break;
458
+ case "value":
459
+ parent = parent.get(keyOfRow);
460
+ break;
461
+ }
462
+ }
463
+ }
464
+ const lastKey = path[path.length - 1];
465
+ if (isArray(parent)) {
466
+ parent[+lastKey] = mapper(parent[+lastKey]);
467
+ } else if (isPlainObject(parent)) {
468
+ parent[lastKey] = mapper(parent[lastKey]);
469
+ }
470
+ if (isSet(parent)) {
471
+ const oldValue = getNthKey(parent, +lastKey);
472
+ const newValue = mapper(oldValue);
473
+ if (oldValue !== newValue) {
474
+ parent.delete(oldValue);
475
+ parent.add(newValue);
476
+ }
477
+ }
478
+ if (isMap(parent)) {
479
+ const row = +path[path.length - 2];
480
+ const keyToRow = getNthKey(parent, row);
481
+ const type = +lastKey === 0 ? "key" : "value";
482
+ switch (type) {
483
+ case "key": {
484
+ const newKey = mapper(keyToRow);
485
+ parent.set(newKey, parent.get(keyToRow));
486
+ if (newKey !== keyToRow) {
487
+ parent.delete(keyToRow);
488
+ }
489
+ break;
490
+ }
491
+ case "value": {
492
+ parent.set(keyToRow, mapper(parent.get(keyToRow)));
493
+ break;
494
+ }
495
+ }
496
+ }
497
+ return object;
498
+ };
499
+
500
+ // node_modules/superjson/dist/plainer.js
501
+ function traverse(tree, walker, origin = []) {
502
+ if (!tree) {
503
+ return;
504
+ }
505
+ if (!isArray(tree)) {
506
+ forEach(tree, (subtree, key) => traverse(subtree, walker, [...origin, ...parsePath(key)]));
507
+ return;
508
+ }
509
+ const [nodeValue, children] = tree;
510
+ if (children) {
511
+ forEach(children, (child, key) => {
512
+ traverse(child, walker, [...origin, ...parsePath(key)]);
513
+ });
514
+ }
515
+ walker(nodeValue, origin);
516
+ }
517
+ function applyValueAnnotations(plain, annotations, superJson) {
518
+ traverse(annotations, (type, path) => {
519
+ plain = setDeep(plain, path, (v) => untransformValue(v, type, superJson));
520
+ });
521
+ return plain;
522
+ }
523
+ function applyReferentialEqualityAnnotations(plain, annotations) {
524
+ function apply(identicalPaths, path) {
525
+ const object = getDeep(plain, parsePath(path));
526
+ identicalPaths.map(parsePath).forEach((identicalObjectPath) => {
527
+ plain = setDeep(plain, identicalObjectPath, () => object);
528
+ });
529
+ }
530
+ if (isArray(annotations)) {
531
+ const [root, other] = annotations;
532
+ root.forEach((identicalPath) => {
533
+ plain = setDeep(plain, parsePath(identicalPath), () => plain);
534
+ });
535
+ if (other) {
536
+ forEach(other, apply);
537
+ }
538
+ } else {
539
+ forEach(annotations, apply);
540
+ }
541
+ return plain;
542
+ }
543
+ var isDeep = (object, superJson) => isPlainObject(object) || isArray(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
544
+ function addIdentity(object, path, identities) {
545
+ const existingSet = identities.get(object);
546
+ if (existingSet) {
547
+ existingSet.push(path);
548
+ } else {
549
+ identities.set(object, [path]);
550
+ }
551
+ }
552
+ function generateReferentialEqualityAnnotations(identitites, dedupe) {
553
+ const result = {};
554
+ let rootEqualityPaths = undefined;
555
+ identitites.forEach((paths) => {
556
+ if (paths.length <= 1) {
557
+ return;
558
+ }
559
+ if (!dedupe) {
560
+ paths = paths.map((path) => path.map(String)).sort((a, b) => a.length - b.length);
561
+ }
562
+ const [representativePath, ...identicalPaths] = paths;
563
+ if (representativePath.length === 0) {
564
+ rootEqualityPaths = identicalPaths.map(stringifyPath);
565
+ } else {
566
+ result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
567
+ }
568
+ });
569
+ if (rootEqualityPaths) {
570
+ if (isEmptyObject(result)) {
571
+ return [rootEqualityPaths];
572
+ } else {
573
+ return [rootEqualityPaths, result];
574
+ }
575
+ } else {
576
+ return isEmptyObject(result) ? undefined : result;
577
+ }
578
+ }
579
+ var walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = new Map) => {
580
+ const primitive = isPrimitive(object);
581
+ if (!primitive) {
582
+ addIdentity(object, path, identities);
583
+ const seen = seenObjects.get(object);
584
+ if (seen) {
585
+ return dedupe ? {
586
+ transformedValue: null
587
+ } : seen;
588
+ }
589
+ }
590
+ if (!isDeep(object, superJson)) {
591
+ const transformed2 = transformValue(object, superJson);
592
+ const result2 = transformed2 ? {
593
+ transformedValue: transformed2.value,
594
+ annotations: [transformed2.type]
595
+ } : {
596
+ transformedValue: object
597
+ };
598
+ if (!primitive) {
599
+ seenObjects.set(object, result2);
600
+ }
601
+ return result2;
602
+ }
603
+ if (includes(objectsInThisPath, object)) {
604
+ return {
605
+ transformedValue: null
606
+ };
607
+ }
608
+ const transformationResult = transformValue(object, superJson);
609
+ const transformed = transformationResult?.value ?? object;
610
+ const transformedValue = isArray(transformed) ? [] : {};
611
+ const innerAnnotations = {};
612
+ forEach(transformed, (value, index) => {
613
+ if (index === "__proto__" || index === "constructor" || index === "prototype") {
614
+ throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
615
+ }
616
+ const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
617
+ transformedValue[index] = recursiveResult.transformedValue;
618
+ if (isArray(recursiveResult.annotations)) {
619
+ innerAnnotations[index] = recursiveResult.annotations;
620
+ } else if (isPlainObject(recursiveResult.annotations)) {
621
+ forEach(recursiveResult.annotations, (tree, key) => {
622
+ innerAnnotations[escapeKey(index) + "." + key] = tree;
623
+ });
624
+ }
625
+ });
626
+ const result = isEmptyObject(innerAnnotations) ? {
627
+ transformedValue,
628
+ annotations: transformationResult ? [transformationResult.type] : undefined
629
+ } : {
630
+ transformedValue,
631
+ annotations: transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
632
+ };
633
+ if (!primitive) {
634
+ seenObjects.set(object, result);
635
+ }
636
+ return result;
637
+ };
638
+
639
+ // node_modules/is-what/dist/index.js
640
+ function getType2(payload) {
641
+ return Object.prototype.toString.call(payload).slice(8, -1);
642
+ }
643
+ function isArray2(payload) {
644
+ return getType2(payload) === "Array";
645
+ }
646
+ function isPlainObject2(payload) {
647
+ if (getType2(payload) !== "Object")
648
+ return false;
649
+ const prototype = Object.getPrototypeOf(payload);
650
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
651
+ }
652
+ function isNull2(payload) {
653
+ return getType2(payload) === "Null";
654
+ }
655
+ function isOneOf(a, b, c, d, e) {
656
+ return (value) => a(value) || b(value) || !!c && c(value) || !!d && d(value) || !!e && e(value);
657
+ }
658
+ function isUndefined2(payload) {
659
+ return getType2(payload) === "Undefined";
660
+ }
661
+ var isNullOrUndefined = isOneOf(isNull2, isUndefined2);
662
+
663
+ // node_modules/copy-anything/dist/index.js
664
+ function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
665
+ const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
666
+ if (propType === "enumerable")
667
+ carry[key] = newVal;
668
+ if (includeNonenumerable && propType === "nonenumerable") {
669
+ Object.defineProperty(carry, key, {
670
+ value: newVal,
671
+ enumerable: false,
672
+ writable: true,
673
+ configurable: true
674
+ });
675
+ }
676
+ }
677
+ function copy(target, options = {}) {
678
+ if (isArray2(target)) {
679
+ return target.map((item) => copy(item, options));
680
+ }
681
+ if (!isPlainObject2(target)) {
682
+ return target;
683
+ }
684
+ const props = Object.getOwnPropertyNames(target);
685
+ const symbols = Object.getOwnPropertySymbols(target);
686
+ return [...props, ...symbols].reduce((carry, key) => {
687
+ if (isArray2(options.props) && !options.props.includes(key)) {
688
+ return carry;
689
+ }
690
+ const val = target[key];
691
+ const newVal = copy(val, options);
692
+ assignProp(carry, key, newVal, target, options.nonenumerable);
693
+ return carry;
694
+ }, {});
695
+ }
696
+
697
+ // node_modules/superjson/dist/index.js
698
+ class SuperJSON {
699
+ constructor({ dedupe = false } = {}) {
700
+ this.classRegistry = new ClassRegistry;
701
+ this.symbolRegistry = new Registry((s) => s.description ?? "");
702
+ this.customTransformerRegistry = new CustomTransformerRegistry;
703
+ this.allowedErrorProps = [];
704
+ this.dedupe = dedupe;
705
+ }
706
+ serialize(object) {
707
+ const identities = new Map;
708
+ const output = walker(object, identities, this, this.dedupe);
709
+ const res = {
710
+ json: output.transformedValue
711
+ };
712
+ if (output.annotations) {
713
+ res.meta = {
714
+ ...res.meta,
715
+ values: output.annotations
716
+ };
717
+ }
718
+ const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
719
+ if (equalityAnnotations) {
720
+ res.meta = {
721
+ ...res.meta,
722
+ referentialEqualities: equalityAnnotations
723
+ };
724
+ }
725
+ return res;
726
+ }
727
+ deserialize(payload) {
728
+ const { json, meta } = payload;
729
+ let result = copy(json);
730
+ if (meta?.values) {
731
+ result = applyValueAnnotations(result, meta.values, this);
732
+ }
733
+ if (meta?.referentialEqualities) {
734
+ result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
735
+ }
736
+ return result;
737
+ }
738
+ stringify(object) {
739
+ return JSON.stringify(this.serialize(object));
740
+ }
741
+ parse(string) {
742
+ return this.deserialize(JSON.parse(string));
743
+ }
744
+ registerClass(v, options) {
745
+ this.classRegistry.register(v, options);
746
+ }
747
+ registerSymbol(v, identifier) {
748
+ this.symbolRegistry.register(v, identifier);
749
+ }
750
+ registerCustom(transformer, name) {
751
+ this.customTransformerRegistry.register({
752
+ name,
753
+ ...transformer
754
+ });
755
+ }
756
+ allowErrorProps(...props) {
757
+ this.allowedErrorProps.push(...props);
758
+ }
759
+ }
760
+ SuperJSON.defaultInstance = new SuperJSON;
761
+ SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
762
+ SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
763
+ SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
764
+ SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
765
+ SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
766
+ SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
767
+ SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
768
+ SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
769
+ var serialize = SuperJSON.serialize;
770
+ var deserialize = SuperJSON.deserialize;
771
+ var stringify = SuperJSON.stringify;
772
+ var parse = SuperJSON.parse;
773
+ var registerClass = SuperJSON.registerClass;
774
+ var registerCustom = SuperJSON.registerCustom;
775
+ var registerSymbol = SuperJSON.registerSymbol;
776
+ var allowErrorProps = SuperJSON.allowErrorProps;
777
+
778
+ // node_modules/eventsource-parser/dist/index.js
779
+ class ParseError extends Error {
780
+ constructor(message, options) {
781
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
782
+ }
783
+ }
784
+ function noop(_arg) {}
785
+ function createParser(callbacks) {
786
+ if (typeof callbacks == "function")
787
+ throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
788
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
789
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
790
+ function feed(newChunk) {
791
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
792
+ for (const line of complete)
793
+ parseLine(line);
794
+ incompleteLine = incomplete, isFirstChunk = false;
795
+ }
796
+ function parseLine(line) {
797
+ if (line === "") {
798
+ dispatchEvent();
799
+ return;
800
+ }
801
+ if (line.startsWith(":")) {
802
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
803
+ return;
804
+ }
805
+ const fieldSeparatorIndex = line.indexOf(":");
806
+ if (fieldSeparatorIndex !== -1) {
807
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
808
+ processField(field, value, line);
809
+ return;
810
+ }
811
+ processField(line, "", line);
812
+ }
813
+ function processField(field, value, line) {
814
+ switch (field) {
815
+ case "event":
816
+ eventType = value;
817
+ break;
818
+ case "data":
819
+ data = `${data}${value}
820
+ `;
821
+ break;
822
+ case "id":
823
+ id = value.includes("\x00") ? undefined : value;
824
+ break;
825
+ case "retry":
826
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
827
+ type: "invalid-retry",
828
+ value,
829
+ line
830
+ }));
831
+ break;
832
+ default:
833
+ onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line }));
834
+ break;
835
+ }
836
+ }
837
+ function dispatchEvent() {
838
+ data.length > 0 && onEvent({
839
+ id,
840
+ event: eventType || undefined,
841
+ data: data.endsWith(`
842
+ `) ? data.slice(0, -1) : data
843
+ }), id = undefined, data = "", eventType = "";
844
+ }
845
+ function reset(options = {}) {
846
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = undefined, data = "", eventType = "", incompleteLine = "";
847
+ }
848
+ return { feed, reset };
849
+ }
850
+ function splitLines(chunk) {
851
+ const lines = [];
852
+ let incompleteLine = "", searchIndex = 0;
853
+ for (;searchIndex < chunk.length; ) {
854
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
855
+ `, searchIndex);
856
+ let lineEnd = -1;
857
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
858
+ incompleteLine = chunk.slice(searchIndex);
859
+ break;
860
+ } else {
861
+ const line = chunk.slice(searchIndex, lineEnd);
862
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
863
+ ` && searchIndex++;
864
+ }
865
+ }
866
+ return [lines, incompleteLine];
867
+ }
868
+
869
+ // node_modules/eventsource-parser/dist/stream.js
870
+ class EventSourceParserStream extends TransformStream {
871
+ constructor({ onError, onRetry, onComment } = {}) {
872
+ let parser;
873
+ super({
874
+ start(controller) {
875
+ parser = createParser({
876
+ onEvent: (event) => {
877
+ controller.enqueue(event);
878
+ },
879
+ onError(error) {
880
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
881
+ },
882
+ onRetry,
883
+ onComment
884
+ });
885
+ },
886
+ transform(chunk) {
887
+ parser.feed(chunk);
888
+ }
889
+ });
890
+ }
891
+ }
892
+
893
+ // node_modules/spiceflow/dist/client/errors.js
894
+ class SpiceflowFetchError extends Error {
895
+ status;
896
+ passedValue;
897
+ value;
898
+ constructor(status, passedValue) {
899
+ let message = String(passedValue?.message || "");
900
+ if (!message) {
901
+ if (typeof passedValue === "object") {
902
+ message = JSON.stringify(passedValue);
903
+ } else {
904
+ message = String(passedValue || "");
905
+ }
906
+ }
907
+ super(message);
908
+ this.status = status;
909
+ this.passedValue = passedValue;
910
+ this.value = passedValue;
911
+ }
912
+ }
913
+
914
+ // node_modules/spiceflow/dist/client/utils.js
915
+ function parseStringifiedValue(value) {
916
+ try {
917
+ return JSON.parse(value);
918
+ } catch (error) {
919
+ return value;
920
+ }
921
+ }
922
+
923
+ // node_modules/spiceflow/dist/client/index.js
924
+ var method = [
925
+ "get",
926
+ "post",
927
+ "put",
928
+ "delete",
929
+ "patch",
930
+ "options",
931
+ "head",
932
+ "connect",
933
+ "subscribe"
934
+ ];
935
+ var isServer = typeof FileList === "undefined";
936
+ var isFile = (v) => {
937
+ if (isServer)
938
+ return v instanceof Blob;
939
+ return v instanceof FileList || v instanceof File;
940
+ };
941
+ var hasFile = (obj) => {
942
+ if (!obj)
943
+ return false;
944
+ for (const key in obj) {
945
+ if (isFile(obj[key]))
946
+ return true;
947
+ if (Array.isArray(obj[key]) && obj[key].find(isFile))
948
+ return true;
949
+ }
950
+ return false;
951
+ };
952
+ var createNewFile = (v) => isServer ? v : new Promise((resolve) => {
953
+ const reader = new FileReader;
954
+ reader.onload = () => {
955
+ const file = new File([reader.result], v.name, {
956
+ lastModified: v.lastModified,
957
+ type: v.type
958
+ });
959
+ resolve(file);
960
+ };
961
+ reader.readAsArrayBuffer(v);
962
+ });
963
+ var processHeaders = (h, path, options = {}, headers = {}) => {
964
+ if (Array.isArray(h)) {
965
+ for (const value of h)
966
+ if (!Array.isArray(value))
967
+ headers = processHeaders(value, path, options, headers);
968
+ else {
969
+ const key = value[0];
970
+ if (typeof key === "string")
971
+ headers[key.toLowerCase()] = value[1];
972
+ else
973
+ for (const [k, value2] of key)
974
+ headers[k.toLowerCase()] = value2;
975
+ }
976
+ return headers;
977
+ }
978
+ if (!h)
979
+ return headers;
980
+ switch (typeof h) {
981
+ case "function":
982
+ if (typeof Headers !== "undefined" && h instanceof Headers)
983
+ return processHeaders(h, path, options, headers);
984
+ const v = h(path, options);
985
+ if (v)
986
+ return processHeaders(v, path, options, headers);
987
+ return headers;
988
+ case "object":
989
+ if (typeof Headers !== "undefined" && h instanceof Headers) {
990
+ h.forEach((value, key) => {
991
+ headers[key.toLowerCase()] = value;
992
+ });
993
+ return headers;
994
+ }
995
+ for (const [key, value] of Object.entries(h))
996
+ headers[key.toLowerCase()] = value;
997
+ return headers;
998
+ default:
999
+ return headers;
1000
+ }
1001
+ };
1002
+
1003
+ class TextDecoderStream extends TransformStream {
1004
+ constructor() {
1005
+ const decoder = new TextDecoder("utf-8", {
1006
+ fatal: true,
1007
+ ignoreBOM: true
1008
+ });
1009
+ super({
1010
+ transform(chunk, controller) {
1011
+ const decoded = decoder.decode(chunk, { stream: true });
1012
+ if (decoded.length > 0) {
1013
+ controller.enqueue(decoded);
1014
+ }
1015
+ },
1016
+ flush(controller) {
1017
+ const output = decoder.decode();
1018
+ if (output.length > 0) {
1019
+ controller.enqueue(output);
1020
+ }
1021
+ }
1022
+ });
1023
+ }
1024
+ }
1025
+ function isAbortError(error) {
1026
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
1027
+ }
1028
+ async function* streamSSEResponse(response, map) {
1029
+ const body = response.body;
1030
+ if (!body)
1031
+ return;
1032
+ const eventStream = response.body.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream);
1033
+ let reader = eventStream.getReader();
1034
+ try {
1035
+ while (true) {
1036
+ const { done, value: event } = await reader.read();
1037
+ if (done)
1038
+ break;
1039
+ if (event?.event === "error") {
1040
+ throw new SpiceflowFetchError(500, superjsonDeserialize(event.data));
1041
+ }
1042
+ if (event) {
1043
+ yield map({ ...event, data: event.data });
1044
+ }
1045
+ }
1046
+ } catch (error) {
1047
+ if (isAbortError(error)) {
1048
+ return;
1049
+ }
1050
+ throw error;
1051
+ }
1052
+ }
1053
+ function tryParsingSSEJson(data) {
1054
+ try {
1055
+ return superjsonDeserialize(JSON.parse(data));
1056
+ } catch (error) {
1057
+ return data;
1058
+ }
1059
+ }
1060
+ var createProxy = (domain, config, paths = [], instance) => {
1061
+ if (config.state && !instance) {
1062
+ throw new Error(`State is only available when using a Spiceflow instance`);
1063
+ }
1064
+ return new Proxy(() => {}, {
1065
+ get(_, param) {
1066
+ if (!paths.length && param === "then" || param === "catch") {
1067
+ return _[param];
1068
+ }
1069
+ return createProxy(domain, config, param === "index" ? paths : [...paths, param], instance);
1070
+ },
1071
+ apply(_, __, [body, options]) {
1072
+ if (!body || options || typeof body === "object" && Object.keys(body).length !== 1 || method.includes(paths.at(-1))) {
1073
+ const methodPaths = [...paths];
1074
+ const method2 = methodPaths.pop();
1075
+ const path = "/" + methodPaths.join("/");
1076
+ let { fetch: fetcher = fetch, headers, onRequest, onResponse } = config;
1077
+ const isGetOrHead = method2 === "get" || method2 === "head" || method2 === "subscribe";
1078
+ headers = processHeaders(headers, path, options);
1079
+ const query = isGetOrHead ? body?.query : options?.query;
1080
+ let q = "";
1081
+ if (query) {
1082
+ const append = (key, value) => {
1083
+ q += (q ? "&" : "?") + `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
1084
+ };
1085
+ for (const [key, value] of Object.entries(query)) {
1086
+ if (Array.isArray(value)) {
1087
+ for (const v of value)
1088
+ append(key, v);
1089
+ continue;
1090
+ }
1091
+ if (typeof value === "object") {
1092
+ append(key, JSON.stringify(value));
1093
+ continue;
1094
+ }
1095
+ append(key, `${value}`);
1096
+ }
1097
+ }
1098
+ return Promise.resolve().then(async () => {
1099
+ let fetchInit = {
1100
+ method: method2?.toUpperCase(),
1101
+ body,
1102
+ headers
1103
+ };
1104
+ fetchInit.headers = {
1105
+ ...headers,
1106
+ ...processHeaders(isGetOrHead ? body?.headers : options?.headers, path, fetchInit)
1107
+ };
1108
+ const fetchOpts = isGetOrHead && typeof body === "object" ? body.fetch : options?.fetch;
1109
+ fetchInit = {
1110
+ ...fetchInit,
1111
+ ...fetchOpts
1112
+ };
1113
+ if (isGetOrHead)
1114
+ delete fetchInit.body;
1115
+ if (onRequest) {
1116
+ if (!Array.isArray(onRequest))
1117
+ onRequest = [onRequest];
1118
+ for (const value of onRequest) {
1119
+ const temp = await value(path, fetchInit);
1120
+ if (typeof temp === "object")
1121
+ fetchInit = {
1122
+ ...fetchInit,
1123
+ ...temp,
1124
+ headers: {
1125
+ ...fetchInit.headers,
1126
+ ...processHeaders(temp.headers, path, fetchInit)
1127
+ }
1128
+ };
1129
+ }
1130
+ }
1131
+ if (isGetOrHead)
1132
+ delete fetchInit.body;
1133
+ if (hasFile(body)) {
1134
+ const formData = new FormData;
1135
+ for (const [key, field] of Object.entries(fetchInit.body)) {
1136
+ if (isServer) {
1137
+ formData.append(key, field);
1138
+ continue;
1139
+ }
1140
+ if (field instanceof File) {
1141
+ formData.append(key, await createNewFile(field));
1142
+ continue;
1143
+ }
1144
+ if (field instanceof FileList) {
1145
+ for (let i = 0;i < field.length; i++)
1146
+ formData.append(key, await createNewFile(field[i]));
1147
+ continue;
1148
+ }
1149
+ if (Array.isArray(field)) {
1150
+ for (let i = 0;i < field.length; i++) {
1151
+ const value = field[i];
1152
+ formData.append(key, value instanceof File ? await createNewFile(value) : value);
1153
+ }
1154
+ continue;
1155
+ }
1156
+ formData.append(key, field);
1157
+ }
1158
+ fetchInit.body = formData;
1159
+ } else if (typeof body === "object") {
1160
+ fetchInit.headers["content-type"] = "application/json";
1161
+ fetchInit.body = JSON.stringify(body);
1162
+ } else if (body !== undefined && body !== null) {
1163
+ fetchInit.headers["content-type"] = "text/plain";
1164
+ }
1165
+ if (isGetOrHead)
1166
+ delete fetchInit.body;
1167
+ fetchInit.headers["x-spiceflow-agent"] = "spiceflow-client";
1168
+ if (onRequest) {
1169
+ if (!Array.isArray(onRequest))
1170
+ onRequest = [onRequest];
1171
+ for (const value of onRequest) {
1172
+ const temp = await value(path, fetchInit);
1173
+ if (typeof temp === "object")
1174
+ fetchInit = {
1175
+ ...fetchInit,
1176
+ ...temp,
1177
+ headers: {
1178
+ ...fetchInit.headers,
1179
+ ...processHeaders(temp.headers, path, fetchInit)
1180
+ }
1181
+ };
1182
+ }
1183
+ }
1184
+ const url = domain + path + q;
1185
+ const response = await (instance?.handle(new Request(url, fetchInit), { state: config.state }) ?? fetcher(url, fetchInit));
1186
+ let data = null;
1187
+ let error = null;
1188
+ if (onResponse) {
1189
+ if (!Array.isArray(onResponse))
1190
+ onResponse = [onResponse];
1191
+ for (const value of onResponse) {
1192
+ const temp = await value(response.clone());
1193
+ }
1194
+ }
1195
+ if (data !== null) {
1196
+ return {
1197
+ data,
1198
+ error,
1199
+ response,
1200
+ status: response.status,
1201
+ headers: response.headers,
1202
+ url
1203
+ };
1204
+ }
1205
+ switch (response.headers.get("Content-Type")?.split(";")[0]) {
1206
+ case "text/event-stream":
1207
+ data = streamSSEResponse(response, (x) => {
1208
+ return tryParsingSSEJson(x.data);
1209
+ });
1210
+ break;
1211
+ case "application/json":
1212
+ data = await response.json();
1213
+ data = superjsonDeserialize(data);
1214
+ break;
1215
+ case "application/octet-stream":
1216
+ data = await response.arrayBuffer();
1217
+ break;
1218
+ case "multipart/form-data":
1219
+ const temp = await response.formData();
1220
+ data = {};
1221
+ temp.forEach((value, key) => {
1222
+ data[key] = value;
1223
+ });
1224
+ break;
1225
+ default:
1226
+ data = await response.text().then(parseStringifiedValue);
1227
+ }
1228
+ if (response.status >= 300 || response.status < 200) {
1229
+ error = new SpiceflowFetchError(response.status, data || "Unknown error");
1230
+ data = null;
1231
+ }
1232
+ return {
1233
+ data,
1234
+ error,
1235
+ response,
1236
+ status: response.status,
1237
+ headers: response.headers,
1238
+ url
1239
+ };
1240
+ });
1241
+ }
1242
+ if (typeof body === "object")
1243
+ return createProxy(domain, config, [...paths, Object.values(body)[0]], instance);
1244
+ return createProxy(domain, config, paths);
1245
+ }
1246
+ });
1247
+ };
1248
+ var createSpiceflowClient = (domain, config) => {
1249
+ if (typeof domain === "string") {
1250
+ let domainStr = String(domain);
1251
+ if (domain.endsWith("/"))
1252
+ domainStr = domain.slice(0, -1);
1253
+ return createProxy(domainStr, config || {});
1254
+ }
1255
+ if (typeof window !== "undefined")
1256
+ console.warn("Spiceflow instance server found on client side, this is not recommended for security reason. Use generic type instead.");
1257
+ return createProxy("http://e.ly", config || {}, [], domain);
1258
+ };
1259
+ function superjsonDeserialize(data) {
1260
+ if (data?.__superjsonMeta) {
1261
+ const { __superjsonMeta, ...rest } = data;
1262
+ return SuperJSON.deserialize({
1263
+ json: rest,
1264
+ meta: __superjsonMeta
1265
+ });
1266
+ }
1267
+ return data;
1268
+ }
1269
+
1270
+ // src/plugin-v2.ts
1271
+ var __dirname = "/Users/morse/Documents/GitHub/kimakivoice/discord/src";
1272
+ var BOT_SERVER_PORT = 5645;
1273
+ var BOT_SERVER_URL = `http://localhost:${BOT_SERVER_PORT}`;
1274
+ async function plugin(context) {
1275
+ const { client } = context;
1276
+ let botProcess = null;
1277
+ let eventStreamAbort = null;
1278
+ async function ensureBotRunning() {
1279
+ try {
1280
+ const response = await fetch(`${BOT_SERVER_URL}/health`);
1281
+ if (response.ok) {
1282
+ console.log("\u2705 Discord bot server already running");
1283
+ return true;
1284
+ }
1285
+ } catch (error) {
1286
+ console.log("\uD83D\uDE80 Starting Discord bot server...");
1287
+ botProcess = spawn("bun", [`${__dirname}/centralBot.ts`], {
1288
+ detached: true,
1289
+ stdio: "ignore"
1290
+ });
1291
+ if (botProcess && typeof botProcess.unref === "function") {
1292
+ botProcess.unref();
1293
+ }
1294
+ for (let i = 0;i < 30; i++) {
1295
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1296
+ try {
1297
+ const response = await fetch(`${BOT_SERVER_URL}/health`);
1298
+ if (response.ok) {
1299
+ console.log("\u2705 Discord bot server started successfully");
1300
+ return true;
1301
+ }
1302
+ } catch (e) {}
1303
+ }
1304
+ console.error("\u274C Failed to start Discord bot server");
1305
+ return false;
1306
+ }
1307
+ }
1308
+ async function connectToBot() {
1309
+ const botClient = createSpiceflowClient(BOT_SERVER_URL);
1310
+ eventStreamAbort = new AbortController;
1311
+ try {
1312
+ const { data: eventStream, error } = await botClient.events.get();
1313
+ if (error) {
1314
+ console.error("Failed to connect to event stream:", error);
1315
+ return;
1316
+ }
1317
+ console.log("\uD83D\uDCE1 Connected to Discord bot server event stream");
1318
+ for await (const event of eventStream) {
1319
+ if (eventStreamAbort?.signal.aborted)
1320
+ break;
1321
+ if (event.type === "connected") {
1322
+ console.log("\uD83D\uDCE1 Event stream connected");
1323
+ } else if (event.type === "opencode" && event.directory === process.cwd()) {
1324
+ handleBotEvent(event.event);
1325
+ }
1326
+ }
1327
+ } catch (error) {
1328
+ console.error("Event stream error:", error);
1329
+ if (!eventStreamAbort?.signal.aborted) {
1330
+ setTimeout(connectToBot, 5000);
1331
+ }
1332
+ }
1333
+ }
1334
+ async function handleBotEvent(event) {
1335
+ console.log(`Received bot event: ${event.type}`);
1336
+ }
1337
+ async function getBotStatus() {
1338
+ const botClient = createSpiceflowClient(BOT_SERVER_URL);
1339
+ const { data, error } = await botClient.status.get();
1340
+ if (error) {
1341
+ console.error("Failed to get bot status:", error);
1342
+ return null;
1343
+ }
1344
+ return data;
1345
+ }
1346
+ async function createSessionForThread(threadId, title) {
1347
+ const botClient = createSpiceflowClient(BOT_SERVER_URL);
1348
+ const { data, error } = await botClient["create-session"].post({
1349
+ threadId,
1350
+ directory: process.cwd(),
1351
+ title
1352
+ });
1353
+ if (error) {
1354
+ console.error("Failed to create session:", error);
1355
+ return null;
1356
+ }
1357
+ if ("sessionId" in data) {
1358
+ console.log(`Created session ${data.sessionId} for thread ${threadId}`);
1359
+ return data;
1360
+ }
1361
+ return null;
1362
+ }
1363
+ async function sendToDiscord(threadId, content) {
1364
+ const botClient = createSpiceflowClient(BOT_SERVER_URL);
1365
+ const { data, error } = await botClient.send.post({
1366
+ threadId,
1367
+ content,
1368
+ directory: process.cwd()
1369
+ });
1370
+ if (error) {
1371
+ console.error("Failed to send to Discord:", error);
1372
+ return null;
1373
+ }
1374
+ if ("messageId" in data) {
1375
+ return data.messageId;
1376
+ }
1377
+ return null;
1378
+ }
1379
+ (async () => {
1380
+ console.log("\uD83D\uDD0C Discord plugin v2 initializing...");
1381
+ console.log(`\uD83D\uDCC1 Working directory: ${process.cwd()}`);
1382
+ const botRunning = await ensureBotRunning();
1383
+ if (!botRunning) {
1384
+ console.error("\u274C Could not start Discord bot server");
1385
+ return;
1386
+ }
1387
+ await connectToBot();
1388
+ const status = await getBotStatus();
1389
+ if (status) {
1390
+ console.log(`\uD83D\uDCCA Bot status: Connected=${status.connected}, Servers=${status.servers.length}`);
1391
+ }
1392
+ try {
1393
+ const eventsResult = await client.event.subscribe();
1394
+ const events = eventsResult.stream;
1395
+ console.log(`\uD83D\uDCE1 Subscribed to OpenCode events for ${process.cwd()}`);
1396
+ for await (const event of events) {
1397
+ if (event.type === "message.updated" || event.type === "message.part.updated") {
1398
+ console.log(`OpenCode event: ${event.type}`);
1399
+ }
1400
+ }
1401
+ } catch (error) {
1402
+ console.error("Failed to subscribe to OpenCode events:", error);
1403
+ }
1404
+ })();
1405
+ process.on("exit", () => {
1406
+ if (eventStreamAbort) {
1407
+ eventStreamAbort.abort();
1408
+ }
1409
+ });
1410
+ return {};
1411
+ }
1412
+ export {
1413
+ plugin as default
1414
+ };