openai 4.7.1 → 4.9.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/CHANGELOG.md +16 -0
- package/README.md +4 -0
- package/_shims/MultipartBody.d.ts +9 -0
- package/_shims/MultipartBody.d.ts.map +1 -0
- package/_shims/MultipartBody.js +16 -0
- package/_shims/MultipartBody.js.map +1 -0
- package/_shims/MultipartBody.mjs +12 -0
- package/_shims/MultipartBody.mjs.map +1 -0
- package/_shims/README.md +46 -0
- package/{src/_shims/ReadableStream-node.ts → _shims/auto/runtime-bun.d.ts} +2 -3
- package/_shims/auto/runtime-bun.d.ts.map +1 -0
- package/_shims/auto/runtime-bun.js +21 -0
- package/_shims/auto/runtime-bun.js.map +1 -0
- package/_shims/auto/runtime-bun.mjs +2 -0
- package/_shims/auto/runtime-bun.mjs.map +1 -0
- package/_shims/auto/runtime-node.d.ts +5 -0
- package/_shims/auto/runtime-node.d.ts.map +1 -0
- package/_shims/auto/runtime-node.js +21 -0
- package/_shims/auto/runtime-node.js.map +1 -0
- package/_shims/auto/runtime-node.mjs +2 -0
- package/_shims/auto/runtime-node.mjs.map +1 -0
- package/_shims/auto/runtime.d.ts +5 -0
- package/_shims/auto/runtime.d.ts.map +1 -0
- package/_shims/auto/runtime.js +21 -0
- package/_shims/auto/runtime.js.map +1 -0
- package/_shims/auto/runtime.mjs +2 -0
- package/_shims/auto/runtime.mjs.map +1 -0
- package/_shims/auto/types-node.d.ts +5 -0
- package/_shims/auto/types-node.d.ts.map +1 -0
- package/_shims/auto/types-node.js +21 -0
- package/_shims/auto/types-node.js.map +1 -0
- package/_shims/auto/types-node.mjs +2 -0
- package/_shims/auto/types-node.mjs.map +1 -0
- package/_shims/auto/types.d.ts +99 -0
- package/_shims/{ReadableStream.js → auto/types.js} +0 -2
- package/{src/_shims/ReadableStream.js → _shims/auto/types.mjs} +0 -2
- package/_shims/bun-runtime.d.ts +6 -0
- package/_shims/bun-runtime.d.ts.map +1 -0
- package/_shims/bun-runtime.js +14 -0
- package/_shims/bun-runtime.js.map +1 -0
- package/_shims/bun-runtime.mjs +10 -0
- package/_shims/bun-runtime.mjs.map +1 -0
- package/_shims/index.d.ts +79 -0
- package/_shims/index.js +13 -0
- package/_shims/index.mjs +7 -0
- package/_shims/manual-types.d.ts +12 -0
- package/_shims/manual-types.js +3 -0
- package/_shims/manual-types.mjs +3 -0
- package/_shims/node-runtime.d.ts +3 -0
- package/_shims/node-runtime.d.ts.map +1 -0
- package/_shims/node-runtime.js +87 -0
- package/_shims/node-runtime.js.map +1 -0
- package/_shims/node-runtime.mjs +54 -0
- package/_shims/node-runtime.mjs.map +1 -0
- package/_shims/node-types.d.ts +42 -0
- package/_shims/node-types.js +3 -0
- package/_shims/node-types.mjs +3 -0
- package/_shims/registry.d.ts +35 -0
- package/_shims/registry.d.ts.map +1 -0
- package/_shims/registry.js +39 -0
- package/_shims/registry.js.map +1 -0
- package/_shims/registry.mjs +35 -0
- package/_shims/registry.mjs.map +1 -0
- package/_shims/web-runtime.d.ts +5 -0
- package/_shims/web-runtime.d.ts.map +1 -0
- package/_shims/web-runtime.js +70 -0
- package/_shims/web-runtime.js.map +1 -0
- package/_shims/web-runtime.mjs +63 -0
- package/_shims/web-runtime.mjs.map +1 -0
- package/_shims/web-types.d.ts +82 -0
- package/_shims/web-types.js +3 -0
- package/_shims/web-types.mjs +3 -0
- package/core.d.ts +170 -218
- package/core.d.ts.map +1 -1
- package/core.js +679 -737
- package/core.js.map +1 -1
- package/core.mjs +673 -688
- package/core.mjs.map +1 -1
- package/error.d.ts +32 -34
- package/error.js +95 -109
- package/error.js.map +1 -1
- package/error.mjs +92 -94
- package/error.mjs.map +1 -1
- package/index.d.mts +164 -175
- package/index.d.ts +164 -175
- package/index.d.ts.map +1 -1
- package/index.js +110 -161
- package/index.mjs +88 -109
- package/package.json +31 -58
- package/pagination.d.ts +31 -41
- package/pagination.js +52 -48
- package/pagination.mjs +50 -46
- package/resource.d.ts +10 -10
- package/resource.js +12 -12
- package/resource.mjs +10 -10
- package/resources/audio/audio.d.ts +12 -12
- package/resources/audio/audio.js +33 -50
- package/resources/audio/audio.mjs +11 -11
- package/resources/audio/index.d.ts +4 -4
- package/resources/audio/index.js +9 -24
- package/resources/audio/index.mjs +4 -4
- package/resources/audio/transcriptions.d.ts +44 -44
- package/resources/audio/transcriptions.js +13 -12
- package/resources/audio/transcriptions.mjs +9 -8
- package/resources/audio/translations.d.ts +38 -38
- package/resources/audio/translations.js +13 -12
- package/resources/audio/translations.mjs +9 -8
- package/resources/chat/chat.d.ts +17 -17
- package/resources/chat/chat.js +30 -47
- package/resources/chat/chat.mjs +8 -8
- package/resources/chat/completions.d.ts +330 -353
- package/resources/chat/completions.js +10 -13
- package/resources/chat/completions.mjs +7 -10
- package/resources/chat/index.d.ts +3 -17
- package/resources/chat/index.js +7 -17
- package/resources/chat/index.mjs +3 -3
- package/resources/completions.d.ts +216 -232
- package/resources/completions.js +10 -13
- package/resources/completions.mjs +7 -10
- package/resources/edits.d.ts +73 -73
- package/resources/edits.js +16 -15
- package/resources/edits.mjs +13 -12
- package/resources/embeddings.d.ts +73 -76
- package/resources/embeddings.js +12 -11
- package/resources/embeddings.mjs +9 -8
- package/resources/files.d.ts +91 -96
- package/resources/files.js +64 -65
- package/resources/files.mjs +57 -58
- package/resources/fine-tunes.d.ts +277 -290
- package/resources/fine-tunes.js +49 -50
- package/resources/fine-tunes.mjs +45 -46
- package/resources/fine-tuning/fine-tuning.d.ts +12 -12
- package/resources/fine-tuning/fine-tuning.js +32 -49
- package/resources/fine-tuning/fine-tuning.mjs +10 -10
- package/resources/fine-tuning/index.d.ts +3 -12
- package/resources/fine-tuning/index.js +9 -29
- package/resources/fine-tuning/index.mjs +3 -3
- package/resources/fine-tuning/jobs.d.ts +173 -179
- package/resources/fine-tuning/jobs.js +50 -47
- package/resources/fine-tuning/jobs.mjs +45 -42
- package/resources/images.d.ts +116 -119
- package/resources/images.js +25 -24
- package/resources/images.mjs +21 -20
- package/resources/index.d.ts +12 -37
- package/resources/index.js +29 -113
- package/resources/index.mjs +12 -12
- package/resources/models.d.ts +41 -40
- package/resources/models.js +30 -28
- package/resources/models.mjs +26 -24
- package/resources/moderations.d.ts +153 -156
- package/resources/moderations.js +12 -11
- package/resources/moderations.mjs +9 -8
- package/shims/node.d.ts +29 -0
- package/shims/node.d.ts.map +1 -0
- package/shims/node.js +31 -0
- package/shims/node.js.map +1 -0
- package/shims/node.mjs +5 -0
- package/shims/node.mjs.map +1 -0
- package/shims/web.d.ts +26 -0
- package/shims/web.d.ts.map +1 -0
- package/shims/web.js +31 -0
- package/shims/web.js.map +1 -0
- package/shims/web.mjs +5 -0
- package/shims/web.mjs.map +1 -0
- package/src/_shims/MultipartBody.ts +9 -0
- package/src/_shims/README.md +46 -0
- package/src/_shims/auto/runtime-bun.ts +4 -0
- package/src/_shims/auto/runtime-node.ts +4 -0
- package/src/_shims/auto/runtime.ts +4 -0
- package/src/_shims/auto/types-node.ts +4 -0
- package/src/_shims/auto/types.d.ts +99 -0
- package/src/_shims/auto/types.js +3 -0
- package/src/_shims/auto/types.mjs +3 -0
- package/src/_shims/bun-runtime.ts +14 -0
- package/src/_shims/index.d.ts +79 -0
- package/src/_shims/index.js +13 -0
- package/src/_shims/index.mjs +7 -0
- package/src/_shims/manual-types.d.ts +12 -0
- package/src/_shims/manual-types.js +3 -0
- package/src/_shims/manual-types.mjs +3 -0
- package/src/_shims/node-runtime.ts +79 -0
- package/src/_shims/node-types.d.ts +42 -0
- package/src/_shims/node-types.js +3 -0
- package/src/_shims/node-types.mjs +3 -0
- package/src/_shims/registry.ts +62 -0
- package/src/_shims/web-runtime.ts +91 -0
- package/src/_shims/web-types.d.ts +82 -0
- package/src/_shims/web-types.js +3 -0
- package/src/_shims/web-types.mjs +3 -0
- package/src/core.ts +35 -18
- package/src/error.ts +3 -3
- package/src/index.ts +6 -6
- package/src/pagination.ts +1 -1
- package/src/resource.ts +1 -1
- package/src/resources/audio/audio.ts +4 -4
- package/src/resources/audio/index.ts +3 -3
- package/src/resources/audio/transcriptions.ts +4 -4
- package/src/resources/audio/translations.ts +4 -4
- package/src/resources/chat/chat.ts +3 -3
- package/src/resources/chat/completions.ts +6 -6
- package/src/resources/chat/index.ts +2 -2
- package/src/resources/completions.ts +5 -5
- package/src/resources/edits.ts +4 -4
- package/src/resources/embeddings.ts +3 -3
- package/src/resources/files.ts +7 -7
- package/src/resources/fine-tunes.ts +7 -7
- package/src/resources/fine-tuning/fine-tuning.ts +3 -3
- package/src/resources/fine-tuning/index.ts +2 -2
- package/src/resources/fine-tuning/jobs.ts +6 -6
- package/src/resources/images.ts +4 -4
- package/src/resources/index.ts +11 -11
- package/src/resources/models.ts +4 -4
- package/src/resources/moderations.ts +3 -3
- package/src/shims/node.ts +50 -0
- package/src/shims/web.ts +50 -0
- package/src/streaming.ts +1 -1
- package/src/uploads.ts +12 -16
- package/src/version.ts +1 -1
- package/streaming.d.ts +9 -8
- package/streaming.d.ts.map +1 -1
- package/streaming.js +194 -185
- package/streaming.mjs +192 -183
- package/uploads.d.ts +23 -39
- package/uploads.d.ts.map +1 -1
- package/uploads.js +115 -157
- package/uploads.js.map +1 -1
- package/uploads.mjs +111 -133
- package/uploads.mjs.map +1 -1
- package/version.d.ts +2 -2
- package/version.js +4 -4
- package/version.mjs +2 -2
- package/_shims/ReadableStream-node.d.ts +0 -6
- package/_shims/ReadableStream-node.d.ts.map +0 -1
- package/_shims/ReadableStream-node.js +0 -14
- package/_shims/ReadableStream-node.js.map +0 -1
- package/_shims/ReadableStream-node.mjs +0 -3
- package/_shims/ReadableStream-node.mjs.map +0 -1
- package/_shims/ReadableStream.d.ts +0 -38
- package/_shims/ReadableStream.mjs +0 -7
- package/_shims/agent-node.d.ts +0 -7
- package/_shims/agent-node.d.ts.map +0 -1
- package/_shims/agent-node.js +0 -28
- package/_shims/agent-node.js.map +0 -1
- package/_shims/agent-node.mjs +0 -16
- package/_shims/agent-node.mjs.map +0 -1
- package/_shims/agent.d.ts +0 -9
- package/_shims/agent.d.ts.map +0 -1
- package/_shims/agent.js +0 -14
- package/_shims/agent.js.map +0 -1
- package/_shims/agent.mjs +0 -10
- package/_shims/agent.mjs.map +0 -1
- package/_shims/fetch-node.d.ts +0 -64
- package/_shims/fetch-node.js +0 -12
- package/_shims/fetch-node.mjs +0 -14
- package/_shims/fetch.d.ts +0 -60
- package/_shims/fetch.js +0 -13
- package/_shims/fetch.mjs +0 -15
- package/_shims/fileFromPath-node.d.ts +0 -17
- package/_shims/fileFromPath-node.d.ts.map +0 -1
- package/_shims/fileFromPath-node.js +0 -17
- package/_shims/fileFromPath-node.js.map +0 -1
- package/_shims/fileFromPath-node.mjs +0 -13
- package/_shims/fileFromPath-node.mjs.map +0 -1
- package/_shims/fileFromPath.d.ts +0 -22
- package/_shims/fileFromPath.d.ts.map +0 -1
- package/_shims/fileFromPath.js +0 -16
- package/_shims/fileFromPath.js.map +0 -1
- package/_shims/fileFromPath.mjs +0 -12
- package/_shims/fileFromPath.mjs.map +0 -1
- package/_shims/form-data-node.d.ts +0 -45
- package/_shims/form-data-node.js +0 -11
- package/_shims/form-data-node.mjs +0 -9
- package/_shims/form-data.d.ts +0 -43
- package/_shims/form-data.js +0 -17
- package/_shims/form-data.mjs +0 -20
- package/_shims/getMultipartRequestOptions-node.d.ts +0 -10
- package/_shims/getMultipartRequestOptions-node.d.ts.map +0 -1
- package/_shims/getMultipartRequestOptions-node.js +0 -22
- package/_shims/getMultipartRequestOptions-node.js.map +0 -1
- package/_shims/getMultipartRequestOptions-node.mjs +0 -18
- package/_shims/getMultipartRequestOptions-node.mjs.map +0 -1
- package/_shims/getMultipartRequestOptions.d.ts +0 -10
- package/_shims/getMultipartRequestOptions.d.ts.map +0 -1
- package/_shims/getMultipartRequestOptions.js +0 -12
- package/_shims/getMultipartRequestOptions.js.map +0 -1
- package/_shims/getMultipartRequestOptions.mjs +0 -8
- package/_shims/getMultipartRequestOptions.mjs.map +0 -1
- package/_shims/node-readable-node.d.ts +0 -8
- package/_shims/node-readable-node.d.ts.map +0 -1
- package/_shims/node-readable-node.js +0 -9
- package/_shims/node-readable-node.js.map +0 -1
- package/_shims/node-readable-node.mjs +0 -5
- package/_shims/node-readable-node.mjs.map +0 -1
- package/_shims/node-readable.d.ts +0 -23
- package/_shims/node-readable.d.ts.map +0 -1
- package/_shims/node-readable.js +0 -11
- package/_shims/node-readable.js.map +0 -1
- package/_shims/node-readable.mjs +0 -7
- package/_shims/node-readable.mjs.map +0 -1
- package/src/_shims/ReadableStream.d.ts +0 -38
- package/src/_shims/ReadableStream.mjs +0 -7
- package/src/_shims/agent-node.ts +0 -22
- package/src/_shims/agent.ts +0 -12
- package/src/_shims/fetch-node.d.ts +0 -64
- package/src/_shims/fetch-node.js +0 -12
- package/src/_shims/fetch-node.mjs +0 -14
- package/src/_shims/fetch.d.ts +0 -60
- package/src/_shims/fetch.js +0 -13
- package/src/_shims/fetch.mjs +0 -15
- package/src/_shims/fileFromPath-node.ts +0 -29
- package/src/_shims/fileFromPath.ts +0 -29
- package/src/_shims/form-data-node.d.ts +0 -45
- package/src/_shims/form-data-node.js +0 -11
- package/src/_shims/form-data-node.mjs +0 -9
- package/src/_shims/form-data.d.ts +0 -43
- package/src/_shims/form-data.js +0 -17
- package/src/_shims/form-data.mjs +0 -20
- package/src/_shims/getMultipartRequestOptions-node.ts +0 -25
- package/src/_shims/getMultipartRequestOptions.ts +0 -14
- package/src/_shims/node-readable-node.ts +0 -10
- package/src/_shims/node-readable.ts +0 -30
package/core.mjs
CHANGED
|
@@ -1,471 +1,445 @@
|
|
|
1
|
-
var __classPrivateFieldSet =
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
if (
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
value
|
|
13
|
-
);
|
|
14
|
-
};
|
|
15
|
-
var __classPrivateFieldGet =
|
|
16
|
-
(this && this.__classPrivateFieldGet) ||
|
|
17
|
-
function (receiver, state, kind, f) {
|
|
18
|
-
if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter');
|
|
19
|
-
if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
|
|
20
|
-
throw new TypeError('Cannot read private member from an object whose class did not declare it');
|
|
21
|
-
return (
|
|
22
|
-
kind === 'm' ? f
|
|
23
|
-
: kind === 'a' ? f.call(receiver)
|
|
24
|
-
: f ? f.value
|
|
25
|
-
: state.get(receiver)
|
|
26
|
-
);
|
|
27
|
-
};
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
28
12
|
var _AbstractPage_client;
|
|
29
|
-
import { VERSION } from
|
|
30
|
-
import { Stream } from
|
|
31
|
-
import { APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError } from
|
|
32
|
-
import { getDefaultAgent } from
|
|
33
|
-
import {
|
|
34
|
-
|
|
35
|
-
export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm } from './uploads.mjs';
|
|
13
|
+
import { VERSION } from "./version.mjs";
|
|
14
|
+
import { Stream } from "./streaming.mjs";
|
|
15
|
+
import { APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError } from "./error.mjs";
|
|
16
|
+
import { kind as shimsKind, getDefaultAgent, fetch, } from "./_shims/index.mjs";
|
|
17
|
+
import { isMultipartBody } from "./uploads.mjs";
|
|
18
|
+
export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from "./uploads.mjs";
|
|
36
19
|
const MAX_RETRIES = 2;
|
|
37
20
|
async function defaultParseResponse(props) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
21
|
+
const { response } = props;
|
|
22
|
+
if (props.options.stream) {
|
|
23
|
+
// Note: there is an invariant here that isn't represented in the type system
|
|
24
|
+
// that if you set `stream: true` the response type must also be `Stream<T>`
|
|
25
|
+
return new Stream(response, props.controller);
|
|
26
|
+
}
|
|
27
|
+
const contentType = response.headers.get('content-type');
|
|
28
|
+
if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
|
|
29
|
+
const json = await response.json();
|
|
30
|
+
debug('response', response.status, response.url, response.headers, json);
|
|
31
|
+
return json;
|
|
32
|
+
}
|
|
33
|
+
// TODO handle blob, arraybuffer, other content types, etc.
|
|
34
|
+
const text = await response.text();
|
|
35
|
+
debug('response', response.status, response.url, response.headers, text);
|
|
36
|
+
return text;
|
|
54
37
|
}
|
|
55
38
|
/**
|
|
56
39
|
* A subclass of `Promise` providing additional helper methods
|
|
57
40
|
* for interacting with the SDK.
|
|
58
41
|
*/
|
|
59
42
|
export class APIPromise extends Promise {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
43
|
+
constructor(responsePromise, parseResponse = defaultParseResponse) {
|
|
44
|
+
super((resolve) => {
|
|
45
|
+
// this is maybe a bit weird but this has to be a no-op to not implicitly
|
|
46
|
+
// parse the response body; instead .then, .catch, .finally are overridden
|
|
47
|
+
// to parse the response
|
|
48
|
+
resolve(null);
|
|
49
|
+
});
|
|
50
|
+
this.responsePromise = responsePromise;
|
|
51
|
+
this.parseResponse = parseResponse;
|
|
52
|
+
}
|
|
53
|
+
_thenUnwrap(transform) {
|
|
54
|
+
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Gets the raw `Response` instance instead of parsing the response
|
|
58
|
+
* data.
|
|
59
|
+
*
|
|
60
|
+
* If you want to parse the response body but still get the `Response`
|
|
61
|
+
* instance, you can use {@link withResponse()}.
|
|
62
|
+
*
|
|
63
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
64
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
|
65
|
+
* or add one of these imports before your first `import … from 'openai'`:
|
|
66
|
+
* - `import 'openai/shims/node'` (if you're running on Node)
|
|
67
|
+
* - `import 'openai/shims/web'` (otherwise)
|
|
68
|
+
*/
|
|
69
|
+
asResponse() {
|
|
70
|
+
return this.responsePromise.then((p) => p.response);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Gets the parsed response data and the raw `Response` instance.
|
|
74
|
+
*
|
|
75
|
+
* If you just want to get the raw `Response` instance without parsing it,
|
|
76
|
+
* you can use {@link asResponse()}.
|
|
77
|
+
*
|
|
78
|
+
*
|
|
79
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
80
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
|
81
|
+
* or add one of these imports before your first `import … from 'openai'`:
|
|
82
|
+
* - `import 'openai/shims/node'` (if you're running on Node)
|
|
83
|
+
* - `import 'openai/shims/web'` (otherwise)
|
|
84
|
+
*/
|
|
85
|
+
async withResponse() {
|
|
86
|
+
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
|
87
|
+
return { data, response };
|
|
88
|
+
}
|
|
89
|
+
parse() {
|
|
90
|
+
if (!this.parsedPromise) {
|
|
91
|
+
this.parsedPromise = this.responsePromise.then(this.parseResponse);
|
|
92
|
+
}
|
|
93
|
+
return this.parsedPromise;
|
|
94
|
+
}
|
|
95
|
+
then(onfulfilled, onrejected) {
|
|
96
|
+
return this.parse().then(onfulfilled, onrejected);
|
|
97
|
+
}
|
|
98
|
+
catch(onrejected) {
|
|
99
|
+
return this.parse().catch(onrejected);
|
|
100
|
+
}
|
|
101
|
+
finally(onfinally) {
|
|
102
|
+
return this.parse().finally(onfinally);
|
|
103
|
+
}
|
|
108
104
|
}
|
|
109
105
|
export class APIClient {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
this.baseURL = baseURL;
|
|
118
|
-
this.maxRetries = validatePositiveInteger(
|
|
119
|
-
'maxRetries',
|
|
120
|
-
maxRetries !== null && maxRetries !== void 0 ? maxRetries : MAX_RETRIES,
|
|
121
|
-
);
|
|
122
|
-
this.timeout = validatePositiveInteger('timeout', timeout);
|
|
123
|
-
this.httpAgent = httpAgent;
|
|
124
|
-
this.fetch = overridenFetch !== null && overridenFetch !== void 0 ? overridenFetch : fetch;
|
|
125
|
-
}
|
|
126
|
-
authHeaders(opts) {
|
|
127
|
-
return {};
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Override this to add your own default headers, for example:
|
|
131
|
-
*
|
|
132
|
-
* {
|
|
133
|
-
* ...super.defaultHeaders(),
|
|
134
|
-
* Authorization: 'Bearer 123',
|
|
135
|
-
* }
|
|
136
|
-
*/
|
|
137
|
-
defaultHeaders(opts) {
|
|
138
|
-
return {
|
|
139
|
-
Accept: 'application/json',
|
|
140
|
-
'Content-Type': 'application/json',
|
|
141
|
-
'User-Agent': this.getUserAgent(),
|
|
142
|
-
...getPlatformHeaders(),
|
|
143
|
-
...this.authHeaders(opts),
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Override this to add your own headers validation:
|
|
148
|
-
*/
|
|
149
|
-
validateHeaders(headers, customHeaders) {}
|
|
150
|
-
defaultIdempotencyKey() {
|
|
151
|
-
return `stainless-node-retry-${uuid4()}`;
|
|
152
|
-
}
|
|
153
|
-
get(path, opts) {
|
|
154
|
-
return this.methodRequest('get', path, opts);
|
|
155
|
-
}
|
|
156
|
-
post(path, opts) {
|
|
157
|
-
return this.methodRequest('post', path, opts);
|
|
158
|
-
}
|
|
159
|
-
patch(path, opts) {
|
|
160
|
-
return this.methodRequest('patch', path, opts);
|
|
161
|
-
}
|
|
162
|
-
put(path, opts) {
|
|
163
|
-
return this.methodRequest('put', path, opts);
|
|
164
|
-
}
|
|
165
|
-
delete(path, opts) {
|
|
166
|
-
return this.methodRequest('delete', path, opts);
|
|
167
|
-
}
|
|
168
|
-
methodRequest(method, path, opts) {
|
|
169
|
-
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
|
|
170
|
-
}
|
|
171
|
-
getAPIList(path, Page, opts) {
|
|
172
|
-
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
173
|
-
}
|
|
174
|
-
calculateContentLength(body) {
|
|
175
|
-
if (typeof body === 'string') {
|
|
176
|
-
if (typeof Buffer !== 'undefined') {
|
|
177
|
-
return Buffer.byteLength(body, 'utf8').toString();
|
|
178
|
-
}
|
|
179
|
-
if (typeof TextEncoder !== 'undefined') {
|
|
180
|
-
const encoder = new TextEncoder();
|
|
181
|
-
const encoded = encoder.encode(body);
|
|
182
|
-
return encoded.length.toString();
|
|
183
|
-
}
|
|
106
|
+
constructor({ baseURL, maxRetries, timeout = 600000, // 10 minutes
|
|
107
|
+
httpAgent, fetch: overridenFetch, }) {
|
|
108
|
+
this.baseURL = baseURL;
|
|
109
|
+
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries !== null && maxRetries !== void 0 ? maxRetries : MAX_RETRIES);
|
|
110
|
+
this.timeout = validatePositiveInteger('timeout', timeout);
|
|
111
|
+
this.httpAgent = httpAgent;
|
|
112
|
+
this.fetch = overridenFetch !== null && overridenFetch !== void 0 ? overridenFetch : fetch;
|
|
184
113
|
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
query = { ...defaultQuery, ...query };
|
|
320
|
-
}
|
|
321
|
-
if (query) {
|
|
322
|
-
url.search = this.stringifyQuery(query);
|
|
323
|
-
}
|
|
324
|
-
return url.toString();
|
|
325
|
-
}
|
|
326
|
-
stringifyQuery(query) {
|
|
327
|
-
return Object.entries(query)
|
|
328
|
-
.filter(([_, value]) => typeof value !== 'undefined')
|
|
329
|
-
.map(([key, value]) => {
|
|
330
|
-
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
331
|
-
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
114
|
+
authHeaders(opts) {
|
|
115
|
+
return {};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Override this to add your own default headers, for example:
|
|
119
|
+
*
|
|
120
|
+
* {
|
|
121
|
+
* ...super.defaultHeaders(),
|
|
122
|
+
* Authorization: 'Bearer 123',
|
|
123
|
+
* }
|
|
124
|
+
*/
|
|
125
|
+
defaultHeaders(opts) {
|
|
126
|
+
return {
|
|
127
|
+
Accept: 'application/json',
|
|
128
|
+
'Content-Type': 'application/json',
|
|
129
|
+
'User-Agent': this.getUserAgent(),
|
|
130
|
+
...getPlatformHeaders(),
|
|
131
|
+
...this.authHeaders(opts),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Override this to add your own headers validation:
|
|
136
|
+
*/
|
|
137
|
+
validateHeaders(headers, customHeaders) { }
|
|
138
|
+
defaultIdempotencyKey() {
|
|
139
|
+
return `stainless-node-retry-${uuid4()}`;
|
|
140
|
+
}
|
|
141
|
+
get(path, opts) {
|
|
142
|
+
return this.methodRequest('get', path, opts);
|
|
143
|
+
}
|
|
144
|
+
post(path, opts) {
|
|
145
|
+
return this.methodRequest('post', path, opts);
|
|
146
|
+
}
|
|
147
|
+
patch(path, opts) {
|
|
148
|
+
return this.methodRequest('patch', path, opts);
|
|
149
|
+
}
|
|
150
|
+
put(path, opts) {
|
|
151
|
+
return this.methodRequest('put', path, opts);
|
|
152
|
+
}
|
|
153
|
+
delete(path, opts) {
|
|
154
|
+
return this.methodRequest('delete', path, opts);
|
|
155
|
+
}
|
|
156
|
+
methodRequest(method, path, opts) {
|
|
157
|
+
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
|
|
158
|
+
}
|
|
159
|
+
getAPIList(path, Page, opts) {
|
|
160
|
+
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
161
|
+
}
|
|
162
|
+
calculateContentLength(body) {
|
|
163
|
+
if (typeof body === 'string') {
|
|
164
|
+
if (typeof Buffer !== 'undefined') {
|
|
165
|
+
return Buffer.byteLength(body, 'utf8').toString();
|
|
166
|
+
}
|
|
167
|
+
if (typeof TextEncoder !== 'undefined') {
|
|
168
|
+
const encoder = new TextEncoder();
|
|
169
|
+
const encoded = encoder.encode(body);
|
|
170
|
+
return encoded.length.toString();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
buildRequest(options) {
|
|
176
|
+
var _a, _b, _c, _d, _e, _f;
|
|
177
|
+
const { method, path, query, headers: headers = {} } = options;
|
|
178
|
+
const body = isMultipartBody(options.body) ? options.body.body
|
|
179
|
+
: options.body ? JSON.stringify(options.body, null, 2)
|
|
180
|
+
: null;
|
|
181
|
+
const contentLength = this.calculateContentLength(body);
|
|
182
|
+
const url = this.buildURL(path, query);
|
|
183
|
+
if ('timeout' in options)
|
|
184
|
+
validatePositiveInteger('timeout', options.timeout);
|
|
185
|
+
const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.timeout;
|
|
186
|
+
const httpAgent = (_c = (_b = options.httpAgent) !== null && _b !== void 0 ? _b : this.httpAgent) !== null && _c !== void 0 ? _c : getDefaultAgent(url);
|
|
187
|
+
const minAgentTimeout = timeout + 1000;
|
|
188
|
+
if (typeof ((_d = httpAgent === null || httpAgent === void 0 ? void 0 : httpAgent.options) === null || _d === void 0 ? void 0 : _d.timeout) === 'number' &&
|
|
189
|
+
minAgentTimeout > ((_e = httpAgent.options.timeout) !== null && _e !== void 0 ? _e : 0)) {
|
|
190
|
+
// Allow any given request to bump our agent active socket timeout.
|
|
191
|
+
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
|
|
192
|
+
// and without mutating agent we would need to create more of them.
|
|
193
|
+
// This tradeoff optimizes for performance.
|
|
194
|
+
httpAgent.options.timeout = minAgentTimeout;
|
|
195
|
+
}
|
|
196
|
+
if (this.idempotencyHeader && method !== 'get') {
|
|
197
|
+
if (!options.idempotencyKey)
|
|
198
|
+
options.idempotencyKey = this.defaultIdempotencyKey();
|
|
199
|
+
headers[this.idempotencyHeader] = options.idempotencyKey;
|
|
200
|
+
}
|
|
201
|
+
const reqHeaders = {
|
|
202
|
+
...(contentLength && { 'Content-Length': contentLength }),
|
|
203
|
+
...this.defaultHeaders(options),
|
|
204
|
+
...headers,
|
|
205
|
+
};
|
|
206
|
+
// let builtin fetch set the Content-Type for multipart bodies
|
|
207
|
+
if (isMultipartBody(options.body) && shimsKind !== 'node') {
|
|
208
|
+
delete reqHeaders['Content-Type'];
|
|
209
|
+
}
|
|
210
|
+
// Strip any headers being explicitly omitted with null
|
|
211
|
+
Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]);
|
|
212
|
+
const req = {
|
|
213
|
+
method,
|
|
214
|
+
...(body && { body: body }),
|
|
215
|
+
headers: reqHeaders,
|
|
216
|
+
...(httpAgent && { agent: httpAgent }),
|
|
217
|
+
// @ts-ignore node-fetch uses a custom AbortSignal type that is
|
|
218
|
+
// not compatible with standard web types
|
|
219
|
+
signal: (_f = options.signal) !== null && _f !== void 0 ? _f : null,
|
|
220
|
+
};
|
|
221
|
+
this.validateHeaders(reqHeaders, headers);
|
|
222
|
+
return { req, url, timeout };
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Used as a callback for mutating the given `RequestInit` object.
|
|
226
|
+
*
|
|
227
|
+
* This is useful for cases where you want to add certain headers based off of
|
|
228
|
+
* the request properties, e.g. `method` or `url`.
|
|
229
|
+
*/
|
|
230
|
+
async prepareRequest(request, { url, options }) { }
|
|
231
|
+
parseHeaders(headers) {
|
|
232
|
+
return (!headers ? {}
|
|
233
|
+
: Symbol.iterator in headers ?
|
|
234
|
+
Object.fromEntries(Array.from(headers).map((header) => [...header]))
|
|
235
|
+
: { ...headers });
|
|
236
|
+
}
|
|
237
|
+
makeStatusError(status, error, message, headers) {
|
|
238
|
+
return APIError.generate(status, error, message, headers);
|
|
239
|
+
}
|
|
240
|
+
request(options, remainingRetries = null) {
|
|
241
|
+
return new APIPromise(this.makeRequest(options, remainingRetries));
|
|
242
|
+
}
|
|
243
|
+
async makeRequest(optionsInput, retriesRemaining) {
|
|
244
|
+
var _a, _b, _c;
|
|
245
|
+
const options = await optionsInput;
|
|
246
|
+
if (retriesRemaining == null) {
|
|
247
|
+
retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
|
|
332
248
|
}
|
|
333
|
-
|
|
334
|
-
|
|
249
|
+
const { req, url, timeout } = this.buildRequest(options);
|
|
250
|
+
await this.prepareRequest(req, { url, options });
|
|
251
|
+
debug('request', url, options, req.headers);
|
|
252
|
+
if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) {
|
|
253
|
+
throw new APIUserAbortError();
|
|
254
|
+
}
|
|
255
|
+
const controller = new AbortController();
|
|
256
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
|
257
|
+
if (response instanceof Error) {
|
|
258
|
+
if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
|
|
259
|
+
throw new APIUserAbortError();
|
|
260
|
+
}
|
|
261
|
+
if (retriesRemaining) {
|
|
262
|
+
return this.retryRequest(options, retriesRemaining);
|
|
263
|
+
}
|
|
264
|
+
if (response.name === 'AbortError') {
|
|
265
|
+
throw new APIConnectionTimeoutError();
|
|
266
|
+
}
|
|
267
|
+
throw new APIConnectionError({ cause: response });
|
|
268
|
+
}
|
|
269
|
+
const responseHeaders = createResponseHeaders(response.headers);
|
|
270
|
+
if (!response.ok) {
|
|
271
|
+
if (retriesRemaining && this.shouldRetry(response)) {
|
|
272
|
+
return this.retryRequest(options, retriesRemaining, responseHeaders);
|
|
273
|
+
}
|
|
274
|
+
const errText = await response.text().catch((e) => castToError(e).message);
|
|
275
|
+
const errJSON = safeJSON(errText);
|
|
276
|
+
const errMessage = errJSON ? undefined : errText;
|
|
277
|
+
debug('response', response.status, url, responseHeaders, errMessage);
|
|
278
|
+
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
|
|
279
|
+
throw err;
|
|
280
|
+
}
|
|
281
|
+
return { response, options, controller };
|
|
282
|
+
}
|
|
283
|
+
requestAPIList(Page, options) {
|
|
284
|
+
const request = this.makeRequest(options, null);
|
|
285
|
+
return new PagePromise(this, request, Page);
|
|
286
|
+
}
|
|
287
|
+
buildURL(path, query) {
|
|
288
|
+
const url = isAbsoluteURL(path) ?
|
|
289
|
+
new URL(path)
|
|
290
|
+
: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
291
|
+
const defaultQuery = this.defaultQuery();
|
|
292
|
+
if (!isEmptyObj(defaultQuery)) {
|
|
293
|
+
query = { ...defaultQuery, ...query };
|
|
294
|
+
}
|
|
295
|
+
if (query) {
|
|
296
|
+
url.search = this.stringifyQuery(query);
|
|
297
|
+
}
|
|
298
|
+
return url.toString();
|
|
299
|
+
}
|
|
300
|
+
stringifyQuery(query) {
|
|
301
|
+
return Object.entries(query)
|
|
302
|
+
.filter(([_, value]) => typeof value !== 'undefined')
|
|
303
|
+
.map(([key, value]) => {
|
|
304
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
305
|
+
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
306
|
+
}
|
|
307
|
+
if (value === null) {
|
|
308
|
+
return `${encodeURIComponent(key)}=`;
|
|
309
|
+
}
|
|
310
|
+
throw new Error(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
|
|
311
|
+
})
|
|
312
|
+
.join('&');
|
|
313
|
+
}
|
|
314
|
+
async fetchWithTimeout(url, init, ms, controller) {
|
|
315
|
+
const { signal, ...options } = init || {};
|
|
316
|
+
if (signal)
|
|
317
|
+
signal.addEventListener('abort', () => controller.abort());
|
|
318
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
319
|
+
return (this.getRequestClient()
|
|
320
|
+
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
|
321
|
+
.fetch.call(undefined, url, { signal: controller.signal, ...options })
|
|
322
|
+
.finally(() => {
|
|
323
|
+
clearTimeout(timeout);
|
|
324
|
+
}));
|
|
325
|
+
}
|
|
326
|
+
getRequestClient() {
|
|
327
|
+
return { fetch: this.fetch };
|
|
328
|
+
}
|
|
329
|
+
shouldRetry(response) {
|
|
330
|
+
// Note this is not a standard header.
|
|
331
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
332
|
+
// If the server explicitly says whether or not to retry, obey.
|
|
333
|
+
if (shouldRetryHeader === 'true')
|
|
334
|
+
return true;
|
|
335
|
+
if (shouldRetryHeader === 'false')
|
|
336
|
+
return false;
|
|
337
|
+
// Retry on request timeouts.
|
|
338
|
+
if (response.status === 408)
|
|
339
|
+
return true;
|
|
340
|
+
// Retry on lock timeouts.
|
|
341
|
+
if (response.status === 409)
|
|
342
|
+
return true;
|
|
343
|
+
// Retry on rate limits.
|
|
344
|
+
if (response.status === 429)
|
|
345
|
+
return true;
|
|
346
|
+
// Retry internal errors.
|
|
347
|
+
if (response.status >= 500)
|
|
348
|
+
return true;
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
async retryRequest(options, retriesRemaining, responseHeaders) {
|
|
352
|
+
var _a;
|
|
353
|
+
retriesRemaining -= 1;
|
|
354
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
355
|
+
//
|
|
356
|
+
// TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
|
|
357
|
+
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
|
|
358
|
+
const retryAfter = parseInt((responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) || '');
|
|
359
|
+
const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
|
|
360
|
+
const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
|
|
361
|
+
await sleep(timeout);
|
|
362
|
+
return this.makeRequest(options, retriesRemaining);
|
|
363
|
+
}
|
|
364
|
+
calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) {
|
|
365
|
+
const initialRetryDelay = 0.5;
|
|
366
|
+
const maxRetryDelay = 2;
|
|
367
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
368
|
+
// just do what it says.
|
|
369
|
+
if (Number.isInteger(retryAfter) && retryAfter <= 60) {
|
|
370
|
+
return retryAfter;
|
|
335
371
|
}
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
);
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
return this.getRequestClient()
|
|
347
|
-
.fetch(url, { signal: controller.signal, ...options })
|
|
348
|
-
.finally(() => {
|
|
349
|
-
clearTimeout(timeout);
|
|
350
|
-
});
|
|
351
|
-
}
|
|
352
|
-
getRequestClient() {
|
|
353
|
-
return { fetch: this.fetch };
|
|
354
|
-
}
|
|
355
|
-
shouldRetry(response) {
|
|
356
|
-
// Note this is not a standard header.
|
|
357
|
-
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
358
|
-
// If the server explicitly says whether or not to retry, obey.
|
|
359
|
-
if (shouldRetryHeader === 'true') return true;
|
|
360
|
-
if (shouldRetryHeader === 'false') return false;
|
|
361
|
-
// Retry on request timeouts.
|
|
362
|
-
if (response.status === 408) return true;
|
|
363
|
-
// Retry on lock timeouts.
|
|
364
|
-
if (response.status === 409) return true;
|
|
365
|
-
// Retry on rate limits.
|
|
366
|
-
if (response.status === 429) return true;
|
|
367
|
-
// Retry internal errors.
|
|
368
|
-
if (response.status >= 500) return true;
|
|
369
|
-
return false;
|
|
370
|
-
}
|
|
371
|
-
async retryRequest(options, retriesRemaining, responseHeaders) {
|
|
372
|
-
var _a;
|
|
373
|
-
retriesRemaining -= 1;
|
|
374
|
-
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
375
|
-
//
|
|
376
|
-
// TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
|
|
377
|
-
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
|
|
378
|
-
const retryAfter = parseInt(
|
|
379
|
-
(responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) ||
|
|
380
|
-
'',
|
|
381
|
-
);
|
|
382
|
-
const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
|
|
383
|
-
const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
|
|
384
|
-
await sleep(timeout);
|
|
385
|
-
return this.makeRequest(options, retriesRemaining);
|
|
386
|
-
}
|
|
387
|
-
calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) {
|
|
388
|
-
const initialRetryDelay = 0.5;
|
|
389
|
-
const maxRetryDelay = 2;
|
|
390
|
-
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
391
|
-
// just do what it says.
|
|
392
|
-
if (Number.isInteger(retryAfter) && retryAfter <= 60) {
|
|
393
|
-
return retryAfter;
|
|
394
|
-
}
|
|
395
|
-
const numRetries = maxRetries - retriesRemaining;
|
|
396
|
-
// Apply exponential backoff, but not more than the max.
|
|
397
|
-
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
|
|
398
|
-
// Apply some jitter, plus-or-minus half a second.
|
|
399
|
-
const jitter = Math.random() - 0.5;
|
|
400
|
-
return sleepSeconds + jitter;
|
|
401
|
-
}
|
|
402
|
-
getUserAgent() {
|
|
403
|
-
return `${this.constructor.name}/JS ${VERSION}`;
|
|
404
|
-
}
|
|
372
|
+
const numRetries = maxRetries - retriesRemaining;
|
|
373
|
+
// Apply exponential backoff, but not more than the max.
|
|
374
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
|
|
375
|
+
// Apply some jitter, plus-or-minus half a second.
|
|
376
|
+
const jitter = Math.random() - 0.5;
|
|
377
|
+
return sleepSeconds + jitter;
|
|
378
|
+
}
|
|
379
|
+
getUserAgent() {
|
|
380
|
+
return `${this.constructor.name}/JS ${VERSION}`;
|
|
381
|
+
}
|
|
405
382
|
}
|
|
406
383
|
export class APIResource {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
384
|
+
constructor(client) {
|
|
385
|
+
this.client = client;
|
|
386
|
+
this.get = client.get.bind(client);
|
|
387
|
+
this.post = client.post.bind(client);
|
|
388
|
+
this.patch = client.patch.bind(client);
|
|
389
|
+
this.put = client.put.bind(client);
|
|
390
|
+
this.delete = client.delete.bind(client);
|
|
391
|
+
this.getAPIList = client.getAPIList.bind(client);
|
|
392
|
+
}
|
|
416
393
|
}
|
|
417
394
|
export class AbstractPage {
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
}
|
|
395
|
+
constructor(client, response, body, options) {
|
|
396
|
+
_AbstractPage_client.set(this, void 0);
|
|
397
|
+
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
|
|
398
|
+
this.options = options;
|
|
399
|
+
this.response = response;
|
|
400
|
+
this.body = body;
|
|
401
|
+
}
|
|
402
|
+
hasNextPage() {
|
|
403
|
+
const items = this.getPaginatedItems();
|
|
404
|
+
if (!items.length)
|
|
405
|
+
return false;
|
|
406
|
+
return this.nextPageInfo() != null;
|
|
407
|
+
}
|
|
408
|
+
async getNextPage() {
|
|
409
|
+
const nextInfo = this.nextPageInfo();
|
|
410
|
+
if (!nextInfo) {
|
|
411
|
+
throw new Error('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
|
|
412
|
+
}
|
|
413
|
+
const nextOptions = { ...this.options };
|
|
414
|
+
if ('params' in nextInfo) {
|
|
415
|
+
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
|
|
416
|
+
}
|
|
417
|
+
else if ('url' in nextInfo) {
|
|
418
|
+
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
|
|
419
|
+
for (const [key, value] of params) {
|
|
420
|
+
nextInfo.url.searchParams.set(key, value);
|
|
421
|
+
}
|
|
422
|
+
nextOptions.query = undefined;
|
|
423
|
+
nextOptions.path = nextInfo.url.toString();
|
|
424
|
+
}
|
|
425
|
+
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
|
|
426
|
+
}
|
|
427
|
+
async *iterPages() {
|
|
428
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
429
|
+
let page = this;
|
|
430
|
+
yield page;
|
|
431
|
+
while (page.hasNextPage()) {
|
|
432
|
+
page = await page.getNextPage();
|
|
433
|
+
yield page;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
|
|
437
|
+
for await (const page of this.iterPages()) {
|
|
438
|
+
for (const item of page.getPaginatedItems()) {
|
|
439
|
+
yield item;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
469
443
|
}
|
|
470
444
|
/**
|
|
471
445
|
* This subclass of Promise will resolve to an instantiated Page once the request completes.
|
|
@@ -477,211 +451,216 @@ export class AbstractPage {
|
|
|
477
451
|
* }
|
|
478
452
|
*/
|
|
479
453
|
export class PagePromise extends APIPromise {
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
yield item;
|
|
497
|
-
}
|
|
498
|
-
}
|
|
454
|
+
constructor(client, request, Page) {
|
|
455
|
+
super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Allow auto-paginating iteration on an unawaited list call, eg:
|
|
459
|
+
*
|
|
460
|
+
* for await (const item of client.items.list()) {
|
|
461
|
+
* console.log(item)
|
|
462
|
+
* }
|
|
463
|
+
*/
|
|
464
|
+
async *[Symbol.asyncIterator]() {
|
|
465
|
+
const page = await this;
|
|
466
|
+
for await (const item of page) {
|
|
467
|
+
yield item;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
499
470
|
}
|
|
500
471
|
export const createResponseHeaders = (headers) => {
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
return target[key.toLowerCase()] || target[key];
|
|
510
|
-
},
|
|
511
|
-
},
|
|
512
|
-
);
|
|
472
|
+
return new Proxy(Object.fromEntries(
|
|
473
|
+
// @ts-ignore
|
|
474
|
+
headers.entries()), {
|
|
475
|
+
get(target, name) {
|
|
476
|
+
const key = name.toString();
|
|
477
|
+
return target[key.toLowerCase()] || target[key];
|
|
478
|
+
},
|
|
479
|
+
});
|
|
513
480
|
};
|
|
514
481
|
// This is required so that we can determine if a given object matches the RequestOptions
|
|
515
482
|
// type at runtime. While this requires duplication, it is enforced by the TypeScript
|
|
516
483
|
// compiler such that any missing / extraneous keys will cause an error.
|
|
517
484
|
const requestOptionsKeys = {
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
485
|
+
method: true,
|
|
486
|
+
path: true,
|
|
487
|
+
query: true,
|
|
488
|
+
body: true,
|
|
489
|
+
headers: true,
|
|
490
|
+
maxRetries: true,
|
|
491
|
+
stream: true,
|
|
492
|
+
timeout: true,
|
|
493
|
+
httpAgent: true,
|
|
494
|
+
signal: true,
|
|
495
|
+
idempotencyKey: true,
|
|
529
496
|
};
|
|
530
497
|
export const isRequestOptions = (obj) => {
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
|
|
536
|
-
);
|
|
498
|
+
return (typeof obj === 'object' &&
|
|
499
|
+
obj !== null &&
|
|
500
|
+
!isEmptyObj(obj) &&
|
|
501
|
+
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
|
|
537
502
|
};
|
|
538
503
|
const getPlatformProperties = () => {
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
504
|
+
if (typeof Deno !== 'undefined' && Deno.build != null) {
|
|
505
|
+
return {
|
|
506
|
+
'X-Stainless-Lang': 'js',
|
|
507
|
+
'X-Stainless-Package-Version': VERSION,
|
|
508
|
+
'X-Stainless-OS': normalizePlatform(Deno.build.os),
|
|
509
|
+
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
|
|
510
|
+
'X-Stainless-Runtime': 'deno',
|
|
511
|
+
'X-Stainless-Runtime-Version': Deno.version,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
|
515
|
+
return {
|
|
516
|
+
'X-Stainless-Lang': 'js',
|
|
517
|
+
'X-Stainless-Package-Version': VERSION,
|
|
518
|
+
'X-Stainless-OS': 'Unknown',
|
|
519
|
+
'X-Stainless-Arch': `other:${EdgeRuntime}`,
|
|
520
|
+
'X-Stainless-Runtime': 'edge',
|
|
521
|
+
'X-Stainless-Runtime-Version': process.version,
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
// Check if Node.js
|
|
525
|
+
if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
|
|
526
|
+
return {
|
|
527
|
+
'X-Stainless-Lang': 'js',
|
|
528
|
+
'X-Stainless-Package-Version': VERSION,
|
|
529
|
+
'X-Stainless-OS': normalizePlatform(process.platform),
|
|
530
|
+
'X-Stainless-Arch': normalizeArch(process.arch),
|
|
531
|
+
'X-Stainless-Runtime': 'node',
|
|
532
|
+
'X-Stainless-Runtime-Version': process.version,
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
const browserInfo = getBrowserInfo();
|
|
536
|
+
if (browserInfo) {
|
|
537
|
+
return {
|
|
538
|
+
'X-Stainless-Lang': 'js',
|
|
539
|
+
'X-Stainless-Package-Version': VERSION,
|
|
540
|
+
'X-Stainless-OS': 'Unknown',
|
|
541
|
+
'X-Stainless-Arch': 'unknown',
|
|
542
|
+
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
|
|
543
|
+
'X-Stainless-Runtime-Version': browserInfo.version,
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
// TODO add support for Cloudflare workers, etc.
|
|
572
547
|
return {
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
548
|
+
'X-Stainless-Lang': 'js',
|
|
549
|
+
'X-Stainless-Package-Version': VERSION,
|
|
550
|
+
'X-Stainless-OS': 'Unknown',
|
|
551
|
+
'X-Stainless-Arch': 'unknown',
|
|
552
|
+
'X-Stainless-Runtime': 'unknown',
|
|
553
|
+
'X-Stainless-Runtime-Version': 'unknown',
|
|
579
554
|
};
|
|
580
|
-
}
|
|
581
|
-
// TODO add support for Cloudflare workers, etc.
|
|
582
|
-
return {
|
|
583
|
-
'X-Stainless-Lang': 'js',
|
|
584
|
-
'X-Stainless-Package-Version': VERSION,
|
|
585
|
-
'X-Stainless-OS': 'Unknown',
|
|
586
|
-
'X-Stainless-Arch': 'unknown',
|
|
587
|
-
'X-Stainless-Runtime': 'unknown',
|
|
588
|
-
'X-Stainless-Runtime-Version': 'unknown',
|
|
589
|
-
};
|
|
590
555
|
};
|
|
591
556
|
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
|
|
592
557
|
function getBrowserInfo() {
|
|
593
|
-
|
|
558
|
+
if (typeof navigator === 'undefined' || !navigator) {
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
// NOTE: The order matters here!
|
|
562
|
+
const browserPatterns = [
|
|
563
|
+
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
564
|
+
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
565
|
+
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
566
|
+
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
567
|
+
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
568
|
+
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
|
569
|
+
];
|
|
570
|
+
// Find the FIRST matching browser
|
|
571
|
+
for (const { key, pattern } of browserPatterns) {
|
|
572
|
+
const match = pattern.exec(navigator.userAgent);
|
|
573
|
+
if (match) {
|
|
574
|
+
const major = match[1] || 0;
|
|
575
|
+
const minor = match[2] || 0;
|
|
576
|
+
const patch = match[3] || 0;
|
|
577
|
+
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
578
|
+
}
|
|
579
|
+
}
|
|
594
580
|
return null;
|
|
595
|
-
}
|
|
596
|
-
// NOTE: The order matters here!
|
|
597
|
-
const browserPatterns = [
|
|
598
|
-
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
599
|
-
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
600
|
-
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
601
|
-
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
602
|
-
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
603
|
-
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
|
604
|
-
];
|
|
605
|
-
// Find the FIRST matching browser
|
|
606
|
-
for (const { key, pattern } of browserPatterns) {
|
|
607
|
-
const match = pattern.exec(navigator.userAgent);
|
|
608
|
-
if (match) {
|
|
609
|
-
const major = match[1] || 0;
|
|
610
|
-
const minor = match[2] || 0;
|
|
611
|
-
const patch = match[3] || 0;
|
|
612
|
-
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
return null;
|
|
616
581
|
}
|
|
617
582
|
const normalizeArch = (arch) => {
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
583
|
+
// Node docs:
|
|
584
|
+
// - https://nodejs.org/api/process.html#processarch
|
|
585
|
+
// Deno docs:
|
|
586
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
587
|
+
if (arch === 'x32')
|
|
588
|
+
return 'x32';
|
|
589
|
+
if (arch === 'x86_64' || arch === 'x64')
|
|
590
|
+
return 'x64';
|
|
591
|
+
if (arch === 'arm')
|
|
592
|
+
return 'arm';
|
|
593
|
+
if (arch === 'aarch64' || arch === 'arm64')
|
|
594
|
+
return 'arm64';
|
|
595
|
+
if (arch)
|
|
596
|
+
return `other:${arch}`;
|
|
597
|
+
return 'unknown';
|
|
628
598
|
};
|
|
629
599
|
const normalizePlatform = (platform) => {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
600
|
+
// Node platforms:
|
|
601
|
+
// - https://nodejs.org/api/process.html#processplatform
|
|
602
|
+
// Deno platforms:
|
|
603
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
604
|
+
// - https://github.com/denoland/deno/issues/14799
|
|
605
|
+
platform = platform.toLowerCase();
|
|
606
|
+
// NOTE: this iOS check is untested and may not work
|
|
607
|
+
// Node does not work natively on IOS, there is a fork at
|
|
608
|
+
// https://github.com/nodejs-mobile/nodejs-mobile
|
|
609
|
+
// however it is unknown at the time of writing how to detect if it is running
|
|
610
|
+
if (platform.includes('ios'))
|
|
611
|
+
return 'iOS';
|
|
612
|
+
if (platform === 'android')
|
|
613
|
+
return 'Android';
|
|
614
|
+
if (platform === 'darwin')
|
|
615
|
+
return 'MacOS';
|
|
616
|
+
if (platform === 'win32')
|
|
617
|
+
return 'Windows';
|
|
618
|
+
if (platform === 'freebsd')
|
|
619
|
+
return 'FreeBSD';
|
|
620
|
+
if (platform === 'openbsd')
|
|
621
|
+
return 'OpenBSD';
|
|
622
|
+
if (platform === 'linux')
|
|
623
|
+
return 'Linux';
|
|
624
|
+
if (platform)
|
|
625
|
+
return `Other:${platform}`;
|
|
626
|
+
return 'Unknown';
|
|
649
627
|
};
|
|
650
628
|
let _platformHeaders;
|
|
651
629
|
const getPlatformHeaders = () => {
|
|
652
|
-
|
|
653
|
-
_platformHeaders
|
|
654
|
-
: (_platformHeaders = getPlatformProperties());
|
|
630
|
+
return (_platformHeaders !== null && _platformHeaders !== void 0 ? _platformHeaders : (_platformHeaders = getPlatformProperties()));
|
|
655
631
|
};
|
|
656
632
|
export const safeJSON = (text) => {
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
633
|
+
try {
|
|
634
|
+
return JSON.parse(text);
|
|
635
|
+
}
|
|
636
|
+
catch (err) {
|
|
637
|
+
return undefined;
|
|
638
|
+
}
|
|
662
639
|
};
|
|
663
640
|
// https://stackoverflow.com/a/19709846
|
|
664
641
|
const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
|
|
665
642
|
const isAbsoluteURL = (url) => {
|
|
666
|
-
|
|
643
|
+
return startsWithSchemeRegexp.test(url);
|
|
667
644
|
};
|
|
668
645
|
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
669
646
|
const validatePositiveInteger = (name, n) => {
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
647
|
+
if (typeof n !== 'number' || !Number.isInteger(n)) {
|
|
648
|
+
throw new Error(`${name} must be an integer`);
|
|
649
|
+
}
|
|
650
|
+
if (n < 0) {
|
|
651
|
+
throw new Error(`${name} must be a positive integer`);
|
|
652
|
+
}
|
|
653
|
+
return n;
|
|
677
654
|
};
|
|
678
655
|
export const castToError = (err) => {
|
|
679
|
-
|
|
680
|
-
|
|
656
|
+
if (err instanceof Error)
|
|
657
|
+
return err;
|
|
658
|
+
return new Error(err);
|
|
681
659
|
};
|
|
682
660
|
export const ensurePresent = (value) => {
|
|
683
|
-
|
|
684
|
-
|
|
661
|
+
if (value == null)
|
|
662
|
+
throw new Error(`Expected a value to be given but received ${value} instead.`);
|
|
663
|
+
return value;
|
|
685
664
|
};
|
|
686
665
|
/**
|
|
687
666
|
* Read an environment variable.
|
|
@@ -689,112 +668,118 @@ export const ensurePresent = (value) => {
|
|
|
689
668
|
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
|
690
669
|
*/
|
|
691
670
|
export const readEnv = (env) => {
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
return
|
|
700
|
-
void 0
|
|
701
|
-
: _d.call(_c, env);
|
|
702
|
-
}
|
|
703
|
-
return undefined;
|
|
671
|
+
var _a, _b, _c, _d;
|
|
672
|
+
if (typeof process !== 'undefined') {
|
|
673
|
+
return (_b = (_a = process.env) === null || _a === void 0 ? void 0 : _a[env]) !== null && _b !== void 0 ? _b : undefined;
|
|
674
|
+
}
|
|
675
|
+
if (typeof Deno !== 'undefined') {
|
|
676
|
+
return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ? void 0 : _d.call(_c, env);
|
|
677
|
+
}
|
|
678
|
+
return undefined;
|
|
704
679
|
};
|
|
705
680
|
export const coerceInteger = (value) => {
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
681
|
+
if (typeof value === 'number')
|
|
682
|
+
return Math.round(value);
|
|
683
|
+
if (typeof value === 'string')
|
|
684
|
+
return parseInt(value, 10);
|
|
685
|
+
throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
|
709
686
|
};
|
|
710
687
|
export const coerceFloat = (value) => {
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
688
|
+
if (typeof value === 'number')
|
|
689
|
+
return value;
|
|
690
|
+
if (typeof value === 'string')
|
|
691
|
+
return parseFloat(value);
|
|
692
|
+
throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
|
714
693
|
};
|
|
715
694
|
export const coerceBoolean = (value) => {
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
695
|
+
if (typeof value === 'boolean')
|
|
696
|
+
return value;
|
|
697
|
+
if (typeof value === 'string')
|
|
698
|
+
return value === 'true';
|
|
699
|
+
return Boolean(value);
|
|
719
700
|
};
|
|
720
701
|
export const maybeCoerceInteger = (value) => {
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
702
|
+
if (value === undefined) {
|
|
703
|
+
return undefined;
|
|
704
|
+
}
|
|
705
|
+
return coerceInteger(value);
|
|
725
706
|
};
|
|
726
707
|
export const maybeCoerceFloat = (value) => {
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
708
|
+
if (value === undefined) {
|
|
709
|
+
return undefined;
|
|
710
|
+
}
|
|
711
|
+
return coerceFloat(value);
|
|
731
712
|
};
|
|
732
713
|
export const maybeCoerceBoolean = (value) => {
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
714
|
+
if (value === undefined) {
|
|
715
|
+
return undefined;
|
|
716
|
+
}
|
|
717
|
+
return coerceBoolean(value);
|
|
737
718
|
};
|
|
738
719
|
// https://stackoverflow.com/a/34491287
|
|
739
720
|
export function isEmptyObj(obj) {
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
721
|
+
if (!obj)
|
|
722
|
+
return true;
|
|
723
|
+
for (const _k in obj)
|
|
724
|
+
return false;
|
|
725
|
+
return true;
|
|
743
726
|
}
|
|
744
727
|
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
|
745
728
|
export function hasOwn(obj, key) {
|
|
746
|
-
|
|
729
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
747
730
|
}
|
|
748
731
|
export function debug(action, ...args) {
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
732
|
+
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
|
|
733
|
+
console.log(`OpenAI:DEBUG:${action}`, ...args);
|
|
734
|
+
}
|
|
752
735
|
}
|
|
753
736
|
/**
|
|
754
737
|
* https://stackoverflow.com/a/2117523
|
|
755
738
|
*/
|
|
756
739
|
const uuid4 = () => {
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
740
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
741
|
+
const r = (Math.random() * 16) | 0;
|
|
742
|
+
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
743
|
+
return v.toString(16);
|
|
744
|
+
});
|
|
762
745
|
};
|
|
763
746
|
export const isRunningInBrowser = () => {
|
|
764
|
-
|
|
747
|
+
return (
|
|
765
748
|
// @ts-ignore
|
|
766
749
|
typeof window !== 'undefined' &&
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
);
|
|
750
|
+
// @ts-ignore
|
|
751
|
+
typeof window.document !== 'undefined' &&
|
|
752
|
+
// @ts-ignore
|
|
753
|
+
typeof navigator !== 'undefined');
|
|
772
754
|
};
|
|
773
755
|
export const isHeadersProtocol = (headers) => {
|
|
774
|
-
|
|
756
|
+
return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function';
|
|
775
757
|
};
|
|
776
758
|
export const getHeader = (headers, key) => {
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
if (value
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
759
|
+
const lowerKey = key.toLowerCase();
|
|
760
|
+
if (isHeadersProtocol(headers))
|
|
761
|
+
return headers.get(key) || headers.get(lowerKey);
|
|
762
|
+
const value = headers[key] || headers[lowerKey];
|
|
763
|
+
if (Array.isArray(value)) {
|
|
764
|
+
if (value.length <= 1)
|
|
765
|
+
return value[0];
|
|
766
|
+
console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
|
|
767
|
+
return value[0];
|
|
768
|
+
}
|
|
769
|
+
return value;
|
|
786
770
|
};
|
|
787
771
|
/**
|
|
788
772
|
* Encodes a string to Base64 format.
|
|
789
773
|
*/
|
|
790
774
|
export const toBase64 = (str) => {
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
775
|
+
if (!str)
|
|
776
|
+
return '';
|
|
777
|
+
if (typeof Buffer !== 'undefined') {
|
|
778
|
+
return Buffer.from(str).toString('base64');
|
|
779
|
+
}
|
|
780
|
+
if (typeof btoa !== 'undefined') {
|
|
781
|
+
return btoa(str);
|
|
782
|
+
}
|
|
783
|
+
throw new Error('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
|
|
799
784
|
};
|
|
800
|
-
//# sourceMappingURL=core.mjs.map
|
|
785
|
+
//# sourceMappingURL=core.mjs.map
|