@bagelink/sdk 1.7.101 → 1.7.104
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/bin/index.ts +16 -0
- package/dist/index.cjs +578 -0
- package/dist/index.d.cts +171 -2
- package/dist/index.d.mts +171 -2
- package/dist/index.d.ts +171 -2
- package/dist/index.mjs +574 -1
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/openAPITools/StreamController.ts +372 -0
- package/src/openAPITools/functionGenerator.ts +183 -1
- package/src/openAPITools/index.ts +2 -0
- package/src/openAPITools/streamClient.ts +247 -0
- package/src/openAPITools/streamDetector.ts +44 -0
package/bin/index.ts
CHANGED
|
@@ -23,6 +23,22 @@ export async function loadTypes() {
|
|
|
23
23
|
const apiPath = join(bagelinkDir, 'api.ts')
|
|
24
24
|
await formatAndWriteCode(apiPath, code)
|
|
25
25
|
|
|
26
|
+
// Copy streamClient utilities to generated directory
|
|
27
|
+
const streamClientSource = join(__dirname, '../src/openAPITools/streamClient.ts')
|
|
28
|
+
const streamClientDest = join(bagelinkDir, 'streamClient.ts')
|
|
29
|
+
if (fs.existsSync(streamClientSource)) {
|
|
30
|
+
const streamClientCode = fs.readFileSync(streamClientSource, 'utf-8')
|
|
31
|
+
await formatAndWriteCode(streamClientDest, streamClientCode)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Copy StreamController to generated directory
|
|
35
|
+
const streamControllerSource = join(__dirname, '../src/openAPITools/StreamController.ts')
|
|
36
|
+
const streamControllerDest = join(bagelinkDir, 'StreamController.ts')
|
|
37
|
+
if (fs.existsSync(streamControllerSource)) {
|
|
38
|
+
const streamControllerCode = fs.readFileSync(streamControllerSource, 'utf-8')
|
|
39
|
+
await formatAndWriteCode(streamControllerDest, streamControllerCode)
|
|
40
|
+
}
|
|
41
|
+
|
|
26
42
|
const indexPath = join(bagelinkDir, 'index.ts')
|
|
27
43
|
await formatAndWriteCode(indexPath, `export * from './api'\nexport * from './types.d'`)
|
|
28
44
|
|
package/dist/index.cjs
CHANGED
|
@@ -6,6 +6,26 @@ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'defau
|
|
|
6
6
|
|
|
7
7
|
const axios__default = /*#__PURE__*/_interopDefaultCompat(axios$1);
|
|
8
8
|
|
|
9
|
+
function isSSEStream(operation) {
|
|
10
|
+
const description = operation.description?.toLowerCase() || "";
|
|
11
|
+
const summary = operation.summary?.toLowerCase() || "";
|
|
12
|
+
const hasSSEKeywords = description.includes("sse") || description.includes("server-sent events") || description.includes("event stream") || summary.includes("stream");
|
|
13
|
+
const responses = operation.responses || {};
|
|
14
|
+
const hasEventStreamContentType = Object.values(responses).some((response) => {
|
|
15
|
+
if ("content" in response) {
|
|
16
|
+
return "text/event-stream" in (response.content || {});
|
|
17
|
+
}
|
|
18
|
+
return false;
|
|
19
|
+
});
|
|
20
|
+
return hasSSEKeywords || hasEventStreamContentType;
|
|
21
|
+
}
|
|
22
|
+
function extractSSEEventTypes(operation) {
|
|
23
|
+
const description = operation.description || "";
|
|
24
|
+
const typeMatches = description.matchAll(/type:\s*"([^"]+)"/g);
|
|
25
|
+
const types = Array.from(typeMatches).map((match) => match[1]);
|
|
26
|
+
return types.length > 0 ? types : void 0;
|
|
27
|
+
}
|
|
28
|
+
|
|
9
29
|
function getPath(pathsObject, path) {
|
|
10
30
|
return pathsObject ? pathsObject[path] : void 0;
|
|
11
31
|
}
|
|
@@ -284,6 +304,7 @@ const primitiveTypes = [
|
|
|
284
304
|
];
|
|
285
305
|
const functionsInventory = {};
|
|
286
306
|
const pathOperations = [];
|
|
307
|
+
const streamEventTypes = {};
|
|
287
308
|
function collectTypeForImportStatement(typeName) {
|
|
288
309
|
typeName = typeName.trim().replace("[]", "");
|
|
289
310
|
if (typeName.includes("|")) {
|
|
@@ -447,6 +468,76 @@ function combineAllParams(parameters, requestBodyParam) {
|
|
|
447
468
|
}).join(", ");
|
|
448
469
|
return `{ ${destructuredNames} }: { ${typeDefinition} } = {}`;
|
|
449
470
|
}
|
|
471
|
+
function generateStreamTypeName(path) {
|
|
472
|
+
return `${toPascalCase(
|
|
473
|
+
path.split("/").filter((p) => p && !/\{|\}/.test(p)).join("_")
|
|
474
|
+
)}StreamEvents`;
|
|
475
|
+
}
|
|
476
|
+
function generateStreamFunction(method, path, formattedPath, allParams, requestBodyPayload, eventTypes) {
|
|
477
|
+
if (allParams === "undefined") {
|
|
478
|
+
allParams = "";
|
|
479
|
+
}
|
|
480
|
+
const bodyVar = requestBodyPayload || "{}";
|
|
481
|
+
const baseUrlRef = 'axios.defaults.baseURL || ""';
|
|
482
|
+
const streamTypeName = generateStreamTypeName(path);
|
|
483
|
+
if (eventTypes?.length) {
|
|
484
|
+
streamEventTypes[streamTypeName] = eventTypes;
|
|
485
|
+
}
|
|
486
|
+
const eventTypesComment = eventTypes?.length ? `
|
|
487
|
+
* Event types: ${eventTypes.map((t) => `"${t}"`).join(", ")}` : "";
|
|
488
|
+
const eventTypesExample = eventTypes?.length ? eventTypes.map((t) => `
|
|
489
|
+
* .on('${t}', (data) => console.log(data))`).join("") : "\n * .on('message', (data) => console.log(data))";
|
|
490
|
+
const typeAnnotation = eventTypes?.length ? `StreamController<${streamTypeName}>` : "StreamController";
|
|
491
|
+
if (method === "post") {
|
|
492
|
+
return `{
|
|
493
|
+
/**
|
|
494
|
+
* Stream SSE events from this endpoint (returns StreamController)${eventTypesComment}
|
|
495
|
+
*
|
|
496
|
+
* @example
|
|
497
|
+
* const stream = api.endpoint.stream(params)${eventTypesExample}
|
|
498
|
+
* .on('error', (err) => console.error(err))
|
|
499
|
+
* .on('complete', () => console.log('Done!'))
|
|
500
|
+
*
|
|
501
|
+
* // Close stream when needed
|
|
502
|
+
* stream.close()
|
|
503
|
+
*/
|
|
504
|
+
stream: (${allParams}, options?: SSEStreamOptions): ${typeAnnotation} => {
|
|
505
|
+
const url = \`\${${baseUrlRef}}${formattedPath}\`
|
|
506
|
+
return createSSEStreamPost<${streamTypeName}>(url, ${bodyVar}, options)
|
|
507
|
+
},
|
|
508
|
+
/**
|
|
509
|
+
* Regular POST request (non-streaming)
|
|
510
|
+
*/
|
|
511
|
+
post: async (${allParams}): Promise<AxiosResponse<any>> => {
|
|
512
|
+
return axios.post(${formattedPath}, ${bodyVar})
|
|
513
|
+
}
|
|
514
|
+
}`;
|
|
515
|
+
} else {
|
|
516
|
+
return `{
|
|
517
|
+
/**
|
|
518
|
+
* Stream SSE events from this endpoint (returns StreamController)${eventTypesComment}
|
|
519
|
+
*
|
|
520
|
+
* @example
|
|
521
|
+
* const stream = api.endpoint.stream(params)${eventTypesExample}
|
|
522
|
+
* .on('error', (err) => console.error(err))
|
|
523
|
+
* .on('complete', () => console.log('Done!'))
|
|
524
|
+
*
|
|
525
|
+
* // Close stream when needed
|
|
526
|
+
* stream.close()
|
|
527
|
+
*/
|
|
528
|
+
stream: (${allParams}, options?: SSEStreamOptions): ${typeAnnotation} => {
|
|
529
|
+
const url = \`\${${baseUrlRef}}${formattedPath}\`
|
|
530
|
+
return createSSEStream<${streamTypeName}>(url, options)
|
|
531
|
+
},
|
|
532
|
+
/**
|
|
533
|
+
* Regular GET request (non-streaming)
|
|
534
|
+
*/
|
|
535
|
+
get: async (${allParams}): Promise<AxiosResponse<any>> => {
|
|
536
|
+
return axios.get(${formattedPath})
|
|
537
|
+
}
|
|
538
|
+
}`;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
450
541
|
function generateAxiosFunction(method, formattedPath, allParams, responseTypeStr, parameters, requestBodyPayload) {
|
|
451
542
|
if (allParams === "undefined") {
|
|
452
543
|
allParams = "";
|
|
@@ -504,6 +595,7 @@ function generateFunctionForOperation(method, path, operation) {
|
|
|
504
595
|
if (!operation) {
|
|
505
596
|
return "";
|
|
506
597
|
}
|
|
598
|
+
const isStream = isSSEStream(operation);
|
|
507
599
|
const methodLower = method.toLowerCase();
|
|
508
600
|
if (["get", "delete"].includes(methodLower) && operation.requestBody) {
|
|
509
601
|
const requestBodyDeref = dereference(operation.requestBody);
|
|
@@ -532,6 +624,17 @@ function generateFunctionForOperation(method, path, operation) {
|
|
|
532
624
|
const responseType = generateResponseType(operation.responses);
|
|
533
625
|
const responseTypeStr = responseType ? `: Promise<AxiosResponse<${responseType}>>` : "";
|
|
534
626
|
const functionComment = buildJSDocComment(operation, method, path);
|
|
627
|
+
if (isStream) {
|
|
628
|
+
const eventTypes = extractSSEEventTypes(operation);
|
|
629
|
+
return functionComment + generateStreamFunction(
|
|
630
|
+
method,
|
|
631
|
+
path,
|
|
632
|
+
formatPathWithParams(path),
|
|
633
|
+
allParams,
|
|
634
|
+
requestBodyPayload,
|
|
635
|
+
eventTypes
|
|
636
|
+
);
|
|
637
|
+
}
|
|
535
638
|
return functionComment + generateAxiosFunction(
|
|
536
639
|
method,
|
|
537
640
|
formatPathWithParams(path),
|
|
@@ -627,10 +730,38 @@ export const ${parent} = ${JSON.stringify(object, void 0, 2)};
|
|
|
627
730
|
});
|
|
628
731
|
return fileTemplate(tsString, allTypes, baseUrl);
|
|
629
732
|
}
|
|
733
|
+
function generateStreamEventTypeDefinitions() {
|
|
734
|
+
if (Object.keys(streamEventTypes).length === 0) {
|
|
735
|
+
return "";
|
|
736
|
+
}
|
|
737
|
+
let typeDefs = "\n// ============================================================================\n";
|
|
738
|
+
typeDefs += "// Stream Event Type Definitions (Fully Typed!)\n";
|
|
739
|
+
typeDefs += "// ============================================================================\n\n";
|
|
740
|
+
for (const [typeName, events] of Object.entries(streamEventTypes)) {
|
|
741
|
+
typeDefs += `/**
|
|
742
|
+
* Event types for ${typeName.replace("StreamEvents", "")} stream
|
|
743
|
+
`;
|
|
744
|
+
typeDefs += ` * Events: ${events.map((e) => `"${e}"`).join(", ")}
|
|
745
|
+
*/
|
|
746
|
+
`;
|
|
747
|
+
typeDefs += `export interface ${typeName} {
|
|
748
|
+
`;
|
|
749
|
+
for (const event of events) {
|
|
750
|
+
typeDefs += ` /** ${event} event data */
|
|
751
|
+
`;
|
|
752
|
+
typeDefs += ` ${event}: any // TODO: Define specific type from OpenAPI schema
|
|
753
|
+
`;
|
|
754
|
+
}
|
|
755
|
+
typeDefs += "}\n\n";
|
|
756
|
+
}
|
|
757
|
+
return typeDefs;
|
|
758
|
+
}
|
|
630
759
|
function fileTemplate(tsString, typeForImport, baseURL) {
|
|
760
|
+
const streamTypeDefs = generateStreamEventTypeDefinitions();
|
|
631
761
|
const templateCode = `import ax from 'axios';
|
|
632
762
|
import type { AxiosResponse } from 'axios';
|
|
633
763
|
import type { ${typeForImport.join(", ")} } from './types.d';
|
|
764
|
+
import { createSSEStream, createSSEStreamPost, StreamController, type SSEStreamOptions, type SSEEvent } from './streamClient';
|
|
634
765
|
|
|
635
766
|
/**
|
|
636
767
|
* Options for file upload operations
|
|
@@ -644,6 +775,24 @@ export interface UploadOptions {
|
|
|
644
775
|
tags?: string[]
|
|
645
776
|
}
|
|
646
777
|
|
|
778
|
+
/**
|
|
779
|
+
* Export SSE stream utilities for direct use
|
|
780
|
+
*
|
|
781
|
+
* @example Chainable event handlers
|
|
782
|
+
* const stream = createSSEStream(url)
|
|
783
|
+
* .on('token', (data) => console.log(data))
|
|
784
|
+
* .on('done', () => console.log('Complete!'))
|
|
785
|
+
*
|
|
786
|
+
* @example Async iteration
|
|
787
|
+
* for await (const event of createSSEStream(url)) {
|
|
788
|
+
* console.log(event.type, event.data)
|
|
789
|
+
* }
|
|
790
|
+
*
|
|
791
|
+
* @example Promise-based
|
|
792
|
+
* const result = await createSSEStream(url).toPromise()
|
|
793
|
+
*/
|
|
794
|
+
export { createSSEStream, createSSEStreamPost, StreamController, type SSEStreamOptions, type SSEEvent } from './streamClient';
|
|
795
|
+
${streamTypeDefs}
|
|
647
796
|
/**
|
|
648
797
|
* Configured axios instance for API requests
|
|
649
798
|
* @example
|
|
@@ -697,6 +846,430 @@ function generateTypes(schemas) {
|
|
|
697
846
|
}).join("\n");
|
|
698
847
|
}
|
|
699
848
|
|
|
849
|
+
class StreamController {
|
|
850
|
+
constructor(streamFn) {
|
|
851
|
+
this.streamFn = streamFn;
|
|
852
|
+
this.abortController = new AbortController();
|
|
853
|
+
this.start();
|
|
854
|
+
}
|
|
855
|
+
handlers = /* @__PURE__ */ new Map();
|
|
856
|
+
errorHandlers = /* @__PURE__ */ new Set();
|
|
857
|
+
completeHandlers = /* @__PURE__ */ new Set();
|
|
858
|
+
abortController;
|
|
859
|
+
_closed = false;
|
|
860
|
+
_promise = null;
|
|
861
|
+
_resolvePromise = null;
|
|
862
|
+
_rejectPromise = null;
|
|
863
|
+
start() {
|
|
864
|
+
const cleanup = this.streamFn(
|
|
865
|
+
(event) => {
|
|
866
|
+
this.emit(event.type, event.data);
|
|
867
|
+
},
|
|
868
|
+
(error) => {
|
|
869
|
+
this.emitError(error);
|
|
870
|
+
},
|
|
871
|
+
() => {
|
|
872
|
+
this.emitComplete();
|
|
873
|
+
}
|
|
874
|
+
);
|
|
875
|
+
this.abortController.signal.addEventListener("abort", () => {
|
|
876
|
+
cleanup();
|
|
877
|
+
this._closed = true;
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Register an event handler (fully typed!)
|
|
882
|
+
* @param event - Event type to listen for
|
|
883
|
+
* @param handler - Handler function (data type inferred from event)
|
|
884
|
+
* @returns this (for chaining)
|
|
885
|
+
*/
|
|
886
|
+
on(event, handler) {
|
|
887
|
+
if (event === "error") {
|
|
888
|
+
this.errorHandlers.add(handler);
|
|
889
|
+
} else if (event === "complete") {
|
|
890
|
+
this.completeHandlers.add(handler);
|
|
891
|
+
} else {
|
|
892
|
+
if (!this.handlers.has(event)) {
|
|
893
|
+
this.handlers.set(event, /* @__PURE__ */ new Set());
|
|
894
|
+
}
|
|
895
|
+
this.handlers.get(event).add(handler);
|
|
896
|
+
}
|
|
897
|
+
return this;
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* Register a one-time event handler (fully typed!)
|
|
901
|
+
* @param event - Event type to listen for
|
|
902
|
+
* @param handler - Handler function (called once then removed, data type inferred from event)
|
|
903
|
+
* @returns this (for chaining)
|
|
904
|
+
*/
|
|
905
|
+
once(event, handler) {
|
|
906
|
+
const wrappedHandler = (data) => {
|
|
907
|
+
handler(data);
|
|
908
|
+
this.off(event, wrappedHandler);
|
|
909
|
+
};
|
|
910
|
+
return this.on(event, wrappedHandler);
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Remove an event handler (fully typed!)
|
|
914
|
+
* @param event - Event type
|
|
915
|
+
* @param handler - Handler to remove
|
|
916
|
+
* @returns this (for chaining)
|
|
917
|
+
*/
|
|
918
|
+
off(event, handler) {
|
|
919
|
+
if (event === "error") {
|
|
920
|
+
this.errorHandlers.delete(handler);
|
|
921
|
+
} else if (event === "complete") {
|
|
922
|
+
this.completeHandlers.delete(handler);
|
|
923
|
+
} else {
|
|
924
|
+
this.handlers.get(event)?.delete(handler);
|
|
925
|
+
}
|
|
926
|
+
return this;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Remove all handlers for an event (or all events if no event specified)
|
|
930
|
+
*/
|
|
931
|
+
removeAllListeners(event) {
|
|
932
|
+
if (event === void 0) {
|
|
933
|
+
this.handlers.clear();
|
|
934
|
+
this.errorHandlers.clear();
|
|
935
|
+
this.completeHandlers.clear();
|
|
936
|
+
} else if (event === "error") {
|
|
937
|
+
this.errorHandlers.clear();
|
|
938
|
+
} else if (event === "complete") {
|
|
939
|
+
this.completeHandlers.clear();
|
|
940
|
+
} else {
|
|
941
|
+
this.handlers.delete(event);
|
|
942
|
+
}
|
|
943
|
+
return this;
|
|
944
|
+
}
|
|
945
|
+
emit(event, data) {
|
|
946
|
+
const handlers = this.handlers.get(event);
|
|
947
|
+
if (handlers) {
|
|
948
|
+
handlers.forEach((handler) => {
|
|
949
|
+
try {
|
|
950
|
+
handler(data);
|
|
951
|
+
} catch (error) {
|
|
952
|
+
console.error(`Error in handler for event "${event}":`, error);
|
|
953
|
+
}
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
if (event === "done" && this._resolvePromise) {
|
|
957
|
+
this._resolvePromise(data);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
emitError(error) {
|
|
961
|
+
this.errorHandlers.forEach((handler) => {
|
|
962
|
+
try {
|
|
963
|
+
handler(error);
|
|
964
|
+
} catch (err) {
|
|
965
|
+
console.error("Error in error handler:", err);
|
|
966
|
+
}
|
|
967
|
+
});
|
|
968
|
+
if (this._rejectPromise) {
|
|
969
|
+
this._rejectPromise(error);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
emitComplete() {
|
|
973
|
+
this.completeHandlers.forEach((handler) => {
|
|
974
|
+
try {
|
|
975
|
+
handler();
|
|
976
|
+
} catch (error) {
|
|
977
|
+
console.error("Error in complete handler:", error);
|
|
978
|
+
}
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Close the stream
|
|
983
|
+
*/
|
|
984
|
+
close() {
|
|
985
|
+
if (!this._closed) {
|
|
986
|
+
this.abortController.abort();
|
|
987
|
+
this._closed = true;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Check if stream is closed
|
|
992
|
+
*/
|
|
993
|
+
get closed() {
|
|
994
|
+
return this._closed;
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Convert stream to a Promise that resolves when 'done' event fires
|
|
998
|
+
* @returns Promise that resolves with the 'done' event data
|
|
999
|
+
*/
|
|
1000
|
+
toPromise() {
|
|
1001
|
+
if (!this._promise) {
|
|
1002
|
+
this._promise = new Promise((resolve, reject) => {
|
|
1003
|
+
this._resolvePromise = resolve;
|
|
1004
|
+
this._rejectPromise = reject;
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
return this._promise;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Make the stream async iterable
|
|
1011
|
+
* Usage: for await (const event of stream) { ... }
|
|
1012
|
+
*/
|
|
1013
|
+
async *[Symbol.asyncIterator]() {
|
|
1014
|
+
const events = [];
|
|
1015
|
+
let resolveNext = null;
|
|
1016
|
+
let done = false;
|
|
1017
|
+
const eventHandler = (type) => (data) => {
|
|
1018
|
+
const event = { type, data };
|
|
1019
|
+
if (resolveNext) {
|
|
1020
|
+
resolveNext(event);
|
|
1021
|
+
resolveNext = null;
|
|
1022
|
+
} else {
|
|
1023
|
+
events.push(event);
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
const originalEmit = this.emit.bind(this);
|
|
1027
|
+
const capturedEvents = [];
|
|
1028
|
+
this.emit = (event, data) => {
|
|
1029
|
+
if (!capturedEvents.includes(event)) {
|
|
1030
|
+
capturedEvents.push(event);
|
|
1031
|
+
this.on(event, eventHandler(event));
|
|
1032
|
+
}
|
|
1033
|
+
originalEmit(event, data);
|
|
1034
|
+
};
|
|
1035
|
+
this.on("complete", () => {
|
|
1036
|
+
done = true;
|
|
1037
|
+
if (resolveNext) {
|
|
1038
|
+
resolveNext(null);
|
|
1039
|
+
resolveNext = null;
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
try {
|
|
1043
|
+
while (!done) {
|
|
1044
|
+
if (events.length > 0) {
|
|
1045
|
+
const event = events.shift();
|
|
1046
|
+
if (event) yield event;
|
|
1047
|
+
} else {
|
|
1048
|
+
const event = await new Promise((resolve) => {
|
|
1049
|
+
resolveNext = resolve;
|
|
1050
|
+
});
|
|
1051
|
+
if (event === null) break;
|
|
1052
|
+
yield event;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
} finally {
|
|
1056
|
+
this.close();
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Collect all events into an array until stream completes
|
|
1061
|
+
* @returns Promise<SSEEvent[]>
|
|
1062
|
+
*/
|
|
1063
|
+
async toArray() {
|
|
1064
|
+
const events = [];
|
|
1065
|
+
for await (const event of this) {
|
|
1066
|
+
events.push(event);
|
|
1067
|
+
}
|
|
1068
|
+
return events;
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Pipe stream events through a transform function
|
|
1072
|
+
*/
|
|
1073
|
+
map(transform) {
|
|
1074
|
+
const mappedController = new StreamController(
|
|
1075
|
+
(onEvent, onError, onComplete) => {
|
|
1076
|
+
this.on("error", onError);
|
|
1077
|
+
this.on("complete", onComplete);
|
|
1078
|
+
this.handlers.forEach((_, eventType) => {
|
|
1079
|
+
this.on(eventType, (data) => {
|
|
1080
|
+
try {
|
|
1081
|
+
const transformed = transform({ type: eventType, data });
|
|
1082
|
+
onEvent({ type: eventType, data: transformed, raw: void 0 });
|
|
1083
|
+
} catch (error) {
|
|
1084
|
+
onError(error);
|
|
1085
|
+
}
|
|
1086
|
+
});
|
|
1087
|
+
});
|
|
1088
|
+
return () => {
|
|
1089
|
+
this.close();
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
);
|
|
1093
|
+
return mappedController;
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Filter events based on a predicate
|
|
1097
|
+
*/
|
|
1098
|
+
filter(predicate) {
|
|
1099
|
+
const filteredController = new StreamController(
|
|
1100
|
+
(onEvent, onError, onComplete) => {
|
|
1101
|
+
this.on("error", onError);
|
|
1102
|
+
this.on("complete", onComplete);
|
|
1103
|
+
this.handlers.forEach((_, eventType) => {
|
|
1104
|
+
this.on(eventType, (data) => {
|
|
1105
|
+
const event = { type: eventType, data };
|
|
1106
|
+
if (predicate(event)) {
|
|
1107
|
+
onEvent(event);
|
|
1108
|
+
}
|
|
1109
|
+
});
|
|
1110
|
+
});
|
|
1111
|
+
return () => {
|
|
1112
|
+
this.close();
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
);
|
|
1116
|
+
return filteredController;
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
function createSSEStream(url, options = {}) {
|
|
1121
|
+
const { headers = {}, withCredentials = true } = options;
|
|
1122
|
+
return new StreamController((onEvent, onError, onComplete) => {
|
|
1123
|
+
const controller = new AbortController();
|
|
1124
|
+
const { signal } = controller;
|
|
1125
|
+
fetch(url, {
|
|
1126
|
+
method: "GET",
|
|
1127
|
+
headers: {
|
|
1128
|
+
Accept: "text/event-stream",
|
|
1129
|
+
...headers
|
|
1130
|
+
},
|
|
1131
|
+
credentials: withCredentials ? "include" : "same-origin",
|
|
1132
|
+
signal
|
|
1133
|
+
}).then(async (response) => {
|
|
1134
|
+
if (!response.ok) {
|
|
1135
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1136
|
+
}
|
|
1137
|
+
if (!response.body) {
|
|
1138
|
+
throw new Error("Response body is null");
|
|
1139
|
+
}
|
|
1140
|
+
const reader = response.body.getReader();
|
|
1141
|
+
const decoder = new TextDecoder();
|
|
1142
|
+
let buffer = "";
|
|
1143
|
+
try {
|
|
1144
|
+
while (true) {
|
|
1145
|
+
const { done, value } = await reader.read();
|
|
1146
|
+
if (done) {
|
|
1147
|
+
onComplete();
|
|
1148
|
+
break;
|
|
1149
|
+
}
|
|
1150
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1151
|
+
const lines = buffer.split("\n");
|
|
1152
|
+
buffer = lines.pop() || "";
|
|
1153
|
+
let eventType = "";
|
|
1154
|
+
let eventData = "";
|
|
1155
|
+
for (const line of lines) {
|
|
1156
|
+
if (line.startsWith("event:")) {
|
|
1157
|
+
eventType = line.slice(6).trim();
|
|
1158
|
+
} else if (line.startsWith("data:")) {
|
|
1159
|
+
eventData = line.slice(5).trim();
|
|
1160
|
+
} else if (line === "" && eventData) {
|
|
1161
|
+
try {
|
|
1162
|
+
const parsedData = JSON.parse(eventData);
|
|
1163
|
+
onEvent({
|
|
1164
|
+
type: eventType || "message",
|
|
1165
|
+
data: parsedData,
|
|
1166
|
+
raw: eventData
|
|
1167
|
+
});
|
|
1168
|
+
} catch {
|
|
1169
|
+
onEvent({
|
|
1170
|
+
type: eventType || "message",
|
|
1171
|
+
data: eventData,
|
|
1172
|
+
raw: eventData
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
eventType = "";
|
|
1176
|
+
eventData = "";
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
} catch (error) {
|
|
1181
|
+
if (error instanceof Error && error.name !== "AbortError") {
|
|
1182
|
+
onError(error);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}).catch((error) => {
|
|
1186
|
+
if (error.name !== "AbortError") {
|
|
1187
|
+
onError(error);
|
|
1188
|
+
}
|
|
1189
|
+
});
|
|
1190
|
+
return () => {
|
|
1191
|
+
controller.abort();
|
|
1192
|
+
};
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
function createSSEStreamPost(url, body, options = {}) {
|
|
1196
|
+
const { headers = {}, withCredentials = true } = options;
|
|
1197
|
+
return new StreamController((onEvent, onError, onComplete) => {
|
|
1198
|
+
const controller = new AbortController();
|
|
1199
|
+
const { signal } = controller;
|
|
1200
|
+
fetch(url, {
|
|
1201
|
+
method: "POST",
|
|
1202
|
+
headers: {
|
|
1203
|
+
"Accept": "text/event-stream",
|
|
1204
|
+
"Content-Type": "application/json",
|
|
1205
|
+
...headers
|
|
1206
|
+
},
|
|
1207
|
+
credentials: withCredentials ? "include" : "same-origin",
|
|
1208
|
+
body: JSON.stringify(body),
|
|
1209
|
+
signal
|
|
1210
|
+
}).then(async (response) => {
|
|
1211
|
+
if (!response.ok) {
|
|
1212
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1213
|
+
}
|
|
1214
|
+
if (!response.body) {
|
|
1215
|
+
throw new Error("Response body is null");
|
|
1216
|
+
}
|
|
1217
|
+
const reader = response.body.getReader();
|
|
1218
|
+
const decoder = new TextDecoder();
|
|
1219
|
+
let buffer = "";
|
|
1220
|
+
try {
|
|
1221
|
+
while (true) {
|
|
1222
|
+
const { done, value } = await reader.read();
|
|
1223
|
+
if (done) {
|
|
1224
|
+
onComplete();
|
|
1225
|
+
break;
|
|
1226
|
+
}
|
|
1227
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1228
|
+
const lines = buffer.split("\n");
|
|
1229
|
+
buffer = lines.pop() || "";
|
|
1230
|
+
let eventType = "";
|
|
1231
|
+
let eventData = "";
|
|
1232
|
+
for (const line of lines) {
|
|
1233
|
+
if (line.startsWith("event:")) {
|
|
1234
|
+
eventType = line.slice(6).trim();
|
|
1235
|
+
} else if (line.startsWith("data:")) {
|
|
1236
|
+
eventData = line.slice(5).trim();
|
|
1237
|
+
} else if (line === "" && eventData) {
|
|
1238
|
+
try {
|
|
1239
|
+
const parsedData = JSON.parse(eventData);
|
|
1240
|
+
onEvent({
|
|
1241
|
+
type: eventType || "message",
|
|
1242
|
+
data: parsedData,
|
|
1243
|
+
raw: eventData
|
|
1244
|
+
});
|
|
1245
|
+
} catch {
|
|
1246
|
+
onEvent({
|
|
1247
|
+
type: eventType || "message",
|
|
1248
|
+
data: eventData,
|
|
1249
|
+
raw: eventData
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
eventType = "";
|
|
1253
|
+
eventData = "";
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
} catch (error) {
|
|
1258
|
+
if (error instanceof Error && error.name !== "AbortError") {
|
|
1259
|
+
onError(error);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
}).catch((error) => {
|
|
1263
|
+
if (error.name !== "AbortError") {
|
|
1264
|
+
onError(error);
|
|
1265
|
+
}
|
|
1266
|
+
});
|
|
1267
|
+
return () => {
|
|
1268
|
+
controller.abort();
|
|
1269
|
+
};
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
|
|
700
1273
|
const basicAuthHeader = { Authorization: "Basic YmFnZWxfdXNlcm5hbWU6Tm90U2VjdXJlQGJhZ2Vs" };
|
|
701
1274
|
const index = async (openApiUrl, baseUrl) => {
|
|
702
1275
|
try {
|
|
@@ -1007,9 +1580,14 @@ class Bagel {
|
|
|
1007
1580
|
}
|
|
1008
1581
|
|
|
1009
1582
|
exports.Bagel = Bagel;
|
|
1583
|
+
exports.StreamController = StreamController;
|
|
1584
|
+
exports.createSSEStream = createSSEStream;
|
|
1585
|
+
exports.createSSEStreamPost = createSSEStreamPost;
|
|
1010
1586
|
exports.dereference = dereference;
|
|
1587
|
+
exports.extractSSEEventTypes = extractSSEEventTypes;
|
|
1011
1588
|
exports.formatAPIErrorMessage = formatAPIErrorMessage;
|
|
1012
1589
|
exports.getPath = getPath;
|
|
1013
1590
|
exports.isReferenceObject = isReferenceObject;
|
|
1591
|
+
exports.isSSEStream = isSSEStream;
|
|
1014
1592
|
exports.isSchemaObject = isSchemaObject;
|
|
1015
1593
|
exports.openAPI = index;
|