@opencode-ai/sdk 1.0.134 → 1.0.137

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 (42) hide show
  1. package/dist/client.d.ts +1 -1
  2. package/dist/client.js +7 -6
  3. package/dist/gen/sdk.gen.d.ts +32 -7
  4. package/dist/gen/sdk.gen.js +74 -15
  5. package/dist/gen/types.gen.d.ts +184 -1
  6. package/dist/v2/client.d.ts +7 -0
  7. package/dist/v2/client.js +25 -0
  8. package/dist/v2/gen/client/client.gen.d.ts +2 -0
  9. package/dist/v2/gen/client/client.gen.js +225 -0
  10. package/dist/v2/gen/client/index.d.ts +8 -0
  11. package/dist/v2/gen/client/index.js +6 -0
  12. package/dist/v2/gen/client/types.gen.d.ts +117 -0
  13. package/dist/v2/gen/client/types.gen.js +2 -0
  14. package/dist/v2/gen/client/utils.gen.d.ts +33 -0
  15. package/dist/v2/gen/client/utils.gen.js +226 -0
  16. package/dist/v2/gen/client.gen.d.ts +12 -0
  17. package/dist/v2/gen/client.gen.js +3 -0
  18. package/dist/v2/gen/core/auth.gen.d.ts +18 -0
  19. package/dist/v2/gen/core/auth.gen.js +14 -0
  20. package/dist/v2/gen/core/bodySerializer.gen.d.ts +25 -0
  21. package/dist/v2/gen/core/bodySerializer.gen.js +57 -0
  22. package/dist/v2/gen/core/params.gen.d.ts +43 -0
  23. package/dist/v2/gen/core/params.gen.js +102 -0
  24. package/dist/v2/gen/core/pathSerializer.gen.d.ts +33 -0
  25. package/dist/v2/gen/core/pathSerializer.gen.js +106 -0
  26. package/dist/v2/gen/core/queryKeySerializer.gen.d.ts +18 -0
  27. package/dist/v2/gen/core/queryKeySerializer.gen.js +93 -0
  28. package/dist/v2/gen/core/serverSentEvents.gen.d.ts +71 -0
  29. package/dist/v2/gen/core/serverSentEvents.gen.js +131 -0
  30. package/dist/v2/gen/core/types.gen.d.ts +78 -0
  31. package/dist/v2/gen/core/types.gen.js +2 -0
  32. package/dist/v2/gen/core/utils.gen.d.ts +19 -0
  33. package/dist/v2/gen/core/utils.gen.js +87 -0
  34. package/dist/v2/gen/sdk.gen.d.ts +850 -0
  35. package/dist/v2/gen/sdk.gen.js +1626 -0
  36. package/dist/v2/gen/types.gen.d.ts +3356 -0
  37. package/dist/v2/gen/types.gen.js +2 -0
  38. package/dist/v2/index.d.ts +10 -0
  39. package/dist/v2/index.js +16 -0
  40. package/dist/v2/server.d.ts +23 -0
  41. package/dist/v2/server.js +91 -0
  42. package/package.json +15 -3
@@ -0,0 +1,25 @@
1
+ import type { ArrayStyle, ObjectStyle, SerializerOptions } from "./pathSerializer.gen.js";
2
+ export type QuerySerializer = (query: Record<string, unknown>) => string;
3
+ export type BodySerializer = (body: any) => any;
4
+ type QuerySerializerOptionsObject = {
5
+ allowReserved?: boolean;
6
+ array?: Partial<SerializerOptions<ArrayStyle>>;
7
+ object?: Partial<SerializerOptions<ObjectStyle>>;
8
+ };
9
+ export type QuerySerializerOptions = QuerySerializerOptionsObject & {
10
+ /**
11
+ * Per-parameter serialization overrides. When provided, these settings
12
+ * override the global array/object settings for specific parameter names.
13
+ */
14
+ parameters?: Record<string, QuerySerializerOptionsObject>;
15
+ };
16
+ export declare const formDataBodySerializer: {
17
+ bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => FormData;
18
+ };
19
+ export declare const jsonBodySerializer: {
20
+ bodySerializer: <T>(body: T) => string;
21
+ };
22
+ export declare const urlSearchParamsBodySerializer: {
23
+ bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => string;
24
+ };
25
+ export {};
@@ -0,0 +1,57 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ const serializeFormDataPair = (data, key, value) => {
3
+ if (typeof value === "string" || value instanceof Blob) {
4
+ data.append(key, value);
5
+ }
6
+ else if (value instanceof Date) {
7
+ data.append(key, value.toISOString());
8
+ }
9
+ else {
10
+ data.append(key, JSON.stringify(value));
11
+ }
12
+ };
13
+ const serializeUrlSearchParamsPair = (data, key, value) => {
14
+ if (typeof value === "string") {
15
+ data.append(key, value);
16
+ }
17
+ else {
18
+ data.append(key, JSON.stringify(value));
19
+ }
20
+ };
21
+ export const formDataBodySerializer = {
22
+ bodySerializer: (body) => {
23
+ const data = new FormData();
24
+ Object.entries(body).forEach(([key, value]) => {
25
+ if (value === undefined || value === null) {
26
+ return;
27
+ }
28
+ if (Array.isArray(value)) {
29
+ value.forEach((v) => serializeFormDataPair(data, key, v));
30
+ }
31
+ else {
32
+ serializeFormDataPair(data, key, value);
33
+ }
34
+ });
35
+ return data;
36
+ },
37
+ };
38
+ export const jsonBodySerializer = {
39
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => (typeof value === "bigint" ? value.toString() : value)),
40
+ };
41
+ export const urlSearchParamsBodySerializer = {
42
+ bodySerializer: (body) => {
43
+ const data = new URLSearchParams();
44
+ Object.entries(body).forEach(([key, value]) => {
45
+ if (value === undefined || value === null) {
46
+ return;
47
+ }
48
+ if (Array.isArray(value)) {
49
+ value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
50
+ }
51
+ else {
52
+ serializeUrlSearchParamsPair(data, key, value);
53
+ }
54
+ });
55
+ return data.toString();
56
+ },
57
+ };
@@ -0,0 +1,43 @@
1
+ type Slot = "body" | "headers" | "path" | "query";
2
+ export type Field = {
3
+ in: Exclude<Slot, "body">;
4
+ /**
5
+ * Field name. This is the name we want the user to see and use.
6
+ */
7
+ key: string;
8
+ /**
9
+ * Field mapped name. This is the name we want to use in the request.
10
+ * If omitted, we use the same value as `key`.
11
+ */
12
+ map?: string;
13
+ } | {
14
+ in: Extract<Slot, "body">;
15
+ /**
16
+ * Key isn't required for bodies.
17
+ */
18
+ key?: string;
19
+ map?: string;
20
+ } | {
21
+ /**
22
+ * Field name. This is the name we want the user to see and use.
23
+ */
24
+ key: string;
25
+ /**
26
+ * Field mapped name. This is the name we want to use in the request.
27
+ * If `in` is omitted, `map` aliases `key` to the transport layer.
28
+ */
29
+ map: Slot;
30
+ };
31
+ export interface Fields {
32
+ allowExtra?: Partial<Record<Slot, boolean>>;
33
+ args?: ReadonlyArray<Field>;
34
+ }
35
+ export type FieldsConfig = ReadonlyArray<Field | Fields>;
36
+ interface Params {
37
+ body: unknown;
38
+ headers: Record<string, unknown>;
39
+ path: Record<string, unknown>;
40
+ query: Record<string, unknown>;
41
+ }
42
+ export declare const buildClientParams: (args: ReadonlyArray<unknown>, fields: FieldsConfig) => Params;
43
+ export {};
@@ -0,0 +1,102 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ const extraPrefixesMap = {
3
+ $body_: "body",
4
+ $headers_: "headers",
5
+ $path_: "path",
6
+ $query_: "query",
7
+ };
8
+ const extraPrefixes = Object.entries(extraPrefixesMap);
9
+ const buildKeyMap = (fields, map) => {
10
+ if (!map) {
11
+ map = new Map();
12
+ }
13
+ for (const config of fields) {
14
+ if ("in" in config) {
15
+ if (config.key) {
16
+ map.set(config.key, {
17
+ in: config.in,
18
+ map: config.map,
19
+ });
20
+ }
21
+ }
22
+ else if ("key" in config) {
23
+ map.set(config.key, {
24
+ map: config.map,
25
+ });
26
+ }
27
+ else if (config.args) {
28
+ buildKeyMap(config.args, map);
29
+ }
30
+ }
31
+ return map;
32
+ };
33
+ const stripEmptySlots = (params) => {
34
+ for (const [slot, value] of Object.entries(params)) {
35
+ if (value && typeof value === "object" && !Object.keys(value).length) {
36
+ delete params[slot];
37
+ }
38
+ }
39
+ };
40
+ export const buildClientParams = (args, fields) => {
41
+ const params = {
42
+ body: {},
43
+ headers: {},
44
+ path: {},
45
+ query: {},
46
+ };
47
+ const map = buildKeyMap(fields);
48
+ let config;
49
+ for (const [index, arg] of args.entries()) {
50
+ if (fields[index]) {
51
+ config = fields[index];
52
+ }
53
+ if (!config) {
54
+ continue;
55
+ }
56
+ if ("in" in config) {
57
+ if (config.key) {
58
+ const field = map.get(config.key);
59
+ const name = field.map || config.key;
60
+ if (field.in) {
61
+ ;
62
+ params[field.in][name] = arg;
63
+ }
64
+ }
65
+ else {
66
+ params.body = arg;
67
+ }
68
+ }
69
+ else {
70
+ for (const [key, value] of Object.entries(arg ?? {})) {
71
+ const field = map.get(key);
72
+ if (field) {
73
+ if (field.in) {
74
+ const name = field.map || key;
75
+ params[field.in][name] = value;
76
+ }
77
+ else {
78
+ params[field.map] = value;
79
+ }
80
+ }
81
+ else {
82
+ const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
83
+ if (extra) {
84
+ const [prefix, slot] = extra;
85
+ params[slot][key.slice(prefix.length)] = value;
86
+ }
87
+ else if ("allowExtra" in config && config.allowExtra) {
88
+ for (const [slot, allowed] of Object.entries(config.allowExtra)) {
89
+ if (allowed) {
90
+ ;
91
+ params[slot][key] = value;
92
+ break;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+ }
99
+ }
100
+ stripEmptySlots(params);
101
+ return params;
102
+ };
@@ -0,0 +1,33 @@
1
+ interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {
2
+ }
3
+ interface SerializePrimitiveOptions {
4
+ allowReserved?: boolean;
5
+ name: string;
6
+ }
7
+ export interface SerializerOptions<T> {
8
+ /**
9
+ * @default true
10
+ */
11
+ explode: boolean;
12
+ style: T;
13
+ }
14
+ export type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited";
15
+ export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
16
+ type MatrixStyle = "label" | "matrix" | "simple";
17
+ export type ObjectStyle = "form" | "deepObject";
18
+ type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
19
+ interface SerializePrimitiveParam extends SerializePrimitiveOptions {
20
+ value: string;
21
+ }
22
+ export declare const separatorArrayExplode: (style: ArraySeparatorStyle) => "." | ";" | "," | "&";
23
+ export declare const separatorArrayNoExplode: (style: ArraySeparatorStyle) => "," | "|" | "%20";
24
+ export declare const separatorObjectExplode: (style: ObjectSeparatorStyle) => "." | ";" | "," | "&";
25
+ export declare const serializeArrayParam: ({ allowReserved, explode, name, style, value, }: SerializeOptions<ArraySeparatorStyle> & {
26
+ value: unknown[];
27
+ }) => string;
28
+ export declare const serializePrimitiveParam: ({ allowReserved, name, value }: SerializePrimitiveParam) => string;
29
+ export declare const serializeObjectParam: ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions<ObjectSeparatorStyle> & {
30
+ value: Record<string, unknown> | Date;
31
+ valueOnly?: boolean;
32
+ }) => string;
33
+ export {};
@@ -0,0 +1,106 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export const separatorArrayExplode = (style) => {
3
+ switch (style) {
4
+ case "label":
5
+ return ".";
6
+ case "matrix":
7
+ return ";";
8
+ case "simple":
9
+ return ",";
10
+ default:
11
+ return "&";
12
+ }
13
+ };
14
+ export const separatorArrayNoExplode = (style) => {
15
+ switch (style) {
16
+ case "form":
17
+ return ",";
18
+ case "pipeDelimited":
19
+ return "|";
20
+ case "spaceDelimited":
21
+ return "%20";
22
+ default:
23
+ return ",";
24
+ }
25
+ };
26
+ export const separatorObjectExplode = (style) => {
27
+ switch (style) {
28
+ case "label":
29
+ return ".";
30
+ case "matrix":
31
+ return ";";
32
+ case "simple":
33
+ return ",";
34
+ default:
35
+ return "&";
36
+ }
37
+ };
38
+ export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }) => {
39
+ if (!explode) {
40
+ const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
41
+ switch (style) {
42
+ case "label":
43
+ return `.${joinedValues}`;
44
+ case "matrix":
45
+ return `;${name}=${joinedValues}`;
46
+ case "simple":
47
+ return joinedValues;
48
+ default:
49
+ return `${name}=${joinedValues}`;
50
+ }
51
+ }
52
+ const separator = separatorArrayExplode(style);
53
+ const joinedValues = value
54
+ .map((v) => {
55
+ if (style === "label" || style === "simple") {
56
+ return allowReserved ? v : encodeURIComponent(v);
57
+ }
58
+ return serializePrimitiveParam({
59
+ allowReserved,
60
+ name,
61
+ value: v,
62
+ });
63
+ })
64
+ .join(separator);
65
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
66
+ };
67
+ export const serializePrimitiveParam = ({ allowReserved, name, value }) => {
68
+ if (value === undefined || value === null) {
69
+ return "";
70
+ }
71
+ if (typeof value === "object") {
72
+ throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
73
+ }
74
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
75
+ };
76
+ export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }) => {
77
+ if (value instanceof Date) {
78
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
79
+ }
80
+ if (style !== "deepObject" && !explode) {
81
+ let values = [];
82
+ Object.entries(value).forEach(([key, v]) => {
83
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
84
+ });
85
+ const joinedValues = values.join(",");
86
+ switch (style) {
87
+ case "form":
88
+ return `${name}=${joinedValues}`;
89
+ case "label":
90
+ return `.${joinedValues}`;
91
+ case "matrix":
92
+ return `;${name}=${joinedValues}`;
93
+ default:
94
+ return joinedValues;
95
+ }
96
+ }
97
+ const separator = separatorObjectExplode(style);
98
+ const joinedValues = Object.entries(value)
99
+ .map(([key, v]) => serializePrimitiveParam({
100
+ allowReserved,
101
+ name: style === "deepObject" ? `${name}[${key}]` : key,
102
+ value: v,
103
+ }))
104
+ .join(separator);
105
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
106
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * JSON-friendly union that mirrors what Pinia Colada can hash.
3
+ */
4
+ export type JsonValue = null | string | number | boolean | JsonValue[] | {
5
+ [key: string]: JsonValue;
6
+ };
7
+ /**
8
+ * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
9
+ */
10
+ export declare const queryKeyJsonReplacer: (_key: string, value: unknown) => {} | null | undefined;
11
+ /**
12
+ * Safely stringifies a value and parses it back into a JsonValue.
13
+ */
14
+ export declare const stringifyToJsonValue: (input: unknown) => JsonValue | undefined;
15
+ /**
16
+ * Normalizes any accepted value into a JSON-friendly shape for query keys.
17
+ */
18
+ export declare const serializeQueryKeyValue: (value: unknown) => JsonValue | undefined;
@@ -0,0 +1,93 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ /**
3
+ * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
4
+ */
5
+ export const queryKeyJsonReplacer = (_key, value) => {
6
+ if (value === undefined || typeof value === "function" || typeof value === "symbol") {
7
+ return undefined;
8
+ }
9
+ if (typeof value === "bigint") {
10
+ return value.toString();
11
+ }
12
+ if (value instanceof Date) {
13
+ return value.toISOString();
14
+ }
15
+ return value;
16
+ };
17
+ /**
18
+ * Safely stringifies a value and parses it back into a JsonValue.
19
+ */
20
+ export const stringifyToJsonValue = (input) => {
21
+ try {
22
+ const json = JSON.stringify(input, queryKeyJsonReplacer);
23
+ if (json === undefined) {
24
+ return undefined;
25
+ }
26
+ return JSON.parse(json);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ };
32
+ /**
33
+ * Detects plain objects (including objects with a null prototype).
34
+ */
35
+ const isPlainObject = (value) => {
36
+ if (value === null || typeof value !== "object") {
37
+ return false;
38
+ }
39
+ const prototype = Object.getPrototypeOf(value);
40
+ return prototype === Object.prototype || prototype === null;
41
+ };
42
+ /**
43
+ * Turns URLSearchParams into a sorted JSON object for deterministic keys.
44
+ */
45
+ const serializeSearchParams = (params) => {
46
+ const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
47
+ const result = {};
48
+ for (const [key, value] of entries) {
49
+ const existing = result[key];
50
+ if (existing === undefined) {
51
+ result[key] = value;
52
+ continue;
53
+ }
54
+ if (Array.isArray(existing)) {
55
+ ;
56
+ existing.push(value);
57
+ }
58
+ else {
59
+ result[key] = [existing, value];
60
+ }
61
+ }
62
+ return result;
63
+ };
64
+ /**
65
+ * Normalizes any accepted value into a JSON-friendly shape for query keys.
66
+ */
67
+ export const serializeQueryKeyValue = (value) => {
68
+ if (value === null) {
69
+ return null;
70
+ }
71
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
72
+ return value;
73
+ }
74
+ if (value === undefined || typeof value === "function" || typeof value === "symbol") {
75
+ return undefined;
76
+ }
77
+ if (typeof value === "bigint") {
78
+ return value.toString();
79
+ }
80
+ if (value instanceof Date) {
81
+ return value.toISOString();
82
+ }
83
+ if (Array.isArray(value)) {
84
+ return stringifyToJsonValue(value);
85
+ }
86
+ if (typeof URLSearchParams !== "undefined" && value instanceof URLSearchParams) {
87
+ return serializeSearchParams(value);
88
+ }
89
+ if (isPlainObject(value)) {
90
+ return stringifyToJsonValue(value);
91
+ }
92
+ return undefined;
93
+ };
@@ -0,0 +1,71 @@
1
+ import type { Config } from "./types.gen.js";
2
+ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> & Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
3
+ /**
4
+ * Fetch API implementation. You can use this option to provide a custom
5
+ * fetch instance.
6
+ *
7
+ * @default globalThis.fetch
8
+ */
9
+ fetch?: typeof fetch;
10
+ /**
11
+ * Implementing clients can call request interceptors inside this hook.
12
+ */
13
+ onRequest?: (url: string, init: RequestInit) => Promise<Request>;
14
+ /**
15
+ * Callback invoked when a network or parsing error occurs during streaming.
16
+ *
17
+ * This option applies only if the endpoint returns a stream of events.
18
+ *
19
+ * @param error The error that occurred.
20
+ */
21
+ onSseError?: (error: unknown) => void;
22
+ /**
23
+ * Callback invoked when an event is streamed from the server.
24
+ *
25
+ * This option applies only if the endpoint returns a stream of events.
26
+ *
27
+ * @param event Event streamed from the server.
28
+ * @returns Nothing (void).
29
+ */
30
+ onSseEvent?: (event: StreamEvent<TData>) => void;
31
+ serializedBody?: RequestInit["body"];
32
+ /**
33
+ * Default retry delay in milliseconds.
34
+ *
35
+ * This option applies only if the endpoint returns a stream of events.
36
+ *
37
+ * @default 3000
38
+ */
39
+ sseDefaultRetryDelay?: number;
40
+ /**
41
+ * Maximum number of retry attempts before giving up.
42
+ */
43
+ sseMaxRetryAttempts?: number;
44
+ /**
45
+ * Maximum retry delay in milliseconds.
46
+ *
47
+ * Applies only when exponential backoff is used.
48
+ *
49
+ * This option applies only if the endpoint returns a stream of events.
50
+ *
51
+ * @default 30000
52
+ */
53
+ sseMaxRetryDelay?: number;
54
+ /**
55
+ * Optional sleep function for retry backoff.
56
+ *
57
+ * Defaults to using `setTimeout`.
58
+ */
59
+ sseSleepFn?: (ms: number) => Promise<void>;
60
+ url: string;
61
+ };
62
+ export interface StreamEvent<TData = unknown> {
63
+ data: TData;
64
+ event?: string;
65
+ id?: string;
66
+ retry?: number;
67
+ }
68
+ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
69
+ stream: AsyncGenerator<TData extends Record<string, unknown> ? TData[keyof TData] : TData, TReturn, TNext>;
70
+ };
71
+ export declare const createSseClient: <TData = unknown>({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions) => ServerSentEventsResult<TData>;
@@ -0,0 +1,131 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) => {
3
+ let lastEventId;
4
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
5
+ const createStream = async function* () {
6
+ let retryDelay = sseDefaultRetryDelay ?? 3000;
7
+ let attempt = 0;
8
+ const signal = options.signal ?? new AbortController().signal;
9
+ while (true) {
10
+ if (signal.aborted)
11
+ break;
12
+ attempt++;
13
+ const headers = options.headers instanceof Headers
14
+ ? options.headers
15
+ : new Headers(options.headers);
16
+ if (lastEventId !== undefined) {
17
+ headers.set("Last-Event-ID", lastEventId);
18
+ }
19
+ try {
20
+ const requestInit = {
21
+ redirect: "follow",
22
+ ...options,
23
+ body: options.serializedBody,
24
+ headers,
25
+ signal,
26
+ };
27
+ let request = new Request(url, requestInit);
28
+ if (onRequest) {
29
+ request = await onRequest(url, requestInit);
30
+ }
31
+ // fetch must be assigned here, otherwise it would throw the error:
32
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
33
+ const _fetch = options.fetch ?? globalThis.fetch;
34
+ const response = await _fetch(request);
35
+ if (!response.ok)
36
+ throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
37
+ if (!response.body)
38
+ throw new Error("No body in SSE response");
39
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
40
+ let buffer = "";
41
+ const abortHandler = () => {
42
+ try {
43
+ reader.cancel();
44
+ }
45
+ catch {
46
+ // noop
47
+ }
48
+ };
49
+ signal.addEventListener("abort", abortHandler);
50
+ try {
51
+ while (true) {
52
+ const { done, value } = await reader.read();
53
+ if (done)
54
+ break;
55
+ buffer += value;
56
+ const chunks = buffer.split("\n\n");
57
+ buffer = chunks.pop() ?? "";
58
+ for (const chunk of chunks) {
59
+ const lines = chunk.split("\n");
60
+ const dataLines = [];
61
+ let eventName;
62
+ for (const line of lines) {
63
+ if (line.startsWith("data:")) {
64
+ dataLines.push(line.replace(/^data:\s*/, ""));
65
+ }
66
+ else if (line.startsWith("event:")) {
67
+ eventName = line.replace(/^event:\s*/, "");
68
+ }
69
+ else if (line.startsWith("id:")) {
70
+ lastEventId = line.replace(/^id:\s*/, "");
71
+ }
72
+ else if (line.startsWith("retry:")) {
73
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
74
+ if (!Number.isNaN(parsed)) {
75
+ retryDelay = parsed;
76
+ }
77
+ }
78
+ }
79
+ let data;
80
+ let parsedJson = false;
81
+ if (dataLines.length) {
82
+ const rawData = dataLines.join("\n");
83
+ try {
84
+ data = JSON.parse(rawData);
85
+ parsedJson = true;
86
+ }
87
+ catch {
88
+ data = rawData;
89
+ }
90
+ }
91
+ if (parsedJson) {
92
+ if (responseValidator) {
93
+ await responseValidator(data);
94
+ }
95
+ if (responseTransformer) {
96
+ data = await responseTransformer(data);
97
+ }
98
+ }
99
+ onSseEvent?.({
100
+ data,
101
+ event: eventName,
102
+ id: lastEventId,
103
+ retry: retryDelay,
104
+ });
105
+ if (dataLines.length) {
106
+ yield data;
107
+ }
108
+ }
109
+ }
110
+ }
111
+ finally {
112
+ signal.removeEventListener("abort", abortHandler);
113
+ reader.releaseLock();
114
+ }
115
+ break; // exit loop on normal completion
116
+ }
117
+ catch (error) {
118
+ // connection failed or aborted; retry after delay
119
+ onSseError?.(error);
120
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
121
+ break; // stop after firing error
122
+ }
123
+ // exponential backoff: double retry each attempt, cap at 30s
124
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
125
+ await sleep(backoff);
126
+ }
127
+ }
128
+ };
129
+ const stream = createStream();
130
+ return { stream };
131
+ };