diff --git a/.gitignore b/.gitignore index 3eed6dd..d98d51a 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ yarn-error.log codegen.log Brewfile.lock.json dist -/deno +dist-deno /*.tgz .idea/ diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 17473a2..b3b5e58 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.1.0-alpha.3" + ".": "0.1.0-alpha.4" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ab0189..b4ed6f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.1.0-alpha.4 (2024-11-15) + +Full Changelog: [v0.1.0-alpha.3...v0.1.0-alpha.4](https://github.com/OmniStack-sh/omnistack-node/compare/v0.1.0-alpha.3...v0.1.0-alpha.4) + +### Chores + +* rebuild project due to codegen change ([#10](https://github.com/OmniStack-sh/omnistack-node/issues/10)) ([60aca76](https://github.com/OmniStack-sh/omnistack-node/commit/60aca76a6b443d636eeae13750f1858bc8fd07f9)) +* rebuild project due to codegen change ([#11](https://github.com/OmniStack-sh/omnistack-node/issues/11)) ([ed48ff3](https://github.com/OmniStack-sh/omnistack-node/commit/ed48ff3f6f4d51be5a5bfa5994eed3b3a430fb48)) +* rebuild project due to codegen change ([#12](https://github.com/OmniStack-sh/omnistack-node/issues/12)) ([89300f5](https://github.com/OmniStack-sh/omnistack-node/commit/89300f553297cfa4b100b5a4958c0323610abfb9)) +* rebuild project due to codegen change ([#8](https://github.com/OmniStack-sh/omnistack-node/issues/8)) ([f4f7860](https://github.com/OmniStack-sh/omnistack-node/commit/f4f78606f5ec44dd99cfb6983e583d48315a3e28)) + ## 0.1.0-alpha.3 (2024-10-18) Full Changelog: [v0.1.0-alpha.2...v0.1.0-alpha.3](https://github.com/OmniStack-sh/omnistack-node/compare/v0.1.0-alpha.2...v0.1.0-alpha.3) diff --git a/README.md b/README.md index b1105e2..9b67527 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,15 @@ TypeScript >= 4.5 is supported. The following runtimes are supported: +- Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more) +- Node.js 18 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions. +- Deno v1.28.0 or higher, using `import Omnistack from "npm:omnistack-node"`. +- Bun 1.0 or later. +- Cloudflare Workers. +- Vercel Edge Runtime. +- Jest 28 or greater with the `"node"` environment (`"jsdom"` is not supported at this time). +- Nitro v2.6 or greater. + Note that React Native is not supported at this time. If you are interested in other runtime environments, please open or upvote an issue on GitHub. diff --git a/package.json b/package.json index 0405ad8..35995f4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "omnistack-node", - "version": "0.1.0-alpha.3", + "version": "0.1.0-alpha.4", "description": "The official TypeScript library for the Omnistack API", "author": "Omnistack ", "types": "dist/index.d.ts", @@ -10,7 +10,7 @@ "license": "Apache-2.0", "packageManager": "yarn@1.22.22", "files": [ - "*" + "**/*" ], "private": false, "scripts": { @@ -45,7 +45,6 @@ "jest": "^29.4.0", "prettier": "^3.0.0", "ts-jest": "^29.1.0", - "ts-morph": "^19.0.0", "ts-node": "^10.5.0", "tsc-multi": "^1.1.0", "tsconfig-paths": "^4.0.0", diff --git a/scripts/build b/scripts/build index 7a7e937..603319b 100755 --- a/scripts/build +++ b/scripts/build @@ -50,7 +50,7 @@ node scripts/utils/postprocess-files.cjs (cd dist && node -e 'require("omnistack-node")') (cd dist && node -e 'import("omnistack-node")' --input-type=module) -if command -v deno &> /dev/null && [ -e ./scripts/build-deno ] +if [ -e ./scripts/build-deno ] then ./scripts/build-deno fi diff --git a/src/core.ts b/src/core.ts index 834f58d..ae76537 100644 --- a/src/core.ts +++ b/src/core.ts @@ -351,9 +351,13 @@ export abstract class APIClient { delete reqHeaders['content-type']; } - // Don't set the retry count header if it was already set or removed by the caller. We check `headers`, - // which can contain nulls, instead of `reqHeaders` to account for the removal case. - if (getHeader(headers, 'x-stainless-retry-count') === undefined) { + // Don't set the retry count header if it was already set or removed through default headers or by the + // caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to + // account for the removal case. + if ( + getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined && + getHeader(headers, 'x-stainless-retry-count') === undefined + ) { reqHeaders['x-stainless-retry-count'] = String(retryCount); } @@ -392,7 +396,7 @@ export abstract class APIClient { error: Object | undefined, message: string | undefined, headers: Headers | undefined, - ) { + ): APIError { return APIError.generate(status, error, message, headers); } @@ -664,9 +668,9 @@ export abstract class AbstractPage implements AsyncIterable { return await this.#client.requestAPIList(this.constructor as any, nextOptions); } - async *iterPages() { + async *iterPages(): AsyncGenerator { // eslint-disable-next-line @typescript-eslint/no-this-alias - let page: AbstractPage = this; + let page: this = this; yield page; while (page.hasNextPage()) { page = await page.getNextPage(); @@ -674,7 +678,7 @@ export abstract class AbstractPage implements AsyncIterable { } } - async *[Symbol.asyncIterator]() { + async *[Symbol.asyncIterator](): AsyncGenerator { for await (const page of this.iterPages()) { for (const item of page.getPaginatedItems()) { yield item; @@ -717,7 +721,7 @@ export class PagePromise< * console.log(item) * } */ - async *[Symbol.asyncIterator]() { + async *[Symbol.asyncIterator](): AsyncGenerator { const page = await this; for await (const item of page) { yield item; diff --git a/src/error.ts b/src/error.ts index 04624db..f57c2c2 100644 --- a/src/error.ts +++ b/src/error.ts @@ -47,7 +47,7 @@ export class APIError extends OmnistackError { errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined, - ) { + ): APIError { if (!status) { return new APIConnectionError({ message, cause: castToError(errorResponse) }); } diff --git a/src/index.ts b/src/index.ts index 8ca858f..28498ec 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,10 +1,12 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import * as Errors from './error'; -import * as Uploads from './uploads'; import { type Agent } from './_shims/index'; import * as Core from './core'; +import * as Errors from './error'; +import * as Uploads from './uploads'; import * as API from './resources/index'; +import { CompletionCreateParams, CompletionCreateResponse, Completions } from './resources/completions'; +import { Chats } from './resources/chats/chats'; export interface ClientOptions { /** @@ -158,7 +160,26 @@ export class Omnistack extends Core.APIClient { static fileFromPath = Uploads.fileFromPath; } -export const { +Omnistack.Chats = Chats; +Omnistack.Completions = Completions; +export declare namespace Omnistack { + export type RequestOptions = Core.RequestOptions; + + export { Chats as Chats }; + + export { + Completions as Completions, + type CompletionCreateResponse as CompletionCreateResponse, + type CompletionCreateParams as CompletionCreateParams, + }; + + export type ProjectAPIKey = API.ProjectAPIKey; + export type ProjectServiceAccount = API.ProjectServiceAccount; + export type ProjectUser = API.ProjectUser; +} + +export { toFile, fileFromPath } from './uploads'; +export { OmnistackError, APIError, APIConnectionError, @@ -172,23 +193,6 @@ export const { InternalServerError, PermissionDeniedError, UnprocessableEntityError, -} = Errors; - -export import toFile = Uploads.toFile; -export import fileFromPath = Uploads.fileFromPath; - -export namespace Omnistack { - export import RequestOptions = Core.RequestOptions; - - export import Chats = API.Chats; - - export import Completions = API.Completions; - export import CompletionCreateResponse = API.CompletionCreateResponse; - export import CompletionCreateParams = API.CompletionCreateParams; - - export import ProjectAPIKey = API.ProjectAPIKey; - export import ProjectServiceAccount = API.ProjectServiceAccount; - export import ProjectUser = API.ProjectUser; -} +} from './error'; export default Omnistack; diff --git a/src/internal/qs/LICENSE.md b/src/internal/qs/LICENSE.md deleted file mode 100644 index 3fda157..0000000 --- a/src/internal/qs/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -BSD 3-Clause License - -Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/puruvj/neoqs/graphs/contributors) All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/internal/qs/README.md b/src/internal/qs/README.md deleted file mode 100644 index 67ae04e..0000000 --- a/src/internal/qs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# qs - -This is a vendored version of [neoqs](https://github.com/PuruVJ/neoqs) which is a TypeScript rewrite of [qs](https://github.com/ljharb/qs), a query string library. diff --git a/src/internal/qs/formats.ts b/src/internal/qs/formats.ts deleted file mode 100644 index 1cf9e2c..0000000 --- a/src/internal/qs/formats.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Format } from './types'; - -export const default_format: Format = 'RFC3986'; -export const formatters: Record string> = { - RFC1738: (v: PropertyKey) => String(v).replace(/%20/g, '+'), - RFC3986: (v: PropertyKey) => String(v), -}; -export const RFC1738 = 'RFC1738'; -export const RFC3986 = 'RFC3986'; diff --git a/src/internal/qs/index.ts b/src/internal/qs/index.ts deleted file mode 100644 index c3a3620..0000000 --- a/src/internal/qs/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { default_format, formatters, RFC1738, RFC3986 } from './formats'; - -const formats = { - formatters, - RFC1738, - RFC3986, - default: default_format, -}; - -export { stringify } from './stringify'; -export { formats }; - -export type { DefaultDecoder, DefaultEncoder, Format, ParseOptions, StringifyOptions } from './types'; diff --git a/src/internal/qs/stringify.ts b/src/internal/qs/stringify.ts deleted file mode 100644 index 6749756..0000000 --- a/src/internal/qs/stringify.ts +++ /dev/null @@ -1,388 +0,0 @@ -import { encode, is_buffer, maybe_map } from './utils'; -import { default_format, formatters } from './formats'; -import type { NonNullableProperties, StringifyOptions } from './types'; - -const has = Object.prototype.hasOwnProperty; - -const array_prefix_generators = { - brackets(prefix: PropertyKey) { - return String(prefix) + '[]'; - }, - comma: 'comma', - indices(prefix: PropertyKey, key: string) { - return String(prefix) + '[' + key + ']'; - }, - repeat(prefix: PropertyKey) { - return String(prefix); - }, -}; - -const is_array = Array.isArray; -const push = Array.prototype.push; -const push_to_array = function (arr: any[], value_or_array: any) { - push.apply(arr, is_array(value_or_array) ? value_or_array : [value_or_array]); -}; - -const to_ISO = Date.prototype.toISOString; - -const defaults = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: 'indices', - charset: 'utf-8', - charsetSentinel: false, - delimiter: '&', - encode: true, - encodeDotInKeys: false, - encoder: encode, - encodeValuesOnly: false, - format: default_format, - formatter: formatters[default_format], - /** @deprecated */ - indices: false, - serializeDate(date) { - return to_ISO.call(date); - }, - skipNulls: false, - strictNullHandling: false, -} as NonNullableProperties; - -function is_non_nullish_primitive(v: unknown): v is string | number | boolean | symbol | bigint { - return ( - typeof v === 'string' || - typeof v === 'number' || - typeof v === 'boolean' || - typeof v === 'symbol' || - typeof v === 'bigint' - ); -} - -const sentinel = {}; - -function inner_stringify( - object: any, - prefix: PropertyKey, - generateArrayPrefix: StringifyOptions['arrayFormat'] | ((prefix: string, key: string) => string), - commaRoundTrip: boolean, - allowEmptyArrays: boolean, - strictNullHandling: boolean, - skipNulls: boolean, - encodeDotInKeys: boolean, - encoder: StringifyOptions['encoder'], - filter: StringifyOptions['filter'], - sort: StringifyOptions['sort'], - allowDots: StringifyOptions['allowDots'], - serializeDate: StringifyOptions['serializeDate'], - format: StringifyOptions['format'], - formatter: StringifyOptions['formatter'], - encodeValuesOnly: boolean, - charset: StringifyOptions['charset'], - sideChannel: WeakMap, -) { - let obj = object; - - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { - // Where object last appeared in the ref tree - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== 'undefined') { - if (pos === step) { - throw new RangeError('Cyclic object value'); - } else { - find_flag = true; // Break while - } - } - if (typeof tmp_sc.get(sentinel) === 'undefined') { - step = 0; - } - } - - if (typeof filter === 'function') { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === 'comma' && is_array(obj)) { - obj = maybe_map(obj, function (value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); - } - - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? - // @ts-expect-error - encoder(prefix, defaults.encoder, charset, 'key', format) - : prefix; - } - - obj = ''; - } - - if (is_non_nullish_primitive(obj) || is_buffer(obj)) { - if (encoder) { - const key_value = - encodeValuesOnly ? prefix - // @ts-expect-error - : encoder(prefix, defaults.encoder, charset, 'key', format); - return [ - formatter?.(key_value) + - '=' + - // @ts-expect-error - formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)), - ]; - } - return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; - } - - const values: string[] = []; - - if (typeof obj === 'undefined') { - return values; - } - - let obj_keys; - if (generateArrayPrefix === 'comma' && is_array(obj)) { - // we need to join elements in - if (encodeValuesOnly && encoder) { - // @ts-expect-error values only - obj = maybe_map(obj, encoder); - } - obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; - } else if (is_array(filter)) { - obj_keys = filter; - } else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); - - const adjusted_prefix = - commaRoundTrip && is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; - - if (allowEmptyArrays && is_array(obj) && obj.length === 0) { - return adjusted_prefix + '[]'; - } - - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = - // @ts-ignore - typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key as any]; - - if (skipNulls && value === null) { - continue; - } - - // @ts-ignore - const encoded_key = allowDots && encodeDotInKeys ? (key as any).replace(/\./g, '%2E') : key; - const key_prefix = - is_array(obj) ? - typeof generateArrayPrefix === 'function' ? - generateArrayPrefix(adjusted_prefix, encoded_key) - : adjusted_prefix - : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); - - sideChannel.set(object, step); - const valueSideChannel = new WeakMap(); - valueSideChannel.set(sentinel, sideChannel); - push_to_array( - values, - inner_stringify( - value, - key_prefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === 'comma' && encodeValuesOnly && is_array(obj) ? null : encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel, - ), - ); - } - - return values; -} - -function normalize_stringify_options( - opts: StringifyOptions = defaults, -): NonNullableProperties> & { indices?: boolean } { - if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { - throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); - } - - if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { - throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); - } - - if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { - throw new TypeError('Encoder has to be a function.'); - } - - const charset = opts.charset || defaults.charset; - if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { - throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); - } - - let format = default_format; - if (typeof opts.format !== 'undefined') { - if (!has.call(formatters, opts.format)) { - throw new TypeError('Unknown format option provided.'); - } - format = opts.format; - } - const formatter = formatters[format]; - - let filter = defaults.filter; - if (typeof opts.filter === 'function' || is_array(opts.filter)) { - filter = opts.filter; - } - - let arrayFormat: StringifyOptions['arrayFormat']; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { - arrayFormat = opts.arrayFormat; - } else if ('indices' in opts) { - arrayFormat = opts.indices ? 'indices' : 'repeat'; - } else { - arrayFormat = defaults.arrayFormat; - } - - if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { - throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); - } - - const allowDots = - typeof opts.allowDots === 'undefined' ? - !!opts.encodeDotInKeys === true ? - true - : defaults.allowDots - : !!opts.allowDots; - - return { - addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, - // @ts-ignore - allowDots: allowDots, - allowEmptyArrays: - typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat: arrayFormat, - charset: charset, - charsetSentinel: - typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, - encodeDotInKeys: - typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, - encodeValuesOnly: - typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter: filter, - format: format, - formatter: formatter, - serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, - // @ts-ignore - sort: typeof opts.sort === 'function' ? opts.sort : null, - strictNullHandling: - typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, - }; -} - -export function stringify(object: any, opts: StringifyOptions = {}) { - let obj = object; - const options = normalize_stringify_options(opts); - - let obj_keys: PropertyKey[] | undefined; - let filter; - - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } else if (is_array(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - - const keys: string[] = []; - - if (typeof obj !== 'object' || obj === null) { - return ''; - } - - const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; - - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - - if (options.sort) { - obj_keys.sort(options.sort); - } - - const sideChannel = new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]!; - - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array( - keys, - inner_stringify( - obj[key], - key, - // @ts-expect-error - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel, - ), - ); - } - - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? '?' : ''; - - if (options.charsetSentinel) { - if (options.charset === 'iso-8859-1') { - // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark - prefix += 'utf8=%26%2310003%3B&'; - } else { - // encodeURIComponent('✓') - prefix += 'utf8=%E2%9C%93&'; - } - } - - return joined.length > 0 ? prefix + joined : ''; -} diff --git a/src/internal/qs/types.ts b/src/internal/qs/types.ts deleted file mode 100644 index 7c28dbb..0000000 --- a/src/internal/qs/types.ts +++ /dev/null @@ -1,71 +0,0 @@ -export type Format = 'RFC1738' | 'RFC3986'; - -export type DefaultEncoder = (str: any, defaultEncoder?: any, charset?: string) => string; -export type DefaultDecoder = (str: string, decoder?: any, charset?: string) => string; - -export type BooleanOptional = boolean | undefined; - -export type StringifyBaseOptions = { - delimiter?: string; - allowDots?: boolean; - encodeDotInKeys?: boolean; - strictNullHandling?: boolean; - skipNulls?: boolean; - encode?: boolean; - encoder?: ( - str: any, - defaultEncoder: DefaultEncoder, - charset: string, - type: 'key' | 'value', - format?: Format, - ) => string; - filter?: Array | ((prefix: PropertyKey, value: any) => any); - arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma'; - indices?: boolean; - sort?: ((a: PropertyKey, b: PropertyKey) => number) | null; - serializeDate?: (d: Date) => string; - format?: 'RFC1738' | 'RFC3986'; - formatter?: (str: PropertyKey) => string; - encodeValuesOnly?: boolean; - addQueryPrefix?: boolean; - charset?: 'utf-8' | 'iso-8859-1'; - charsetSentinel?: boolean; - allowEmptyArrays?: boolean; - commaRoundTrip?: boolean; -}; - -export type StringifyOptions = StringifyBaseOptions; - -export type ParseBaseOptions = { - comma?: boolean; - delimiter?: string | RegExp; - depth?: number | false; - decoder?: (str: string, defaultDecoder: DefaultDecoder, charset: string, type: 'key' | 'value') => any; - arrayLimit?: number; - parseArrays?: boolean; - plainObjects?: boolean; - allowPrototypes?: boolean; - allowSparse?: boolean; - parameterLimit?: number; - strictDepth?: boolean; - strictNullHandling?: boolean; - ignoreQueryPrefix?: boolean; - charset?: 'utf-8' | 'iso-8859-1'; - charsetSentinel?: boolean; - interpretNumericEntities?: boolean; - allowEmptyArrays?: boolean; - duplicates?: 'combine' | 'first' | 'last'; - allowDots?: boolean; - decodeDotInKeys?: boolean; -}; - -export type ParseOptions = ParseBaseOptions; - -export type ParsedQs = { - [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[]; -}; - -// Type to remove null or undefined union from each property -export type NonNullableProperties = { - [K in keyof T]-?: Exclude; -}; diff --git a/src/internal/qs/utils.ts b/src/internal/qs/utils.ts deleted file mode 100644 index 113b18f..0000000 --- a/src/internal/qs/utils.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { RFC1738 } from './formats'; -import type { DefaultEncoder, Format } from './types'; - -const has = Object.prototype.hasOwnProperty; -const is_array = Array.isArray; - -const hex_table = (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); - } - - return array; -})(); - -function compact_queue>(queue: Array<{ obj: T; prop: string }>) { - while (queue.length > 1) { - const item = queue.pop(); - if (!item) continue; - - const obj = item.obj[item.prop]; - - if (is_array(obj)) { - const compacted: unknown[] = []; - - for (let j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); - } - } - - // @ts-ignore - item.obj[item.prop] = compacted; - } - } -} - -function array_to_object(source: any[], options: { plainObjects: boolean }) { - const obj = options && options.plainObjects ? Object.create(null) : {}; - for (let i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; - } - } - - return obj; -} - -export function merge( - target: any, - source: any, - options: { plainObjects?: boolean; allowPrototypes?: boolean } = {}, -) { - if (!source) { - return target; - } - - if (typeof source !== 'object') { - if (is_array(target)) { - target.push(source); - } else if (target && typeof target === 'object') { - if ( - (options && (options.plainObjects || options.allowPrototypes)) || - !has.call(Object.prototype, source) - ) { - target[source] = true; - } - } else { - return [target, source]; - } - - return target; - } - - if (!target || typeof target !== 'object') { - return [target].concat(source); - } - - let mergeTarget = target; - if (is_array(target) && !is_array(source)) { - // @ts-ignore - mergeTarget = array_to_object(target, options); - } - - if (is_array(target) && is_array(source)) { - source.forEach(function (item, i) { - if (has.call(target, i)) { - const targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = merge(targetItem, item, options); - } else { - target.push(item); - } - } else { - target[i] = item; - } - }); - return target; - } - - return Object.keys(source).reduce(function (acc, key) { - const value = source[key]; - - if (has.call(acc, key)) { - acc[key] = merge(acc[key], value, options); - } else { - acc[key] = value; - } - return acc; - }, mergeTarget); -} - -export function assign_single_source(target: any, source: any) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); -} - -export function decode(str: string, _: any, charset: string) { - const strWithoutPlus = str.replace(/\+/g, ' '); - if (charset === 'iso-8859-1') { - // unescape never throws, no try...catch needed: - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - // utf-8 - try { - return decodeURIComponent(strWithoutPlus); - } catch (e) { - return strWithoutPlus; - } -} - -const limit = 1024; - -export const encode: ( - str: any, - defaultEncoder: DefaultEncoder, - charset: string, - type: 'key' | 'value', - format: Format, -) => string = (str, _defaultEncoder, charset, _kind, format: Format) => { - // This code was originally written by Brian White for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; - } - - let string = str; - if (typeof str === 'symbol') { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== 'string') { - string = String(str); - } - - if (charset === 'iso-8859-1') { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { - return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; - }); - } - - let out = ''; - for (let j = 0; j < string.length; j += limit) { - const segment = string.length >= limit ? string.slice(j, j + limit) : string; - const arr = []; - - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if ( - c === 0x2d || // - - c === 0x2e || // . - c === 0x5f || // _ - c === 0x7e || // ~ - (c >= 0x30 && c <= 0x39) || // 0-9 - (c >= 0x41 && c <= 0x5a) || // a-z - (c >= 0x61 && c <= 0x7a) || // A-Z - (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( ) - ) { - arr[arr.length] = segment.charAt(i); - continue; - } - - if (c < 0x80) { - arr[arr.length] = hex_table[c]; - continue; - } - - if (c < 0x800) { - arr[arr.length] = hex_table[0xc0 | (c >> 6)]! + hex_table[0x80 | (c & 0x3f)]; - continue; - } - - if (c < 0xd800 || c >= 0xe000) { - arr[arr.length] = - hex_table[0xe0 | (c >> 12)]! + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; - continue; - } - - i += 1; - c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); - - arr[arr.length] = - hex_table[0xf0 | (c >> 18)]! + - hex_table[0x80 | ((c >> 12) & 0x3f)] + - hex_table[0x80 | ((c >> 6) & 0x3f)] + - hex_table[0x80 | (c & 0x3f)]; - } - - out += arr.join(''); - } - - return out; -}; - -export function compact(value: any) { - const queue = [{ obj: { o: value }, prop: 'o' }]; - const refs = []; - - for (let i = 0; i < queue.length; ++i) { - const item = queue[i]; - // @ts-ignore - const obj = item.obj[item.prop]; - - const keys = Object.keys(obj); - for (let j = 0; j < keys.length; ++j) { - const key = keys[j]!; - const val = obj[key]; - if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj: obj, prop: key }); - refs.push(val); - } - } - } - - compact_queue(queue); - - return value; -} - -export function is_regexp(obj: any) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -} - -export function is_buffer(obj: any) { - if (!obj || typeof obj !== 'object') { - return false; - } - - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -} - -export function combine(a: any, b: any) { - return [].concat(a, b); -} - -export function maybe_map(val: T[], fn: (v: T) => T) { - if (is_array(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i]!)); - } - return mapped; - } - return fn(val); -} diff --git a/src/resources/assistants/assistants.ts b/src/resources/assistants/assistants.ts deleted file mode 100644 index 8bda2b1..0000000 --- a/src/resources/assistants/assistants.ts +++ /dev/null @@ -1,731 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as AssistantsAPI from './assistants'; -import * as ThreadsAPI from './threads'; - -export class Assistants extends APIResource { - threads: ThreadsAPI.Threads = new ThreadsAPI.Threads(this._client); - - /** - * Modifies an assistant. - */ - create( - assistantId: string, - body: AssistantCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/assistants/${assistantId}`, { body, ...options }); - } - - /** - * Retrieves an assistant. - */ - retrieve(assistantId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/assistants/${assistantId}`, options); - } - - /** - * Returns a list of assistants. - */ - list(query?: AssistantListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: AssistantListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/assistants', { query, ...options }); - } - - /** - * Delete an assistant. - */ - delete(assistantId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.delete(`/assistants/${assistantId}`, options); - } -} - -/** - * Represents an `assistant` that can call the model and use tools. - */ -export interface AssistantObject { - /** - * The identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the assistant was created. - */ - created_at: number; - - /** - * The description of the assistant. The maximum length is 512 characters. - */ - description: string | null; - - /** - * The system instructions that the assistant uses. The maximum length is 256,000 - * characters. - */ - instructions: string | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata: unknown | null; - - /** - * ID of the model to use. You can use the - * [List models](/docs/api-reference/models/list) API to see all of your available - * models, or see our [Model overview](/docs/models/overview) for descriptions of - * them. - */ - model: string; - - /** - * The name of the assistant. The maximum length is 256 characters. - */ - name: string | null; - - /** - * The object type, which is always `assistant`. - */ - object: 'assistant'; - - /** - * A list of tool enabled on the assistant. There can be a maximum of 128 tools per - * assistant. Tools can be of types `code_interpreter`, `file_search`, or - * `function`. - */ - tools: Array< - | AssistantObject.AssistantToolsCode - | AssistantObject.AssistantToolsFileSearch - | AssistantObject.AssistantToolsFunction - >; - - /** - * Specifies the format that the model must output. Compatible with - * [GPT-4o](/docs/models/gpt-4o), - * [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models - * since `gpt-3.5-turbo-1106`. - * - * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - * Outputs which ensures the model will match your supplied JSON schema. Learn more - * in the [Structured Outputs guide](/docs/guides/structured-outputs). - * - * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - * message the model generates is valid JSON. - * - * **Important:** when using JSON mode, you **must** also instruct the model to - * produce JSON yourself via a system or user message. Without this, the model may - * generate an unending stream of whitespace until the generation reaches the token - * limit, resulting in a long-running and seemingly "stuck" request. Also note that - * the message content may be partially cut off if `finish_reason="length"`, which - * indicates the generation exceeded `max_tokens` or the conversation exceeded the - * max context length. - */ - response_format?: - | 'auto' - | AssistantObject.ResponseFormatText - | AssistantObject.ResponseFormatJsonObject - | AssistantObject.ResponseFormatJsonSchema - | null; - - /** - * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - * make the output more random, while lower values like 0.2 will make it more - * focused and deterministic. - */ - temperature?: number | null; - - /** - * A set of resources that are used by the assistant's tools. The resources are - * specific to the type of tool. For example, the `code_interpreter` tool requires - * a list of file IDs, while the `file_search` tool requires a list of vector store - * IDs. - */ - tool_resources?: AssistantObject.ToolResources | null; - - /** - * An alternative to sampling with temperature, called nucleus sampling, where the - * model considers the results of the tokens with top_p probability mass. So 0.1 - * means only the tokens comprising the top 10% probability mass are considered. - * - * We generally recommend altering this or temperature but not both. - */ - top_p?: number | null; -} - -export namespace AssistantObject { - export interface AssistantToolsCode { - /** - * The type of tool being defined: `code_interpreter` - */ - type: 'code_interpreter'; - } - - export interface AssistantToolsFileSearch { - /** - * The type of tool being defined: `file_search` - */ - type: 'file_search'; - - /** - * Overrides for the file search tool. - */ - file_search?: AssistantToolsFileSearch.FileSearch; - } - - export namespace AssistantToolsFileSearch { - /** - * Overrides for the file search tool. - */ - export interface FileSearch { - /** - * The maximum number of results the file search tool should output. The default is - * 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between - * 1 and 50 inclusive. - * - * Note that the file search tool may output fewer than `max_num_results` results. - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - max_num_results?: number; - - /** - * The ranking options for the file search. If not specified, the file search tool - * will use the `auto` ranker and a score_threshold of 0. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - ranking_options?: FileSearch.RankingOptions; - } - - export namespace FileSearch { - /** - * The ranking options for the file search. If not specified, the file search tool - * will use the `auto` ranker and a score_threshold of 0. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - export interface RankingOptions { - /** - * The score threshold for the file search. All values must be a floating point - * number between 0 and 1. - */ - score_threshold: number; - - /** - * The ranker to use for the file search. If not specified will use the `auto` - * ranker. - */ - ranker?: 'auto' | 'default_2024_08_21'; - } - } - } - - export interface AssistantToolsFunction { - function: AssistantToolsFunction.Function; - - /** - * The type of tool being defined: `function` - */ - type: 'function'; - } - - export namespace AssistantToolsFunction { - export interface Function { - /** - * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain - * underscores and dashes, with a maximum length of 64. - */ - name: string; - - /** - * A description of what the function does, used by the model to choose when and - * how to call the function. - */ - description?: string; - - /** - * The parameters the functions accepts, described as a JSON Schema object. See the - * [guide](/docs/guides/function-calling) for examples, and the - * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - * documentation about the format. - * - * Omitting `parameters` defines a function with an empty parameter list. - */ - parameters?: Record; - - /** - * Whether to enable strict schema adherence when generating the function call. If - * set to true, the model will follow the exact schema defined in the `parameters` - * field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn - * more about Structured Outputs in the - * [function calling guide](docs/guides/function-calling). - */ - strict?: boolean | null; - } - } - - export interface ResponseFormatText { - /** - * The type of response format being defined: `text` - */ - type: 'text'; - } - - export interface ResponseFormatJsonObject { - /** - * The type of response format being defined: `json_object` - */ - type: 'json_object'; - } - - export interface ResponseFormatJsonSchema { - json_schema: ResponseFormatJsonSchema.JsonSchema; - - /** - * The type of response format being defined: `json_schema` - */ - type: 'json_schema'; - } - - export namespace ResponseFormatJsonSchema { - export interface JsonSchema { - /** - * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores - * and dashes, with a maximum length of 64. - */ - name: string; - - /** - * A description of what the response format is for, used by the model to determine - * how to respond in the format. - */ - description?: string; - - /** - * The schema for the response format, described as a JSON Schema object. - */ - schema?: Record; - - /** - * Whether to enable strict schema adherence when generating the output. If set to - * true, the model will always follow the exact schema defined in the `schema` - * field. Only a subset of JSON Schema is supported when `strict` is `true`. To - * learn more, read the - * [Structured Outputs guide](/docs/guides/structured-outputs). - */ - strict?: boolean | null; - } - } - - /** - * A set of resources that are used by the assistant's tools. The resources are - * specific to the type of tool. For example, the `code_interpreter` tool requires - * a list of file IDs, while the `file_search` tool requires a list of vector store - * IDs. - */ - export interface ToolResources { - code_interpreter?: ToolResources.CodeInterpreter; - - file_search?: ToolResources.FileSearch; - } - - export namespace ToolResources { - export interface CodeInterpreter { - /** - * A list of [file](/docs/api-reference/files) IDs made available to the - * `code_interpreter`` tool. There can be a maximum of 20 files associated with the - * tool. - */ - file_ids?: Array; - } - - export interface FileSearch { - /** - * The ID of the [vector store](/docs/api-reference/vector-stores/object) attached - * to this assistant. There can be a maximum of 1 vector store attached to the - * assistant. - */ - vector_store_ids?: Array; - } - } -} - -export interface AssistantListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface AssistantDeleteResponse { - id: string; - - deleted: boolean; - - object: 'assistant.deleted'; -} - -export interface AssistantCreateParams { - /** - * The description of the assistant. The maximum length is 512 characters. - */ - description?: string | null; - - /** - * The system instructions that the assistant uses. The maximum length is 256,000 - * characters. - */ - instructions?: string | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; - - /** - * ID of the model to use. You can use the - * [List models](/docs/api-reference/models/list) API to see all of your available - * models, or see our [Model overview](/docs/models/overview) for descriptions of - * them. - */ - model?: string; - - /** - * The name of the assistant. The maximum length is 256 characters. - */ - name?: string | null; - - /** - * Specifies the format that the model must output. Compatible with - * [GPT-4o](/docs/models/gpt-4o), - * [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models - * since `gpt-3.5-turbo-1106`. - * - * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - * Outputs which ensures the model will match your supplied JSON schema. Learn more - * in the [Structured Outputs guide](/docs/guides/structured-outputs). - * - * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - * message the model generates is valid JSON. - * - * **Important:** when using JSON mode, you **must** also instruct the model to - * produce JSON yourself via a system or user message. Without this, the model may - * generate an unending stream of whitespace until the generation reaches the token - * limit, resulting in a long-running and seemingly "stuck" request. Also note that - * the message content may be partially cut off if `finish_reason="length"`, which - * indicates the generation exceeded `max_tokens` or the conversation exceeded the - * max context length. - */ - response_format?: - | 'auto' - | AssistantCreateParams.ResponseFormatText - | AssistantCreateParams.ResponseFormatJsonObject - | AssistantCreateParams.ResponseFormatJsonSchema - | null; - - /** - * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - * make the output more random, while lower values like 0.2 will make it more - * focused and deterministic. - */ - temperature?: number | null; - - /** - * A set of resources that are used by the assistant's tools. The resources are - * specific to the type of tool. For example, the `code_interpreter` tool requires - * a list of file IDs, while the `file_search` tool requires a list of vector store - * IDs. - */ - tool_resources?: AssistantCreateParams.ToolResources | null; - - /** - * A list of tool enabled on the assistant. There can be a maximum of 128 tools per - * assistant. Tools can be of types `code_interpreter`, `file_search`, or - * `function`. - */ - tools?: Array< - | AssistantCreateParams.AssistantToolsCode - | AssistantCreateParams.AssistantToolsFileSearch - | AssistantCreateParams.AssistantToolsFunction - >; - - /** - * An alternative to sampling with temperature, called nucleus sampling, where the - * model considers the results of the tokens with top_p probability mass. So 0.1 - * means only the tokens comprising the top 10% probability mass are considered. - * - * We generally recommend altering this or temperature but not both. - */ - top_p?: number | null; -} - -export namespace AssistantCreateParams { - export interface ResponseFormatText { - /** - * The type of response format being defined: `text` - */ - type: 'text'; - } - - export interface ResponseFormatJsonObject { - /** - * The type of response format being defined: `json_object` - */ - type: 'json_object'; - } - - export interface ResponseFormatJsonSchema { - json_schema: ResponseFormatJsonSchema.JsonSchema; - - /** - * The type of response format being defined: `json_schema` - */ - type: 'json_schema'; - } - - export namespace ResponseFormatJsonSchema { - export interface JsonSchema { - /** - * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores - * and dashes, with a maximum length of 64. - */ - name: string; - - /** - * A description of what the response format is for, used by the model to determine - * how to respond in the format. - */ - description?: string; - - /** - * The schema for the response format, described as a JSON Schema object. - */ - schema?: Record; - - /** - * Whether to enable strict schema adherence when generating the output. If set to - * true, the model will always follow the exact schema defined in the `schema` - * field. Only a subset of JSON Schema is supported when `strict` is `true`. To - * learn more, read the - * [Structured Outputs guide](/docs/guides/structured-outputs). - */ - strict?: boolean | null; - } - } - - /** - * A set of resources that are used by the assistant's tools. The resources are - * specific to the type of tool. For example, the `code_interpreter` tool requires - * a list of file IDs, while the `file_search` tool requires a list of vector store - * IDs. - */ - export interface ToolResources { - code_interpreter?: ToolResources.CodeInterpreter; - - file_search?: ToolResources.FileSearch; - } - - export namespace ToolResources { - export interface CodeInterpreter { - /** - * Overrides the list of [file](/docs/api-reference/files) IDs made available to - * the `code_interpreter` tool. There can be a maximum of 20 files associated with - * the tool. - */ - file_ids?: Array; - } - - export interface FileSearch { - /** - * Overrides the [vector store](/docs/api-reference/vector-stores/object) attached - * to this assistant. There can be a maximum of 1 vector store attached to the - * assistant. - */ - vector_store_ids?: Array; - } - } - - export interface AssistantToolsCode { - /** - * The type of tool being defined: `code_interpreter` - */ - type: 'code_interpreter'; - } - - export interface AssistantToolsFileSearch { - /** - * The type of tool being defined: `file_search` - */ - type: 'file_search'; - - /** - * Overrides for the file search tool. - */ - file_search?: AssistantToolsFileSearch.FileSearch; - } - - export namespace AssistantToolsFileSearch { - /** - * Overrides for the file search tool. - */ - export interface FileSearch { - /** - * The maximum number of results the file search tool should output. The default is - * 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between - * 1 and 50 inclusive. - * - * Note that the file search tool may output fewer than `max_num_results` results. - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - max_num_results?: number; - - /** - * The ranking options for the file search. If not specified, the file search tool - * will use the `auto` ranker and a score_threshold of 0. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - ranking_options?: FileSearch.RankingOptions; - } - - export namespace FileSearch { - /** - * The ranking options for the file search. If not specified, the file search tool - * will use the `auto` ranker and a score_threshold of 0. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - export interface RankingOptions { - /** - * The score threshold for the file search. All values must be a floating point - * number between 0 and 1. - */ - score_threshold: number; - - /** - * The ranker to use for the file search. If not specified will use the `auto` - * ranker. - */ - ranker?: 'auto' | 'default_2024_08_21'; - } - } - } - - export interface AssistantToolsFunction { - function: AssistantToolsFunction.Function; - - /** - * The type of tool being defined: `function` - */ - type: 'function'; - } - - export namespace AssistantToolsFunction { - export interface Function { - /** - * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain - * underscores and dashes, with a maximum length of 64. - */ - name: string; - - /** - * A description of what the function does, used by the model to choose when and - * how to call the function. - */ - description?: string; - - /** - * The parameters the functions accepts, described as a JSON Schema object. See the - * [guide](/docs/guides/function-calling) for examples, and the - * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - * documentation about the format. - * - * Omitting `parameters` defines a function with an empty parameter list. - */ - parameters?: Record; - - /** - * Whether to enable strict schema adherence when generating the function call. If - * set to true, the model will follow the exact schema defined in the `parameters` - * field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn - * more about Structured Outputs in the - * [function calling guide](docs/guides/function-calling). - */ - strict?: boolean | null; - } - } -} - -export interface AssistantListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Sort order by the `created_at` timestamp of the objects. `asc` for ascending - * order and `desc` for descending order. - */ - order?: 'asc' | 'desc'; -} - -export namespace Assistants { - export import AssistantObject = AssistantsAPI.AssistantObject; - export import AssistantListResponse = AssistantsAPI.AssistantListResponse; - export import AssistantDeleteResponse = AssistantsAPI.AssistantDeleteResponse; - export import AssistantCreateParams = AssistantsAPI.AssistantCreateParams; - export import AssistantListParams = AssistantsAPI.AssistantListParams; - export import Threads = ThreadsAPI.Threads; - export import MessageObject = ThreadsAPI.MessageObject; - export import RunObject = ThreadsAPI.RunObject; - export import ThreadObject = ThreadsAPI.ThreadObject; -} diff --git a/src/resources/assistants/index.ts b/src/resources/assistants/index.ts deleted file mode 100644 index 7762f91..0000000 --- a/src/resources/assistants/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { - AssistantObject, - AssistantListResponse, - AssistantDeleteResponse, - AssistantCreateParams, - AssistantListParams, - Assistants, -} from './assistants'; -export { MessageObject, RunObject, ThreadObject, Threads } from './threads'; diff --git a/src/resources/assistants/threads.ts b/src/resources/assistants/threads.ts deleted file mode 100644 index e23ce8b..0000000 --- a/src/resources/assistants/threads.ts +++ /dev/null @@ -1,899 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as ThreadsAPI from './threads'; - -export class Threads extends APIResource {} - -/** - * Represents a message within a [thread](/docs/api-reference/threads). - */ -export interface MessageObject { - /** - * The identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * If applicable, the ID of the [assistant](/docs/api-reference/assistants) that - * authored this message. - */ - assistant_id: string | null; - - /** - * A list of files attached to the message, and the tools they were added to. - */ - attachments: Array | null; - - /** - * The Unix timestamp (in seconds) for when the message was completed. - */ - completed_at: number | null; - - /** - * The content of the message in array of text and/or images. - */ - content: Array< - | MessageObject.MessageContentImageFileObject - | MessageObject.MessageContentImageURLObject - | MessageObject.MessageContentTextObject - | MessageObject.MessageContentRefusalObject - >; - - /** - * The Unix timestamp (in seconds) for when the message was created. - */ - created_at: number; - - /** - * The Unix timestamp (in seconds) for when the message was marked as incomplete. - */ - incomplete_at: number | null; - - /** - * On an incomplete message, details about why the message is incomplete. - */ - incomplete_details: MessageObject.IncompleteDetails | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata: unknown | null; - - /** - * The object type, which is always `thread.message`. - */ - object: 'thread.message'; - - /** - * The entity that produced the message. One of `user` or `assistant`. - */ - role: 'user' | 'assistant'; - - /** - * The ID of the [run](/docs/api-reference/runs) associated with the creation of - * this message. Value is `null` when messages are created manually using the - * create message or create thread endpoints. - */ - run_id: string | null; - - /** - * The status of the message, which can be either `in_progress`, `incomplete`, or - * `completed`. - */ - status: 'in_progress' | 'incomplete' | 'completed'; - - /** - * The [thread](/docs/api-reference/threads) ID that this message belongs to. - */ - thread_id: string; -} - -export namespace MessageObject { - export interface Attachment { - /** - * The ID of the file to attach to the message. - */ - file_id?: string; - - /** - * The tools to add this file to. - */ - tools?: Array; - } - - export namespace Attachment { - export interface AssistantToolsCode { - /** - * The type of tool being defined: `code_interpreter` - */ - type: 'code_interpreter'; - } - - export interface AssistantToolsFileSearchTypeOnly { - /** - * The type of tool being defined: `file_search` - */ - type: 'file_search'; - } - } - - /** - * References an image [File](/docs/api-reference/files) in the content of a - * message. - */ - export interface MessageContentImageFileObject { - image_file: MessageContentImageFileObject.ImageFile; - - /** - * Always `image_file`. - */ - type: 'image_file'; - } - - export namespace MessageContentImageFileObject { - export interface ImageFile { - /** - * The [File](/docs/api-reference/files) ID of the image in the message content. - * Set `purpose="vision"` when uploading the File if you need to later display the - * file content. - */ - file_id: string; - - /** - * Specifies the detail level of the image if specified by the user. `low` uses - * fewer tokens, you can opt in to high resolution using `high`. - */ - detail?: 'auto' | 'low' | 'high'; - } - } - - /** - * References an image URL in the content of a message. - */ - export interface MessageContentImageURLObject { - image_url: MessageContentImageURLObject.ImageURL; - - /** - * The type of the content part. - */ - type: 'image_url'; - } - - export namespace MessageContentImageURLObject { - export interface ImageURL { - /** - * The external URL of the image, must be a supported image types: jpeg, jpg, png, - * gif, webp. - */ - url: string; - - /** - * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in - * to high resolution using `high`. Default value is `auto` - */ - detail?: 'auto' | 'low' | 'high'; - } - } - - /** - * The text content that is part of a message. - */ - export interface MessageContentTextObject { - text: MessageContentTextObject.Text; - - /** - * Always `text`. - */ - type: 'text'; - } - - export namespace MessageContentTextObject { - export interface Text { - annotations: Array< - | Text.MessageContentTextAnnotationsFileCitationObject - | Text.MessageContentTextAnnotationsFilePathObject - >; - - /** - * The data that makes up the text. - */ - value: string; - } - - export namespace Text { - /** - * A citation within the message that points to a specific quote from a specific - * File associated with the assistant or the message. Generated when the assistant - * uses the "file_search" tool to search files. - */ - export interface MessageContentTextAnnotationsFileCitationObject { - end_index: number; - - file_citation: MessageContentTextAnnotationsFileCitationObject.FileCitation; - - start_index: number; - - /** - * The text in the message content that needs to be replaced. - */ - text: string; - - /** - * Always `file_citation`. - */ - type: 'file_citation'; - } - - export namespace MessageContentTextAnnotationsFileCitationObject { - export interface FileCitation { - /** - * The ID of the specific File the citation is from. - */ - file_id: string; - } - } - - /** - * A URL for the file that's generated when the assistant used the - * `code_interpreter` tool to generate a file. - */ - export interface MessageContentTextAnnotationsFilePathObject { - end_index: number; - - file_path: MessageContentTextAnnotationsFilePathObject.FilePath; - - start_index: number; - - /** - * The text in the message content that needs to be replaced. - */ - text: string; - - /** - * Always `file_path`. - */ - type: 'file_path'; - } - - export namespace MessageContentTextAnnotationsFilePathObject { - export interface FilePath { - /** - * The ID of the file that was generated. - */ - file_id: string; - } - } - } - } - - /** - * The refusal content generated by the assistant. - */ - export interface MessageContentRefusalObject { - refusal: string; - - /** - * Always `refusal`. - */ - type: 'refusal'; - } - - /** - * On an incomplete message, details about why the message is incomplete. - */ - export interface IncompleteDetails { - /** - * The reason the message is incomplete. - */ - reason: 'content_filter' | 'max_tokens' | 'run_cancelled' | 'run_expired' | 'run_failed'; - } -} - -/** - * Represents an execution run on a [thread](/docs/api-reference/threads). - */ -export interface RunObject { - /** - * The identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The ID of the [assistant](/docs/api-reference/assistants) used for execution of - * this run. - */ - assistant_id: string; - - /** - * The Unix timestamp (in seconds) for when the run was cancelled. - */ - cancelled_at: number | null; - - /** - * The Unix timestamp (in seconds) for when the run was completed. - */ - completed_at: number | null; - - /** - * The Unix timestamp (in seconds) for when the run was created. - */ - created_at: number; - - /** - * The Unix timestamp (in seconds) for when the run will expire. - */ - expires_at: number | null; - - /** - * The Unix timestamp (in seconds) for when the run failed. - */ - failed_at: number | null; - - /** - * Details on why the run is incomplete. Will be `null` if the run is not - * incomplete. - */ - incomplete_details: RunObject.IncompleteDetails | null; - - /** - * The instructions that the [assistant](/docs/api-reference/assistants) used for - * this run. - */ - instructions: string; - - /** - * The last error associated with this run. Will be `null` if there are no errors. - */ - last_error: RunObject.LastError | null; - - /** - * The maximum number of completion tokens specified to have been used over the - * course of the run. - */ - max_completion_tokens: number | null; - - /** - * The maximum number of prompt tokens specified to have been used over the course - * of the run. - */ - max_prompt_tokens: number | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata: unknown | null; - - /** - * The model that the [assistant](/docs/api-reference/assistants) used for this - * run. - */ - model: string; - - /** - * The object type, which is always `thread.run`. - */ - object: 'thread.run'; - - /** - * Whether to enable - * [parallel function calling](/docs/guides/function-calling/parallel-function-calling) - * during tool use. - */ - parallel_tool_calls: boolean; - - /** - * Details on the action required to continue the run. Will be `null` if no action - * is required. - */ - required_action: RunObject.RequiredAction | null; - - /** - * Specifies the format that the model must output. Compatible with - * [GPT-4o](/docs/models/gpt-4o), - * [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models - * since `gpt-3.5-turbo-1106`. - * - * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - * Outputs which ensures the model will match your supplied JSON schema. Learn more - * in the [Structured Outputs guide](/docs/guides/structured-outputs). - * - * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - * message the model generates is valid JSON. - * - * **Important:** when using JSON mode, you **must** also instruct the model to - * produce JSON yourself via a system or user message. Without this, the model may - * generate an unending stream of whitespace until the generation reaches the token - * limit, resulting in a long-running and seemingly "stuck" request. Also note that - * the message content may be partially cut off if `finish_reason="length"`, which - * indicates the generation exceeded `max_tokens` or the conversation exceeded the - * max context length. - */ - response_format: - | 'auto' - | RunObject.ResponseFormatText - | RunObject.ResponseFormatJsonObject - | RunObject.ResponseFormatJsonSchema - | null; - - /** - * The Unix timestamp (in seconds) for when the run was started. - */ - started_at: number | null; - - /** - * The status of the run, which can be either `queued`, `in_progress`, - * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, - * `incomplete`, or `expired`. - */ - status: - | 'queued' - | 'in_progress' - | 'requires_action' - | 'cancelling' - | 'cancelled' - | 'failed' - | 'completed' - | 'incomplete' - | 'expired'; - - /** - * The ID of the [thread](/docs/api-reference/threads) that was executed on as a - * part of this run. - */ - thread_id: string; - - /** - * Controls which (if any) tool is called by the model. `none` means the model will - * not call any tools and instead generates a message. `auto` is the default value - * and means the model can pick between generating a message or calling one or more - * tools. `required` means the model must call one or more tools before responding - * to the user. Specifying a particular tool like `{"type": "file_search"}` or - * `{"type": "function", "function": {"name": "my_function"}}` forces the model to - * call that tool. - */ - tool_choice: 'none' | 'auto' | 'required' | RunObject.AssistantsNamedToolChoice | null; - - /** - * The list of tools that the [assistant](/docs/api-reference/assistants) used for - * this run. - */ - tools: Array< - RunObject.AssistantToolsCode | RunObject.AssistantToolsFileSearch | RunObject.AssistantToolsFunction - >; - - /** - * Controls for how a thread will be truncated prior to the run. Use this to - * control the intial context window of the run. - */ - truncation_strategy: RunObject.TruncationStrategy | null; - - /** - * Usage statistics related to the run. This value will be `null` if the run is not - * in a terminal state (i.e. `in_progress`, `queued`, etc.). - */ - usage: RunObject.Usage | null; - - /** - * The sampling temperature used for this run. If not set, defaults to 1. - */ - temperature?: number | null; - - /** - * The nucleus sampling value used for this run. If not set, defaults to 1. - */ - top_p?: number | null; -} - -export namespace RunObject { - /** - * Details on why the run is incomplete. Will be `null` if the run is not - * incomplete. - */ - export interface IncompleteDetails { - /** - * The reason why the run is incomplete. This will point to which specific token - * limit was reached over the course of the run. - */ - reason?: 'max_completion_tokens' | 'max_prompt_tokens'; - } - - /** - * The last error associated with this run. Will be `null` if there are no errors. - */ - export interface LastError { - /** - * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. - */ - code: 'server_error' | 'rate_limit_exceeded' | 'invalid_prompt'; - - /** - * A human-readable description of the error. - */ - message: string; - } - - /** - * Details on the action required to continue the run. Will be `null` if no action - * is required. - */ - export interface RequiredAction { - /** - * Details on the tool outputs needed for this run to continue. - */ - submit_tool_outputs: RequiredAction.SubmitToolOutputs; - - /** - * For now, this is always `submit_tool_outputs`. - */ - type: 'submit_tool_outputs'; - } - - export namespace RequiredAction { - /** - * Details on the tool outputs needed for this run to continue. - */ - export interface SubmitToolOutputs { - /** - * A list of the relevant tool calls. - */ - tool_calls: Array; - } - - export namespace SubmitToolOutputs { - /** - * Tool call objects - */ - export interface ToolCall { - /** - * The ID of the tool call. This ID must be referenced when you submit the tool - * outputs in using the - * [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) - * endpoint. - */ - id: string; - - /** - * The function definition. - */ - function: ToolCall.Function; - - /** - * The type of tool call the output is required for. For now, this is always - * `function`. - */ - type: 'function'; - } - - export namespace ToolCall { - /** - * The function definition. - */ - export interface Function { - /** - * The arguments that the model expects you to pass to the function. - */ - arguments: string; - - /** - * The name of the function. - */ - name: string; - } - } - } - } - - export interface ResponseFormatText { - /** - * The type of response format being defined: `text` - */ - type: 'text'; - } - - export interface ResponseFormatJsonObject { - /** - * The type of response format being defined: `json_object` - */ - type: 'json_object'; - } - - export interface ResponseFormatJsonSchema { - json_schema: ResponseFormatJsonSchema.JsonSchema; - - /** - * The type of response format being defined: `json_schema` - */ - type: 'json_schema'; - } - - export namespace ResponseFormatJsonSchema { - export interface JsonSchema { - /** - * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores - * and dashes, with a maximum length of 64. - */ - name: string; - - /** - * A description of what the response format is for, used by the model to determine - * how to respond in the format. - */ - description?: string; - - /** - * The schema for the response format, described as a JSON Schema object. - */ - schema?: Record; - - /** - * Whether to enable strict schema adherence when generating the output. If set to - * true, the model will always follow the exact schema defined in the `schema` - * field. Only a subset of JSON Schema is supported when `strict` is `true`. To - * learn more, read the - * [Structured Outputs guide](/docs/guides/structured-outputs). - */ - strict?: boolean | null; - } - } - - /** - * Specifies a tool the model should use. Use to force the model to call a specific - * tool. - */ - export interface AssistantsNamedToolChoice { - /** - * The type of the tool. If type is `function`, the function name must be set - */ - type: 'function' | 'code_interpreter' | 'file_search'; - - function?: AssistantsNamedToolChoice.Function; - } - - export namespace AssistantsNamedToolChoice { - export interface Function { - /** - * The name of the function to call. - */ - name: string; - } - } - - export interface AssistantToolsCode { - /** - * The type of tool being defined: `code_interpreter` - */ - type: 'code_interpreter'; - } - - export interface AssistantToolsFileSearch { - /** - * The type of tool being defined: `file_search` - */ - type: 'file_search'; - - /** - * Overrides for the file search tool. - */ - file_search?: AssistantToolsFileSearch.FileSearch; - } - - export namespace AssistantToolsFileSearch { - /** - * Overrides for the file search tool. - */ - export interface FileSearch { - /** - * The maximum number of results the file search tool should output. The default is - * 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between - * 1 and 50 inclusive. - * - * Note that the file search tool may output fewer than `max_num_results` results. - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - max_num_results?: number; - - /** - * The ranking options for the file search. If not specified, the file search tool - * will use the `auto` ranker and a score_threshold of 0. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - ranking_options?: FileSearch.RankingOptions; - } - - export namespace FileSearch { - /** - * The ranking options for the file search. If not specified, the file search tool - * will use the `auto` ranker and a score_threshold of 0. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - export interface RankingOptions { - /** - * The score threshold for the file search. All values must be a floating point - * number between 0 and 1. - */ - score_threshold: number; - - /** - * The ranker to use for the file search. If not specified will use the `auto` - * ranker. - */ - ranker?: 'auto' | 'default_2024_08_21'; - } - } - } - - export interface AssistantToolsFunction { - function: AssistantToolsFunction.Function; - - /** - * The type of tool being defined: `function` - */ - type: 'function'; - } - - export namespace AssistantToolsFunction { - export interface Function { - /** - * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain - * underscores and dashes, with a maximum length of 64. - */ - name: string; - - /** - * A description of what the function does, used by the model to choose when and - * how to call the function. - */ - description?: string; - - /** - * The parameters the functions accepts, described as a JSON Schema object. See the - * [guide](/docs/guides/function-calling) for examples, and the - * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - * documentation about the format. - * - * Omitting `parameters` defines a function with an empty parameter list. - */ - parameters?: Record; - - /** - * Whether to enable strict schema adherence when generating the function call. If - * set to true, the model will follow the exact schema defined in the `parameters` - * field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn - * more about Structured Outputs in the - * [function calling guide](docs/guides/function-calling). - */ - strict?: boolean | null; - } - } - - /** - * Controls for how a thread will be truncated prior to the run. Use this to - * control the intial context window of the run. - */ - export interface TruncationStrategy { - /** - * The truncation strategy to use for the thread. The default is `auto`. If set to - * `last_messages`, the thread will be truncated to the n most recent messages in - * the thread. When set to `auto`, messages in the middle of the thread will be - * dropped to fit the context length of the model, `max_prompt_tokens`. - */ - type: 'auto' | 'last_messages'; - - /** - * The number of most recent messages from the thread when constructing the context - * for the run. - */ - last_messages?: number | null; - } - - /** - * Usage statistics related to the run. This value will be `null` if the run is not - * in a terminal state (i.e. `in_progress`, `queued`, etc.). - */ - export interface Usage { - /** - * Number of completion tokens used over the course of the run. - */ - completion_tokens: number; - - /** - * Number of prompt tokens used over the course of the run. - */ - prompt_tokens: number; - - /** - * Total number of tokens used (prompt + completion). - */ - total_tokens: number; - } -} - -/** - * Represents a thread that contains [messages](/docs/api-reference/messages). - */ -export interface ThreadObject { - /** - * The identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the thread was created. - */ - created_at: number; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata: unknown | null; - - /** - * The object type, which is always `thread`. - */ - object: 'thread'; - - /** - * A set of resources that are made available to the assistant's tools in this - * thread. The resources are specific to the type of tool. For example, the - * `code_interpreter` tool requires a list of file IDs, while the `file_search` - * tool requires a list of vector store IDs. - */ - tool_resources: ThreadObject.ToolResources | null; -} - -export namespace ThreadObject { - /** - * A set of resources that are made available to the assistant's tools in this - * thread. The resources are specific to the type of tool. For example, the - * `code_interpreter` tool requires a list of file IDs, while the `file_search` - * tool requires a list of vector store IDs. - */ - export interface ToolResources { - code_interpreter?: ToolResources.CodeInterpreter; - - file_search?: ToolResources.FileSearch; - } - - export namespace ToolResources { - export interface CodeInterpreter { - /** - * A list of [file](/docs/api-reference/files) IDs made available to the - * `code_interpreter` tool. There can be a maximum of 20 files associated with the - * tool. - */ - file_ids?: Array; - } - - export interface FileSearch { - /** - * The [vector store](/docs/api-reference/vector-stores/object) attached to this - * thread. There can be a maximum of 1 vector store attached to the thread. - */ - vector_store_ids?: Array; - } - } -} - -export namespace Threads { - export import MessageObject = ThreadsAPI.MessageObject; - export import RunObject = ThreadsAPI.RunObject; - export import ThreadObject = ThreadsAPI.ThreadObject; -} diff --git a/src/resources/audio/audio.ts b/src/resources/audio/audio.ts deleted file mode 100644 index 9b026ec..0000000 --- a/src/resources/audio/audio.ts +++ /dev/null @@ -1,23 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as SpeechAPI from './speech'; -import * as TranscriptionsAPI from './transcriptions'; -import * as TranslationsAPI from './translations'; - -export class Audio extends APIResource { - speech: SpeechAPI.Speech = new SpeechAPI.Speech(this._client); - transcriptions: TranscriptionsAPI.Transcriptions = new TranscriptionsAPI.Transcriptions(this._client); - translations: TranslationsAPI.Translations = new TranslationsAPI.Translations(this._client); -} - -export namespace Audio { - export import Speech = SpeechAPI.Speech; - export import SpeechCreateParams = SpeechAPI.SpeechCreateParams; - export import Transcriptions = TranscriptionsAPI.Transcriptions; - export import TranscriptionCreateResponse = TranscriptionsAPI.TranscriptionCreateResponse; - export import TranscriptionCreateParams = TranscriptionsAPI.TranscriptionCreateParams; - export import Translations = TranslationsAPI.Translations; - export import TranslationCreateResponse = TranslationsAPI.TranslationCreateResponse; - export import TranslationCreateParams = TranslationsAPI.TranslationCreateParams; -} diff --git a/src/resources/audio/index.ts b/src/resources/audio/index.ts deleted file mode 100644 index 3a47358..0000000 --- a/src/resources/audio/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { Audio } from './audio'; -export { SpeechCreateParams, Speech } from './speech'; -export { TranscriptionCreateResponse, TranscriptionCreateParams, Transcriptions } from './transcriptions'; -export { TranslationCreateResponse, TranslationCreateParams, Translations } from './translations'; diff --git a/src/resources/audio/speech.ts b/src/resources/audio/speech.ts deleted file mode 100644 index 6a2303e..0000000 --- a/src/resources/audio/speech.ts +++ /dev/null @@ -1,51 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as SpeechAPI from './speech'; -import { type Response } from '../../_shims/index'; - -export class Speech extends APIResource { - /** - * Generates audio from the input text. - */ - create(body: SpeechCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/audio/speech', { body, ...options, __binaryResponse: true }); - } -} - -export interface SpeechCreateParams { - /** - * The text to generate audio for. The maximum length is 4096 characters. - */ - input: string; - - /** - * One of the available [TTS models](/docs/models/tts): `tts-1` or `tts-1-hd` - */ - model: (string & {}) | 'tts-1' | 'tts-1-hd'; - - /** - * The voice to use when generating the audio. Supported voices are `alloy`, - * `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are - * available in the - * [Text to speech guide](/docs/guides/text-to-speech/voice-options). - */ - voice: 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer'; - - /** - * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, - * `wav`, and `pcm`. - */ - response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'; - - /** - * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is - * the default. - */ - speed?: number; -} - -export namespace Speech { - export import SpeechCreateParams = SpeechAPI.SpeechCreateParams; -} diff --git a/src/resources/audio/transcriptions.ts b/src/resources/audio/transcriptions.ts deleted file mode 100644 index 601dc45..0000000 --- a/src/resources/audio/transcriptions.ts +++ /dev/null @@ -1,200 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as TranscriptionsAPI from './transcriptions'; - -export class Transcriptions extends APIResource { - /** - * Transcribes audio into the input language. - */ - create( - body: TranscriptionCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post('/audio/transcriptions', Core.multipartFormRequestOptions({ body, ...options })); - } -} - -/** - * Represents a transcription response returned by model, based on the provided - * input. - */ -export type TranscriptionCreateResponse = - | TranscriptionCreateResponse.CreateTranscriptionResponseJson - | TranscriptionCreateResponse.CreateTranscriptionResponseVerboseJson; - -export namespace TranscriptionCreateResponse { - /** - * Represents a transcription response returned by model, based on the provided - * input. - */ - export interface CreateTranscriptionResponseJson { - /** - * The transcribed text. - */ - text: string; - } - - /** - * Represents a verbose json transcription response returned by model, based on the - * provided input. - */ - export interface CreateTranscriptionResponseVerboseJson { - /** - * The duration of the input audio. - */ - duration: number; - - /** - * The language of the input audio. - */ - language: string; - - /** - * The transcribed text. - */ - text: string; - - /** - * Segments of the transcribed text and their corresponding details. - */ - segments?: Array; - - /** - * Extracted words and their corresponding timestamps. - */ - words?: Array; - } - - export namespace CreateTranscriptionResponseVerboseJson { - export interface Segment { - /** - * Unique identifier of the segment. - */ - id: number; - - /** - * Average logprob of the segment. If the value is lower than -1, consider the - * logprobs failed. - */ - avg_logprob: number; - - /** - * Compression ratio of the segment. If the value is greater than 2.4, consider the - * compression failed. - */ - compression_ratio: number; - - /** - * End time of the segment in seconds. - */ - end: number; - - /** - * Probability of no speech in the segment. If the value is higher than 1.0 and the - * `avg_logprob` is below -1, consider this segment silent. - */ - no_speech_prob: number; - - /** - * Seek offset of the segment. - */ - seek: number; - - /** - * Start time of the segment in seconds. - */ - start: number; - - /** - * Temperature parameter used for generating the segment. - */ - temperature: number; - - /** - * Text content of the segment. - */ - text: string; - - /** - * Array of token IDs for the text content. - */ - tokens: Array; - } - - export interface Word { - /** - * End time of the word in seconds. - */ - end: number; - - /** - * Start time of the word in seconds. - */ - start: number; - - /** - * The text content of the word. - */ - word: string; - } - } -} - -export interface TranscriptionCreateParams { - /** - * The audio file object (not file name) to transcribe, in one of these formats: - * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - */ - file: Core.Uploadable; - - /** - * ID of the model to use. Only `whisper-1` (which is powered by our open source - * Whisper V2 model) is currently available. - */ - model: (string & {}) | 'whisper-1'; - - /** - * The language of the input audio. Supplying the input language in - * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will - * improve accuracy and latency. - */ - language?: string; - - /** - * An optional text to guide the model's style or continue a previous audio - * segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the - * audio language. - */ - prompt?: string; - - /** - * The format of the output, in one of these options: `json`, `text`, `srt`, - * `verbose_json`, or `vtt`. - */ - response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; - - /** - * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the - * output more random, while lower values like 0.2 will make it more focused and - * deterministic. If set to 0, the model will use - * [log probability](https://en.wikipedia.org/wiki/Log_probability) to - * automatically increase the temperature until certain thresholds are hit. - */ - temperature?: number; - - /** - * The timestamp granularities to populate for this transcription. - * `response_format` must be set `verbose_json` to use timestamp granularities. - * Either or both of these options are supported: `word`, or `segment`. Note: There - * is no additional latency for segment timestamps, but generating word timestamps - * incurs additional latency. - */ - timestamp_granularities?: Array<'word' | 'segment'>; -} - -export namespace Transcriptions { - export import TranscriptionCreateResponse = TranscriptionsAPI.TranscriptionCreateResponse; - export import TranscriptionCreateParams = TranscriptionsAPI.TranscriptionCreateParams; -} diff --git a/src/resources/audio/translations.ts b/src/resources/audio/translations.ts deleted file mode 100644 index 50ce2d5..0000000 --- a/src/resources/audio/translations.ts +++ /dev/null @@ -1,147 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as TranslationsAPI from './translations'; - -export class Translations extends APIResource { - /** - * Translates audio into English. - */ - create( - body: TranslationCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post('/audio/translations', Core.multipartFormRequestOptions({ body, ...options })); - } -} - -export type TranslationCreateResponse = - | TranslationCreateResponse.CreateTranslationResponseJson - | TranslationCreateResponse.CreateTranslationResponseVerboseJson; - -export namespace TranslationCreateResponse { - export interface CreateTranslationResponseJson { - text: string; - } - - export interface CreateTranslationResponseVerboseJson { - /** - * The duration of the input audio. - */ - duration: number; - - /** - * The language of the output translation (always `english`). - */ - language: string; - - /** - * The translated text. - */ - text: string; - - /** - * Segments of the translated text and their corresponding details. - */ - segments?: Array; - } - - export namespace CreateTranslationResponseVerboseJson { - export interface Segment { - /** - * Unique identifier of the segment. - */ - id: number; - - /** - * Average logprob of the segment. If the value is lower than -1, consider the - * logprobs failed. - */ - avg_logprob: number; - - /** - * Compression ratio of the segment. If the value is greater than 2.4, consider the - * compression failed. - */ - compression_ratio: number; - - /** - * End time of the segment in seconds. - */ - end: number; - - /** - * Probability of no speech in the segment. If the value is higher than 1.0 and the - * `avg_logprob` is below -1, consider this segment silent. - */ - no_speech_prob: number; - - /** - * Seek offset of the segment. - */ - seek: number; - - /** - * Start time of the segment in seconds. - */ - start: number; - - /** - * Temperature parameter used for generating the segment. - */ - temperature: number; - - /** - * Text content of the segment. - */ - text: string; - - /** - * Array of token IDs for the text content. - */ - tokens: Array; - } - } -} - -export interface TranslationCreateParams { - /** - * The audio file object (not file name) translate, in one of these formats: flac, - * mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - */ - file: Core.Uploadable; - - /** - * ID of the model to use. Only `whisper-1` (which is powered by our open source - * Whisper V2 model) is currently available. - */ - model: (string & {}) | 'whisper-1'; - - /** - * An optional text to guide the model's style or continue a previous audio - * segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in - * English. - */ - prompt?: string; - - /** - * The format of the output, in one of these options: `json`, `text`, `srt`, - * `verbose_json`, or `vtt`. - */ - response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; - - /** - * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the - * output more random, while lower values like 0.2 will make it more focused and - * deterministic. If set to 0, the model will use - * [log probability](https://en.wikipedia.org/wiki/Log_probability) to - * automatically increase the temperature until certain thresholds are hit. - */ - temperature?: number; -} - -export namespace Translations { - export import TranslationCreateResponse = TranslationsAPI.TranslationCreateResponse; - export import TranslationCreateParams = TranslationsAPI.TranslationCreateParams; -} diff --git a/src/resources/batches.ts b/src/resources/batches.ts deleted file mode 100644 index c48bf38..0000000 --- a/src/resources/batches.ts +++ /dev/null @@ -1,276 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../resource'; -import { isRequestOptions } from '../core'; -import * as Core from '../core'; -import * as BatchesAPI from './batches'; - -export class Batches extends APIResource { - /** - * Creates and executes a batch from an uploaded file of requests - */ - create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/batches', { body, ...options }); - } - - /** - * Retrieves a batch. - */ - retrieve(batchId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/batches/${batchId}`, options); - } - - /** - * List your organization's batches. - */ - list(query?: BatchListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: BatchListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/batches', { query, ...options }); - } - - /** - * Cancels an in-progress batch. The batch will be in status `cancelling` for up to - * 10 minutes, before changing to `cancelled`, where it will have partial results - * (if any) available in the output file. - */ - cancel(batchId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post(`/batches/${batchId}/cancel`, options); - } -} - -export interface Batch { - id: string; - - /** - * The time frame within which the batch should be processed. - */ - completion_window: string; - - /** - * The Unix timestamp (in seconds) for when the batch was created. - */ - created_at: number; - - /** - * The OpenAI API endpoint used by the batch. - */ - endpoint: string; - - /** - * The ID of the input file for the batch. - */ - input_file_id: string; - - /** - * The object type, which is always `batch`. - */ - object: 'batch'; - - /** - * The current status of the batch. - */ - status: - | 'validating' - | 'failed' - | 'in_progress' - | 'finalizing' - | 'completed' - | 'expired' - | 'cancelling' - | 'cancelled'; - - /** - * The Unix timestamp (in seconds) for when the batch was cancelled. - */ - cancelled_at?: number; - - /** - * The Unix timestamp (in seconds) for when the batch started cancelling. - */ - cancelling_at?: number; - - /** - * The Unix timestamp (in seconds) for when the batch was completed. - */ - completed_at?: number; - - /** - * The ID of the file containing the outputs of requests with errors. - */ - error_file_id?: string; - - errors?: Batch.Errors; - - /** - * The Unix timestamp (in seconds) for when the batch expired. - */ - expired_at?: number; - - /** - * The Unix timestamp (in seconds) for when the batch will expire. - */ - expires_at?: number; - - /** - * The Unix timestamp (in seconds) for when the batch failed. - */ - failed_at?: number; - - /** - * The Unix timestamp (in seconds) for when the batch started finalizing. - */ - finalizing_at?: number; - - /** - * The Unix timestamp (in seconds) for when the batch started processing. - */ - in_progress_at?: number; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; - - /** - * The ID of the file containing the outputs of successfully executed requests. - */ - output_file_id?: string; - - /** - * The request counts for different statuses within the batch. - */ - request_counts?: Batch.RequestCounts; -} - -export namespace Batch { - export interface Errors { - data?: Array; - - /** - * The object type, which is always `list`. - */ - object?: string; - } - - export namespace Errors { - export interface Data { - /** - * An error code identifying the error type. - */ - code?: string; - - /** - * The line number of the input file where the error occurred, if applicable. - */ - line?: number | null; - - /** - * A human-readable message providing more details about the error. - */ - message?: string; - - /** - * The name of the parameter that caused the error, if applicable. - */ - param?: string | null; - } - } - - /** - * The request counts for different statuses within the batch. - */ - export interface RequestCounts { - /** - * Number of requests that have been completed successfully. - */ - completed: number; - - /** - * Number of requests that have failed. - */ - failed: number; - - /** - * Total number of requests in the batch. - */ - total: number; - } -} - -export interface BatchListResponse { - data: Array; - - has_more: boolean; - - object: 'list'; - - first_id?: string; - - last_id?: string; -} - -export interface BatchCreateParams { - /** - * The time frame within which the batch should be processed. Currently only `24h` - * is supported. - */ - completion_window: '24h'; - - /** - * The endpoint to be used for all requests in the batch. Currently - * `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. - * Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 - * embedding inputs across all requests in the batch. - */ - endpoint: '/v1/chat/completions' | '/v1/embeddings' | '/v1/completions'; - - /** - * The ID of an uploaded file that contains requests for the new batch. - * - * See [upload file](/docs/api-reference/files/create) for how to upload a file. - * - * Your input file must be formatted as a - * [JSONL file](/docs/api-reference/batch/request-input), and must be uploaded with - * the purpose `batch`. The file can contain up to 50,000 requests, and can be up - * to 100 MB in size. - */ - input_file_id: string; - - /** - * Optional custom metadata for the batch. - */ - metadata?: Record | null; -} - -export interface BatchListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; -} - -export namespace Batches { - export import Batch = BatchesAPI.Batch; - export import BatchListResponse = BatchesAPI.BatchListResponse; - export import BatchCreateParams = BatchesAPI.BatchCreateParams; - export import BatchListParams = BatchesAPI.BatchListParams; -} diff --git a/src/resources/chats/chats.ts b/src/resources/chats/chats.ts index cdbbb5d..f2bd467 100644 --- a/src/resources/chats/chats.ts +++ b/src/resources/chats/chats.ts @@ -2,13 +2,18 @@ import { APIResource } from '../../resource'; import * as CompletionsAPI from './completions'; +import { CompletionCreateParams, CompletionCreateResponse, Completions } from './completions'; export class Chats extends APIResource { completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this._client); } -export namespace Chats { - export import Completions = CompletionsAPI.Completions; - export import CompletionCreateResponse = CompletionsAPI.CompletionCreateResponse; - export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams; +Chats.Completions = Completions; + +export declare namespace Chats { + export { + Completions as Completions, + type CompletionCreateResponse as CompletionCreateResponse, + type CompletionCreateParams as CompletionCreateParams, + }; } diff --git a/src/resources/chats/completions.ts b/src/resources/chats/completions.ts index 0d88da3..555c9b1 100644 --- a/src/resources/chats/completions.ts +++ b/src/resources/chats/completions.ts @@ -2,7 +2,6 @@ import { APIResource } from '../../resource'; import * as Core from '../../core'; -import * as CompletionsAPI from './completions'; export class Completions extends APIResource { /** @@ -1049,7 +1048,9 @@ export namespace CompletionCreateParams { } } -export namespace Completions { - export import CompletionCreateResponse = CompletionsAPI.CompletionCreateResponse; - export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams; +export declare namespace Completions { + export { + type CompletionCreateResponse as CompletionCreateResponse, + type CompletionCreateParams as CompletionCreateParams, + }; } diff --git a/src/resources/chats/index.ts b/src/resources/chats/index.ts index aa3d27f..ba2f954 100644 --- a/src/resources/chats/index.ts +++ b/src/resources/chats/index.ts @@ -1,4 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. export { Chats } from './chats'; -export { CompletionCreateResponse, CompletionCreateParams, Completions } from './completions'; +export { Completions, type CompletionCreateResponse, type CompletionCreateParams } from './completions'; diff --git a/src/resources/completions.ts b/src/resources/completions.ts index a586aaa..e34c77e 100644 --- a/src/resources/completions.ts +++ b/src/resources/completions.ts @@ -2,7 +2,6 @@ import { APIResource } from '../resource'; import * as Core from '../core'; -import * as CompletionsAPI from './completions'; export class Completions extends APIResource { /** @@ -306,7 +305,9 @@ export namespace CompletionCreateParams { } } -export namespace Completions { - export import CompletionCreateResponse = CompletionsAPI.CompletionCreateResponse; - export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams; +export declare namespace Completions { + export { + type CompletionCreateResponse as CompletionCreateResponse, + type CompletionCreateParams as CompletionCreateParams, + }; } diff --git a/src/resources/embeddings.ts b/src/resources/embeddings.ts deleted file mode 100644 index bd50a17..0000000 --- a/src/resources/embeddings.ts +++ /dev/null @@ -1,121 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../resource'; -import * as Core from '../core'; -import * as EmbeddingsAPI from './embeddings'; - -export class Embeddings extends APIResource { - /** - * Creates an embedding vector representing the input text. - */ - create( - body: EmbeddingCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post('/embeddings', { body, ...options }); - } -} - -export interface EmbeddingCreateResponse { - /** - * The list of embeddings generated by the model. - */ - data: Array; - - /** - * The name of the model used to generate the embedding. - */ - model: string; - - /** - * The object type, which is always "list". - */ - object: 'list'; - - /** - * The usage information for the request. - */ - usage: EmbeddingCreateResponse.Usage; -} - -export namespace EmbeddingCreateResponse { - /** - * Represents an embedding vector returned by embedding endpoint. - */ - export interface Data { - /** - * The embedding vector, which is a list of floats. The length of vector depends on - * the model as listed in the [embedding guide](/docs/guides/embeddings). - */ - embedding: Array; - - /** - * The index of the embedding in the list of embeddings. - */ - index: number; - - /** - * The object type, which is always "embedding". - */ - object: 'embedding'; - } - - /** - * The usage information for the request. - */ - export interface Usage { - /** - * The number of tokens used by the prompt. - */ - prompt_tokens: number; - - /** - * The total number of tokens used by the request. - */ - total_tokens: number; - } -} - -export interface EmbeddingCreateParams { - /** - * Input text to embed, encoded as a string or array of tokens. To embed multiple - * inputs in a single request, pass an array of strings or array of token arrays. - * The input must not exceed the max input tokens for the model (8192 tokens for - * `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 - * dimensions or less. - * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - * for counting tokens. - */ - input: string | Array | Array | Array>; - - /** - * ID of the model to use. You can use the - * [List models](/docs/api-reference/models/list) API to see all of your available - * models, or see our [Model overview](/docs/models/overview) for descriptions of - * them. - */ - model: (string & {}) | 'text-embedding-ada-002' | 'text-embedding-3-small' | 'text-embedding-3-large'; - - /** - * The number of dimensions the resulting output embeddings should have. Only - * supported in `text-embedding-3` and later models. - */ - dimensions?: number; - - /** - * The format to return the embeddings in. Can be either `float` or - * [`base64`](https://pypi.org/project/pybase64/). - */ - encoding_format?: 'float' | 'base64'; - - /** - * A unique identifier representing your end-user, which can help OpenAI to monitor - * and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). - */ - user?: string; -} - -export namespace Embeddings { - export import EmbeddingCreateResponse = EmbeddingsAPI.EmbeddingCreateResponse; - export import EmbeddingCreateParams = EmbeddingsAPI.EmbeddingCreateParams; -} diff --git a/src/resources/files/content.ts b/src/resources/files/content.ts deleted file mode 100644 index 27f0ab9..0000000 --- a/src/resources/files/content.ts +++ /dev/null @@ -1,23 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as ContentAPI from './content'; - -export class Content extends APIResource { - /** - * Returns the contents of the specified file. - */ - retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/files/${fileId}/content`, { - ...options, - headers: { Accept: 'application/json', ...options?.headers }, - }); - } -} - -export type ContentRetrieveResponse = string; - -export namespace Content { - export import ContentRetrieveResponse = ContentAPI.ContentRetrieveResponse; -} diff --git a/src/resources/files/files.ts b/src/resources/files/files.ts deleted file mode 100644 index 22b65ec..0000000 --- a/src/resources/files/files.ts +++ /dev/null @@ -1,167 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as FilesAPI from './files'; -import * as ContentAPI from './content'; - -export class Files extends APIResource { - content: ContentAPI.Content = new ContentAPI.Content(this._client); - - /** - * Upload a file that can be used across various endpoints. Individual files can be - * up to 512 MB, and the size of all files uploaded by one organization can be up - * to 100 GB. - * - * The Assistants API supports files up to 2 million tokens and of specific file - * types. See the [Assistants Tools guide](/docs/assistants/tools) for details. - * - * The Fine-tuning API only supports `.jsonl` files. The input also has certain - * required formats for fine-tuning - * [chat](/docs/api-reference/fine-tuning/chat-input) or - * [completions](/docs/api-reference/fine-tuning/completions-input) models. - * - * The Batch API only supports `.jsonl` files up to 100 MB in size. The input also - * has a specific required [format](/docs/api-reference/batch/request-input). - * - * Please [contact us](https://help.openai.com/) if you need to increase these - * storage limits. - */ - create(body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/files', Core.multipartFormRequestOptions({ body, ...options })); - } - - /** - * Returns information about a specific file. - */ - retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/files/${fileId}`, options); - } - - /** - * Returns a list of files that belong to the user's organization. - */ - list(query?: FileListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: FileListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/files', { query, ...options }); - } - - /** - * Delete a file. - */ - delete(fileId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.delete(`/files/${fileId}`, options); - } -} - -/** - * The `File` object represents a document that has been uploaded to OpenAI. - */ -export interface OpenAIFile { - /** - * The file identifier, which can be referenced in the API endpoints. - */ - id: string; - - /** - * The size of the file, in bytes. - */ - bytes: number; - - /** - * The Unix timestamp (in seconds) for when the file was created. - */ - created_at: number; - - /** - * The name of the file. - */ - filename: string; - - /** - * The object type, which is always `file`. - */ - object: 'file'; - - /** - * The intended purpose of the file. Supported values are `assistants`, - * `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` - * and `vision`. - */ - purpose: - | 'assistants' - | 'assistants_output' - | 'batch' - | 'batch_output' - | 'fine-tune' - | 'fine-tune-results' - | 'vision'; - - /** - * @deprecated: Deprecated. The current status of the file, which can be either - * `uploaded`, `processed`, or `error`. - */ - status: 'uploaded' | 'processed' | 'error'; - - /** - * @deprecated: Deprecated. For details on why a fine-tuning training file failed - * validation, see the `error` field on `fine_tuning.job`. - */ - status_details?: string; -} - -export interface FileListResponse { - data: Array; - - object: 'list'; -} - -export interface FileDeleteResponse { - id: string; - - deleted: boolean; - - object: 'file'; -} - -export interface FileCreateParams { - /** - * The File object (not file name) to be uploaded. - */ - file: Core.Uploadable; - - /** - * The intended purpose of the uploaded file. - * - * Use "assistants" for [Assistants](/docs/api-reference/assistants) and - * [Message](/docs/api-reference/messages) files, "vision" for Assistants image - * file inputs, "batch" for [Batch API](/docs/guides/batch), and "fine-tune" for - * [Fine-tuning](/docs/api-reference/fine-tuning). - */ - purpose: 'assistants' | 'batch' | 'fine-tune' | 'vision'; -} - -export interface FileListParams { - /** - * Only return files with the given purpose. - */ - purpose?: string; -} - -export namespace Files { - export import OpenAIFile = FilesAPI.OpenAIFile; - export import FileListResponse = FilesAPI.FileListResponse; - export import FileDeleteResponse = FilesAPI.FileDeleteResponse; - export import FileCreateParams = FilesAPI.FileCreateParams; - export import FileListParams = FilesAPI.FileListParams; - export import Content = ContentAPI.Content; - export import ContentRetrieveResponse = ContentAPI.ContentRetrieveResponse; -} diff --git a/src/resources/files/index.ts b/src/resources/files/index.ts deleted file mode 100644 index 538a28a..0000000 --- a/src/resources/files/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { ContentRetrieveResponse, Content } from './content'; -export { - OpenAIFile, - FileListResponse, - FileDeleteResponse, - FileCreateParams, - FileListParams, - Files, -} from './files'; diff --git a/src/resources/fine-tuning/fine-tuning.ts b/src/resources/fine-tuning/fine-tuning.ts deleted file mode 100644 index d7f9b8f..0000000 --- a/src/resources/fine-tuning/fine-tuning.ts +++ /dev/null @@ -1,16 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as JobsAPI from './jobs/jobs'; - -export class FineTuning extends APIResource { - jobs: JobsAPI.Jobs = new JobsAPI.Jobs(this._client); -} - -export namespace FineTuning { - export import Jobs = JobsAPI.Jobs; - export import FineTuningJob = JobsAPI.FineTuningJob; - export import JobListResponse = JobsAPI.JobListResponse; - export import JobCreateParams = JobsAPI.JobCreateParams; - export import JobListParams = JobsAPI.JobListParams; -} diff --git a/src/resources/fine-tuning/index.ts b/src/resources/fine-tuning/index.ts deleted file mode 100644 index 347c6b1..0000000 --- a/src/resources/fine-tuning/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { FineTuning } from './fine-tuning'; -export { FineTuningJob, JobListResponse, JobCreateParams, JobListParams, Jobs } from './jobs/index'; diff --git a/src/resources/fine-tuning/jobs/checkpoints.ts b/src/resources/fine-tuning/jobs/checkpoints.ts deleted file mode 100644 index 57b1df0..0000000 --- a/src/resources/fine-tuning/jobs/checkpoints.ts +++ /dev/null @@ -1,121 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as CheckpointsAPI from './checkpoints'; - -export class Checkpoints extends APIResource { - /** - * List checkpoints for a fine-tuning job. - */ - list( - fineTuningJobId: string, - query?: CheckpointListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - fineTuningJobId: string, - query: CheckpointListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(fineTuningJobId, {}, query); - } - return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, { query, ...options }); - } -} - -export interface CheckpointListResponse { - data: Array; - - has_more: boolean; - - object: 'list'; - - first_id?: string | null; - - last_id?: string | null; -} - -export namespace CheckpointListResponse { - /** - * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a - * fine-tuning job that is ready to use. - */ - export interface Data { - /** - * The checkpoint identifier, which can be referenced in the API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the checkpoint was created. - */ - created_at: number; - - /** - * The name of the fine-tuned checkpoint model that is created. - */ - fine_tuned_model_checkpoint: string; - - /** - * The name of the fine-tuning job that this checkpoint was created from. - */ - fine_tuning_job_id: string; - - /** - * Metrics at the step number during the fine-tuning job. - */ - metrics: Data.Metrics; - - /** - * The object type, which is always "fine_tuning.job.checkpoint". - */ - object: 'fine_tuning.job.checkpoint'; - - /** - * The step number that the checkpoint was created at. - */ - step_number: number; - } - - export namespace Data { - /** - * Metrics at the step number during the fine-tuning job. - */ - export interface Metrics { - full_valid_loss?: number; - - full_valid_mean_token_accuracy?: number; - - step?: number; - - train_loss?: number; - - train_mean_token_accuracy?: number; - - valid_loss?: number; - - valid_mean_token_accuracy?: number; - } - } -} - -export interface CheckpointListParams { - /** - * Identifier for the last checkpoint ID from the previous pagination request. - */ - after?: string; - - /** - * Number of checkpoints to retrieve. - */ - limit?: number; -} - -export namespace Checkpoints { - export import CheckpointListResponse = CheckpointsAPI.CheckpointListResponse; - export import CheckpointListParams = CheckpointsAPI.CheckpointListParams; -} diff --git a/src/resources/fine-tuning/jobs/events.ts b/src/resources/fine-tuning/jobs/events.ts deleted file mode 100644 index 0bc525d..0000000 --- a/src/resources/fine-tuning/jobs/events.ts +++ /dev/null @@ -1,68 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as EventsAPI from './events'; - -export class Events extends APIResource { - /** - * Get status updates for a fine-tuning job. - */ - retrieve( - fineTuningJobId: string, - query?: EventRetrieveParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - retrieve(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise; - retrieve( - fineTuningJobId: string, - query: EventRetrieveParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.retrieve(fineTuningJobId, {}, query); - } - return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}/events`, { query, ...options }); - } -} - -export interface EventRetrieveResponse { - data: Array; - - object: 'list'; -} - -export namespace EventRetrieveResponse { - /** - * Fine-tuning job event object - */ - export interface Data { - id: string; - - created_at: number; - - level: 'info' | 'warn' | 'error'; - - message: string; - - object: 'fine_tuning.job.event'; - } -} - -export interface EventRetrieveParams { - /** - * Identifier for the last event from the previous pagination request. - */ - after?: string; - - /** - * Number of events to retrieve. - */ - limit?: number; -} - -export namespace Events { - export import EventRetrieveResponse = EventsAPI.EventRetrieveResponse; - export import EventRetrieveParams = EventsAPI.EventRetrieveParams; -} diff --git a/src/resources/fine-tuning/jobs/index.ts b/src/resources/fine-tuning/jobs/index.ts deleted file mode 100644 index a9d15c2..0000000 --- a/src/resources/fine-tuning/jobs/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { CheckpointListResponse, CheckpointListParams, Checkpoints } from './checkpoints'; -export { EventRetrieveResponse, EventRetrieveParams, Events } from './events'; -export { FineTuningJob, JobListResponse, JobCreateParams, JobListParams, Jobs } from './jobs'; diff --git a/src/resources/fine-tuning/jobs/jobs.ts b/src/resources/fine-tuning/jobs/jobs.ts deleted file mode 100644 index b83c474..0000000 --- a/src/resources/fine-tuning/jobs/jobs.ts +++ /dev/null @@ -1,420 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as JobsAPI from './jobs'; -import * as CheckpointsAPI from './checkpoints'; -import * as EventsAPI from './events'; - -export class Jobs extends APIResource { - events: EventsAPI.Events = new EventsAPI.Events(this._client); - checkpoints: CheckpointsAPI.Checkpoints = new CheckpointsAPI.Checkpoints(this._client); - - /** - * Creates a fine-tuning job which begins the process of creating a new model from - * a given dataset. - * - * Response includes details of the enqueued job including job status and the name - * of the fine-tuned models once complete. - * - * [Learn more about fine-tuning](/docs/guides/fine-tuning) - */ - create(body: JobCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/fine_tuning/jobs', { body, ...options }); - } - - /** - * Get info about a fine-tuning job. - * - * [Learn more about fine-tuning](/docs/guides/fine-tuning) - */ - retrieve(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); - } - - /** - * List your organization's fine-tuning jobs - */ - list(query?: JobListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: JobListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/fine_tuning/jobs', { query, ...options }); - } - - /** - * Immediately cancel a fine-tune job. - */ - cancel(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); - } -} - -/** - * The `fine_tuning.job` object represents a fine-tuning job that has been created - * through the API. - */ -export interface FineTuningJob { - /** - * The object identifier, which can be referenced in the API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the fine-tuning job was created. - */ - created_at: number; - - /** - * For fine-tuning jobs that have `failed`, this will contain more information on - * the cause of the failure. - */ - error: FineTuningJob.Error | null; - - /** - * The name of the fine-tuned model that is being created. The value will be null - * if the fine-tuning job is still running. - */ - fine_tuned_model: string | null; - - /** - * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The - * value will be null if the fine-tuning job is still running. - */ - finished_at: number | null; - - /** - * The hyperparameters used for the fine-tuning job. See the - * [fine-tuning guide](/docs/guides/fine-tuning) for more details. - */ - hyperparameters: FineTuningJob.Hyperparameters; - - /** - * The base model that is being fine-tuned. - */ - model: string; - - /** - * The object type, which is always "fine_tuning.job". - */ - object: 'fine_tuning.job'; - - /** - * The organization that owns the fine-tuning job. - */ - organization_id: string; - - /** - * The compiled results file ID(s) for the fine-tuning job. You can retrieve the - * results with the [Files API](/docs/api-reference/files/retrieve-contents). - */ - result_files: Array; - - /** - * The seed used for the fine-tuning job. - */ - seed: number; - - /** - * The current status of the fine-tuning job, which can be either - * `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. - */ - status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; - - /** - * The total number of billable tokens processed by this fine-tuning job. The value - * will be null if the fine-tuning job is still running. - */ - trained_tokens: number | null; - - /** - * The file ID used for training. You can retrieve the training data with the - * [Files API](/docs/api-reference/files/retrieve-contents). - */ - training_file: string; - - /** - * The file ID used for validation. You can retrieve the validation results with - * the [Files API](/docs/api-reference/files/retrieve-contents). - */ - validation_file: string | null; - - /** - * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to - * finish. The value will be null if the fine-tuning job is not running. - */ - estimated_finish?: number | null; - - /** - * A list of integrations to enable for this fine-tuning job. - */ - integrations?: Array | null; -} - -export namespace FineTuningJob { - /** - * For fine-tuning jobs that have `failed`, this will contain more information on - * the cause of the failure. - */ - export interface Error { - /** - * A machine-readable error code. - */ - code: string; - - /** - * A human-readable error message. - */ - message: string; - - /** - * The parameter that was invalid, usually `training_file` or `validation_file`. - * This field will be null if the failure was not parameter-specific. - */ - param: string | null; - } - - /** - * The hyperparameters used for the fine-tuning job. See the - * [fine-tuning guide](/docs/guides/fine-tuning) for more details. - */ - export interface Hyperparameters { - /** - * The number of epochs to train the model for. An epoch refers to one full cycle - * through the training dataset. "auto" decides the optimal number of epochs based - * on the size of the dataset. If setting the number manually, we support any - * number between 1 and 50 epochs. - */ - n_epochs: 'auto' | number; - } - - export interface Integration { - /** - * The type of the integration being enabled for the fine-tuning job - */ - type: 'wandb'; - - /** - * The settings for your integration with Weights and Biases. This payload - * specifies the project that metrics will be sent to. Optionally, you can set an - * explicit display name for your run, add tags to your run, and set a default - * entity (team, username, etc) to be associated with your run. - */ - wandb: Integration.Wandb; - } - - export namespace Integration { - /** - * The settings for your integration with Weights and Biases. This payload - * specifies the project that metrics will be sent to. Optionally, you can set an - * explicit display name for your run, add tags to your run, and set a default - * entity (team, username, etc) to be associated with your run. - */ - export interface Wandb { - /** - * The name of the project that the new run will be created under. - */ - project: string; - - /** - * The entity to use for the run. This allows you to set the team or username of - * the WandB user that you would like associated with the run. If not set, the - * default entity for the registered WandB API key is used. - */ - entity?: string | null; - - /** - * A display name to set for the run. If not set, we will use the Job ID as the - * name. - */ - name?: string | null; - - /** - * A list of tags to be attached to the newly created run. These tags are passed - * through directly to WandB. Some default tags are generated by OpenAI: - * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". - */ - tags?: Array; - } - } -} - -export interface JobListResponse { - data: Array; - - has_more: boolean; - - object: 'list'; -} - -export interface JobCreateParams { - /** - * The name of the model to fine-tune. You can select one of the - * [supported models](/docs/guides/fine-tuning/which-models-can-be-fine-tuned). - */ - model: (string & {}) | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo' | 'gpt-4o-mini'; - - /** - * The ID of an uploaded file that contains training data. - * - * See [upload file](/docs/api-reference/files/create) for how to upload a file. - * - * Your dataset must be formatted as a JSONL file. Additionally, you must upload - * your file with the purpose `fine-tune`. - * - * The contents of the file should differ depending on if the model uses the - * [chat](/docs/api-reference/fine-tuning/chat-input) or - * [completions](/docs/api-reference/fine-tuning/completions-input) format. - * - * See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. - */ - training_file: string; - - /** - * The hyperparameters used for the fine-tuning job. - */ - hyperparameters?: JobCreateParams.Hyperparameters; - - /** - * A list of integrations to enable for your fine-tuning job. - */ - integrations?: Array | null; - - /** - * The seed controls the reproducibility of the job. Passing in the same seed and - * job parameters should produce the same results, but may differ in rare cases. If - * a seed is not specified, one will be generated for you. - */ - seed?: number | null; - - /** - * A string of up to 64 characters that will be added to your fine-tuned model - * name. - * - * For example, a `suffix` of "custom-model-name" would produce a model name like - * `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. - */ - suffix?: string | null; - - /** - * The ID of an uploaded file that contains validation data. - * - * If you provide this file, the data is used to generate validation metrics - * periodically during fine-tuning. These metrics can be viewed in the fine-tuning - * results file. The same data should not be present in both train and validation - * files. - * - * Your dataset must be formatted as a JSONL file. You must upload your file with - * the purpose `fine-tune`. - * - * See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. - */ - validation_file?: string | null; -} - -export namespace JobCreateParams { - /** - * The hyperparameters used for the fine-tuning job. - */ - export interface Hyperparameters { - /** - * Number of examples in each batch. A larger batch size means that model - * parameters are updated less frequently, but with lower variance. - */ - batch_size?: 'auto' | number; - - /** - * Scaling factor for the learning rate. A smaller learning rate may be useful to - * avoid overfitting. - */ - learning_rate_multiplier?: 'auto' | number; - - /** - * The number of epochs to train the model for. An epoch refers to one full cycle - * through the training dataset. - */ - n_epochs?: 'auto' | number; - } - - export interface Integration { - /** - * The type of integration to enable. Currently, only "wandb" (Weights and Biases) - * is supported. - */ - type: 'wandb'; - - /** - * The settings for your integration with Weights and Biases. This payload - * specifies the project that metrics will be sent to. Optionally, you can set an - * explicit display name for your run, add tags to your run, and set a default - * entity (team, username, etc) to be associated with your run. - */ - wandb: Integration.Wandb; - } - - export namespace Integration { - /** - * The settings for your integration with Weights and Biases. This payload - * specifies the project that metrics will be sent to. Optionally, you can set an - * explicit display name for your run, add tags to your run, and set a default - * entity (team, username, etc) to be associated with your run. - */ - export interface Wandb { - /** - * The name of the project that the new run will be created under. - */ - project: string; - - /** - * The entity to use for the run. This allows you to set the team or username of - * the WandB user that you would like associated with the run. If not set, the - * default entity for the registered WandB API key is used. - */ - entity?: string | null; - - /** - * A display name to set for the run. If not set, we will use the Job ID as the - * name. - */ - name?: string | null; - - /** - * A list of tags to be attached to the newly created run. These tags are passed - * through directly to WandB. Some default tags are generated by OpenAI: - * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". - */ - tags?: Array; - } - } -} - -export interface JobListParams { - /** - * Identifier for the last job from the previous pagination request. - */ - after?: string; - - /** - * Number of fine-tuning jobs to retrieve. - */ - limit?: number; -} - -export namespace Jobs { - export import FineTuningJob = JobsAPI.FineTuningJob; - export import JobListResponse = JobsAPI.JobListResponse; - export import JobCreateParams = JobsAPI.JobCreateParams; - export import JobListParams = JobsAPI.JobListParams; - export import Events = EventsAPI.Events; - export import EventRetrieveResponse = EventsAPI.EventRetrieveResponse; - export import EventRetrieveParams = EventsAPI.EventRetrieveParams; - export import Checkpoints = CheckpointsAPI.Checkpoints; - export import CheckpointListResponse = CheckpointsAPI.CheckpointListResponse; - export import CheckpointListParams = CheckpointsAPI.CheckpointListParams; -} diff --git a/src/resources/images/edits.ts b/src/resources/images/edits.ts deleted file mode 100644 index 6081356..0000000 --- a/src/resources/images/edits.ts +++ /dev/null @@ -1,70 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as EditsAPI from './edits'; -import * as ImagesAPI from './images'; - -export class Edits extends APIResource { - /** - * Creates an edited or extended image given an original image and a prompt. - */ - create(body: EditCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/images/edits', Core.multipartFormRequestOptions({ body, ...options })); - } -} - -export interface EditCreateParams { - /** - * The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask - * is not provided, image must have transparency, which will be used as the mask. - */ - image: Core.Uploadable; - - /** - * A text description of the desired image(s). The maximum length is 1000 - * characters. - */ - prompt: string; - - /** - * An additional image whose fully transparent areas (e.g. where alpha is zero) - * indicate where `image` should be edited. Must be a valid PNG file, less than - * 4MB, and have the same dimensions as `image`. - */ - mask?: Core.Uploadable; - - /** - * The model to use for image generation. Only `dall-e-2` is supported at this - * time. - */ - model?: (string & {}) | 'dall-e-2' | null; - - /** - * The number of images to generate. Must be between 1 and 10. - */ - n?: number | null; - - /** - * The format in which the generated images are returned. Must be one of `url` or - * `b64_json`. URLs are only valid for 60 minutes after the image has been - * generated. - */ - response_format?: 'url' | 'b64_json' | null; - - /** - * The size of the generated images. Must be one of `256x256`, `512x512`, or - * `1024x1024`. - */ - size?: '256x256' | '512x512' | '1024x1024' | null; - - /** - * A unique identifier representing your end-user, which can help OpenAI to monitor - * and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). - */ - user?: string; -} - -export namespace Edits { - export import EditCreateParams = EditsAPI.EditCreateParams; -} diff --git a/src/resources/images/generations.ts b/src/resources/images/generations.ts deleted file mode 100644 index b2aa331..0000000 --- a/src/resources/images/generations.ts +++ /dev/null @@ -1,76 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as GenerationsAPI from './generations'; -import * as ImagesAPI from './images'; - -export class Generations extends APIResource { - /** - * Creates an image given a prompt. - */ - create( - body: GenerationCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post('/images/generations', { body, ...options }); - } -} - -export interface GenerationCreateParams { - /** - * A text description of the desired image(s). The maximum length is 1000 - * characters for `dall-e-2` and 4000 characters for `dall-e-3`. - */ - prompt: string; - - /** - * The model to use for image generation. - */ - model?: (string & {}) | 'dall-e-2' | 'dall-e-3' | null; - - /** - * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only - * `n=1` is supported. - */ - n?: number | null; - - /** - * The quality of the image that will be generated. `hd` creates images with finer - * details and greater consistency across the image. This param is only supported - * for `dall-e-3`. - */ - quality?: 'standard' | 'hd'; - - /** - * The format in which the generated images are returned. Must be one of `url` or - * `b64_json`. URLs are only valid for 60 minutes after the image has been - * generated. - */ - response_format?: 'url' | 'b64_json' | null; - - /** - * The size of the generated images. Must be one of `256x256`, `512x512`, or - * `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or - * `1024x1792` for `dall-e-3` models. - */ - size?: '256x256' | '512x512' | '1024x1024' | '1792x1024' | '1024x1792' | null; - - /** - * The style of the generated images. Must be one of `vivid` or `natural`. Vivid - * causes the model to lean towards generating hyper-real and dramatic images. - * Natural causes the model to produce more natural, less hyper-real looking - * images. This param is only supported for `dall-e-3`. - */ - style?: 'vivid' | 'natural' | null; - - /** - * A unique identifier representing your end-user, which can help OpenAI to monitor - * and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). - */ - user?: string; -} - -export namespace Generations { - export import GenerationCreateParams = GenerationsAPI.GenerationCreateParams; -} diff --git a/src/resources/images/images.ts b/src/resources/images/images.ts deleted file mode 100644 index 2bf0abf..0000000 --- a/src/resources/images/images.ts +++ /dev/null @@ -1,53 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as ImagesAPI from './images'; -import * as EditsAPI from './edits'; -import * as GenerationsAPI from './generations'; -import * as VariationsAPI from './variations'; - -export class Images extends APIResource { - generations: GenerationsAPI.Generations = new GenerationsAPI.Generations(this._client); - edits: EditsAPI.Edits = new EditsAPI.Edits(this._client); - variations: VariationsAPI.Variations = new VariationsAPI.Variations(this._client); -} - -export interface ImageResponse { - created: number; - - data: Array; -} - -export namespace ImageResponse { - /** - * Represents the url or the content of an image generated by the OpenAI API. - */ - export interface Data { - /** - * The base64-encoded JSON of the generated image, if `response_format` is - * `b64_json`. - */ - b64_json?: string; - - /** - * The prompt that was used to generate the image, if there was any revision to the - * prompt. - */ - revised_prompt?: string; - - /** - * The URL of the generated image, if `response_format` is `url` (default). - */ - url?: string; - } -} - -export namespace Images { - export import ImageResponse = ImagesAPI.ImageResponse; - export import Generations = GenerationsAPI.Generations; - export import GenerationCreateParams = GenerationsAPI.GenerationCreateParams; - export import Edits = EditsAPI.Edits; - export import EditCreateParams = EditsAPI.EditCreateParams; - export import Variations = VariationsAPI.Variations; - export import VariationCreateParams = VariationsAPI.VariationCreateParams; -} diff --git a/src/resources/images/index.ts b/src/resources/images/index.ts deleted file mode 100644 index d0d6a24..0000000 --- a/src/resources/images/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { EditCreateParams, Edits } from './edits'; -export { GenerationCreateParams, Generations } from './generations'; -export { ImageResponse, Images } from './images'; -export { VariationCreateParams, Variations } from './variations'; diff --git a/src/resources/images/variations.ts b/src/resources/images/variations.ts deleted file mode 100644 index 25c8d56..0000000 --- a/src/resources/images/variations.ts +++ /dev/null @@ -1,61 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as VariationsAPI from './variations'; -import * as ImagesAPI from './images'; - -export class Variations extends APIResource { - /** - * Creates a variation of a given image. - */ - create( - body: VariationCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post('/images/variations', Core.multipartFormRequestOptions({ body, ...options })); - } -} - -export interface VariationCreateParams { - /** - * The image to use as the basis for the variation(s). Must be a valid PNG file, - * less than 4MB, and square. - */ - image: Core.Uploadable; - - /** - * The model to use for image generation. Only `dall-e-2` is supported at this - * time. - */ - model?: (string & {}) | 'dall-e-2' | null; - - /** - * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only - * `n=1` is supported. - */ - n?: number | null; - - /** - * The format in which the generated images are returned. Must be one of `url` or - * `b64_json`. URLs are only valid for 60 minutes after the image has been - * generated. - */ - response_format?: 'url' | 'b64_json' | null; - - /** - * The size of the generated images. Must be one of `256x256`, `512x512`, or - * `1024x1024`. - */ - size?: '256x256' | '512x512' | '1024x1024' | null; - - /** - * A unique identifier representing your end-user, which can help OpenAI to monitor - * and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). - */ - user?: string; -} - -export namespace Variations { - export import VariationCreateParams = VariationsAPI.VariationCreateParams; -} diff --git a/src/resources/index.ts b/src/resources/index.ts index deb6e75..a745c92 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -2,4 +2,4 @@ export * from './shared'; export { Chats } from './chats/chats'; -export { CompletionCreateResponse, CompletionCreateParams, Completions } from './completions'; +export { Completions, type CompletionCreateResponse, type CompletionCreateParams } from './completions'; diff --git a/src/resources/models.ts b/src/resources/models.ts deleted file mode 100644 index 4d7bfb0..0000000 --- a/src/resources/models.ts +++ /dev/null @@ -1,76 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../resource'; -import * as Core from '../core'; -import * as ModelsAPI from './models'; - -export class Models extends APIResource { - /** - * Retrieves a model instance, providing basic information about the model such as - * the owner and permissioning. - */ - retrieve(model: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/models/${model}`, options); - } - - /** - * Lists the currently available models, and provides basic information about each - * one such as the owner and availability. - */ - list(options?: Core.RequestOptions): Core.APIPromise { - return this._client.get('/models', options); - } - - /** - * Delete a fine-tuned model. You must have the Owner role in your organization to - * delete a model. - */ - delete(model: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.delete(`/models/${model}`, options); - } -} - -/** - * Describes an OpenAI model offering that can be used with the API. - */ -export interface Model { - /** - * The model identifier, which can be referenced in the API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) when the model was created. - */ - created: number; - - /** - * The object type, which is always "model". - */ - object: 'model'; - - /** - * The organization that owns the model. - */ - owned_by: string; -} - -export interface ModelListResponse { - data: Array; - - object: 'list'; -} - -export interface ModelDeleteResponse { - id: string; - - deleted: boolean; - - object: string; -} - -export namespace Models { - export import Model = ModelsAPI.Model; - export import ModelListResponse = ModelsAPI.ModelListResponse; - export import ModelDeleteResponse = ModelsAPI.ModelDeleteResponse; -} diff --git a/src/resources/moderations.ts b/src/resources/moderations.ts deleted file mode 100644 index 60ee43c..0000000 --- a/src/resources/moderations.ts +++ /dev/null @@ -1,363 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../resource'; -import * as Core from '../core'; -import * as ModerationsAPI from './moderations'; - -export class Moderations extends APIResource { - /** - * Classifies if text and/or image inputs are potentially harmful. Learn more in - * the [moderation guide](/docs/guides/moderation). - */ - create( - body: ModerationCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post('/moderations', { body, ...options }); - } -} - -/** - * Represents if a given text input is potentially harmful. - */ -export interface ModerationCreateResponse { - /** - * The unique identifier for the moderation request. - */ - id: string; - - /** - * The model used to generate the moderation results. - */ - model: string; - - /** - * A list of moderation objects. - */ - results: Array; -} - -export namespace ModerationCreateResponse { - export interface Result { - /** - * A list of the categories, and whether they are flagged or not. - */ - categories: Result.Categories; - - /** - * A list of the categories along with the input type(s) that the score applies to. - */ - category_applied_input_types: Result.CategoryAppliedInputTypes; - - /** - * A list of the categories along with their scores as predicted by model. - */ - category_scores: Result.CategoryScores; - - /** - * Whether any of the below categories are flagged. - */ - flagged: boolean; - } - - export namespace Result { - /** - * A list of the categories, and whether they are flagged or not. - */ - export interface Categories { - /** - * Content that expresses, incites, or promotes harassing language towards any - * target. - */ - harassment: boolean; - - /** - * Harassment content that also includes violence or serious harm towards any - * target. - */ - 'harassment/threatening': boolean; - - /** - * Content that expresses, incites, or promotes hate based on race, gender, - * ethnicity, religion, nationality, sexual orientation, disability status, or - * caste. Hateful content aimed at non-protected groups (e.g., chess players) is - * harassment. - */ - hate: boolean; - - /** - * Hateful content that also includes violence or serious harm towards the targeted - * group based on race, gender, ethnicity, religion, nationality, sexual - * orientation, disability status, or caste. - */ - 'hate/threatening': boolean; - - /** - * Content that includes instructions or advice that facilitate the planning or - * execution of wrongdoing, or that gives advice or instruction on how to commit - * illicit acts. For example, "how to shoplift" would fit this category. - */ - illicit: boolean; - - /** - * Content that includes instructions or advice that facilitate the planning or - * execution of wrongdoing that also includes violence, or that gives advice or - * instruction on the procurement of any weapon. - */ - 'illicit/violent': boolean; - - /** - * Content that promotes, encourages, or depicts acts of self-harm, such as - * suicide, cutting, and eating disorders. - */ - 'self-harm': boolean; - - /** - * Content that encourages performing acts of self-harm, such as suicide, cutting, - * and eating disorders, or that gives instructions or advice on how to commit such - * acts. - */ - 'self-harm/instructions': boolean; - - /** - * Content where the speaker expresses that they are engaging or intend to engage - * in acts of self-harm, such as suicide, cutting, and eating disorders. - */ - 'self-harm/intent': boolean; - - /** - * Content meant to arouse sexual excitement, such as the description of sexual - * activity, or that promotes sexual services (excluding sex education and - * wellness). - */ - sexual: boolean; - - /** - * Sexual content that includes an individual who is under 18 years old. - */ - 'sexual/minors': boolean; - - /** - * Content that depicts death, violence, or physical injury. - */ - violence: boolean; - - /** - * Content that depicts death, violence, or physical injury in graphic detail. - */ - 'violence/graphic': boolean; - } - - /** - * A list of the categories along with the input type(s) that the score applies to. - */ - export interface CategoryAppliedInputTypes { - /** - * The applied input type(s) for the category 'harassment'. - */ - harassment: Array<'text'>; - - /** - * The applied input type(s) for the category 'harassment/threatening'. - */ - 'harassment/threatening': Array<'text'>; - - /** - * The applied input type(s) for the category 'hate'. - */ - hate: Array<'text'>; - - /** - * The applied input type(s) for the category 'hate/threatening'. - */ - 'hate/threatening': Array<'text'>; - - /** - * The applied input type(s) for the category 'illicit'. - */ - illicit: Array<'text'>; - - /** - * The applied input type(s) for the category 'illicit/violent'. - */ - 'illicit/violent': Array<'text'>; - - /** - * The applied input type(s) for the category 'self-harm'. - */ - 'self-harm': Array<'text' | 'image'>; - - /** - * The applied input type(s) for the category 'self-harm/instructions'. - */ - 'self-harm/instructions': Array<'text' | 'image'>; - - /** - * The applied input type(s) for the category 'self-harm/intent'. - */ - 'self-harm/intent': Array<'text' | 'image'>; - - /** - * The applied input type(s) for the category 'sexual'. - */ - sexual: Array<'text' | 'image'>; - - /** - * The applied input type(s) for the category 'sexual/minors'. - */ - 'sexual/minors': Array<'text'>; - - /** - * The applied input type(s) for the category 'violence'. - */ - violence: Array<'text' | 'image'>; - - /** - * The applied input type(s) for the category 'violence/graphic'. - */ - 'violence/graphic': Array<'text' | 'image'>; - } - - /** - * A list of the categories along with their scores as predicted by model. - */ - export interface CategoryScores { - /** - * The score for the category 'harassment'. - */ - harassment: number; - - /** - * The score for the category 'harassment/threatening'. - */ - 'harassment/threatening': number; - - /** - * The score for the category 'hate'. - */ - hate: number; - - /** - * The score for the category 'hate/threatening'. - */ - 'hate/threatening': number; - - /** - * The score for the category 'illicit'. - */ - illicit: number; - - /** - * The score for the category 'illicit/violent'. - */ - 'illicit/violent': number; - - /** - * The score for the category 'self-harm'. - */ - 'self-harm': number; - - /** - * The score for the category 'self-harm/instructions'. - */ - 'self-harm/instructions': number; - - /** - * The score for the category 'self-harm/intent'. - */ - 'self-harm/intent': number; - - /** - * The score for the category 'sexual'. - */ - sexual: number; - - /** - * The score for the category 'sexual/minors'. - */ - 'sexual/minors': number; - - /** - * The score for the category 'violence'. - */ - violence: number; - - /** - * The score for the category 'violence/graphic'. - */ - 'violence/graphic': number; - } - } -} - -export interface ModerationCreateParams { - /** - * Input (or inputs) to classify. Can be a single string, an array of strings, or - * an array of multi-modal input objects similar to other models. - */ - input: - | string - | Array - | Array; - - /** - * The content moderation model you would like to use. Learn more in - * [the moderation guide](/docs/guides/moderation), and learn about available - * models [here](/docs/models/moderation). - */ - model?: - | (string & {}) - | 'omni-moderation-latest' - | 'omni-moderation-2024-09-26' - | 'text-moderation-latest' - | 'text-moderation-stable'; -} - -export namespace ModerationCreateParams { - /** - * An object describing an image to classify. - */ - export interface UnionMember0 { - /** - * Contains either an image URL or a data URL for a base64 encoded image. - */ - image_url: UnionMember0.ImageURL; - - /** - * Always `image_url`. - */ - type: 'image_url'; - } - - export namespace UnionMember0 { - /** - * Contains either an image URL or a data URL for a base64 encoded image. - */ - export interface ImageURL { - /** - * Either a URL of the image or the base64 encoded image data. - */ - url: string; - } - } - - /** - * An object describing text to classify. - */ - export interface UnionMember1 { - /** - * A string of text to classify. - */ - text: string; - - /** - * Always `text`. - */ - type: 'text'; - } -} - -export namespace Moderations { - export import ModerationCreateResponse = ModerationsAPI.ModerationCreateResponse; - export import ModerationCreateParams = ModerationsAPI.ModerationCreateParams; -} diff --git a/src/resources/organization/audit-logs.ts b/src/resources/organization/audit-logs.ts deleted file mode 100644 index 2ec0323..0000000 --- a/src/resources/organization/audit-logs.ts +++ /dev/null @@ -1,814 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as AuditLogsAPI from './audit-logs'; - -export class AuditLogs extends APIResource { - /** - * List user actions and configuration changes within this organization. - */ - list(query?: AuditLogListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: AuditLogListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/organization/audit_logs', { query, ...options }); - } -} - -export interface AuditLogListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: 'list'; -} - -export namespace AuditLogListResponse { - /** - * A log of a user action or configuration change within this organization. - */ - export interface Data { - /** - * The ID of this log. - */ - id: string; - - /** - * The actor who performed the audit logged action. - */ - actor: Data.Actor; - - /** - * The Unix timestamp (in seconds) of the event. - */ - effective_at: number; - - /** - * The event type. - */ - type: - | 'api_key.created' - | 'api_key.updated' - | 'api_key.deleted' - | 'invite.sent' - | 'invite.accepted' - | 'invite.deleted' - | 'login.succeeded' - | 'login.failed' - | 'logout.succeeded' - | 'logout.failed' - | 'organization.updated' - | 'project.created' - | 'project.updated' - | 'project.archived' - | 'service_account.created' - | 'service_account.updated' - | 'service_account.deleted' - | 'user.added' - | 'user.updated' - | 'user.deleted'; - - /** - * The details for events with this `type`. - */ - 'api_key.created'?: Data.APIKeyCreated; - - /** - * The details for events with this `type`. - */ - 'api_key.deleted'?: Data.APIKeyDeleted; - - /** - * The details for events with this `type`. - */ - 'api_key.updated'?: Data.APIKeyUpdated; - - /** - * The details for events with this `type`. - */ - 'invite.accepted'?: Data.InviteAccepted; - - /** - * The details for events with this `type`. - */ - 'invite.deleted'?: Data.InviteDeleted; - - /** - * The details for events with this `type`. - */ - 'invite.sent'?: Data.InviteSent; - - /** - * The details for events with this `type`. - */ - 'login.failed'?: Data.LoginFailed; - - /** - * The details for events with this `type`. - */ - 'logout.failed'?: Data.LogoutFailed; - - /** - * The details for events with this `type`. - */ - 'organization.updated'?: Data.OrganizationUpdated; - - /** - * The project that the action was scoped to. Absent for actions not scoped to - * projects. - */ - project?: Data.Project; - - /** - * The details for events with this `type`. - */ - 'project.archived'?: Data.ProjectArchived; - - /** - * The details for events with this `type`. - */ - 'project.created'?: Data.ProjectCreated; - - /** - * The details for events with this `type`. - */ - 'project.updated'?: Data.ProjectUpdated; - - /** - * The details for events with this `type`. - */ - 'service_account.created'?: Data.ServiceAccountCreated; - - /** - * The details for events with this `type`. - */ - 'service_account.deleted'?: Data.ServiceAccountDeleted; - - /** - * The details for events with this `type`. - */ - 'service_account.updated'?: Data.ServiceAccountUpdated; - - /** - * The details for events with this `type`. - */ - 'user.added'?: Data.UserAdded; - - /** - * The details for events with this `type`. - */ - 'user.deleted'?: Data.UserDeleted; - - /** - * The details for events with this `type`. - */ - 'user.updated'?: Data.UserUpdated; - } - - export namespace Data { - /** - * The actor who performed the audit logged action. - */ - export interface Actor { - /** - * The API Key used to perform the audit logged action. - */ - api_key?: Actor.APIKey; - - /** - * The session in which the audit logged action was performed. - */ - session?: Actor.Session; - - /** - * The type of actor. Is either `session` or `api_key`. - */ - type?: 'session' | 'api_key'; - } - - export namespace Actor { - /** - * The API Key used to perform the audit logged action. - */ - export interface APIKey { - /** - * The tracking id of the API key. - */ - id?: string; - - /** - * The service account that performed the audit logged action. - */ - service_account?: APIKey.ServiceAccount; - - /** - * The type of API key. Can be either `user` or `service_account`. - */ - type?: 'user' | 'service_account'; - - /** - * The user who performed the audit logged action. - */ - user?: APIKey.User; - } - - export namespace APIKey { - /** - * The service account that performed the audit logged action. - */ - export interface ServiceAccount { - /** - * The service account id. - */ - id?: string; - } - - /** - * The user who performed the audit logged action. - */ - export interface User { - /** - * The user id. - */ - id?: string; - - /** - * The user email. - */ - email?: string; - } - } - - /** - * The session in which the audit logged action was performed. - */ - export interface Session { - /** - * The IP address from which the action was performed. - */ - ip_address?: string; - - /** - * The user who performed the audit logged action. - */ - user?: Session.User; - } - - export namespace Session { - /** - * The user who performed the audit logged action. - */ - export interface User { - /** - * The user id. - */ - id?: string; - - /** - * The user email. - */ - email?: string; - } - } - } - - /** - * The details for events with this `type`. - */ - export interface APIKeyCreated { - /** - * The tracking ID of the API key. - */ - id?: string; - - /** - * The payload used to create the API key. - */ - data?: APIKeyCreated.Data; - } - - export namespace APIKeyCreated { - /** - * The payload used to create the API key. - */ - export interface Data { - /** - * A list of scopes allowed for the API key, e.g. `["api.model.request"]` - */ - scopes?: Array; - } - } - - /** - * The details for events with this `type`. - */ - export interface APIKeyDeleted { - /** - * The tracking ID of the API key. - */ - id?: string; - } - - /** - * The details for events with this `type`. - */ - export interface APIKeyUpdated { - /** - * The tracking ID of the API key. - */ - id?: string; - - /** - * The payload used to update the API key. - */ - changes_requested?: APIKeyUpdated.ChangesRequested; - } - - export namespace APIKeyUpdated { - /** - * The payload used to update the API key. - */ - export interface ChangesRequested { - /** - * A list of scopes allowed for the API key, e.g. `["api.model.request"]` - */ - scopes?: Array; - } - } - - /** - * The details for events with this `type`. - */ - export interface InviteAccepted { - /** - * The ID of the invite. - */ - id?: string; - } - - /** - * The details for events with this `type`. - */ - export interface InviteDeleted { - /** - * The ID of the invite. - */ - id?: string; - } - - /** - * The details for events with this `type`. - */ - export interface InviteSent { - /** - * The ID of the invite. - */ - id?: string; - - /** - * The payload used to create the invite. - */ - data?: InviteSent.Data; - } - - export namespace InviteSent { - /** - * The payload used to create the invite. - */ - export interface Data { - /** - * The email invited to the organization. - */ - email?: string; - - /** - * The role the email was invited to be. Is either `owner` or `member`. - */ - role?: string; - } - } - - /** - * The details for events with this `type`. - */ - export interface LoginFailed { - /** - * The error code of the failure. - */ - error_code?: string; - - /** - * The error message of the failure. - */ - error_message?: string; - } - - /** - * The details for events with this `type`. - */ - export interface LogoutFailed { - /** - * The error code of the failure. - */ - error_code?: string; - - /** - * The error message of the failure. - */ - error_message?: string; - } - - /** - * The details for events with this `type`. - */ - export interface OrganizationUpdated { - /** - * The organization ID. - */ - id?: string; - - /** - * The payload used to update the organization settings. - */ - changes_requested?: OrganizationUpdated.ChangesRequested; - } - - export namespace OrganizationUpdated { - /** - * The payload used to update the organization settings. - */ - export interface ChangesRequested { - /** - * The organization description. - */ - description?: string; - - /** - * The organization name. - */ - name?: string; - - settings?: ChangesRequested.Settings; - - /** - * The organization title. - */ - title?: string; - } - - export namespace ChangesRequested { - export interface Settings { - /** - * Visibility of the threads page which shows messages created with the Assistants - * API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. - */ - threads_ui_visibility?: string; - - /** - * Visibility of the usage dashboard which shows activity and costs for your - * organization. One of `ANY_ROLE` or `OWNERS`. - */ - usage_dashboard_visibility?: string; - } - } - } - - /** - * The project that the action was scoped to. Absent for actions not scoped to - * projects. - */ - export interface Project { - /** - * The project ID. - */ - id?: string; - - /** - * The project title. - */ - name?: string; - } - - /** - * The details for events with this `type`. - */ - export interface ProjectArchived { - /** - * The project ID. - */ - id?: string; - } - - /** - * The details for events with this `type`. - */ - export interface ProjectCreated { - /** - * The project ID. - */ - id?: string; - - /** - * The payload used to create the project. - */ - data?: ProjectCreated.Data; - } - - export namespace ProjectCreated { - /** - * The payload used to create the project. - */ - export interface Data { - /** - * The project name. - */ - name?: string; - - /** - * The title of the project as seen on the dashboard. - */ - title?: string; - } - } - - /** - * The details for events with this `type`. - */ - export interface ProjectUpdated { - /** - * The project ID. - */ - id?: string; - - /** - * The payload used to update the project. - */ - changes_requested?: ProjectUpdated.ChangesRequested; - } - - export namespace ProjectUpdated { - /** - * The payload used to update the project. - */ - export interface ChangesRequested { - /** - * The title of the project as seen on the dashboard. - */ - title?: string; - } - } - - /** - * The details for events with this `type`. - */ - export interface ServiceAccountCreated { - /** - * The service account ID. - */ - id?: string; - - /** - * The payload used to create the service account. - */ - data?: ServiceAccountCreated.Data; - } - - export namespace ServiceAccountCreated { - /** - * The payload used to create the service account. - */ - export interface Data { - /** - * The role of the service account. Is either `owner` or `member`. - */ - role?: string; - } - } - - /** - * The details for events with this `type`. - */ - export interface ServiceAccountDeleted { - /** - * The service account ID. - */ - id?: string; - } - - /** - * The details for events with this `type`. - */ - export interface ServiceAccountUpdated { - /** - * The service account ID. - */ - id?: string; - - /** - * The payload used to updated the service account. - */ - changes_requested?: ServiceAccountUpdated.ChangesRequested; - } - - export namespace ServiceAccountUpdated { - /** - * The payload used to updated the service account. - */ - export interface ChangesRequested { - /** - * The role of the service account. Is either `owner` or `member`. - */ - role?: string; - } - } - - /** - * The details for events with this `type`. - */ - export interface UserAdded { - /** - * The user ID. - */ - id?: string; - - /** - * The payload used to add the user to the project. - */ - data?: UserAdded.Data; - } - - export namespace UserAdded { - /** - * The payload used to add the user to the project. - */ - export interface Data { - /** - * The role of the user. Is either `owner` or `member`. - */ - role?: string; - } - } - - /** - * The details for events with this `type`. - */ - export interface UserDeleted { - /** - * The user ID. - */ - id?: string; - } - - /** - * The details for events with this `type`. - */ - export interface UserUpdated { - /** - * The project ID. - */ - id?: string; - - /** - * The payload used to update the user. - */ - changes_requested?: UserUpdated.ChangesRequested; - } - - export namespace UserUpdated { - /** - * The payload used to update the user. - */ - export interface ChangesRequested { - /** - * The role of the user. Is either `owner` or `member`. - */ - role?: string; - } - } - } -} - -export interface AuditLogListParams { - /** - * Return only events performed by users with these emails. - */ - actor_emails?: Array; - - /** - * Return only events performed by these actors. Can be a user ID, a service - * account ID, or an api key tracking ID. - */ - actor_ids?: Array; - - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * Return only events whose `effective_at` (Unix seconds) is in this range. - */ - effective_at?: AuditLogListParams.EffectiveAt; - - /** - * Return only events with a `type` in one of these values. For example, - * `project.created`. For all options, see the documentation for the - * [audit log object](/docs/api-reference/audit-logs/object). - */ - event_types?: Array< - | 'api_key.created' - | 'api_key.updated' - | 'api_key.deleted' - | 'invite.sent' - | 'invite.accepted' - | 'invite.deleted' - | 'login.succeeded' - | 'login.failed' - | 'logout.succeeded' - | 'logout.failed' - | 'organization.updated' - | 'project.created' - | 'project.updated' - | 'project.archived' - | 'service_account.created' - | 'service_account.updated' - | 'service_account.deleted' - | 'user.added' - | 'user.updated' - | 'user.deleted' - >; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Return only events for these projects. - */ - project_ids?: Array; - - /** - * Return only events performed on these targets. For example, a project ID - * updated. - */ - resource_ids?: Array; -} - -export namespace AuditLogListParams { - /** - * Return only events whose `effective_at` (Unix seconds) is in this range. - */ - export interface EffectiveAt { - /** - * Return only events whose `effective_at` (Unix seconds) is greater than this - * value. - */ - gt?: number; - - /** - * Return only events whose `effective_at` (Unix seconds) is greater than or equal - * to this value. - */ - gte?: number; - - /** - * Return only events whose `effective_at` (Unix seconds) is less than this value. - */ - lt?: number; - - /** - * Return only events whose `effective_at` (Unix seconds) is less than or equal to - * this value. - */ - lte?: number; - } -} - -export namespace AuditLogs { - export import AuditLogListResponse = AuditLogsAPI.AuditLogListResponse; - export import AuditLogListParams = AuditLogsAPI.AuditLogListParams; -} diff --git a/src/resources/organization/index.ts b/src/resources/organization/index.ts deleted file mode 100644 index c8ee468..0000000 --- a/src/resources/organization/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { AuditLogListResponse, AuditLogListParams, AuditLogs } from './audit-logs'; -export { - Invite, - InviteListResponse, - InviteDeleteResponse, - InviteCreateParams, - InviteListParams, - Invites, -} from './invites'; -export { Organization } from './organization'; -export { - Project, - ProjectListResponse, - ProjectCreateParams, - ProjectListParams, - Projects, -} from './projects/index'; -export { User, UserListResponse, UserDeleteResponse, UserCreateParams, UserListParams, Users } from './users'; diff --git a/src/resources/organization/invites.ts b/src/resources/organization/invites.ts deleted file mode 100644 index 421c08e..0000000 --- a/src/resources/organization/invites.ts +++ /dev/null @@ -1,162 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as InvitesAPI from './invites'; - -export class Invites extends APIResource { - /** - * Create an invite for a user to the organization. The invite must be accepted by - * the user before they have access to the organization. - */ - create(body: InviteCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/organization/invites', { body, ...options }); - } - - /** - * Retrieves an invite. - */ - retrieve(inviteId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/organization/invites/${inviteId}`, options); - } - - /** - * Returns a list of invites in the organization. - */ - list(query?: InviteListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: InviteListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/organization/invites', { query, ...options }); - } - - /** - * Delete an invite. If the invite has already been accepted, it cannot be deleted. - */ - delete(inviteId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.delete(`/organization/invites/${inviteId}`, options); - } -} - -/** - * Represents an individual `invite` to the organization. - */ -export interface Invite { - /** - * The identifier, which can be referenced in API endpoints - */ - id: string; - - /** - * The email address of the individual to whom the invite was sent - */ - email: string; - - /** - * The Unix timestamp (in seconds) of when the invite expires. - */ - expires_at: number; - - /** - * The Unix timestamp (in seconds) of when the invite was sent. - */ - invited_at: number; - - /** - * The object type, which is always `organization.invite` - */ - object: 'organization.invite'; - - /** - * `owner` or `reader` - */ - role: 'owner' | 'reader'; - - /** - * `accepted`,`expired`, or `pending` - */ - status: 'accepted' | 'expired' | 'pending'; - - /** - * The Unix timestamp (in seconds) of when the invite was accepted. - */ - accepted_at?: number; -} - -export interface InviteListResponse { - data: Array; - - /** - * The object type, which is always `list` - */ - object: 'list'; - - /** - * The first `invite_id` in the retrieved `list` - */ - first_id?: string; - - /** - * The `has_more` property is used for pagination to indicate there are additional - * results. - */ - has_more?: boolean; - - /** - * The last `invite_id` in the retrieved `list` - */ - last_id?: string; -} - -export interface InviteDeleteResponse { - id: string; - - deleted: boolean; - - /** - * The object type, which is always `organization.invite.deleted` - */ - object: 'organization.invite.deleted'; -} - -export interface InviteCreateParams { - /** - * Send an email to this address - */ - email: string; - - /** - * `owner` or `reader` - */ - role: 'reader' | 'owner'; -} - -export interface InviteListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; -} - -export namespace Invites { - export import Invite = InvitesAPI.Invite; - export import InviteListResponse = InvitesAPI.InviteListResponse; - export import InviteDeleteResponse = InvitesAPI.InviteDeleteResponse; - export import InviteCreateParams = InvitesAPI.InviteCreateParams; - export import InviteListParams = InvitesAPI.InviteListParams; -} diff --git a/src/resources/organization/organization.ts b/src/resources/organization/organization.ts deleted file mode 100644 index 2b5dfc2..0000000 --- a/src/resources/organization/organization.ts +++ /dev/null @@ -1,37 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as AuditLogsAPI from './audit-logs'; -import * as InvitesAPI from './invites'; -import * as UsersAPI from './users'; -import * as ProjectsAPI from './projects/projects'; - -export class Organization extends APIResource { - auditLogs: AuditLogsAPI.AuditLogs = new AuditLogsAPI.AuditLogs(this._client); - invites: InvitesAPI.Invites = new InvitesAPI.Invites(this._client); - users: UsersAPI.Users = new UsersAPI.Users(this._client); - projects: ProjectsAPI.Projects = new ProjectsAPI.Projects(this._client); -} - -export namespace Organization { - export import AuditLogs = AuditLogsAPI.AuditLogs; - export import AuditLogListResponse = AuditLogsAPI.AuditLogListResponse; - export import AuditLogListParams = AuditLogsAPI.AuditLogListParams; - export import Invites = InvitesAPI.Invites; - export import Invite = InvitesAPI.Invite; - export import InviteListResponse = InvitesAPI.InviteListResponse; - export import InviteDeleteResponse = InvitesAPI.InviteDeleteResponse; - export import InviteCreateParams = InvitesAPI.InviteCreateParams; - export import InviteListParams = InvitesAPI.InviteListParams; - export import Users = UsersAPI.Users; - export import User = UsersAPI.User; - export import UserListResponse = UsersAPI.UserListResponse; - export import UserDeleteResponse = UsersAPI.UserDeleteResponse; - export import UserCreateParams = UsersAPI.UserCreateParams; - export import UserListParams = UsersAPI.UserListParams; - export import Projects = ProjectsAPI.Projects; - export import Project = ProjectsAPI.Project; - export import ProjectListResponse = ProjectsAPI.ProjectListResponse; - export import ProjectCreateParams = ProjectsAPI.ProjectCreateParams; - export import ProjectListParams = ProjectsAPI.ProjectListParams; -} diff --git a/src/resources/organization/projects/api-keys.ts b/src/resources/organization/projects/api-keys.ts deleted file mode 100644 index a15e3ee..0000000 --- a/src/resources/organization/projects/api-keys.ts +++ /dev/null @@ -1,5 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; - -export class APIKeys extends APIResource {} diff --git a/src/resources/organization/projects/index.ts b/src/resources/organization/projects/index.ts deleted file mode 100644 index 368ad2c..0000000 --- a/src/resources/organization/projects/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { APIKeys } from './api-keys'; -export { Project, ProjectListResponse, ProjectCreateParams, ProjectListParams, Projects } from './projects'; -export { - ServiceAccountCreateResponse, - ServiceAccountListResponse, - ServiceAccountCreateParams, - ServiceAccountListParams, - ServiceAccounts, -} from './service-accounts'; -export { UserListResponse, UserDeleteResponse, UserCreateParams, UserListParams, Users } from './users'; diff --git a/src/resources/organization/projects/projects.ts b/src/resources/organization/projects/projects.ts deleted file mode 100644 index c4d1476..0000000 --- a/src/resources/organization/projects/projects.ts +++ /dev/null @@ -1,150 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as ProjectsAPI from './projects'; -import * as APIKeysAPI from './api-keys'; -import * as ServiceAccountsAPI from './service-accounts'; -import * as UsersAPI from './users'; - -export class Projects extends APIResource { - users: UsersAPI.Users = new UsersAPI.Users(this._client); - serviceAccounts: ServiceAccountsAPI.ServiceAccounts = new ServiceAccountsAPI.ServiceAccounts(this._client); - apiKeys: APIKeysAPI.APIKeys = new APIKeysAPI.APIKeys(this._client); - - /** - * Modifies a project in the organization. - */ - create( - projectId: string, - body: ProjectCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/organization/projects/${projectId}`, { body, ...options }); - } - - /** - * Retrieves a project. - */ - retrieve(projectId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/organization/projects/${projectId}`, options); - } - - /** - * Returns a list of projects. - */ - list(query?: ProjectListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: ProjectListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/organization/projects', { query, ...options }); - } - - /** - * Archives a project in the organization. Archived projects cannot be used or - * updated. - */ - archive(projectId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post(`/organization/projects/${projectId}/archive`, options); - } -} - -/** - * Represents an individual project. - */ -export interface Project { - /** - * The identifier, which can be referenced in API endpoints - */ - id: string; - - /** - * The Unix timestamp (in seconds) of when the project was created. - */ - created_at: number; - - /** - * The name of the project. This appears in reporting. - */ - name: string; - - /** - * The object type, which is always `organization.project` - */ - object: 'organization.project'; - - /** - * `active` or `archived` - */ - status: 'active' | 'archived'; - - /** - * The Unix timestamp (in seconds) of when the project was archived or `null`. - */ - archived_at?: number | null; -} - -export interface ProjectListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: 'list'; -} - -export interface ProjectCreateParams { - /** - * The updated name of the project, this name appears in reports. - */ - name: string; -} - -export interface ProjectListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * If `true` returns all projects including those that have been `archived`. - * Archived projects are not included by default. - */ - include_archived?: boolean; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; -} - -export namespace Projects { - export import Project = ProjectsAPI.Project; - export import ProjectListResponse = ProjectsAPI.ProjectListResponse; - export import ProjectCreateParams = ProjectsAPI.ProjectCreateParams; - export import ProjectListParams = ProjectsAPI.ProjectListParams; - export import Users = UsersAPI.Users; - export import UserListResponse = UsersAPI.UserListResponse; - export import UserDeleteResponse = UsersAPI.UserDeleteResponse; - export import UserCreateParams = UsersAPI.UserCreateParams; - export import UserListParams = UsersAPI.UserListParams; - export import ServiceAccounts = ServiceAccountsAPI.ServiceAccounts; - export import ServiceAccountCreateResponse = ServiceAccountsAPI.ServiceAccountCreateResponse; - export import ServiceAccountListResponse = ServiceAccountsAPI.ServiceAccountListResponse; - export import ServiceAccountCreateParams = ServiceAccountsAPI.ServiceAccountCreateParams; - export import ServiceAccountListParams = ServiceAccountsAPI.ServiceAccountListParams; - export import APIKeys = APIKeysAPI.APIKeys; -} diff --git a/src/resources/organization/projects/service-accounts.ts b/src/resources/organization/projects/service-accounts.ts deleted file mode 100644 index 3744a6f..0000000 --- a/src/resources/organization/projects/service-accounts.ts +++ /dev/null @@ -1,131 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as ServiceAccountsAPI from './service-accounts'; -import * as Shared from '../../shared'; - -export class ServiceAccounts extends APIResource { - /** - * Creates a new service account in the project. This also returns an unredacted - * API key for the service account. - */ - create( - projectId: string, - body: ServiceAccountCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/organization/projects/${projectId}/service_accounts`, { body, ...options }); - } - - /** - * Retrieves a service account in the project. - */ - retrieve( - projectId: string, - serviceAccountId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.get( - `/organization/projects/${projectId}/service_accounts/${serviceAccountId}`, - options, - ); - } - - /** - * Returns a list of service accounts in the project. - */ - list( - projectId: string, - query?: ServiceAccountListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(projectId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - projectId: string, - query: ServiceAccountListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(projectId, {}, query); - } - return this._client.get(`/organization/projects/${projectId}/service_accounts`, { query, ...options }); - } -} - -export interface ServiceAccountCreateResponse { - id: string; - - api_key: ServiceAccountCreateResponse.APIKey; - - created_at: number; - - name: string; - - object: 'organization.project.service_account'; - - /** - * Service accounts can only have one role of type `member` - */ - role: 'member'; -} - -export namespace ServiceAccountCreateResponse { - export interface APIKey { - id: string; - - created_at: number; - - name: string; - - /** - * The object type, which is always `organization.project.service_account.api_key` - */ - object: 'organization.project.service_account.api_key'; - - value: string; - } -} - -export interface ServiceAccountListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: 'list'; -} - -export interface ServiceAccountCreateParams { - /** - * The name of the service account being created. - */ - name: string; -} - -export interface ServiceAccountListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; -} - -export namespace ServiceAccounts { - export import ServiceAccountCreateResponse = ServiceAccountsAPI.ServiceAccountCreateResponse; - export import ServiceAccountListResponse = ServiceAccountsAPI.ServiceAccountListResponse; - export import ServiceAccountCreateParams = ServiceAccountsAPI.ServiceAccountCreateParams; - export import ServiceAccountListParams = ServiceAccountsAPI.ServiceAccountListParams; -} diff --git a/src/resources/organization/projects/users.ts b/src/resources/organization/projects/users.ts deleted file mode 100644 index d456e08..0000000 --- a/src/resources/organization/projects/users.ts +++ /dev/null @@ -1,113 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as UsersAPI from './users'; -import * as Shared from '../../shared'; - -export class Users extends APIResource { - /** - * Modifies a user's role in the project. - */ - create( - projectId: string, - userId: string, - body: UserCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/organization/projects/${projectId}/users/${userId}`, { body, ...options }); - } - - /** - * Retrieves a user in the project. - */ - retrieve( - projectId: string, - userId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.get(`/organization/projects/${projectId}/users/${userId}`, options); - } - - /** - * Returns a list of users in the project. - */ - list( - projectId: string, - query?: UserListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(projectId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - projectId: string, - query: UserListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(projectId, {}, query); - } - return this._client.get(`/organization/projects/${projectId}/users`, { query, ...options }); - } - - /** - * Deletes a user from the project. - */ - delete( - projectId: string, - userId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.delete(`/organization/projects/${projectId}/users/${userId}`, options); - } -} - -export interface UserListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface UserDeleteResponse { - id: string; - - deleted: boolean; - - object: 'organization.project.user.deleted'; -} - -export interface UserCreateParams { - /** - * `owner` or `member` - */ - role: 'owner' | 'member'; -} - -export interface UserListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; -} - -export namespace Users { - export import UserListResponse = UsersAPI.UserListResponse; - export import UserDeleteResponse = UsersAPI.UserDeleteResponse; - export import UserCreateParams = UsersAPI.UserCreateParams; - export import UserListParams = UsersAPI.UserListParams; -} diff --git a/src/resources/organization/users.ts b/src/resources/organization/users.ts deleted file mode 100644 index 5fd8b70..0000000 --- a/src/resources/organization/users.ts +++ /dev/null @@ -1,130 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as UsersAPI from './users'; - -export class Users extends APIResource { - /** - * Modifies a user's role in the organization. - */ - create(userId: string, body: UserCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post(`/organization/users/${userId}`, { body, ...options }); - } - - /** - * Retrieves a user by their identifier. - */ - retrieve(userId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/organization/users/${userId}`, options); - } - - /** - * Lists all of the users in the organization. - */ - list(query?: UserListParams, options?: Core.RequestOptions): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: UserListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/organization/users', { query, ...options }); - } - - /** - * Deletes a user from the organization. - */ - delete(userId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.delete(`/organization/users/${userId}`, options); - } -} - -/** - * Represents an individual `user` within an organization. - */ -export interface User { - /** - * The identifier, which can be referenced in API endpoints - */ - id: string; - - /** - * The Unix timestamp (in seconds) of when the user was added. - */ - added_at: number; - - /** - * The email address of the user - */ - email: string; - - /** - * The name of the user - */ - name: string; - - /** - * The object type, which is always `organization.user` - */ - object: 'organization.user'; - - /** - * `owner` or `reader` - */ - role: 'owner' | 'reader'; -} - -export interface UserListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: 'list'; -} - -export interface UserDeleteResponse { - id: string; - - deleted: boolean; - - object: 'organization.user.deleted'; -} - -export interface UserCreateParams { - /** - * `owner` or `reader` - */ - role: 'owner' | 'reader'; -} - -export interface UserListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; -} - -export namespace Users { - export import User = UsersAPI.User; - export import UserListResponse = UsersAPI.UserListResponse; - export import UserDeleteResponse = UsersAPI.UserDeleteResponse; - export import UserCreateParams = UsersAPI.UserCreateParams; - export import UserListParams = UsersAPI.UserListParams; -} diff --git a/src/resources/projects/api-keys.ts b/src/resources/projects/api-keys.ts deleted file mode 100644 index 0825513..0000000 --- a/src/resources/projects/api-keys.ts +++ /dev/null @@ -1,93 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as APIKeysAPI from './api-keys'; -import * as Shared from '../shared'; - -export class APIKeys extends APIResource { - /** - * Retrieves an API key in the project. - */ - retrieve( - projectId: string, - keyId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.get(`/organization/projects/${projectId}/api_keys/${keyId}`, options); - } - - /** - * Returns a list of API keys in the project. - */ - list( - projectId: string, - query?: APIKeyListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(projectId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - projectId: string, - query: APIKeyListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(projectId, {}, query); - } - return this._client.get(`/organization/projects/${projectId}/api_keys`, { query, ...options }); - } - - /** - * Deletes an API key from the project. - */ - delete( - projectId: string, - keyId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.delete(`/organization/projects/${projectId}/api_keys/${keyId}`, options); - } -} - -export interface APIKeyListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: 'list'; -} - -export interface APIKeyDeleteResponse { - id: string; - - deleted: boolean; - - object: 'organization.project.api_key.deleted'; -} - -export interface APIKeyListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; -} - -export namespace APIKeys { - export import APIKeyListResponse = APIKeysAPI.APIKeyListResponse; - export import APIKeyDeleteResponse = APIKeysAPI.APIKeyDeleteResponse; - export import APIKeyListParams = APIKeysAPI.APIKeyListParams; -} diff --git a/src/resources/projects/index.ts b/src/resources/projects/index.ts deleted file mode 100644 index 1068240..0000000 --- a/src/resources/projects/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { APIKeyListResponse, APIKeyDeleteResponse, APIKeyListParams, APIKeys } from './api-keys'; -export { Projects } from './projects'; -export { ServiceAccountDeleteResponse, ServiceAccounts } from './service-accounts'; diff --git a/src/resources/projects/projects.ts b/src/resources/projects/projects.ts deleted file mode 100644 index e46134e..0000000 --- a/src/resources/projects/projects.ts +++ /dev/null @@ -1,19 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as APIKeysAPI from './api-keys'; -import * as ServiceAccountsAPI from './service-accounts'; - -export class Projects extends APIResource { - serviceAccounts: ServiceAccountsAPI.ServiceAccounts = new ServiceAccountsAPI.ServiceAccounts(this._client); - apiKeys: APIKeysAPI.APIKeys = new APIKeysAPI.APIKeys(this._client); -} - -export namespace Projects { - export import ServiceAccounts = ServiceAccountsAPI.ServiceAccounts; - export import ServiceAccountDeleteResponse = ServiceAccountsAPI.ServiceAccountDeleteResponse; - export import APIKeys = APIKeysAPI.APIKeys; - export import APIKeyListResponse = APIKeysAPI.APIKeyListResponse; - export import APIKeyDeleteResponse = APIKeysAPI.APIKeyDeleteResponse; - export import APIKeyListParams = APIKeysAPI.APIKeyListParams; -} diff --git a/src/resources/projects/service-accounts.ts b/src/resources/projects/service-accounts.ts deleted file mode 100644 index 5327c56..0000000 --- a/src/resources/projects/service-accounts.ts +++ /dev/null @@ -1,33 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as ServiceAccountsAPI from './service-accounts'; - -export class ServiceAccounts extends APIResource { - /** - * Deletes a service account from the project. - */ - delete( - projectId: string, - serviceAccountId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.delete( - `/organization/projects/${projectId}/service_accounts/${serviceAccountId}`, - options, - ); - } -} - -export interface ServiceAccountDeleteResponse { - id: string; - - deleted: boolean; - - object: 'organization.project.service_account.deleted'; -} - -export namespace ServiceAccounts { - export import ServiceAccountDeleteResponse = ServiceAccountsAPI.ServiceAccountDeleteResponse; -} diff --git a/src/resources/threads/index.ts b/src/resources/threads/index.ts deleted file mode 100644 index 893fe33..0000000 --- a/src/resources/threads/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { - MessageListResponse, - MessageDeleteResponse, - MessageCreateParams, - MessageListParams, - Messages, -} from './messages'; -export { - RunListResponse, - RunCreateParams, - RunListParams, - RunSubmitToolOutputsParams, - Runs, -} from './runs/index'; -export { ThreadDeleteResponse, ThreadCreateParams, ThreadUpdateParams, Threads } from './threads'; diff --git a/src/resources/threads/messages.ts b/src/resources/threads/messages.ts deleted file mode 100644 index e3c724d..0000000 --- a/src/resources/threads/messages.ts +++ /dev/null @@ -1,135 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as MessagesAPI from './messages'; -import * as ThreadsAPI from '../assistants/threads'; - -export class Messages extends APIResource { - /** - * Modifies a message. - */ - create( - threadId: string, - messageId: string, - body: MessageCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/threads/${threadId}/messages/${messageId}`, { body, ...options }); - } - - /** - * Retrieve a message. - */ - retrieve( - threadId: string, - messageId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.get(`/threads/${threadId}/messages/${messageId}`, options); - } - - /** - * Returns a list of messages for a given thread. - */ - list( - threadId: string, - query?: MessageListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(threadId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - threadId: string, - query: MessageListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(threadId, {}, query); - } - return this._client.get(`/threads/${threadId}/messages`, { query, ...options }); - } - - /** - * Deletes a message. - */ - delete( - threadId: string, - messageId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.delete(`/threads/${threadId}/messages/${messageId}`, options); - } -} - -export interface MessageListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface MessageDeleteResponse { - id: string; - - deleted: boolean; - - object: 'thread.message.deleted'; -} - -export interface MessageCreateParams { - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; -} - -export interface MessageListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Sort order by the `created_at` timestamp of the objects. `asc` for ascending - * order and `desc` for descending order. - */ - order?: 'asc' | 'desc'; - - /** - * Filter messages by the run ID that generated them. - */ - run_id?: string; -} - -export namespace Messages { - export import MessageListResponse = MessagesAPI.MessageListResponse; - export import MessageDeleteResponse = MessagesAPI.MessageDeleteResponse; - export import MessageCreateParams = MessagesAPI.MessageCreateParams; - export import MessageListParams = MessagesAPI.MessageListParams; -} diff --git a/src/resources/threads/runs/index.ts b/src/resources/threads/runs/index.ts deleted file mode 100644 index 14c4f7f..0000000 --- a/src/resources/threads/runs/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { RunListResponse, RunCreateParams, RunListParams, RunSubmitToolOutputsParams, Runs } from './runs'; -export { RunStepObject, StepListResponse, StepRetrieveParams, StepListParams, Steps } from './steps'; diff --git a/src/resources/threads/runs/runs.ts b/src/resources/threads/runs/runs.ts deleted file mode 100644 index d7f6433..0000000 --- a/src/resources/threads/runs/runs.ts +++ /dev/null @@ -1,174 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as RunsAPI from './runs'; -import * as ThreadsAPI from '../../assistants/threads'; -import * as StepsAPI from './steps'; - -export class Runs extends APIResource { - steps: StepsAPI.Steps = new StepsAPI.Steps(this._client); - - /** - * Modifies a run. - */ - create( - threadId: string, - runId: string, - body: RunCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/threads/${threadId}/runs/${runId}`, { body, ...options }); - } - - /** - * Retrieves a run. - */ - retrieve( - threadId: string, - runId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.get(`/threads/${threadId}/runs/${runId}`, options); - } - - /** - * Returns a list of runs belonging to a thread. - */ - list( - threadId: string, - query?: RunListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(threadId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - threadId: string, - query: RunListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(threadId, {}, query); - } - return this._client.get(`/threads/${threadId}/runs`, { query, ...options }); - } - - /** - * Cancels a run that is `in_progress`. - */ - cancel( - threadId: string, - runId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, options); - } - - /** - * When a run has the `status: "requires_action"` and `required_action.type` is - * `submit_tool_outputs`, this endpoint can be used to submit the outputs from the - * tool calls once they're all completed. All outputs must be submitted in a single - * request. - */ - submitToolOutputs( - threadId: string, - runId: string, - body: RunSubmitToolOutputsParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { body, ...options }); - } -} - -export interface RunListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface RunCreateParams { - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; -} - -export interface RunListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Sort order by the `created_at` timestamp of the objects. `asc` for ascending - * order and `desc` for descending order. - */ - order?: 'asc' | 'desc'; -} - -export interface RunSubmitToolOutputsParams { - /** - * A list of tools for which the outputs are being submitted. - */ - tool_outputs: Array; - - /** - * If `true`, returns a stream of events that happen during the Run as server-sent - * events, terminating when the Run enters a terminal state with a `data: [DONE]` - * message. - */ - stream?: boolean | null; -} - -export namespace RunSubmitToolOutputsParams { - export interface ToolOutput { - /** - * The output of the tool call to be submitted to continue the run. - */ - output?: string; - - /** - * The ID of the tool call in the `required_action` object within the run object - * the output is being submitted for. - */ - tool_call_id?: string; - } -} - -export namespace Runs { - export import RunListResponse = RunsAPI.RunListResponse; - export import RunCreateParams = RunsAPI.RunCreateParams; - export import RunListParams = RunsAPI.RunListParams; - export import RunSubmitToolOutputsParams = RunsAPI.RunSubmitToolOutputsParams; - export import Steps = StepsAPI.Steps; - export import RunStepObject = StepsAPI.RunStepObject; - export import StepListResponse = StepsAPI.StepListResponse; - export import StepRetrieveParams = StepsAPI.StepRetrieveParams; - export import StepListParams = StepsAPI.StepListParams; -} diff --git a/src/resources/threads/runs/steps.ts b/src/resources/threads/runs/steps.ts deleted file mode 100644 index c6f3fa2..0000000 --- a/src/resources/threads/runs/steps.ts +++ /dev/null @@ -1,523 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as StepsAPI from './steps'; - -export class Steps extends APIResource { - /** - * Retrieves a run step. - */ - retrieve( - threadId: string, - runId: string, - stepId: string, - query?: StepRetrieveParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - retrieve( - threadId: string, - runId: string, - stepId: string, - options?: Core.RequestOptions, - ): Core.APIPromise; - retrieve( - threadId: string, - runId: string, - stepId: string, - query: StepRetrieveParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.retrieve(threadId, runId, stepId, {}, query); - } - return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { query, ...options }); - } - - /** - * Returns a list of run steps belonging to a run. - */ - list( - threadId: string, - runId: string, - query?: StepListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(threadId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - threadId: string, - runId: string, - query: StepListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(threadId, runId, {}, query); - } - return this._client.get(`/threads/${threadId}/runs/${runId}/steps`, { query, ...options }); - } -} - -/** - * Represents a step in execution of a run. - */ -export interface RunStepObject { - /** - * The identifier of the run step, which can be referenced in API endpoints. - */ - id: string; - - /** - * The ID of the [assistant](/docs/api-reference/assistants) associated with the - * run step. - */ - assistant_id: string; - - /** - * The Unix timestamp (in seconds) for when the run step was cancelled. - */ - cancelled_at: number | null; - - /** - * The Unix timestamp (in seconds) for when the run step completed. - */ - completed_at: number | null; - - /** - * The Unix timestamp (in seconds) for when the run step was created. - */ - created_at: number; - - /** - * The Unix timestamp (in seconds) for when the run step expired. A step is - * considered expired if the parent run is expired. - */ - expired_at: number | null; - - /** - * The Unix timestamp (in seconds) for when the run step failed. - */ - failed_at: number | null; - - /** - * The last error associated with this run step. Will be `null` if there are no - * errors. - */ - last_error: RunStepObject.LastError | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata: unknown | null; - - /** - * The object type, which is always `thread.run.step`. - */ - object: 'thread.run.step'; - - /** - * The ID of the [run](/docs/api-reference/runs) that this run step is a part of. - */ - run_id: string; - - /** - * The status of the run step, which can be either `in_progress`, `cancelled`, - * `failed`, `completed`, or `expired`. - */ - status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired'; - - /** - * The details of the run step. - */ - step_details: - | RunStepObject.RunStepDetailsMessageCreationObject - | RunStepObject.RunStepDetailsToolCallsObject; - - /** - * The ID of the [thread](/docs/api-reference/threads) that was run. - */ - thread_id: string; - - /** - * The type of run step, which can be either `message_creation` or `tool_calls`. - */ - type: 'message_creation' | 'tool_calls'; - - /** - * Usage statistics related to the run step. This value will be `null` while the - * run step's status is `in_progress`. - */ - usage: RunStepObject.Usage | null; -} - -export namespace RunStepObject { - /** - * The last error associated with this run step. Will be `null` if there are no - * errors. - */ - export interface LastError { - /** - * One of `server_error` or `rate_limit_exceeded`. - */ - code: 'server_error' | 'rate_limit_exceeded'; - - /** - * A human-readable description of the error. - */ - message: string; - } - - /** - * Details of the message creation by the run step. - */ - export interface RunStepDetailsMessageCreationObject { - message_creation: RunStepDetailsMessageCreationObject.MessageCreation; - - /** - * Always `message_creation`. - */ - type: 'message_creation'; - } - - export namespace RunStepDetailsMessageCreationObject { - export interface MessageCreation { - /** - * The ID of the message that was created by this run step. - */ - message_id: string; - } - } - - /** - * Details of the tool call. - */ - export interface RunStepDetailsToolCallsObject { - /** - * An array of tool calls the run step was involved in. These can be associated - * with one of three types of tools: `code_interpreter`, `file_search`, or - * `function`. - */ - tool_calls: Array< - | RunStepDetailsToolCallsObject.RunStepDetailsToolCallsCodeObject - | RunStepDetailsToolCallsObject.RunStepDetailsToolCallsFileSearchObject - | RunStepDetailsToolCallsObject.RunStepDetailsToolCallsFunctionObject - >; - - /** - * Always `tool_calls`. - */ - type: 'tool_calls'; - } - - export namespace RunStepDetailsToolCallsObject { - /** - * Details of the Code Interpreter tool call the run step was involved in. - */ - export interface RunStepDetailsToolCallsCodeObject { - /** - * The ID of the tool call. - */ - id: string; - - /** - * The Code Interpreter tool call definition. - */ - code_interpreter: RunStepDetailsToolCallsCodeObject.CodeInterpreter; - - /** - * The type of tool call. This is always going to be `code_interpreter` for this - * type of tool call. - */ - type: 'code_interpreter'; - } - - export namespace RunStepDetailsToolCallsCodeObject { - /** - * The Code Interpreter tool call definition. - */ - export interface CodeInterpreter { - /** - * The input to the Code Interpreter tool call. - */ - input: string; - - /** - * The outputs from the Code Interpreter tool call. Code Interpreter can output one - * or more items, including text (`logs`) or images (`image`). Each of these are - * represented by a different object type. - */ - outputs: Array< - | CodeInterpreter.RunStepDetailsToolCallsCodeOutputLogsObject - | CodeInterpreter.RunStepDetailsToolCallsCodeOutputImageObject - >; - } - - export namespace CodeInterpreter { - /** - * Text output from the Code Interpreter tool call as part of a run step. - */ - export interface RunStepDetailsToolCallsCodeOutputLogsObject { - /** - * The text output from the Code Interpreter tool call. - */ - logs: string; - - /** - * Always `logs`. - */ - type: 'logs'; - } - - export interface RunStepDetailsToolCallsCodeOutputImageObject { - image: RunStepDetailsToolCallsCodeOutputImageObject.Image; - - /** - * Always `image`. - */ - type: 'image'; - } - - export namespace RunStepDetailsToolCallsCodeOutputImageObject { - export interface Image { - /** - * The [file](/docs/api-reference/files) ID of the image. - */ - file_id: string; - } - } - } - } - - export interface RunStepDetailsToolCallsFileSearchObject { - /** - * The ID of the tool call object. - */ - id: string; - - /** - * For now, this is always going to be an empty object. - */ - file_search: RunStepDetailsToolCallsFileSearchObject.FileSearch; - - /** - * The type of tool call. This is always going to be `file_search` for this type of - * tool call. - */ - type: 'file_search'; - } - - export namespace RunStepDetailsToolCallsFileSearchObject { - /** - * For now, this is always going to be an empty object. - */ - export interface FileSearch { - /** - * The ranking options for the file search. - */ - ranking_options?: FileSearch.RankingOptions; - - /** - * The results of the file search. - */ - results?: Array; - } - - export namespace FileSearch { - /** - * The ranking options for the file search. - */ - export interface RankingOptions { - /** - * The ranker used for the file search. - */ - ranker: 'default_2024_08_21'; - - /** - * The score threshold for the file search. All values must be a floating point - * number between 0 and 1. - */ - score_threshold: number; - } - - /** - * A result instance of the file search. - */ - export interface Result { - /** - * The ID of the file that result was found in. - */ - file_id: string; - - /** - * The name of the file that result was found in. - */ - file_name: string; - - /** - * The score of the result. All values must be a floating point number between 0 - * and 1. - */ - score: number; - - /** - * The content of the result that was found. The content is only included if - * requested via the include query parameter. - */ - content?: Array; - } - - export namespace Result { - export interface Content { - /** - * The text content of the file. - */ - text?: string; - - /** - * The type of the content. - */ - type?: 'text'; - } - } - } - } - - export interface RunStepDetailsToolCallsFunctionObject { - /** - * The ID of the tool call object. - */ - id: string; - - /** - * The definition of the function that was called. - */ - function: RunStepDetailsToolCallsFunctionObject.Function; - - /** - * The type of tool call. This is always going to be `function` for this type of - * tool call. - */ - type: 'function'; - } - - export namespace RunStepDetailsToolCallsFunctionObject { - /** - * The definition of the function that was called. - */ - export interface Function { - /** - * The arguments passed to the function. - */ - arguments: string; - - /** - * The name of the function. - */ - name: string; - - /** - * The output of the function. This will be `null` if the outputs have not been - * [submitted](/docs/api-reference/runs/submitToolOutputs) yet. - */ - output: string | null; - } - } - } - - /** - * Usage statistics related to the run step. This value will be `null` while the - * run step's status is `in_progress`. - */ - export interface Usage { - /** - * Number of completion tokens used over the course of the run step. - */ - completion_tokens: number; - - /** - * Number of prompt tokens used over the course of the run step. - */ - prompt_tokens: number; - - /** - * Total number of tokens used (prompt + completion). - */ - total_tokens: number; - } -} - -export interface StepListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface StepRetrieveParams { - /** - * A list of additional fields to include in the response. Currently the only - * supported value is `step_details.tool_calls[*].file_search.results[*].content` - * to fetch the file search result content. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - include?: Array<'step_details.tool_calls[*].file_search.results[*].content'>; -} - -export interface StepListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * A list of additional fields to include in the response. Currently the only - * supported value is `step_details.tool_calls[*].file_search.results[*].content` - * to fetch the file search result content. - * - * See the - * [file search tool documentation](/docs/assistants/tools/file-search/customizing-file-search-settings) - * for more information. - */ - include?: Array<'step_details.tool_calls[*].file_search.results[*].content'>; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Sort order by the `created_at` timestamp of the objects. `asc` for ascending - * order and `desc` for descending order. - */ - order?: 'asc' | 'desc'; -} - -export namespace Steps { - export import RunStepObject = StepsAPI.RunStepObject; - export import StepListResponse = StepsAPI.StepListResponse; - export import StepRetrieveParams = StepsAPI.StepRetrieveParams; - export import StepListParams = StepsAPI.StepListParams; -} diff --git a/src/resources/threads/threads.ts b/src/resources/threads/threads.ts deleted file mode 100644 index ea4457f..0000000 --- a/src/resources/threads/threads.ts +++ /dev/null @@ -1,472 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as ThreadsThreadsAPI from './threads'; -import * as ThreadsAPI from '../assistants/threads'; -import * as MessagesAPI from './messages'; -import * as RunsAPI from './runs/runs'; - -export class Threads extends APIResource { - messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client); - runs: RunsAPI.Runs = new RunsAPI.Runs(this._client); - - /** - * Create a thread. - */ - create(body?: ThreadCreateParams, options?: Core.RequestOptions): Core.APIPromise; - create(options?: Core.RequestOptions): Core.APIPromise; - create( - body: ThreadCreateParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(body)) { - return this.create({}, body); - } - return this._client.post('/threads', { body, ...options }); - } - - /** - * Retrieves a thread. - */ - retrieve(threadId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/threads/${threadId}`, options); - } - - /** - * Modifies a thread. - */ - update( - threadId: string, - body: ThreadUpdateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/threads/${threadId}`, { body, ...options }); - } - - /** - * Delete a thread. - */ - delete(threadId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.delete(`/threads/${threadId}`, options); - } -} - -export interface ThreadDeleteResponse { - id: string; - - deleted: boolean; - - object: 'thread.deleted'; -} - -export interface ThreadCreateParams { - /** - * A list of [messages](/docs/api-reference/messages) to start the thread with. - */ - messages?: Array; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; - - /** - * A set of resources that are made available to the assistant's tools in this - * thread. The resources are specific to the type of tool. For example, the - * `code_interpreter` tool requires a list of file IDs, while the `file_search` - * tool requires a list of vector store IDs. - */ - tool_resources?: ThreadCreateParams.ToolResources | null; -} - -export namespace ThreadCreateParams { - export interface Message { - /** - * The text contents of the message. - */ - content: - | string - | Array< - | Message.MessageContentImageFileObject - | Message.MessageContentImageURLObject - | Message.MessageRequestContentTextObject - >; - - /** - * The role of the entity that is creating the message. Allowed values include: - * - * - `user`: Indicates the message is sent by an actual user and should be used in - * most cases to represent user-generated messages. - * - `assistant`: Indicates the message is generated by the assistant. Use this - * value to insert messages from the assistant into the conversation. - */ - role: 'user' | 'assistant'; - - /** - * A list of files attached to the message, and the tools they should be added to. - */ - attachments?: Array | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; - } - - export namespace Message { - /** - * References an image [File](/docs/api-reference/files) in the content of a - * message. - */ - export interface MessageContentImageFileObject { - image_file: MessageContentImageFileObject.ImageFile; - - /** - * Always `image_file`. - */ - type: 'image_file'; - } - - export namespace MessageContentImageFileObject { - export interface ImageFile { - /** - * The [File](/docs/api-reference/files) ID of the image in the message content. - * Set `purpose="vision"` when uploading the File if you need to later display the - * file content. - */ - file_id: string; - - /** - * Specifies the detail level of the image if specified by the user. `low` uses - * fewer tokens, you can opt in to high resolution using `high`. - */ - detail?: 'auto' | 'low' | 'high'; - } - } - - /** - * References an image URL in the content of a message. - */ - export interface MessageContentImageURLObject { - image_url: MessageContentImageURLObject.ImageURL; - - /** - * The type of the content part. - */ - type: 'image_url'; - } - - export namespace MessageContentImageURLObject { - export interface ImageURL { - /** - * The external URL of the image, must be a supported image types: jpeg, jpg, png, - * gif, webp. - */ - url: string; - - /** - * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in - * to high resolution using `high`. Default value is `auto` - */ - detail?: 'auto' | 'low' | 'high'; - } - } - - /** - * The text content that is part of a message. - */ - export interface MessageRequestContentTextObject { - /** - * Text content to be sent to the model - */ - text: string; - - /** - * Always `text`. - */ - type: 'text'; - } - - export interface Attachment { - /** - * The ID of the file to attach to the message. - */ - file_id?: string; - - /** - * The tools to add this file to. - */ - tools?: Array; - } - - export namespace Attachment { - export interface AssistantToolsCode { - /** - * The type of tool being defined: `code_interpreter` - */ - type: 'code_interpreter'; - } - - export interface AssistantToolsFileSearchTypeOnly { - /** - * The type of tool being defined: `file_search` - */ - type: 'file_search'; - } - } - } - - /** - * A set of resources that are made available to the assistant's tools in this - * thread. The resources are specific to the type of tool. For example, the - * `code_interpreter` tool requires a list of file IDs, while the `file_search` - * tool requires a list of vector store IDs. - */ - export interface ToolResources { - code_interpreter?: ToolResources.CodeInterpreter; - - file_search?: ToolResources.UnionMember0 | ToolResources.UnionMember1; - } - - export namespace ToolResources { - export interface CodeInterpreter { - /** - * A list of [file](/docs/api-reference/files) IDs made available to the - * `code_interpreter` tool. There can be a maximum of 20 files associated with the - * tool. - */ - file_ids?: Array; - } - - export interface UnionMember0 { - /** - * The [vector store](/docs/api-reference/vector-stores/object) attached to this - * thread. There can be a maximum of 1 vector store attached to the thread. - */ - vector_store_ids: Array; - - /** - * A helper to create a [vector store](/docs/api-reference/vector-stores/object) - * with file_ids and attach it to this thread. There can be a maximum of 1 vector - * store attached to the thread. - */ - vector_stores?: Array; - } - - export namespace UnionMember0 { - export interface VectorStore { - /** - * The chunking strategy used to chunk the file(s). If not set, will use the `auto` - * strategy. - */ - chunking_strategy?: VectorStore.AutoChunkingStrategy | VectorStore.StaticChunkingStrategy; - - /** - * A list of [file](/docs/api-reference/files) IDs to add to the vector store. - * There can be a maximum of 10000 files in a vector store. - */ - file_ids?: Array; - - /** - * Set of 16 key-value pairs that can be attached to a vector store. This can be - * useful for storing additional information about the vector store in a structured - * format. Keys can be a maximum of 64 characters long and values can be a maximum - * of 512 characters long. - */ - metadata?: unknown; - } - - export namespace VectorStore { - /** - * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of - * `800` and `chunk_overlap_tokens` of `400`. - */ - export interface AutoChunkingStrategy { - /** - * Always `auto`. - */ - type: 'auto'; - } - - export interface StaticChunkingStrategy { - static: StaticChunkingStrategy.Static; - - /** - * Always `static`. - */ - type: 'static'; - } - - export namespace StaticChunkingStrategy { - export interface Static { - /** - * The number of tokens that overlap between chunks. The default value is `400`. - * - * Note that the overlap must not exceed half of `max_chunk_size_tokens`. - */ - chunk_overlap_tokens: number; - - /** - * The maximum number of tokens in each chunk. The default value is `800`. The - * minimum value is `100` and the maximum value is `4096`. - */ - max_chunk_size_tokens: number; - } - } - } - } - - export interface UnionMember1 { - /** - * A helper to create a [vector store](/docs/api-reference/vector-stores/object) - * with file_ids and attach it to this thread. There can be a maximum of 1 vector - * store attached to the thread. - */ - vector_stores: Array; - - /** - * The [vector store](/docs/api-reference/vector-stores/object) attached to this - * thread. There can be a maximum of 1 vector store attached to the thread. - */ - vector_store_ids?: Array; - } - - export namespace UnionMember1 { - export interface VectorStore { - /** - * The chunking strategy used to chunk the file(s). If not set, will use the `auto` - * strategy. - */ - chunking_strategy?: VectorStore.AutoChunkingStrategy | VectorStore.StaticChunkingStrategy; - - /** - * A list of [file](/docs/api-reference/files) IDs to add to the vector store. - * There can be a maximum of 10000 files in a vector store. - */ - file_ids?: Array; - - /** - * Set of 16 key-value pairs that can be attached to a vector store. This can be - * useful for storing additional information about the vector store in a structured - * format. Keys can be a maximum of 64 characters long and values can be a maximum - * of 512 characters long. - */ - metadata?: unknown; - } - - export namespace VectorStore { - /** - * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of - * `800` and `chunk_overlap_tokens` of `400`. - */ - export interface AutoChunkingStrategy { - /** - * Always `auto`. - */ - type: 'auto'; - } - - export interface StaticChunkingStrategy { - static: StaticChunkingStrategy.Static; - - /** - * Always `static`. - */ - type: 'static'; - } - - export namespace StaticChunkingStrategy { - export interface Static { - /** - * The number of tokens that overlap between chunks. The default value is `400`. - * - * Note that the overlap must not exceed half of `max_chunk_size_tokens`. - */ - chunk_overlap_tokens: number; - - /** - * The maximum number of tokens in each chunk. The default value is `800`. The - * minimum value is `100` and the maximum value is `4096`. - */ - max_chunk_size_tokens: number; - } - } - } - } - } -} - -export interface ThreadUpdateParams { - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; - - /** - * A set of resources that are made available to the assistant's tools in this - * thread. The resources are specific to the type of tool. For example, the - * `code_interpreter` tool requires a list of file IDs, while the `file_search` - * tool requires a list of vector store IDs. - */ - tool_resources?: ThreadUpdateParams.ToolResources | null; -} - -export namespace ThreadUpdateParams { - /** - * A set of resources that are made available to the assistant's tools in this - * thread. The resources are specific to the type of tool. For example, the - * `code_interpreter` tool requires a list of file IDs, while the `file_search` - * tool requires a list of vector store IDs. - */ - export interface ToolResources { - code_interpreter?: ToolResources.CodeInterpreter; - - file_search?: ToolResources.FileSearch; - } - - export namespace ToolResources { - export interface CodeInterpreter { - /** - * A list of [file](/docs/api-reference/files) IDs made available to the - * `code_interpreter` tool. There can be a maximum of 20 files associated with the - * tool. - */ - file_ids?: Array; - } - - export interface FileSearch { - /** - * The [vector store](/docs/api-reference/vector-stores/object) attached to this - * thread. There can be a maximum of 1 vector store attached to the thread. - */ - vector_store_ids?: Array; - } - } -} - -export namespace Threads { - export import ThreadDeleteResponse = ThreadsThreadsAPI.ThreadDeleteResponse; - export import ThreadCreateParams = ThreadsThreadsAPI.ThreadCreateParams; - export import ThreadUpdateParams = ThreadsThreadsAPI.ThreadUpdateParams; - export import Messages = MessagesAPI.Messages; - export import MessageListResponse = MessagesAPI.MessageListResponse; - export import MessageDeleteResponse = MessagesAPI.MessageDeleteResponse; - export import MessageCreateParams = MessagesAPI.MessageCreateParams; - export import MessageListParams = MessagesAPI.MessageListParams; - export import Runs = RunsAPI.Runs; - export import RunListResponse = RunsAPI.RunListResponse; - export import RunCreateParams = RunsAPI.RunCreateParams; - export import RunListParams = RunsAPI.RunListParams; - export import RunSubmitToolOutputsParams = RunsAPI.RunSubmitToolOutputsParams; -} diff --git a/src/resources/uploads/index.ts b/src/resources/uploads/index.ts deleted file mode 100644 index f300913..0000000 --- a/src/resources/uploads/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { PartCreateParams, Parts } from './parts'; -export { Upload, UploadPart, UploadCreateParams, UploadCompleteParams, Uploads } from './uploads'; diff --git a/src/resources/uploads/parts.ts b/src/resources/uploads/parts.ts deleted file mode 100644 index 90bcae8..0000000 --- a/src/resources/uploads/parts.ts +++ /dev/null @@ -1,42 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as PartsAPI from './parts'; -import * as UploadsAPI from './uploads'; - -export class Parts extends APIResource { - /** - * Adds a [Part](/docs/api-reference/uploads/part-object) to an - * [Upload](/docs/api-reference/uploads/object) object. A Part represents a chunk - * of bytes from the file you are trying to upload. - * - * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload - * maximum of 8 GB. - * - * It is possible to add multiple Parts in parallel. You can decide the intended - * order of the Parts when you - * [complete the Upload](/docs/api-reference/uploads/complete). - */ - create( - uploadId: string, - body: PartCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post( - `/uploads/${uploadId}/parts`, - Core.multipartFormRequestOptions({ body, ...options }), - ); - } -} - -export interface PartCreateParams { - /** - * The chunk of bytes for this Part. - */ - data: Core.Uploadable; -} - -export namespace Parts { - export import PartCreateParams = PartsAPI.PartCreateParams; -} diff --git a/src/resources/uploads/uploads.ts b/src/resources/uploads/uploads.ts deleted file mode 100644 index 0be35c1..0000000 --- a/src/resources/uploads/uploads.ts +++ /dev/null @@ -1,190 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import * as Core from '../../core'; -import * as UploadsAPI from './uploads'; -import * as FilesAPI from '../files/files'; -import * as PartsAPI from './parts'; - -export class Uploads extends APIResource { - parts: PartsAPI.Parts = new PartsAPI.Parts(this._client); - - /** - * Creates an intermediate [Upload](/docs/api-reference/uploads/object) object that - * you can add [Parts](/docs/api-reference/uploads/part-object) to. Currently, an - * Upload can accept at most 8 GB in total and expires after an hour after you - * create it. - * - * Once you complete the Upload, we will create a - * [File](/docs/api-reference/files/object) object that contains all the parts you - * uploaded. This File is usable in the rest of our platform as a regular File - * object. - * - * For certain `purpose`s, the correct `mime_type` must be specified. Please refer - * to documentation for the supported MIME types for your use case: - * - * - [Assistants](/docs/assistants/tools/file-search/supported-files) - * - * For guidance on the proper filename extensions for each purpose, please follow - * the documentation on [creating a File](/docs/api-reference/files/create). - */ - create(body: UploadCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/uploads', { body, ...options }); - } - - /** - * Cancels the Upload. No Parts may be added after an Upload is cancelled. - */ - cancel(uploadId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post(`/uploads/${uploadId}/cancel`, options); - } - - /** - * Completes the [Upload](/docs/api-reference/uploads/object). - * - * Within the returned Upload object, there is a nested - * [File](/docs/api-reference/files/object) object that is ready to use in the rest - * of the platform. - * - * You can specify the order of the Parts by passing in an ordered list of the Part - * IDs. - * - * The number of bytes uploaded upon completion must match the number of bytes - * initially specified when creating the Upload object. No Parts may be added after - * an Upload is completed. - */ - complete( - uploadId: string, - body: UploadCompleteParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options }); - } -} - -/** - * The Upload object can accept byte chunks in the form of Parts. - */ -export interface Upload { - /** - * The Upload unique identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The intended number of bytes to be uploaded. - */ - bytes: number; - - /** - * The Unix timestamp (in seconds) for when the Upload was created. - */ - created_at: number; - - /** - * The Unix timestamp (in seconds) for when the Upload was created. - */ - expires_at: number; - - /** - * The name of the file to be uploaded. - */ - filename: string; - - /** - * The intended purpose of the file. - * [Please refer here](/docs/api-reference/files/object#files/object-purpose) for - * acceptable values. - */ - purpose: string; - - /** - * The status of the Upload. - */ - status: 'pending' | 'completed' | 'cancelled' | 'expired'; - - /** - * The ready File object after the Upload is completed. - */ - file?: FilesAPI.OpenAIFile | null; - - /** - * The object type, which is always "upload". - */ - object?: 'upload'; -} - -/** - * The upload Part represents a chunk of bytes we can add to an Upload object. - */ -export interface UploadPart { - /** - * The upload Part unique identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the Part was created. - */ - created_at: number; - - /** - * The object type, which is always `upload.part`. - */ - object: 'upload.part'; - - /** - * The ID of the Upload object that this Part was added to. - */ - upload_id: string; -} - -export interface UploadCreateParams { - /** - * The number of bytes in the file you are uploading. - */ - bytes: number; - - /** - * The name of the file to upload. - */ - filename: string; - - /** - * The MIME type of the file. - * - * This must fall within the supported MIME types for your file purpose. See the - * supported MIME types for assistants and vision. - */ - mime_type: string; - - /** - * The intended purpose of the uploaded file. - * - * See the - * [documentation on File purposes](/docs/api-reference/files/create#files-create-purpose). - */ - purpose: 'assistants' | 'batch' | 'fine-tune' | 'vision'; -} - -export interface UploadCompleteParams { - /** - * The ordered list of Part IDs. - */ - part_ids: Array; - - /** - * The optional md5 checksum for the file contents to verify if the bytes uploaded - * matches what you expect. - */ - md5?: string; -} - -export namespace Uploads { - export import Upload = UploadsAPI.Upload; - export import UploadPart = UploadsAPI.UploadPart; - export import UploadCreateParams = UploadsAPI.UploadCreateParams; - export import UploadCompleteParams = UploadsAPI.UploadCompleteParams; - export import Parts = PartsAPI.Parts; - export import PartCreateParams = PartsAPI.PartCreateParams; -} diff --git a/src/resources/vector-stores/file-batches/file-batches.ts b/src/resources/vector-stores/file-batches/file-batches.ts deleted file mode 100644 index 18c3dd5..0000000 --- a/src/resources/vector-stores/file-batches/file-batches.ts +++ /dev/null @@ -1,171 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import * as Core from '../../../core'; -import * as FileBatchesAPI from './file-batches'; -import * as FilesAPI from './files'; - -export class FileBatches extends APIResource { - files: FilesAPI.Files = new FilesAPI.Files(this._client); - - /** - * Create a vector store file batch. - */ - create( - vectorStoreId: string, - body: FileBatchCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, { body, ...options }); - } - - /** - * Retrieves a vector store file batch. - */ - retrieve( - vectorStoreId: string, - batchId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, options); - } - - /** - * Cancel a vector store file batch. This attempts to cancel the processing of - * files in this batch as soon as possible. - */ - cancel( - vectorStoreId: string, - batchId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, options); - } -} - -/** - * A batch of files attached to a vector store. - */ -export interface VectorStoreFileBatchObject { - /** - * The identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the vector store files batch was - * created. - */ - created_at: number; - - file_counts: VectorStoreFileBatchObject.FileCounts; - - /** - * The object type, which is always `vector_store.file_batch`. - */ - object: 'vector_store.files_batch'; - - /** - * The status of the vector store files batch, which can be either `in_progress`, - * `completed`, `cancelled` or `failed`. - */ - status: 'in_progress' | 'completed' | 'cancelled' | 'failed'; - - /** - * The ID of the [vector store](/docs/api-reference/vector-stores/object) that the - * [File](/docs/api-reference/files) is attached to. - */ - vector_store_id: string; -} - -export namespace VectorStoreFileBatchObject { - export interface FileCounts { - /** - * The number of files that where cancelled. - */ - cancelled: number; - - /** - * The number of files that have been processed. - */ - completed: number; - - /** - * The number of files that have failed to process. - */ - failed: number; - - /** - * The number of files that are currently being processed. - */ - in_progress: number; - - /** - * The total number of files. - */ - total: number; - } -} - -export interface FileBatchCreateParams { - /** - * A list of [File](/docs/api-reference/files) IDs that the vector store should - * use. Useful for tools like `file_search` that can access files. - */ - file_ids: Array; - - /** - * The chunking strategy used to chunk the file(s). If not set, will use the `auto` - * strategy. - */ - chunking_strategy?: - | FileBatchCreateParams.AutoChunkingStrategyRequestParam - | FileBatchCreateParams.StaticChunkingStrategyRequestParam; -} - -export namespace FileBatchCreateParams { - /** - * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of - * `800` and `chunk_overlap_tokens` of `400`. - */ - export interface AutoChunkingStrategyRequestParam { - /** - * Always `auto`. - */ - type: 'auto'; - } - - export interface StaticChunkingStrategyRequestParam { - static: StaticChunkingStrategyRequestParam.Static; - - /** - * Always `static`. - */ - type: 'static'; - } - - export namespace StaticChunkingStrategyRequestParam { - export interface Static { - /** - * The number of tokens that overlap between chunks. The default value is `400`. - * - * Note that the overlap must not exceed half of `max_chunk_size_tokens`. - */ - chunk_overlap_tokens: number; - - /** - * The maximum number of tokens in each chunk. The default value is `800`. The - * minimum value is `100` and the maximum value is `4096`. - */ - max_chunk_size_tokens: number; - } - } -} - -export namespace FileBatches { - export import VectorStoreFileBatchObject = FileBatchesAPI.VectorStoreFileBatchObject; - export import FileBatchCreateParams = FileBatchesAPI.FileBatchCreateParams; - export import Files = FilesAPI.Files; - export import FileListResponse = FilesAPI.FileListResponse; - export import FileListParams = FilesAPI.FileListParams; -} diff --git a/src/resources/vector-stores/file-batches/files.ts b/src/resources/vector-stores/file-batches/files.ts deleted file mode 100644 index 23d2345..0000000 --- a/src/resources/vector-stores/file-batches/files.ts +++ /dev/null @@ -1,90 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../../resource'; -import { isRequestOptions } from '../../../core'; -import * as Core from '../../../core'; -import * as FileBatchesFilesAPI from './files'; -import * as FilesAPI from '../files'; - -export class Files extends APIResource { - /** - * Returns a list of vector store files in a batch. - */ - list( - vectorStoreId: string, - batchId: string, - query?: FileListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list( - vectorStoreId: string, - batchId: string, - options?: Core.RequestOptions, - ): Core.APIPromise; - list( - vectorStoreId: string, - batchId: string, - query: FileListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(vectorStoreId, batchId, {}, query); - } - return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, { - query, - ...options, - }); - } -} - -export interface FileListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface FileListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. - */ - filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Sort order by the `created_at` timestamp of the objects. `asc` for ascending - * order and `desc` for descending order. - */ - order?: 'asc' | 'desc'; -} - -export namespace Files { - export import FileListResponse = FileBatchesFilesAPI.FileListResponse; - export import FileListParams = FileBatchesFilesAPI.FileListParams; -} diff --git a/src/resources/vector-stores/file-batches/index.ts b/src/resources/vector-stores/file-batches/index.ts deleted file mode 100644 index 7c4b126..0000000 --- a/src/resources/vector-stores/file-batches/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { FileListResponse, FileListParams, Files } from './files'; -export { VectorStoreFileBatchObject, FileBatchCreateParams, FileBatches } from './file-batches'; diff --git a/src/resources/vector-stores/files.ts b/src/resources/vector-stores/files.ts deleted file mode 100644 index d5eeb20..0000000 --- a/src/resources/vector-stores/files.ts +++ /dev/null @@ -1,290 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as FilesAPI from './files'; - -export class Files extends APIResource { - /** - * Create a vector store file by attaching a [File](/docs/api-reference/files) to a - * [vector store](/docs/api-reference/vector-stores/object). - */ - create( - vectorStoreId: string, - body: FileCreateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/vector_stores/${vectorStoreId}/files`, { body, ...options }); - } - - /** - * Retrieves a vector store file. - */ - retrieve( - vectorStoreId: string, - fileId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, options); - } - - /** - * Returns a list of vector store files. - */ - list( - vectorStoreId: string, - query?: FileListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(vectorStoreId: string, options?: Core.RequestOptions): Core.APIPromise; - list( - vectorStoreId: string, - query: FileListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list(vectorStoreId, {}, query); - } - return this._client.get(`/vector_stores/${vectorStoreId}/files`, { query, ...options }); - } - - /** - * Delete a vector store file. This will remove the file from the vector store but - * the file itself will not be deleted. To delete the file, use the - * [delete file](/docs/api-reference/files/delete) endpoint. - */ - delete( - vectorStoreId: string, - fileId: string, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, options); - } -} - -/** - * A list of files attached to a vector store. - */ -export interface VectorStoreFileObject { - /** - * The identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the vector store file was created. - */ - created_at: number; - - /** - * The last error associated with this vector store file. Will be `null` if there - * are no errors. - */ - last_error: VectorStoreFileObject.LastError | null; - - /** - * The object type, which is always `vector_store.file`. - */ - object: 'vector_store.file'; - - /** - * The status of the vector store file, which can be either `in_progress`, - * `completed`, `cancelled`, or `failed`. The status `completed` indicates that the - * vector store file is ready for use. - */ - status: 'in_progress' | 'completed' | 'cancelled' | 'failed'; - - /** - * The total vector store usage in bytes. Note that this may be different from the - * original file size. - */ - usage_bytes: number; - - /** - * The ID of the [vector store](/docs/api-reference/vector-stores/object) that the - * [File](/docs/api-reference/files) is attached to. - */ - vector_store_id: string; - - /** - * The strategy used to chunk the file. - */ - chunking_strategy?: - | VectorStoreFileObject.StaticChunkingStrategyResponseParam - | VectorStoreFileObject.OtherChunkingStrategyResponseParam; -} - -export namespace VectorStoreFileObject { - /** - * The last error associated with this vector store file. Will be `null` if there - * are no errors. - */ - export interface LastError { - /** - * One of `server_error` or `rate_limit_exceeded`. - */ - code: 'server_error' | 'unsupported_file' | 'invalid_file'; - - /** - * A human-readable description of the error. - */ - message: string; - } - - export interface StaticChunkingStrategyResponseParam { - static: StaticChunkingStrategyResponseParam.Static; - - /** - * Always `static`. - */ - type: 'static'; - } - - export namespace StaticChunkingStrategyResponseParam { - export interface Static { - /** - * The number of tokens that overlap between chunks. The default value is `400`. - * - * Note that the overlap must not exceed half of `max_chunk_size_tokens`. - */ - chunk_overlap_tokens: number; - - /** - * The maximum number of tokens in each chunk. The default value is `800`. The - * minimum value is `100` and the maximum value is `4096`. - */ - max_chunk_size_tokens: number; - } - } - - /** - * This is returned when the chunking strategy is unknown. Typically, this is - * because the file was indexed before the `chunking_strategy` concept was - * introduced in the API. - */ - export interface OtherChunkingStrategyResponseParam { - /** - * Always `other`. - */ - type: 'other'; - } -} - -export interface FileListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface FileDeleteResponse { - id: string; - - deleted: boolean; - - object: 'vector_store.file.deleted'; -} - -export interface FileCreateParams { - /** - * A [File](/docs/api-reference/files) ID that the vector store should use. Useful - * for tools like `file_search` that can access files. - */ - file_id: string; - - /** - * The chunking strategy used to chunk the file(s). If not set, will use the `auto` - * strategy. - */ - chunking_strategy?: - | FileCreateParams.AutoChunkingStrategyRequestParam - | FileCreateParams.StaticChunkingStrategyRequestParam; -} - -export namespace FileCreateParams { - /** - * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of - * `800` and `chunk_overlap_tokens` of `400`. - */ - export interface AutoChunkingStrategyRequestParam { - /** - * Always `auto`. - */ - type: 'auto'; - } - - export interface StaticChunkingStrategyRequestParam { - static: StaticChunkingStrategyRequestParam.Static; - - /** - * Always `static`. - */ - type: 'static'; - } - - export namespace StaticChunkingStrategyRequestParam { - export interface Static { - /** - * The number of tokens that overlap between chunks. The default value is `400`. - * - * Note that the overlap must not exceed half of `max_chunk_size_tokens`. - */ - chunk_overlap_tokens: number; - - /** - * The maximum number of tokens in each chunk. The default value is `800`. The - * minimum value is `100` and the maximum value is `4096`. - */ - max_chunk_size_tokens: number; - } - } -} - -export interface FileListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. - */ - filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Sort order by the `created_at` timestamp of the objects. `asc` for ascending - * order and `desc` for descending order. - */ - order?: 'asc' | 'desc'; -} - -export namespace Files { - export import VectorStoreFileObject = FilesAPI.VectorStoreFileObject; - export import FileListResponse = FilesAPI.FileListResponse; - export import FileDeleteResponse = FilesAPI.FileDeleteResponse; - export import FileCreateParams = FilesAPI.FileCreateParams; - export import FileListParams = FilesAPI.FileListParams; -} diff --git a/src/resources/vector-stores/index.ts b/src/resources/vector-stores/index.ts deleted file mode 100644 index 15f37f3..0000000 --- a/src/resources/vector-stores/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export { VectorStoreFileBatchObject, FileBatchCreateParams, FileBatches } from './file-batches/index'; -export { - VectorStoreFileObject, - FileListResponse, - FileDeleteResponse, - FileCreateParams, - FileListParams, - Files, -} from './files'; -export { - VectorStoreObject, - VectorStoreListResponse, - VectorStoreDeleteResponse, - VectorStoreCreateParams, - VectorStoreUpdateParams, - VectorStoreListParams, - VectorStores, -} from './vector-stores'; diff --git a/src/resources/vector-stores/vector-stores.ts b/src/resources/vector-stores/vector-stores.ts deleted file mode 100644 index 7332326..0000000 --- a/src/resources/vector-stores/vector-stores.ts +++ /dev/null @@ -1,366 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import { APIResource } from '../../resource'; -import { isRequestOptions } from '../../core'; -import * as Core from '../../core'; -import * as VectorStoresAPI from './vector-stores'; -import * as FilesAPI from './files'; -import * as FileBatchesAPI from './file-batches/file-batches'; - -export class VectorStores extends APIResource { - files: FilesAPI.Files = new FilesAPI.Files(this._client); - fileBatches: FileBatchesAPI.FileBatches = new FileBatchesAPI.FileBatches(this._client); - - /** - * Create a vector store. - */ - create(body: VectorStoreCreateParams, options?: Core.RequestOptions): Core.APIPromise { - return this._client.post('/vector_stores', { body, ...options }); - } - - /** - * Retrieves a vector store. - */ - retrieve(vectorStoreId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.get(`/vector_stores/${vectorStoreId}`, options); - } - - /** - * Modifies a vector store. - */ - update( - vectorStoreId: string, - body: VectorStoreUpdateParams, - options?: Core.RequestOptions, - ): Core.APIPromise { - return this._client.post(`/vector_stores/${vectorStoreId}`, { body, ...options }); - } - - /** - * Returns a list of vector stores. - */ - list( - query?: VectorStoreListParams, - options?: Core.RequestOptions, - ): Core.APIPromise; - list(options?: Core.RequestOptions): Core.APIPromise; - list( - query: VectorStoreListParams | Core.RequestOptions = {}, - options?: Core.RequestOptions, - ): Core.APIPromise { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.get('/vector_stores', { query, ...options }); - } - - /** - * Delete a vector store. - */ - delete(vectorStoreId: string, options?: Core.RequestOptions): Core.APIPromise { - return this._client.delete(`/vector_stores/${vectorStoreId}`, options); - } -} - -/** - * A vector store is a collection of processed files can be used by the - * `file_search` tool. - */ -export interface VectorStoreObject { - /** - * The identifier, which can be referenced in API endpoints. - */ - id: string; - - /** - * The Unix timestamp (in seconds) for when the vector store was created. - */ - created_at: number; - - file_counts: VectorStoreObject.FileCounts; - - /** - * The Unix timestamp (in seconds) for when the vector store was last active. - */ - last_active_at: number | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata: unknown | null; - - /** - * The name of the vector store. - */ - name: string; - - /** - * The object type, which is always `vector_store`. - */ - object: 'vector_store'; - - /** - * The status of the vector store, which can be either `expired`, `in_progress`, or - * `completed`. A status of `completed` indicates that the vector store is ready - * for use. - */ - status: 'expired' | 'in_progress' | 'completed'; - - /** - * The total number of bytes used by the files in the vector store. - */ - usage_bytes: number; - - /** - * The expiration policy for a vector store. - */ - expires_after?: VectorStoreObject.ExpiresAfter; - - /** - * The Unix timestamp (in seconds) for when the vector store will expire. - */ - expires_at?: number | null; -} - -export namespace VectorStoreObject { - export interface FileCounts { - /** - * The number of files that were cancelled. - */ - cancelled: number; - - /** - * The number of files that have been successfully processed. - */ - completed: number; - - /** - * The number of files that have failed to process. - */ - failed: number; - - /** - * The number of files that are currently being processed. - */ - in_progress: number; - - /** - * The total number of files. - */ - total: number; - } - - /** - * The expiration policy for a vector store. - */ - export interface ExpiresAfter { - /** - * Anchor timestamp after which the expiration policy applies. Supported anchors: - * `last_active_at`. - */ - anchor: 'last_active_at'; - - /** - * The number of days after the anchor time that the vector store will expire. - */ - days: number; - } -} - -export interface VectorStoreListResponse { - data: Array; - - first_id: string; - - has_more: boolean; - - last_id: string; - - object: string; -} - -export interface VectorStoreDeleteResponse { - id: string; - - deleted: boolean; - - object: 'vector_store.deleted'; -} - -export interface VectorStoreCreateParams { - /** - * The chunking strategy used to chunk the file(s). If not set, will use the `auto` - * strategy. Only applicable if `file_ids` is non-empty. - */ - chunking_strategy?: - | VectorStoreCreateParams.AutoChunkingStrategyRequestParam - | VectorStoreCreateParams.StaticChunkingStrategyRequestParam; - - /** - * The expiration policy for a vector store. - */ - expires_after?: VectorStoreCreateParams.ExpiresAfter; - - /** - * A list of [File](/docs/api-reference/files) IDs that the vector store should - * use. Useful for tools like `file_search` that can access files. - */ - file_ids?: Array; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; - - /** - * The name of the vector store. - */ - name?: string; -} - -export namespace VectorStoreCreateParams { - /** - * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of - * `800` and `chunk_overlap_tokens` of `400`. - */ - export interface AutoChunkingStrategyRequestParam { - /** - * Always `auto`. - */ - type: 'auto'; - } - - export interface StaticChunkingStrategyRequestParam { - static: StaticChunkingStrategyRequestParam.Static; - - /** - * Always `static`. - */ - type: 'static'; - } - - export namespace StaticChunkingStrategyRequestParam { - export interface Static { - /** - * The number of tokens that overlap between chunks. The default value is `400`. - * - * Note that the overlap must not exceed half of `max_chunk_size_tokens`. - */ - chunk_overlap_tokens: number; - - /** - * The maximum number of tokens in each chunk. The default value is `800`. The - * minimum value is `100` and the maximum value is `4096`. - */ - max_chunk_size_tokens: number; - } - } - - /** - * The expiration policy for a vector store. - */ - export interface ExpiresAfter { - /** - * Anchor timestamp after which the expiration policy applies. Supported anchors: - * `last_active_at`. - */ - anchor: 'last_active_at'; - - /** - * The number of days after the anchor time that the vector store will expire. - */ - days: number; - } -} - -export interface VectorStoreUpdateParams { - /** - * The expiration policy for a vector store. - */ - expires_after?: VectorStoreUpdateParams.ExpiresAfter | null; - - /** - * Set of 16 key-value pairs that can be attached to an object. This can be useful - * for storing additional information about the object in a structured format. Keys - * can be a maximum of 64 characters long and values can be a maximum of 512 - * characters long. - */ - metadata?: unknown | null; - - /** - * The name of the vector store. - */ - name?: string | null; -} - -export namespace VectorStoreUpdateParams { - /** - * The expiration policy for a vector store. - */ - export interface ExpiresAfter { - /** - * Anchor timestamp after which the expiration policy applies. Supported anchors: - * `last_active_at`. - */ - anchor: 'last_active_at'; - - /** - * The number of days after the anchor time that the vector store will expire. - */ - days: number; - } -} - -export interface VectorStoreListParams { - /** - * A cursor for use in pagination. `after` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include after=obj_foo in order to - * fetch the next page of the list. - */ - after?: string; - - /** - * A cursor for use in pagination. `before` is an object ID that defines your place - * in the list. For instance, if you make a list request and receive 100 objects, - * ending with obj_foo, your subsequent call can include before=obj_foo in order to - * fetch the previous page of the list. - */ - before?: string; - - /** - * A limit on the number of objects to be returned. Limit can range between 1 and - * 100, and the default is 20. - */ - limit?: number; - - /** - * Sort order by the `created_at` timestamp of the objects. `asc` for ascending - * order and `desc` for descending order. - */ - order?: 'asc' | 'desc'; -} - -export namespace VectorStores { - export import VectorStoreObject = VectorStoresAPI.VectorStoreObject; - export import VectorStoreListResponse = VectorStoresAPI.VectorStoreListResponse; - export import VectorStoreDeleteResponse = VectorStoresAPI.VectorStoreDeleteResponse; - export import VectorStoreCreateParams = VectorStoresAPI.VectorStoreCreateParams; - export import VectorStoreUpdateParams = VectorStoresAPI.VectorStoreUpdateParams; - export import VectorStoreListParams = VectorStoresAPI.VectorStoreListParams; - export import Files = FilesAPI.Files; - export import VectorStoreFileObject = FilesAPI.VectorStoreFileObject; - export import FileListResponse = FilesAPI.FileListResponse; - export import FileDeleteResponse = FilesAPI.FileDeleteResponse; - export import FileCreateParams = FilesAPI.FileCreateParams; - export import FileListParams = FilesAPI.FileListParams; - export import FileBatches = FileBatchesAPI.FileBatches; - export import VectorStoreFileBatchObject = FileBatchesAPI.VectorStoreFileBatchObject; - export import FileBatchCreateParams = FileBatchesAPI.FileBatchCreateParams; -} diff --git a/src/version.ts b/src/version.ts index a64b06c..fe6d1df 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.1.0-alpha.3'; // x-release-please-version +export const VERSION = '0.1.0-alpha.4'; // x-release-please-version diff --git a/tests/api-resources/assistants/assistants.test.ts b/tests/api-resources/assistants/assistants.test.ts deleted file mode 100644 index 9581df4..0000000 --- a/tests/api-resources/assistants/assistants.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource assistants', () => { - test('create', async () => { - const responsePromise = client.assistants.create('assistant_id', {}); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve', async () => { - const responsePromise = client.assistants.retrieve('assistant_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.assistants.retrieve('assistant_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.assistants.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.assistants.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.assistants.list( - { after: 'after', before: 'before', limit: 0, order: 'asc' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.assistants.delete('assistant_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.assistants.delete('assistant_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/audio/speech.test.ts b/tests/api-resources/audio/speech.test.ts deleted file mode 100644 index ed2b7f8..0000000 --- a/tests/api-resources/audio/speech.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource speech', () => { - test('create: required and optional params', async () => { - const response = await client.audio.speech.create({ - input: 'input', - model: 'string', - voice: 'alloy', - response_format: 'mp3', - speed: 0.25, - }); - }); -}); diff --git a/tests/api-resources/audio/transcriptions.test.ts b/tests/api-resources/audio/transcriptions.test.ts deleted file mode 100644 index c5f54a0..0000000 --- a/tests/api-resources/audio/transcriptions.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack, { toFile } from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource transcriptions', () => { - test('create: only required params', async () => { - const responsePromise = client.audio.transcriptions.create({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), - model: 'whisper-1', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.audio.transcriptions.create({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), - model: 'whisper-1', - language: 'language', - prompt: 'prompt', - response_format: 'json', - temperature: 0, - timestamp_granularities: ['word', 'segment'], - }); - }); -}); diff --git a/tests/api-resources/audio/translations.test.ts b/tests/api-resources/audio/translations.test.ts deleted file mode 100644 index 91f58aa..0000000 --- a/tests/api-resources/audio/translations.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack, { toFile } from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource translations', () => { - test('create: only required params', async () => { - const responsePromise = client.audio.translations.create({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), - model: 'whisper-1', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.audio.translations.create({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), - model: 'whisper-1', - prompt: 'prompt', - response_format: 'json', - temperature: 0, - }); - }); -}); diff --git a/tests/api-resources/batches.test.ts b/tests/api-resources/batches.test.ts deleted file mode 100644 index e73466f..0000000 --- a/tests/api-resources/batches.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource batches', () => { - test('create: only required params', async () => { - const responsePromise = client.batches.create({ - completion_window: '24h', - endpoint: '/v1/chat/completions', - input_file_id: 'input_file_id', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.batches.create({ - completion_window: '24h', - endpoint: '/v1/chat/completions', - input_file_id: 'input_file_id', - metadata: { foo: 'string' }, - }); - }); - - test('retrieve', async () => { - const responsePromise = client.batches.retrieve('batch_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.batches.retrieve('batch_id', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list', async () => { - const responsePromise = client.batches.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.batches.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.batches.list({ after: 'after', limit: 0 }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('cancel', async () => { - const responsePromise = client.batches.cancel('batch_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('cancel: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.batches.cancel('batch_id', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); -}); diff --git a/tests/api-resources/embeddings.test.ts b/tests/api-resources/embeddings.test.ts deleted file mode 100644 index 5669d22..0000000 --- a/tests/api-resources/embeddings.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource embeddings', () => { - test('create: only required params', async () => { - const responsePromise = client.embeddings.create({ - input: 'The quick brown fox jumped over the lazy dog', - model: 'text-embedding-3-small', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.embeddings.create({ - input: 'The quick brown fox jumped over the lazy dog', - model: 'text-embedding-3-small', - dimensions: 1, - encoding_format: 'float', - user: 'user-1234', - }); - }); -}); diff --git a/tests/api-resources/files/content.test.ts b/tests/api-resources/files/content.test.ts deleted file mode 100644 index 99e319a..0000000 --- a/tests/api-resources/files/content.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource content', () => { - test('retrieve', async () => { - const responsePromise = client.files.content.retrieve('file_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.files.content.retrieve('file_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/files/files.test.ts b/tests/api-resources/files/files.test.ts deleted file mode 100644 index 07d52cc..0000000 --- a/tests/api-resources/files/files.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack, { toFile } from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource files', () => { - test('create: only required params', async () => { - const responsePromise = client.files.create({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), - purpose: 'assistants', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.files.create({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), - purpose: 'assistants', - }); - }); - - test('retrieve', async () => { - const responsePromise = client.files.retrieve('file_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.files.retrieve('file_id', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list', async () => { - const responsePromise = client.files.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.files.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.files.list({ purpose: 'purpose' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.files.delete('file_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.files.delete('file_id', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); -}); diff --git a/tests/api-resources/fine-tuning/jobs/checkpoints.test.ts b/tests/api-resources/fine-tuning/jobs/checkpoints.test.ts deleted file mode 100644 index 3a99a96..0000000 --- a/tests/api-resources/fine-tuning/jobs/checkpoints.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource checkpoints', () => { - test('list', async () => { - const responsePromise = client.fineTuning.jobs.checkpoints.list('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.fineTuning.jobs.checkpoints.list('ft-AF1WoRqd3aJAHsqc9NY7iL8F', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.fineTuning.jobs.checkpoints.list( - 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - { after: 'after', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/fine-tuning/jobs/events.test.ts b/tests/api-resources/fine-tuning/jobs/events.test.ts deleted file mode 100644 index f432e85..0000000 --- a/tests/api-resources/fine-tuning/jobs/events.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource events', () => { - test('retrieve', async () => { - const responsePromise = client.fineTuning.jobs.events.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.fineTuning.jobs.events.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('retrieve: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.fineTuning.jobs.events.retrieve( - 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - { after: 'after', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/fine-tuning/jobs/jobs.test.ts b/tests/api-resources/fine-tuning/jobs/jobs.test.ts deleted file mode 100644 index d5573b1..0000000 --- a/tests/api-resources/fine-tuning/jobs/jobs.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource jobs', () => { - test('create: only required params', async () => { - const responsePromise = client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', - hyperparameters: { batch_size: 'auto', learning_rate_multiplier: 'auto', n_epochs: 'auto' }, - integrations: [ - { - type: 'wandb', - wandb: { - project: 'my-wandb-project', - entity: 'entity', - name: 'name', - tags: ['custom-tag', 'custom-tag', 'custom-tag'], - }, - }, - { - type: 'wandb', - wandb: { - project: 'my-wandb-project', - entity: 'entity', - name: 'name', - tags: ['custom-tag', 'custom-tag', 'custom-tag'], - }, - }, - { - type: 'wandb', - wandb: { - project: 'my-wandb-project', - entity: 'entity', - name: 'name', - tags: ['custom-tag', 'custom-tag', 'custom-tag'], - }, - }, - ], - seed: 42, - suffix: 'x', - validation_file: 'file-abc123', - }); - }); - - test('retrieve', async () => { - const responsePromise = client.fineTuning.jobs.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.fineTuning.jobs.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.fineTuning.jobs.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.fineTuning.jobs.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.fineTuning.jobs.list({ after: 'after', limit: 0 }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('cancel', async () => { - const responsePromise = client.fineTuning.jobs.cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('cancel: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.fineTuning.jobs.cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/images/edits.test.ts b/tests/api-resources/images/edits.test.ts deleted file mode 100644 index 94ada6f..0000000 --- a/tests/api-resources/images/edits.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack, { toFile } from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource edits', () => { - test('create: only required params', async () => { - const responsePromise = client.images.edits.create({ - image: await toFile(Buffer.from('# my file contents'), 'README.md'), - prompt: 'A cute baby sea otter wearing a beret', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.images.edits.create({ - image: await toFile(Buffer.from('# my file contents'), 'README.md'), - prompt: 'A cute baby sea otter wearing a beret', - mask: await toFile(Buffer.from('# my file contents'), 'README.md'), - model: 'dall-e-2', - n: 1, - response_format: 'url', - size: '256x256', - user: 'user-1234', - }); - }); -}); diff --git a/tests/api-resources/images/generations.test.ts b/tests/api-resources/images/generations.test.ts deleted file mode 100644 index 1df6470..0000000 --- a/tests/api-resources/images/generations.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource generations', () => { - test('create: only required params', async () => { - const responsePromise = client.images.generations.create({ prompt: 'A cute baby sea otter' }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.images.generations.create({ - prompt: 'A cute baby sea otter', - model: 'dall-e-3', - n: 1, - quality: 'standard', - response_format: 'url', - size: '256x256', - style: 'vivid', - user: 'user-1234', - }); - }); -}); diff --git a/tests/api-resources/images/variations.test.ts b/tests/api-resources/images/variations.test.ts deleted file mode 100644 index d2c4c79..0000000 --- a/tests/api-resources/images/variations.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack, { toFile } from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource variations', () => { - test('create: only required params', async () => { - const responsePromise = client.images.variations.create({ - image: await toFile(Buffer.from('# my file contents'), 'README.md'), - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.images.variations.create({ - image: await toFile(Buffer.from('# my file contents'), 'README.md'), - model: 'dall-e-2', - n: 1, - response_format: 'url', - size: '256x256', - user: 'user-1234', - }); - }); -}); diff --git a/tests/api-resources/models.test.ts b/tests/api-resources/models.test.ts deleted file mode 100644 index 59b9375..0000000 --- a/tests/api-resources/models.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource models', () => { - test('retrieve', async () => { - const responsePromise = client.models.retrieve('gpt-4o-mini'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.models.retrieve('gpt-4o-mini', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list', async () => { - const responsePromise = client.models.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.models.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('delete', async () => { - const responsePromise = client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/moderations.test.ts b/tests/api-resources/moderations.test.ts deleted file mode 100644 index 9bfcd5a..0000000 --- a/tests/api-resources/moderations.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource moderations', () => { - test('create: only required params', async () => { - const responsePromise = client.moderations.create({ input: 'I want to kill them.' }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.moderations.create({ - input: 'I want to kill them.', - model: 'omni-moderation-2024-09-26', - }); - }); -}); diff --git a/tests/api-resources/organization/audit-logs.test.ts b/tests/api-resources/organization/audit-logs.test.ts deleted file mode 100644 index 44823b5..0000000 --- a/tests/api-resources/organization/audit-logs.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource auditLogs', () => { - test('list', async () => { - const responsePromise = client.organization.auditLogs.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.organization.auditLogs.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.auditLogs.list( - { - actor_emails: ['string', 'string', 'string'], - actor_ids: ['string', 'string', 'string'], - after: 'after', - before: 'before', - effective_at: { gt: 0, gte: 0, lt: 0, lte: 0 }, - event_types: ['api_key.created', 'api_key.updated', 'api_key.deleted'], - limit: 0, - project_ids: ['string', 'string', 'string'], - resource_ids: ['string', 'string', 'string'], - }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/organization/invites.test.ts b/tests/api-resources/organization/invites.test.ts deleted file mode 100644 index b2cd9a0..0000000 --- a/tests/api-resources/organization/invites.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource invites', () => { - test('create: only required params', async () => { - const responsePromise = client.organization.invites.create({ email: 'email', role: 'reader' }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.organization.invites.create({ email: 'email', role: 'reader' }); - }); - - test('retrieve', async () => { - const responsePromise = client.organization.invites.retrieve('invite_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.invites.retrieve('invite_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.organization.invites.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.organization.invites.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.invites.list({ after: 'after', limit: 0 }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.organization.invites.delete('invite_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.invites.delete('invite_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/organization/projects/projects.test.ts b/tests/api-resources/organization/projects/projects.test.ts deleted file mode 100644 index 2451cd2..0000000 --- a/tests/api-resources/organization/projects/projects.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource projects', () => { - test('create: only required params', async () => { - const responsePromise = client.organization.projects.create('project_id', { name: 'name' }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.organization.projects.create('project_id', { name: 'name' }); - }); - - test('retrieve', async () => { - const responsePromise = client.organization.projects.retrieve('project_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.retrieve('project_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.organization.projects.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.organization.projects.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.list( - { after: 'after', include_archived: true, limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('archive', async () => { - const responsePromise = client.organization.projects.archive('project_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('archive: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.archive('project_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/organization/projects/service-accounts.test.ts b/tests/api-resources/organization/projects/service-accounts.test.ts deleted file mode 100644 index 7d38d19..0000000 --- a/tests/api-resources/organization/projects/service-accounts.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource serviceAccounts', () => { - test('create: only required params', async () => { - const responsePromise = client.organization.projects.serviceAccounts.create('project_id', { - name: 'name', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.organization.projects.serviceAccounts.create('project_id', { - name: 'name', - }); - }); - - test('retrieve', async () => { - const responsePromise = client.organization.projects.serviceAccounts.retrieve( - 'project_id', - 'service_account_id', - ); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.serviceAccounts.retrieve('project_id', 'service_account_id', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.organization.projects.serviceAccounts.list('project_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.serviceAccounts.list('project_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.serviceAccounts.list( - 'project_id', - { after: 'after', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/organization/projects/users.test.ts b/tests/api-resources/organization/projects/users.test.ts deleted file mode 100644 index f7d0812..0000000 --- a/tests/api-resources/organization/projects/users.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource users', () => { - test('create: only required params', async () => { - const responsePromise = client.organization.projects.users.create('project_id', 'user_id', { - role: 'owner', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.organization.projects.users.create('project_id', 'user_id', { - role: 'owner', - }); - }); - - test('retrieve', async () => { - const responsePromise = client.organization.projects.users.retrieve('project_id', 'user_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.users.retrieve('project_id', 'user_id', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.organization.projects.users.list('project_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.users.list('project_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.users.list( - 'project_id', - { after: 'after', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.organization.projects.users.delete('project_id', 'user_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.projects.users.delete('project_id', 'user_id', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/organization/users.test.ts b/tests/api-resources/organization/users.test.ts deleted file mode 100644 index 8d01b58..0000000 --- a/tests/api-resources/organization/users.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource users', () => { - test('create: only required params', async () => { - const responsePromise = client.organization.users.create('user_id', { role: 'owner' }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.organization.users.create('user_id', { role: 'owner' }); - }); - - test('retrieve', async () => { - const responsePromise = client.organization.users.retrieve('user_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.users.retrieve('user_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.organization.users.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.organization.users.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.users.list({ after: 'after', limit: 0 }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.organization.users.delete('user_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.organization.users.delete('user_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/projects/api-keys.test.ts b/tests/api-resources/projects/api-keys.test.ts deleted file mode 100644 index 414f930..0000000 --- a/tests/api-resources/projects/api-keys.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource apiKeys', () => { - test('retrieve', async () => { - const responsePromise = client.projects.apiKeys.retrieve('project_id', 'key_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.projects.apiKeys.retrieve('project_id', 'key_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.projects.apiKeys.list('project_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.projects.apiKeys.list('project_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.projects.apiKeys.list( - 'project_id', - { after: 'after', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.projects.apiKeys.delete('project_id', 'key_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.projects.apiKeys.delete('project_id', 'key_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/projects/service-accounts.test.ts b/tests/api-resources/projects/service-accounts.test.ts deleted file mode 100644 index ea09e20..0000000 --- a/tests/api-resources/projects/service-accounts.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource serviceAccounts', () => { - test('delete', async () => { - const responsePromise = client.projects.serviceAccounts.delete('project_id', 'service_account_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.projects.serviceAccounts.delete('project_id', 'service_account_id', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/threads/messages.test.ts b/tests/api-resources/threads/messages.test.ts deleted file mode 100644 index 275f9b5..0000000 --- a/tests/api-resources/threads/messages.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource messages', () => { - test('create', async () => { - const responsePromise = client.threads.messages.create('thread_id', 'message_id', {}); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve', async () => { - const responsePromise = client.threads.messages.retrieve('thread_id', 'message_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.messages.retrieve('thread_id', 'message_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.threads.messages.list('thread_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.messages.list('thread_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.messages.list( - 'thread_id', - { after: 'after', before: 'before', limit: 0, order: 'asc', run_id: 'run_id' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.threads.messages.delete('thread_id', 'message_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.messages.delete('thread_id', 'message_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/threads/runs/runs.test.ts b/tests/api-resources/threads/runs/runs.test.ts deleted file mode 100644 index 5200132..0000000 --- a/tests/api-resources/threads/runs/runs.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource runs', () => { - test('create', async () => { - const responsePromise = client.threads.runs.create('thread_id', 'run_id', {}); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve', async () => { - const responsePromise = client.threads.runs.retrieve('thread_id', 'run_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.runs.retrieve('thread_id', 'run_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.threads.runs.list('thread_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.threads.runs.list('thread_id', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.runs.list( - 'thread_id', - { after: 'after', before: 'before', limit: 0, order: 'asc' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('cancel', async () => { - const responsePromise = client.threads.runs.cancel('thread_id', 'run_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('cancel: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.runs.cancel('thread_id', 'run_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('submitToolOutputs: only required params', async () => { - const responsePromise = client.threads.runs.submitToolOutputs('thread_id', 'run_id', { - tool_outputs: [{}, {}, {}], - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('submitToolOutputs: required and optional params', async () => { - const response = await client.threads.runs.submitToolOutputs('thread_id', 'run_id', { - tool_outputs: [ - { output: 'output', tool_call_id: 'tool_call_id' }, - { output: 'output', tool_call_id: 'tool_call_id' }, - { output: 'output', tool_call_id: 'tool_call_id' }, - ], - stream: true, - }); - }); -}); diff --git a/tests/api-resources/threads/runs/steps.test.ts b/tests/api-resources/threads/runs/steps.test.ts deleted file mode 100644 index 8de1eae..0000000 --- a/tests/api-resources/threads/runs/steps.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource steps', () => { - test('retrieve', async () => { - const responsePromise = client.threads.runs.steps.retrieve('thread_id', 'run_id', 'step_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.runs.steps.retrieve('thread_id', 'run_id', 'step_id', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('retrieve: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.runs.steps.retrieve( - 'thread_id', - 'run_id', - 'step_id', - { include: ['step_details.tool_calls[*].file_search.results[*].content'] }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.threads.runs.steps.list('thread_id', 'run_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.runs.steps.list('thread_id', 'run_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.runs.steps.list( - 'thread_id', - 'run_id', - { - after: 'after', - before: 'before', - include: ['step_details.tool_calls[*].file_search.results[*].content'], - limit: 0, - order: 'asc', - }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/threads/threads.test.ts b/tests/api-resources/threads/threads.test.ts deleted file mode 100644 index 006118a..0000000 --- a/tests/api-resources/threads/threads.test.ts +++ /dev/null @@ -1,196 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource threads', () => { - test('create', async () => { - const responsePromise = client.threads.create(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.threads.create({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('create: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.threads.create( - { - messages: [ - { - content: 'string', - role: 'user', - attachments: [ - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - ], - metadata: {}, - }, - { - content: 'string', - role: 'user', - attachments: [ - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - ], - metadata: {}, - }, - { - content: 'string', - role: 'user', - attachments: [ - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - { - file_id: 'file_id', - tools: [ - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - { type: 'code_interpreter' }, - ], - }, - ], - metadata: {}, - }, - ], - metadata: {}, - tool_resources: { - code_interpreter: { file_ids: ['string', 'string', 'string'] }, - file_search: { - vector_store_ids: ['string'], - vector_stores: [ - { - chunking_strategy: { type: 'auto' }, - file_ids: ['string', 'string', 'string'], - metadata: {}, - }, - ], - }, - }, - }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('retrieve', async () => { - const responsePromise = client.threads.retrieve('thread_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.threads.retrieve('thread_id', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('update', async () => { - const responsePromise = client.threads.update('thread_id', {}); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete', async () => { - const responsePromise = client.threads.delete('thread_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.threads.delete('thread_id', { path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); -}); diff --git a/tests/api-resources/uploads/parts.test.ts b/tests/api-resources/uploads/parts.test.ts deleted file mode 100644 index 9a165f4..0000000 --- a/tests/api-resources/uploads/parts.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack, { toFile } from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource parts', () => { - test('create: only required params', async () => { - const responsePromise = client.uploads.parts.create('upload_abc123', { - data: await toFile(Buffer.from('# my file contents'), 'README.md'), - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.uploads.parts.create('upload_abc123', { - data: await toFile(Buffer.from('# my file contents'), 'README.md'), - }); - }); -}); diff --git a/tests/api-resources/uploads/uploads.test.ts b/tests/api-resources/uploads/uploads.test.ts deleted file mode 100644 index 24ae4f1..0000000 --- a/tests/api-resources/uploads/uploads.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource uploads', () => { - test('create: only required params', async () => { - const responsePromise = client.uploads.create({ - bytes: 0, - filename: 'filename', - mime_type: 'mime_type', - purpose: 'assistants', - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.uploads.create({ - bytes: 0, - filename: 'filename', - mime_type: 'mime_type', - purpose: 'assistants', - }); - }); - - test('cancel', async () => { - const responsePromise = client.uploads.cancel('upload_abc123'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('cancel: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.uploads.cancel('upload_abc123', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('complete: only required params', async () => { - const responsePromise = client.uploads.complete('upload_abc123', { - part_ids: ['string', 'string', 'string'], - }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('complete: required and optional params', async () => { - const response = await client.uploads.complete('upload_abc123', { - part_ids: ['string', 'string', 'string'], - md5: 'md5', - }); - }); -}); diff --git a/tests/api-resources/vector-stores/file-batches/file-batches.test.ts b/tests/api-resources/vector-stores/file-batches/file-batches.test.ts deleted file mode 100644 index dfecd3c..0000000 --- a/tests/api-resources/vector-stores/file-batches/file-batches.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource fileBatches', () => { - test('create: only required params', async () => { - const responsePromise = client.vectorStores.fileBatches.create('vs_abc123', { file_ids: ['string'] }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.vectorStores.fileBatches.create('vs_abc123', { - file_ids: ['string'], - chunking_strategy: { type: 'auto' }, - }); - }); - - test('retrieve', async () => { - const responsePromise = client.vectorStores.fileBatches.retrieve('vs_abc123', 'vsfb_abc123'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.fileBatches.retrieve('vs_abc123', 'vsfb_abc123', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('cancel', async () => { - const responsePromise = client.vectorStores.fileBatches.cancel('vector_store_id', 'batch_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('cancel: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.fileBatches.cancel('vector_store_id', 'batch_id', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/vector-stores/file-batches/files.test.ts b/tests/api-resources/vector-stores/file-batches/files.test.ts deleted file mode 100644 index f8d29d2..0000000 --- a/tests/api-resources/vector-stores/file-batches/files.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource files', () => { - test('list', async () => { - const responsePromise = client.vectorStores.fileBatches.files.list('vector_store_id', 'batch_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.fileBatches.files.list('vector_store_id', 'batch_id', { - path: '/_stainless_unknown_path', - }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.fileBatches.files.list( - 'vector_store_id', - 'batch_id', - { after: 'after', before: 'before', filter: 'in_progress', limit: 0, order: 'asc' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/vector-stores/files.test.ts b/tests/api-resources/vector-stores/files.test.ts deleted file mode 100644 index d06b840..0000000 --- a/tests/api-resources/vector-stores/files.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource files', () => { - test('create: only required params', async () => { - const responsePromise = client.vectorStores.files.create('vs_abc123', { file_id: 'file_id' }); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('create: required and optional params', async () => { - const response = await client.vectorStores.files.create('vs_abc123', { - file_id: 'file_id', - chunking_strategy: { type: 'auto' }, - }); - }); - - test('retrieve', async () => { - const responsePromise = client.vectorStores.files.retrieve('vs_abc123', 'file-abc123'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.files.retrieve('vs_abc123', 'file-abc123', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list', async () => { - const responsePromise = client.vectorStores.files.list('vector_store_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.files.list('vector_store_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.files.list( - 'vector_store_id', - { after: 'after', before: 'before', filter: 'in_progress', limit: 0, order: 'asc' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.vectorStores.files.delete('vector_store_id', 'file_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.files.delete('vector_store_id', 'file_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/api-resources/vector-stores/vector-stores.test.ts b/tests/api-resources/vector-stores/vector-stores.test.ts deleted file mode 100644 index 34cf171..0000000 --- a/tests/api-resources/vector-stores/vector-stores.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Omnistack from 'omnistack'; -import { Response } from 'node-fetch'; - -const client = new Omnistack({ - bearerToken: 'My Bearer Token', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource vectorStores', () => { - test('create', async () => { - const responsePromise = client.vectorStores.create({}); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve', async () => { - const responsePromise = client.vectorStores.retrieve('vector_store_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('retrieve: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.retrieve('vector_store_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('update', async () => { - const responsePromise = client.vectorStores.update('vector_store_id', {}); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list', async () => { - const responsePromise = client.vectorStores.list(); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('list: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect(client.vectorStores.list({ path: '/_stainless_unknown_path' })).rejects.toThrow( - Omnistack.NotFoundError, - ); - }); - - test('list: request options and params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.list( - { after: 'after', before: 'before', limit: 0, order: 'asc' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Omnistack.NotFoundError); - }); - - test('delete', async () => { - const responsePromise = client.vectorStores.delete('vector_store_id'); - const rawResponse = await responsePromise.asResponse(); - expect(rawResponse).toBeInstanceOf(Response); - const response = await responsePromise; - expect(response).not.toBeInstanceOf(Response); - const dataAndResponse = await responsePromise.withResponse(); - expect(dataAndResponse.data).toBe(response); - expect(dataAndResponse.response).toBe(rawResponse); - }); - - test('delete: request options instead of params are passed correctly', async () => { - // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error - await expect( - client.vectorStores.delete('vector_store_id', { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Omnistack.NotFoundError); - }); -}); diff --git a/tests/index.test.ts b/tests/index.test.ts index 01ab718..90cb7b5 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -295,6 +295,39 @@ describe('retries', () => { expect(capturedRequest!.headers as Headers).not.toHaveProperty('x-stainless-retry-count'); }); + test('omit retry count header by default', async () => { + let count = 0; + let capturedRequest: RequestInit | undefined; + const testFetch = async (url: RequestInfo, init: RequestInit = {}): Promise => { + count++; + if (count <= 2) { + return new Response(undefined, { + status: 429, + headers: { + 'Retry-After': '0.1', + }, + }); + } + capturedRequest = init; + return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); + }; + const client = new Omnistack({ + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + defaultHeaders: { 'X-Stainless-Retry-Count': null }, + }); + + expect( + await client.request({ + path: '/foo', + method: 'get', + }), + ).toEqual({ a: 1 }); + + expect(capturedRequest!.headers as Headers).not.toHaveProperty('x-stainless-retry-count'); + }); + test('overwrite retry count header', async () => { let count = 0; let capturedRequest: RequestInit | undefined; diff --git a/tests/qs/empty-keys-cases.ts b/tests/qs/empty-keys-cases.ts deleted file mode 100644 index ea2c1b0..0000000 --- a/tests/qs/empty-keys-cases.ts +++ /dev/null @@ -1,271 +0,0 @@ -export const empty_test_cases = [ - { - input: '&', - with_empty_keys: {}, - stringify_output: { - brackets: '', - indices: '', - repeat: '', - }, - no_empty_keys: {}, - }, - { - input: '&&', - with_empty_keys: {}, - stringify_output: { - brackets: '', - indices: '', - repeat: '', - }, - no_empty_keys: {}, - }, - { - input: '&=', - with_empty_keys: { '': '' }, - stringify_output: { - brackets: '=', - indices: '=', - repeat: '=', - }, - no_empty_keys: {}, - }, - { - input: '&=&', - with_empty_keys: { '': '' }, - stringify_output: { - brackets: '=', - indices: '=', - repeat: '=', - }, - no_empty_keys: {}, - }, - { - input: '&=&=', - with_empty_keys: { '': ['', ''] }, - stringify_output: { - brackets: '[]=&[]=', - indices: '[0]=&[1]=', - repeat: '=&=', - }, - no_empty_keys: {}, - }, - { - input: '&=&=&', - with_empty_keys: { '': ['', ''] }, - stringify_output: { - brackets: '[]=&[]=', - indices: '[0]=&[1]=', - repeat: '=&=', - }, - no_empty_keys: {}, - }, - { - input: '=', - with_empty_keys: { '': '' }, - no_empty_keys: {}, - stringify_output: { - brackets: '=', - indices: '=', - repeat: '=', - }, - }, - { - input: '=&', - with_empty_keys: { '': '' }, - stringify_output: { - brackets: '=', - indices: '=', - repeat: '=', - }, - no_empty_keys: {}, - }, - { - input: '=&&&', - with_empty_keys: { '': '' }, - stringify_output: { - brackets: '=', - indices: '=', - repeat: '=', - }, - no_empty_keys: {}, - }, - { - input: '=&=&=&', - with_empty_keys: { '': ['', '', ''] }, - stringify_output: { - brackets: '[]=&[]=&[]=', - indices: '[0]=&[1]=&[2]=', - repeat: '=&=&=', - }, - no_empty_keys: {}, - }, - { - input: '=&a[]=b&a[1]=c', - with_empty_keys: { '': '', a: ['b', 'c'] }, - stringify_output: { - brackets: '=&a[]=b&a[]=c', - indices: '=&a[0]=b&a[1]=c', - repeat: '=&a=b&a=c', - }, - no_empty_keys: { a: ['b', 'c'] }, - }, - { - input: '=a', - with_empty_keys: { '': 'a' }, - no_empty_keys: {}, - stringify_output: { - brackets: '=a', - indices: '=a', - repeat: '=a', - }, - }, - { - input: 'a==a', - with_empty_keys: { a: '=a' }, - no_empty_keys: { a: '=a' }, - stringify_output: { - brackets: 'a==a', - indices: 'a==a', - repeat: 'a==a', - }, - }, - { - input: '=&a[]=b', - with_empty_keys: { '': '', a: ['b'] }, - stringify_output: { - brackets: '=&a[]=b', - indices: '=&a[0]=b', - repeat: '=&a=b', - }, - no_empty_keys: { a: ['b'] }, - }, - { - input: '=&a[]=b&a[]=c&a[2]=d', - with_empty_keys: { '': '', a: ['b', 'c', 'd'] }, - stringify_output: { - brackets: '=&a[]=b&a[]=c&a[]=d', - indices: '=&a[0]=b&a[1]=c&a[2]=d', - repeat: '=&a=b&a=c&a=d', - }, - no_empty_keys: { a: ['b', 'c', 'd'] }, - }, - { - input: '=a&=b', - with_empty_keys: { '': ['a', 'b'] }, - stringify_output: { - brackets: '[]=a&[]=b', - indices: '[0]=a&[1]=b', - repeat: '=a&=b', - }, - no_empty_keys: {}, - }, - { - input: '=a&foo=b', - with_empty_keys: { '': 'a', foo: 'b' }, - no_empty_keys: { foo: 'b' }, - stringify_output: { - brackets: '=a&foo=b', - indices: '=a&foo=b', - repeat: '=a&foo=b', - }, - }, - { - input: 'a[]=b&a=c&=', - with_empty_keys: { '': '', a: ['b', 'c'] }, - stringify_output: { - brackets: '=&a[]=b&a[]=c', - indices: '=&a[0]=b&a[1]=c', - repeat: '=&a=b&a=c', - }, - no_empty_keys: { a: ['b', 'c'] }, - }, - { - input: 'a[]=b&a=c&=', - with_empty_keys: { '': '', a: ['b', 'c'] }, - stringify_output: { - brackets: '=&a[]=b&a[]=c', - indices: '=&a[0]=b&a[1]=c', - repeat: '=&a=b&a=c', - }, - no_empty_keys: { a: ['b', 'c'] }, - }, - { - input: 'a[0]=b&a=c&=', - with_empty_keys: { '': '', a: ['b', 'c'] }, - stringify_output: { - brackets: '=&a[]=b&a[]=c', - indices: '=&a[0]=b&a[1]=c', - repeat: '=&a=b&a=c', - }, - no_empty_keys: { a: ['b', 'c'] }, - }, - { - input: 'a=b&a[]=c&=', - with_empty_keys: { '': '', a: ['b', 'c'] }, - stringify_output: { - brackets: '=&a[]=b&a[]=c', - indices: '=&a[0]=b&a[1]=c', - repeat: '=&a=b&a=c', - }, - no_empty_keys: { a: ['b', 'c'] }, - }, - { - input: 'a=b&a[0]=c&=', - with_empty_keys: { '': '', a: ['b', 'c'] }, - stringify_output: { - brackets: '=&a[]=b&a[]=c', - indices: '=&a[0]=b&a[1]=c', - repeat: '=&a=b&a=c', - }, - no_empty_keys: { a: ['b', 'c'] }, - }, - { - input: '[]=a&[]=b& []=1', - with_empty_keys: { '': ['a', 'b'], ' ': ['1'] }, - stringify_output: { - brackets: '[]=a&[]=b& []=1', - indices: '[0]=a&[1]=b& [0]=1', - repeat: '=a&=b& =1', - }, - no_empty_keys: { 0: 'a', 1: 'b', ' ': ['1'] }, - }, - { - input: '[0]=a&[1]=b&a[0]=1&a[1]=2', - with_empty_keys: { '': ['a', 'b'], a: ['1', '2'] }, - no_empty_keys: { 0: 'a', 1: 'b', a: ['1', '2'] }, - stringify_output: { - brackets: '[]=a&[]=b&a[]=1&a[]=2', - indices: '[0]=a&[1]=b&a[0]=1&a[1]=2', - repeat: '=a&=b&a=1&a=2', - }, - }, - { - input: '[deep]=a&[deep]=2', - with_empty_keys: { '': { deep: ['a', '2'] } }, - stringify_output: { - brackets: '[deep][]=a&[deep][]=2', - indices: '[deep][0]=a&[deep][1]=2', - repeat: '[deep]=a&[deep]=2', - }, - no_empty_keys: { deep: ['a', '2'] }, - }, - { - input: '%5B0%5D=a&%5B1%5D=b', - with_empty_keys: { '': ['a', 'b'] }, - stringify_output: { - brackets: '[]=a&[]=b', - indices: '[0]=a&[1]=b', - repeat: '=a&=b', - }, - no_empty_keys: { 0: 'a', 1: 'b' }, - }, -] satisfies { - input: string; - with_empty_keys: Record; - stringify_output: { - brackets: string; - indices: string; - repeat: string; - }; - no_empty_keys: Record; -}[]; diff --git a/tests/qs/stringify.test.ts b/tests/qs/stringify.test.ts deleted file mode 100644 index 2a7f98c..0000000 --- a/tests/qs/stringify.test.ts +++ /dev/null @@ -1,2232 +0,0 @@ -import iconv from 'iconv-lite'; -import { stringify } from 'omnistack/internal/qs'; -import { encode } from 'omnistack/internal/qs/utils'; -import { StringifyOptions } from 'omnistack/internal/qs/types'; -import { empty_test_cases } from './empty-keys-cases'; -import assert from 'assert'; - -describe('stringify()', function () { - test('stringifies a querystring object', function () { - expect(stringify({ a: 'b' })).toBe('a=b'); - expect(stringify({ a: 1 })).toBe('a=1'); - expect(stringify({ a: 1, b: 2 })).toBe('a=1&b=2'); - expect(stringify({ a: 'A_Z' })).toBe('a=A_Z'); - expect(stringify({ a: '€' })).toBe('a=%E2%82%AC'); - expect(stringify({ a: '' })).toBe('a=%EE%80%80'); - expect(stringify({ a: 'א' })).toBe('a=%D7%90'); - expect(stringify({ a: '𐐷' })).toBe('a=%F0%90%90%B7'); - }); - - test('stringifies falsy values', function () { - expect(stringify(undefined)).toBe(''); - expect(stringify(null)).toBe(''); - expect(stringify(null, { strictNullHandling: true })).toBe(''); - expect(stringify(false)).toBe(''); - expect(stringify(0)).toBe(''); - }); - - test('stringifies symbols', function () { - expect(stringify(Symbol.iterator)).toBe(''); - expect(stringify([Symbol.iterator])).toBe('0=Symbol%28Symbol.iterator%29'); - expect(stringify({ a: Symbol.iterator })).toBe('a=Symbol%28Symbol.iterator%29'); - expect(stringify({ a: [Symbol.iterator] }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe( - 'a[]=Symbol%28Symbol.iterator%29', - ); - }); - - test('stringifies bigints', function () { - var three = BigInt(3); - // @ts-expect-error - var encodeWithN = function (value, defaultEncoder, charset) { - var result = defaultEncoder(value, defaultEncoder, charset); - return typeof value === 'bigint' ? result + 'n' : result; - }; - - expect(stringify(three)).toBe(''); - expect(stringify([three])).toBe('0=3'); - expect(stringify([three], { encoder: encodeWithN })).toBe('0=3n'); - expect(stringify({ a: three })).toBe('a=3'); - expect(stringify({ a: three }, { encoder: encodeWithN })).toBe('a=3n'); - expect(stringify({ a: [three] }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe('a[]=3'); - expect( - stringify({ a: [three] }, { encodeValuesOnly: true, encoder: encodeWithN, arrayFormat: 'brackets' }), - ).toBe('a[]=3n'); - }); - - test('encodes dot in key of object when encodeDotInKeys and allowDots is provided', function () { - expect( - stringify({ 'name.obj': { first: 'John', last: 'Doe' } }, { allowDots: false, encodeDotInKeys: false }), - ).toBe('name.obj%5Bfirst%5D=John&name.obj%5Blast%5D=Doe'); - expect( - stringify({ 'name.obj': { first: 'John', last: 'Doe' } }, { allowDots: true, encodeDotInKeys: false }), - ).toBe('name.obj.first=John&name.obj.last=Doe'); - expect( - stringify({ 'name.obj': { first: 'John', last: 'Doe' } }, { allowDots: false, encodeDotInKeys: true }), - ).toBe('name%252Eobj%5Bfirst%5D=John&name%252Eobj%5Blast%5D=Doe'); - expect( - stringify({ 'name.obj': { first: 'John', last: 'Doe' } }, { allowDots: true, encodeDotInKeys: true }), - ).toBe('name%252Eobj.first=John&name%252Eobj.last=Doe'); - - // st.equal( - // stringify( - // { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - // { allowDots: false, encodeDotInKeys: false }, - // ), - // 'name.obj.subobject%5Bfirst.godly.name%5D=John&name.obj.subobject%5Blast%5D=Doe', - // 'with allowDots false and encodeDotInKeys false', - // ); - // st.equal( - // stringify( - // { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - // { allowDots: true, encodeDotInKeys: false }, - // ), - // 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe', - // 'with allowDots false and encodeDotInKeys false', - // ); - // st.equal( - // stringify( - // { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - // { allowDots: false, encodeDotInKeys: true }, - // ), - // 'name%252Eobj%252Esubobject%5Bfirst.godly.name%5D=John&name%252Eobj%252Esubobject%5Blast%5D=Doe', - // 'with allowDots false and encodeDotInKeys true', - // ); - // st.equal( - // stringify( - // { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - // { allowDots: true, encodeDotInKeys: true }, - // ), - // 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', - // 'with allowDots true and encodeDotInKeys true', - // ); - expect( - stringify( - { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - { allowDots: false, encodeDotInKeys: false }, - ), - ).toBe('name.obj.subobject%5Bfirst.godly.name%5D=John&name.obj.subobject%5Blast%5D=Doe'); - expect( - stringify( - { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - { allowDots: true, encodeDotInKeys: false }, - ), - ).toBe('name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe'); - expect( - stringify( - { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - { allowDots: false, encodeDotInKeys: true }, - ), - ).toBe('name%252Eobj%252Esubobject%5Bfirst.godly.name%5D=John&name%252Eobj%252Esubobject%5Blast%5D=Doe'); - expect( - stringify( - { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - { allowDots: true, encodeDotInKeys: true }, - ), - ).toBe('name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe'); - }); - - test('should encode dot in key of object, and automatically set allowDots to `true` when encodeDotInKeys is true and allowDots in undefined', function () { - // st.equal( - // stringify( - // { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - // { encodeDotInKeys: true }, - // ), - // 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', - // 'with allowDots undefined and encodeDotInKeys true', - // ); - expect( - stringify( - { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - { encodeDotInKeys: true }, - ), - ).toBe('name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe'); - }); - - test('should encode dot in key of object when encodeDotInKeys and allowDots is provided, and nothing else when encodeValuesOnly is provided', function () { - // st.equal( - // stringify( - // { 'name.obj': { first: 'John', last: 'Doe' } }, - // { - // encodeDotInKeys: true, - // allowDots: true, - // encodeValuesOnly: true, - // }, - // ), - // 'name%2Eobj.first=John&name%2Eobj.last=Doe', - // ); - expect( - stringify( - { 'name.obj': { first: 'John', last: 'Doe' } }, - { - encodeDotInKeys: true, - allowDots: true, - encodeValuesOnly: true, - }, - ), - ).toBe('name%2Eobj.first=John&name%2Eobj.last=Doe'); - - // st.equal( - // stringify( - // { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - // { allowDots: true, encodeDotInKeys: true, encodeValuesOnly: true }, - // ), - // 'name%2Eobj%2Esubobject.first%2Egodly%2Ename=John&name%2Eobj%2Esubobject.last=Doe', - // ); - expect( - stringify( - { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, - { allowDots: true, encodeDotInKeys: true, encodeValuesOnly: true }, - ), - ).toBe('name%2Eobj%2Esubobject.first%2Egodly%2Ename=John&name%2Eobj%2Esubobject.last=Doe'); - }); - - test('throws when `commaRoundTrip` is not a boolean', function () { - // st['throws']( - // function () { - // stringify({}, { commaRoundTrip: 'not a boolean' }); - // }, - // TypeError, - // 'throws when `commaRoundTrip` is not a boolean', - // ); - expect(() => { - // @ts-expect-error - stringify({}, { commaRoundTrip: 'not a boolean' }); - }).toThrow(TypeError); - }); - - test('throws when `encodeDotInKeys` is not a boolean', function () { - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 'foobar' }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 'foobar' }); - }).toThrow(TypeError); - - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 0 }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 0 }); - }).toThrow(TypeError); - - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { encodeDotInKeys: NaN }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { encodeDotInKeys: NaN }); - }).toThrow(TypeError); - - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { encodeDotInKeys: null }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { encodeDotInKeys: null }); - }).toThrow(TypeError); - }); - - test('adds query prefix', function () { - // st.equal(stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); - expect(stringify({ a: 'b' }, { addQueryPrefix: true })).toBe('?a=b'); - }); - - test('with query prefix, outputs blank string given an empty object', function () { - // st.equal(stringify({}, { addQueryPrefix: true }), ''); - expect(stringify({}, { addQueryPrefix: true })).toBe(''); - }); - - test('stringifies nested falsy values', function () { - // st.equal(stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); - // st.equal( - // stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), - // 'a%5Bb%5D%5Bc%5D', - // ); - // st.equal(stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); - expect(stringify({ a: { b: { c: null } } })).toBe('a%5Bb%5D%5Bc%5D='); - expect(stringify({ a: { b: { c: null } } }, { strictNullHandling: true })).toBe('a%5Bb%5D%5Bc%5D'); - expect(stringify({ a: { b: { c: false } } })).toBe('a%5Bb%5D%5Bc%5D=false'); - }); - - test('stringifies a nested object', function () { - // st.equal(stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); - // st.equal(stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); - expect(stringify({ a: { b: 'c' } })).toBe('a%5Bb%5D=c'); - expect(stringify({ a: { b: { c: { d: 'e' } } } })).toBe('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); - }); - - test('`allowDots` option: stringifies a nested object with dots notation', function () { - // st.equal(stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); - // st.equal(stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); - expect(stringify({ a: { b: 'c' } }, { allowDots: true })).toBe('a.b=c'); - expect(stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true })).toBe('a.b.c.d=e'); - }); - - test('stringifies an array value', function () { - // st.equal( - // stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), - // 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', - // 'indices => indices', - // ); - // st.equal( - // stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), - // 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', - // 'brackets => brackets', - // ); - // st.equal( - // stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), - // 'a=b%2Cc%2Cd', - // 'comma => comma', - // ); - // st.equal( - // stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma', commaRoundTrip: true }), - // 'a=b%2Cc%2Cd', - // 'comma round trip => comma', - // ); - // st.equal( - // stringify({ a: ['b', 'c', 'd'] }), - // 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', - // 'default => indices', - // ); - expect(stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' })).toBe( - 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', - ); - expect(stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' })).toBe( - 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', - ); - expect(stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' })).toBe('a=b%2Cc%2Cd'); - expect(stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma', commaRoundTrip: true })).toBe( - 'a=b%2Cc%2Cd', - ); - expect(stringify({ a: ['b', 'c', 'd'] })).toBe('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); - }); - - test('`skipNulls` option', function () { - // st.equal( - // stringify({ a: 'b', c: null }, { skipNulls: true }), - // 'a=b', - // 'omits nulls when asked', - // ); - expect(stringify({ a: 'b', c: null }, { skipNulls: true })).toBe('a=b'); - - // st.equal( - // stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), - // 'a%5Bb%5D=c', - // 'omits nested nulls when asked', - // ); - expect(stringify({ a: { b: 'c', d: null } }, { skipNulls: true })).toBe('a%5Bb%5D=c'); - }); - - test('omits array indices when asked', function () { - // st.equal(stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); - expect(stringify({ a: ['b', 'c', 'd'] }, { indices: false })).toBe('a=b&a=c&a=d'); - }); - - test('omits object key/value pair when value is empty array', function () { - // st.equal(stringify({ a: [], b: 'zz' }), 'b=zz'); - expect(stringify({ a: [], b: 'zz' })).toBe('b=zz'); - }); - - test('should not omit object key/value pair when value is empty array and when asked', function () { - // st.equal(stringify({ a: [], b: 'zz' }), 'b=zz'); - // st.equal(stringify({ a: [], b: 'zz' }, { allowEmptyArrays: false }), 'b=zz'); - // st.equal(stringify({ a: [], b: 'zz' }, { allowEmptyArrays: true }), 'a[]&b=zz'); - expect(stringify({ a: [], b: 'zz' })).toBe('b=zz'); - expect(stringify({ a: [], b: 'zz' }, { allowEmptyArrays: false })).toBe('b=zz'); - expect(stringify({ a: [], b: 'zz' }, { allowEmptyArrays: true })).toBe('a[]&b=zz'); - }); - - test('should throw when allowEmptyArrays is not of type boolean', function () { - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 'foobar' }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 'foobar' }); - }).toThrow(TypeError); - - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 0 }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 0 }); - }).toThrow(TypeError); - - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { allowEmptyArrays: NaN }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { allowEmptyArrays: NaN }); - }).toThrow(TypeError); - - // st['throws'](function () { - // stringify({ a: [], b: 'zz' }, { allowEmptyArrays: null }); - // }, TypeError); - expect(() => { - // @ts-expect-error - stringify({ a: [], b: 'zz' }, { allowEmptyArrays: null }); - }).toThrow(TypeError); - }); - - test('allowEmptyArrays + strictNullHandling', function () { - // st.equal( - // stringify({ testEmptyArray: [] }, { strictNullHandling: true, allowEmptyArrays: true }), - // 'testEmptyArray[]', - // ); - expect(stringify({ testEmptyArray: [] }, { strictNullHandling: true, allowEmptyArrays: true })).toBe( - 'testEmptyArray[]', - ); - }); - - describe('stringifies an array value with one item vs multiple items', function () { - test('non-array item', function () { - // s2t.equal( - // stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - // 'a=c', - // ); - // s2t.equal( - // stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - // 'a=c', - // ); - // s2t.equal(stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); - // s2t.equal(stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); - expect(stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' })).toBe('a=c'); - expect(stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe('a=c'); - expect(stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' })).toBe('a=c'); - expect(stringify({ a: 'c' }, { encodeValuesOnly: true })).toBe('a=c'); - }); - - test('array with a single item', function () { - // s2t.equal( - // stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - // 'a[0]=c', - // ); - // s2t.equal( - // stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - // 'a[]=c', - // ); - // s2t.equal( - // stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), - // 'a=c', - // ); - // s2t.equal( - // stringify( - // { a: ['c'] }, - // { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }, - // ), - // 'a[]=c', - // ); // so it parses back as an array - // s2t.equal(stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); - expect(stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' })).toBe('a[0]=c'); - expect(stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe('a[]=c'); - expect(stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' })).toBe('a=c'); - expect( - stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), - ).toBe('a[]=c'); - expect(stringify({ a: ['c'] }, { encodeValuesOnly: true })).toBe('a[0]=c'); - }); - - test('array with multiple items', function () { - // s2t.equal( - // stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - // 'a[0]=c&a[1]=d', - // ); - // s2t.equal( - // stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - // 'a[]=c&a[]=d', - // ); - // s2t.equal( - // stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), - // 'a=c,d', - // ); - // s2t.equal( - // stringify( - // { a: ['c', 'd'] }, - // { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }, - // ), - // 'a=c,d', - // ); - // s2t.equal(stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); - expect(stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' })).toBe( - 'a[0]=c&a[1]=d', - ); - expect(stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe( - 'a[]=c&a[]=d', - ); - expect(stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' })).toBe('a=c,d'); - expect( - stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), - ).toBe('a=c,d'); - expect(stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true })).toBe('a[0]=c&a[1]=d'); - }); - - test('array with multiple items with a comma inside', function () { - // s2t.equal( - // stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), - // 'a=c%2Cd,e', - // ); - // s2t.equal(stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma' }), 'a=c%2Cd%2Ce'); - expect(stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma' })).toBe( - 'a=c%2Cd,e', - ); - expect(stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma' })).toBe('a=c%2Cd%2Ce'); - - // s2t.equal( - // stringify( - // { a: ['c,d', 'e'] }, - // { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }, - // ), - // 'a=c%2Cd,e', - // ); - // s2t.equal( - // stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma', commaRoundTrip: true }), - // 'a=c%2Cd%2Ce', - // ); - expect( - stringify( - { a: ['c,d', 'e'] }, - { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }, - ), - ).toBe('a=c%2Cd,e'); - expect(stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma', commaRoundTrip: true })).toBe( - 'a=c%2Cd%2Ce', - ); - }); - }); - - test('stringifies a nested array value', function () { - expect(stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' })).toBe( - 'a[b][0]=c&a[b][1]=d', - ); - expect(stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe( - 'a[b][]=c&a[b][]=d', - ); - expect(stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'comma' })).toBe( - 'a[b]=c,d', - ); - expect(stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true })).toBe('a[b][0]=c&a[b][1]=d'); - }); - - test('stringifies comma and empty array values', function () { - // st.equal( - // stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'indices' }), - // 'a[0]=,&a[1]=&a[2]=c,d%', - // ); - // st.equal( - // stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'brackets' }), - // 'a[]=,&a[]=&a[]=c,d%', - // ); - // st.equal( - // stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'comma' }), - // 'a=,,,c,d%', - // ); - // st.equal( - // stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'repeat' }), - // 'a=,&a=&a=c,d%', - // ); - expect(stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'indices' })).toBe( - 'a[0]=,&a[1]=&a[2]=c,d%', - ); - expect(stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'brackets' })).toBe( - 'a[]=,&a[]=&a[]=c,d%', - ); - expect(stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'comma' })).toBe('a=,,,c,d%'); - expect(stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'repeat' })).toBe( - 'a=,&a=&a=c,d%', - ); - - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'a[0]=%2C&a[1]=&a[2]=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'a[]=%2C&a[]=&a[]=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }, - // ), - // 'a=%2C,,c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }, - // ), - // 'a=%2C&a=&a=c%2Cd%25', - // ); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), - ).toBe('a%5B0%5D=%2C&a%5B1%5D=&a%5B2%5D=c%2Cd%25'); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), - ).toBe('a[]=%2C&a[]=&a[]=c%2Cd%25'); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), - ).toBe('a=%2C%2C%2Cc%2Cd%25'); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), - ).toBe('a=%2C&a=&a=c%2Cd%25'); - - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }, - // ), - // 'a%5B0%5D=%2C&a%5B1%5D=&a%5B2%5D=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }, - // ), - // 'a%5B%5D=%2C&a%5B%5D=&a%5B%5D=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }, - // ), - // 'a=%2C%2C%2Cc%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: [',', '', 'c,d%'] }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }, - // ), - // 'a=%2C&a=&a=c%2Cd%25', - // ); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), - ).toBe('a=%2C&a=&a=c%2Cd%25'); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), - ).toBe('a%5B0%5D=%2C&a%5B1%5D=&a%5B2%5D=c%2Cd%25'); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), - ).toBe('a[]=%2C&a[]=&a[]=c%2Cd%25'); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), - ).toBe('a=%2C%2C%2Cc%2Cd%25'); - expect( - stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), - ).toBe('a=%2C&a=&a=c%2Cd%25'); - }); - - test('stringifies comma and empty non-array values', function () { - // st.equal( - // stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'indices' }), - // 'a=,&b=&c=c,d%', - // ); - // st.equal( - // stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'brackets' }), - // 'a=,&b=&c=c,d%', - // ); - // st.equal( - // stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'comma' }), - // 'a=,&b=&c=c,d%', - // ); - // st.equal( - // stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'repeat' }), - // 'a=,&b=&c=c,d%', - // ); - expect(stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'indices' })).toBe( - 'a=,&b=&c=c,d%', - ); - expect(stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'brackets' })).toBe( - 'a=,&b=&c=c,d%', - ); - - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - expect( - stringify( - { a: ',', b: '', c: 'c,d%' }, - { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }, - ), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - expect( - stringify( - { a: ',', b: '', c: 'c,d%' }, - { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }, - ), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - expect( - stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - expect( - stringify( - { a: ',', b: '', c: 'c,d%' }, - { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }, - ), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - // st.equal( - // stringify( - // { a: ',', b: '', c: 'c,d%' }, - // { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }, - // ), - // 'a=%2C&b=&c=c%2Cd%25', - // ); - expect( - stringify( - { a: ',', b: '', c: 'c,d%' }, - { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }, - ), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - expect( - stringify( - { a: ',', b: '', c: 'c,d%' }, - { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }, - ), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - expect( - stringify( - { a: ',', b: '', c: 'c,d%' }, - { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }, - ), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - expect( - stringify( - { a: ',', b: '', c: 'c,d%' }, - { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }, - ), - ).toBe('a=%2C&b=&c=c%2Cd%25'); - }); - - test('stringifies a nested array value with dots notation', function () { - // st.equal( - // stringify( - // { a: { b: ['c', 'd'] } }, - // { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'a.b[0]=c&a.b[1]=d', - // 'indices: stringifies with dots + indices', - // ); - // st.equal( - // stringify( - // { a: { b: ['c', 'd'] } }, - // { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'a.b[]=c&a.b[]=d', - // 'brackets: stringifies with dots + brackets', - // ); - // st.equal( - // stringify( - // { a: { b: ['c', 'd'] } }, - // { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' }, - // ), - // 'a.b=c,d', - // 'comma: stringifies with dots + comma', - // ); - // st.equal( - // stringify({ a: { b: ['c', 'd'] } }, { allowDots: true, encodeValuesOnly: true }), - // 'a.b[0]=c&a.b[1]=d', - // 'default: stringifies with dots + indices', - // ); - expect( - stringify( - { a: { b: ['c', 'd'] } }, - { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' }, - ), - ).toBe('a.b[0]=c&a.b[1]=d'); - expect( - stringify( - { a: { b: ['c', 'd'] } }, - { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' }, - ), - ).toBe('a.b[]=c&a.b[]=d'); - expect( - stringify({ a: { b: ['c', 'd'] } }, { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' }), - ).toBe('a.b=c,d'); - expect(stringify({ a: { b: ['c', 'd'] } }, { allowDots: true, encodeValuesOnly: true })).toBe( - 'a.b[0]=c&a.b[1]=d', - ); - }); - - test('stringifies an object inside an array', function () { - // st.equal( - // stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), - // 'a[0][b]=c', - // 'indices => indices', - // ); - // st.equal( - // stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), - // 'a[b]=c', - // 'repeat => repeat', - // ); - // st.equal( - // stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), - // 'a[][b]=c', - // 'brackets => brackets', - // ); - // st.equal( - // stringify({ a: [{ b: 'c' }] }, { encodeValuesOnly: true }), - // 'a[0][b]=c', - // 'default => indices', - // ); - expect(stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices', encodeValuesOnly: true })).toBe( - 'a[0][b]=c', - ); - expect(stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'repeat', encodeValuesOnly: true })).toBe('a[b]=c'); - expect(stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets', encodeValuesOnly: true })).toBe( - 'a[][b]=c', - ); - expect(stringify({ a: [{ b: 'c' }] }, { encodeValuesOnly: true })).toBe('a[0][b]=c'); - - // st.equal( - // stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), - // 'a[0][b][c][0]=1', - // 'indices => indices', - // ); - // st.equal( - // stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), - // 'a[b][c]=1', - // 'repeat => repeat', - // ); - // st.equal( - // stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), - // 'a[][b][c][]=1', - // 'brackets => brackets', - // ); - // st.equal( - // stringify({ a: [{ b: { c: [1] } }] }, { encodeValuesOnly: true }), - // 'a[0][b][c][0]=1', - // 'default => indices', - // ); - expect(stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices', encodeValuesOnly: true })).toBe( - 'a[0][b][c][0]=1', - ); - expect(stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'repeat', encodeValuesOnly: true })).toBe( - 'a[b][c]=1', - ); - expect(stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets', encodeValuesOnly: true })).toBe( - 'a[][b][c][]=1', - ); - expect(stringify({ a: [{ b: { c: [1] } }] }, { encodeValuesOnly: true })).toBe('a[0][b][c][0]=1'); - }); - - test('stringifies an array with mixed objects and primitives', function () { - // st.equal( - // stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - // 'a[0][b]=1&a[1]=2&a[2]=3', - // 'indices => indices', - // ); - // st.equal( - // stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - // 'a[][b]=1&a[]=2&a[]=3', - // 'brackets => brackets', - // ); - // st.equal( - // stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), - // '???', - // 'brackets => brackets', - // { skip: 'TODO: figure out what this should do' }, - // ); - // st.equal( - // stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true }), - // 'a[0][b]=1&a[1]=2&a[2]=3', - // 'default => indices', - // ); - expect(stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' })).toBe( - 'a[0][b]=1&a[1]=2&a[2]=3', - ); - expect(stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe( - 'a[][b]=1&a[]=2&a[]=3', - ); - // !Skipped: Figure out what this should do - // expect( - // stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), - // ).toBe('???'); - expect(stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true })).toBe('a[0][b]=1&a[1]=2&a[2]=3'); - }); - - test('stringifies an object inside an array with dots notation', function () { - // st.equal( - // stringify({ a: [{ b: 'c' }] }, { allowDots: true, encode: false, arrayFormat: 'indices' }), - // 'a[0].b=c', - // 'indices => indices', - // ); - // st.equal( - // stringify( - // { a: [{ b: 'c' }] }, - // { allowDots: true, encode: false, arrayFormat: 'brackets' }, - // ), - // 'a[].b=c', - // 'brackets => brackets', - // ); - // st.equal( - // stringify({ a: [{ b: 'c' }] }, { allowDots: true, encode: false }), - // 'a[0].b=c', - // 'default => indices', - // ); - expect(stringify({ a: [{ b: 'c' }] }, { allowDots: true, encode: false, arrayFormat: 'indices' })).toBe( - 'a[0].b=c', - ); - expect(stringify({ a: [{ b: 'c' }] }, { allowDots: true, encode: false, arrayFormat: 'brackets' })).toBe( - 'a[].b=c', - ); - expect(stringify({ a: [{ b: 'c' }] }, { allowDots: true, encode: false })).toBe('a[0].b=c'); - - // st.equal( - // stringify( - // { a: [{ b: { c: [1] } }] }, - // { allowDots: true, encode: false, arrayFormat: 'indices' }, - // ), - // 'a[0].b.c[0]=1', - // 'indices => indices', - // ); - // st.equal( - // stringify( - // { a: [{ b: { c: [1] } }] }, - // { allowDots: true, encode: false, arrayFormat: 'brackets' }, - // ), - // 'a[].b.c[]=1', - // 'brackets => brackets', - // ); - // st.equal( - // stringify({ a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false }), - // 'a[0].b.c[0]=1', - // 'default => indices', - // ); - expect( - stringify({ a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false, arrayFormat: 'indices' }), - ).toBe('a[0].b.c[0]=1'); - expect( - stringify({ a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false, arrayFormat: 'brackets' }), - ).toBe('a[].b.c[]=1'); - expect(stringify({ a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false })).toBe('a[0].b.c[0]=1'); - }); - - test('does not omit object keys when indices = false', function () { - // st.equal(stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); - expect(stringify({ a: [{ b: 'c' }] }, { indices: false })).toBe('a%5Bb%5D=c'); - }); - - test('uses indices notation for arrays when indices=true', function () { - // st.equal(stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); - expect(stringify({ a: ['b', 'c'] }, { indices: true })).toBe('a%5B0%5D=b&a%5B1%5D=c'); - }); - - test('uses indices notation for arrays when no arrayFormat is specified', function () { - // st.equal(stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); - expect(stringify({ a: ['b', 'c'] })).toBe('a%5B0%5D=b&a%5B1%5D=c'); - }); - - test('uses indices notation for arrays when arrayFormat=indices', function () { - // st.equal(stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); - expect(stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })).toBe('a%5B0%5D=b&a%5B1%5D=c'); - }); - - test('uses repeat notation for arrays when arrayFormat=repeat', function () { - // st.equal(stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); - expect(stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })).toBe('a=b&a=c'); - }); - - test('uses brackets notation for arrays when arrayFormat=brackets', function () { - // st.equal(stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); - expect(stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })).toBe('a%5B%5D=b&a%5B%5D=c'); - }); - - test('stringifies a complicated object', function () { - // st.equal(stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); - expect(stringify({ a: { b: 'c', d: 'e' } })).toBe('a%5Bb%5D=c&a%5Bd%5D=e'); - }); - - test('stringifies an empty value', function () { - // st.equal(stringify({ a: '' }), 'a='); - // st.equal(stringify({ a: null }, { strictNullHandling: true }), 'a'); - expect(stringify({ a: '' })).toBe('a='); - expect(stringify({ a: null }, { strictNullHandling: true })).toBe('a'); - - // st.equal(stringify({ a: '', b: '' }), 'a=&b='); - // st.equal(stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); - expect(stringify({ a: '', b: '' })).toBe('a=&b='); - expect(stringify({ a: null, b: '' }, { strictNullHandling: true })).toBe('a&b='); - - // st.equal(stringify({ a: { b: '' } }), 'a%5Bb%5D='); - // st.equal(stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); - // st.equal(stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); - expect(stringify({ a: { b: '' } })).toBe('a%5Bb%5D='); - expect(stringify({ a: { b: null } }, { strictNullHandling: true })).toBe('a%5Bb%5D'); - expect(stringify({ a: { b: null } }, { strictNullHandling: false })).toBe('a%5Bb%5D='); - }); - - test('stringifies an empty array in different arrayFormat', function () { - // st.equal(stringify({ a: [], b: [null], c: 'c' }, { encode: false }), 'b[0]=&c=c'); - expect(stringify({ a: [], b: [null], c: 'c' }, { encode: false })).toBe('b[0]=&c=c'); - // arrayFormat default - // st.equal( - // stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' }), - // 'b[0]=&c=c', - // ); - // st.equal( - // stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), - // 'b[]=&c=c', - // ); - // st.equal( - // stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), - // 'b=&c=c', - // ); - // st.equal( - // stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), - // 'b=&c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'comma', commaRoundTrip: true }, - // ), - // 'b[]=&c=c', - // ); - expect(stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' })).toBe( - 'b[0]=&c=c', - ); - expect(stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' })).toBe( - 'b[]=&c=c', - ); - expect(stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' })).toBe('b=&c=c'); - expect(stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' })).toBe('b=&c=c'); - expect( - stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), - ).toBe('b[]=&c=c'); - - // with strictNullHandling - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'indices', strictNullHandling: true }, - // ), - // 'b[0]&c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'brackets', strictNullHandling: true }, - // ), - // 'b[]&c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'repeat', strictNullHandling: true }, - // ), - // 'b&c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'comma', strictNullHandling: true }, - // ), - // 'b&c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }, - // ), - // 'b[]&c=c', - // ); - - expect( - stringify( - { a: [], b: [null], c: 'c' }, - { encode: false, arrayFormat: 'indices', strictNullHandling: true }, - ), - ).toBe('b[0]&c=c'); - expect( - stringify( - { a: [], b: [null], c: 'c' }, - { encode: false, arrayFormat: 'brackets', strictNullHandling: true }, - ), - ).toBe('b[]&c=c'); - expect( - stringify( - { a: [], b: [null], c: 'c' }, - { encode: false, arrayFormat: 'repeat', strictNullHandling: true }, - ), - ).toBe('b&c=c'); - expect( - stringify( - { a: [], b: [null], c: 'c' }, - { encode: false, arrayFormat: 'comma', strictNullHandling: true }, - ), - ).toBe('b&c=c'); - expect( - stringify( - { a: [], b: [null], c: 'c' }, - { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }, - ), - ).toBe('b[]&c=c'); - - // with skipNulls - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'indices', skipNulls: true }, - // ), - // 'c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'brackets', skipNulls: true }, - // ), - // 'c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'repeat', skipNulls: true }, - // ), - // 'c=c', - // ); - // st.equal( - // stringify( - // { a: [], b: [null], c: 'c' }, - // { encode: false, arrayFormat: 'comma', skipNulls: true }, - // ), - // 'c=c', - // ); - expect( - stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), - ).toBe('c=c'); - expect( - stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), - ).toBe('c=c'); - expect( - stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', skipNulls: true }), - ).toBe('c=c'); - expect( - stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', skipNulls: true }), - ).toBe('c=c'); - }); - - test('stringifies a null object', function () { - var obj = Object.create(null); - obj.a = 'b'; - // st.equal(stringify(obj), 'a=b'); - expect(stringify(obj)).toBe('a=b'); - }); - - test('returns an empty string for invalid input', function () { - // st.equal(stringify(undefined), ''); - // st.equal(stringify(false), ''); - // st.equal(stringify(null), ''); - // st.equal(stringify(''), ''); - expect(stringify(undefined)).toBe(''); - expect(stringify(false)).toBe(''); - expect(stringify(null)).toBe(''); - expect(stringify('')).toBe(''); - }); - - test('stringifies an object with a null object as a child', function () { - var obj = { a: Object.create(null) }; - - obj.a.b = 'c'; - // st.equal(stringify(obj), 'a%5Bb%5D=c'); - expect(stringify(obj)).toBe('a%5Bb%5D=c'); - }); - - test('drops keys with a value of undefined', function () { - // st.equal(stringify({ a: undefined }), ''); - expect(stringify({ a: undefined })).toBe(''); - - // st.equal( - // stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), - // 'a%5Bc%5D', - // ); - // st.equal( - // stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), - // 'a%5Bc%5D=', - // ); - // st.equal(stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); - expect(stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).toBe('a%5Bc%5D'); - expect(stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).toBe('a%5Bc%5D='); - expect(stringify({ a: { b: undefined, c: '' } })).toBe('a%5Bc%5D='); - }); - - test('url encodes values', function () { - // st.equal(stringify({ a: 'b c' }), 'a=b%20c'); - expect(stringify({ a: 'b c' })).toBe('a=b%20c'); - }); - - test('stringifies a date', function () { - var now = new Date(); - var str = 'a=' + encodeURIComponent(now.toISOString()); - // st.equal(stringify({ a: now }), str); - expect(stringify({ a: now })).toBe(str); - }); - - test('stringifies the weird object from qs', function () { - // st.equal( - // stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), - // 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F', - // ); - expect(stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).toBe( - 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F', - ); - }); - - // TODO: Investigate how to to intercept in vitest - // TODO(rob) - test('skips properties that are part of the object prototype', function () { - // st.intercept(Object.prototype, 'crash', { value: 'test' }); - // @ts-expect-error - Object.prototype.crash = 'test'; - - // st.equal(stringify({ a: 'b' }), 'a=b'); - // st.equal(stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); - expect(stringify({ a: 'b' })).toBe('a=b'); - expect(stringify({ a: { b: 'c' } })).toBe('a%5Bb%5D=c'); - }); - - test('stringifies boolean values', function () { - // st.equal(stringify({ a: true }), 'a=true'); - // st.equal(stringify({ a: { b: true } }), 'a%5Bb%5D=true'); - // st.equal(stringify({ b: false }), 'b=false'); - // st.equal(stringify({ b: { c: false } }), 'b%5Bc%5D=false'); - expect(stringify({ a: true })).toBe('a=true'); - expect(stringify({ a: { b: true } })).toBe('a%5Bb%5D=true'); - expect(stringify({ b: false })).toBe('b=false'); - expect(stringify({ b: { c: false } })).toBe('b%5Bc%5D=false'); - }); - - test('stringifies buffer values', function () { - // st.equal(stringify({ a: Buffer.from('test') }), 'a=test'); - // st.equal(stringify({ a: { b: Buffer.from('test') } }), 'a%5Bb%5D=test'); - }); - - test('stringifies an object using an alternative delimiter', function () { - // st.equal(stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); - expect(stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).toBe('a=b;c=d'); - }); - - // We dont target environments which dont even have Buffer - // test('does not blow up when Buffer global is missing', function () { - // var restore = mockProperty(global, 'Buffer', { delete: true }); - - // var result = stringify({ a: 'b', c: 'd' }); - - // restore(); - - // st.equal(result, 'a=b&c=d'); - // st.end(); - // }); - - test('does not crash when parsing circular references', function () { - var a: any = {}; - a.b = a; - - // st['throws']( - // function () { - // stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); - // }, - // /RangeError: Cyclic object value/, - // 'cyclic values throw', - // ); - expect(() => { - stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); - }).toThrow('Cyclic object value'); - - var circular: any = { - a: 'value', - }; - circular.a = circular; - // st['throws']( - // function () { - // stringify(circular); - // }, - // /RangeError: Cyclic object value/, - // 'cyclic values throw', - // ); - expect(() => { - stringify(circular); - }).toThrow('Cyclic object value'); - - var arr = ['a']; - // st.doesNotThrow(function () { - // stringify({ x: arr, y: arr }); - // }, 'non-cyclic values do not throw'); - expect(() => { - stringify({ x: arr, y: arr }); - }).not.toThrow(); - }); - - test('non-circular duplicated references can still work', function () { - var hourOfDay = { - function: 'hour_of_day', - }; - - var p1 = { - function: 'gte', - arguments: [hourOfDay, 0], - }; - var p2 = { - function: 'lte', - arguments: [hourOfDay, 23], - }; - - // st.equal( - // stringify( - // { filters: { $and: [p1, p2] } }, - // { encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23', - // ); - // st.equal( - // stringify( - // { filters: { $and: [p1, p2] } }, - // { encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'filters[$and][][function]=gte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=0&filters[$and][][function]=lte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=23', - // ); - // st.equal( - // stringify( - // { filters: { $and: [p1, p2] } }, - // { encodeValuesOnly: true, arrayFormat: 'repeat' }, - // ), - // 'filters[$and][function]=gte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=0&filters[$and][function]=lte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=23', - // ); - expect( - stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - ).toBe( - 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23', - ); - expect( - stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - ).toBe( - 'filters[$and][][function]=gte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=0&filters[$and][][function]=lte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=23', - ); - expect( - stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), - ).toBe( - 'filters[$and][function]=gte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=0&filters[$and][function]=lte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=23', - ); - }); - - test('selects properties when filter=array', function () { - // st.equal(stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); - // st.equal(stringify({ a: 1 }, { filter: [] }), ''); - expect(stringify({ a: 'b' }, { filter: ['a'] })).toBe('a=b'); - expect(stringify({ a: 1 }, { filter: [] })).toBe(''); - - // st.equal( - // stringify( - // { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, - // { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' }, - // ), - // 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', - // 'indices => indices', - // ); - // st.equal( - // stringify( - // { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, - // { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' }, - // ), - // 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', - // 'brackets => brackets', - // ); - // st.equal( - // stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] }), - // 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', - // 'default => indices', - // ); - expect(stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).toBe( - 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', - ); - expect( - stringify( - { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, - { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' }, - ), - ).toBe('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); - expect( - stringify( - { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, - { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' }, - ), - ).toBe('a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3'); - }); - - test('supports custom representations when filter=function', function () { - var calls = 0; - var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; - var filterFunc: StringifyOptions['filter'] = function (prefix, value) { - calls += 1; - if (calls === 1) { - // st.equal(prefix, '', 'prefix is empty'); - // st.equal(value, obj); - expect(prefix).toBe(''); - expect(value).toBe(obj); - } else if (prefix === 'c') { - return void 0; - } else if (value instanceof Date) { - // st.equal(prefix, 'e[f]'); - expect(prefix).toBe('e[f]'); - return value.getTime(); - } - return value; - }; - - // st.equal(stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); - // st.equal(calls, 5); - expect(stringify(obj, { filter: filterFunc })).toBe('a=b&e%5Bf%5D=1257894000000'); - expect(calls).toBe(5); - }); - - test('can disable uri encoding', function () { - // st.equal(stringify({ a: 'b' }, { encode: false }), 'a=b'); - // st.equal(stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); - // st.equal( - // stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), - // 'a=b&c', - // ); - expect(stringify({ a: 'b' }, { encode: false })).toBe('a=b'); - expect(stringify({ a: { b: 'c' } }, { encode: false })).toBe('a[b]=c'); - expect(stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false })).toBe('a=b&c'); - }); - - test('can sort the keys', function () { - // @ts-expect-error - var sort: NonNullable = function (a: string, b: string) { - return a.localeCompare(b); - }; - // st.equal(stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); - // st.equal( - // stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), - // 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a', - // ); - expect(stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort })).toBe('a=c&b=f&z=y'); - expect(stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort })).toBe( - 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a', - ); - }); - - test('can sort the keys at depth 3 or more too', function () { - // @ts-expect-error - var sort: NonNullable = function (a: string, b: string) { - return a.localeCompare(b); - }; - // st.equal( - // stringify( - // { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, - // { sort: sort, encode: false }, - // ), - // 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb', - // ); - // st.equal( - // stringify( - // { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, - // { sort: null, encode: false }, - // ), - // 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b', - // ); - expect( - stringify( - { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, - { sort: sort, encode: false }, - ), - ).toBe('a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb'); - expect( - stringify( - { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, - { sort: null, encode: false }, - ), - ).toBe('a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b'); - }); - - test('can stringify with custom encoding', function () { - // st.equal( - // stringify( - // { 県: '大阪府', '': '' }, - // { - // encoder: function (str) { - // if (str.length === 0) { - // return ''; - // } - // var buf = iconv.encode(str, 'shiftjis'); - // var result = []; - // for (var i = 0; i < buf.length; ++i) { - // result.push(buf.readUInt8(i).toString(16)); - // } - // return '%' + result.join('%'); - // }, - // }, - // ), - // '%8c%a7=%91%e5%8d%e3%95%7b&=', - // ); - expect( - stringify( - { 県: '大阪府', '': '' }, - { - encoder: function (str) { - if (str.length === 0) { - return ''; - } - var buf = iconv.encode(str, 'shiftjis'); - var result = []; - for (var i = 0; i < buf.length; ++i) { - result.push(buf.readUInt8(i).toString(16)); - } - return '%' + result.join('%'); - }, - }, - ), - ).toBe('%8c%a7=%91%e5%8d%e3%95%7b&='); - }); - - test('receives the default encoder as a second argument', function () { - // stringify( - // { a: 1, b: new Date(), c: true, d: [1] }, - // { - // encoder: function (str) { - // st.match(typeof str, /^(?:string|number|boolean)$/); - // return ''; - // }, - // }, - // ); - - stringify( - { a: 1, b: new Date(), c: true, d: [1] }, - { - encoder: function (str) { - // st.match(typeof str, /^(?:string|number|boolean)$/); - assert.match(typeof str, /^(?:string|number|boolean)$/); - return ''; - }, - }, - ); - }); - - test('receives the default encoder as a second argument', function () { - // stringify( - // { a: 1 }, - // { - // encoder: function (str, defaultEncoder) { - // st.equal(defaultEncoder, utils.encode); - // }, - // }, - // ); - - stringify( - { a: 1 }, - { - // @ts-ignore - encoder: function (_str, defaultEncoder) { - expect(defaultEncoder).toBe(encode); - }, - }, - ); - }); - - test('throws error with wrong encoder', function () { - // st['throws'](function () { - // stringify({}, { encoder: 'string' }); - // }, new TypeError('Encoder has to be a function.')); - // st.end(); - expect(() => { - // @ts-expect-error - stringify({}, { encoder: 'string' }); - }).toThrow(TypeError); - }); - - (typeof Buffer === 'undefined' ? test.skip : test)( - 'can use custom encoder for a buffer object', - function () { - // st.equal( - // stringify( - // { a: Buffer.from([1]) }, - // { - // encoder: function (buffer) { - // if (typeof buffer === 'string') { - // return buffer; - // } - // return String.fromCharCode(buffer.readUInt8(0) + 97); - // }, - // }, - // ), - // 'a=b', - // ); - expect( - stringify( - { a: Buffer.from([1]) }, - { - encoder: function (buffer) { - if (typeof buffer === 'string') { - return buffer; - } - return String.fromCharCode(buffer.readUInt8(0) + 97); - }, - }, - ), - ).toBe('a=b'); - - // st.equal( - // stringify( - // { a: Buffer.from('a b') }, - // { - // encoder: function (buffer) { - // return buffer; - // }, - // }, - // ), - // 'a=a b', - // ); - expect( - stringify( - { a: Buffer.from('a b') }, - { - encoder: function (buffer) { - return buffer; - }, - }, - ), - ).toBe('a=a b'); - }, - ); - - test('serializeDate option', function () { - var date = new Date(); - // st.equal( - // stringify({ a: date }), - // 'a=' + date.toISOString().replace(/:/g, '%3A'), - // 'default is toISOString', - // ); - expect(stringify({ a: date })).toBe('a=' + date.toISOString().replace(/:/g, '%3A')); - - var mutatedDate = new Date(); - mutatedDate.toISOString = function () { - throw new SyntaxError(); - }; - // st['throws'](function () { - // mutatedDate.toISOString(); - // }, SyntaxError); - expect(() => { - mutatedDate.toISOString(); - }).toThrow(SyntaxError); - // st.equal( - // stringify({ a: mutatedDate }), - // 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), - // 'toISOString works even when method is not locally present', - // ); - expect(stringify({ a: mutatedDate })).toBe( - 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), - ); - - var specificDate = new Date(6); - // st.equal( - // stringify( - // { a: specificDate }, - // { - // serializeDate: function (d) { - // return d.getTime() * 7; - // }, - // }, - // ), - // 'a=42', - // 'custom serializeDate function called', - // ); - expect( - stringify( - { a: specificDate }, - { - // @ts-ignore - serializeDate: function (d) { - return d.getTime() * 7; - }, - }, - ), - ).toBe('a=42'); - - // st.equal( - // stringify( - // { a: [date] }, - // { - // serializeDate: function (d) { - // return d.getTime(); - // }, - // arrayFormat: 'comma', - // }, - // ), - // 'a=' + date.getTime(), - // 'works with arrayFormat comma', - // ); - // st.equal( - // stringify( - // { a: [date] }, - // { - // serializeDate: function (d) { - // return d.getTime(); - // }, - // arrayFormat: 'comma', - // commaRoundTrip: true, - // }, - // ), - // 'a%5B%5D=' + date.getTime(), - // 'works with arrayFormat comma', - // ); - expect( - stringify( - { a: [date] }, - { - // @ts-expect-error - serializeDate: function (d) { - return d.getTime(); - }, - arrayFormat: 'comma', - }, - ), - ).toBe('a=' + date.getTime()); - expect( - stringify( - { a: [date] }, - { - // @ts-expect-error - serializeDate: function (d) { - return d.getTime(); - }, - arrayFormat: 'comma', - commaRoundTrip: true, - }, - ), - ).toBe('a%5B%5D=' + date.getTime()); - }); - - test('RFC 1738 serialization', function () { - // st.equal(stringify({ a: 'b c' }, { format: formats.RFC1738 }), 'a=b+c'); - // st.equal(stringify({ 'a b': 'c d' }, { format: formats.RFC1738 }), 'a+b=c+d'); - // st.equal( - // stringify({ 'a b': Buffer.from('a b') }, { format: formats.RFC1738 }), - // 'a+b=a+b', - // ); - expect(stringify({ a: 'b c' }, { format: 'RFC1738' })).toBe('a=b+c'); - expect(stringify({ 'a b': 'c d' }, { format: 'RFC1738' })).toBe('a+b=c+d'); - expect(stringify({ 'a b': Buffer.from('a b') }, { format: 'RFC1738' })).toBe('a+b=a+b'); - - // st.equal(stringify({ 'foo(ref)': 'bar' }, { format: formats.RFC1738 }), 'foo(ref)=bar'); - expect(stringify({ 'foo(ref)': 'bar' }, { format: 'RFC1738' })).toBe('foo(ref)=bar'); - }); - - test('RFC 3986 spaces serialization', function () { - // st.equal(stringify({ a: 'b c' }, { format: formats.RFC3986 }), 'a=b%20c'); - // st.equal(stringify({ 'a b': 'c d' }, { format: formats.RFC3986 }), 'a%20b=c%20d'); - // st.equal( - // stringify({ 'a b': Buffer.from('a b') }, { format: formats.RFC3986 }), - // 'a%20b=a%20b', - // ); - expect(stringify({ a: 'b c' }, { format: 'RFC3986' })).toBe('a=b%20c'); - expect(stringify({ 'a b': 'c d' }, { format: 'RFC3986' })).toBe('a%20b=c%20d'); - expect(stringify({ 'a b': Buffer.from('a b') }, { format: 'RFC3986' })).toBe('a%20b=a%20b'); - }); - - test('Backward compatibility to RFC 3986', function () { - // st.equal(stringify({ a: 'b c' }), 'a=b%20c'); - // st.equal(stringify({ 'a b': Buffer.from('a b') }), 'a%20b=a%20b'); - expect(stringify({ a: 'b c' })).toBe('a=b%20c'); - expect(stringify({ 'a b': Buffer.from('a b') })).toBe('a%20b=a%20b'); - }); - - test('Edge cases and unknown formats', function () { - ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { - // st['throws'](function () { - // stringify({ a: 'b c' }, { format: format }); - // }, new TypeError('Unknown format option provided.')); - expect(() => { - // @ts-expect-error - stringify({ a: 'b c' }, { format: format }); - }).toThrow(TypeError); - }); - }); - - test('encodeValuesOnly', function () { - // st.equal( - // stringify( - // { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, - // { encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h', - // 'encodeValuesOnly + indices', - // ); - // st.equal( - // stringify( - // { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, - // { encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'a=b&c[]=d&c[]=e%3Df&f[][]=g&f[][]=h', - // 'encodeValuesOnly + brackets', - // ); - // st.equal( - // stringify( - // { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, - // { encodeValuesOnly: true, arrayFormat: 'repeat' }, - // ), - // 'a=b&c=d&c=e%3Df&f=g&f=h', - // 'encodeValuesOnly + repeat', - // ); - expect( - stringify( - { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, - { encodeValuesOnly: true, arrayFormat: 'indices' }, - ), - ).toBe('a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); - expect( - stringify( - { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, - { encodeValuesOnly: true, arrayFormat: 'brackets' }, - ), - ).toBe('a=b&c[]=d&c[]=e%3Df&f[][]=g&f[][]=h'); - expect( - stringify( - { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, - { encodeValuesOnly: true, arrayFormat: 'repeat' }, - ), - ).toBe('a=b&c=d&c=e%3Df&f=g&f=h'); - - // st.equal( - // stringify({ a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, { arrayFormat: 'indices' }), - // 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h', - // 'no encodeValuesOnly + indices', - // ); - // st.equal( - // stringify({ a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, { arrayFormat: 'brackets' }), - // 'a=b&c%5B%5D=d&c%5B%5D=e&f%5B%5D%5B%5D=g&f%5B%5D%5B%5D=h', - // 'no encodeValuesOnly + brackets', - // ); - // st.equal( - // stringify({ a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, { arrayFormat: 'repeat' }), - // 'a=b&c=d&c=e&f=g&f=h', - // 'no encodeValuesOnly + repeat', - // ); - expect(stringify({ a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, { arrayFormat: 'indices' })).toBe( - 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h', - ); - expect(stringify({ a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, { arrayFormat: 'brackets' })).toBe( - 'a=b&c%5B%5D=d&c%5B%5D=e&f%5B%5D%5B%5D=g&f%5B%5D%5B%5D=h', - ); - expect(stringify({ a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, { arrayFormat: 'repeat' })).toBe( - 'a=b&c=d&c=e&f=g&f=h', - ); - }); - - test('encodeValuesOnly - strictNullHandling', function () { - // st.equal( - // stringify({ a: { b: null } }, { encodeValuesOnly: true, strictNullHandling: true }), - // 'a[b]', - // ); - expect(stringify({ a: { b: null } }, { encodeValuesOnly: true, strictNullHandling: true })).toBe('a[b]'); - }); - - test('throws if an invalid charset is specified', function () { - // st['throws'](function () { - // stringify({ a: 'b' }, { charset: 'foobar' }); - // }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); - expect(() => { - // @ts-expect-error - stringify({ a: 'b' }, { charset: 'foobar' }); - }).toThrow(TypeError); - }); - - test('respects a charset of iso-8859-1', function () { - // st.equal(stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6'); - expect(stringify({ æ: 'æ' }, { charset: 'iso-8859-1' })).toBe('%E6=%E6'); - }); - - test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function () { - // st.equal(stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); - expect(stringify({ a: '☺' }, { charset: 'iso-8859-1' })).toBe('a=%26%239786%3B'); - }); - - test('respects an explicit charset of utf-8 (the default)', function () { - // st.equal(stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6'); - expect(stringify({ a: 'æ' }, { charset: 'utf-8' })).toBe('a=%C3%A6'); - }); - - test('`charsetSentinel` option', function () { - // st.equal( - // stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), - // 'utf8=%E2%9C%93&a=%C3%A6', - // 'adds the right sentinel when instructed to and the charset is utf-8', - // ); - expect(stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' })).toBe( - 'utf8=%E2%9C%93&a=%C3%A6', - ); - - // st.equal( - // stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), - // 'utf8=%26%2310003%3B&a=%E6', - // 'adds the right sentinel when instructed to and the charset is iso-8859-1', - // ); - expect(stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' })).toBe( - 'utf8=%26%2310003%3B&a=%E6', - ); - }); - - test('does not mutate the options argument', function () { - var options = {}; - stringify({}, options); - // st.deepEqual(options, {}); - expect(options).toEqual({}); - }); - - test('strictNullHandling works with custom filter', function () { - // @ts-expect-error - var filter = function (_prefix, value) { - return value; - }; - - var options = { strictNullHandling: true, filter: filter }; - // st.equal(stringify({ key: null }, options), 'key'); - expect(stringify({ key: null }, options)).toBe('key'); - }); - - test('strictNullHandling works with null serializeDate', function () { - var serializeDate = function () { - return null; - }; - var options = { strictNullHandling: true, serializeDate: serializeDate }; - var date = new Date(); - // st.equal(stringify({ key: date }, options), 'key'); - // @ts-expect-error - expect(stringify({ key: date }, options)).toBe('key'); - }); - - test('allows for encoding keys and values differently', function () { - // @ts-expect-error - var encoder = function (str, defaultEncoder, charset, type) { - if (type === 'key') { - return defaultEncoder(str, defaultEncoder, charset, type).toLowerCase(); - } - if (type === 'value') { - return defaultEncoder(str, defaultEncoder, charset, type).toUpperCase(); - } - throw 'this should never happen! type: ' + type; - }; - - // st.deepEqual(stringify({ KeY: 'vAlUe' }, { encoder: encoder }), 'key=VALUE'); - expect(stringify({ KeY: 'vAlUe' }, { encoder: encoder })).toBe('key=VALUE'); - }); - - test('objects inside arrays', function () { - var obj = { a: { b: { c: 'd', e: 'f' } } }; - var withArray = { a: { b: [{ c: 'd', e: 'f' }] } }; - - // st.equal( - // stringify(obj, { encode: false }), - // 'a[b][c]=d&a[b][e]=f', - // 'no array, no arrayFormat', - // ); - // st.equal( - // stringify(obj, { encode: false, arrayFormat: 'brackets' }), - // 'a[b][c]=d&a[b][e]=f', - // 'no array, bracket', - // ); - // st.equal( - // stringify(obj, { encode: false, arrayFormat: 'indices' }), - // 'a[b][c]=d&a[b][e]=f', - // 'no array, indices', - // ); - // st.equal( - // stringify(obj, { encode: false, arrayFormat: 'repeat' }), - // 'a[b][c]=d&a[b][e]=f', - // 'no array, repeat', - // ); - // st.equal( - // stringify(obj, { encode: false, arrayFormat: 'comma' }), - // 'a[b][c]=d&a[b][e]=f', - // 'no array, comma', - // ); - expect(stringify(obj, { encode: false })).toBe('a[b][c]=d&a[b][e]=f'); - expect(stringify(obj, { encode: false, arrayFormat: 'brackets' })).toBe('a[b][c]=d&a[b][e]=f'); - expect(stringify(obj, { encode: false, arrayFormat: 'indices' })).toBe('a[b][c]=d&a[b][e]=f'); - expect(stringify(obj, { encode: false, arrayFormat: 'repeat' })).toBe('a[b][c]=d&a[b][e]=f'); - expect(stringify(obj, { encode: false, arrayFormat: 'comma' })).toBe('a[b][c]=d&a[b][e]=f'); - - // st.equal( - // stringify(withArray, { encode: false }), - // 'a[b][0][c]=d&a[b][0][e]=f', - // 'array, no arrayFormat', - // ); - // st.equal( - // stringify(withArray, { encode: false, arrayFormat: 'brackets' }), - // 'a[b][][c]=d&a[b][][e]=f', - // 'array, bracket', - // ); - // st.equal( - // stringify(withArray, { encode: false, arrayFormat: 'indices' }), - // 'a[b][0][c]=d&a[b][0][e]=f', - // 'array, indices', - // ); - // st.equal( - // stringify(withArray, { encode: false, arrayFormat: 'repeat' }), - // 'a[b][c]=d&a[b][e]=f', - // 'array, repeat', - // ); - // st.equal( - // stringify(withArray, { encode: false, arrayFormat: 'comma' }), - // '???', - // 'array, comma', - // { skip: 'TODO: figure out what this should do' }, - // ); - expect(stringify(withArray, { encode: false })).toBe('a[b][0][c]=d&a[b][0][e]=f'); - expect(stringify(withArray, { encode: false, arrayFormat: 'brackets' })).toBe('a[b][][c]=d&a[b][][e]=f'); - expect(stringify(withArray, { encode: false, arrayFormat: 'indices' })).toBe('a[b][0][c]=d&a[b][0][e]=f'); - expect(stringify(withArray, { encode: false, arrayFormat: 'repeat' })).toBe('a[b][c]=d&a[b][e]=f'); - // !TODo: Figure out what this should do - // expect(stringify(withArray, { encode: false, arrayFormat: 'comma' })).toBe( - // 'a[b][c]=d&a[b][e]=f', - // ); - }); - - test('stringifies sparse arrays', function () { - // st.equal( - // stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - // 'a[1]=2&a[4]=1', - // ); - // st.equal( - // stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - // 'a[]=2&a[]=1', - // ); - // st.equal( - // stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), - // 'a=2&a=1', - // ); - expect(stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'indices' })).toBe( - 'a[1]=2&a[4]=1', - ); - expect(stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' })).toBe( - 'a[]=2&a[]=1', - ); - expect(stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'repeat' })).toBe( - 'a=2&a=1', - ); - - // st.equal( - // stringify( - // { a: [, { b: [, , { c: '1' }] }] }, - // { encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'a[1][b][2][c]=1', - // ); - // st.equal( - // stringify( - // { a: [, { b: [, , { c: '1' }] }] }, - // { encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'a[][b][][c]=1', - // ); - // st.equal( - // stringify( - // { a: [, { b: [, , { c: '1' }] }] }, - // { encodeValuesOnly: true, arrayFormat: 'repeat' }, - // ), - // 'a[b][c]=1', - // ); - expect( - stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - ).toBe('a[1][b][2][c]=1'); - expect( - stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - ).toBe('a[][b][][c]=1'); - expect( - stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), - ).toBe('a[b][c]=1'); - - // st.equal( - // stringify( - // { a: [, [, , [, , , { c: '1' }]]] }, - // { encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'a[1][2][3][c]=1', - // ); - // st.equal( - // stringify( - // { a: [, [, , [, , , { c: '1' }]]] }, - // { encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'a[][][][c]=1', - // ); - // st.equal( - // stringify( - // { a: [, [, , [, , , { c: '1' }]]] }, - // { encodeValuesOnly: true, arrayFormat: 'repeat' }, - // ), - // 'a[c]=1', - // ); - expect( - stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - ).toBe('a[1][2][3][c]=1'); - expect( - stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - ).toBe('a[][][][c]=1'); - expect( - stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), - ).toBe('a[c]=1'); - - // st.equal( - // stringify( - // { a: [, [, , [, , , { c: [, '1'] }]]] }, - // { encodeValuesOnly: true, arrayFormat: 'indices' }, - // ), - // 'a[1][2][3][c][1]=1', - // ); - // st.equal( - // stringify( - // { a: [, [, , [, , , { c: [, '1'] }]]] }, - // { encodeValuesOnly: true, arrayFormat: 'brackets' }, - // ), - // 'a[][][][c][]=1', - // ); - // st.equal( - // stringify( - // { a: [, [, , [, , , { c: [, '1'] }]]] }, - // { encodeValuesOnly: true, arrayFormat: 'repeat' }, - // ), - // 'a[c]=1', - // ); - expect( - stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), - ).toBe('a[1][2][3][c][1]=1'); - expect( - stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), - ).toBe('a[][][][c][]=1'); - expect( - stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), - ).toBe('a[c]=1'); - }); - - test('encodes a very long string', function () { - var chars = []; - var expected = []; - for (var i = 0; i < 5e3; i++) { - chars.push(' ' + i); - - expected.push('%20' + i); - } - - var obj = { - foo: chars.join(''), - }; - - // st.equal( - // stringify(obj, { arrayFormat: 'bracket', charset: 'utf-8' }), - // 'foo=' + expected.join(''), - // ); - // @ts-expect-error - expect(stringify(obj, { arrayFormat: 'bracket', charset: 'utf-8' })).toBe('foo=' + expected.join('')); - }); -}); - -describe('stringifies empty keys', function () { - empty_test_cases.forEach(function (testCase) { - test('stringifies an object with empty string key with ' + testCase.input, function () { - // st.deepEqual( - // stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'indices' }), - // testCase.stringifyOutput.indices, - // 'test case: ' + testCase.input + ', indices', - // ); - // st.deepEqual( - // stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'brackets' }), - // testCase.stringifyOutput.brackets, - // 'test case: ' + testCase.input + ', brackets', - // ); - // st.deepEqual( - // stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'repeat' }), - // testCase.stringifyOutput.repeat, - // 'test case: ' + testCase.input + ', repeat', - // ); - expect(stringify(testCase.with_empty_keys, { encode: false, arrayFormat: 'indices' })).toBe( - testCase.stringify_output.indices, - ); - expect(stringify(testCase.with_empty_keys, { encode: false, arrayFormat: 'brackets' })).toBe( - testCase.stringify_output.brackets, - ); - expect(stringify(testCase.with_empty_keys, { encode: false, arrayFormat: 'repeat' })).toBe( - testCase.stringify_output.repeat, - ); - }); - }); - - test('edge case with object/arrays', function () { - // st.deepEqual(stringify({ '': { '': [2, 3] } }, { encode: false }), '[][0]=2&[][1]=3'); - // st.deepEqual( - // stringify({ '': { '': [2, 3], a: 2 } }, { encode: false }), - // '[][0]=2&[][1]=3&[a]=2', - // ); - // st.deepEqual( - // stringify({ '': { '': [2, 3] } }, { encode: false, arrayFormat: 'indices' }), - // '[][0]=2&[][1]=3', - // ); - // st.deepEqual( - // stringify({ '': { '': [2, 3], a: 2 } }, { encode: false, arrayFormat: 'indices' }), - // '[][0]=2&[][1]=3&[a]=2', - // ); - expect(stringify({ '': { '': [2, 3] } }, { encode: false })).toBe('[][0]=2&[][1]=3'); - expect(stringify({ '': { '': [2, 3], a: 2 } }, { encode: false })).toBe('[][0]=2&[][1]=3&[a]=2'); - expect(stringify({ '': { '': [2, 3] } }, { encode: false, arrayFormat: 'indices' })).toBe( - '[][0]=2&[][1]=3', - ); - expect(stringify({ '': { '': [2, 3], a: 2 } }, { encode: false, arrayFormat: 'indices' })).toBe( - '[][0]=2&[][1]=3&[a]=2', - ); - }); -}); diff --git a/tests/qs/utils.test.ts b/tests/qs/utils.test.ts deleted file mode 100644 index e08fdcb..0000000 --- a/tests/qs/utils.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { combine, merge, is_buffer, assign_single_source } from 'omnistack/internal/qs/utils'; - -describe('merge()', function () { - // t.deepEqual(merge(null, true), [null, true], 'merges true into null'); - expect(merge(null, true)).toEqual([null, true]); - - // t.deepEqual(merge(null, [42]), [null, 42], 'merges null into an array'); - expect(merge(null, [42])).toEqual([null, 42]); - - // t.deepEqual( - // merge({ a: 'b' }, { a: 'c' }), - // { a: ['b', 'c'] }, - // 'merges two objects with the same key', - // ); - expect(merge({ a: 'b' }, { a: 'c' })).toEqual({ a: ['b', 'c'] }); - - var oneMerged = merge({ foo: 'bar' }, { foo: { first: '123' } }); - // t.deepEqual( - // oneMerged, - // { foo: ['bar', { first: '123' }] }, - // 'merges a standalone and an object into an array', - // ); - expect(oneMerged).toEqual({ foo: ['bar', { first: '123' }] }); - - var twoMerged = merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); - // t.deepEqual( - // twoMerged, - // { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, - // 'merges a standalone and two objects into an array', - // ); - expect(twoMerged).toEqual({ foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }); - - var sandwiched = merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); - // t.deepEqual( - // sandwiched, - // { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, - // 'merges an object sandwiched by two standalones into an array', - // ); - expect(sandwiched).toEqual({ foo: ['bar', { first: '123', second: '456' }, 'baz'] }); - - var nestedArrays = merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); - // t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); - expect(nestedArrays).toEqual({ foo: ['baz', 'bar', 'xyzzy'] }); - - var noOptionsNonObjectSource = merge({ foo: 'baz' }, 'bar'); - // t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); - expect(noOptionsNonObjectSource).toEqual({ foo: 'baz', bar: true }); - - (typeof Object.defineProperty !== 'function' ? test.skip : test)( - 'avoids invoking array setters unnecessarily', - function () { - var setCount = 0; - var getCount = 0; - var observed: any[] = []; - Object.defineProperty(observed, 0, { - get: function () { - getCount += 1; - return { bar: 'baz' }; - }, - set: function () { - setCount += 1; - }, - }); - merge(observed, [null]); - // st.equal(setCount, 0); - // st.equal(getCount, 1); - expect(setCount).toEqual(0); - expect(getCount).toEqual(1); - observed[0] = observed[0]; // eslint-disable-line no-self-assign - // st.equal(setCount, 1); - // st.equal(getCount, 2); - expect(setCount).toEqual(1); - expect(getCount).toEqual(2); - }, - ); -}); - -test('assign()', function () { - var target = { a: 1, b: 2 }; - var source = { b: 3, c: 4 }; - var result = assign_single_source(target, source); - - expect(result).toEqual(target); - expect(target).toEqual({ a: 1, b: 3, c: 4 }); - expect(source).toEqual({ b: 3, c: 4 }); -}); - -describe('combine()', function () { - test('both arrays', function () { - var a = [1]; - var b = [2]; - var combined = combine(a, b); - - // st.deepEqual(a, [1], 'a is not mutated'); - // st.deepEqual(b, [2], 'b is not mutated'); - // st.notEqual(a, combined, 'a !== combined'); - // st.notEqual(b, combined, 'b !== combined'); - // st.deepEqual(combined, [1, 2], 'combined is a + b'); - expect(a).toEqual([1]); - expect(b).toEqual([2]); - expect(combined).toEqual([1, 2]); - expect(a).not.toEqual(combined); - expect(b).not.toEqual(combined); - }); - - test('one array, one non-array', function () { - var aN = 1; - var a = [aN]; - var bN = 2; - var b = [bN]; - - var combinedAnB = combine(aN, b); - // st.deepEqual(b, [bN], 'b is not mutated'); - // st.notEqual(aN, combinedAnB, 'aN + b !== aN'); - // st.notEqual(a, combinedAnB, 'aN + b !== a'); - // st.notEqual(bN, combinedAnB, 'aN + b !== bN'); - // st.notEqual(b, combinedAnB, 'aN + b !== b'); - // st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); - expect(b).toEqual([bN]); - expect(combinedAnB).not.toEqual(aN); - expect(combinedAnB).not.toEqual(a); - expect(combinedAnB).not.toEqual(bN); - expect(combinedAnB).not.toEqual(b); - expect(combinedAnB).toEqual([1, 2]); - - var combinedABn = combine(a, bN); - // st.deepEqual(a, [aN], 'a is not mutated'); - // st.notEqual(aN, combinedABn, 'a + bN !== aN'); - // st.notEqual(a, combinedABn, 'a + bN !== a'); - // st.notEqual(bN, combinedABn, 'a + bN !== bN'); - // st.notEqual(b, combinedABn, 'a + bN !== b'); - // st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); - expect(a).toEqual([aN]); - expect(combinedABn).not.toEqual(aN); - expect(combinedABn).not.toEqual(a); - expect(combinedABn).not.toEqual(bN); - expect(combinedABn).not.toEqual(b); - expect(combinedABn).toEqual([1, 2]); - }); - - test('neither is an array', function () { - var combined = combine(1, 2); - // st.notEqual(1, combined, '1 + 2 !== 1'); - // st.notEqual(2, combined, '1 + 2 !== 2'); - // st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); - expect(combined).not.toEqual(1); - expect(combined).not.toEqual(2); - expect(combined).toEqual([1, 2]); - }); -}); - -test('is_buffer()', function () { - for (const x of [null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g]) { - // t.equal(is_buffer(x), false, inspect(x) + ' is not a buffer'); - expect(is_buffer(x)).toEqual(false); - } - - var fakeBuffer = { constructor: Buffer }; - // t.equal(is_buffer(fakeBuffer), false, 'fake buffer is not a buffer'); - expect(is_buffer(fakeBuffer)).toEqual(false); - - var saferBuffer = Buffer.from('abc'); - // t.equal(is_buffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); - expect(is_buffer(saferBuffer)).toEqual(true); - - var buffer = Buffer.from('abc'); - // t.equal(is_buffer(buffer), true, 'real Buffer instance is a buffer'); - expect(is_buffer(buffer)).toEqual(true); -}); diff --git a/tsconfig.deno.json b/tsconfig.deno.json index 2ee93f3..849e070 100644 --- a/tsconfig.deno.json +++ b/tsconfig.deno.json @@ -1,19 +1,14 @@ { "extends": "./tsconfig.json", - "include": ["deno"], + "include": ["dist-deno"], "exclude": [], "compilerOptions": { - "rootDir": "./deno", + "rootDir": "./dist-deno", "lib": ["es2020", "DOM"], - "paths": { - "omnistack-node/_shims/auto/*": ["deno/_shims/auto/*-deno"], - "omnistack-node/*": ["deno/*"], - "omnistack-node": ["deno/index.ts"], - }, "noEmit": true, "declaration": true, "declarationMap": true, - "outDir": "deno", + "outDir": "dist-deno", "pretty": true, "sourceMap": true } diff --git a/tsconfig.json b/tsconfig.json index d1ba325..a0be9b9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,7 @@ "paths": { "omnistack-node/_shims/auto/*": ["src/_shims/auto/*-node"], "omnistack-node/*": ["src/*"], - "omnistack-node": ["src/index.ts"], + "omnistack-node": ["src/index.ts"] }, "noEmit": true, @@ -32,6 +32,7 @@ "noUncheckedIndexedAccess": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, + "isolatedModules": false, "skipLibCheck": true } diff --git a/yarn.lock b/yarn.lock index 10ebd6d..bfd47d8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -322,9 +322,9 @@ eslint-visitor-keys "^3.3.0" "@eslint-community/regexpp@^4.5.1": - version "4.9.0" - resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.9.0.tgz#7ccb5f58703fa61ffdcbf39e2c604a109e781162" - integrity sha512-zJmuCWj2VLBt4c25CfBIbMZLGLyhkvs7LznyVX5HfpzeocThgIj5XQK4L+g3U36mMcx8bPMhGyPpwCATamC4jQ== + version "4.11.1" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.11.1.tgz#a547badfc719eb3e5f4b556325e542fbe9d7a18f" + integrity sha512-m4DVN9ZqskZoLU5GlWZadwDnYo3vAEydiUayB9widCl9ffWx2IvPnp6n3on5rJmziJSw9Bv+Z3ChDVdMwXCY8Q== "@eslint-community/regexpp@^4.6.1": version "4.6.2" @@ -759,16 +759,6 @@ dependencies: "@swc/counter" "^0.1.3" -"@ts-morph/common@~0.20.0": - version "0.20.0" - resolved "https://registry.yarnpkg.com/@ts-morph/common/-/common-0.20.0.tgz#3f161996b085ba4519731e4d24c35f6cba5b80af" - integrity sha512-7uKjByfbPpwuzkstL3L5MQyuXPSKdoNG93Fmi2JoDcTf3pEP731JdRFAduRVkOs8oqxPsXKA+ScrWkdQ8t/I+Q== - dependencies: - fast-glob "^3.2.12" - minimatch "^7.4.3" - mkdirp "^2.1.6" - path-browserify "^1.0.1" - "@tsconfig/node10@^1.0.7": version "1.0.8" resolved "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.8.tgz#c1e4e80d6f964fbecb3359c43bd48b40f7cadad9" @@ -857,9 +847,9 @@ pretty-format "^29.0.0" "@types/json-schema@^7.0.12": - version "7.0.13" - resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.13.tgz#02c24f4363176d2d18fc8b70b9f3c54aba178a85" - integrity sha512-RbSSoHliUbnXj3ny0CNFOoxrIDV6SUGyStHsvDqosw6CkdPV8TtWGlfecuK4ToyMEAql6pzNxgCFKanovUzlgQ== + version "7.0.15" + resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" + integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== "@types/node-fetch@^2.6.4": version "2.6.4" @@ -882,9 +872,9 @@ integrity sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA== "@types/semver@^7.5.0": - version "7.5.3" - resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.5.3.tgz#9a726e116beb26c24f1ccd6850201e1246122e04" - integrity sha512-OxepLK9EuNEIPxWNME+C6WwbRAOOI2o2BaQEGzz5Lu2e4Z5eDnEo+/aVEDMIXywoJitJ7xWd641wrGLZdtwRyw== + version "7.5.8" + resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.5.8.tgz#8268a8c57a3e4abd25c165ecd36237db7948a55e" + integrity sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ== "@types/stack-utils@^2.0.0": version "2.0.3" @@ -904,15 +894,15 @@ "@types/yargs-parser" "*" "@typescript-eslint/eslint-plugin@^6.7.0": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.7.3.tgz#d98046e9f7102d49a93d944d413c6055c47fafd7" - integrity sha512-vntq452UHNltxsaaN+L9WyuMch8bMd9CqJ3zhzTPXXidwbf5mqqKCVXEuvRZUqLJSTLeWE65lQwyXsRGnXkCTA== + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.21.0.tgz#30830c1ca81fd5f3c2714e524c4303e0194f9cd3" + integrity sha512-oy9+hTPCUFpngkEZUSzbf9MxI65wbKFoQYsgPdILTfbUldp5ovUuphZVe4i30emU9M/kP+T64Di0mxl7dSw3MA== dependencies: "@eslint-community/regexpp" "^4.5.1" - "@typescript-eslint/scope-manager" "6.7.3" - "@typescript-eslint/type-utils" "6.7.3" - "@typescript-eslint/utils" "6.7.3" - "@typescript-eslint/visitor-keys" "6.7.3" + "@typescript-eslint/scope-manager" "6.21.0" + "@typescript-eslint/type-utils" "6.21.0" + "@typescript-eslint/utils" "6.21.0" + "@typescript-eslint/visitor-keys" "6.21.0" debug "^4.3.4" graphemer "^1.4.0" ignore "^5.2.4" @@ -921,71 +911,72 @@ ts-api-utils "^1.0.1" "@typescript-eslint/parser@^6.7.0": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-6.7.3.tgz#aaf40092a32877439e5957e18f2d6a91c82cc2fd" - integrity sha512-TlutE+iep2o7R8Lf+yoer3zU6/0EAUc8QIBB3GYBc1KGz4c4TRm83xwXUZVPlZ6YCLss4r77jbu6j3sendJoiQ== - dependencies: - "@typescript-eslint/scope-manager" "6.7.3" - "@typescript-eslint/types" "6.7.3" - "@typescript-eslint/typescript-estree" "6.7.3" - "@typescript-eslint/visitor-keys" "6.7.3" + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-6.21.0.tgz#af8fcf66feee2edc86bc5d1cf45e33b0630bf35b" + integrity sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ== + dependencies: + "@typescript-eslint/scope-manager" "6.21.0" + "@typescript-eslint/types" "6.21.0" + "@typescript-eslint/typescript-estree" "6.21.0" + "@typescript-eslint/visitor-keys" "6.21.0" debug "^4.3.4" -"@typescript-eslint/scope-manager@6.7.3": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-6.7.3.tgz#07e5709c9bdae3eaf216947433ef97b3b8b7d755" - integrity sha512-wOlo0QnEou9cHO2TdkJmzF7DFGvAKEnB82PuPNHpT8ZKKaZu6Bm63ugOTn9fXNJtvuDPanBc78lGUGGytJoVzQ== +"@typescript-eslint/scope-manager@6.21.0": + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-6.21.0.tgz#ea8a9bfc8f1504a6ac5d59a6df308d3a0630a2b1" + integrity sha512-OwLUIWZJry80O99zvqXVEioyniJMa+d2GrqpUTqi5/v5D5rOrppJVBPa0yKCblcigC0/aYAzxxqQ1B+DS2RYsg== dependencies: - "@typescript-eslint/types" "6.7.3" - "@typescript-eslint/visitor-keys" "6.7.3" + "@typescript-eslint/types" "6.21.0" + "@typescript-eslint/visitor-keys" "6.21.0" -"@typescript-eslint/type-utils@6.7.3": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-6.7.3.tgz#c2c165c135dda68a5e70074ade183f5ad68f3400" - integrity sha512-Fc68K0aTDrKIBvLnKTZ5Pf3MXK495YErrbHb1R6aTpfK5OdSFj0rVN7ib6Tx6ePrZ2gsjLqr0s98NG7l96KSQw== +"@typescript-eslint/type-utils@6.21.0": + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-6.21.0.tgz#6473281cfed4dacabe8004e8521cee0bd9d4c01e" + integrity sha512-rZQI7wHfao8qMX3Rd3xqeYSMCL3SoiSQLBATSiVKARdFGCYSRvmViieZjqc58jKgs8Y8i9YvVVhRbHSTA4VBag== dependencies: - "@typescript-eslint/typescript-estree" "6.7.3" - "@typescript-eslint/utils" "6.7.3" + "@typescript-eslint/typescript-estree" "6.21.0" + "@typescript-eslint/utils" "6.21.0" debug "^4.3.4" ts-api-utils "^1.0.1" -"@typescript-eslint/types@6.7.3": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-6.7.3.tgz#0402b5628a63f24f2dc9d4a678e9a92cc50ea3e9" - integrity sha512-4g+de6roB2NFcfkZb439tigpAMnvEIg3rIjWQ+EM7IBaYt/CdJt6em9BJ4h4UpdgaBWdmx2iWsafHTrqmgIPNw== +"@typescript-eslint/types@6.21.0": + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-6.21.0.tgz#205724c5123a8fef7ecd195075fa6e85bac3436d" + integrity sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg== -"@typescript-eslint/typescript-estree@6.7.3": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.7.3.tgz#ec5bb7ab4d3566818abaf0e4a8fa1958561b7279" - integrity sha512-YLQ3tJoS4VxLFYHTw21oe1/vIZPRqAO91z6Uv0Ss2BKm/Ag7/RVQBcXTGcXhgJMdA4U+HrKuY5gWlJlvoaKZ5g== +"@typescript-eslint/typescript-estree@6.21.0": + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.21.0.tgz#c47ae7901db3b8bddc3ecd73daff2d0895688c46" + integrity sha512-6npJTkZcO+y2/kr+z0hc4HwNfrrP4kNYh57ek7yCNlrBjWQ1Y0OS7jiZTkgumrvkX5HkEKXFZkkdFNkaW2wmUQ== dependencies: - "@typescript-eslint/types" "6.7.3" - "@typescript-eslint/visitor-keys" "6.7.3" + "@typescript-eslint/types" "6.21.0" + "@typescript-eslint/visitor-keys" "6.21.0" debug "^4.3.4" globby "^11.1.0" is-glob "^4.0.3" + minimatch "9.0.3" semver "^7.5.4" ts-api-utils "^1.0.1" -"@typescript-eslint/utils@6.7.3": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-6.7.3.tgz#96c655816c373135b07282d67407cb577f62e143" - integrity sha512-vzLkVder21GpWRrmSR9JxGZ5+ibIUSudXlW52qeKpzUEQhRSmyZiVDDj3crAth7+5tmN1ulvgKaCU2f/bPRCzg== +"@typescript-eslint/utils@6.21.0": + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-6.21.0.tgz#4714e7a6b39e773c1c8e97ec587f520840cd8134" + integrity sha512-NfWVaC8HP9T8cbKQxHcsJBY5YE1O33+jpMwN45qzWWaPDZgLIbo12toGMWnmhvCpd3sIxkpDw3Wv1B3dYrbDQQ== dependencies: "@eslint-community/eslint-utils" "^4.4.0" "@types/json-schema" "^7.0.12" "@types/semver" "^7.5.0" - "@typescript-eslint/scope-manager" "6.7.3" - "@typescript-eslint/types" "6.7.3" - "@typescript-eslint/typescript-estree" "6.7.3" + "@typescript-eslint/scope-manager" "6.21.0" + "@typescript-eslint/types" "6.21.0" + "@typescript-eslint/typescript-estree" "6.21.0" semver "^7.5.4" -"@typescript-eslint/visitor-keys@6.7.3": - version "6.7.3" - resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.7.3.tgz#83809631ca12909bd2083558d2f93f5747deebb2" - integrity sha512-HEVXkU9IB+nk9o63CeICMHxFWbHWr3E1mpilIQBe9+7L/lH97rleFLVtYsfnWB+JVMaiFnEaxvknvmIzX+CqVg== +"@typescript-eslint/visitor-keys@6.21.0": + version "6.21.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.21.0.tgz#87a99d077aa507e20e238b11d56cc26ade45fe47" + integrity sha512-JJtkDduxLi9bivAB+cYOVMtbkqdPOhZ+ZI5LC47MIRrDV4Yn2o+ZnW10Nkmr28xRpSpdJ6Sm42Hjf2+REYXm0A== dependencies: - "@typescript-eslint/types" "6.7.3" + "@typescript-eslint/types" "6.21.0" eslint-visitor-keys "^3.4.1" abort-controller@^3.0.0: @@ -1314,11 +1305,6 @@ co@^4.6.0: resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" integrity sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ== -code-block-writer@^12.0.0: - version "12.0.0" - resolved "https://registry.yarnpkg.com/code-block-writer/-/code-block-writer-12.0.0.tgz#4dd58946eb4234105aff7f0035977b2afdc2a770" - integrity sha512-q4dMFMlXtKR3XNBHyMHt/3pwYNA69EDk00lloMOaaUMKPUXBw6lpXtbu3MMVG6/uOihGnRDOlkyqsONEUj60+w== - collect-v8-coverage@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz#c0b29bcd33bcd0779a1344c2136051e6afd3d9e9" @@ -1392,13 +1378,20 @@ cross-spawn@^7.0.2, cross-spawn@^7.0.3: shebang-command "^2.0.0" which "^2.0.1" -debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4: +debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== dependencies: ms "2.1.2" +debug@^4.3.4: + version "4.3.7" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.7.tgz#87945b4151a011d76d95a198d7111c865c360a52" + integrity sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ== + dependencies: + ms "^2.1.3" + dedent@^1.0.0: version "1.5.1" resolved "https://registry.yarnpkg.com/dedent/-/dedent-1.5.1.tgz#4f3fc94c8b711e9bb2800d185cd6ad20f2a90aff" @@ -1546,12 +1539,7 @@ eslint-scope@^7.2.2: esrecurse "^4.3.0" estraverse "^5.2.0" -eslint-visitor-keys@^3.3.0, eslint-visitor-keys@^3.4.1: - version "3.4.2" - resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.2.tgz#8c2095440eca8c933bedcadf16fefa44dbe9ba5f" - integrity sha512-8drBzUEyZ2llkpCA67iYrgEssKDUu68V8ChqqOfFupIaG/LCVPUT+CoGJpT77zJprs4T/W7p07LP7zAIMuweVw== - -eslint-visitor-keys@^3.4.3: +eslint-visitor-keys@^3.3.0, eslint-visitor-keys@^3.4.1, eslint-visitor-keys@^3.4.3: version "3.4.3" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== @@ -1709,18 +1697,7 @@ fast-glob@^3.2.12: merge2 "^1.3.0" micromatch "^4.0.4" -fast-glob@^3.2.9: - version "3.3.1" - resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.1.tgz#784b4e897340f3dbbef17413b3f11acf03c874c4" - integrity sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg== - dependencies: - "@nodelib/fs.stat" "^2.0.2" - "@nodelib/fs.walk" "^1.2.3" - glob-parent "^5.1.2" - merge2 "^1.3.0" - micromatch "^4.0.4" - -fast-glob@^3.3.0: +fast-glob@^3.2.9, fast-glob@^3.3.0: version "3.3.2" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" integrity sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow== @@ -1742,9 +1719,9 @@ fast-levenshtein@^2.0.6: integrity sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw== fastq@^1.6.0: - version "1.15.0" - resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.15.0.tgz#d04d07c6a2a68fe4599fea8d2e103a937fae6b3a" - integrity sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw== + version "1.17.1" + resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.17.1.tgz#2a523f07a4e7b1e81a42b91b8bf2254107753b47" + integrity sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w== dependencies: reusify "^1.0.4" @@ -1967,9 +1944,9 @@ iconv-lite@^0.6.3: safer-buffer ">= 2.1.2 < 3.0.0" ignore@^5.2.0, ignore@^5.2.4: - version "5.2.4" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.4.tgz#a291c0c6178ff1b960befe47fcdec301674a6324" - integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== + version "5.3.2" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.3.2.tgz#3cd40e729f3643fd87cb04e50bf0eb722bc596f5" + integrity sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g== import-fresh@^3.2.1: version "3.3.0" @@ -2674,6 +2651,13 @@ mimic-fn@^4.0.0: resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-4.0.0.tgz#60a90550d5cb0b239cca65d893b1a53b29871ecc" integrity sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw== +minimatch@9.0.3: + version "9.0.3" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.3.tgz#a6e00c3de44c3a542bfaae70abfc22420a6da825" + integrity sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg== + dependencies: + brace-expansion "^2.0.1" + minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" @@ -2681,29 +2665,17 @@ minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: dependencies: brace-expansion "^1.1.7" -minimatch@^7.4.3: - version "7.4.6" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-7.4.6.tgz#845d6f254d8f4a5e4fd6baf44d5f10c8448365fb" - integrity sha512-sBz8G/YjVniEz6lKPNpKxXwazJe4c19fEfV2GDMX6AjFz+MX9uDWIZW8XreVhkFW3fkIdTv/gxWr/Kks5FFAVw== - dependencies: - brace-expansion "^2.0.1" - minimist@^1.2.6: version "1.2.6" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== -mkdirp@^2.1.6: - version "2.1.6" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-2.1.6.tgz#964fbcb12b2d8c5d6fbc62a963ac95a273e2cc19" - integrity sha512-+hEnITedc8LAtIP9u3HJDFIdcLV2vXP33sqLLIzkv1Db1zO/1OxbvYf0Y1OC/S/Qo5dxHXepofhmxL02PsKe+A== - ms@2.1.2: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -ms@^2.0.0: +ms@^2.0.0, ms@^2.1.3: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== @@ -2861,11 +2833,6 @@ parse-json@^5.2.0: json-parse-even-better-errors "^2.3.0" lines-and-columns "^1.1.6" -path-browserify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-browserify/-/path-browserify-1.0.1.tgz#d98454a9c3753d5790860f16f68867b9e46be1fd" - integrity sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g== - path-exists@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" @@ -3058,13 +3025,18 @@ semver@^6.3.0, semver@^6.3.1: resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.1.tgz#556d2ef8689146e46dcea4bfdd095f3434dffcb4" integrity sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA== -semver@^7.5.3, semver@^7.5.4: +semver@^7.5.3: version "7.5.4" resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== dependencies: lru-cache "^6.0.0" +semver@^7.5.4: + version "7.6.3" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.3.tgz#980f7b5550bc175fb4dc09403085627f9eb33143" + integrity sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A== + shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" @@ -3261,9 +3233,9 @@ tr46@~0.0.3: integrity sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o= ts-api-utils@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/ts-api-utils/-/ts-api-utils-1.0.3.tgz#f12c1c781d04427313dbac808f453f050e54a331" - integrity sha512-wNMeqtMz5NtwpT/UZGY5alT+VoKdSsOOP/kqHFcUW1P/VRhH2wJ48+DN2WwUliNbQ976ETwDL0Ifd2VVvgonvg== + version "1.3.0" + resolved "https://registry.yarnpkg.com/ts-api-utils/-/ts-api-utils-1.3.0.tgz#4b490e27129f1e8e686b45cc4ab63714dc60eea1" + integrity sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ== ts-jest@^29.1.0: version "29.1.1" @@ -3279,14 +3251,6 @@ ts-jest@^29.1.0: semver "^7.5.3" yargs-parser "^21.0.1" -ts-morph@^19.0.0: - version "19.0.0" - resolved "https://registry.yarnpkg.com/ts-morph/-/ts-morph-19.0.0.tgz#43e95fb0156c3fe3c77c814ac26b7d0be2f93169" - integrity sha512-D6qcpiJdn46tUqV45vr5UGM2dnIEuTGNxVhg0sk5NX11orcouwj6i1bMqZIz2mZTZB1Hcgy7C3oEVhAT+f6mbQ== - dependencies: - "@ts-morph/common" "~0.20.0" - code-block-writer "^12.0.0" - ts-node@^10.5.0: version "10.7.0" resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.7.0.tgz#35d503d0fab3e2baa672a0e94f4b40653c2463f5"