@mixedbread/sdk 0.2.2 → 0.4.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 +23 -0
- package/README.md +110 -37
- package/api-promise.d.mts +2 -0
- package/api-promise.d.mts.map +1 -0
- package/api-promise.d.ts +2 -0
- package/api-promise.d.ts.map +1 -0
- package/{_shims/auto/runtime.js → api-promise.js} +3 -5
- package/api-promise.js.map +1 -0
- package/api-promise.mjs +2 -0
- package/api-promise.mjs.map +1 -0
- package/client.d.mts +236 -0
- package/client.d.mts.map +1 -0
- package/client.d.ts +236 -0
- package/client.d.ts.map +1 -0
- package/client.js +527 -0
- package/client.js.map +1 -0
- package/client.mjs +500 -0
- package/client.mjs.map +1 -0
- package/core/api-promise.d.mts +47 -0
- package/core/api-promise.d.mts.map +1 -0
- package/core/api-promise.d.ts +47 -0
- package/core/api-promise.d.ts.map +1 -0
- package/core/api-promise.js +84 -0
- package/core/api-promise.js.map +1 -0
- package/core/api-promise.mjs +80 -0
- package/core/api-promise.mjs.map +1 -0
- package/core/error.d.mts +47 -0
- package/core/error.d.mts.map +1 -0
- package/core/error.d.ts +47 -0
- package/core/error.d.ts.map +1 -0
- package/core/error.js +113 -0
- package/core/error.js.map +1 -0
- package/core/error.mjs +97 -0
- package/core/error.mjs.map +1 -0
- package/core/pagination.d.mts +67 -0
- package/core/pagination.d.mts.map +1 -0
- package/core/pagination.d.ts +67 -0
- package/core/pagination.d.ts.map +1 -0
- package/core/pagination.js +120 -0
- package/core/pagination.js.map +1 -0
- package/core/pagination.mjs +114 -0
- package/core/pagination.mjs.map +1 -0
- package/core/resource.d.mts +6 -0
- package/core/resource.d.mts.map +1 -0
- package/core/resource.d.ts +6 -0
- package/core/resource.d.ts.map +1 -0
- package/core/resource.js +11 -0
- package/core/resource.js.map +1 -0
- package/core/resource.mjs +7 -0
- package/core/resource.mjs.map +1 -0
- package/core/uploads.d.mts +3 -0
- package/core/uploads.d.mts.map +1 -0
- package/core/uploads.d.ts +3 -0
- package/core/uploads.d.ts.map +1 -0
- package/core/uploads.js +6 -0
- package/core/uploads.js.map +1 -0
- package/core/uploads.mjs +2 -0
- package/core/uploads.mjs.map +1 -0
- package/error.d.mts +2 -0
- package/error.d.mts.map +1 -0
- package/error.d.ts +1 -46
- package/error.d.ts.map +1 -1
- package/error.js +16 -110
- package/error.js.map +1 -1
- package/error.mjs +1 -96
- package/error.mjs.map +1 -1
- package/index.d.mts +7 -169
- package/index.d.mts.map +1 -0
- package/index.d.ts +6 -168
- package/index.d.ts.map +1 -1
- package/index.js +14 -157
- package/index.js.map +1 -1
- package/index.mjs +6 -130
- package/index.mjs.map +1 -1
- package/internal/builtin-types.d.mts +75 -0
- package/internal/builtin-types.d.mts.map +1 -0
- package/internal/builtin-types.d.ts +75 -0
- package/internal/builtin-types.d.ts.map +1 -0
- package/internal/builtin-types.js +4 -0
- package/internal/builtin-types.js.map +1 -0
- package/internal/builtin-types.mjs +3 -0
- package/internal/builtin-types.mjs.map +1 -0
- package/internal/detect-platform.d.mts +15 -0
- package/internal/detect-platform.d.mts.map +1 -0
- package/internal/detect-platform.d.ts +15 -0
- package/internal/detect-platform.d.ts.map +1 -0
- package/internal/detect-platform.js +162 -0
- package/internal/detect-platform.js.map +1 -0
- package/internal/detect-platform.mjs +157 -0
- package/internal/detect-platform.mjs.map +1 -0
- package/internal/errors.d.mts +3 -0
- package/internal/errors.d.mts.map +1 -0
- package/internal/errors.d.ts +3 -0
- package/internal/errors.d.ts.map +1 -0
- package/internal/errors.js +41 -0
- package/internal/errors.js.map +1 -0
- package/internal/errors.mjs +36 -0
- package/internal/errors.mjs.map +1 -0
- package/internal/headers.d.mts +21 -0
- package/internal/headers.d.mts.map +1 -0
- package/internal/headers.d.ts +21 -0
- package/internal/headers.d.ts.map +1 -0
- package/internal/headers.js +77 -0
- package/internal/headers.js.map +1 -0
- package/internal/headers.mjs +72 -0
- package/internal/headers.mjs.map +1 -0
- package/internal/parse.d.mts +13 -0
- package/internal/parse.d.mts.map +1 -0
- package/internal/parse.d.ts +13 -0
- package/internal/parse.d.ts.map +1 -0
- package/internal/parse.js +36 -0
- package/internal/parse.js.map +1 -0
- package/internal/parse.mjs +32 -0
- package/internal/parse.mjs.map +1 -0
- package/internal/request-options.d.mts +33 -0
- package/internal/request-options.d.mts.map +1 -0
- package/internal/request-options.d.ts +33 -0
- package/internal/request-options.d.ts.map +1 -0
- package/internal/request-options.js +14 -0
- package/internal/request-options.js.map +1 -0
- package/internal/request-options.mjs +10 -0
- package/internal/request-options.mjs.map +1 -0
- package/internal/shim-types.d.mts +28 -0
- package/internal/shim-types.d.ts +28 -0
- package/internal/shims/crypto.d.mts +13 -0
- package/internal/shims/crypto.d.mts.map +1 -0
- package/internal/shims/crypto.d.ts +13 -0
- package/internal/shims/crypto.d.ts.map +1 -0
- package/internal/shims/crypto.js +13 -0
- package/internal/shims/crypto.js.map +1 -0
- package/internal/shims/crypto.mjs +9 -0
- package/internal/shims/crypto.mjs.map +1 -0
- package/internal/shims/file.d.mts +23 -0
- package/internal/shims/file.d.mts.map +1 -0
- package/internal/shims/file.d.ts +23 -0
- package/internal/shims/file.d.ts.map +1 -0
- package/internal/shims/file.js +16 -0
- package/internal/shims/file.js.map +1 -0
- package/internal/shims/file.mjs +12 -0
- package/internal/shims/file.mjs.map +1 -0
- package/internal/shims/getBuiltinModule.d.mts +11 -0
- package/internal/shims/getBuiltinModule.d.mts.map +1 -0
- package/internal/shims/getBuiltinModule.d.ts +11 -0
- package/internal/shims/getBuiltinModule.d.ts.map +1 -0
- package/internal/shims/getBuiltinModule.js +68 -0
- package/internal/shims/getBuiltinModule.js.map +1 -0
- package/internal/shims/getBuiltinModule.mjs +64 -0
- package/internal/shims/getBuiltinModule.mjs.map +1 -0
- package/internal/shims/nullGetBuiltinModule.d.mts +2 -0
- package/internal/shims/nullGetBuiltinModule.d.mts.map +1 -0
- package/internal/shims/nullGetBuiltinModule.d.ts +2 -0
- package/internal/shims/nullGetBuiltinModule.d.ts.map +1 -0
- package/internal/shims/nullGetBuiltinModule.js +5 -0
- package/internal/shims/nullGetBuiltinModule.js.map +1 -0
- package/internal/shims/nullGetBuiltinModule.mjs +2 -0
- package/internal/shims/nullGetBuiltinModule.mjs.map +1 -0
- package/internal/shims.d.mts +20 -0
- package/internal/shims.d.mts.map +1 -0
- package/internal/shims.d.ts +20 -0
- package/internal/shims.d.ts.map +1 -0
- package/internal/shims.js +93 -0
- package/internal/shims.js.map +1 -0
- package/internal/shims.mjs +85 -0
- package/internal/shims.mjs.map +1 -0
- package/internal/to-file.d.mts +46 -0
- package/internal/to-file.d.mts.map +1 -0
- package/internal/to-file.d.ts +46 -0
- package/internal/to-file.d.ts.map +1 -0
- package/internal/to-file.js +91 -0
- package/internal/to-file.js.map +1 -0
- package/internal/to-file.mjs +87 -0
- package/internal/to-file.mjs.map +1 -0
- package/internal/types.d.mts +68 -0
- package/internal/types.d.mts.map +1 -0
- package/internal/types.d.ts +68 -0
- package/internal/types.d.ts.map +1 -0
- package/internal/types.js +4 -0
- package/internal/types.js.map +1 -0
- package/internal/types.mjs +3 -0
- package/internal/types.mjs.map +1 -0
- package/internal/uploads.d.mts +44 -0
- package/internal/uploads.d.mts.map +1 -0
- package/internal/uploads.d.ts +44 -0
- package/internal/uploads.d.ts.map +1 -0
- package/internal/uploads.js +131 -0
- package/internal/uploads.js.map +1 -0
- package/internal/uploads.mjs +122 -0
- package/internal/uploads.mjs.map +1 -0
- package/internal/utils/base64.d.mts +3 -0
- package/internal/utils/base64.d.mts.map +1 -0
- package/internal/utils/base64.d.ts +3 -0
- package/internal/utils/base64.d.ts.map +1 -0
- package/internal/utils/base64.js +33 -0
- package/internal/utils/base64.js.map +1 -0
- package/internal/utils/base64.mjs +28 -0
- package/internal/utils/base64.mjs.map +1 -0
- package/internal/utils/env.d.mts +9 -0
- package/internal/utils/env.d.mts.map +1 -0
- package/internal/utils/env.d.ts +9 -0
- package/internal/utils/env.d.ts.map +1 -0
- package/internal/utils/env.js +22 -0
- package/internal/utils/env.js.map +1 -0
- package/internal/utils/env.mjs +18 -0
- package/internal/utils/env.mjs.map +1 -0
- package/internal/utils/log.d.mts +38 -0
- package/internal/utils/log.d.mts.map +1 -0
- package/internal/utils/log.d.ts +38 -0
- package/internal/utils/log.d.ts.map +1 -0
- package/internal/utils/log.js +85 -0
- package/internal/utils/log.js.map +1 -0
- package/internal/utils/log.mjs +79 -0
- package/internal/utils/log.mjs.map +1 -0
- package/internal/utils/path.d.mts +15 -0
- package/internal/utils/path.d.mts.map +1 -0
- package/internal/utils/path.d.ts +15 -0
- package/internal/utils/path.d.ts.map +1 -0
- package/internal/utils/path.js +58 -0
- package/internal/utils/path.js.map +1 -0
- package/internal/utils/path.mjs +53 -0
- package/internal/utils/path.mjs.map +1 -0
- package/internal/utils/sleep.d.mts +2 -0
- package/internal/utils/sleep.d.mts.map +1 -0
- package/internal/utils/sleep.d.ts +2 -0
- package/internal/utils/sleep.d.ts.map +1 -0
- package/internal/utils/sleep.js +7 -0
- package/internal/utils/sleep.js.map +1 -0
- package/internal/utils/sleep.mjs +3 -0
- package/internal/utils/sleep.mjs.map +1 -0
- package/internal/utils/uuid.d.mts +5 -0
- package/internal/utils/uuid.d.mts.map +1 -0
- package/internal/utils/uuid.d.ts +5 -0
- package/internal/utils/uuid.d.ts.map +1 -0
- package/internal/utils/uuid.js +20 -0
- package/internal/utils/uuid.js.map +1 -0
- package/internal/utils/uuid.mjs +16 -0
- package/internal/utils/uuid.mjs.map +1 -0
- package/internal/utils/values.d.mts +16 -0
- package/internal/utils/values.d.mts.map +1 -0
- package/internal/utils/values.d.ts +16 -0
- package/internal/utils/values.d.ts.map +1 -0
- package/internal/utils/values.js +109 -0
- package/internal/utils/values.js.map +1 -0
- package/internal/utils/values.mjs +92 -0
- package/internal/utils/values.mjs.map +1 -0
- package/internal/utils.d.mts +7 -0
- package/internal/utils.d.mts.map +1 -0
- package/internal/utils.d.ts +7 -0
- package/internal/utils.d.ts.map +1 -0
- package/{_shims/auto/runtime-bun.js → internal/utils.js} +8 -5
- package/internal/utils.js.map +1 -0
- package/internal/utils.mjs +8 -0
- package/internal/utils.mjs.map +1 -0
- package/lib/polling.d.mts +48 -0
- package/lib/polling.d.mts.map +1 -0
- package/lib/polling.d.ts.map +1 -1
- package/lib/polling.js +0 -1
- package/lib/polling.js.map +1 -1
- package/lib/polling.mjs +0 -1
- package/lib/polling.mjs.map +1 -1
- package/package.json +126 -63
- package/pagination.d.mts +2 -0
- package/pagination.d.mts.map +1 -0
- package/pagination.d.ts +1 -29
- package/pagination.d.ts.map +1 -1
- package/pagination.js +16 -42
- package/pagination.js.map +1 -1
- package/pagination.mjs +1 -40
- package/pagination.mjs.map +1 -1
- package/resource.d.mts +2 -0
- package/resource.d.mts.map +1 -0
- package/resource.d.ts +1 -5
- package/resource.d.ts.map +1 -1
- package/resource.js +16 -8
- package/resource.js.map +1 -1
- package/resource.mjs +1 -6
- package/resource.mjs.map +1 -1
- package/resources/embeddings.d.mts +46 -0
- package/resources/embeddings.d.mts.map +1 -0
- package/resources/embeddings.d.ts +4 -3
- package/resources/embeddings.d.ts.map +1 -1
- package/resources/embeddings.js +1 -1
- package/resources/embeddings.js.map +1 -1
- package/resources/embeddings.mjs +1 -1
- package/resources/embeddings.mjs.map +1 -1
- package/resources/extractions/content.d.mts +34 -0
- package/resources/extractions/content.d.mts.map +1 -0
- package/resources/extractions/content.d.ts +4 -3
- package/resources/extractions/content.d.ts.map +1 -1
- package/resources/extractions/content.js +1 -1
- package/resources/extractions/content.js.map +1 -1
- package/resources/extractions/content.mjs +1 -1
- package/resources/extractions/content.mjs.map +1 -1
- package/resources/extractions/extractions.d.mts +18 -0
- package/resources/extractions/extractions.d.mts.map +1 -0
- package/resources/extractions/extractions.d.ts +1 -1
- package/resources/extractions/extractions.d.ts.map +1 -1
- package/resources/extractions/extractions.js +1 -1
- package/resources/extractions/extractions.js.map +1 -1
- package/resources/extractions/extractions.mjs +1 -1
- package/resources/extractions/index.d.mts +5 -0
- package/resources/extractions/index.d.mts.map +1 -0
- package/resources/extractions/index.d.ts.map +1 -1
- package/resources/extractions/jobs.d.mts +85 -0
- package/resources/extractions/jobs.d.mts.map +1 -0
- package/resources/extractions/jobs.d.ts +5 -4
- package/resources/extractions/jobs.d.ts.map +1 -1
- package/resources/extractions/jobs.js +4 -3
- package/resources/extractions/jobs.js.map +1 -1
- package/resources/extractions/jobs.mjs +4 -3
- package/resources/extractions/jobs.mjs.map +1 -1
- package/resources/extractions/schema.d.mts +86 -0
- package/resources/extractions/schema.d.mts.map +1 -0
- package/resources/extractions/schema.d.ts +6 -5
- package/resources/extractions/schema.d.ts.map +1 -1
- package/resources/extractions/schema.js +1 -1
- package/resources/extractions/schema.js.map +1 -1
- package/resources/extractions/schema.mjs +1 -1
- package/resources/extractions/schema.mjs.map +1 -1
- package/resources/extractions.d.mts +2 -0
- package/resources/extractions.d.mts.map +1 -0
- package/resources/extractions.d.ts.map +1 -1
- package/resources/files.d.mts +125 -0
- package/resources/files.d.mts.map +1 -0
- package/resources/files.d.ts +16 -16
- package/resources/files.d.ts.map +1 -1
- package/resources/files.js +24 -46
- package/resources/files.js.map +1 -1
- package/resources/files.mjs +23 -21
- package/resources/files.mjs.map +1 -1
- package/resources/index.d.mts +8 -0
- package/resources/index.d.mts.map +1 -0
- package/resources/index.d.ts +2 -2
- package/resources/index.d.ts.map +1 -1
- package/resources/index.js +1 -3
- package/resources/index.js.map +1 -1
- package/resources/index.mjs +2 -2
- package/resources/index.mjs.map +1 -1
- package/resources/parsing/index.d.mts +3 -0
- package/resources/parsing/index.d.mts.map +1 -0
- package/resources/parsing/index.d.ts +1 -1
- package/resources/parsing/index.d.ts.map +1 -1
- package/resources/parsing/index.js +1 -2
- package/resources/parsing/index.js.map +1 -1
- package/resources/parsing/index.mjs +1 -1
- package/resources/parsing/index.mjs.map +1 -1
- package/resources/parsing/jobs.d.mts +289 -0
- package/resources/parsing/jobs.d.mts.map +1 -0
- package/resources/parsing/jobs.d.ts +16 -17
- package/resources/parsing/jobs.d.ts.map +1 -1
- package/resources/parsing/jobs.js +18 -18
- package/resources/parsing/jobs.js.map +1 -1
- package/resources/parsing/jobs.mjs +17 -16
- package/resources/parsing/jobs.mjs.map +1 -1
- package/resources/parsing/parsing.d.mts +10 -0
- package/resources/parsing/parsing.d.mts.map +1 -0
- package/resources/parsing/parsing.d.ts +2 -2
- package/resources/parsing/parsing.d.ts.map +1 -1
- package/resources/parsing/parsing.js +1 -2
- package/resources/parsing/parsing.js.map +1 -1
- package/resources/parsing/parsing.mjs +2 -3
- package/resources/parsing/parsing.mjs.map +1 -1
- package/resources/parsing.d.mts +2 -0
- package/resources/parsing.d.mts.map +1 -0
- package/resources/parsing.d.ts.map +1 -1
- package/resources/shared.d.mts +49 -0
- package/resources/shared.d.mts.map +1 -0
- package/resources/top-level.d.mts +184 -0
- package/resources/top-level.d.mts.map +1 -0
- package/resources/top-level.d.ts.map +1 -1
- package/resources/vector-stores/files.d.mts +303 -0
- package/resources/vector-stores/files.d.mts.map +1 -0
- package/resources/vector-stores/files.d.ts +27 -16
- package/resources/vector-stores/files.d.ts.map +1 -1
- package/resources/vector-stores/files.js +23 -23
- package/resources/vector-stores/files.js.map +1 -1
- package/resources/vector-stores/files.mjs +22 -21
- package/resources/vector-stores/files.mjs.map +1 -1
- package/resources/vector-stores/index.d.mts +3 -0
- package/resources/vector-stores/index.d.mts.map +1 -0
- package/resources/vector-stores/index.d.ts +2 -2
- package/resources/vector-stores/index.d.ts.map +1 -1
- package/resources/vector-stores/index.js +1 -3
- package/resources/vector-stores/index.js.map +1 -1
- package/resources/vector-stores/index.mjs +2 -2
- package/resources/vector-stores/index.mjs.map +1 -1
- package/resources/vector-stores/vector-stores.d.mts +428 -0
- package/resources/vector-stores/vector-stores.d.mts.map +1 -0
- package/resources/vector-stores/vector-stores.d.ts +15 -16
- package/resources/vector-stores/vector-stores.d.ts.map +1 -1
- package/resources/vector-stores/vector-stores.js +18 -19
- package/resources/vector-stores/vector-stores.js.map +1 -1
- package/resources/vector-stores/vector-stores.mjs +18 -18
- package/resources/vector-stores/vector-stores.mjs.map +1 -1
- package/resources/vector-stores.d.mts +2 -0
- package/resources/vector-stores.d.mts.map +1 -0
- package/resources/vector-stores.d.ts.map +1 -1
- package/resources.d.mts +2 -0
- package/resources.d.mts.map +1 -0
- package/resources.d.ts.map +1 -1
- package/src/api-promise.ts +2 -0
- package/src/client.ts +860 -0
- package/src/core/README.md +3 -0
- package/src/core/api-promise.ts +92 -0
- package/src/core/error.ts +130 -0
- package/src/core/pagination.ts +183 -0
- package/src/core/resource.ts +11 -0
- package/src/core/uploads.ts +2 -0
- package/src/error.ts +2 -130
- package/src/index.ts +6 -330
- package/src/internal/README.md +3 -0
- package/src/internal/builtin-types.ts +93 -0
- package/src/internal/detect-platform.ts +196 -0
- package/src/internal/errors.ts +33 -0
- package/src/internal/headers.ts +96 -0
- package/src/internal/parse.ts +50 -0
- package/src/internal/request-options.ts +37 -0
- package/src/internal/shim-types.d.ts +28 -0
- package/src/internal/shims/crypto.ts +18 -0
- package/src/internal/shims/file.ts +32 -0
- package/src/internal/shims/getBuiltinModule.ts +64 -0
- package/src/internal/shims/nullGetBuiltinModule.ts +1 -0
- package/src/internal/shims.ts +107 -0
- package/src/internal/to-file.ts +152 -0
- package/src/internal/types.ts +92 -0
- package/src/internal/uploads.ts +175 -0
- package/src/internal/utils/base64.ts +37 -0
- package/src/internal/utils/env.ts +18 -0
- package/src/internal/utils/log.ts +126 -0
- package/src/internal/utils/path.ts +65 -0
- package/src/internal/utils/sleep.ts +3 -0
- package/src/internal/utils/uuid.ts +19 -0
- package/src/internal/utils/values.ts +102 -0
- package/src/internal/utils.ts +8 -0
- package/src/lib/polling.ts +0 -1
- package/src/pagination.ts +2 -82
- package/src/resource.ts +2 -11
- package/src/resources/embeddings.ts +5 -4
- package/src/resources/extractions/content.ts +4 -3
- package/src/resources/extractions/extractions.ts +1 -1
- package/src/resources/extractions/jobs.ts +7 -5
- package/src/resources/extractions/schema.ts +6 -5
- package/src/resources/files.ts +30 -34
- package/src/resources/index.ts +2 -2
- package/src/resources/parsing/index.ts +1 -1
- package/src/resources/parsing/jobs.ts +23 -32
- package/src/resources/parsing/parsing.ts +2 -3
- package/src/resources/vector-stores/files.ts +51 -49
- package/src/resources/vector-stores/index.ts +4 -2
- package/src/resources/vector-stores/vector-stores.ts +27 -38
- package/src/tsconfig.json +2 -2
- package/src/uploads.ts +2 -255
- package/src/version.ts +1 -1
- package/uploads.d.mts +2 -0
- package/uploads.d.mts.map +1 -0
- package/uploads.d.ts +1 -74
- package/uploads.d.ts.map +1 -1
- package/uploads.js +16 -168
- package/uploads.js.map +1 -1
- package/uploads.mjs +1 -157
- package/uploads.mjs.map +1 -1
- package/version.d.mts +2 -0
- package/version.d.mts.map +1 -0
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
- package/_shims/MultipartBody.d.ts +0 -9
- package/_shims/MultipartBody.d.ts.map +0 -1
- package/_shims/MultipartBody.js +0 -16
- package/_shims/MultipartBody.js.map +0 -1
- package/_shims/MultipartBody.mjs +0 -12
- package/_shims/MultipartBody.mjs.map +0 -1
- package/_shims/README.md +0 -46
- package/_shims/auto/runtime-bun.d.ts +0 -5
- package/_shims/auto/runtime-bun.d.ts.map +0 -1
- package/_shims/auto/runtime-bun.js.map +0 -1
- package/_shims/auto/runtime-bun.mjs +0 -2
- package/_shims/auto/runtime-bun.mjs.map +0 -1
- package/_shims/auto/runtime-node.d.ts +0 -5
- package/_shims/auto/runtime-node.d.ts.map +0 -1
- package/_shims/auto/runtime-node.js +0 -21
- package/_shims/auto/runtime-node.js.map +0 -1
- package/_shims/auto/runtime-node.mjs +0 -2
- package/_shims/auto/runtime-node.mjs.map +0 -1
- package/_shims/auto/runtime.d.ts +0 -5
- package/_shims/auto/runtime.d.ts.map +0 -1
- package/_shims/auto/runtime.js.map +0 -1
- package/_shims/auto/runtime.mjs +0 -2
- package/_shims/auto/runtime.mjs.map +0 -1
- package/_shims/auto/types-node.d.ts +0 -5
- package/_shims/auto/types-node.d.ts.map +0 -1
- package/_shims/auto/types-node.js +0 -21
- package/_shims/auto/types-node.js.map +0 -1
- package/_shims/auto/types-node.mjs +0 -2
- package/_shims/auto/types-node.mjs.map +0 -1
- package/_shims/auto/types.d.ts +0 -101
- package/_shims/auto/types.js +0 -3
- package/_shims/auto/types.mjs +0 -3
- package/_shims/bun-runtime.d.ts +0 -6
- package/_shims/bun-runtime.d.ts.map +0 -1
- package/_shims/bun-runtime.js +0 -14
- package/_shims/bun-runtime.js.map +0 -1
- package/_shims/bun-runtime.mjs +0 -10
- package/_shims/bun-runtime.mjs.map +0 -1
- package/_shims/index.d.ts +0 -83
- package/_shims/index.js +0 -17
- package/_shims/index.mjs +0 -11
- package/_shims/manual-types.d.ts +0 -12
- package/_shims/manual-types.js +0 -3
- package/_shims/manual-types.mjs +0 -3
- package/_shims/node-runtime.d.ts +0 -3
- package/_shims/node-runtime.d.ts.map +0 -1
- package/_shims/node-runtime.js +0 -89
- package/_shims/node-runtime.js.map +0 -1
- package/_shims/node-runtime.mjs +0 -56
- package/_shims/node-runtime.mjs.map +0 -1
- package/_shims/node-types.d.ts +0 -42
- package/_shims/node-types.js +0 -3
- package/_shims/node-types.mjs +0 -3
- package/_shims/registry.d.ts +0 -37
- package/_shims/registry.d.ts.map +0 -1
- package/_shims/registry.js +0 -41
- package/_shims/registry.js.map +0 -1
- package/_shims/registry.mjs +0 -37
- package/_shims/registry.mjs.map +0 -1
- package/_shims/web-runtime.d.ts +0 -5
- package/_shims/web-runtime.d.ts.map +0 -1
- package/_shims/web-runtime.js +0 -78
- package/_shims/web-runtime.js.map +0 -1
- package/_shims/web-runtime.mjs +0 -71
- package/_shims/web-runtime.mjs.map +0 -1
- package/_shims/web-types.d.ts +0 -83
- package/_shims/web-types.js +0 -3
- package/_shims/web-types.mjs +0 -3
- package/core.d.ts +0 -252
- package/core.d.ts.map +0 -1
- package/core.js +0 -917
- package/core.js.map +0 -1
- package/core.mjs +0 -885
- package/core.mjs.map +0 -1
- package/shims/node.d.ts +0 -30
- package/shims/node.d.ts.map +0 -1
- package/shims/node.js +0 -31
- package/shims/node.js.map +0 -1
- package/shims/node.mjs +0 -5
- package/shims/node.mjs.map +0 -1
- package/shims/web.d.ts +0 -26
- package/shims/web.d.ts.map +0 -1
- package/shims/web.js +0 -31
- package/shims/web.js.map +0 -1
- package/shims/web.mjs +0 -5
- package/shims/web.mjs.map +0 -1
- package/src/_shims/MultipartBody.ts +0 -9
- package/src/_shims/README.md +0 -46
- package/src/_shims/auto/runtime-bun.ts +0 -4
- package/src/_shims/auto/runtime-node.ts +0 -4
- package/src/_shims/auto/runtime.ts +0 -4
- package/src/_shims/auto/types-node.ts +0 -4
- package/src/_shims/auto/types.d.ts +0 -101
- package/src/_shims/auto/types.js +0 -3
- package/src/_shims/auto/types.mjs +0 -3
- package/src/_shims/bun-runtime.ts +0 -14
- package/src/_shims/index.d.ts +0 -83
- package/src/_shims/index.js +0 -17
- package/src/_shims/index.mjs +0 -11
- package/src/_shims/manual-types.d.ts +0 -12
- package/src/_shims/manual-types.js +0 -3
- package/src/_shims/manual-types.mjs +0 -3
- package/src/_shims/node-runtime.ts +0 -81
- package/src/_shims/node-types.d.ts +0 -42
- package/src/_shims/node-types.js +0 -3
- package/src/_shims/node-types.mjs +0 -3
- package/src/_shims/registry.ts +0 -67
- package/src/_shims/web-runtime.ts +0 -103
- package/src/_shims/web-types.d.ts +0 -83
- package/src/_shims/web-types.js +0 -3
- package/src/_shims/web-types.mjs +0 -3
- package/src/core.ts +0 -1227
- package/src/shims/node.ts +0 -50
- package/src/shims/web.ts +0 -50
package/src/core.ts
DELETED
@@ -1,1227 +0,0 @@
|
|
1
|
-
import { VERSION } from './version';
|
2
|
-
import {
|
3
|
-
MixedbreadError,
|
4
|
-
APIError,
|
5
|
-
APIConnectionError,
|
6
|
-
APIConnectionTimeoutError,
|
7
|
-
APIUserAbortError,
|
8
|
-
} from './error';
|
9
|
-
import {
|
10
|
-
kind as shimsKind,
|
11
|
-
type Readable,
|
12
|
-
getDefaultAgent,
|
13
|
-
type Agent,
|
14
|
-
fetch,
|
15
|
-
type RequestInfo,
|
16
|
-
type RequestInit,
|
17
|
-
type Response,
|
18
|
-
type HeadersInit,
|
19
|
-
init,
|
20
|
-
} from './_shims/index';
|
21
|
-
|
22
|
-
// try running side effects outside of _shims/index to workaround https://github.com/vercel/next.js/issues/76881
|
23
|
-
init();
|
24
|
-
|
25
|
-
export { type Response };
|
26
|
-
import { BlobLike, isBlobLike, isMultipartBody } from './uploads';
|
27
|
-
export {
|
28
|
-
maybeMultipartFormRequestOptions,
|
29
|
-
multipartFormRequestOptions,
|
30
|
-
createForm,
|
31
|
-
type Uploadable,
|
32
|
-
} from './uploads';
|
33
|
-
|
34
|
-
export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
|
35
|
-
|
36
|
-
/**
|
37
|
-
* An alias to the builtin `Array` type so we can
|
38
|
-
* easily alias it in import statements if there are name clashes.
|
39
|
-
*/
|
40
|
-
type _Array<T> = Array<T>;
|
41
|
-
|
42
|
-
/**
|
43
|
-
* An alias to the builtin `Record` type so we can
|
44
|
-
* easily alias it in import statements if there are name clashes.
|
45
|
-
*/
|
46
|
-
type _Record<K extends keyof any, T> = Record<K, T>;
|
47
|
-
|
48
|
-
export type { _Array as Array, _Record as Record };
|
49
|
-
|
50
|
-
type PromiseOrValue<T> = T | Promise<T>;
|
51
|
-
|
52
|
-
type APIResponseProps = {
|
53
|
-
response: Response;
|
54
|
-
options: FinalRequestOptions;
|
55
|
-
controller: AbortController;
|
56
|
-
};
|
57
|
-
|
58
|
-
async function defaultParseResponse<T>(props: APIResponseProps): Promise<T> {
|
59
|
-
const { response } = props;
|
60
|
-
// fetch refuses to read the body when the status code is 204.
|
61
|
-
if (response.status === 204) {
|
62
|
-
return null as T;
|
63
|
-
}
|
64
|
-
|
65
|
-
if (props.options.__binaryResponse) {
|
66
|
-
return response as unknown as T;
|
67
|
-
}
|
68
|
-
|
69
|
-
const contentType = response.headers.get('content-type');
|
70
|
-
const mediaType = contentType?.split(';')[0]?.trim();
|
71
|
-
const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
|
72
|
-
if (isJSON) {
|
73
|
-
const json = await response.json();
|
74
|
-
|
75
|
-
debug('response', response.status, response.url, response.headers, json);
|
76
|
-
|
77
|
-
return json as T;
|
78
|
-
}
|
79
|
-
|
80
|
-
const text = await response.text();
|
81
|
-
debug('response', response.status, response.url, response.headers, text);
|
82
|
-
|
83
|
-
// TODO handle blob, arraybuffer, other content types, etc.
|
84
|
-
return text as unknown as T;
|
85
|
-
}
|
86
|
-
|
87
|
-
/**
|
88
|
-
* A subclass of `Promise` providing additional helper methods
|
89
|
-
* for interacting with the SDK.
|
90
|
-
*/
|
91
|
-
export class APIPromise<T> extends Promise<T> {
|
92
|
-
private parsedPromise: Promise<T> | undefined;
|
93
|
-
|
94
|
-
constructor(
|
95
|
-
private responsePromise: Promise<APIResponseProps>,
|
96
|
-
private parseResponse: (props: APIResponseProps) => PromiseOrValue<T> = defaultParseResponse,
|
97
|
-
) {
|
98
|
-
super((resolve) => {
|
99
|
-
// this is maybe a bit weird but this has to be a no-op to not implicitly
|
100
|
-
// parse the response body; instead .then, .catch, .finally are overridden
|
101
|
-
// to parse the response
|
102
|
-
resolve(null as any);
|
103
|
-
});
|
104
|
-
}
|
105
|
-
|
106
|
-
_thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U> {
|
107
|
-
return new APIPromise(this.responsePromise, async (props) =>
|
108
|
-
transform(await this.parseResponse(props), props),
|
109
|
-
);
|
110
|
-
}
|
111
|
-
|
112
|
-
/**
|
113
|
-
* Gets the raw `Response` instance instead of parsing the response
|
114
|
-
* data.
|
115
|
-
*
|
116
|
-
* If you want to parse the response body but still get the `Response`
|
117
|
-
* instance, you can use {@link withResponse()}.
|
118
|
-
*
|
119
|
-
* 👋 Getting the wrong TypeScript type for `Response`?
|
120
|
-
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
121
|
-
* or add one of these imports before your first `import … from '@mixedbread/sdk'`:
|
122
|
-
* - `import '@mixedbread/sdk/shims/node'` (if you're running on Node)
|
123
|
-
* - `import '@mixedbread/sdk/shims/web'` (otherwise)
|
124
|
-
*/
|
125
|
-
asResponse(): Promise<Response> {
|
126
|
-
return this.responsePromise.then((p) => p.response);
|
127
|
-
}
|
128
|
-
/**
|
129
|
-
* Gets the parsed response data and the raw `Response` instance.
|
130
|
-
*
|
131
|
-
* If you just want to get the raw `Response` instance without parsing it,
|
132
|
-
* you can use {@link asResponse()}.
|
133
|
-
*
|
134
|
-
*
|
135
|
-
* 👋 Getting the wrong TypeScript type for `Response`?
|
136
|
-
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
137
|
-
* or add one of these imports before your first `import … from '@mixedbread/sdk'`:
|
138
|
-
* - `import '@mixedbread/sdk/shims/node'` (if you're running on Node)
|
139
|
-
* - `import '@mixedbread/sdk/shims/web'` (otherwise)
|
140
|
-
*/
|
141
|
-
async withResponse(): Promise<{ data: T; response: Response }> {
|
142
|
-
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
143
|
-
return { data, response };
|
144
|
-
}
|
145
|
-
|
146
|
-
private parse(): Promise<T> {
|
147
|
-
if (!this.parsedPromise) {
|
148
|
-
this.parsedPromise = this.responsePromise.then(this.parseResponse);
|
149
|
-
}
|
150
|
-
return this.parsedPromise;
|
151
|
-
}
|
152
|
-
|
153
|
-
override then<TResult1 = T, TResult2 = never>(
|
154
|
-
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
|
155
|
-
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
|
156
|
-
): Promise<TResult1 | TResult2> {
|
157
|
-
return this.parse().then(onfulfilled, onrejected);
|
158
|
-
}
|
159
|
-
|
160
|
-
override catch<TResult = never>(
|
161
|
-
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,
|
162
|
-
): Promise<T | TResult> {
|
163
|
-
return this.parse().catch(onrejected);
|
164
|
-
}
|
165
|
-
|
166
|
-
override finally(onfinally?: (() => void) | undefined | null): Promise<T> {
|
167
|
-
return this.parse().finally(onfinally);
|
168
|
-
}
|
169
|
-
}
|
170
|
-
|
171
|
-
export abstract class APIClient {
|
172
|
-
baseURL: string;
|
173
|
-
maxRetries: number;
|
174
|
-
timeout: number;
|
175
|
-
httpAgent: Agent | undefined;
|
176
|
-
|
177
|
-
private fetch: Fetch;
|
178
|
-
protected idempotencyHeader?: string;
|
179
|
-
|
180
|
-
constructor({
|
181
|
-
baseURL,
|
182
|
-
maxRetries = 2,
|
183
|
-
timeout = 60000, // 1 minute
|
184
|
-
httpAgent,
|
185
|
-
fetch: overriddenFetch,
|
186
|
-
}: {
|
187
|
-
baseURL: string;
|
188
|
-
maxRetries?: number | undefined;
|
189
|
-
timeout: number | undefined;
|
190
|
-
httpAgent: Agent | undefined;
|
191
|
-
fetch: Fetch | undefined;
|
192
|
-
}) {
|
193
|
-
this.baseURL = baseURL;
|
194
|
-
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
|
195
|
-
this.timeout = validatePositiveInteger('timeout', timeout);
|
196
|
-
this.httpAgent = httpAgent;
|
197
|
-
|
198
|
-
this.fetch = overriddenFetch ?? fetch;
|
199
|
-
}
|
200
|
-
|
201
|
-
protected authHeaders(opts: FinalRequestOptions): Headers {
|
202
|
-
return {};
|
203
|
-
}
|
204
|
-
|
205
|
-
/**
|
206
|
-
* Override this to add your own default headers, for example:
|
207
|
-
*
|
208
|
-
* {
|
209
|
-
* ...super.defaultHeaders(),
|
210
|
-
* Authorization: 'Bearer 123',
|
211
|
-
* }
|
212
|
-
*/
|
213
|
-
protected defaultHeaders(opts: FinalRequestOptions): Headers {
|
214
|
-
return {
|
215
|
-
Accept: 'application/json',
|
216
|
-
'Content-Type': 'application/json',
|
217
|
-
'User-Agent': this.getUserAgent(),
|
218
|
-
...getPlatformHeaders(),
|
219
|
-
...this.authHeaders(opts),
|
220
|
-
};
|
221
|
-
}
|
222
|
-
|
223
|
-
protected abstract defaultQuery(): DefaultQuery | undefined;
|
224
|
-
|
225
|
-
/**
|
226
|
-
* Override this to add your own headers validation:
|
227
|
-
*/
|
228
|
-
protected validateHeaders(headers: Headers, customHeaders: Headers) {}
|
229
|
-
|
230
|
-
protected defaultIdempotencyKey(): string {
|
231
|
-
return `stainless-node-retry-${uuid4()}`;
|
232
|
-
}
|
233
|
-
|
234
|
-
get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
|
235
|
-
return this.methodRequest('get', path, opts);
|
236
|
-
}
|
237
|
-
|
238
|
-
post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
|
239
|
-
return this.methodRequest('post', path, opts);
|
240
|
-
}
|
241
|
-
|
242
|
-
patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
|
243
|
-
return this.methodRequest('patch', path, opts);
|
244
|
-
}
|
245
|
-
|
246
|
-
put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
|
247
|
-
return this.methodRequest('put', path, opts);
|
248
|
-
}
|
249
|
-
|
250
|
-
delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
|
251
|
-
return this.methodRequest('delete', path, opts);
|
252
|
-
}
|
253
|
-
|
254
|
-
private methodRequest<Req, Rsp>(
|
255
|
-
method: HTTPMethod,
|
256
|
-
path: string,
|
257
|
-
opts?: PromiseOrValue<RequestOptions<Req>>,
|
258
|
-
): APIPromise<Rsp> {
|
259
|
-
return this.request(
|
260
|
-
Promise.resolve(opts).then(async (opts) => {
|
261
|
-
const body =
|
262
|
-
opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())
|
263
|
-
: opts?.body instanceof DataView ? opts.body
|
264
|
-
: opts?.body instanceof ArrayBuffer ? new DataView(opts.body)
|
265
|
-
: opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)
|
266
|
-
: opts?.body;
|
267
|
-
return { method, path, ...opts, body };
|
268
|
-
}),
|
269
|
-
);
|
270
|
-
}
|
271
|
-
|
272
|
-
getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
|
273
|
-
path: string,
|
274
|
-
Page: new (...args: any[]) => PageClass,
|
275
|
-
opts?: RequestOptions<any>,
|
276
|
-
): PagePromise<PageClass, Item> {
|
277
|
-
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
278
|
-
}
|
279
|
-
|
280
|
-
private calculateContentLength(body: unknown): string | null {
|
281
|
-
if (typeof body === 'string') {
|
282
|
-
if (typeof Buffer !== 'undefined') {
|
283
|
-
return Buffer.byteLength(body, 'utf8').toString();
|
284
|
-
}
|
285
|
-
|
286
|
-
if (typeof TextEncoder !== 'undefined') {
|
287
|
-
const encoder = new TextEncoder();
|
288
|
-
const encoded = encoder.encode(body);
|
289
|
-
return encoded.length.toString();
|
290
|
-
}
|
291
|
-
} else if (ArrayBuffer.isView(body)) {
|
292
|
-
return body.byteLength.toString();
|
293
|
-
}
|
294
|
-
|
295
|
-
return null;
|
296
|
-
}
|
297
|
-
|
298
|
-
buildRequest<Req>(
|
299
|
-
options: FinalRequestOptions<Req>,
|
300
|
-
{ retryCount = 0 }: { retryCount?: number } = {},
|
301
|
-
): { req: RequestInit; url: string; timeout: number } {
|
302
|
-
options = { ...options };
|
303
|
-
const { method, path, query, headers: headers = {} } = options;
|
304
|
-
|
305
|
-
const body =
|
306
|
-
ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
|
307
|
-
options.body
|
308
|
-
: isMultipartBody(options.body) ? options.body.body
|
309
|
-
: options.body ? JSON.stringify(options.body, null, 2)
|
310
|
-
: null;
|
311
|
-
const contentLength = this.calculateContentLength(body);
|
312
|
-
|
313
|
-
const url = this.buildURL(path!, query);
|
314
|
-
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
|
315
|
-
options.timeout = options.timeout ?? this.timeout;
|
316
|
-
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
|
317
|
-
const minAgentTimeout = options.timeout + 1000;
|
318
|
-
if (
|
319
|
-
typeof (httpAgent as any)?.options?.timeout === 'number' &&
|
320
|
-
minAgentTimeout > ((httpAgent as any).options.timeout ?? 0)
|
321
|
-
) {
|
322
|
-
// Allow any given request to bump our agent active socket timeout.
|
323
|
-
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
|
324
|
-
// and without mutating agent we would need to create more of them.
|
325
|
-
// This tradeoff optimizes for performance.
|
326
|
-
(httpAgent as any).options.timeout = minAgentTimeout;
|
327
|
-
}
|
328
|
-
|
329
|
-
if (this.idempotencyHeader && method !== 'get') {
|
330
|
-
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
|
331
|
-
headers[this.idempotencyHeader] = options.idempotencyKey;
|
332
|
-
}
|
333
|
-
|
334
|
-
const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });
|
335
|
-
|
336
|
-
const req: RequestInit = {
|
337
|
-
method,
|
338
|
-
...(body && { body: body as any }),
|
339
|
-
headers: reqHeaders,
|
340
|
-
...(httpAgent && { agent: httpAgent }),
|
341
|
-
// @ts-ignore node-fetch uses a custom AbortSignal type that is
|
342
|
-
// not compatible with standard web types
|
343
|
-
signal: options.signal ?? null,
|
344
|
-
};
|
345
|
-
|
346
|
-
return { req, url, timeout: options.timeout };
|
347
|
-
}
|
348
|
-
|
349
|
-
private buildHeaders({
|
350
|
-
options,
|
351
|
-
headers,
|
352
|
-
contentLength,
|
353
|
-
retryCount,
|
354
|
-
}: {
|
355
|
-
options: FinalRequestOptions;
|
356
|
-
headers: Record<string, string | null | undefined>;
|
357
|
-
contentLength: string | null | undefined;
|
358
|
-
retryCount: number;
|
359
|
-
}): Record<string, string> {
|
360
|
-
const reqHeaders: Record<string, string> = {};
|
361
|
-
if (contentLength) {
|
362
|
-
reqHeaders['content-length'] = contentLength;
|
363
|
-
}
|
364
|
-
|
365
|
-
const defaultHeaders = this.defaultHeaders(options);
|
366
|
-
applyHeadersMut(reqHeaders, defaultHeaders);
|
367
|
-
applyHeadersMut(reqHeaders, headers);
|
368
|
-
|
369
|
-
// let builtin fetch set the Content-Type for multipart bodies
|
370
|
-
if (isMultipartBody(options.body) && shimsKind !== 'node') {
|
371
|
-
delete reqHeaders['content-type'];
|
372
|
-
}
|
373
|
-
|
374
|
-
// Don't set theses headers if they were already set or removed through default headers or by the caller.
|
375
|
-
// We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account
|
376
|
-
// for the removal case.
|
377
|
-
if (
|
378
|
-
getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
|
379
|
-
getHeader(headers, 'x-stainless-retry-count') === undefined
|
380
|
-
) {
|
381
|
-
reqHeaders['x-stainless-retry-count'] = String(retryCount);
|
382
|
-
}
|
383
|
-
if (
|
384
|
-
getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&
|
385
|
-
getHeader(headers, 'x-stainless-timeout') === undefined &&
|
386
|
-
options.timeout
|
387
|
-
) {
|
388
|
-
reqHeaders['x-stainless-timeout'] = String(Math.trunc(options.timeout / 1000));
|
389
|
-
}
|
390
|
-
|
391
|
-
this.validateHeaders(reqHeaders, headers);
|
392
|
-
|
393
|
-
return reqHeaders;
|
394
|
-
}
|
395
|
-
|
396
|
-
/**
|
397
|
-
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
398
|
-
*/
|
399
|
-
protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}
|
400
|
-
|
401
|
-
/**
|
402
|
-
* Used as a callback for mutating the given `RequestInit` object.
|
403
|
-
*
|
404
|
-
* This is useful for cases where you want to add certain headers based off of
|
405
|
-
* the request properties, e.g. `method` or `url`.
|
406
|
-
*/
|
407
|
-
protected async prepareRequest(
|
408
|
-
request: RequestInit,
|
409
|
-
{ url, options }: { url: string; options: FinalRequestOptions },
|
410
|
-
): Promise<void> {}
|
411
|
-
|
412
|
-
protected parseHeaders(headers: HeadersInit | null | undefined): Record<string, string> {
|
413
|
-
return (
|
414
|
-
!headers ? {}
|
415
|
-
: Symbol.iterator in headers ?
|
416
|
-
Object.fromEntries(Array.from(headers as Iterable<string[]>).map((header) => [...header]))
|
417
|
-
: { ...(headers as any as Record<string, string>) }
|
418
|
-
);
|
419
|
-
}
|
420
|
-
|
421
|
-
protected makeStatusError(
|
422
|
-
status: number | undefined,
|
423
|
-
error: Object | undefined,
|
424
|
-
message: string | undefined,
|
425
|
-
headers: Headers | undefined,
|
426
|
-
): APIError {
|
427
|
-
return APIError.generate(status, error, message, headers);
|
428
|
-
}
|
429
|
-
|
430
|
-
request<Req, Rsp>(
|
431
|
-
options: PromiseOrValue<FinalRequestOptions<Req>>,
|
432
|
-
remainingRetries: number | null = null,
|
433
|
-
): APIPromise<Rsp> {
|
434
|
-
return new APIPromise(this.makeRequest(options, remainingRetries));
|
435
|
-
}
|
436
|
-
|
437
|
-
private async makeRequest<Req>(
|
438
|
-
optionsInput: PromiseOrValue<FinalRequestOptions<Req>>,
|
439
|
-
retriesRemaining: number | null,
|
440
|
-
): Promise<APIResponseProps> {
|
441
|
-
const options = await optionsInput;
|
442
|
-
const maxRetries = options.maxRetries ?? this.maxRetries;
|
443
|
-
if (retriesRemaining == null) {
|
444
|
-
retriesRemaining = maxRetries;
|
445
|
-
}
|
446
|
-
|
447
|
-
await this.prepareOptions(options);
|
448
|
-
|
449
|
-
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
|
450
|
-
|
451
|
-
await this.prepareRequest(req, { url, options });
|
452
|
-
|
453
|
-
debug('request', url, options, req.headers);
|
454
|
-
|
455
|
-
if (options.signal?.aborted) {
|
456
|
-
throw new APIUserAbortError();
|
457
|
-
}
|
458
|
-
|
459
|
-
const controller = new AbortController();
|
460
|
-
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
461
|
-
|
462
|
-
if (response instanceof Error) {
|
463
|
-
if (options.signal?.aborted) {
|
464
|
-
throw new APIUserAbortError();
|
465
|
-
}
|
466
|
-
if (retriesRemaining) {
|
467
|
-
return this.retryRequest(options, retriesRemaining);
|
468
|
-
}
|
469
|
-
if (response.name === 'AbortError') {
|
470
|
-
throw new APIConnectionTimeoutError();
|
471
|
-
}
|
472
|
-
throw new APIConnectionError({ cause: response });
|
473
|
-
}
|
474
|
-
|
475
|
-
const responseHeaders = createResponseHeaders(response.headers);
|
476
|
-
|
477
|
-
if (!response.ok) {
|
478
|
-
if (retriesRemaining && this.shouldRetry(response)) {
|
479
|
-
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
480
|
-
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);
|
481
|
-
return this.retryRequest(options, retriesRemaining, responseHeaders);
|
482
|
-
}
|
483
|
-
|
484
|
-
const errText = await response.text().catch((e) => castToError(e).message);
|
485
|
-
const errJSON = safeJSON(errText);
|
486
|
-
const errMessage = errJSON ? undefined : errText;
|
487
|
-
const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
|
488
|
-
|
489
|
-
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
|
490
|
-
|
491
|
-
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
|
492
|
-
throw err;
|
493
|
-
}
|
494
|
-
|
495
|
-
return { response, options, controller };
|
496
|
-
}
|
497
|
-
|
498
|
-
requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
|
499
|
-
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
|
500
|
-
options: FinalRequestOptions,
|
501
|
-
): PagePromise<PageClass, Item> {
|
502
|
-
const request = this.makeRequest(options, null);
|
503
|
-
return new PagePromise<PageClass, Item>(this, request, Page);
|
504
|
-
}
|
505
|
-
|
506
|
-
buildURL<Req>(path: string, query: Req | null | undefined): string {
|
507
|
-
const url =
|
508
|
-
isAbsoluteURL(path) ?
|
509
|
-
new URL(path)
|
510
|
-
: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
511
|
-
|
512
|
-
const defaultQuery = this.defaultQuery();
|
513
|
-
if (!isEmptyObj(defaultQuery)) {
|
514
|
-
query = { ...defaultQuery, ...query } as Req;
|
515
|
-
}
|
516
|
-
|
517
|
-
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
518
|
-
url.search = this.stringifyQuery(query as Record<string, unknown>);
|
519
|
-
}
|
520
|
-
|
521
|
-
return url.toString();
|
522
|
-
}
|
523
|
-
|
524
|
-
protected stringifyQuery(query: Record<string, unknown>): string {
|
525
|
-
return Object.entries(query)
|
526
|
-
.filter(([_, value]) => typeof value !== 'undefined')
|
527
|
-
.map(([key, value]) => {
|
528
|
-
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
529
|
-
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
530
|
-
}
|
531
|
-
if (value === null) {
|
532
|
-
return `${encodeURIComponent(key)}=`;
|
533
|
-
}
|
534
|
-
throw new MixedbreadError(
|
535
|
-
`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.`,
|
536
|
-
);
|
537
|
-
})
|
538
|
-
.join('&');
|
539
|
-
}
|
540
|
-
|
541
|
-
async fetchWithTimeout(
|
542
|
-
url: RequestInfo,
|
543
|
-
init: RequestInit | undefined,
|
544
|
-
ms: number,
|
545
|
-
controller: AbortController,
|
546
|
-
): Promise<Response> {
|
547
|
-
const { signal, ...options } = init || {};
|
548
|
-
if (signal) signal.addEventListener('abort', () => controller.abort());
|
549
|
-
|
550
|
-
const timeout = setTimeout(() => controller.abort(), ms);
|
551
|
-
|
552
|
-
const fetchOptions = {
|
553
|
-
signal: controller.signal as any,
|
554
|
-
...options,
|
555
|
-
};
|
556
|
-
if (fetchOptions.method) {
|
557
|
-
// Custom methods like 'patch' need to be uppercased
|
558
|
-
// See https://github.com/nodejs/undici/issues/2294
|
559
|
-
fetchOptions.method = fetchOptions.method.toUpperCase();
|
560
|
-
}
|
561
|
-
|
562
|
-
return (
|
563
|
-
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
564
|
-
this.fetch.call(undefined, url, fetchOptions).finally(() => {
|
565
|
-
clearTimeout(timeout);
|
566
|
-
})
|
567
|
-
);
|
568
|
-
}
|
569
|
-
|
570
|
-
private shouldRetry(response: Response): boolean {
|
571
|
-
// Note this is not a standard header.
|
572
|
-
const shouldRetryHeader = response.headers.get('x-should-retry');
|
573
|
-
|
574
|
-
// If the server explicitly says whether or not to retry, obey.
|
575
|
-
if (shouldRetryHeader === 'true') return true;
|
576
|
-
if (shouldRetryHeader === 'false') return false;
|
577
|
-
|
578
|
-
// Retry on request timeouts.
|
579
|
-
if (response.status === 408) return true;
|
580
|
-
|
581
|
-
// Retry on lock timeouts.
|
582
|
-
if (response.status === 409) return true;
|
583
|
-
|
584
|
-
// Retry on rate limits.
|
585
|
-
if (response.status === 429) return true;
|
586
|
-
|
587
|
-
// Retry internal errors.
|
588
|
-
if (response.status >= 500) return true;
|
589
|
-
|
590
|
-
return false;
|
591
|
-
}
|
592
|
-
|
593
|
-
private async retryRequest(
|
594
|
-
options: FinalRequestOptions,
|
595
|
-
retriesRemaining: number,
|
596
|
-
responseHeaders?: Headers | undefined,
|
597
|
-
): Promise<APIResponseProps> {
|
598
|
-
let timeoutMillis: number | undefined;
|
599
|
-
|
600
|
-
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
601
|
-
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
|
602
|
-
if (retryAfterMillisHeader) {
|
603
|
-
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
604
|
-
if (!Number.isNaN(timeoutMs)) {
|
605
|
-
timeoutMillis = timeoutMs;
|
606
|
-
}
|
607
|
-
}
|
608
|
-
|
609
|
-
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
610
|
-
const retryAfterHeader = responseHeaders?.['retry-after'];
|
611
|
-
if (retryAfterHeader && !timeoutMillis) {
|
612
|
-
const timeoutSeconds = parseFloat(retryAfterHeader);
|
613
|
-
if (!Number.isNaN(timeoutSeconds)) {
|
614
|
-
timeoutMillis = timeoutSeconds * 1000;
|
615
|
-
} else {
|
616
|
-
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
617
|
-
}
|
618
|
-
}
|
619
|
-
|
620
|
-
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
621
|
-
// just do what it says, but otherwise calculate a default
|
622
|
-
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
|
623
|
-
const maxRetries = options.maxRetries ?? this.maxRetries;
|
624
|
-
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
625
|
-
}
|
626
|
-
await sleep(timeoutMillis);
|
627
|
-
|
628
|
-
return this.makeRequest(options, retriesRemaining - 1);
|
629
|
-
}
|
630
|
-
|
631
|
-
private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {
|
632
|
-
const initialRetryDelay = 0.5;
|
633
|
-
const maxRetryDelay = 8.0;
|
634
|
-
|
635
|
-
const numRetries = maxRetries - retriesRemaining;
|
636
|
-
|
637
|
-
// Apply exponential backoff, but not more than the max.
|
638
|
-
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
639
|
-
|
640
|
-
// Apply some jitter, take up to at most 25 percent of the retry time.
|
641
|
-
const jitter = 1 - Math.random() * 0.25;
|
642
|
-
|
643
|
-
return sleepSeconds * jitter * 1000;
|
644
|
-
}
|
645
|
-
|
646
|
-
private getUserAgent(): string {
|
647
|
-
return `${this.constructor.name}/JS ${VERSION}`;
|
648
|
-
}
|
649
|
-
}
|
650
|
-
|
651
|
-
export type PageInfo = { url: URL } | { params: Record<string, unknown> | null };
|
652
|
-
|
653
|
-
export abstract class AbstractPage<Item> implements AsyncIterable<Item> {
|
654
|
-
#client: APIClient;
|
655
|
-
protected options: FinalRequestOptions;
|
656
|
-
|
657
|
-
protected response: Response;
|
658
|
-
protected body: unknown;
|
659
|
-
|
660
|
-
constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions) {
|
661
|
-
this.#client = client;
|
662
|
-
this.options = options;
|
663
|
-
this.response = response;
|
664
|
-
this.body = body;
|
665
|
-
}
|
666
|
-
|
667
|
-
/**
|
668
|
-
* @deprecated Use nextPageInfo instead
|
669
|
-
*/
|
670
|
-
abstract nextPageParams(): Partial<Record<string, unknown>> | null;
|
671
|
-
abstract nextPageInfo(): PageInfo | null;
|
672
|
-
|
673
|
-
abstract getPaginatedItems(): Item[];
|
674
|
-
|
675
|
-
hasNextPage(): boolean {
|
676
|
-
const items = this.getPaginatedItems();
|
677
|
-
if (!items.length) return false;
|
678
|
-
return this.nextPageInfo() != null;
|
679
|
-
}
|
680
|
-
|
681
|
-
async getNextPage(): Promise<this> {
|
682
|
-
const nextInfo = this.nextPageInfo();
|
683
|
-
if (!nextInfo) {
|
684
|
-
throw new MixedbreadError(
|
685
|
-
'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
|
686
|
-
);
|
687
|
-
}
|
688
|
-
const nextOptions = { ...this.options };
|
689
|
-
if ('params' in nextInfo && typeof nextOptions.query === 'object') {
|
690
|
-
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
|
691
|
-
} else if ('url' in nextInfo) {
|
692
|
-
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
|
693
|
-
for (const [key, value] of params) {
|
694
|
-
nextInfo.url.searchParams.set(key, value as any);
|
695
|
-
}
|
696
|
-
nextOptions.query = undefined;
|
697
|
-
nextOptions.path = nextInfo.url.toString();
|
698
|
-
}
|
699
|
-
return await this.#client.requestAPIList(this.constructor as any, nextOptions);
|
700
|
-
}
|
701
|
-
|
702
|
-
async *iterPages(): AsyncGenerator<this> {
|
703
|
-
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
704
|
-
let page: this = this;
|
705
|
-
yield page;
|
706
|
-
while (page.hasNextPage()) {
|
707
|
-
page = await page.getNextPage();
|
708
|
-
yield page;
|
709
|
-
}
|
710
|
-
}
|
711
|
-
|
712
|
-
async *[Symbol.asyncIterator](): AsyncGenerator<Item> {
|
713
|
-
for await (const page of this.iterPages()) {
|
714
|
-
for (const item of page.getPaginatedItems()) {
|
715
|
-
yield item;
|
716
|
-
}
|
717
|
-
}
|
718
|
-
}
|
719
|
-
}
|
720
|
-
|
721
|
-
/**
|
722
|
-
* This subclass of Promise will resolve to an instantiated Page once the request completes.
|
723
|
-
*
|
724
|
-
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
|
725
|
-
*
|
726
|
-
* for await (const item of client.items.list()) {
|
727
|
-
* console.log(item)
|
728
|
-
* }
|
729
|
-
*/
|
730
|
-
export class PagePromise<
|
731
|
-
PageClass extends AbstractPage<Item>,
|
732
|
-
Item = ReturnType<PageClass['getPaginatedItems']>[number],
|
733
|
-
>
|
734
|
-
extends APIPromise<PageClass>
|
735
|
-
implements AsyncIterable<Item>
|
736
|
-
{
|
737
|
-
constructor(
|
738
|
-
client: APIClient,
|
739
|
-
request: Promise<APIResponseProps>,
|
740
|
-
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
|
741
|
-
) {
|
742
|
-
super(
|
743
|
-
request,
|
744
|
-
async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options),
|
745
|
-
);
|
746
|
-
}
|
747
|
-
|
748
|
-
/**
|
749
|
-
* Allow auto-paginating iteration on an unawaited list call, eg:
|
750
|
-
*
|
751
|
-
* for await (const item of client.items.list()) {
|
752
|
-
* console.log(item)
|
753
|
-
* }
|
754
|
-
*/
|
755
|
-
async *[Symbol.asyncIterator](): AsyncGenerator<Item> {
|
756
|
-
const page = await this;
|
757
|
-
for await (const item of page) {
|
758
|
-
yield item;
|
759
|
-
}
|
760
|
-
}
|
761
|
-
}
|
762
|
-
|
763
|
-
export const createResponseHeaders = (
|
764
|
-
headers: Awaited<ReturnType<Fetch>>['headers'],
|
765
|
-
): Record<string, string> => {
|
766
|
-
return new Proxy(
|
767
|
-
Object.fromEntries(
|
768
|
-
// @ts-ignore
|
769
|
-
headers.entries(),
|
770
|
-
),
|
771
|
-
{
|
772
|
-
get(target, name) {
|
773
|
-
const key = name.toString();
|
774
|
-
return target[key.toLowerCase()] || target[key];
|
775
|
-
},
|
776
|
-
},
|
777
|
-
);
|
778
|
-
};
|
779
|
-
|
780
|
-
type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
|
781
|
-
|
782
|
-
export type RequestClient = { fetch: Fetch };
|
783
|
-
export type Headers = Record<string, string | null | undefined>;
|
784
|
-
export type DefaultQuery = Record<string, string | undefined>;
|
785
|
-
export type KeysEnum<T> = { [P in keyof Required<T>]: true };
|
786
|
-
|
787
|
-
export type RequestOptions<
|
788
|
-
Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer,
|
789
|
-
> = {
|
790
|
-
method?: HTTPMethod;
|
791
|
-
path?: string;
|
792
|
-
query?: Req | undefined;
|
793
|
-
body?: Req | null | undefined;
|
794
|
-
headers?: Headers | undefined;
|
795
|
-
|
796
|
-
maxRetries?: number;
|
797
|
-
stream?: boolean | undefined;
|
798
|
-
timeout?: number;
|
799
|
-
httpAgent?: Agent;
|
800
|
-
signal?: AbortSignal | undefined | null;
|
801
|
-
idempotencyKey?: string;
|
802
|
-
|
803
|
-
__binaryRequest?: boolean | undefined;
|
804
|
-
__binaryResponse?: boolean | undefined;
|
805
|
-
};
|
806
|
-
|
807
|
-
// This is required so that we can determine if a given object matches the RequestOptions
|
808
|
-
// type at runtime. While this requires duplication, it is enforced by the TypeScript
|
809
|
-
// compiler such that any missing / extraneous keys will cause an error.
|
810
|
-
const requestOptionsKeys: KeysEnum<RequestOptions> = {
|
811
|
-
method: true,
|
812
|
-
path: true,
|
813
|
-
query: true,
|
814
|
-
body: true,
|
815
|
-
headers: true,
|
816
|
-
|
817
|
-
maxRetries: true,
|
818
|
-
stream: true,
|
819
|
-
timeout: true,
|
820
|
-
httpAgent: true,
|
821
|
-
signal: true,
|
822
|
-
idempotencyKey: true,
|
823
|
-
|
824
|
-
__binaryRequest: true,
|
825
|
-
__binaryResponse: true,
|
826
|
-
};
|
827
|
-
|
828
|
-
export const isRequestOptions = (obj: unknown): obj is RequestOptions => {
|
829
|
-
return (
|
830
|
-
typeof obj === 'object' &&
|
831
|
-
obj !== null &&
|
832
|
-
!isEmptyObj(obj) &&
|
833
|
-
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
|
834
|
-
);
|
835
|
-
};
|
836
|
-
|
837
|
-
export type FinalRequestOptions<Req = unknown | Record<string, unknown> | Readable | DataView> =
|
838
|
-
RequestOptions<Req> & {
|
839
|
-
method: HTTPMethod;
|
840
|
-
path: string;
|
841
|
-
};
|
842
|
-
|
843
|
-
declare const Deno: any;
|
844
|
-
declare const EdgeRuntime: any;
|
845
|
-
type Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';
|
846
|
-
type PlatformName =
|
847
|
-
| 'MacOS'
|
848
|
-
| 'Linux'
|
849
|
-
| 'Windows'
|
850
|
-
| 'FreeBSD'
|
851
|
-
| 'OpenBSD'
|
852
|
-
| 'iOS'
|
853
|
-
| 'Android'
|
854
|
-
| `Other:${string}`
|
855
|
-
| 'Unknown';
|
856
|
-
type Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari';
|
857
|
-
type PlatformProperties = {
|
858
|
-
'X-Stainless-Lang': 'js';
|
859
|
-
'X-Stainless-Package-Version': string;
|
860
|
-
'X-Stainless-OS': PlatformName;
|
861
|
-
'X-Stainless-Arch': Arch;
|
862
|
-
'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown';
|
863
|
-
'X-Stainless-Runtime-Version': string;
|
864
|
-
};
|
865
|
-
const getPlatformProperties = (): PlatformProperties => {
|
866
|
-
if (typeof Deno !== 'undefined' && Deno.build != null) {
|
867
|
-
return {
|
868
|
-
'X-Stainless-Lang': 'js',
|
869
|
-
'X-Stainless-Package-Version': VERSION,
|
870
|
-
'X-Stainless-OS': normalizePlatform(Deno.build.os),
|
871
|
-
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
|
872
|
-
'X-Stainless-Runtime': 'deno',
|
873
|
-
'X-Stainless-Runtime-Version':
|
874
|
-
typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
|
875
|
-
};
|
876
|
-
}
|
877
|
-
if (typeof EdgeRuntime !== 'undefined') {
|
878
|
-
return {
|
879
|
-
'X-Stainless-Lang': 'js',
|
880
|
-
'X-Stainless-Package-Version': VERSION,
|
881
|
-
'X-Stainless-OS': 'Unknown',
|
882
|
-
'X-Stainless-Arch': `other:${EdgeRuntime}`,
|
883
|
-
'X-Stainless-Runtime': 'edge',
|
884
|
-
'X-Stainless-Runtime-Version': process.version,
|
885
|
-
};
|
886
|
-
}
|
887
|
-
// Check if Node.js
|
888
|
-
if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
|
889
|
-
return {
|
890
|
-
'X-Stainless-Lang': 'js',
|
891
|
-
'X-Stainless-Package-Version': VERSION,
|
892
|
-
'X-Stainless-OS': normalizePlatform(process.platform),
|
893
|
-
'X-Stainless-Arch': normalizeArch(process.arch),
|
894
|
-
'X-Stainless-Runtime': 'node',
|
895
|
-
'X-Stainless-Runtime-Version': process.version,
|
896
|
-
};
|
897
|
-
}
|
898
|
-
|
899
|
-
const browserInfo = getBrowserInfo();
|
900
|
-
if (browserInfo) {
|
901
|
-
return {
|
902
|
-
'X-Stainless-Lang': 'js',
|
903
|
-
'X-Stainless-Package-Version': VERSION,
|
904
|
-
'X-Stainless-OS': 'Unknown',
|
905
|
-
'X-Stainless-Arch': 'unknown',
|
906
|
-
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
|
907
|
-
'X-Stainless-Runtime-Version': browserInfo.version,
|
908
|
-
};
|
909
|
-
}
|
910
|
-
|
911
|
-
// TODO add support for Cloudflare workers, etc.
|
912
|
-
return {
|
913
|
-
'X-Stainless-Lang': 'js',
|
914
|
-
'X-Stainless-Package-Version': VERSION,
|
915
|
-
'X-Stainless-OS': 'Unknown',
|
916
|
-
'X-Stainless-Arch': 'unknown',
|
917
|
-
'X-Stainless-Runtime': 'unknown',
|
918
|
-
'X-Stainless-Runtime-Version': 'unknown',
|
919
|
-
};
|
920
|
-
};
|
921
|
-
|
922
|
-
type BrowserInfo = {
|
923
|
-
browser: Browser;
|
924
|
-
version: string;
|
925
|
-
};
|
926
|
-
|
927
|
-
declare const navigator: { userAgent: string } | undefined;
|
928
|
-
|
929
|
-
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
|
930
|
-
function getBrowserInfo(): BrowserInfo | null {
|
931
|
-
if (typeof navigator === 'undefined' || !navigator) {
|
932
|
-
return null;
|
933
|
-
}
|
934
|
-
|
935
|
-
// NOTE: The order matters here!
|
936
|
-
const browserPatterns = [
|
937
|
-
{ key: 'edge' as const, pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
938
|
-
{ key: 'ie' as const, pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
939
|
-
{ key: 'ie' as const, pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
940
|
-
{ key: 'chrome' as const, pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
941
|
-
{ key: 'firefox' as const, pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
942
|
-
{ key: 'safari' as const, pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
943
|
-
];
|
944
|
-
|
945
|
-
// Find the FIRST matching browser
|
946
|
-
for (const { key, pattern } of browserPatterns) {
|
947
|
-
const match = pattern.exec(navigator.userAgent);
|
948
|
-
if (match) {
|
949
|
-
const major = match[1] || 0;
|
950
|
-
const minor = match[2] || 0;
|
951
|
-
const patch = match[3] || 0;
|
952
|
-
|
953
|
-
return { browser: key, version: `${major}.${minor}.${patch}` };
|
954
|
-
}
|
955
|
-
}
|
956
|
-
|
957
|
-
return null;
|
958
|
-
}
|
959
|
-
|
960
|
-
const normalizeArch = (arch: string): Arch => {
|
961
|
-
// Node docs:
|
962
|
-
// - https://nodejs.org/api/process.html#processarch
|
963
|
-
// Deno docs:
|
964
|
-
// - https://doc.deno.land/deno/stable/~/Deno.build
|
965
|
-
if (arch === 'x32') return 'x32';
|
966
|
-
if (arch === 'x86_64' || arch === 'x64') return 'x64';
|
967
|
-
if (arch === 'arm') return 'arm';
|
968
|
-
if (arch === 'aarch64' || arch === 'arm64') return 'arm64';
|
969
|
-
if (arch) return `other:${arch}`;
|
970
|
-
return 'unknown';
|
971
|
-
};
|
972
|
-
|
973
|
-
const normalizePlatform = (platform: string): PlatformName => {
|
974
|
-
// Node platforms:
|
975
|
-
// - https://nodejs.org/api/process.html#processplatform
|
976
|
-
// Deno platforms:
|
977
|
-
// - https://doc.deno.land/deno/stable/~/Deno.build
|
978
|
-
// - https://github.com/denoland/deno/issues/14799
|
979
|
-
|
980
|
-
platform = platform.toLowerCase();
|
981
|
-
|
982
|
-
// NOTE: this iOS check is untested and may not work
|
983
|
-
// Node does not work natively on IOS, there is a fork at
|
984
|
-
// https://github.com/nodejs-mobile/nodejs-mobile
|
985
|
-
// however it is unknown at the time of writing how to detect if it is running
|
986
|
-
if (platform.includes('ios')) return 'iOS';
|
987
|
-
if (platform === 'android') return 'Android';
|
988
|
-
if (platform === 'darwin') return 'MacOS';
|
989
|
-
if (platform === 'win32') return 'Windows';
|
990
|
-
if (platform === 'freebsd') return 'FreeBSD';
|
991
|
-
if (platform === 'openbsd') return 'OpenBSD';
|
992
|
-
if (platform === 'linux') return 'Linux';
|
993
|
-
if (platform) return `Other:${platform}`;
|
994
|
-
return 'Unknown';
|
995
|
-
};
|
996
|
-
|
997
|
-
let _platformHeaders: PlatformProperties;
|
998
|
-
const getPlatformHeaders = () => {
|
999
|
-
return (_platformHeaders ??= getPlatformProperties());
|
1000
|
-
};
|
1001
|
-
|
1002
|
-
export const safeJSON = (text: string) => {
|
1003
|
-
try {
|
1004
|
-
return JSON.parse(text);
|
1005
|
-
} catch (err) {
|
1006
|
-
return undefined;
|
1007
|
-
}
|
1008
|
-
};
|
1009
|
-
|
1010
|
-
// https://url.spec.whatwg.org/#url-scheme-string
|
1011
|
-
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
1012
|
-
const isAbsoluteURL = (url: string): boolean => {
|
1013
|
-
return startsWithSchemeRegexp.test(url);
|
1014
|
-
};
|
1015
|
-
|
1016
|
-
export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
1017
|
-
|
1018
|
-
const validatePositiveInteger = (name: string, n: unknown): number => {
|
1019
|
-
if (typeof n !== 'number' || !Number.isInteger(n)) {
|
1020
|
-
throw new MixedbreadError(`${name} must be an integer`);
|
1021
|
-
}
|
1022
|
-
if (n < 0) {
|
1023
|
-
throw new MixedbreadError(`${name} must be a positive integer`);
|
1024
|
-
}
|
1025
|
-
return n;
|
1026
|
-
};
|
1027
|
-
|
1028
|
-
export const castToError = (err: any): Error => {
|
1029
|
-
if (err instanceof Error) return err;
|
1030
|
-
if (typeof err === 'object' && err !== null) {
|
1031
|
-
try {
|
1032
|
-
return new Error(JSON.stringify(err));
|
1033
|
-
} catch {}
|
1034
|
-
}
|
1035
|
-
return new Error(err);
|
1036
|
-
};
|
1037
|
-
|
1038
|
-
export const ensurePresent = <T>(value: T | null | undefined): T => {
|
1039
|
-
if (value == null) throw new MixedbreadError(`Expected a value to be given but received ${value} instead.`);
|
1040
|
-
return value;
|
1041
|
-
};
|
1042
|
-
|
1043
|
-
/**
|
1044
|
-
* Read an environment variable.
|
1045
|
-
*
|
1046
|
-
* Trims beginning and trailing whitespace.
|
1047
|
-
*
|
1048
|
-
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
1049
|
-
*/
|
1050
|
-
export const readEnv = (env: string): string | undefined => {
|
1051
|
-
if (typeof process !== 'undefined') {
|
1052
|
-
return process.env?.[env]?.trim() ?? undefined;
|
1053
|
-
}
|
1054
|
-
if (typeof Deno !== 'undefined') {
|
1055
|
-
return Deno.env?.get?.(env)?.trim();
|
1056
|
-
}
|
1057
|
-
return undefined;
|
1058
|
-
};
|
1059
|
-
|
1060
|
-
export const coerceInteger = (value: unknown): number => {
|
1061
|
-
if (typeof value === 'number') return Math.round(value);
|
1062
|
-
if (typeof value === 'string') return parseInt(value, 10);
|
1063
|
-
|
1064
|
-
throw new MixedbreadError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
1065
|
-
};
|
1066
|
-
|
1067
|
-
export const coerceFloat = (value: unknown): number => {
|
1068
|
-
if (typeof value === 'number') return value;
|
1069
|
-
if (typeof value === 'string') return parseFloat(value);
|
1070
|
-
|
1071
|
-
throw new MixedbreadError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
1072
|
-
};
|
1073
|
-
|
1074
|
-
export const coerceBoolean = (value: unknown): boolean => {
|
1075
|
-
if (typeof value === 'boolean') return value;
|
1076
|
-
if (typeof value === 'string') return value === 'true';
|
1077
|
-
return Boolean(value);
|
1078
|
-
};
|
1079
|
-
|
1080
|
-
export const maybeCoerceInteger = (value: unknown): number | undefined => {
|
1081
|
-
if (value === undefined) {
|
1082
|
-
return undefined;
|
1083
|
-
}
|
1084
|
-
return coerceInteger(value);
|
1085
|
-
};
|
1086
|
-
|
1087
|
-
export const maybeCoerceFloat = (value: unknown): number | undefined => {
|
1088
|
-
if (value === undefined) {
|
1089
|
-
return undefined;
|
1090
|
-
}
|
1091
|
-
return coerceFloat(value);
|
1092
|
-
};
|
1093
|
-
|
1094
|
-
export const maybeCoerceBoolean = (value: unknown): boolean | undefined => {
|
1095
|
-
if (value === undefined) {
|
1096
|
-
return undefined;
|
1097
|
-
}
|
1098
|
-
return coerceBoolean(value);
|
1099
|
-
};
|
1100
|
-
|
1101
|
-
// https://stackoverflow.com/a/34491287
|
1102
|
-
export function isEmptyObj(obj: Object | null | undefined): boolean {
|
1103
|
-
if (!obj) return true;
|
1104
|
-
for (const _k in obj) return false;
|
1105
|
-
return true;
|
1106
|
-
}
|
1107
|
-
|
1108
|
-
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
1109
|
-
export function hasOwn(obj: Object, key: string): boolean {
|
1110
|
-
return Object.prototype.hasOwnProperty.call(obj, key);
|
1111
|
-
}
|
1112
|
-
|
1113
|
-
/**
|
1114
|
-
* Copies headers from "newHeaders" onto "targetHeaders",
|
1115
|
-
* using lower-case for all properties,
|
1116
|
-
* ignoring any keys with undefined values,
|
1117
|
-
* and deleting any keys with null values.
|
1118
|
-
*/
|
1119
|
-
function applyHeadersMut(targetHeaders: Headers, newHeaders: Headers): void {
|
1120
|
-
for (const k in newHeaders) {
|
1121
|
-
if (!hasOwn(newHeaders, k)) continue;
|
1122
|
-
const lowerKey = k.toLowerCase();
|
1123
|
-
if (!lowerKey) continue;
|
1124
|
-
|
1125
|
-
const val = newHeaders[k];
|
1126
|
-
|
1127
|
-
if (val === null) {
|
1128
|
-
delete targetHeaders[lowerKey];
|
1129
|
-
} else if (val !== undefined) {
|
1130
|
-
targetHeaders[lowerKey] = val;
|
1131
|
-
}
|
1132
|
-
}
|
1133
|
-
}
|
1134
|
-
|
1135
|
-
export function debug(action: string, ...args: any[]) {
|
1136
|
-
if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {
|
1137
|
-
console.log(`Mixedbread:DEBUG:${action}`, ...args);
|
1138
|
-
}
|
1139
|
-
}
|
1140
|
-
|
1141
|
-
/**
|
1142
|
-
* https://stackoverflow.com/a/2117523
|
1143
|
-
*/
|
1144
|
-
const uuid4 = () => {
|
1145
|
-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
1146
|
-
const r = (Math.random() * 16) | 0;
|
1147
|
-
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
1148
|
-
return v.toString(16);
|
1149
|
-
});
|
1150
|
-
};
|
1151
|
-
|
1152
|
-
export const isRunningInBrowser = () => {
|
1153
|
-
return (
|
1154
|
-
// @ts-ignore
|
1155
|
-
typeof window !== 'undefined' &&
|
1156
|
-
// @ts-ignore
|
1157
|
-
typeof window.document !== 'undefined' &&
|
1158
|
-
// @ts-ignore
|
1159
|
-
typeof navigator !== 'undefined'
|
1160
|
-
);
|
1161
|
-
};
|
1162
|
-
|
1163
|
-
export interface HeadersProtocol {
|
1164
|
-
get: (header: string) => string | null | undefined;
|
1165
|
-
}
|
1166
|
-
export type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;
|
1167
|
-
|
1168
|
-
export const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {
|
1169
|
-
return typeof headers?.get === 'function';
|
1170
|
-
};
|
1171
|
-
|
1172
|
-
export const getRequiredHeader = (headers: HeadersLike | Headers, header: string): string => {
|
1173
|
-
const foundHeader = getHeader(headers, header);
|
1174
|
-
if (foundHeader === undefined) {
|
1175
|
-
throw new Error(`Could not find ${header} header`);
|
1176
|
-
}
|
1177
|
-
return foundHeader;
|
1178
|
-
};
|
1179
|
-
|
1180
|
-
export const getHeader = (headers: HeadersLike | Headers, header: string): string | undefined => {
|
1181
|
-
const lowerCasedHeader = header.toLowerCase();
|
1182
|
-
if (isHeadersProtocol(headers)) {
|
1183
|
-
// to deal with the case where the header looks like Stainless-Event-Id
|
1184
|
-
const intercapsHeader =
|
1185
|
-
header[0]?.toUpperCase() +
|
1186
|
-
header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
|
1187
|
-
for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
|
1188
|
-
const value = headers.get(key);
|
1189
|
-
if (value) {
|
1190
|
-
return value;
|
1191
|
-
}
|
1192
|
-
}
|
1193
|
-
}
|
1194
|
-
|
1195
|
-
for (const [key, value] of Object.entries(headers)) {
|
1196
|
-
if (key.toLowerCase() === lowerCasedHeader) {
|
1197
|
-
if (Array.isArray(value)) {
|
1198
|
-
if (value.length <= 1) return value[0];
|
1199
|
-
console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
|
1200
|
-
return value[0];
|
1201
|
-
}
|
1202
|
-
return value;
|
1203
|
-
}
|
1204
|
-
}
|
1205
|
-
|
1206
|
-
return undefined;
|
1207
|
-
};
|
1208
|
-
|
1209
|
-
/**
|
1210
|
-
* Encodes a string to Base64 format.
|
1211
|
-
*/
|
1212
|
-
export const toBase64 = (str: string | null | undefined): string => {
|
1213
|
-
if (!str) return '';
|
1214
|
-
if (typeof Buffer !== 'undefined') {
|
1215
|
-
return Buffer.from(str).toString('base64');
|
1216
|
-
}
|
1217
|
-
|
1218
|
-
if (typeof btoa !== 'undefined') {
|
1219
|
-
return btoa(str);
|
1220
|
-
}
|
1221
|
-
|
1222
|
-
throw new MixedbreadError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
|
1223
|
-
};
|
1224
|
-
|
1225
|
-
export function isObj(obj: unknown): obj is Record<string, unknown> {
|
1226
|
-
return obj != null && typeof obj === 'object' && !Array.isArray(obj);
|
1227
|
-
}
|