From 1625ecf85ab5a9550217acb1b6655c9ea5611fa3 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 23 Apr 2026 02:17:29 +0000 Subject: [PATCH 01/12] chore(internal): more robust bootstrap script --- scripts/bootstrap | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/bootstrap b/scripts/bootstrap index a8b69ff3..2e315f53 100755 --- a/scripts/bootstrap +++ b/scripts/bootstrap @@ -4,7 +4,7 @@ set -e cd "$(dirname "$0")/.." -if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ] && [ "$SKIP_BREW" != "1" ] && [ -t 0 ]; then +if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ] && [ "${SKIP_BREW:-}" != "1" ] && [ -t 0 ]; then brew bundle check >/dev/null 2>&1 || { echo -n "==> Install Homebrew dependencies? (y/N): " read -r response From ee1ac34270e0607eb8f6f6ea884b37a7c9167e3d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sun, 26 Apr 2026 02:03:17 +0000 Subject: [PATCH 02/12] chore(formatter): run prettier and eslint separately --- eslint.config.mjs | 3 - package.json | 1 - scripts/fast-format | 6 +- scripts/format | 3 +- scripts/lint | 3 + src/api-promise.ts | 2 +- src/client.ts | 927 +++++++----------- src/core/api-promise.ts | 9 +- src/core/error.ts | 46 +- src/error.ts | 2 +- src/index.ts | 16 +- src/internal/builtin-types.ts | 23 +- src/internal/detect-platform.ts | 6 +- src/internal/errors.ts | 14 +- src/internal/headers.ts | 4 +- src/internal/parse.ts | 12 +- src/internal/qs/utils.ts | 5 +- src/internal/request-options.ts | 6 +- src/internal/shim-types.ts | 4 +- src/internal/shims.ts | 4 +- src/internal/to-file.ts | 14 +- src/internal/types.ts | 50 +- src/internal/utils/log.ts | 37 +- src/internal/utils/query.ts | 2 +- src/internal/utils/uuid.ts | 8 +- src/resource.ts | 2 +- src/resources/audiences.ts | 24 +- src/resources/audit-events.ts | 7 +- src/resources/auth.ts | 2 +- src/resources/automations/automations.ts | 9 +- src/resources/automations/index.ts | 10 +- src/resources/automations/invoke.ts | 23 +- src/resources/brands.ts | 14 +- src/resources/bulk.ts | 19 +- src/resources/inbound.ts | 2 +- src/resources/index.ts | 198 +--- src/resources/journeys.ts | 13 +- src/resources/lists/index.ts | 20 +- src/resources/lists/lists.ts | 39 +- src/resources/lists/subscriptions.ts | 47 +- src/resources/messages.ts | 42 +- src/resources/notifications/checks.ts | 25 +- src/resources/notifications/index.ts | 43 +- src/resources/notifications/notifications.ts | 95 +- src/resources/profiles/index.ts | 20 +- src/resources/profiles/lists.ts | 14 +- src/resources/profiles/profiles.ts | 36 +- src/resources/providers/catalog.ts | 10 +- src/resources/providers/index.ts | 12 +- src/resources/providers/providers.ts | 14 +- src/resources/requests.ts | 5 +- src/resources/routing-strategies.ts | 29 +- src/resources/send.ts | 26 +- src/resources/shared.ts | 47 +- src/resources/tenants/index.ts | 30 +- src/resources/tenants/preferences/index.ts | 4 +- src/resources/tenants/preferences/items.ts | 20 +- .../tenants/preferences/preferences.ts | 2 +- src/resources/tenants/templates/index.ts | 11 +- src/resources/tenants/templates/templates.ts | 42 +- src/resources/tenants/templates/versions.ts | 17 +- src/resources/tenants/tenants.ts | 33 +- src/resources/translations.ts | 14 +- src/resources/users/index.ts | 33 +- src/resources/users/preferences.ts | 30 +- src/resources/users/tenants.ts | 40 +- src/resources/users/tokens.ts | 38 +- src/resources/users/users.ts | 37 +- src/uploads.ts | 2 +- src/version.ts | 2 +- tests/api-resources/audiences.test.ts | 17 +- tests/api-resources/audit-events.test.ts | 11 +- tests/api-resources/auth.test.ts | 17 +- .../automations/automations.test.ts | 14 +- .../api-resources/automations/invoke.test.ts | 67 +- tests/api-resources/brands.test.ts | 189 ++-- tests/api-resources/bulk.test.ts | 129 ++- tests/api-resources/inbound.test.ts | 43 +- tests/api-resources/journeys.test.ts | 11 +- tests/api-resources/lists/lists.test.ts | 43 +- .../api-resources/lists/subscriptions.test.ts | 127 +-- tests/api-resources/messages.test.ts | 50 +- .../notifications/checks.test.ts | 35 +- .../notifications/notifications.test.ts | 167 ++-- tests/api-resources/profiles/lists.test.ts | 49 +- tests/api-resources/profiles/profiles.test.ts | 33 +- tests/api-resources/providers/catalog.test.ts | 22 +- .../api-resources/providers/providers.test.ts | 31 +- tests/api-resources/requests.test.ts | 5 +- .../api-resources/routing-strategies.test.ts | 177 ++-- tests/api-resources/send.test.ts | 193 ++-- .../tenants/preferences/items.test.ts | 20 +- .../tenants/templates/templates.test.ts | 119 +-- .../tenants/templates/versions.test.ts | 15 +- tests/api-resources/tenants/tenants.test.ts | 60 +- tests/api-resources/translations.test.ts | 5 +- tests/api-resources/users/preferences.test.ts | 42 +- tests/api-resources/users/tenants.test.ts | 41 +- tests/api-resources/users/tokens.test.ts | 68 +- tests/index.test.ts | 498 +++++----- tests/qs/utils.test.ts | 2 +- tests/stringifyQuery.test.ts | 32 +- yarn.lock | 32 - 103 files changed, 1707 insertions(+), 3066 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index 7850bf49..07b28b78 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,7 +1,6 @@ // @ts-check import tseslint from 'typescript-eslint'; import unusedImports from 'eslint-plugin-unused-imports'; -import prettier from 'eslint-plugin-prettier'; export default tseslint.config( { @@ -14,11 +13,9 @@ export default tseslint.config( plugins: { '@typescript-eslint': tseslint.plugin, 'unused-imports': unusedImports, - prettier, }, rules: { 'no-unused-vars': 'off', - 'prettier/prettier': 'error', 'unused-imports/no-unused-imports': 'error', 'no-restricted-imports': [ 'error', diff --git a/package.json b/package.json index 8aeaadf7..7d86550e 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,6 @@ "@typescript-eslint/eslint-plugin": "8.31.1", "@typescript-eslint/parser": "8.31.1", "eslint": "^9.39.1", - "eslint-plugin-prettier": "^5.4.1", "eslint-plugin-unused-imports": "^4.1.4", "iconv-lite": "^0.6.3", "jest": "^29.4.0", diff --git a/scripts/fast-format b/scripts/fast-format index 53721ac0..e1723136 100755 --- a/scripts/fast-format +++ b/scripts/fast-format @@ -31,10 +31,8 @@ if ! [ -z "$ESLINT_FILES" ]; then fi echo "==> Running prettier --write" -# format things eslint didn't -PRETTIER_FILES="$(grep '\.\(js\|json\)$' "$FILE_LIST" || true)" +PRETTIER_FILES="$(grep '\.\([mc]?tsx?\|[mc]?jsx?\|json\)$' "$FILE_LIST" || true)" if ! [ -z "$PRETTIER_FILES" ]; then echo "$PRETTIER_FILES" | xargs ./node_modules/.bin/prettier \ - --write --cache --cache-strategy metadata --no-error-on-unmatched-pattern \ - '!**/dist' '!**/*.ts' '!**/*.mts' '!**/*.cts' '!**/*.js' '!**/*.mjs' '!**/*.cjs' + --write --cache --cache-strategy metadata --no-error-on-unmatched-pattern fi diff --git a/scripts/format b/scripts/format index 7a756401..b1b2c17a 100755 --- a/scripts/format +++ b/scripts/format @@ -8,5 +8,4 @@ echo "==> Running eslint --fix" ./node_modules/.bin/eslint --fix . echo "==> Running prettier --write" -# format things eslint didn't -./node_modules/.bin/prettier --write --cache --cache-strategy metadata . '!**/dist' '!**/*.ts' '!**/*.mts' '!**/*.cts' '!**/*.js' '!**/*.mjs' '!**/*.cjs' +./node_modules/.bin/prettier --write --cache --cache-strategy metadata . diff --git a/scripts/lint b/scripts/lint index 3ffb78a6..1f532548 100755 --- a/scripts/lint +++ b/scripts/lint @@ -4,6 +4,9 @@ set -e cd "$(dirname "$0")/.." +echo "==> Running prettier --check" +./node_modules/.bin/prettier --check . + echo "==> Running eslint" ./node_modules/.bin/eslint . diff --git a/src/api-promise.ts b/src/api-promise.ts index 8c775ee6..4e701286 100644 --- a/src/api-promise.ts +++ b/src/api-promise.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/api-promise instead */ -export * from './core/api-promise'; +export * from "./core/api-promise" \ No newline at end of file diff --git a/src/client.ts b/src/client.ts index a55a0521..fc4e49f1 100644 --- a/src/client.ts +++ b/src/client.ts @@ -17,194 +17,30 @@ import * as Errors from './core/error'; import * as Uploads from './core/uploads'; import * as API from './resources/index'; import { APIPromise } from './core/api-promise'; -import { - Audience, - AudienceListMembersParams, - AudienceListMembersResponse, - AudienceListParams, - AudienceListResponse, - AudienceUpdateParams, - AudienceUpdateResponse, - Audiences, -} from './resources/audiences'; -import { - AuditEvent, - AuditEventListParams, - AuditEventListResponse, - AuditEvents, -} from './resources/audit-events'; +import { Audience, AudienceListMembersParams, AudienceListMembersResponse, AudienceListParams, AudienceListResponse, AudienceUpdateParams, AudienceUpdateResponse, Audiences } from './resources/audiences'; +import { AuditEvent, AuditEventListParams, AuditEventListResponse, AuditEvents } from './resources/audit-events'; import { Auth, AuthIssueTokenParams, AuthIssueTokenResponse } from './resources/auth'; -import { - Brand, - BrandColors, - BrandCreateParams, - BrandListParams, - BrandListResponse, - BrandSettings, - BrandSettingsEmail, - BrandSettingsInApp, - BrandSnippet, - BrandSnippets, - BrandTemplate, - BrandUpdateParams, - Brands, - EmailFooter, - EmailHead, - EmailHeader, - Icons, - Logo, - WidgetBackground, -} from './resources/brands'; -import { - Bulk, - BulkAddUsersParams, - BulkCreateJobParams, - BulkCreateJobResponse, - BulkListUsersParams, - BulkListUsersResponse, - BulkRetrieveJobResponse, - InboundBulkMessage, - InboundBulkMessageUser, -} from './resources/bulk'; +import { Brand, BrandColors, BrandCreateParams, BrandListParams, BrandListResponse, BrandSettings, BrandSettingsEmail, BrandSettingsInApp, BrandSnippet, BrandSnippets, BrandTemplate, BrandUpdateParams, Brands, EmailFooter, EmailHead, EmailHeader, Icons, Logo, WidgetBackground } from './resources/brands'; +import { Bulk, BulkAddUsersParams, BulkCreateJobParams, BulkCreateJobResponse, BulkListUsersParams, BulkListUsersResponse, BulkRetrieveJobResponse, InboundBulkMessage, InboundBulkMessageUser } from './resources/bulk'; import { Inbound, InboundTrackEventParams, InboundTrackEventResponse } from './resources/inbound'; -import { - Journey, - JourneyInvokeParams, - JourneyListParams, - Journeys, - JourneysInvokeRequest, - JourneysInvokeResponse, - JourneysListResponse, -} from './resources/journeys'; -import { - MessageContentResponse, - MessageDetails, - MessageHistoryParams, - MessageHistoryResponse, - MessageListParams, - MessageListResponse, - MessageRetrieveResponse, - Messages, -} from './resources/messages'; +import { Journey, JourneyInvokeParams, JourneyListParams, Journeys, JourneysInvokeRequest, JourneysInvokeResponse, JourneysListResponse } from './resources/journeys'; +import { MessageContentResponse, MessageDetails, MessageHistoryParams, MessageHistoryResponse, MessageListParams, MessageListResponse, MessageRetrieveResponse, Messages } from './resources/messages'; import { Requests } from './resources/requests'; -import { - AssociatedNotificationListResponse, - RoutingStrategies, - RoutingStrategyCreateParams, - RoutingStrategyCreateRequest, - RoutingStrategyGetResponse, - RoutingStrategyListNotificationsParams, - RoutingStrategyListParams, - RoutingStrategyListResponse, - RoutingStrategyReplaceParams, - RoutingStrategyReplaceRequest, - RoutingStrategySummary, -} from './resources/routing-strategies'; +import { AssociatedNotificationListResponse, RoutingStrategies, RoutingStrategyCreateParams, RoutingStrategyCreateRequest, RoutingStrategyGetResponse, RoutingStrategyListNotificationsParams, RoutingStrategyListParams, RoutingStrategyListResponse, RoutingStrategyReplaceParams, RoutingStrategyReplaceRequest, RoutingStrategySummary } from './resources/routing-strategies'; import { Send, SendMessageParams, SendMessageResponse } from './resources/send'; -import { - TranslationRetrieveParams, - TranslationRetrieveResponse, - TranslationUpdateParams, - Translations, -} from './resources/translations'; -import { - AutomationInvokeResponse, - AutomationListParams, - AutomationTemplate, - AutomationTemplateListResponse, - Automations, -} from './resources/automations/automations'; -import { - ListListParams, - ListListResponse, - ListRestoreParams, - ListUpdateParams, - Lists, - PutSubscriptionsRecipient, - SubscriptionList, -} from './resources/lists/lists'; -import { - BaseCheck, - Check, - ElementWithChecksums, - NotificationContentGetResponse, - NotificationContentMutationResponse, - NotificationContentPutRequest, - NotificationCreateParams, - NotificationElementPutRequest, - NotificationGetContent, - NotificationListParams, - NotificationListResponse, - NotificationListVersionsParams, - NotificationLocalePutRequest, - NotificationPublishParams, - NotificationPutContentParams, - NotificationPutElementParams, - NotificationPutLocaleParams, - NotificationReplaceParams, - NotificationRetrieveContentParams, - NotificationRetrieveContentResponse, - NotificationRetrieveParams, - NotificationTemplateCreateRequest, - NotificationTemplatePayload, - NotificationTemplatePublishRequest, - NotificationTemplateResponse, - NotificationTemplateState, - NotificationTemplateSummary, - NotificationTemplateUpdateRequest, - NotificationTemplateVersionListResponse, - Notifications, - VersionNode, -} from './resources/notifications/notifications'; -import { - ProfileCreateParams, - ProfileCreateResponse, - ProfileReplaceParams, - ProfileReplaceResponse, - ProfileRetrieveResponse, - ProfileUpdateParams, - Profiles, - SubscribeToListsRequestItem, -} from './resources/profiles/profiles'; -import { - Provider, - ProviderCreateParams, - ProviderListParams, - ProviderListResponse, - ProviderUpdateParams, - Providers, - ProvidersCatalogEntry, -} from './resources/providers/providers'; -import { - BaseTemplateTenantAssociation, - DefaultPreferences, - PostTenantTemplatePublishRequest, - PostTenantTemplatePublishResponse, - PutTenantTemplateRequest, - PutTenantTemplateResponse, - SubscriptionTopicNew, - Tenant, - TenantAssociation, - TenantListParams, - TenantListResponse, - TenantListUsersParams, - TenantListUsersResponse, - TenantTemplateInput, - TenantUpdateParams, - Tenants, -} from './resources/tenants/tenants'; +import { TranslationRetrieveParams, TranslationRetrieveResponse, TranslationUpdateParams, Translations } from './resources/translations'; +import { AutomationInvokeResponse, AutomationListParams, AutomationTemplate, AutomationTemplateListResponse, Automations } from './resources/automations/automations'; +import { ListListParams, ListListResponse, ListRestoreParams, ListUpdateParams, Lists, PutSubscriptionsRecipient, SubscriptionList } from './resources/lists/lists'; +import { BaseCheck, Check, ElementWithChecksums, NotificationContentGetResponse, NotificationContentMutationResponse, NotificationContentPutRequest, NotificationCreateParams, NotificationElementPutRequest, NotificationGetContent, NotificationListParams, NotificationListResponse, NotificationListVersionsParams, NotificationLocalePutRequest, NotificationPublishParams, NotificationPutContentParams, NotificationPutElementParams, NotificationPutLocaleParams, NotificationReplaceParams, NotificationRetrieveContentParams, NotificationRetrieveContentResponse, NotificationRetrieveParams, NotificationTemplateCreateRequest, NotificationTemplatePayload, NotificationTemplatePublishRequest, NotificationTemplateResponse, NotificationTemplateState, NotificationTemplateSummary, NotificationTemplateUpdateRequest, NotificationTemplateVersionListResponse, Notifications, VersionNode } from './resources/notifications/notifications'; +import { ProfileCreateParams, ProfileCreateResponse, ProfileReplaceParams, ProfileReplaceResponse, ProfileRetrieveResponse, ProfileUpdateParams, Profiles, SubscribeToListsRequestItem } from './resources/profiles/profiles'; +import { Provider, ProviderCreateParams, ProviderListParams, ProviderListResponse, ProviderUpdateParams, Providers, ProvidersCatalogEntry } from './resources/providers/providers'; +import { BaseTemplateTenantAssociation, DefaultPreferences, PostTenantTemplatePublishRequest, PostTenantTemplatePublishResponse, PutTenantTemplateRequest, PutTenantTemplateResponse, SubscriptionTopicNew, Tenant, TenantAssociation, TenantListParams, TenantListResponse, TenantListUsersParams, TenantListUsersResponse, TenantTemplateInput, TenantUpdateParams, Tenants } from './resources/tenants/tenants'; import { Users } from './resources/users/users'; import { type Fetch } from './internal/builtin-types'; import { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers'; import { FinalRequestOptions, RequestOptions } from './internal/request-options'; import { readEnv } from './internal/utils/env'; -import { - type LogLevel, - type Logger, - formatRequestDetails, - loggerFor, - parseLogLevel, -} from './internal/utils/log'; +import { type LogLevel, type Logger, formatRequestDetails, loggerFor, parseLogLevel } from './internal/utils/log'; import { isEmptyObj } from './internal/utils/values'; export interface ClientOptions { @@ -283,7 +119,7 @@ export interface ClientOptions { } /** - * API Client for interfacing with the Courier API. + * API Client for interfacing with the Courier API. */ export class Courier { apiKey: string; @@ -319,7 +155,7 @@ export class Courier { }: ClientOptions = {}) { if (apiKey === undefined) { throw new Errors.CourierError( - "The COURIER_API_KEY environment variable is missing or empty; either provide it, or instantiate the Courier client with an apiKey option, like new Courier({ apiKey: 'My API Key' }).", + 'The COURIER_API_KEY environment variable is missing or empty; either provide it, or instantiate the Courier client with an apiKey option, like new Courier({ apiKey: \'My API Key\' }).' ); } @@ -335,10 +171,7 @@ export class Courier { const defaultLogLevel = 'warn'; // Set default logLevel early so that we can log a warning in parseLogLevel. this.logLevel = defaultLogLevel; - this.logLevel = - parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? - parseLogLevel(readEnv('COURIER_LOG'), "process.env['COURIER_LOG']", this) ?? - defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? parseLogLevel(readEnv('COURIER_LOG'), 'process.env[\'COURIER_LOG\']', this) ?? defaultLogLevel; this.fetchOptions = options.fetchOptions; this.maxRetries = options.maxRetries ?? 2; this.fetch = options.fetch ?? Shims.getDefaultFetch(); @@ -363,7 +196,7 @@ export class Courier { fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, - ...options, + ...options }); return client; } @@ -376,7 +209,7 @@ export class Courier { } protected defaultQuery(): Record | undefined { - return this._options.defaultQuery; + return this._options.defaultQuery } protected validateHeaders({ values, nulls }: NullableHeaders) { @@ -408,11 +241,7 @@ export class Courier { return Errors.APIError.generate(status, error, message, headers); } - buildURL( - path: string, - query: Record | null | undefined, - defaultBaseURL?: string | undefined, - ): string { + buildURL(path: string, query: Record | null | undefined, defaultBaseURL?: string | undefined): string { const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL; const url = isAbsoluteURL(path) ? @@ -500,9 +329,7 @@ export class Courier { await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining, - }); + const { req, url, timeout } = await this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); await this.prepareRequest(req, { url, options }); @@ -511,16 +338,7 @@ export class Courier { const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; const startTime = Date.now(); - loggerFor(this).debug( - `[${requestLogID}] sending request`, - formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers, - }), - ); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ retryOfRequestLogID, method: options.method, url, options, headers: req.headers })); if (options.signal?.aborted) { throw new Errors.APIUserAbortError(); @@ -539,45 +357,21 @@ export class Courier { // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = - isAbortError(response) || - /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')) if (retriesRemaining) { - loggerFor(this).info( - `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`, - ); - loggerFor(this).debug( - `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, - formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - }), - ); + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`) + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, message: response.message })); return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); } - loggerFor(this).info( - `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`, - ); - loggerFor(this).debug( - `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, - formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - }), - ); + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`) + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, message: response.message })); if (isTimeout) { throw new Errors.APIConnectionTimeoutError(); } throw new Errors.APIConnectionError({ cause: response }); } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${ - response.ok ? 'succeeded' : 'failed' - } with status ${response.status} in ${headersTime - startTime}ms`; + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; if (!response.ok) { const shouldRetry = await this.shouldRetry(response); @@ -586,60 +380,27 @@ export class Courier { // We don't need the body of this response. await Shims.CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - loggerFor(this).debug( - `[${requestLogID}] response error (${retryMessage})`, - formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - }), - ); - return this.retryRequest( - options, - retriesRemaining, - retryOfRequestLogID ?? requestLogID, - response.headers, - ); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`) + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, durationMs: headersTime - startTime })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); } const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`) const errText = await response.text().catch((err: any) => castToError(err).message); const errJSON = safeJSON(errText) as any; const errMessage = errJSON ? undefined : errText; - loggerFor(this).debug( - `[${requestLogID}] response error (${retryMessage})`, - formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime, - }), - ); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, message: errMessage, durationMs: Date.now() - startTime })); const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); throw err; } - loggerFor(this).info(responseInfo); - loggerFor(this).debug( - `[${requestLogID}] response start`, - formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - }), - ); + loggerFor(this).info(responseInfo) + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, durationMs: headersTime - startTime })); return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; } @@ -656,9 +417,7 @@ export class Courier { const timeout = setTimeout(abort, ms); - const isReadableBody = - ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) || - (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); + const isReadableBody = ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) || (typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body); const fetchOptions: RequestInit = { signal: controller.signal as any, @@ -673,6 +432,7 @@ export class Courier { } try { + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare return await this.fetch.call(undefined, url, fetchOptions); } finally { @@ -773,12 +533,11 @@ export class Courier { const req: FinalizedRequestInit = { method, headers: reqHeaders, - ...(options.signal && { signal: options.signal }), - ...((globalThis as any).ReadableStream && - body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }), + ...(options.signal && { signal: options.signal}), + ...((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream && { duplex: "half" }), ...(body && { body }), - ...((this.fetchOptions as any) ?? {}), - ...((options.fetchOptions as any) ?? {}), + ...(this.fetchOptions as any ?? {}), + ...(options.fetchOptions as any ?? {}), }; return { req, url, timeout: options.timeout }; @@ -803,17 +562,15 @@ export class Courier { const headers = buildHeaders([ idempotencyHeaders, - { - Accept: 'application/json', - 'User-Agent': this.getUserAgent(), - 'X-Stainless-Retry-Count': String(retryCount), - ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), - ...getPlatformHeaders(), - }, + {Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...getPlatformHeaders()}, await this.authHeaders(options), this._options.defaultHeaders, bodyHeaders, - options.headers, + options.headers ]); this.validateHeaders(headers); @@ -840,9 +597,11 @@ export class Courier { ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || - (typeof body === 'string' && + ( + typeof body === 'string' && // Preserve legacy string encoding behavior for now - headers.values.has('content-type')) || + headers.values.has('content-type') + ) || // `Blob` is superset of `File` ((globalThis as any).Blob && body instanceof (globalThis as any).Blob) || // `FormData` -> `multipart/form-data` @@ -873,7 +632,7 @@ export class Courier { } static Courier = this; - static DEFAULT_TIMEOUT = 60000; // 1 minute + static DEFAULT_TIMEOUT = 60000 // 1 minute static CourierError = Errors.CourierError; static APIError = Errors.APIError; @@ -933,291 +692,295 @@ Courier.Translations = Translations; Courier.Users = Users; export declare namespace Courier { - export type RequestOptions = Opts.RequestOptions; - - export { - Send as Send, - type SendMessageResponse as SendMessageResponse, - type SendMessageParams as SendMessageParams, - }; - - export { - Audiences as Audiences, - type Audience as Audience, - type AudienceUpdateResponse as AudienceUpdateResponse, - type AudienceListResponse as AudienceListResponse, - type AudienceListMembersResponse as AudienceListMembersResponse, - type AudienceUpdateParams as AudienceUpdateParams, - type AudienceListParams as AudienceListParams, - type AudienceListMembersParams as AudienceListMembersParams, - }; - - export { - Providers as Providers, - type Provider as Provider, - type ProvidersCatalogEntry as ProvidersCatalogEntry, - type ProviderListResponse as ProviderListResponse, - type ProviderCreateParams as ProviderCreateParams, - type ProviderUpdateParams as ProviderUpdateParams, - type ProviderListParams as ProviderListParams, - }; - - export { - AuditEvents as AuditEvents, - type AuditEvent as AuditEvent, - type AuditEventListResponse as AuditEventListResponse, - type AuditEventListParams as AuditEventListParams, - }; - - export { - Auth as Auth, - type AuthIssueTokenResponse as AuthIssueTokenResponse, - type AuthIssueTokenParams as AuthIssueTokenParams, - }; - - export { - Automations as Automations, - type AutomationInvokeResponse as AutomationInvokeResponse, - type AutomationTemplate as AutomationTemplate, - type AutomationTemplateListResponse as AutomationTemplateListResponse, - type AutomationListParams as AutomationListParams, - }; - - export { - Journeys as Journeys, - type Journey as Journey, - type JourneysInvokeRequest as JourneysInvokeRequest, - type JourneysInvokeResponse as JourneysInvokeResponse, - type JourneysListResponse as JourneysListResponse, - type JourneyListParams as JourneyListParams, - type JourneyInvokeParams as JourneyInvokeParams, - }; - - export { - Brands as Brands, - type Brand as Brand, - type BrandColors as BrandColors, - type BrandSettings as BrandSettings, - type BrandSettingsEmail as BrandSettingsEmail, - type BrandSettingsInApp as BrandSettingsInApp, - type BrandSnippet as BrandSnippet, - type BrandSnippets as BrandSnippets, - type BrandTemplate as BrandTemplate, - type EmailFooter as EmailFooter, - type EmailHead as EmailHead, - type EmailHeader as EmailHeader, - type Icons as Icons, - type Logo as Logo, - type WidgetBackground as WidgetBackground, - type BrandListResponse as BrandListResponse, - type BrandCreateParams as BrandCreateParams, - type BrandUpdateParams as BrandUpdateParams, - type BrandListParams as BrandListParams, - }; - - export { - Bulk as Bulk, - type InboundBulkMessage as InboundBulkMessage, - type InboundBulkMessageUser as InboundBulkMessageUser, - type BulkCreateJobResponse as BulkCreateJobResponse, - type BulkListUsersResponse as BulkListUsersResponse, - type BulkRetrieveJobResponse as BulkRetrieveJobResponse, - type BulkAddUsersParams as BulkAddUsersParams, - type BulkCreateJobParams as BulkCreateJobParams, - type BulkListUsersParams as BulkListUsersParams, - }; - - export { - Inbound as Inbound, - type InboundTrackEventResponse as InboundTrackEventResponse, - type InboundTrackEventParams as InboundTrackEventParams, - }; - - export { - Lists as Lists, - type PutSubscriptionsRecipient as PutSubscriptionsRecipient, - type SubscriptionList as SubscriptionList, - type ListListResponse as ListListResponse, - type ListUpdateParams as ListUpdateParams, - type ListListParams as ListListParams, - type ListRestoreParams as ListRestoreParams, - }; - - export { - Messages as Messages, - type MessageDetails as MessageDetails, - type MessageRetrieveResponse as MessageRetrieveResponse, - type MessageListResponse as MessageListResponse, - type MessageContentResponse as MessageContentResponse, - type MessageHistoryResponse as MessageHistoryResponse, - type MessageListParams as MessageListParams, - type MessageHistoryParams as MessageHistoryParams, - }; - - export { Requests as Requests }; - - export { - Notifications as Notifications, - type BaseCheck as BaseCheck, - type Check as Check, - type ElementWithChecksums as ElementWithChecksums, - type NotificationContentGetResponse as NotificationContentGetResponse, - type NotificationContentMutationResponse as NotificationContentMutationResponse, - type NotificationContentPutRequest as NotificationContentPutRequest, - type NotificationElementPutRequest as NotificationElementPutRequest, - type NotificationGetContent as NotificationGetContent, - type NotificationLocalePutRequest as NotificationLocalePutRequest, - type NotificationTemplateCreateRequest as NotificationTemplateCreateRequest, - type NotificationTemplatePayload as NotificationTemplatePayload, - type NotificationTemplatePublishRequest as NotificationTemplatePublishRequest, - type NotificationTemplateResponse as NotificationTemplateResponse, - type NotificationTemplateState as NotificationTemplateState, - type NotificationTemplateSummary as NotificationTemplateSummary, - type NotificationTemplateUpdateRequest as NotificationTemplateUpdateRequest, - type NotificationTemplateVersionListResponse as NotificationTemplateVersionListResponse, - type VersionNode as VersionNode, - type NotificationListResponse as NotificationListResponse, - type NotificationRetrieveContentResponse as NotificationRetrieveContentResponse, - type NotificationCreateParams as NotificationCreateParams, - type NotificationRetrieveParams as NotificationRetrieveParams, - type NotificationListParams as NotificationListParams, - type NotificationListVersionsParams as NotificationListVersionsParams, - type NotificationPublishParams as NotificationPublishParams, - type NotificationPutContentParams as NotificationPutContentParams, - type NotificationPutElementParams as NotificationPutElementParams, - type NotificationPutLocaleParams as NotificationPutLocaleParams, - type NotificationReplaceParams as NotificationReplaceParams, - type NotificationRetrieveContentParams as NotificationRetrieveContentParams, - }; - - export { - RoutingStrategies as RoutingStrategies, - type AssociatedNotificationListResponse as AssociatedNotificationListResponse, - type RoutingStrategyCreateRequest as RoutingStrategyCreateRequest, - type RoutingStrategyGetResponse as RoutingStrategyGetResponse, - type RoutingStrategyListResponse as RoutingStrategyListResponse, - type RoutingStrategyReplaceRequest as RoutingStrategyReplaceRequest, - type RoutingStrategySummary as RoutingStrategySummary, - type RoutingStrategyCreateParams as RoutingStrategyCreateParams, - type RoutingStrategyListParams as RoutingStrategyListParams, - type RoutingStrategyListNotificationsParams as RoutingStrategyListNotificationsParams, - type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams, - }; - - export { - Profiles as Profiles, - type SubscribeToListsRequestItem as SubscribeToListsRequestItem, - type ProfileCreateResponse as ProfileCreateResponse, - type ProfileRetrieveResponse as ProfileRetrieveResponse, - type ProfileReplaceResponse as ProfileReplaceResponse, - type ProfileCreateParams as ProfileCreateParams, - type ProfileUpdateParams as ProfileUpdateParams, - type ProfileReplaceParams as ProfileReplaceParams, - }; - - export { - Tenants as Tenants, - type BaseTemplateTenantAssociation as BaseTemplateTenantAssociation, - type DefaultPreferences as DefaultPreferences, - type PostTenantTemplatePublishRequest as PostTenantTemplatePublishRequest, - type PostTenantTemplatePublishResponse as PostTenantTemplatePublishResponse, - type PutTenantTemplateRequest as PutTenantTemplateRequest, - type PutTenantTemplateResponse as PutTenantTemplateResponse, - type SubscriptionTopicNew as SubscriptionTopicNew, - type Tenant as Tenant, - type TenantAssociation as TenantAssociation, - type TenantTemplateInput as TenantTemplateInput, - type TenantListResponse as TenantListResponse, - type TenantListUsersResponse as TenantListUsersResponse, - type TenantUpdateParams as TenantUpdateParams, - type TenantListParams as TenantListParams, - type TenantListUsersParams as TenantListUsersParams, - }; - - export { - Translations as Translations, - type TranslationRetrieveResponse as TranslationRetrieveResponse, - type TranslationRetrieveParams as TranslationRetrieveParams, - type TranslationUpdateParams as TranslationUpdateParams, - }; - - export { Users as Users }; - - export type AirshipProfile = API.AirshipProfile; - export type AirshipProfileAudience = API.AirshipProfileAudience; - export type Alignment = API.Alignment; - export type AudienceFilter = API.AudienceFilter; - export type AudienceFilterConfig = API.AudienceFilterConfig; - export type AudienceRecipient = API.AudienceRecipient; - export type Channel = API.Channel; - export type ChannelClassification = API.ChannelClassification; - export type ChannelMetadata = API.ChannelMetadata; - export type ChannelPreference = API.ChannelPreference; - export type DeviceType = API.DeviceType; - export type Discord = API.Discord; - export type ElementalActionNodeWithType = API.ElementalActionNodeWithType; - export type ElementalBaseNode = API.ElementalBaseNode; - export type ElementalChannelNode = API.ElementalChannelNode; - export type ElementalChannelNodeWithType = API.ElementalChannelNodeWithType; - export type ElementalContent = API.ElementalContent; - export type ElementalContentSugar = API.ElementalContentSugar; - export type ElementalDividerNodeWithType = API.ElementalDividerNodeWithType; - export type ElementalHTMLNodeWithType = API.ElementalHTMLNodeWithType; - export type ElementalImageNodeWithType = API.ElementalImageNodeWithType; - export type ElementalMetaNodeWithType = API.ElementalMetaNodeWithType; - export type ElementalNode = API.ElementalNode; - export type ElementalQuoteNodeWithType = API.ElementalQuoteNodeWithType; - export type ElementalTextNodeWithType = API.ElementalTextNodeWithType; - export type Expo = API.Expo; - export type FilterConfig = API.FilterConfig; - export type Intercom = API.Intercom; - export type IntercomRecipient = API.IntercomRecipient; - export type ListFilter = API.ListFilter; - export type ListPatternRecipient = API.ListPatternRecipient; - export type ListRecipient = API.ListRecipient; - export type MessageChannels = API.MessageChannels; - export type MessageContext = API.MessageContext; - export type MessageProviders = API.MessageProviders; - export type MessageProvidersType = API.MessageProvidersType; - export type MessageRouting = API.MessageRouting; - export type MessageRoutingChannel = API.MessageRoutingChannel; - export type Metadata = API.Metadata; - export type MsTeams = API.MsTeams; - export type MsTeamsBaseProperties = API.MsTeamsBaseProperties; - export type MsTeamsRecipient = API.MsTeamsRecipient; - export type MultipleTokens = API.MultipleTokens; - export type NotificationPreferenceDetails = API.NotificationPreferenceDetails; - export type Pagerduty = API.Pagerduty; - export type PagerdutyRecipient = API.PagerdutyRecipient; - export type Paging = API.Paging; - export type Preference = API.Preference; - export type PreferenceStatus = API.PreferenceStatus; - export type RecipientPreferences = API.RecipientPreferences; - export type Rule = API.Rule; - export type SendDirectMessage = API.SendDirectMessage; - export type SendToChannel = API.SendToChannel; - export type SendToMsTeamsChannelID = API.SendToMsTeamsChannelID; - export type SendToMsTeamsChannelName = API.SendToMsTeamsChannelName; - export type SendToMsTeamsConversationID = API.SendToMsTeamsConversationID; - export type SendToMsTeamsEmail = API.SendToMsTeamsEmail; - export type SendToMsTeamsUserID = API.SendToMsTeamsUserID; - export type SendToSlackChannel = API.SendToSlackChannel; - export type SendToSlackEmail = API.SendToSlackEmail; - export type SendToSlackUserID = API.SendToSlackUserID; - export type Slack = API.Slack; - export type SlackBaseProperties = API.SlackBaseProperties; - export type SlackRecipient = API.SlackRecipient; - export type TextStyle = API.TextStyle; - export type Timeouts = API.Timeouts; - export type Token = API.Token; - export type UserProfile = API.UserProfile; - export type UserProfileFirebaseToken = API.UserProfileFirebaseToken; - export type UserRecipient = API.UserRecipient; - export type Utm = API.Utm; - export type WebhookAuthMode = API.WebhookAuthMode; - export type WebhookAuthentication = API.WebhookAuthentication; - export type WebhookMethod = API.WebhookMethod; - export type WebhookProfile = API.WebhookProfile; - export type WebhookProfileType = API.WebhookProfileType; - export type WebhookRecipient = API.WebhookRecipient; -} + export type RequestOptions = Opts.RequestOptions; + + export { + Send as Send, + type SendMessageResponse as SendMessageResponse, + type SendMessageParams as SendMessageParams +}; + +export { + Audiences as Audiences, + type Audience as Audience, + type AudienceUpdateResponse as AudienceUpdateResponse, + type AudienceListResponse as AudienceListResponse, + type AudienceListMembersResponse as AudienceListMembersResponse, + type AudienceUpdateParams as AudienceUpdateParams, + type AudienceListParams as AudienceListParams, + type AudienceListMembersParams as AudienceListMembersParams +}; + +export { + Providers as Providers, + type Provider as Provider, + type ProvidersCatalogEntry as ProvidersCatalogEntry, + type ProviderListResponse as ProviderListResponse, + type ProviderCreateParams as ProviderCreateParams, + type ProviderUpdateParams as ProviderUpdateParams, + type ProviderListParams as ProviderListParams +}; + +export { + AuditEvents as AuditEvents, + type AuditEvent as AuditEvent, + type AuditEventListResponse as AuditEventListResponse, + type AuditEventListParams as AuditEventListParams +}; + +export { + Auth as Auth, + type AuthIssueTokenResponse as AuthIssueTokenResponse, + type AuthIssueTokenParams as AuthIssueTokenParams +}; + +export { + Automations as Automations, + type AutomationInvokeResponse as AutomationInvokeResponse, + type AutomationTemplate as AutomationTemplate, + type AutomationTemplateListResponse as AutomationTemplateListResponse, + type AutomationListParams as AutomationListParams +}; + +export { + Journeys as Journeys, + type Journey as Journey, + type JourneysInvokeRequest as JourneysInvokeRequest, + type JourneysInvokeResponse as JourneysInvokeResponse, + type JourneysListResponse as JourneysListResponse, + type JourneyListParams as JourneyListParams, + type JourneyInvokeParams as JourneyInvokeParams +}; + +export { + Brands as Brands, + type Brand as Brand, + type BrandColors as BrandColors, + type BrandSettings as BrandSettings, + type BrandSettingsEmail as BrandSettingsEmail, + type BrandSettingsInApp as BrandSettingsInApp, + type BrandSnippet as BrandSnippet, + type BrandSnippets as BrandSnippets, + type BrandTemplate as BrandTemplate, + type EmailFooter as EmailFooter, + type EmailHead as EmailHead, + type EmailHeader as EmailHeader, + type Icons as Icons, + type Logo as Logo, + type WidgetBackground as WidgetBackground, + type BrandListResponse as BrandListResponse, + type BrandCreateParams as BrandCreateParams, + type BrandUpdateParams as BrandUpdateParams, + type BrandListParams as BrandListParams +}; + +export { + Bulk as Bulk, + type InboundBulkMessage as InboundBulkMessage, + type InboundBulkMessageUser as InboundBulkMessageUser, + type BulkCreateJobResponse as BulkCreateJobResponse, + type BulkListUsersResponse as BulkListUsersResponse, + type BulkRetrieveJobResponse as BulkRetrieveJobResponse, + type BulkAddUsersParams as BulkAddUsersParams, + type BulkCreateJobParams as BulkCreateJobParams, + type BulkListUsersParams as BulkListUsersParams +}; + +export { + Inbound as Inbound, + type InboundTrackEventResponse as InboundTrackEventResponse, + type InboundTrackEventParams as InboundTrackEventParams +}; + +export { + Lists as Lists, + type PutSubscriptionsRecipient as PutSubscriptionsRecipient, + type SubscriptionList as SubscriptionList, + type ListListResponse as ListListResponse, + type ListUpdateParams as ListUpdateParams, + type ListListParams as ListListParams, + type ListRestoreParams as ListRestoreParams +}; + +export { + Messages as Messages, + type MessageDetails as MessageDetails, + type MessageRetrieveResponse as MessageRetrieveResponse, + type MessageListResponse as MessageListResponse, + type MessageContentResponse as MessageContentResponse, + type MessageHistoryResponse as MessageHistoryResponse, + type MessageListParams as MessageListParams, + type MessageHistoryParams as MessageHistoryParams +}; + +export { + Requests as Requests +}; + +export { + Notifications as Notifications, + type BaseCheck as BaseCheck, + type Check as Check, + type ElementWithChecksums as ElementWithChecksums, + type NotificationContentGetResponse as NotificationContentGetResponse, + type NotificationContentMutationResponse as NotificationContentMutationResponse, + type NotificationContentPutRequest as NotificationContentPutRequest, + type NotificationElementPutRequest as NotificationElementPutRequest, + type NotificationGetContent as NotificationGetContent, + type NotificationLocalePutRequest as NotificationLocalePutRequest, + type NotificationTemplateCreateRequest as NotificationTemplateCreateRequest, + type NotificationTemplatePayload as NotificationTemplatePayload, + type NotificationTemplatePublishRequest as NotificationTemplatePublishRequest, + type NotificationTemplateResponse as NotificationTemplateResponse, + type NotificationTemplateState as NotificationTemplateState, + type NotificationTemplateSummary as NotificationTemplateSummary, + type NotificationTemplateUpdateRequest as NotificationTemplateUpdateRequest, + type NotificationTemplateVersionListResponse as NotificationTemplateVersionListResponse, + type VersionNode as VersionNode, + type NotificationListResponse as NotificationListResponse, + type NotificationRetrieveContentResponse as NotificationRetrieveContentResponse, + type NotificationCreateParams as NotificationCreateParams, + type NotificationRetrieveParams as NotificationRetrieveParams, + type NotificationListParams as NotificationListParams, + type NotificationListVersionsParams as NotificationListVersionsParams, + type NotificationPublishParams as NotificationPublishParams, + type NotificationPutContentParams as NotificationPutContentParams, + type NotificationPutElementParams as NotificationPutElementParams, + type NotificationPutLocaleParams as NotificationPutLocaleParams, + type NotificationReplaceParams as NotificationReplaceParams, + type NotificationRetrieveContentParams as NotificationRetrieveContentParams +}; + +export { + RoutingStrategies as RoutingStrategies, + type AssociatedNotificationListResponse as AssociatedNotificationListResponse, + type RoutingStrategyCreateRequest as RoutingStrategyCreateRequest, + type RoutingStrategyGetResponse as RoutingStrategyGetResponse, + type RoutingStrategyListResponse as RoutingStrategyListResponse, + type RoutingStrategyReplaceRequest as RoutingStrategyReplaceRequest, + type RoutingStrategySummary as RoutingStrategySummary, + type RoutingStrategyCreateParams as RoutingStrategyCreateParams, + type RoutingStrategyListParams as RoutingStrategyListParams, + type RoutingStrategyListNotificationsParams as RoutingStrategyListNotificationsParams, + type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams +}; + +export { + Profiles as Profiles, + type SubscribeToListsRequestItem as SubscribeToListsRequestItem, + type ProfileCreateResponse as ProfileCreateResponse, + type ProfileRetrieveResponse as ProfileRetrieveResponse, + type ProfileReplaceResponse as ProfileReplaceResponse, + type ProfileCreateParams as ProfileCreateParams, + type ProfileUpdateParams as ProfileUpdateParams, + type ProfileReplaceParams as ProfileReplaceParams +}; + +export { + Tenants as Tenants, + type BaseTemplateTenantAssociation as BaseTemplateTenantAssociation, + type DefaultPreferences as DefaultPreferences, + type PostTenantTemplatePublishRequest as PostTenantTemplatePublishRequest, + type PostTenantTemplatePublishResponse as PostTenantTemplatePublishResponse, + type PutTenantTemplateRequest as PutTenantTemplateRequest, + type PutTenantTemplateResponse as PutTenantTemplateResponse, + type SubscriptionTopicNew as SubscriptionTopicNew, + type Tenant as Tenant, + type TenantAssociation as TenantAssociation, + type TenantTemplateInput as TenantTemplateInput, + type TenantListResponse as TenantListResponse, + type TenantListUsersResponse as TenantListUsersResponse, + type TenantUpdateParams as TenantUpdateParams, + type TenantListParams as TenantListParams, + type TenantListUsersParams as TenantListUsersParams +}; + +export { + Translations as Translations, + type TranslationRetrieveResponse as TranslationRetrieveResponse, + type TranslationRetrieveParams as TranslationRetrieveParams, + type TranslationUpdateParams as TranslationUpdateParams +}; + +export { + Users as Users +}; + +export type AirshipProfile = API.AirshipProfile; +export type AirshipProfileAudience = API.AirshipProfileAudience; +export type Alignment = API.Alignment; +export type AudienceFilter = API.AudienceFilter; +export type AudienceFilterConfig = API.AudienceFilterConfig; +export type AudienceRecipient = API.AudienceRecipient; +export type Channel = API.Channel; +export type ChannelClassification = API.ChannelClassification; +export type ChannelMetadata = API.ChannelMetadata; +export type ChannelPreference = API.ChannelPreference; +export type DeviceType = API.DeviceType; +export type Discord = API.Discord; +export type ElementalActionNodeWithType = API.ElementalActionNodeWithType; +export type ElementalBaseNode = API.ElementalBaseNode; +export type ElementalChannelNode = API.ElementalChannelNode; +export type ElementalChannelNodeWithType = API.ElementalChannelNodeWithType; +export type ElementalContent = API.ElementalContent; +export type ElementalContentSugar = API.ElementalContentSugar; +export type ElementalDividerNodeWithType = API.ElementalDividerNodeWithType; +export type ElementalHTMLNodeWithType = API.ElementalHTMLNodeWithType; +export type ElementalImageNodeWithType = API.ElementalImageNodeWithType; +export type ElementalMetaNodeWithType = API.ElementalMetaNodeWithType; +export type ElementalNode = API.ElementalNode; +export type ElementalQuoteNodeWithType = API.ElementalQuoteNodeWithType; +export type ElementalTextNodeWithType = API.ElementalTextNodeWithType; +export type Expo = API.Expo; +export type FilterConfig = API.FilterConfig; +export type Intercom = API.Intercom; +export type IntercomRecipient = API.IntercomRecipient; +export type ListFilter = API.ListFilter; +export type ListPatternRecipient = API.ListPatternRecipient; +export type ListRecipient = API.ListRecipient; +export type MessageChannels = API.MessageChannels; +export type MessageContext = API.MessageContext; +export type MessageProviders = API.MessageProviders; +export type MessageProvidersType = API.MessageProvidersType; +export type MessageRouting = API.MessageRouting; +export type MessageRoutingChannel = API.MessageRoutingChannel; +export type Metadata = API.Metadata; +export type MsTeams = API.MsTeams; +export type MsTeamsBaseProperties = API.MsTeamsBaseProperties; +export type MsTeamsRecipient = API.MsTeamsRecipient; +export type MultipleTokens = API.MultipleTokens; +export type NotificationPreferenceDetails = API.NotificationPreferenceDetails; +export type Pagerduty = API.Pagerduty; +export type PagerdutyRecipient = API.PagerdutyRecipient; +export type Paging = API.Paging; +export type Preference = API.Preference; +export type PreferenceStatus = API.PreferenceStatus; +export type RecipientPreferences = API.RecipientPreferences; +export type Rule = API.Rule; +export type SendDirectMessage = API.SendDirectMessage; +export type SendToChannel = API.SendToChannel; +export type SendToMsTeamsChannelID = API.SendToMsTeamsChannelID; +export type SendToMsTeamsChannelName = API.SendToMsTeamsChannelName; +export type SendToMsTeamsConversationID = API.SendToMsTeamsConversationID; +export type SendToMsTeamsEmail = API.SendToMsTeamsEmail; +export type SendToMsTeamsUserID = API.SendToMsTeamsUserID; +export type SendToSlackChannel = API.SendToSlackChannel; +export type SendToSlackEmail = API.SendToSlackEmail; +export type SendToSlackUserID = API.SendToSlackUserID; +export type Slack = API.Slack; +export type SlackBaseProperties = API.SlackBaseProperties; +export type SlackRecipient = API.SlackRecipient; +export type TextStyle = API.TextStyle; +export type Timeouts = API.Timeouts; +export type Token = API.Token; +export type UserProfile = API.UserProfile; +export type UserProfileFirebaseToken = API.UserProfileFirebaseToken; +export type UserRecipient = API.UserRecipient; +export type Utm = API.Utm; +export type WebhookAuthMode = API.WebhookAuthMode; +export type WebhookAuthentication = API.WebhookAuthentication; +export type WebhookMethod = API.WebhookMethod; +export type WebhookProfile = API.WebhookProfile; +export type WebhookProfileType = API.WebhookProfileType; +export type WebhookRecipient = API.WebhookRecipient; + } diff --git a/src/core/api-promise.ts b/src/core/api-promise.ts index 8174c9f1..75c7112c 100644 --- a/src/core/api-promise.ts +++ b/src/core/api-promise.ts @@ -16,10 +16,7 @@ export class APIPromise extends Promise { constructor( client: Courier, private responsePromise: Promise, - private parseResponse: ( - client: Courier, - props: APIResponseProps, - ) => PromiseOrValue = defaultParseResponse, + private parseResponse: (client: Courier, props: APIResponseProps) => PromiseOrValue = defaultParseResponse, ) { super((resolve) => { // this is maybe a bit weird but this has to be a no-op to not implicitly @@ -31,9 +28,7 @@ export class APIPromise extends Promise { } _thenUnwrap(transform: (data: T, props: APIResponseProps) => U): APIPromise { - return new APIPromise(this.#client, this.responsePromise, async (client, props) => - transform(await this.parseResponse(client, props), props), - ); + return new APIPromise(this.#client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); } /** diff --git a/src/core/error.ts b/src/core/error.ts index fd075715..d91fdb38 100644 --- a/src/core/error.ts +++ b/src/core/error.ts @@ -2,13 +2,10 @@ import { castToError } from '../internal/errors'; -export class CourierError extends Error {} +export class CourierError extends Error { +} -export class APIError< - TStatus extends number | undefined = number | undefined, - THeaders extends Headers | undefined = Headers | undefined, - TError extends Object | undefined = Object | undefined, -> extends CourierError { +export class APIError extends CourierError { /** HTTP status for the response that caused the error */ readonly status: TStatus; /** HTTP headers for the response that caused the error */ @@ -16,6 +13,9 @@ export class APIError< /** JSON body of the response that caused the error */ readonly error: TError; + + ; + constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) { super(`${APIError.makeMessage(status, error, message)}`); this.status = status; @@ -26,8 +26,7 @@ export class APIError< private static makeMessage(status: number | undefined, error: any, message: string | undefined) { const msg = error?.message ? - typeof error.message === 'string' ? - error.message + typeof error.message === 'string' ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; @@ -44,12 +43,7 @@ export class APIError< return '(no status code or body)'; } - static generate( - status: number | undefined, - errorResponse: Object | undefined, - message: string | undefined, - headers: Headers | undefined, - ): APIError { + static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError { if (!status || !headers) { return new APIConnectionError({ message, cause: castToError(errorResponse) }); } @@ -113,18 +107,26 @@ export class APIConnectionTimeoutError extends APIConnectionError { } } -export class BadRequestError extends APIError<400, Headers> {} +export class BadRequestError extends APIError<400, Headers> { +} -export class AuthenticationError extends APIError<401, Headers> {} +export class AuthenticationError extends APIError<401, Headers> { +} -export class PermissionDeniedError extends APIError<403, Headers> {} +export class PermissionDeniedError extends APIError<403, Headers> { +} -export class NotFoundError extends APIError<404, Headers> {} +export class NotFoundError extends APIError<404, Headers> { +} -export class ConflictError extends APIError<409, Headers> {} +export class ConflictError extends APIError<409, Headers> { +} -export class UnprocessableEntityError extends APIError<422, Headers> {} +export class UnprocessableEntityError extends APIError<422, Headers> { +} -export class RateLimitError extends APIError<429, Headers> {} +export class RateLimitError extends APIError<429, Headers> { +} -export class InternalServerError extends APIError {} +export class InternalServerError extends APIError { +} diff --git a/src/error.ts b/src/error.ts index fc55f46c..d0832d34 100644 --- a/src/error.ts +++ b/src/error.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/error instead */ -export * from './core/error'; +export * from "./core/error" \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index ff16c989..2ce795be 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,18 +5,4 @@ export { Courier as default } from './client'; export { type Uploadable, toFile } from './core/uploads'; export { APIPromise } from './core/api-promise'; export { Courier, type ClientOptions } from './client'; -export { - CourierError, - APIError, - APIConnectionError, - APIConnectionTimeoutError, - APIUserAbortError, - NotFoundError, - ConflictError, - RateLimitError, - BadRequestError, - AuthenticationError, - InternalServerError, - PermissionDeniedError, - UnprocessableEntityError, -} from './core/error'; +export { CourierError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError } from './core/error'; diff --git a/src/internal/builtin-types.ts b/src/internal/builtin-types.ts index c23d3bde..6059d5db 100644 --- a/src/internal/builtin-types.ts +++ b/src/internal/builtin-types.ts @@ -1,20 +1,23 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise; +export type Fetch = ( + input: string | URL | Request, + init?: RequestInit, +) => Promise /** * An alias to the builtin `RequestInit` type so we can * easily alias it in import statements if there are name clashes. - * - * https://developer.mozilla.org/docs/Web/API/RequestInit + * + * https://developer.mozilla.org/docs/Web/API/RequestInit */ type _RequestInit = RequestInit; /** * An alias to the builtin `Response` type so we can * easily alias it in import statements if there are name clashes. - * - * https://developer.mozilla.org/docs/Web/API/Response + * + * https://developer.mozilla.org/docs/Web/API/Response */ type _Response = Response; @@ -51,15 +54,7 @@ type _Array = Array; */ type _Record = Record; -export type { - _Array as Array, - _BodyInit as BodyInit, - _HeadersInit as HeadersInit, - _Record as Record, - _RequestInfo as RequestInfo, - _RequestInit as RequestInit, - _Response as Response, -}; +export type { _Array as Array, _BodyInit as BodyInit, _HeadersInit as HeadersInit, _Record as Record, _RequestInfo as RequestInfo, _RequestInit as RequestInit, _Response as Response }; /** * A copy of the builtin `EndingType` type as it isn't fully supported in certain diff --git a/src/internal/detect-platform.ts b/src/internal/detect-platform.ts index e82d95c9..394ede88 100644 --- a/src/internal/detect-platform.ts +++ b/src/internal/detect-platform.ts @@ -25,11 +25,7 @@ function getDetectedPlatform(): DetectedPlatform { if (typeof EdgeRuntime !== 'undefined') { return 'edge'; } - if ( - Object.prototype.toString.call( - typeof (globalThis as any).process !== 'undefined' ? (globalThis as any).process : 0, - ) === '[object process]' - ) { + if (Object.prototype.toString.call(typeof (globalThis as any).process !== 'undefined' ? (globalThis as any).process : 0) === '[object process]') { return 'node'; } return 'unknown'; diff --git a/src/internal/errors.ts b/src/internal/errors.ts index 82c7b14d..c14a742b 100644 --- a/src/internal/errors.ts +++ b/src/internal/errors.ts @@ -2,12 +2,12 @@ export function isAbortError(err: unknown) { return ( - typeof err === 'object' && - err !== null && - // Spec-compliant fetch implementations - (('name' in err && (err as any).name === 'AbortError') || + typeof err === 'object' && err !== null && ( + // Spec-compliant fetch implementations + ('name' in err && (err as any).name === 'AbortError') || // Expo fetch - ('message' in err && String((err as any).message).includes('FetchRequestCanceledException'))) + ('message' in err && String((err as any).message).includes('FetchRequestCanceledException')) + ) ); } @@ -24,10 +24,10 @@ export const castToError = (err: any): Error => { if (err.name) error.name = err.name; return error; } - } catch {} + } catch { } try { return new Error(JSON.stringify(err)); - } catch {} + } catch { } } return new Error(err); }; diff --git a/src/internal/headers.ts b/src/internal/headers.ts index c724a9d2..fa2ea2b9 100644 --- a/src/internal/headers.ts +++ b/src/internal/headers.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { isReadonlyArray } from './utils/values'; +import { isReadonlyArray } from "./utils/values"; type HeaderValue = string | undefined | null; export type HeadersLike = @@ -51,7 +51,7 @@ function* iterateHeaders(headers: HeadersLike): IterableIterator(client: Courier, props: APIResponseProps): Promise { const { response, requestLogID, retryOfRequestLogID, startTime } = props; const body = await (async () => { + // fetch refuses to read the body when the status code is 204. if (response.status === 204) { return null as T; @@ -42,15 +43,6 @@ export async function defaultParseResponse(client: Courier, props: APIRespons const text = await response.text(); return text as unknown as T; })(); - loggerFor(client).debug( - `[${requestLogID}] response parsed`, - formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime, - }), - ); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, body, durationMs: Date.now() - startTime })); return body; } diff --git a/src/internal/qs/utils.ts b/src/internal/qs/utils.ts index 4cd56579..f21d955b 100644 --- a/src/internal/qs/utils.ts +++ b/src/internal/qs/utils.ts @@ -62,7 +62,10 @@ export function merge( if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { + if ( + (options && (options.plainObjects || options.allowPrototypes)) || + !has(Object.prototype, source) + ) { target[source] = true; } } else { diff --git a/src/internal/request-options.ts b/src/internal/request-options.ts index 2aabf9aa..a8558b20 100644 --- a/src/internal/request-options.ts +++ b/src/internal/request-options.ts @@ -76,10 +76,14 @@ export type RequestOptions = { defaultBaseURL?: string | undefined; __binaryResponse?: boolean | undefined; + }; export type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit }; -export type RequestEncoder = (request: { headers: NullableHeaders; body: unknown }) => EncodedContent; +export type RequestEncoder = (request: { + headers: NullableHeaders; + body: unknown; +}) => EncodedContent; export const FallbackEncoder: RequestEncoder = ({ headers, body }) => { return { diff --git a/src/internal/shim-types.ts b/src/internal/shim-types.ts index 8ddf7b0a..accbf576 100644 --- a/src/internal/shim-types.ts +++ b/src/internal/shim-types.ts @@ -19,8 +19,8 @@ type _ConditionalNodeReadableStream = typeof globalThis extends { ReadableStream: any } ? never : _NodeReadableStream; type _ReadableStream = NeverToAny< - | ([0] extends [1 & _DOMReadableStream] ? never : _DOMReadableStream) - | ([0] extends [1 & _ConditionalNodeReadableStream] ? never : _ConditionalNodeReadableStream) + ([0] extends [1 & _DOMReadableStream] ? never : _DOMReadableStream) | + ([0] extends [1 & _ConditionalNodeReadableStream] ? never : _ConditionalNodeReadableStream) >; export type { _ReadableStream as ReadableStream }; diff --git a/src/internal/shims.ts b/src/internal/shims.ts index e011f197..61f9949c 100644 --- a/src/internal/shims.ts +++ b/src/internal/shims.ts @@ -27,9 +27,7 @@ export function makeReadableStream(...args: ReadableStreamArgs): ReadableStream if (typeof ReadableStream === 'undefined') { // Note: All of the platforms / runtimes we officially support already define // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. - throw new Error( - '`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`', - ); + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); } return new ReadableStream(...args); diff --git a/src/internal/to-file.ts b/src/internal/to-file.ts index 30eada32..c72a2b41 100644 --- a/src/internal/to-file.ts +++ b/src/internal/to-file.ts @@ -1,4 +1,4 @@ -import { BlobPart, getName, makeFile, isAsyncIterable } from './uploads'; +import { BlobPart, getName, makeFile, isAsyncIterable } from "./uploads"; import type { FilePropertyBag } from './builtin-types'; import { checkFileSupport } from './uploads'; @@ -65,11 +65,8 @@ const isResponseLike = (value: any): value is ResponseLike => typeof value.url === 'string' && typeof value.blob === 'function'; -export type ToFileInput = - | FileLike - | ResponseLike - | Exclude - | AsyncIterable; +export type ToFileInput = FileLike | ResponseLike | Exclude | AsyncIterable; + /** * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats @@ -119,7 +116,9 @@ export async function toFile( return makeFile(parts, name, options); } -async function getBytes(value: BlobLikePart | AsyncIterable): Promise> { +async function getBytes( + value: BlobLikePart | AsyncIterable, +): Promise> { let parts: Array = []; if ( typeof value === 'string' || @@ -152,3 +151,4 @@ function propsForError(value: unknown): string { const props = Object.getOwnPropertyNames(value); return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; } + diff --git a/src/internal/types.ts b/src/internal/types.ts index b668dfc0..c45fee32 100644 --- a/src/internal/types.ts +++ b/src/internal/types.ts @@ -7,40 +7,34 @@ export type KeysEnum = { [P in keyof Required]: true }; export type FinalizedRequestInit = RequestInit & { headers: Headers }; -type NotAny = [0] extends [1 & T] ? never : T; +type NotAny = [0] extends [(1 & T)] ? never : T; /** * Some environments overload the global fetch function, and Parameters only gets the last signature. */ -type OverloadedParameters = - T extends ( - { +type OverloadedParameters = T extends { + (...args: infer A): unknown; + (...args: infer B): unknown; + (...args: infer C): unknown; + (...args: infer D): unknown; +} + ? A | B | C | D + : T extends { (...args: infer A): unknown; (...args: infer B): unknown; (...args: infer C): unknown; - (...args: infer D): unknown; } - ) ? - A | B | C | D - : T extends ( - { - (...args: infer A): unknown; - (...args: infer B): unknown; - (...args: infer C): unknown; - } - ) ? - A | B | C - : T extends ( - { + ? A | B | C + : T extends { (...args: infer A): unknown; (...args: infer B): unknown; } - ) ? - A | B - : T extends (...args: infer A) => unknown ? A + ? A | B + : T extends (...args: infer A) => unknown + ? A : never; -/* eslint-disable */ + /** * These imports attempt to get types from a parent package's dependencies. * Unresolved bare specifiers can trigger [automatic type acquisition][1] in some projects, which @@ -63,19 +57,19 @@ type OverloadedParameters = * * [1]: https://www.typescriptlang.org/tsconfig/#typeAcquisition */ -/** @ts-ignore For users with \@types/node */ +/** @ts-ignore For users with \@types/node */ /* prettier-ignore */ type UndiciTypesRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with undici */ +/** @ts-ignore For users with undici */ /* prettier-ignore */ type UndiciRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with \@types/bun */ +/** @ts-ignore For users with \@types/bun */ /* prettier-ignore */ type BunRequestInit = globalThis.FetchRequestInit; -/** @ts-ignore For users with node-fetch@2 */ +/** @ts-ignore For users with node-fetch@2 */ /* prettier-ignore */ type NodeFetch2RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with node-fetch@3, doesn't need file extension because types are at ./@types/index.d.ts */ +/** @ts-ignore For users with node-fetch@3, doesn't need file extension because types are at ./@types/index.d.ts */ /* prettier-ignore */ type NodeFetch3RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users who use Deno */ +/** @ts-ignore For users who use Deno */ /* prettier-ignore */ type FetchRequestInit = NonNullable[1]>; -/* eslint-enable */ + type RequestInits = | NotAny diff --git a/src/internal/utils/log.ts b/src/internal/utils/log.ts index dbbb7b33..be2c27b4 100644 --- a/src/internal/utils/log.ts +++ b/src/internal/utils/log.ts @@ -4,7 +4,7 @@ import { hasOwn } from './values'; import { type Courier } from '../../client'; import { RequestOptions } from '../request-options'; -type LogFn = (message: string, ...rest: unknown[]) => void; +type LogFn = (message: string, ...rest: unknown[]) => void export type Logger = { error: LogFn; warn: LogFn; @@ -21,22 +21,14 @@ const levelNumbers = { debug: 500, }; -export const parseLogLevel = ( - maybeLevel: string | undefined, - sourceName: string, - client: Courier, -): LogLevel | undefined => { +export const parseLogLevel = (maybeLevel: string | undefined, sourceName: string, client: Courier): LogLevel | undefined => { if (!maybeLevel) { return undefined; } if (hasOwn(levelNumbers, maybeLevel)) { return maybeLevel; - } - loggerFor(client).warn( - `${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify( - Object.keys(levelNumbers), - )}`, - ); + }; + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); return undefined; }; @@ -97,24 +89,11 @@ export const formatRequestDetails = (details: { body?: unknown; }) => { if (details.options) { - details.options = { ...details.options }; + details.options = {...details.options}; delete details.options['headers']; // redundant + leaks internals } if (details.headers) { - details.headers = Object.fromEntries( - (details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map( - ([name, value]) => [ - name, - ( - name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie' - ) ? - '***' - : value, - ], - ), - ); + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, name.toLowerCase() === 'authorization' || name.toLowerCase() === 'cookie' || name.toLowerCase() === 'set-cookie' ? '***' : value])) } if ('retryOfRequestLogID' in details) { if (details.retryOfRequestLogID) { @@ -122,5 +101,5 @@ export const formatRequestDetails = (details: { } delete details.retryOfRequestLogID; } - return details; -}; + return details +} diff --git a/src/internal/utils/query.ts b/src/internal/utils/query.ts index 0139cacb..06e72d93 100644 --- a/src/internal/utils/query.ts +++ b/src/internal/utils/query.ts @@ -3,5 +3,5 @@ import * as qs from '../qs/stringify'; export function stringifyQuery(query: object | Record) { - return qs.stringify(query, { arrayFormat: 'comma' }); + return qs.stringify(query, { arrayFormat: 'comma' }) } diff --git a/src/internal/utils/uuid.ts b/src/internal/utils/uuid.ts index b0e53aaf..53708ba6 100644 --- a/src/internal/utils/uuid.ts +++ b/src/internal/utils/uuid.ts @@ -10,8 +10,10 @@ export let uuid4 = function () { return crypto.randomUUID(); } const u8 = new Uint8Array(1); - const randomByte = crypto ? () => crypto.getRandomValues(u8)[0]! : () => (Math.random() * 0xff) & 0xff; - return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => + const randomByte = crypto + ? () => crypto.getRandomValues(u8)[0]! + : () => (Math.random() * 0xff) & 0xff; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16), ); -}; +} diff --git a/src/resource.ts b/src/resource.ts index 363e3516..57a27a94 100644 --- a/src/resource.ts +++ b/src/resource.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/resource instead */ -export * from './core/resource'; +export * from "./core/resource" \ No newline at end of file diff --git a/src/resources/audiences.ts b/src/resources/audiences.ts index c6942ae6..713f4788 100644 --- a/src/resources/audiences.ts +++ b/src/resources/audiences.ts @@ -18,21 +18,14 @@ export class Audiences extends APIResource { /** * Creates or updates audience. */ - update( - audienceID: string, - body: AudienceUpdateParams, - options?: RequestOptions, - ): APIPromise { + update(audienceID: string, body: AudienceUpdateParams, options?: RequestOptions): APIPromise { return this._client.put(path`/audiences/${audienceID}`, { body, ...options }); } /** * Get the audiences associated with the authorization token. */ - list( - query: AudienceListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: AudienceListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/audiences', { query, ...options }); } @@ -40,20 +33,13 @@ export class Audiences extends APIResource { * Deletes the specified audience. */ delete(audienceID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/audiences/${audienceID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/audiences/${audienceID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** * Get list of members of an audience. */ - listMembers( - audienceID: string, - query: AudienceListMembersParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + listMembers(audienceID: string, query: AudienceListMembersParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/audiences/${audienceID}/members`, { query, ...options }); } } @@ -163,6 +149,6 @@ export declare namespace Audiences { type AudienceListMembersResponse as AudienceListMembersResponse, type AudienceUpdateParams as AudienceUpdateParams, type AudienceListParams as AudienceListParams, - type AudienceListMembersParams as AudienceListMembersParams, + type AudienceListMembersParams as AudienceListMembersParams }; } diff --git a/src/resources/audit-events.ts b/src/resources/audit-events.ts index 11c35fc4..b5950eb6 100644 --- a/src/resources/audit-events.ts +++ b/src/resources/audit-events.ts @@ -17,10 +17,7 @@ export class AuditEvents extends APIResource { /** * Fetch the list of audit events */ - list( - query: AuditEventListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: AuditEventListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/audit-events', { query, ...options }); } } @@ -64,6 +61,6 @@ export declare namespace AuditEvents { export { type AuditEvent as AuditEvent, type AuditEventListResponse as AuditEventListResponse, - type AuditEventListParams as AuditEventListParams, + type AuditEventListParams as AuditEventListParams }; } diff --git a/src/resources/auth.ts b/src/resources/auth.ts index 0ce3ab19..8a3262af 100644 --- a/src/resources/auth.ts +++ b/src/resources/auth.ts @@ -65,6 +65,6 @@ export interface AuthIssueTokenParams { export declare namespace Auth { export { type AuthIssueTokenResponse as AuthIssueTokenResponse, - type AuthIssueTokenParams as AuthIssueTokenParams, + type AuthIssueTokenParams as AuthIssueTokenParams }; } diff --git a/src/resources/automations/automations.ts b/src/resources/automations/automations.ts index 6448ce72..6be3fa1b 100644 --- a/src/resources/automations/automations.ts +++ b/src/resources/automations/automations.ts @@ -18,10 +18,7 @@ export class Automations extends APIResource { * await client.automations.list(); * ``` */ - list( - query: AutomationListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: AutomationListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/automations', { query, ...options }); } } @@ -87,12 +84,12 @@ export declare namespace Automations { type AutomationInvokeResponse as AutomationInvokeResponse, type AutomationTemplate as AutomationTemplate, type AutomationTemplateListResponse as AutomationTemplateListResponse, - type AutomationListParams as AutomationListParams, + type AutomationListParams as AutomationListParams }; export { Invoke as Invoke, type InvokeInvokeAdHocParams as InvokeInvokeAdHocParams, - type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams, + type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams }; } diff --git a/src/resources/automations/index.ts b/src/resources/automations/index.ts index a1988573..8ff76556 100644 --- a/src/resources/automations/index.ts +++ b/src/resources/automations/index.ts @@ -1,10 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { - Automations, - type AutomationInvokeResponse, - type AutomationTemplate, - type AutomationTemplateListResponse, - type AutomationListParams, -} from './automations'; -export { Invoke, type InvokeInvokeAdHocParams, type InvokeInvokeByTemplateParams } from './invoke'; +export { Automations, type AutomationInvokeResponse, type AutomationTemplate, type AutomationTemplateListResponse, type AutomationListParams } from './automations';; +export { Invoke, type InvokeInvokeAdHocParams, type InvokeInvokeByTemplateParams } from './invoke';; diff --git a/src/resources/automations/invoke.ts b/src/resources/automations/invoke.ts index dbfebedf..8c0b9e1b 100644 --- a/src/resources/automations/invoke.ts +++ b/src/resources/automations/invoke.ts @@ -33,10 +33,7 @@ export class Invoke extends APIResource { * }); * ``` */ - invokeAdHoc( - body: InvokeInvokeAdHocParams, - options?: RequestOptions, - ): APIPromise { + invokeAdHoc(body: InvokeInvokeAdHocParams, options?: RequestOptions): APIPromise { return this._client.post('/automations/invoke', { body, ...options }); } @@ -52,11 +49,7 @@ export class Invoke extends APIResource { * ); * ``` */ - invokeByTemplate( - templateID: string, - body: InvokeInvokeByTemplateParams, - options?: RequestOptions, - ): APIPromise { + invokeByTemplate(templateID: string, body: InvokeInvokeByTemplateParams, options?: RequestOptions): APIPromise { return this._client.post(path`/automations/${templateID}/invoke`, { body, ...options }); } } @@ -77,15 +70,7 @@ export interface InvokeInvokeAdHocParams { export namespace InvokeInvokeAdHocParams { export interface Automation { - steps: Array< - | Automation.AutomationDelayStep - | Automation.AutomationSendStep - | Automation.AutomationSendListStep - | Automation.AutomationUpdateProfileStep - | Automation.AutomationCancelStep - | Automation.AutomationFetchDataStep - | Automation.AutomationInvokeStep - >; + steps: Array; cancelation_token?: string | null; } @@ -182,6 +167,6 @@ export interface InvokeInvokeByTemplateParams { export declare namespace Invoke { export { type InvokeInvokeAdHocParams as InvokeInvokeAdHocParams, - type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams, + type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams }; } diff --git a/src/resources/brands.ts b/src/resources/brands.ts index 9a99a163..342c1669 100644 --- a/src/resources/brands.ts +++ b/src/resources/brands.ts @@ -33,10 +33,7 @@ export class Brands extends APIResource { /** * Get the list of brands. */ - list( - query: BrandListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: BrandListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/brands', { query, ...options }); } @@ -44,10 +41,7 @@ export class Brands extends APIResource { * Delete a brand by brand ID. */ delete(brandID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/brands/${brandID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/brands/${brandID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -74,7 +68,7 @@ export interface BrandColors { secondary?: string; - [k: string]: string | undefined; +[k: string]: string | undefined } export interface BrandSettings { @@ -238,6 +232,6 @@ export declare namespace Brands { type BrandListResponse as BrandListResponse, type BrandCreateParams as BrandCreateParams, type BrandUpdateParams as BrandUpdateParams, - type BrandListParams as BrandListParams, + type BrandListParams as BrandListParams }; } diff --git a/src/resources/bulk.ts b/src/resources/bulk.ts index 923f1268..4d847204 100644 --- a/src/resources/bulk.ts +++ b/src/resources/bulk.ts @@ -17,11 +17,7 @@ export class Bulk extends APIResource { * for email provider routing. */ addUsers(jobID: string, body: BulkAddUsersParams, options?: RequestOptions): APIPromise { - return this._client.post(path`/bulk/${jobID}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.post(path`/bulk/${jobID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -40,11 +36,7 @@ export class Bulk extends APIResource { /** * Get Bulk Job Users */ - listUsers( - jobID: string, - query: BulkListUsersParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + listUsers(jobID: string, query: BulkListUsersParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/bulk/${jobID}/users`, { query, ...options }); } @@ -59,10 +51,7 @@ export class Bulk extends APIResource { * Run a bulk job */ runJob(jobID: string, options?: RequestOptions): APIPromise { - return this._client.post(path`/bulk/${jobID}/run`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.post(path`/bulk/${jobID}/run`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -205,6 +194,6 @@ export declare namespace Bulk { type BulkRetrieveJobResponse as BulkRetrieveJobResponse, type BulkAddUsersParams as BulkAddUsersParams, type BulkCreateJobParams as BulkCreateJobParams, - type BulkListUsersParams as BulkListUsersParams, + type BulkListUsersParams as BulkListUsersParams }; } diff --git a/src/resources/inbound.ts b/src/resources/inbound.ts index 56d5d272..4fee7906 100644 --- a/src/resources/inbound.ts +++ b/src/resources/inbound.ts @@ -62,6 +62,6 @@ export interface InboundTrackEventParams { export declare namespace Inbound { export { type InboundTrackEventResponse as InboundTrackEventResponse, - type InboundTrackEventParams as InboundTrackEventParams, + type InboundTrackEventParams as InboundTrackEventParams }; } diff --git a/src/resources/index.ts b/src/resources/index.ts index 39e3d90d..d8dfc5f2 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -1,180 +1,22 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export * from './shared'; -export { - Audiences, - type Audience, - type AudienceUpdateResponse, - type AudienceListResponse, - type AudienceListMembersResponse, - type AudienceUpdateParams, - type AudienceListParams, - type AudienceListMembersParams, -} from './audiences'; -export { - AuditEvents, - type AuditEvent, - type AuditEventListResponse, - type AuditEventListParams, -} from './audit-events'; -export { Auth, type AuthIssueTokenResponse, type AuthIssueTokenParams } from './auth'; -export { - Automations, - type AutomationInvokeResponse, - type AutomationTemplate, - type AutomationTemplateListResponse, - type AutomationListParams, -} from './automations/automations'; -export { - Brands, - type Brand, - type BrandColors, - type BrandSettings, - type BrandSettingsEmail, - type BrandSettingsInApp, - type BrandSnippet, - type BrandSnippets, - type BrandTemplate, - type EmailFooter, - type EmailHead, - type EmailHeader, - type Icons, - type Logo, - type WidgetBackground, - type BrandListResponse, - type BrandCreateParams, - type BrandUpdateParams, - type BrandListParams, -} from './brands'; -export { - Bulk, - type InboundBulkMessage, - type InboundBulkMessageUser, - type BulkCreateJobResponse, - type BulkListUsersResponse, - type BulkRetrieveJobResponse, - type BulkAddUsersParams, - type BulkCreateJobParams, - type BulkListUsersParams, -} from './bulk'; -export { Inbound, type InboundTrackEventResponse, type InboundTrackEventParams } from './inbound'; -export { - Journeys, - type Journey, - type JourneysInvokeRequest, - type JourneysInvokeResponse, - type JourneysListResponse, - type JourneyListParams, - type JourneyInvokeParams, -} from './journeys'; -export { - Lists, - type PutSubscriptionsRecipient, - type SubscriptionList, - type ListListResponse, - type ListUpdateParams, - type ListListParams, - type ListRestoreParams, -} from './lists/lists'; -export { - Messages, - type MessageDetails, - type MessageRetrieveResponse, - type MessageListResponse, - type MessageContentResponse, - type MessageHistoryResponse, - type MessageListParams, - type MessageHistoryParams, -} from './messages'; -export { - Notifications, - type BaseCheck, - type Check, - type ElementWithChecksums, - type NotificationContentGetResponse, - type NotificationContentMutationResponse, - type NotificationContentPutRequest, - type NotificationElementPutRequest, - type NotificationGetContent, - type NotificationLocalePutRequest, - type NotificationTemplateCreateRequest, - type NotificationTemplatePayload, - type NotificationTemplatePublishRequest, - type NotificationTemplateResponse, - type NotificationTemplateState, - type NotificationTemplateSummary, - type NotificationTemplateUpdateRequest, - type NotificationTemplateVersionListResponse, - type VersionNode, - type NotificationListResponse, - type NotificationRetrieveContentResponse, - type NotificationCreateParams, - type NotificationRetrieveParams, - type NotificationListParams, - type NotificationListVersionsParams, - type NotificationPublishParams, - type NotificationPutContentParams, - type NotificationPutElementParams, - type NotificationPutLocaleParams, - type NotificationReplaceParams, - type NotificationRetrieveContentParams, -} from './notifications/notifications'; -export { - Profiles, - type SubscribeToListsRequestItem, - type ProfileCreateResponse, - type ProfileRetrieveResponse, - type ProfileReplaceResponse, - type ProfileCreateParams, - type ProfileUpdateParams, - type ProfileReplaceParams, -} from './profiles/profiles'; -export { - Providers, - type Provider, - type ProvidersCatalogEntry, - type ProviderListResponse, - type ProviderCreateParams, - type ProviderUpdateParams, - type ProviderListParams, -} from './providers/providers'; -export { Requests } from './requests'; -export { - RoutingStrategies, - type AssociatedNotificationListResponse, - type RoutingStrategyCreateRequest, - type RoutingStrategyGetResponse, - type RoutingStrategyListResponse, - type RoutingStrategyReplaceRequest, - type RoutingStrategySummary, - type RoutingStrategyCreateParams, - type RoutingStrategyListParams, - type RoutingStrategyListNotificationsParams, - type RoutingStrategyReplaceParams, -} from './routing-strategies'; -export { Send, type SendMessageResponse, type SendMessageParams } from './send'; -export { - Tenants, - type BaseTemplateTenantAssociation, - type DefaultPreferences, - type PostTenantTemplatePublishRequest, - type PostTenantTemplatePublishResponse, - type PutTenantTemplateRequest, - type PutTenantTemplateResponse, - type SubscriptionTopicNew, - type Tenant, - type TenantAssociation, - type TenantTemplateInput, - type TenantListResponse, - type TenantListUsersResponse, - type TenantUpdateParams, - type TenantListParams, - type TenantListUsersParams, -} from './tenants/tenants'; -export { - Translations, - type TranslationRetrieveResponse, - type TranslationRetrieveParams, - type TranslationUpdateParams, -} from './translations'; -export { Users } from './users/users'; +export * from './shared';; +export { Audiences, type Audience, type AudienceUpdateResponse, type AudienceListResponse, type AudienceListMembersResponse, type AudienceUpdateParams, type AudienceListParams, type AudienceListMembersParams } from './audiences';; +export { AuditEvents, type AuditEvent, type AuditEventListResponse, type AuditEventListParams } from './audit-events';; +export { Auth, type AuthIssueTokenResponse, type AuthIssueTokenParams } from './auth';; +export { Automations, type AutomationInvokeResponse, type AutomationTemplate, type AutomationTemplateListResponse, type AutomationListParams } from './automations/automations';; +export { Brands, type Brand, type BrandColors, type BrandSettings, type BrandSettingsEmail, type BrandSettingsInApp, type BrandSnippet, type BrandSnippets, type BrandTemplate, type EmailFooter, type EmailHead, type EmailHeader, type Icons, type Logo, type WidgetBackground, type BrandListResponse, type BrandCreateParams, type BrandUpdateParams, type BrandListParams } from './brands';; +export { Bulk, type InboundBulkMessage, type InboundBulkMessageUser, type BulkCreateJobResponse, type BulkListUsersResponse, type BulkRetrieveJobResponse, type BulkAddUsersParams, type BulkCreateJobParams, type BulkListUsersParams } from './bulk';; +export { Inbound, type InboundTrackEventResponse, type InboundTrackEventParams } from './inbound';; +export { Journeys, type Journey, type JourneysInvokeRequest, type JourneysInvokeResponse, type JourneysListResponse, type JourneyListParams, type JourneyInvokeParams } from './journeys';; +export { Lists, type PutSubscriptionsRecipient, type SubscriptionList, type ListListResponse, type ListUpdateParams, type ListListParams, type ListRestoreParams } from './lists/lists';; +export { Messages, type MessageDetails, type MessageRetrieveResponse, type MessageListResponse, type MessageContentResponse, type MessageHistoryResponse, type MessageListParams, type MessageHistoryParams } from './messages';; +export { Notifications, type BaseCheck, type Check, type ElementWithChecksums, type NotificationContentGetResponse, type NotificationContentMutationResponse, type NotificationContentPutRequest, type NotificationElementPutRequest, type NotificationGetContent, type NotificationLocalePutRequest, type NotificationTemplateCreateRequest, type NotificationTemplatePayload, type NotificationTemplatePublishRequest, type NotificationTemplateResponse, type NotificationTemplateState, type NotificationTemplateSummary, type NotificationTemplateUpdateRequest, type NotificationTemplateVersionListResponse, type VersionNode, type NotificationListResponse, type NotificationRetrieveContentResponse, type NotificationCreateParams, type NotificationRetrieveParams, type NotificationListParams, type NotificationListVersionsParams, type NotificationPublishParams, type NotificationPutContentParams, type NotificationPutElementParams, type NotificationPutLocaleParams, type NotificationReplaceParams, type NotificationRetrieveContentParams } from './notifications/notifications';; +export { Profiles, type SubscribeToListsRequestItem, type ProfileCreateResponse, type ProfileRetrieveResponse, type ProfileReplaceResponse, type ProfileCreateParams, type ProfileUpdateParams, type ProfileReplaceParams } from './profiles/profiles';; +export { Providers, type Provider, type ProvidersCatalogEntry, type ProviderListResponse, type ProviderCreateParams, type ProviderUpdateParams, type ProviderListParams } from './providers/providers';; +export { Requests } from './requests';; +export { RoutingStrategies, type AssociatedNotificationListResponse, type RoutingStrategyCreateRequest, type RoutingStrategyGetResponse, type RoutingStrategyListResponse, type RoutingStrategyReplaceRequest, type RoutingStrategySummary, type RoutingStrategyCreateParams, type RoutingStrategyListParams, type RoutingStrategyListNotificationsParams, type RoutingStrategyReplaceParams } from './routing-strategies';; +export { Send, type SendMessageResponse, type SendMessageParams } from './send';; +export { Tenants, type BaseTemplateTenantAssociation, type DefaultPreferences, type PostTenantTemplatePublishRequest, type PostTenantTemplatePublishResponse, type PutTenantTemplateRequest, type PutTenantTemplateResponse, type SubscriptionTopicNew, type Tenant, type TenantAssociation, type TenantTemplateInput, type TenantListResponse, type TenantListUsersResponse, type TenantUpdateParams, type TenantListParams, type TenantListUsersParams } from './tenants/tenants';; +export { Translations, type TranslationRetrieveResponse, type TranslationRetrieveParams, type TranslationUpdateParams } from './translations';; +export { Users } from './users/users';; diff --git a/src/resources/journeys.ts b/src/resources/journeys.ts index a7157480..5b8a9b01 100644 --- a/src/resources/journeys.ts +++ b/src/resources/journeys.ts @@ -14,10 +14,7 @@ export class Journeys extends APIResource { * const journeysListResponse = await client.journeys.list(); * ``` */ - list( - query: JourneyListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: JourneyListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/journeys', { query, ...options }); } @@ -35,11 +32,7 @@ export class Journeys extends APIResource { * ); * ``` */ - invoke( - templateID: string, - body: JourneyInvokeParams, - options?: RequestOptions, - ): APIPromise { + invoke(templateID: string, body: JourneyInvokeParams, options?: RequestOptions): APIPromise { return this._client.post(path`/journeys/${templateID}/invoke`, { body, ...options }); } } @@ -169,6 +162,6 @@ export declare namespace Journeys { type JourneysInvokeResponse as JourneysInvokeResponse, type JourneysListResponse as JourneysListResponse, type JourneyListParams as JourneyListParams, - type JourneyInvokeParams as JourneyInvokeParams, + type JourneyInvokeParams as JourneyInvokeParams }; } diff --git a/src/resources/lists/index.ts b/src/resources/lists/index.ts index 41a006b7..d2b5acdb 100644 --- a/src/resources/lists/index.ts +++ b/src/resources/lists/index.ts @@ -1,20 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { - Lists, - type PutSubscriptionsRecipient, - type SubscriptionList, - type ListListResponse, - type ListUpdateParams, - type ListListParams, - type ListRestoreParams, -} from './lists'; -export { - Subscriptions, - type SubscriptionListResponse, - type SubscriptionListParams, - type SubscriptionAddParams, - type SubscriptionSubscribeParams, - type SubscriptionSubscribeUserParams, - type SubscriptionUnsubscribeUserParams, -} from './subscriptions'; +export { Lists, type PutSubscriptionsRecipient, type SubscriptionList, type ListListResponse, type ListUpdateParams, type ListListParams, type ListRestoreParams } from './lists';; +export { Subscriptions, type SubscriptionListResponse, type SubscriptionListParams, type SubscriptionAddParams, type SubscriptionSubscribeParams, type SubscriptionSubscribeUserParams, type SubscriptionUnsubscribeUserParams } from './subscriptions';; diff --git a/src/resources/lists/lists.ts b/src/resources/lists/lists.ts index 3967f269..9fa5e60e 100644 --- a/src/resources/lists/lists.ts +++ b/src/resources/lists/lists.ts @@ -3,15 +3,7 @@ import { APIResource } from '../../core/resource'; import * as Shared from '../shared'; import * as SubscriptionsAPI from './subscriptions'; -import { - SubscriptionAddParams, - SubscriptionListParams, - SubscriptionListResponse, - SubscriptionSubscribeParams, - SubscriptionSubscribeUserParams, - SubscriptionUnsubscribeUserParams, - Subscriptions, -} from './subscriptions'; +import { SubscriptionAddParams, SubscriptionListParams, SubscriptionListResponse, SubscriptionSubscribeParams, SubscriptionSubscribeUserParams, SubscriptionUnsubscribeUserParams, Subscriptions } from './subscriptions'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -31,20 +23,13 @@ export class Lists extends APIResource { * Create or replace an existing list with the supplied values. */ update(listID: string, body: ListUpdateParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/lists/${listID}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.put(path`/lists/${listID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** * Returns all of the lists, with the ability to filter based on a pattern. */ - list( - query: ListListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: ListListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/lists', { query, ...options }); } @@ -52,21 +37,14 @@ export class Lists extends APIResource { * Delete a list by list ID. */ delete(listID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/lists/${listID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/lists/${listID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** * Restore a previously deleted list. */ restore(listID: string, body: ListRestoreParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/lists/${listID}/restore`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.put(path`/lists/${listID}/restore`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -113,7 +91,8 @@ export interface ListListParams { pattern?: string | null; } -export interface ListRestoreParams {} +export interface ListRestoreParams { +} Lists.Subscriptions = Subscriptions; @@ -124,7 +103,7 @@ export declare namespace Lists { type ListListResponse as ListListResponse, type ListUpdateParams as ListUpdateParams, type ListListParams as ListListParams, - type ListRestoreParams as ListRestoreParams, + type ListRestoreParams as ListRestoreParams }; export { @@ -134,6 +113,6 @@ export declare namespace Lists { type SubscriptionAddParams as SubscriptionAddParams, type SubscriptionSubscribeParams as SubscriptionSubscribeParams, type SubscriptionSubscribeUserParams as SubscriptionSubscribeUserParams, - type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams, + type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams }; } diff --git a/src/resources/lists/subscriptions.ts b/src/resources/lists/subscriptions.ts index 4878baec..a1f2573f 100644 --- a/src/resources/lists/subscriptions.ts +++ b/src/resources/lists/subscriptions.ts @@ -12,11 +12,7 @@ export class Subscriptions extends APIResource { /** * Get the list's subscriptions. */ - list( - listID: string, - query: SubscriptionListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(listID: string, query: SubscriptionListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/lists/${listID}/subscriptions`, { query, ...options }); } @@ -25,11 +21,7 @@ export class Subscriptions extends APIResource { * subscriptions. If the list does not exist, it will be automatically created. */ add(listID: string, body: SubscriptionAddParams, options?: RequestOptions): APIPromise { - return this._client.post(path`/lists/${listID}/subscriptions`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.post(path`/lists/${listID}/subscriptions`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -37,43 +29,24 @@ export class Subscriptions extends APIResource { * list does not exist, it will be automatically created. */ subscribe(listID: string, body: SubscriptionSubscribeParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/lists/${listID}/subscriptions`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.put(path`/lists/${listID}/subscriptions`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** * Subscribe a user to an existing list (note: if the List does not exist, it will * be automatically created). */ - subscribeUser( - userID: string, - params: SubscriptionSubscribeUserParams, - options?: RequestOptions, - ): APIPromise { - const { list_id, ...body } = params; - return this._client.put(path`/lists/${list_id}/subscriptions/${userID}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + subscribeUser(userID: string, params: SubscriptionSubscribeUserParams, options?: RequestOptions): APIPromise { + const { list_id, ...body } = params + return this._client.put(path`/lists/${list_id}/subscriptions/${userID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** * Delete a subscription to a list by list ID and user ID. */ - unsubscribeUser( - userID: string, - params: SubscriptionUnsubscribeUserParams, - options?: RequestOptions, - ): APIPromise { - const { list_id } = params; - return this._client.delete(path`/lists/${list_id}/subscriptions/${userID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + unsubscribeUser(userID: string, params: SubscriptionUnsubscribeUserParams, options?: RequestOptions): APIPromise { + const { list_id } = params + return this._client.delete(path`/lists/${list_id}/subscriptions/${userID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -134,6 +107,6 @@ export declare namespace Subscriptions { type SubscriptionAddParams as SubscriptionAddParams, type SubscriptionSubscribeParams as SubscriptionSubscribeParams, type SubscriptionSubscribeUserParams as SubscriptionSubscribeUserParams, - type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams, + type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams }; } diff --git a/src/resources/messages.ts b/src/resources/messages.ts index 43435ead..70ccdb3d 100644 --- a/src/resources/messages.ts +++ b/src/resources/messages.ts @@ -17,10 +17,7 @@ export class Messages extends APIResource { /** * Fetch the statuses of messages you've previously sent. */ - list( - query: MessageListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: MessageListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/messages', { query, ...options }); } @@ -45,11 +42,7 @@ export class Messages extends APIResource { /** * Fetch the array of events of a message you've previously sent. */ - history( - messageID: string, - query: MessageHistoryParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + history(messageID: string, query: MessageHistoryParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/messages/${messageID}/history`, { query, ...options }); } } @@ -85,22 +78,7 @@ export interface MessageDetails { /** * The current status of the message. */ - status: - | 'CANCELED' - | 'CLICKED' - | 'DELAYED' - | 'DELIVERED' - | 'DIGESTED' - | 'ENQUEUED' - | 'FILTERED' - | 'OPENED' - | 'ROUTED' - | 'SENT' - | 'SIMULATED' - | 'THROTTLED' - | 'UNDELIVERABLE' - | 'UNMAPPED' - | 'UNROUTABLE'; + status: 'CANCELED' | 'CLICKED' | 'DELAYED' | 'DELIVERED' | 'DIGESTED' | 'ENQUEUED' | 'FILTERED' | 'OPENED' | 'ROUTED' | 'SENT' | 'SIMULATED' | 'THROTTLED' | 'UNDELIVERABLE' | 'UNMAPPED' | 'UNROUTABLE'; /** * A UTC timestamp at which the recipient clicked on a tracked link for the first @@ -128,17 +106,7 @@ export interface MessageDetails { /** * The reason for the current status of the message. */ - reason?: - | 'BOUNCED' - | 'FAILED' - | 'FILTERED' - | 'NO_CHANNELS' - | 'NO_PROVIDERS' - | 'OPT_IN_REQUIRED' - | 'PROVIDER_ERROR' - | 'UNPUBLISHED' - | 'UNSUBSCRIBED' - | null; + reason?: 'BOUNCED' | 'FAILED' | 'FILTERED' | 'NO_CHANNELS' | 'NO_PROVIDERS' | 'OPT_IN_REQUIRED' | 'PROVIDER_ERROR' | 'UNPUBLISHED' | 'UNSUBSCRIBED' | null; /** * A UTC timestamp at which Courier passed the message to the Integration provider. @@ -340,6 +308,6 @@ export declare namespace Messages { type MessageContentResponse as MessageContentResponse, type MessageHistoryResponse as MessageHistoryResponse, type MessageListParams as MessageListParams, - type MessageHistoryParams as MessageHistoryParams, + type MessageHistoryParams as MessageHistoryParams }; } diff --git a/src/resources/notifications/checks.ts b/src/resources/notifications/checks.ts index c8d0565e..ec984fba 100644 --- a/src/resources/notifications/checks.ts +++ b/src/resources/notifications/checks.ts @@ -28,12 +28,8 @@ export class Checks extends APIResource { * ); * ``` */ - update( - submissionID: string, - params: CheckUpdateParams, - options?: RequestOptions, - ): APIPromise { - const { id, ...body } = params; + update(submissionID: string, params: CheckUpdateParams, options?: RequestOptions): APIPromise { + const { id, ...body } = params return this._client.put(path`/notifications/${id}/${submissionID}/checks`, { body, ...options }); } @@ -48,12 +44,8 @@ export class Checks extends APIResource { * ); * ``` */ - list( - submissionID: string, - params: CheckListParams, - options?: RequestOptions, - ): APIPromise { - const { id } = params; + list(submissionID: string, params: CheckListParams, options?: RequestOptions): APIPromise { + const { id } = params return this._client.get(path`/notifications/${id}/${submissionID}/checks`, options); } @@ -68,11 +60,8 @@ export class Checks extends APIResource { * ``` */ delete(submissionID: string, params: CheckDeleteParams, options?: RequestOptions): APIPromise { - const { id } = params; - return this._client.delete(path`/notifications/${id}/${submissionID}/checks`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { id } = params + return this._client.delete(path`/notifications/${id}/${submissionID}/checks`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -116,6 +105,6 @@ export declare namespace Checks { type CheckListResponse as CheckListResponse, type CheckUpdateParams as CheckUpdateParams, type CheckListParams as CheckListParams, - type CheckDeleteParams as CheckDeleteParams, + type CheckDeleteParams as CheckDeleteParams }; } diff --git a/src/resources/notifications/index.ts b/src/resources/notifications/index.ts index 7d2862b3..fdf8c291 100644 --- a/src/resources/notifications/index.ts +++ b/src/resources/notifications/index.ts @@ -1,43 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { - Checks, - type CheckUpdateResponse, - type CheckListResponse, - type CheckUpdateParams, - type CheckListParams, - type CheckDeleteParams, -} from './checks'; -export { - Notifications, - type BaseCheck, - type Check, - type ElementWithChecksums, - type NotificationContentGetResponse, - type NotificationContentMutationResponse, - type NotificationContentPutRequest, - type NotificationElementPutRequest, - type NotificationGetContent, - type NotificationLocalePutRequest, - type NotificationTemplateCreateRequest, - type NotificationTemplatePayload, - type NotificationTemplatePublishRequest, - type NotificationTemplateResponse, - type NotificationTemplateState, - type NotificationTemplateSummary, - type NotificationTemplateUpdateRequest, - type NotificationTemplateVersionListResponse, - type VersionNode, - type NotificationListResponse, - type NotificationRetrieveContentResponse, - type NotificationCreateParams, - type NotificationRetrieveParams, - type NotificationListParams, - type NotificationListVersionsParams, - type NotificationPublishParams, - type NotificationPutContentParams, - type NotificationPutElementParams, - type NotificationPutLocaleParams, - type NotificationReplaceParams, - type NotificationRetrieveContentParams, -} from './notifications'; +export { Checks, type CheckUpdateResponse, type CheckListResponse, type CheckUpdateParams, type CheckListParams, type CheckDeleteParams } from './checks';; +export { Notifications, type BaseCheck, type Check, type ElementWithChecksums, type NotificationContentGetResponse, type NotificationContentMutationResponse, type NotificationContentPutRequest, type NotificationElementPutRequest, type NotificationGetContent, type NotificationLocalePutRequest, type NotificationTemplateCreateRequest, type NotificationTemplatePayload, type NotificationTemplatePublishRequest, type NotificationTemplateResponse, type NotificationTemplateState, type NotificationTemplateSummary, type NotificationTemplateUpdateRequest, type NotificationTemplateVersionListResponse, type VersionNode, type NotificationListResponse, type NotificationRetrieveContentResponse, type NotificationCreateParams, type NotificationRetrieveParams, type NotificationListParams, type NotificationListVersionsParams, type NotificationPublishParams, type NotificationPutContentParams, type NotificationPutElementParams, type NotificationPutLocaleParams, type NotificationReplaceParams, type NotificationRetrieveContentParams } from './notifications';; diff --git a/src/resources/notifications/notifications.ts b/src/resources/notifications/notifications.ts index 94c877d9..c4992083 100644 --- a/src/resources/notifications/notifications.ts +++ b/src/resources/notifications/notifications.ts @@ -3,14 +3,7 @@ import { APIResource } from '../../core/resource'; import * as Shared from '../shared'; import * as ChecksAPI from './checks'; -import { - CheckDeleteParams, - CheckListParams, - CheckListResponse, - CheckUpdateParams, - CheckUpdateResponse, - Checks, -} from './checks'; +import { CheckDeleteParams, CheckListParams, CheckListResponse, CheckUpdateParams, CheckUpdateResponse, Checks } from './checks'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -56,11 +49,7 @@ export class Notifications extends APIResource { * await client.notifications.retrieve('id'); * ``` */ - retrieve( - id: string, - query: NotificationRetrieveParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + retrieve(id: string, query: NotificationRetrieveParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/notifications/${id}`, { query, ...options }); } @@ -72,10 +61,7 @@ export class Notifications extends APIResource { * const notifications = await client.notifications.list(); * ``` */ - list( - query: NotificationListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: NotificationListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/notifications', { query, ...options }); } @@ -88,10 +74,7 @@ export class Notifications extends APIResource { * ``` */ archive(id: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/notifications/${id}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/notifications/${id}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -103,11 +86,7 @@ export class Notifications extends APIResource { * await client.notifications.listVersions('id'); * ``` */ - listVersions( - id: string, - query: NotificationListVersionsParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + listVersions(id: string, query: NotificationListVersionsParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/notifications/${id}/versions`, { query, ...options }); } @@ -120,16 +99,8 @@ export class Notifications extends APIResource { * await client.notifications.publish('id'); * ``` */ - publish( - id: string, - body: NotificationPublishParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { - return this._client.post(path`/notifications/${id}/publish`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + publish(id: string, body: NotificationPublishParams | null | undefined = {}, options?: RequestOptions): APIPromise { + return this._client.post(path`/notifications/${id}/publish`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -149,11 +120,7 @@ export class Notifications extends APIResource { * }); * ``` */ - putContent( - id: string, - body: NotificationPutContentParams, - options?: RequestOptions, - ): APIPromise { + putContent(id: string, body: NotificationPutContentParams, options?: RequestOptions): APIPromise { return this._client.put(path`/notifications/${id}/content`, { body, ...options }); } @@ -172,12 +139,8 @@ export class Notifications extends APIResource { * }); * ``` */ - putElement( - elementID: string, - params: NotificationPutElementParams, - options?: RequestOptions, - ): APIPromise { - const { id, ...body } = params; + putElement(elementID: string, params: NotificationPutElementParams, options?: RequestOptions): APIPromise { + const { id, ...body } = params return this._client.put(path`/notifications/${id}/elements/${elementID}`, { body, ...options }); } @@ -199,12 +162,8 @@ export class Notifications extends APIResource { * }); * ``` */ - putLocale( - localeID: string, - params: NotificationPutLocaleParams, - options?: RequestOptions, - ): APIPromise { - const { id, ...body } = params; + putLocale(localeID: string, params: NotificationPutLocaleParams, options?: RequestOptions): APIPromise { + const { id, ...body } = params return this._client.put(path`/notifications/${id}/locales/${localeID}`, { body, ...options }); } @@ -230,11 +189,7 @@ export class Notifications extends APIResource { * }); * ``` */ - replace( - id: string, - body: NotificationReplaceParams, - options?: RequestOptions, - ): APIPromise { + replace(id: string, body: NotificationReplaceParams, options?: RequestOptions): APIPromise { return this._client.put(path`/notifications/${id}`, { body, ...options }); } @@ -251,11 +206,7 @@ export class Notifications extends APIResource { * ); * ``` */ - retrieveContent( - id: string, - query: NotificationRetrieveContentParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + retrieveContent(id: string, query: NotificationRetrieveContentParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/notifications/${id}/content`, { query, ...options }); } } @@ -299,7 +250,7 @@ export interface ElementWithChecksums { */ locales?: { [key: string]: ElementWithChecksums.Locales }; - [k: string]: unknown; +[k: string]: unknown } export namespace ElementWithChecksums { @@ -408,7 +359,7 @@ export interface NotificationElementPutRequest { */ state?: NotificationTemplateState; - [k: string]: unknown; +[k: string]: unknown } export interface NotificationGetContent { @@ -500,7 +451,7 @@ export namespace NotificationLocalePutRequest { */ id: string; - [k: string]: unknown; + [k: string]: unknown } } @@ -630,7 +581,7 @@ export interface NotificationTemplateResponse extends NotificationTemplatePayloa /** * Template state. Defaults to `DRAFT`. */ -export type NotificationTemplateState = 'DRAFT' | 'PUBLISHED'; +export type NotificationTemplateState = 'DRAFT' | 'PUBLISHED' /** * V2 (CDS) template summary returned in list responses. @@ -767,7 +718,7 @@ export namespace NotificationListResponse { * Elemental content response for V2 templates. Contains versioned elements with * content checksums. */ -export type NotificationRetrieveContentResponse = NotificationContentGetResponse | NotificationGetContent; +export type NotificationRetrieveContentResponse = NotificationContentGetResponse | NotificationGetContent export interface NotificationCreateParams { /** @@ -895,7 +846,7 @@ export interface NotificationPutElementParams { */ state?: NotificationTemplateState; - [k: string]: unknown; +[k: string]: unknown } export interface NotificationPutLocaleParams { @@ -922,7 +873,7 @@ export namespace NotificationPutLocaleParams { */ id: string; - [k: string]: unknown; + [k: string]: unknown } } @@ -981,7 +932,7 @@ export declare namespace Notifications { type NotificationPutElementParams as NotificationPutElementParams, type NotificationPutLocaleParams as NotificationPutLocaleParams, type NotificationReplaceParams as NotificationReplaceParams, - type NotificationRetrieveContentParams as NotificationRetrieveContentParams, + type NotificationRetrieveContentParams as NotificationRetrieveContentParams }; export { @@ -990,6 +941,6 @@ export declare namespace Notifications { type CheckListResponse as CheckListResponse, type CheckUpdateParams as CheckUpdateParams, type CheckListParams as CheckListParams, - type CheckDeleteParams as CheckDeleteParams, + type CheckDeleteParams as CheckDeleteParams }; } diff --git a/src/resources/profiles/index.ts b/src/resources/profiles/index.ts index 87a750c4..27e208ba 100644 --- a/src/resources/profiles/index.ts +++ b/src/resources/profiles/index.ts @@ -1,20 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { - Lists, - type ListRetrieveResponse, - type ListDeleteResponse, - type ListSubscribeResponse, - type ListRetrieveParams, - type ListSubscribeParams, -} from './lists'; -export { - Profiles, - type SubscribeToListsRequestItem, - type ProfileCreateResponse, - type ProfileRetrieveResponse, - type ProfileReplaceResponse, - type ProfileCreateParams, - type ProfileUpdateParams, - type ProfileReplaceParams, -} from './profiles'; +export { Lists, type ListRetrieveResponse, type ListDeleteResponse, type ListSubscribeResponse, type ListRetrieveParams, type ListSubscribeParams } from './lists';; +export { Profiles, type SubscribeToListsRequestItem, type ProfileCreateResponse, type ProfileRetrieveResponse, type ProfileReplaceResponse, type ProfileCreateParams, type ProfileUpdateParams, type ProfileReplaceParams } from './profiles';; diff --git a/src/resources/profiles/lists.ts b/src/resources/profiles/lists.ts index bc21195f..7659b38f 100644 --- a/src/resources/profiles/lists.ts +++ b/src/resources/profiles/lists.ts @@ -11,11 +11,7 @@ export class Lists extends APIResource { /** * Returns the subscribed lists for a specified user. */ - retrieve( - userID: string, - query: ListRetrieveParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + retrieve(userID: string, query: ListRetrieveParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/profiles/${userID}/lists`, { query, ...options }); } @@ -30,11 +26,7 @@ export class Lists extends APIResource { * Subscribes the given user to one or more lists. If the list does not exist, it * will be created. */ - subscribe( - userID: string, - body: ListSubscribeParams, - options?: RequestOptions, - ): APIPromise { + subscribe(userID: string, body: ListSubscribeParams, options?: RequestOptions): APIPromise { return this._client.post(path`/profiles/${userID}/lists`, { body, ...options }); } } @@ -98,6 +90,6 @@ export declare namespace Lists { type ListDeleteResponse as ListDeleteResponse, type ListSubscribeResponse as ListSubscribeResponse, type ListRetrieveParams as ListRetrieveParams, - type ListSubscribeParams as ListSubscribeParams, + type ListSubscribeParams as ListSubscribeParams }; } diff --git a/src/resources/profiles/profiles.ts b/src/resources/profiles/profiles.ts index 358fae68..8fd58739 100644 --- a/src/resources/profiles/profiles.ts +++ b/src/resources/profiles/profiles.ts @@ -3,14 +3,7 @@ import { APIResource } from '../../core/resource'; import * as Shared from '../shared'; import * as ListsAPI from './lists'; -import { - ListDeleteResponse, - ListRetrieveParams, - ListRetrieveResponse, - ListSubscribeParams, - ListSubscribeResponse, - Lists, -} from './lists'; +import { ListDeleteResponse, ListRetrieveParams, ListRetrieveResponse, ListSubscribeParams, ListSubscribeResponse, Lists } from './lists'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -23,11 +16,7 @@ export class Profiles extends APIResource { * Merge the supplied values with an existing profile or create a new profile if * one doesn't already exist. */ - create( - userID: string, - body: ProfileCreateParams, - options?: RequestOptions, - ): APIPromise { + create(userID: string, body: ProfileCreateParams, options?: RequestOptions): APIPromise { return this._client.post(path`/profiles/${userID}`, { body, ...options }); } @@ -42,21 +31,14 @@ export class Profiles extends APIResource { * Update a profile */ update(userID: string, body: ProfileUpdateParams, options?: RequestOptions): APIPromise { - return this._client.patch(path`/profiles/${userID}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.patch(path`/profiles/${userID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** * Deletes the specified user profile. */ delete(userID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/profiles/${userID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/profiles/${userID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -66,11 +48,7 @@ export class Profiles extends APIResource { * `PUT` update is a full replacement of the data. For partial updates, use the * [Patch](https://www.courier.com/docs/reference/profiles/patch/) request. */ - replace( - userID: string, - body: ProfileReplaceParams, - options?: RequestOptions, - ): APIPromise { + replace(userID: string, body: ProfileReplaceParams, options?: RequestOptions): APIPromise { return this._client.put(path`/profiles/${userID}`, { body, ...options }); } } @@ -139,7 +117,7 @@ export declare namespace Profiles { type ProfileReplaceResponse as ProfileReplaceResponse, type ProfileCreateParams as ProfileCreateParams, type ProfileUpdateParams as ProfileUpdateParams, - type ProfileReplaceParams as ProfileReplaceParams, + type ProfileReplaceParams as ProfileReplaceParams }; export { @@ -148,6 +126,6 @@ export declare namespace Profiles { type ListDeleteResponse as ListDeleteResponse, type ListSubscribeResponse as ListSubscribeResponse, type ListRetrieveParams as ListRetrieveParams, - type ListSubscribeParams as ListSubscribeParams, + type ListSubscribeParams as ListSubscribeParams }; } diff --git a/src/resources/providers/catalog.ts b/src/resources/providers/catalog.ts index b49b5b0a..7536dcb7 100644 --- a/src/resources/providers/catalog.ts +++ b/src/resources/providers/catalog.ts @@ -13,10 +13,7 @@ export class Catalog extends APIResource { * `required`). Providers with no configurable schema return only `provider`, * `name`, and `description`. */ - list( - query: CatalogListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: CatalogListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/providers/catalog', { query, ...options }); } } @@ -49,5 +46,8 @@ export interface CatalogListParams { } export declare namespace Catalog { - export { type CatalogListResponse as CatalogListResponse, type CatalogListParams as CatalogListParams }; + export { + type CatalogListResponse as CatalogListResponse, + type CatalogListParams as CatalogListParams + }; } diff --git a/src/resources/providers/index.ts b/src/resources/providers/index.ts index 48625736..f3963617 100644 --- a/src/resources/providers/index.ts +++ b/src/resources/providers/index.ts @@ -1,12 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Catalog, type CatalogListResponse, type CatalogListParams } from './catalog'; -export { - Providers, - type Provider, - type ProvidersCatalogEntry, - type ProviderListResponse, - type ProviderCreateParams, - type ProviderUpdateParams, - type ProviderListParams, -} from './providers'; +export { Catalog, type CatalogListResponse, type CatalogListParams } from './catalog';; +export { Providers, type Provider, type ProvidersCatalogEntry, type ProviderListResponse, type ProviderCreateParams, type ProviderUpdateParams, type ProviderListParams } from './providers';; diff --git a/src/resources/providers/providers.ts b/src/resources/providers/providers.ts index 4c649aa2..19be01e2 100644 --- a/src/resources/providers/providers.ts +++ b/src/resources/providers/providers.ts @@ -42,10 +42,7 @@ export class Providers extends APIResource { * List configured provider integrations for the current workspace. Supports * cursor-based pagination. */ - list( - query: ProviderListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: ProviderListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/providers', { query, ...options }); } @@ -54,10 +51,7 @@ export class Providers extends APIResource { * by routing or notifications. */ delete(id: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/providers/${id}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/providers/${id}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -232,12 +226,12 @@ export declare namespace Providers { type ProviderListResponse as ProviderListResponse, type ProviderCreateParams as ProviderCreateParams, type ProviderUpdateParams as ProviderUpdateParams, - type ProviderListParams as ProviderListParams, + type ProviderListParams as ProviderListParams }; export { Catalog as Catalog, type CatalogListResponse as CatalogListResponse, - type CatalogListParams as CatalogListParams, + type CatalogListParams as CatalogListParams }; } diff --git a/src/resources/requests.ts b/src/resources/requests.ts index 7c287eea..130198ab 100644 --- a/src/resources/requests.ts +++ b/src/resources/requests.ts @@ -11,9 +11,6 @@ export class Requests extends APIResource { * Archive message */ archive(requestID: string, options?: RequestOptions): APIPromise { - return this._client.put(path`/requests/${requestID}/archive`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.put(path`/requests/${requestID}/archive`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } diff --git a/src/resources/routing-strategies.ts b/src/resources/routing-strategies.ts index 35593c32..cfdc9067 100644 --- a/src/resources/routing-strategies.ts +++ b/src/resources/routing-strategies.ts @@ -27,10 +27,7 @@ export class RoutingStrategies extends APIResource { * }); * ``` */ - create( - body: RoutingStrategyCreateParams, - options?: RequestOptions, - ): APIPromise { + create(body: RoutingStrategyCreateParams, options?: RequestOptions): APIPromise { return this._client.post('/routing-strategies', { body, ...options }); } @@ -59,10 +56,7 @@ export class RoutingStrategies extends APIResource { * await client.routingStrategies.list(); * ``` */ - list( - query: RoutingStrategyListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: RoutingStrategyListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/routing-strategies', { query, ...options }); } @@ -76,10 +70,7 @@ export class RoutingStrategies extends APIResource { * ``` */ archive(id: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/routing-strategies/${id}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/routing-strategies/${id}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -92,11 +83,7 @@ export class RoutingStrategies extends APIResource { * await client.routingStrategies.listNotifications('id'); * ``` */ - listNotifications( - id: string, - query: RoutingStrategyListNotificationsParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + listNotifications(id: string, query: RoutingStrategyListNotificationsParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/routing-strategies/${id}/notifications`, { query, ...options }); } @@ -117,11 +104,7 @@ export class RoutingStrategies extends APIResource { * }); * ``` */ - replace( - id: string, - body: RoutingStrategyReplaceParams, - options?: RequestOptions, - ): APIPromise { + replace(id: string, body: RoutingStrategyReplaceParams, options?: RequestOptions): APIPromise { return this._client.put(path`/routing-strategies/${id}`, { body, ...options }); } } @@ -420,6 +403,6 @@ export declare namespace RoutingStrategies { type RoutingStrategyCreateParams as RoutingStrategyCreateParams, type RoutingStrategyListParams as RoutingStrategyListParams, type RoutingStrategyListNotificationsParams as RoutingStrategyListNotificationsParams, - type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams, + type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams }; } diff --git a/src/resources/send.ts b/src/resources/send.ts index bc35c9f5..4bb59203 100644 --- a/src/resources/send.ts +++ b/src/resources/send.ts @@ -89,26 +89,7 @@ export namespace SendMessageParams { /** * The recipient or a list of recipients of the message */ - to?: - | Shared.UserRecipient - | Shared.AudienceRecipient - | Shared.ListRecipient - | Shared.ListPatternRecipient - | Shared.SlackRecipient - | Shared.MsTeamsRecipient - | Shared.PagerdutyRecipient - | Shared.WebhookRecipient - | Array< - | Shared.UserRecipient - | Shared.AudienceRecipient - | Shared.ListRecipient - | Shared.ListPatternRecipient - | Shared.SlackRecipient - | Shared.MsTeamsRecipient - | Shared.PagerdutyRecipient - | Shared.WebhookRecipient - > - | null; + to?: Shared.UserRecipient | Shared.AudienceRecipient | Shared.ListRecipient | Shared.ListPatternRecipient | Shared.SlackRecipient | Shared.MsTeamsRecipient | Shared.PagerdutyRecipient | Shared.WebhookRecipient | Array | null; } export namespace Message { @@ -187,5 +168,8 @@ export namespace SendMessageParams { } export declare namespace Send { - export { type SendMessageResponse as SendMessageResponse, type SendMessageParams as SendMessageParams }; + export { + type SendMessageResponse as SendMessageResponse, + type SendMessageParams as SendMessageParams + }; } diff --git a/src/resources/shared.ts b/src/resources/shared.ts index 26816586..41642f30 100644 --- a/src/resources/shared.ts +++ b/src/resources/shared.ts @@ -12,7 +12,7 @@ export interface AirshipProfileAudience { named_user: string; } -export type Alignment = 'center' | 'left' | 'right' | 'full'; +export type Alignment = 'center' | 'left' | 'right' | 'full' export interface AudienceFilter { /** @@ -81,7 +81,7 @@ export interface Channel { timeouts?: Timeouts | null; } -export type ChannelClassification = 'direct_message' | 'email' | 'push' | 'sms' | 'webhook' | 'inbox'; +export type ChannelClassification = 'direct_message' | 'email' | 'push' | 'sms' | 'webhook' | 'inbox' export interface ChannelMetadata { utm?: Utm | null; @@ -91,9 +91,9 @@ export interface ChannelPreference { channel: ChannelClassification; } -export type DeviceType = string; +export type DeviceType = string -export type Discord = SendToChannel | SendDirectMessage; +export type Discord = SendToChannel | SendDirectMessage export interface ElementalActionNodeWithType extends ElementalBaseNode { type?: 'action'; @@ -203,15 +203,7 @@ export interface ElementalMetaNodeWithType extends ElementalBaseNode { * [control flow docs](https://www.courier.com/docs/platform/content/elemental/control-flow/) * for more details. */ -export type ElementalNode = - | ElementalTextNodeWithType - | ElementalMetaNodeWithType - | ElementalChannelNodeWithType - | ElementalImageNodeWithType - | ElementalActionNodeWithType - | ElementalDividerNodeWithType - | ElementalQuoteNodeWithType - | ElementalHTMLNodeWithType; +export type ElementalNode = ElementalTextNodeWithType | ElementalMetaNodeWithType | ElementalChannelNodeWithType | ElementalImageNodeWithType | ElementalActionNodeWithType | ElementalDividerNodeWithType | ElementalQuoteNodeWithType | ElementalHTMLNodeWithType export interface ElementalQuoteNodeWithType extends ElementalBaseNode { type?: 'quote'; @@ -221,7 +213,7 @@ export interface ElementalTextNodeWithType extends ElementalBaseNode { type?: 'text'; } -export type Expo = Token | MultipleTokens; +export type Expo = Token | MultipleTokens /** * A filter rule that can be either a single condition (with path/value) or a @@ -296,7 +288,7 @@ export interface ListRecipient { list_id?: string | null; } -export type MessageChannels = { [key: string]: Channel }; +export type MessageChannels = { [key: string]: Channel } export interface MessageContext { /** @@ -305,7 +297,7 @@ export interface MessageContext { tenant_id?: string | null; } -export type MessageProviders = { [key: string]: MessageProvidersType }; +export type MessageProviders = { [key: string]: MessageProvidersType } export interface MessageProvidersType { /** @@ -329,18 +321,13 @@ export interface MessageRouting { method: 'all' | 'single'; } -export type MessageRoutingChannel = string | MessageRouting; +export type MessageRoutingChannel = string | MessageRouting export interface Metadata { utm?: Utm | null; } -export type MsTeams = - | SendToMsTeamsUserID - | SendToMsTeamsEmail - | SendToMsTeamsChannelID - | SendToMsTeamsConversationID - | SendToMsTeamsChannelName; +export type MsTeams = SendToMsTeamsUserID | SendToMsTeamsEmail | SendToMsTeamsChannelID | SendToMsTeamsConversationID | SendToMsTeamsChannelName export interface MsTeamsBaseProperties { service_url: string; @@ -400,7 +387,7 @@ export interface Preference { source?: 'subscription' | 'list' | 'recipient' | null; } -export type PreferenceStatus = 'OPTED_IN' | 'OPTED_OUT' | 'REQUIRED'; +export type PreferenceStatus = 'OPTED_IN' | 'OPTED_OUT' | 'REQUIRED' export interface RecipientPreferences { categories?: { [key: string]: NotificationPreferenceDetails } | null; @@ -482,7 +469,7 @@ export interface SendToSlackUserID { user_id: string; } -export type Slack = SendToSlackChannel | SendToSlackEmail | SendToSlackUserID; +export type Slack = SendToSlackChannel | SendToSlackEmail | SendToSlackUserID export interface SlackBaseProperties { access_token: string; @@ -495,7 +482,7 @@ export interface SlackRecipient { slack: Slack; } -export type TextStyle = 'text' | 'h1' | 'h2' | 'subtext'; +export type TextStyle = 'text' | 'h1' | 'h2' | 'subtext' export interface Timeouts { channel?: number | null; @@ -591,7 +578,7 @@ export namespace UserProfile { } } -export type UserProfileFirebaseToken = string | Array; +export type UserProfileFirebaseToken = string | Array export interface UserRecipient { /** @@ -662,7 +649,7 @@ export interface Utm { term?: string | null; } -export type WebhookAuthMode = 'none' | 'basic' | 'bearer'; +export type WebhookAuthMode = 'none' | 'basic' | 'bearer' export interface WebhookAuthentication { /** @@ -686,7 +673,7 @@ export interface WebhookAuthentication { username?: string | null; } -export type WebhookMethod = 'POST' | 'PUT'; +export type WebhookMethod = 'POST' | 'PUT' export interface WebhookProfile { /** @@ -717,7 +704,7 @@ export interface WebhookProfile { profile?: WebhookProfileType | null; } -export type WebhookProfileType = 'limited' | 'expanded'; +export type WebhookProfileType = 'limited' | 'expanded' /** * Send via webhook diff --git a/src/resources/tenants/index.ts b/src/resources/tenants/index.ts index c5216c97..85927059 100644 --- a/src/resources/tenants/index.ts +++ b/src/resources/tenants/index.ts @@ -1,29 +1,5 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Preferences } from './preferences/index'; -export { - Templates, - type TemplateListResponse, - type TemplateRetrieveParams, - type TemplateListParams, - type TemplatePublishParams, - type TemplateReplaceParams, -} from './templates/index'; -export { - Tenants, - type BaseTemplateTenantAssociation, - type DefaultPreferences, - type PostTenantTemplatePublishRequest, - type PostTenantTemplatePublishResponse, - type PutTenantTemplateRequest, - type PutTenantTemplateResponse, - type SubscriptionTopicNew, - type Tenant, - type TenantAssociation, - type TenantTemplateInput, - type TenantListResponse, - type TenantListUsersResponse, - type TenantUpdateParams, - type TenantListParams, - type TenantListUsersParams, -} from './tenants'; +export { Preferences } from './preferences/index';; +export { Templates, type TemplateListResponse, type TemplateRetrieveParams, type TemplateListParams, type TemplatePublishParams, type TemplateReplaceParams } from './templates/index';; +export { Tenants, type BaseTemplateTenantAssociation, type DefaultPreferences, type PostTenantTemplatePublishRequest, type PostTenantTemplatePublishResponse, type PutTenantTemplateRequest, type PutTenantTemplateResponse, type SubscriptionTopicNew, type Tenant, type TenantAssociation, type TenantTemplateInput, type TenantListResponse, type TenantListUsersResponse, type TenantUpdateParams, type TenantListParams, type TenantListUsersParams } from './tenants';; diff --git a/src/resources/tenants/preferences/index.ts b/src/resources/tenants/preferences/index.ts index 9fe5bafc..4f64a618 100644 --- a/src/resources/tenants/preferences/index.ts +++ b/src/resources/tenants/preferences/index.ts @@ -1,4 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Items, type ItemUpdateParams, type ItemDeleteParams } from './items'; -export { Preferences } from './preferences'; +export { Items, type ItemUpdateParams, type ItemDeleteParams } from './items';; +export { Preferences } from './preferences';; diff --git a/src/resources/tenants/preferences/items.ts b/src/resources/tenants/preferences/items.ts index 5b93e99e..4ff3d429 100644 --- a/src/resources/tenants/preferences/items.ts +++ b/src/resources/tenants/preferences/items.ts @@ -22,12 +22,8 @@ export class Items extends APIResource { * ``` */ update(topicID: string, params: ItemUpdateParams, options?: RequestOptions): APIPromise { - const { tenant_id, ...body } = params; - return this._client.put(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { tenant_id, ...body } = params + return this._client.put(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -41,11 +37,8 @@ export class Items extends APIResource { * ``` */ delete(topicID: string, params: ItemDeleteParams, options?: RequestOptions): APIPromise { - const { tenant_id } = params; - return this._client.delete(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { tenant_id } = params + return this._client.delete(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -82,5 +75,8 @@ export interface ItemDeleteParams { } export declare namespace Items { - export { type ItemUpdateParams as ItemUpdateParams, type ItemDeleteParams as ItemDeleteParams }; + export { + type ItemUpdateParams as ItemUpdateParams, + type ItemDeleteParams as ItemDeleteParams + }; } diff --git a/src/resources/tenants/preferences/preferences.ts b/src/resources/tenants/preferences/preferences.ts index 231183c6..573c76c2 100644 --- a/src/resources/tenants/preferences/preferences.ts +++ b/src/resources/tenants/preferences/preferences.ts @@ -14,6 +14,6 @@ export declare namespace Preferences { export { Items as Items, type ItemUpdateParams as ItemUpdateParams, - type ItemDeleteParams as ItemDeleteParams, + type ItemDeleteParams as ItemDeleteParams }; } diff --git a/src/resources/tenants/templates/index.ts b/src/resources/tenants/templates/index.ts index d4f43150..0417b524 100644 --- a/src/resources/tenants/templates/index.ts +++ b/src/resources/tenants/templates/index.ts @@ -1,11 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { - Templates, - type TemplateListResponse, - type TemplateRetrieveParams, - type TemplateListParams, - type TemplatePublishParams, - type TemplateReplaceParams, -} from './templates'; -export { Versions, type VersionRetrieveParams } from './versions'; +export { Templates, type TemplateListResponse, type TemplateRetrieveParams, type TemplateListParams, type TemplatePublishParams, type TemplateReplaceParams } from './templates';; +export { Versions, type VersionRetrieveParams } from './versions';; diff --git a/src/resources/tenants/templates/templates.ts b/src/resources/tenants/templates/templates.ts index 52e39d5b..172aaaa7 100644 --- a/src/resources/tenants/templates/templates.ts +++ b/src/resources/tenants/templates/templates.ts @@ -23,12 +23,8 @@ export class Templates extends APIResource { * }); * ``` */ - retrieve( - templateID: string, - params: TemplateRetrieveParams, - options?: RequestOptions, - ): APIPromise { - const { tenant_id } = params; + retrieve(templateID: string, params: TemplateRetrieveParams, options?: RequestOptions): APIPromise { + const { tenant_id } = params return this._client.get(path`/tenants/${tenant_id}/templates/${templateID}`, options); } @@ -42,11 +38,7 @@ export class Templates extends APIResource { * ); * ``` */ - list( - tenantID: string, - query: TemplateListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(tenantID: string, query: TemplateListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/tenants/${tenantID}/templates`, { query, ...options }); } @@ -64,16 +56,9 @@ export class Templates extends APIResource { * }); * ``` */ - publish( - templateID: string, - params: TemplatePublishParams, - options?: RequestOptions, - ): APIPromise { - const { tenant_id, ...body } = params; - return this._client.post(path`/tenants/${tenant_id}/templates/${templateID}/publish`, { - body, - ...options, - }); + publish(templateID: string, params: TemplatePublishParams, options?: RequestOptions): APIPromise { + const { tenant_id, ...body } = params + return this._client.post(path`/tenants/${tenant_id}/templates/${templateID}/publish`, { body, ...options }); } /** @@ -96,12 +81,8 @@ export class Templates extends APIResource { * }); * ``` */ - replace( - templateID: string, - params: TemplateReplaceParams, - options?: RequestOptions, - ): APIPromise { - const { tenant_id, ...body } = params; + replace(templateID: string, params: TemplateReplaceParams, options?: RequestOptions): APIPromise { + const { tenant_id, ...body } = params return this._client.put(path`/tenants/${tenant_id}/templates/${templateID}`, { body, ...options }); } } @@ -215,8 +196,11 @@ export declare namespace Templates { type TemplateRetrieveParams as TemplateRetrieveParams, type TemplateListParams as TemplateListParams, type TemplatePublishParams as TemplatePublishParams, - type TemplateReplaceParams as TemplateReplaceParams, + type TemplateReplaceParams as TemplateReplaceParams }; - export { Versions as Versions, type VersionRetrieveParams as VersionRetrieveParams }; + export { + Versions as Versions, + type VersionRetrieveParams as VersionRetrieveParams + }; } diff --git a/src/resources/tenants/templates/versions.ts b/src/resources/tenants/templates/versions.ts index 62a07d6d..a0891111 100644 --- a/src/resources/tenants/templates/versions.ts +++ b/src/resources/tenants/templates/versions.ts @@ -25,16 +25,9 @@ export class Versions extends APIResource { * ); * ``` */ - retrieve( - version: string, - params: VersionRetrieveParams, - options?: RequestOptions, - ): APIPromise { - const { tenant_id, template_id } = params; - return this._client.get( - path`/tenants/${tenant_id}/templates/${template_id}/versions/${version}`, - options, - ); + retrieve(version: string, params: VersionRetrieveParams, options?: RequestOptions): APIPromise { + const { tenant_id, template_id } = params + return this._client.get(path`/tenants/${tenant_id}/templates/${template_id}/versions/${version}`, options); } } @@ -51,5 +44,7 @@ export interface VersionRetrieveParams { } export declare namespace Versions { - export { type VersionRetrieveParams as VersionRetrieveParams }; + export { + type VersionRetrieveParams as VersionRetrieveParams + }; } diff --git a/src/resources/tenants/tenants.ts b/src/resources/tenants/tenants.ts index 75aa7b31..48c28484 100644 --- a/src/resources/tenants/tenants.ts +++ b/src/resources/tenants/tenants.ts @@ -6,14 +6,7 @@ import * as Shared from '../shared'; import * as PreferencesAPI from './preferences/preferences'; import { Preferences } from './preferences/preferences'; import * as TemplatesAPI from './templates/templates'; -import { - TemplateListParams, - TemplateListResponse, - TemplatePublishParams, - TemplateReplaceParams, - TemplateRetrieveParams, - Templates, -} from './templates/templates'; +import { TemplateListParams, TemplateListResponse, TemplatePublishParams, TemplateReplaceParams, TemplateRetrieveParams, Templates } from './templates/templates'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -57,10 +50,7 @@ export class Tenants extends APIResource { * const tenants = await client.tenants.list(); * ``` */ - list( - query: TenantListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(query: TenantListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get('/tenants', { query, ...options }); } @@ -73,10 +63,7 @@ export class Tenants extends APIResource { * ``` */ delete(tenantID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/tenants/${tenantID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/tenants/${tenantID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -89,11 +76,7 @@ export class Tenants extends APIResource { * ); * ``` */ - listUsers( - tenantID: string, - query: TenantListUsersParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + listUsers(tenantID: string, query: TenantListUsersParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/tenants/${tenantID}/users`, { query, ...options }); } } @@ -453,10 +436,12 @@ export declare namespace Tenants { type TenantListUsersResponse as TenantListUsersResponse, type TenantUpdateParams as TenantUpdateParams, type TenantListParams as TenantListParams, - type TenantListUsersParams as TenantListUsersParams, + type TenantListUsersParams as TenantListUsersParams }; - export { Preferences as Preferences }; + export { + Preferences as Preferences + }; export { Templates as Templates, @@ -464,6 +449,6 @@ export declare namespace Tenants { type TemplateRetrieveParams as TemplateRetrieveParams, type TemplateListParams as TemplateListParams, type TemplatePublishParams as TemplatePublishParams, - type TemplateReplaceParams as TemplateReplaceParams, + type TemplateReplaceParams as TemplateReplaceParams }; } diff --git a/src/resources/translations.ts b/src/resources/translations.ts index ac89f265..4a3d015a 100644 --- a/src/resources/translations.ts +++ b/src/resources/translations.ts @@ -11,7 +11,7 @@ export class Translations extends APIResource { * Get translations by locale */ retrieve(locale: string, params: TranslationRetrieveParams, options?: RequestOptions): APIPromise { - const { domain } = params; + const { domain } = params return this._client.get(path`/translations/${domain}/${locale}`, options); } @@ -19,16 +19,12 @@ export class Translations extends APIResource { * Update a translation */ update(locale: string, params: TranslationUpdateParams, options?: RequestOptions): APIPromise { - const { domain, body } = params; - return this._client.put(path`/translations/${domain}/${locale}`, { - body: body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { domain, body } = params + return this._client.put(path`/translations/${domain}/${locale}`, { body: body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } -export type TranslationRetrieveResponse = string; +export type TranslationRetrieveResponse = string export interface TranslationRetrieveParams { /** @@ -55,6 +51,6 @@ export declare namespace Translations { export { type TranslationRetrieveResponse as TranslationRetrieveResponse, type TranslationRetrieveParams as TranslationRetrieveParams, - type TranslationUpdateParams as TranslationUpdateParams, + type TranslationUpdateParams as TranslationUpdateParams }; } diff --git a/src/resources/users/index.ts b/src/resources/users/index.ts index c654207f..dd5b467f 100644 --- a/src/resources/users/index.ts +++ b/src/resources/users/index.ts @@ -1,31 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { - Preferences, - type TopicPreference, - type PreferenceRetrieveResponse, - type PreferenceRetrieveTopicResponse, - type PreferenceUpdateOrCreateTopicResponse, - type PreferenceRetrieveParams, - type PreferenceRetrieveTopicParams, - type PreferenceUpdateOrCreateTopicParams, -} from './preferences'; -export { - Tenants, - type TenantListResponse, - type TenantListParams, - type TenantAddMultipleParams, - type TenantAddSingleParams, - type TenantRemoveSingleParams, -} from './tenants'; -export { - Tokens, - type UserToken, - type TokenRetrieveResponse, - type TokenListResponse, - type TokenRetrieveParams, - type TokenUpdateParams, - type TokenDeleteParams, - type TokenAddSingleParams, -} from './tokens'; -export { Users } from './users'; +export { Preferences, type TopicPreference, type PreferenceRetrieveResponse, type PreferenceRetrieveTopicResponse, type PreferenceUpdateOrCreateTopicResponse, type PreferenceRetrieveParams, type PreferenceRetrieveTopicParams, type PreferenceUpdateOrCreateTopicParams } from './preferences';; +export { Tenants, type TenantListResponse, type TenantListParams, type TenantAddMultipleParams, type TenantAddSingleParams, type TenantRemoveSingleParams } from './tenants';; +export { Tokens, type UserToken, type TokenRetrieveResponse, type TokenListResponse, type TokenRetrieveParams, type TokenUpdateParams, type TokenDeleteParams, type TokenAddSingleParams } from './tokens';; +export { Users } from './users';; diff --git a/src/resources/users/preferences.ts b/src/resources/users/preferences.ts index 223d96ba..24a671da 100644 --- a/src/resources/users/preferences.ts +++ b/src/resources/users/preferences.ts @@ -17,11 +17,7 @@ export class Preferences extends APIResource { * ); * ``` */ - retrieve( - userID: string, - query: PreferenceRetrieveParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + retrieve(userID: string, query: PreferenceRetrieveParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/users/${userID}/preferences`, { query, ...options }); } @@ -36,12 +32,8 @@ export class Preferences extends APIResource { * }); * ``` */ - retrieveTopic( - topicID: string, - params: PreferenceRetrieveTopicParams, - options?: RequestOptions, - ): APIPromise { - const { user_id, ...query } = params; + retrieveTopic(topicID: string, params: PreferenceRetrieveTopicParams, options?: RequestOptions): APIPromise { + const { user_id, ...query } = params return this._client.get(path`/users/${user_id}/preferences/${topicID}`, { query, ...options }); } @@ -64,17 +56,9 @@ export class Preferences extends APIResource { * ); * ``` */ - updateOrCreateTopic( - topicID: string, - params: PreferenceUpdateOrCreateTopicParams, - options?: RequestOptions, - ): APIPromise { - const { user_id, tenant_id, ...body } = params; - return this._client.put(path`/users/${user_id}/preferences/${topicID}`, { - query: { tenant_id }, - body, - ...options, - }); + updateOrCreateTopic(topicID: string, params: PreferenceUpdateOrCreateTopicParams, options?: RequestOptions): APIPromise { + const { user_id, tenant_id, ...body } = params + return this._client.put(path`/users/${user_id}/preferences/${topicID}`, { query: { tenant_id }, body, ...options }); } } @@ -174,6 +158,6 @@ export declare namespace Preferences { type PreferenceUpdateOrCreateTopicResponse as PreferenceUpdateOrCreateTopicResponse, type PreferenceRetrieveParams as PreferenceRetrieveParams, type PreferenceRetrieveTopicParams as PreferenceRetrieveTopicParams, - type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams, + type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams }; } diff --git a/src/resources/users/tenants.ts b/src/resources/users/tenants.ts index b68b7e02..520a66aa 100644 --- a/src/resources/users/tenants.ts +++ b/src/resources/users/tenants.ts @@ -16,11 +16,7 @@ export class Tenants extends APIResource { * const tenants = await client.users.tenants.list('user_id'); * ``` */ - list( - userID: string, - query: TenantListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { + list(userID: string, query: TenantListParams | null | undefined = {}, options?: RequestOptions): APIPromise { return this._client.get(path`/users/${userID}/tenants`, { query, ...options }); } @@ -37,11 +33,7 @@ export class Tenants extends APIResource { * ``` */ addMultiple(userID: string, body: TenantAddMultipleParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/users/${userID}/tenants`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.put(path`/users/${userID}/tenants`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -58,12 +50,8 @@ export class Tenants extends APIResource { * ``` */ addSingle(tenantID: string, params: TenantAddSingleParams, options?: RequestOptions): APIPromise { - const { user_id, ...body } = params; - return this._client.put(path`/users/${user_id}/tenants/${tenantID}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { user_id, ...body } = params + return this._client.put(path`/users/${user_id}/tenants/${tenantID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -75,10 +63,7 @@ export class Tenants extends APIResource { * ``` */ removeAll(userID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/users/${userID}/tenants`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.delete(path`/users/${userID}/tenants`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -91,16 +76,9 @@ export class Tenants extends APIResource { * }); * ``` */ - removeSingle( - tenantID: string, - params: TenantRemoveSingleParams, - options?: RequestOptions, - ): APIPromise { - const { user_id } = params; - return this._client.delete(path`/users/${user_id}/tenants/${tenantID}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + removeSingle(tenantID: string, params: TenantRemoveSingleParams, options?: RequestOptions): APIPromise { + const { user_id } = params + return this._client.delete(path`/users/${user_id}/tenants/${tenantID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -176,6 +154,6 @@ export declare namespace Tenants { type TenantListParams as TenantListParams, type TenantAddMultipleParams as TenantAddMultipleParams, type TenantAddSingleParams as TenantAddSingleParams, - type TenantRemoveSingleParams as TenantRemoveSingleParams, + type TenantRemoveSingleParams as TenantRemoveSingleParams }; } diff --git a/src/resources/users/tokens.ts b/src/resources/users/tokens.ts index 1e0c15fb..986ebe9c 100644 --- a/src/resources/users/tokens.ts +++ b/src/resources/users/tokens.ts @@ -17,12 +17,8 @@ export class Tokens extends APIResource { * }); * ``` */ - retrieve( - token: string, - params: TokenRetrieveParams, - options?: RequestOptions, - ): APIPromise { - const { user_id } = params; + retrieve(token: string, params: TokenRetrieveParams, options?: RequestOptions): APIPromise { + const { user_id } = params return this._client.get(path`/users/${user_id}/tokens/${token}`, options); } @@ -38,12 +34,8 @@ export class Tokens extends APIResource { * ``` */ update(token: string, params: TokenUpdateParams, options?: RequestOptions): APIPromise { - const { user_id, ...body } = params; - return this._client.patch(path`/users/${user_id}/tokens/${token}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { user_id, ...body } = params + return this._client.patch(path`/users/${user_id}/tokens/${token}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -69,11 +61,8 @@ export class Tokens extends APIResource { * ``` */ delete(token: string, params: TokenDeleteParams, options?: RequestOptions): APIPromise { - const { user_id } = params; - return this._client.delete(path`/users/${user_id}/tokens/${token}`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { user_id } = params + return this._client.delete(path`/users/${user_id}/tokens/${token}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -85,10 +74,7 @@ export class Tokens extends APIResource { * ``` */ addMultiple(userID: string, options?: RequestOptions): APIPromise { - return this._client.put(path`/users/${userID}/tokens`, { - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + return this._client.put(path`/users/${userID}/tokens`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } /** @@ -103,12 +89,8 @@ export class Tokens extends APIResource { * ``` */ addSingle(token: string, params: TokenAddSingleParams, options?: RequestOptions): APIPromise { - const { user_id, ...body } = params; - return this._client.put(path`/users/${user_id}/tokens/${token}`, { - body, - ...options, - headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); + const { user_id, ...body } = params + return this._client.put(path`/users/${user_id}/tokens/${token}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); } } @@ -368,6 +350,6 @@ export declare namespace Tokens { type TokenRetrieveParams as TokenRetrieveParams, type TokenUpdateParams as TokenUpdateParams, type TokenDeleteParams as TokenDeleteParams, - type TokenAddSingleParams as TokenAddSingleParams, + type TokenAddSingleParams as TokenAddSingleParams }; } diff --git a/src/resources/users/users.ts b/src/resources/users/users.ts index c2e1eb73..88395fee 100644 --- a/src/resources/users/users.ts +++ b/src/resources/users/users.ts @@ -2,36 +2,11 @@ import { APIResource } from '../../core/resource'; import * as PreferencesAPI from './preferences'; -import { - PreferenceRetrieveParams, - PreferenceRetrieveResponse, - PreferenceRetrieveTopicParams, - PreferenceRetrieveTopicResponse, - PreferenceUpdateOrCreateTopicParams, - PreferenceUpdateOrCreateTopicResponse, - Preferences, - TopicPreference, -} from './preferences'; +import { PreferenceRetrieveParams, PreferenceRetrieveResponse, PreferenceRetrieveTopicParams, PreferenceRetrieveTopicResponse, PreferenceUpdateOrCreateTopicParams, PreferenceUpdateOrCreateTopicResponse, Preferences, TopicPreference } from './preferences'; import * as TenantsAPI from './tenants'; -import { - TenantAddMultipleParams, - TenantAddSingleParams, - TenantListParams, - TenantListResponse, - TenantRemoveSingleParams, - Tenants, -} from './tenants'; +import { TenantAddMultipleParams, TenantAddSingleParams, TenantListParams, TenantListResponse, TenantRemoveSingleParams, Tenants } from './tenants'; import * as TokensAPI from './tokens'; -import { - TokenAddSingleParams, - TokenDeleteParams, - TokenListResponse, - TokenRetrieveParams, - TokenRetrieveResponse, - TokenUpdateParams, - Tokens, - UserToken, -} from './tokens'; +import { TokenAddSingleParams, TokenDeleteParams, TokenListResponse, TokenRetrieveParams, TokenRetrieveResponse, TokenUpdateParams, Tokens, UserToken } from './tokens'; export class Users extends APIResource { preferences: PreferencesAPI.Preferences = new PreferencesAPI.Preferences(this._client); @@ -52,7 +27,7 @@ export declare namespace Users { type PreferenceUpdateOrCreateTopicResponse as PreferenceUpdateOrCreateTopicResponse, type PreferenceRetrieveParams as PreferenceRetrieveParams, type PreferenceRetrieveTopicParams as PreferenceRetrieveTopicParams, - type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams, + type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams }; export { @@ -61,7 +36,7 @@ export declare namespace Users { type TenantListParams as TenantListParams, type TenantAddMultipleParams as TenantAddMultipleParams, type TenantAddSingleParams as TenantAddSingleParams, - type TenantRemoveSingleParams as TenantRemoveSingleParams, + type TenantRemoveSingleParams as TenantRemoveSingleParams }; export { @@ -72,6 +47,6 @@ export declare namespace Users { type TokenRetrieveParams as TokenRetrieveParams, type TokenUpdateParams as TokenUpdateParams, type TokenDeleteParams as TokenDeleteParams, - type TokenAddSingleParams as TokenAddSingleParams, + type TokenAddSingleParams as TokenAddSingleParams }; } diff --git a/src/uploads.ts b/src/uploads.ts index b2ef6471..d5437085 100644 --- a/src/uploads.ts +++ b/src/uploads.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/uploads instead */ -export * from './core/uploads'; +export * from "./core/uploads" \ No newline at end of file diff --git a/src/version.ts b/src/version.ts index 4533200e..4bb2954d 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '7.10.2'; // x-release-please-version +export const VERSION = '7.10.2';// x-release-please-version diff --git a/tests/api-resources/audiences.test.ts b/tests/api-resources/audiences.test.ts index be870cdd..ff776ad0 100644 --- a/tests/api-resources/audiences.test.ts +++ b/tests/api-resources/audiences.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource audiences', () => { // Mock server tests are disabled @@ -47,9 +44,9 @@ describe('resource audiences', () => { // Mock server tests are disabled test.skip('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.audiences.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.audiences.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -79,8 +76,8 @@ describe('resource audiences', () => { // Mock server tests are disabled test.skip('listMembers: 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.audiences.listMembers('audience_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.audiences.listMembers('audience_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/audit-events.test.ts b/tests/api-resources/audit-events.test.ts index 236efabb..5cc5cbca 100644 --- a/tests/api-resources/audit-events.test.ts +++ b/tests/api-resources/audit-events.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource auditEvents', () => { // Mock server tests are disabled @@ -35,8 +32,8 @@ describe('resource auditEvents', () => { // Mock server tests are disabled test.skip('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.auditEvents.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.auditEvents.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/auth.test.ts b/tests/api-resources/auth.test.ts index 7773e3d1..63c291aa 100644 --- a/tests/api-resources/auth.test.ts +++ b/tests/api-resources/auth.test.ts @@ -2,19 +2,12 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource auth', () => { // Mock server tests are disabled test.skip('issueToken: only required params', async () => { - const responsePromise = client.auth.issueToken({ - expires_in: '$YOUR_NUMBER days', - scope: - 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands', - }); + const responsePromise = client.auth.issueToken({ expires_in: '$YOUR_NUMBER days', scope: 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands' }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -26,10 +19,6 @@ describe('resource auth', () => { // Mock server tests are disabled test.skip('issueToken: required and optional params', async () => { - const response = await client.auth.issueToken({ - expires_in: '$YOUR_NUMBER days', - scope: - 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands', - }); + const response = await client.auth.issueToken({ expires_in: '$YOUR_NUMBER days', scope: 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands' }); }); }); diff --git a/tests/api-resources/automations/automations.test.ts b/tests/api-resources/automations/automations.test.ts index eb2e9248..a772c5f7 100644 --- a/tests/api-resources/automations/automations.test.ts +++ b/tests/api-resources/automations/automations.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource automations', () => { // Mock server tests are disabled @@ -23,11 +20,8 @@ describe('resource automations', () => { // Mock server tests are disabled test.skip('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.automations.list( - { cursor: 'cursor', version: 'published' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.automations.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/automations/invoke.test.ts b/tests/api-resources/automations/invoke.test.ts index d52475be..8887eb85 100644 --- a/tests/api-resources/automations/invoke.test.ts +++ b/tests/api-resources/automations/invoke.test.ts @@ -2,17 +2,12 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource invoke', () => { // Mock server tests are disabled test.skip('invokeAdHoc: only required params', async () => { - const responsePromise = client.automations.invoke.invokeAdHoc({ - automation: { steps: [{ action: 'delay' }, { action: 'send' }] }, - }); + const responsePromise = client.automations.invoke.invokeAdHoc({ automation: { steps: [{ action: 'delay' }, { action: 'send' }] } }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -25,37 +20,29 @@ describe('resource invoke', () => { // Mock server tests are disabled test.skip('invokeAdHoc: required and optional params', async () => { const response = await client.automations.invoke.invokeAdHoc({ - automation: { - steps: [ - { - action: 'delay', - duration: 'duration', - until: '20240408T080910.123', - }, - { - action: 'send', - brand: 'brand', - data: { foo: 'bar' }, - profile: { foo: 'bar' }, - recipient: 'recipient', - template: '64TP5HKPFTM8VTK1Y75SJDQX9JK0', - }, - ], - cancelation_token: 'delay-send--user-yes--abc-123', - }, - brand: 'brand', - data: { name: 'bar' }, - profile: { tenant_id: 'bar' }, - recipient: 'user-yes', - template: 'template', - }); + automation: { steps: [{ + action: 'delay', + duration: 'duration', + until: '20240408T080910.123', + }, { + action: 'send', + brand: 'brand', + data: { foo: 'bar' }, + profile: { foo: 'bar' }, + recipient: 'recipient', + template: '64TP5HKPFTM8VTK1Y75SJDQX9JK0', + }], cancelation_token: 'delay-send--user-yes--abc-123' }, + brand: 'brand', + data: { name: 'bar' }, + profile: { tenant_id: 'bar' }, + recipient: 'user-yes', + template: 'template', + }); }); // Mock server tests are disabled test.skip('invokeByTemplate: only required params', async () => { - const responsePromise = client.automations.invoke.invokeByTemplate('templateId', { - recipient: 'recipient', - }); + const responsePromise = client.automations.invoke.invokeByTemplate('templateId', { recipient: 'recipient' }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -68,11 +55,11 @@ describe('resource invoke', () => { // Mock server tests are disabled test.skip('invokeByTemplate: required and optional params', async () => { const response = await client.automations.invoke.invokeByTemplate('templateId', { - recipient: 'recipient', - brand: 'brand', - data: { foo: 'bar' }, - profile: { foo: 'bar' }, - template: 'template', - }); + recipient: 'recipient', + brand: 'brand', + data: { foo: 'bar' }, + profile: { foo: 'bar' }, + template: 'template', + }); }); }); diff --git a/tests/api-resources/brands.test.ts b/tests/api-resources/brands.test.ts index d02ad9cc..cc49ddeb 100644 --- a/tests/api-resources/brands.test.ts +++ b/tests/api-resources/brands.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource brands', () => { // Mock server tests are disabled @@ -23,51 +20,51 @@ describe('resource brands', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.brands.create({ - name: 'name', - id: 'id', - settings: { - colors: { primary: 'primary', secondary: 'secondary' }, - email: { - footer: { content: 'content', inheritDefault: true }, - head: { inheritDefault: true, content: 'content' }, - header: { - logo: { href: 'href', image: 'image' }, - barColor: 'barColor', - inheritDefault: true, - }, - templateOverride: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - mjml: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - }, - footerBackgroundColor: 'footerBackgroundColor', - footerFullWidth: true, - }, - }, - inapp: { - colors: { primary: 'primary', secondary: 'secondary' }, - icons: { bell: 'bell', message: 'message' }, - widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, - borderRadius: 'borderRadius', - disableMessageIcon: true, - fontFamily: 'fontFamily', - placement: 'top', - }, - }, - snippets: { items: [{ name: 'name', value: 'value' }] }, - }); + name: 'name', + id: 'id', + settings: { + colors: { primary: 'primary', secondary: 'secondary' }, + email: { + footer: { content: 'content', inheritDefault: true }, + head: { inheritDefault: true, content: 'content' }, + header: { + logo: { href: 'href', image: 'image' }, + barColor: 'barColor', + inheritDefault: true, + }, + templateOverride: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + mjml: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + }, + footerBackgroundColor: 'footerBackgroundColor', + footerFullWidth: true, + }, + }, + inapp: { + colors: { primary: 'primary', secondary: 'secondary' }, + icons: { bell: 'bell', message: 'message' }, + widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, + borderRadius: 'borderRadius', + disableMessageIcon: true, + fontFamily: 'fontFamily', + placement: 'top', + }, + }, + snippets: { items: [{ name: 'name', value: 'value' }] }, + }); }); // Mock server tests are disabled @@ -97,50 +94,50 @@ describe('resource brands', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.brands.update('brand_id', { - name: 'name', - settings: { - colors: { primary: 'primary', secondary: 'secondary' }, - email: { - footer: { content: 'content', inheritDefault: true }, - head: { inheritDefault: true, content: 'content' }, - header: { - logo: { href: 'href', image: 'image' }, - barColor: 'barColor', - inheritDefault: true, - }, - templateOverride: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - mjml: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - }, - footerBackgroundColor: 'footerBackgroundColor', - footerFullWidth: true, - }, - }, - inapp: { - colors: { primary: 'primary', secondary: 'secondary' }, - icons: { bell: 'bell', message: 'message' }, - widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, - borderRadius: 'borderRadius', - disableMessageIcon: true, - fontFamily: 'fontFamily', - placement: 'top', - }, - }, - snippets: { items: [{ name: 'name', value: 'value' }] }, - }); + name: 'name', + settings: { + colors: { primary: 'primary', secondary: 'secondary' }, + email: { + footer: { content: 'content', inheritDefault: true }, + head: { inheritDefault: true, content: 'content' }, + header: { + logo: { href: 'href', image: 'image' }, + barColor: 'barColor', + inheritDefault: true, + }, + templateOverride: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + mjml: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + }, + footerBackgroundColor: 'footerBackgroundColor', + footerFullWidth: true, + }, + }, + inapp: { + colors: { primary: 'primary', secondary: 'secondary' }, + icons: { bell: 'bell', message: 'message' }, + widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, + borderRadius: 'borderRadius', + disableMessageIcon: true, + fontFamily: 'fontFamily', + placement: 'top', + }, + }, + snippets: { items: [{ name: 'name', value: 'value' }] }, + }); }); // Mock server tests are disabled @@ -158,9 +155,9 @@ describe('resource brands', () => { // Mock server tests are disabled test.skip('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.brands.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.brands.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/bulk.test.ts b/tests/api-resources/bulk.test.ts index 2cec3e13..cb0c5761 100644 --- a/tests/api-resources/bulk.test.ts +++ b/tests/api-resources/bulk.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource bulk', () => { // Mock server tests are disabled @@ -22,61 +19,49 @@ describe('resource bulk', () => { // Mock server tests are disabled test.skip('addUsers: required and optional params', async () => { - const response = await client.bulk.addUsers('job_id', { - users: [ - { - data: {}, - preferences: { - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - }, - profile: { foo: 'bar' }, - recipient: 'recipient', - to: { - account_id: 'account_id', - context: { tenant_id: 'tenant_id' }, - data: { foo: 'bar' }, - email: 'email', - list_id: 'list_id', - locale: 'locale', - phone_number: 'phone_number', - preferences: { - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - }, - }, - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - }, - }, - templateId: 'templateId', - }, - tenant_id: 'tenant_id', - user_id: 'user_id', - }, - }, - ], - }); + const response = await client.bulk.addUsers('job_id', { users: [{ + data: {}, + preferences: { + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + }, + profile: { foo: 'bar' }, + recipient: 'recipient', + to: { + account_id: 'account_id', + context: { tenant_id: 'tenant_id' }, + data: { foo: 'bar' }, + email: 'email', + list_id: 'list_id', + locale: 'locale', + phone_number: 'phone_number', + preferences: { + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + } }, + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + } }, + templateId: 'templateId', + }, + tenant_id: 'tenant_id', + user_id: 'user_id', + }, + }] }); }); // Mock server tests are disabled @@ -93,17 +78,15 @@ describe('resource bulk', () => { // Mock server tests are disabled test.skip('createJob: required and optional params', async () => { - const response = await client.bulk.createJob({ - message: { - event: 'event', - brand: 'brand', - content: { body: 'body', title: 'title' }, - data: { foo: 'bar' }, - locale: { foo: { foo: 'bar' } }, - override: { foo: 'bar' }, - template: 'template', - }, - }); + const response = await client.bulk.createJob({ message: { + event: 'event', + brand: 'brand', + content: { body: 'body', title: 'title' }, + data: { foo: 'bar' }, + locale: { foo: { foo: 'bar' } }, + override: { foo: 'bar' }, + template: 'template', + } }); }); // Mock server tests are disabled @@ -121,9 +104,9 @@ describe('resource bulk', () => { // Mock server tests are disabled test.skip('listUsers: 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.bulk.listUsers('job_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.bulk.listUsers('job_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/inbound.test.ts b/tests/api-resources/inbound.test.ts index 9e49a5b9..b737f526 100644 --- a/tests/api-resources/inbound.test.ts +++ b/tests/api-resources/inbound.test.ts @@ -2,24 +2,21 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource inbound', () => { // Mock server tests are disabled test.skip('trackEvent: only required params', async () => { const responsePromise = client.inbound.trackEvent({ - event: 'New Order Placed', - messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', - properties: { - order_id: 'bar', - total_orders: 'bar', - last_order_id: 'bar', - }, - type: 'track', - }); + event: 'New Order Placed', + messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', + properties: { + order_id: 'bar', + total_orders: 'bar', + last_order_id: 'bar', + }, + type: 'track', + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -32,15 +29,15 @@ describe('resource inbound', () => { // Mock server tests are disabled test.skip('trackEvent: required and optional params', async () => { const response = await client.inbound.trackEvent({ - event: 'New Order Placed', - messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', - properties: { - order_id: 'bar', - total_orders: 'bar', - last_order_id: 'bar', - }, - type: 'track', - userId: '1234', - }); + event: 'New Order Placed', + messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', + properties: { + order_id: 'bar', + total_orders: 'bar', + last_order_id: 'bar', + }, + type: 'track', + userId: '1234', + }); }); }); diff --git a/tests/api-resources/journeys.test.ts b/tests/api-resources/journeys.test.ts index 92d4b7a5..41634daf 100644 --- a/tests/api-resources/journeys.test.ts +++ b/tests/api-resources/journeys.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource journeys', () => { // Mock server tests are disabled @@ -23,9 +20,9 @@ describe('resource journeys', () => { // Mock server tests are disabled test.skip('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.journeys.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.journeys.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/lists/lists.test.ts b/tests/api-resources/lists/lists.test.ts index 0a69942b..d13103a8 100644 --- a/tests/api-resources/lists/lists.test.ts +++ b/tests/api-resources/lists/lists.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource lists', () => { // Mock server tests are disabled @@ -35,24 +32,20 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.lists.update('list_id', { - name: 'name', - preferences: { - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - }, - }); + name: 'name', + preferences: { + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + }, + }); }); // Mock server tests are disabled @@ -70,9 +63,9 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('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.lists.list({ cursor: 'cursor', pattern: 'pattern' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.lists.list({ cursor: 'cursor', pattern: 'pattern' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/lists/subscriptions.test.ts b/tests/api-resources/lists/subscriptions.test.ts index ec7570f5..62fe825a 100644 --- a/tests/api-resources/lists/subscriptions.test.ts +++ b/tests/api-resources/lists/subscriptions.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource subscriptions', () => { // Mock server tests are disabled @@ -23,16 +20,14 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('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.lists.subscriptions.list('list_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.lists.subscriptions.list('list_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled test.skip('add: only required params', async () => { - const responsePromise = client.lists.subscriptions.add('list_id', { - recipients: [{ recipientId: 'recipientId' }], - }); + const responsePromise = client.lists.subscriptions.add('list_id', { recipients: [{ recipientId: 'recipientId' }] }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -44,36 +39,26 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('add: required and optional params', async () => { - const response = await client.lists.subscriptions.add('list_id', { - recipients: [ - { - recipientId: 'recipientId', - preferences: { - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - }, - }, - ], - }); + const response = await client.lists.subscriptions.add('list_id', { recipients: [{ + recipientId: 'recipientId', + preferences: { + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + }, + }] }); }); // Mock server tests are disabled test.skip('subscribe: only required params', async () => { - const responsePromise = client.lists.subscriptions.subscribe('list_id', { - recipients: [{ recipientId: 'recipientId' }], - }); + const responsePromise = client.lists.subscriptions.subscribe('list_id', { recipients: [{ recipientId: 'recipientId' }] }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -85,29 +70,21 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('subscribe: required and optional params', async () => { - const response = await client.lists.subscriptions.subscribe('list_id', { - recipients: [ - { - recipientId: 'recipientId', - preferences: { - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - }, - }, - ], - }); + const response = await client.lists.subscriptions.subscribe('list_id', { recipients: [{ + recipientId: 'recipientId', + preferences: { + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + }, + }] }); }); // Mock server tests are disabled @@ -125,24 +102,20 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('subscribeUser: required and optional params', async () => { const response = await client.lists.subscriptions.subscribeUser('user_id', { - list_id: 'list_id', - preferences: { - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - }, - }); + list_id: 'list_id', + preferences: { + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + }, + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/messages.test.ts b/tests/api-resources/messages.test.ts index 48000970..57ce38ba 100644 --- a/tests/api-resources/messages.test.ts +++ b/tests/api-resources/messages.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource messages', () => { // Mock server tests are disabled @@ -35,27 +32,24 @@ describe('resource messages', () => { // Mock server tests are disabled test.skip('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.messages.list( - { - archived: true, - cursor: 'cursor', - enqueued_after: 'enqueued_after', - event: 'event', - list: 'list', - messageId: 'messageId', - notification: 'notification', - provider: ['string'], - recipient: 'recipient', - status: ['string'], - tag: ['string'], - tags: 'tags', - tenant_id: 'tenant_id', - traceId: 'traceId', - }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.messages.list({ + archived: true, + cursor: 'cursor', + enqueued_after: 'enqueued_after', + event: 'event', + list: 'list', + messageId: 'messageId', + notification: 'notification', + provider: ['string'], + recipient: 'recipient', + status: ['string'], + tag: ['string'], + tags: 'tags', + tenant_id: 'tenant_id', + traceId: 'traceId', + }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -97,8 +91,8 @@ describe('resource messages', () => { // Mock server tests are disabled test.skip('history: 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.messages.history('message_id', { type: 'type' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.messages.history('message_id', { type: 'type' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/notifications/checks.test.ts b/tests/api-resources/notifications/checks.test.ts index cc4a65ab..9cfa58a6 100644 --- a/tests/api-resources/notifications/checks.test.ts +++ b/tests/api-resources/notifications/checks.test.ts @@ -2,24 +2,16 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource checks', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.notifications.checks.update('submissionId', { - id: 'id', - checks: [ - { - id: 'id', - status: 'RESOLVED', - type: 'custom', - }, - ], - }); + const responsePromise = client.notifications.checks.update('submissionId', { id: 'id', checks: [{ + id: 'id', + status: 'RESOLVED', + type: 'custom', + }] }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -31,16 +23,11 @@ describe('resource checks', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { - const response = await client.notifications.checks.update('submissionId', { - id: 'id', - checks: [ - { - id: 'id', - status: 'RESOLVED', - type: 'custom', - }, - ], - }); + const response = await client.notifications.checks.update('submissionId', { id: 'id', checks: [{ + id: 'id', + status: 'RESOLVED', + type: 'custom', + }] }); }); // Mock server tests are disabled diff --git a/tests/api-resources/notifications/notifications.test.ts b/tests/api-resources/notifications/notifications.test.ts index b5fcdfe3..fde2400b 100644 --- a/tests/api-resources/notifications/notifications.test.ts +++ b/tests/api-resources/notifications/notifications.test.ts @@ -2,24 +2,19 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource notifications', () => { // Mock server tests are disabled test.skip('create: only required params', async () => { - const responsePromise = client.notifications.create({ - notification: { - brand: { id: 'brand_abc' }, - content: { elements: [{}], version: '2022-01-01' }, - name: 'Welcome Email', - routing: { strategy_id: 'rs_123' }, - subscription: { topic_id: 'marketing' }, - tags: ['onboarding', 'welcome'], - }, - }); + const responsePromise = client.notifications.create({ notification: { + brand: { id: 'brand_abc' }, + content: { elements: [{}], version: '2022-01-01' }, + name: 'Welcome Email', + routing: { strategy_id: 'rs_123' }, + subscription: { topic_id: 'marketing' }, + tags: ['onboarding', 'welcome'], + } }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -32,16 +27,16 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.notifications.create({ - notification: { - brand: { id: 'brand_abc' }, - content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, - name: 'Welcome Email', - routing: { strategy_id: 'rs_123' }, - subscription: { topic_id: 'marketing' }, - tags: ['onboarding', 'welcome'], - }, - state: 'DRAFT', - }); + notification: { + brand: { id: 'brand_abc' }, + content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, + name: 'Welcome Email', + routing: { strategy_id: 'rs_123' }, + subscription: { topic_id: 'marketing' }, + tags: ['onboarding', 'welcome'], + }, + state: 'DRAFT', + }); }); // Mock server tests are disabled @@ -59,9 +54,9 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('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.notifications.retrieve('id', { version: 'version' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.notifications.retrieve('id', { version: 'version' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -79,16 +74,13 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('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.notifications.list( - { - cursor: 'cursor', - event_id: 'event_id', - notes: true, - }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.notifications.list({ + cursor: 'cursor', + event_id: 'event_id', + notes: true, + }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -118,13 +110,9 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('listVersions: 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.notifications.listVersions( - 'id', - { cursor: 'cursor', limit: 10 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.notifications.listVersions('id', { cursor: 'cursor', limit: 10 }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -142,9 +130,9 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('publish: 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.notifications.publish('id', { version: 'v321669910225' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.notifications.publish('id', { version: 'v321669910225' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -162,9 +150,9 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('putContent: required and optional params', async () => { const response = await client.notifications.putContent('id', { - content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, - state: 'DRAFT', - }); + content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, + state: 'DRAFT', + }); }); // Mock server tests are disabled @@ -182,23 +170,20 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('putElement: required and optional params', async () => { const response = await client.notifications.putElement('elementId', { - id: 'id', - type: 'text', - channels: ['string'], - data: { content: 'bar' }, - if: 'if', - loop: 'loop', - ref: 'ref', - state: 'DRAFT', - }); + id: 'id', + type: 'text', + channels: ['string'], + data: { content: 'bar' }, + if: 'if', + loop: 'loop', + ref: 'ref', + state: 'DRAFT', + }); }); // Mock server tests are disabled test.skip('putLocale: only required params', async () => { - const responsePromise = client.notifications.putLocale('localeId', { - id: 'id', - elements: [{ id: 'elem_1' }, { id: 'elem_2' }], - }); + const responsePromise = client.notifications.putLocale('localeId', { id: 'id', elements: [{ id: 'elem_1' }, { id: 'elem_2' }] }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -211,24 +196,22 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('putLocale: required and optional params', async () => { const response = await client.notifications.putLocale('localeId', { - id: 'id', - elements: [{ id: 'elem_1' }, { id: 'elem_2' }], - state: 'DRAFT', - }); + id: 'id', + elements: [{ id: 'elem_1' }, { id: 'elem_2' }], + state: 'DRAFT', + }); }); // Mock server tests are disabled test.skip('replace: only required params', async () => { - const responsePromise = client.notifications.replace('id', { - notification: { - brand: { id: 'id' }, - content: { elements: [{}], version: '2022-01-01' }, - name: 'Updated Name', - routing: { strategy_id: 'strategy_id' }, - subscription: { topic_id: 'topic_id' }, - tags: ['updated'], - }, - }); + const responsePromise = client.notifications.replace('id', { notification: { + brand: { id: 'id' }, + content: { elements: [{}], version: '2022-01-01' }, + name: 'Updated Name', + routing: { strategy_id: 'strategy_id' }, + subscription: { topic_id: 'topic_id' }, + tags: ['updated'], + } }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -241,16 +224,16 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('replace: required and optional params', async () => { const response = await client.notifications.replace('id', { - notification: { - brand: { id: 'id' }, - content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, - name: 'Updated Name', - routing: { strategy_id: 'strategy_id' }, - subscription: { topic_id: 'topic_id' }, - tags: ['updated'], - }, - state: 'PUBLISHED', - }); + notification: { + brand: { id: 'id' }, + content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, + name: 'Updated Name', + routing: { strategy_id: 'strategy_id' }, + subscription: { topic_id: 'topic_id' }, + tags: ['updated'], + }, + state: 'PUBLISHED', + }); }); // Mock server tests are disabled @@ -268,12 +251,8 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('retrieveContent: 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.notifications.retrieveContent( - 'id', - { version: 'version' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.notifications.retrieveContent('id', { version: 'version' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/profiles/lists.test.ts b/tests/api-resources/profiles/lists.test.ts index 54fe8e00..522abeb8 100644 --- a/tests/api-resources/profiles/lists.test.ts +++ b/tests/api-resources/profiles/lists.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource lists', () => { // Mock server tests are disabled @@ -23,9 +20,9 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('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.profiles.lists.retrieve('user_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.profiles.lists.retrieve('user_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -54,28 +51,20 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('subscribe: required and optional params', async () => { - const response = await client.profiles.lists.subscribe('user_id', { - lists: [ - { - listId: 'listId', - preferences: { - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - }, - }, - }, - }, - ], - }); + const response = await client.profiles.lists.subscribe('user_id', { lists: [{ + listId: 'listId', + preferences: { + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + } }, + }, + }] }); }); }); diff --git a/tests/api-resources/profiles/profiles.test.ts b/tests/api-resources/profiles/profiles.test.ts index 65785844..9dcb9b59 100644 --- a/tests/api-resources/profiles/profiles.test.ts +++ b/tests/api-resources/profiles/profiles.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource profiles', () => { // Mock server tests are disabled @@ -39,15 +36,11 @@ describe('resource profiles', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.profiles.update('user_id', { - patch: [ - { - op: 'op', - path: 'path', - value: 'value', - }, - ], - }); + const responsePromise = client.profiles.update('user_id', { patch: [{ + op: 'op', + path: 'path', + value: 'value', + }] }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -59,15 +52,11 @@ describe('resource profiles', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { - const response = await client.profiles.update('user_id', { - patch: [ - { - op: 'op', - path: 'path', - value: 'value', - }, - ], - }); + const response = await client.profiles.update('user_id', { patch: [{ + op: 'op', + path: 'path', + value: 'value', + }] }); }); // Mock server tests are disabled diff --git a/tests/api-resources/providers/catalog.test.ts b/tests/api-resources/providers/catalog.test.ts index f087e739..27246cbd 100644 --- a/tests/api-resources/providers/catalog.test.ts +++ b/tests/api-resources/providers/catalog.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource catalog', () => { // Mock server tests are disabled @@ -23,15 +20,12 @@ describe('resource catalog', () => { // Mock server tests are disabled test.skip('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.providers.catalog.list( - { - channel: 'channel', - keys: 'keys', - name: 'name', - }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.providers.catalog.list({ + channel: 'channel', + keys: 'keys', + name: 'name', + }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/providers/providers.test.ts b/tests/api-resources/providers/providers.test.ts index 3ea22cfc..2370c58f 100644 --- a/tests/api-resources/providers/providers.test.ts +++ b/tests/api-resources/providers/providers.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource providers', () => { // Mock server tests are disabled @@ -23,11 +20,11 @@ describe('resource providers', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.providers.create({ - provider: 'provider', - alias: 'alias', - settings: { foo: 'bar' }, - title: 'title', - }); + provider: 'provider', + alias: 'alias', + settings: { foo: 'bar' }, + title: 'title', + }); }); // Mock server tests are disabled @@ -57,11 +54,11 @@ describe('resource providers', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.providers.update('id', { - provider: 'provider', - alias: 'alias', - settings: { foo: 'bar' }, - title: 'title', - }); + provider: 'provider', + alias: 'alias', + settings: { foo: 'bar' }, + title: 'title', + }); }); // Mock server tests are disabled @@ -79,9 +76,9 @@ describe('resource providers', () => { // Mock server tests are disabled test.skip('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.providers.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.providers.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/requests.test.ts b/tests/api-resources/requests.test.ts index 104590ae..ca8ca68c 100644 --- a/tests/api-resources/requests.test.ts +++ b/tests/api-resources/requests.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource requests', () => { // Mock server tests are disabled diff --git a/tests/api-resources/routing-strategies.test.ts b/tests/api-resources/routing-strategies.test.ts index 3f6de460..afd555ff 100644 --- a/tests/api-resources/routing-strategies.test.ts +++ b/tests/api-resources/routing-strategies.test.ts @@ -2,18 +2,15 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.routingStrategies.create({ - name: 'Email via SendGrid', - routing: { channels: ['email'], method: 'single' }, - }); + name: 'Email via SendGrid', + routing: { channels: ['email'], method: 'single' }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -26,46 +23,38 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.routingStrategies.create({ - name: 'Email via SendGrid', - routing: { channels: ['email'], method: 'single' }, - channels: { - email: { - brand_id: 'brand_id', - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: { foo: 'bar' }, - providers: ['sendgrid', 'ses'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - }, - }, - description: 'Routes email through sendgrid with SES failover', - providers: { - sendgrid: { - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: {}, - timeouts: 0, - }, - }, - tags: ['production', 'email'], - }); + name: 'Email via SendGrid', + routing: { channels: ['email'], method: 'single' }, + channels: { email: { + brand_id: 'brand_id', + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: { foo: 'bar' }, + providers: ['sendgrid', 'ses'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + } }, + description: 'Routes email through sendgrid with SES failover', + providers: { sendgrid: { + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: {}, + timeouts: 0, + } }, + tags: ['production', 'email'], + }); }); // Mock server tests are disabled @@ -95,9 +84,9 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('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.routingStrategies.list({ cursor: 'cursor', limit: 1 }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.routingStrategies.list({ cursor: 'cursor', limit: 1 }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -127,21 +116,17 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('listNotifications: 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.routingStrategies.listNotifications( - 'id', - { cursor: 'cursor', limit: 1 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.routingStrategies.listNotifications('id', { cursor: 'cursor', limit: 1 }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled test.skip('replace: only required params', async () => { const responsePromise = client.routingStrategies.replace('id', { - name: 'Email via SendGrid v2', - routing: { channels: ['email'], method: 'single' }, - }); + name: 'Email via SendGrid v2', + routing: { channels: ['email'], method: 'single' }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -154,45 +139,37 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('replace: required and optional params', async () => { const response = await client.routingStrategies.replace('id', { - name: 'Email via SendGrid v2', - routing: { channels: ['email'], method: 'single' }, - channels: { - email: { - brand_id: 'brand_id', - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: { foo: 'bar' }, - providers: ['ses', 'sendgrid'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - }, - }, - description: 'Updated routing with SES primary', - providers: { - ses: { - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: {}, - timeouts: 0, - }, - }, - tags: ['production', 'email', 'v2'], - }); + name: 'Email via SendGrid v2', + routing: { channels: ['email'], method: 'single' }, + channels: { email: { + brand_id: 'brand_id', + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: { foo: 'bar' }, + providers: ['ses', 'sendgrid'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + } }, + description: 'Updated routing with SES primary', + providers: { ses: { + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: {}, + timeouts: 0, + } }, + tags: ['production', 'email', 'v2'], + }); }); }); diff --git a/tests/api-resources/send.test.ts b/tests/api-resources/send.test.ts index 2daf02a5..88ce631c 100644 --- a/tests/api-resources/send.test.ts +++ b/tests/api-resources/send.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource send', () => { // Mock server tests are disabled @@ -22,106 +19,92 @@ describe('resource send', () => { // Mock server tests are disabled test.skip('message: required and optional params', async () => { - const response = await client.send.message({ - message: { - brand_id: 'brand_id', - channels: { - foo: { - brand_id: 'brand_id', - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: { foo: 'bar' }, - providers: ['string'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - }, - }, - content: { body: 'body', title: 'title' }, - context: { tenant_id: 'tenant_id' }, - data: { foo: 'bar' }, - delay: { - duration: 0, - timezone: 'timezone', - until: 'until', - }, - expiry: { expires_in: 'string', expires_at: 'expires_at' }, - metadata: { - event: 'event', - tags: ['string'], - trace_id: 'trace_id', - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - preferences: { subscription_topic_id: 'subscription_topic_id' }, - providers: { - foo: { - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: { foo: 'bar' }, - timeouts: 0, - }, - }, - routing: { channels: ['string'], method: 'all' }, - template: 'template_id', - timeout: { - channel: { foo: 0 }, - criteria: 'no-escalation', - escalation: 0, - message: 0, - provider: { foo: 0 }, - }, - to: { - account_id: 'account_id', - context: { tenant_id: 'tenant_id' }, - data: { foo: 'bar' }, - email: 'email', - list_id: 'list_id', - locale: 'locale', - phone_number: 'phone_number', - preferences: { - notifications: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - }, - }, - categories: { - foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - }, - }, - templateId: 'templateId', - }, - tenant_id: 'tenant_id', - user_id: 'user_id', - }, - }, - }); + const response = await client.send.message({ message: { + brand_id: 'brand_id', + channels: { foo: { + brand_id: 'brand_id', + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: { foo: 'bar' }, + providers: ['string'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + } }, + content: { body: 'body', title: 'title' }, + context: { tenant_id: 'tenant_id' }, + data: { foo: 'bar' }, + delay: { + duration: 0, + timezone: 'timezone', + until: 'until', + }, + expiry: { expires_in: 'string', expires_at: 'expires_at' }, + metadata: { + event: 'event', + tags: ['string'], + trace_id: 'trace_id', + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + preferences: { subscription_topic_id: 'subscription_topic_id' }, + providers: { foo: { + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: { foo: 'bar' }, + timeouts: 0, + } }, + routing: { channels: ['string'], method: 'all' }, + template: 'template_id', + timeout: { + channel: { foo: 0 }, + criteria: 'no-escalation', + escalation: 0, + message: 0, + provider: { foo: 0 }, + }, + to: { + account_id: 'account_id', + context: { tenant_id: 'tenant_id' }, + data: { foo: 'bar' }, + email: 'email', + list_id: 'list_id', + locale: 'locale', + phone_number: 'phone_number', + preferences: { + notifications: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + } }, + categories: { foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + } }, + templateId: 'templateId', + }, + tenant_id: 'tenant_id', + user_id: 'user_id', + }, + } }); }); }); diff --git a/tests/api-resources/tenants/preferences/items.test.ts b/tests/api-resources/tenants/preferences/items.test.ts index f502f673..ee5d6276 100644 --- a/tests/api-resources/tenants/preferences/items.test.ts +++ b/tests/api-resources/tenants/preferences/items.test.ts @@ -2,18 +2,12 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource items', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.tenants.preferences.items.update('topic_id', { - tenant_id: 'tenant_id', - status: 'OPTED_IN', - }); + const responsePromise = client.tenants.preferences.items.update('topic_id', { tenant_id: 'tenant_id', status: 'OPTED_IN' }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -26,11 +20,11 @@ describe('resource items', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.tenants.preferences.items.update('topic_id', { - tenant_id: 'tenant_id', - status: 'OPTED_IN', - custom_routing: ['inbox'], - has_custom_routing: true, - }); + tenant_id: 'tenant_id', + status: 'OPTED_IN', + custom_routing: ['inbox'], + has_custom_routing: true, + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/tenants/templates/templates.test.ts b/tests/api-resources/tenants/templates/templates.test.ts index 94e7ae8e..a4687699 100644 --- a/tests/api-resources/tenants/templates/templates.test.ts +++ b/tests/api-resources/tenants/templates/templates.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource templates', () => { // Mock server tests are disabled @@ -40,13 +37,9 @@ describe('resource templates', () => { // Mock server tests are disabled test.skip('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.tenants.templates.list( - 'tenant_id', - { cursor: 'cursor', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.tenants.templates.list('tenant_id', { cursor: 'cursor', limit: 0 }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -63,18 +56,15 @@ describe('resource templates', () => { // Mock server tests are disabled test.skip('publish: required and optional params', async () => { - const response = await client.tenants.templates.publish('template_id', { - tenant_id: 'tenant_id', - version: 'version', - }); + const response = await client.tenants.templates.publish('template_id', { tenant_id: 'tenant_id', version: 'version' }); }); // Mock server tests are disabled test.skip('replace: only required params', async () => { const responsePromise = client.tenants.templates.replace('template_id', { - tenant_id: 'tenant_id', - template: { content: { elements: [{}], version: 'version' } }, - }); + tenant_id: 'tenant_id', + template: { content: { elements: [{}], version: 'version' } }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -87,58 +77,45 @@ describe('resource templates', () => { // Mock server tests are disabled test.skip('replace: required and optional params', async () => { const response = await client.tenants.templates.replace('template_id', { - tenant_id: 'tenant_id', - template: { - content: { - elements: [ - { - channels: ['string'], - if: 'if', - loop: 'loop', - ref: 'ref', - type: 'text', - }, - ], - version: 'version', - }, - channels: { - foo: { - brand_id: 'brand_id', - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: { foo: 'bar' }, - providers: ['string'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - }, - }, - providers: { - foo: { - if: 'if', - metadata: { - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - override: { foo: 'bar' }, - timeouts: 0, - }, - }, - routing: { channels: ['string'], method: 'all' }, - }, - published: true, - }); + tenant_id: 'tenant_id', + template: { + content: { elements: [{ + channels: ['string'], + if: 'if', + loop: 'loop', + ref: 'ref', + type: 'text', + }], version: 'version' }, + channels: { foo: { + brand_id: 'brand_id', + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: { foo: 'bar' }, + providers: ['string'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + } }, + providers: { foo: { + if: 'if', + metadata: { utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + } }, + override: { foo: 'bar' }, + timeouts: 0, + } }, + routing: { channels: ['string'], method: 'all' }, + }, + published: true, + }); }); }); diff --git a/tests/api-resources/tenants/templates/versions.test.ts b/tests/api-resources/tenants/templates/versions.test.ts index fca12b6f..5ac199c2 100644 --- a/tests/api-resources/tenants/templates/versions.test.ts +++ b/tests/api-resources/tenants/templates/versions.test.ts @@ -2,18 +2,12 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource versions', () => { // Mock server tests are disabled test.skip('retrieve: only required params', async () => { - const responsePromise = client.tenants.templates.versions.retrieve('version', { - tenant_id: 'tenant_id', - template_id: 'template_id', - }); + const responsePromise = client.tenants.templates.versions.retrieve('version', { tenant_id: 'tenant_id', template_id: 'template_id' }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -25,9 +19,6 @@ describe('resource versions', () => { // Mock server tests are disabled test.skip('retrieve: required and optional params', async () => { - const response = await client.tenants.templates.versions.retrieve('version', { - tenant_id: 'tenant_id', - template_id: 'template_id', - }); + const response = await client.tenants.templates.versions.retrieve('version', { tenant_id: 'tenant_id', template_id: 'template_id' }); }); }); diff --git a/tests/api-resources/tenants/tenants.test.ts b/tests/api-resources/tenants/tenants.test.ts index 3ea303e1..e97a1685 100644 --- a/tests/api-resources/tenants/tenants.test.ts +++ b/tests/api-resources/tenants/tenants.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource tenants', () => { // Mock server tests are disabled @@ -35,22 +32,18 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.tenants.update('tenant_id', { - name: 'name', - brand_id: 'brand_id', - default_preferences: { - items: [ - { - status: 'OPTED_OUT', - custom_routing: ['direct_message'], - has_custom_routing: true, - id: 'id', - }, - ], - }, - parent_tenant_id: 'parent_tenant_id', - properties: { foo: 'bar' }, - user_profile: { foo: 'bar' }, - }); + name: 'name', + brand_id: 'brand_id', + default_preferences: { items: [{ + status: 'OPTED_OUT', + custom_routing: ['direct_message'], + has_custom_routing: true, + id: 'id', + }] }, + parent_tenant_id: 'parent_tenant_id', + properties: { foo: 'bar' }, + user_profile: { foo: 'bar' }, + }); }); // Mock server tests are disabled @@ -68,16 +61,13 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('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.tenants.list( - { - cursor: 'cursor', - limit: 0, - parent_tenant_id: 'parent_tenant_id', - }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.tenants.list({ + cursor: 'cursor', + limit: 0, + parent_tenant_id: 'parent_tenant_id', + }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -107,12 +97,8 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('listUsers: 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.tenants.listUsers( - 'tenant_id', - { cursor: 'cursor', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.tenants.listUsers('tenant_id', { cursor: 'cursor', limit: 0 }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/translations.test.ts b/tests/api-resources/translations.test.ts index 3f0c1df9..2fd26d45 100644 --- a/tests/api-resources/translations.test.ts +++ b/tests/api-resources/translations.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource translations', () => { // Mock server tests are disabled diff --git a/tests/api-resources/users/preferences.test.ts b/tests/api-resources/users/preferences.test.ts index 51252679..db4409c9 100644 --- a/tests/api-resources/users/preferences.test.ts +++ b/tests/api-resources/users/preferences.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource preferences', () => { // Mock server tests are disabled @@ -23,13 +20,9 @@ describe('resource preferences', () => { // Mock server tests are disabled test.skip('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.users.preferences.retrieve( - 'user_id', - { tenant_id: 'tenant_id' }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.users.preferences.retrieve('user_id', { tenant_id: 'tenant_id' }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -46,18 +39,15 @@ describe('resource preferences', () => { // Mock server tests are disabled test.skip('retrieveTopic: required and optional params', async () => { - const response = await client.users.preferences.retrieveTopic('topic_id', { - user_id: 'user_id', - tenant_id: 'tenant_id', - }); + const response = await client.users.preferences.retrieveTopic('topic_id', { user_id: 'user_id', tenant_id: 'tenant_id' }); }); // Mock server tests are disabled test.skip('updateOrCreateTopic: only required params', async () => { const responsePromise = client.users.preferences.updateOrCreateTopic('topic_id', { - user_id: 'user_id', - topic: { status: 'OPTED_IN' }, - }); + user_id: 'user_id', + topic: { status: 'OPTED_IN' }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -70,13 +60,13 @@ describe('resource preferences', () => { // Mock server tests are disabled test.skip('updateOrCreateTopic: required and optional params', async () => { const response = await client.users.preferences.updateOrCreateTopic('topic_id', { - user_id: 'user_id', - topic: { - status: 'OPTED_IN', - custom_routing: ['inbox', 'email'], - has_custom_routing: true, - }, - tenant_id: 'tenant_id', - }); + user_id: 'user_id', + topic: { + status: 'OPTED_IN', + custom_routing: ['inbox', 'email'], + has_custom_routing: true, + }, + tenant_id: 'tenant_id', + }); }); }); diff --git a/tests/api-resources/users/tenants.test.ts b/tests/api-resources/users/tenants.test.ts index 73c46f87..a9a27d1d 100644 --- a/tests/api-resources/users/tenants.test.ts +++ b/tests/api-resources/users/tenants.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource tenants', () => { // Mock server tests are disabled @@ -23,20 +20,14 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('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.users.tenants.list( - 'user_id', - { cursor: 'cursor', limit: 0 }, - { path: '/_stainless_unknown_path' }, - ), - ).rejects.toThrow(Courier.NotFoundError); + await expect(client.users.tenants.list('user_id', { cursor: 'cursor', limit: 0 }, { path: '/_stainless_unknown_path' })) + .rejects + .toThrow(Courier.NotFoundError); }); // Mock server tests are disabled test.skip('addMultiple: only required params', async () => { - const responsePromise = client.users.tenants.addMultiple('user_id', { - tenants: [{ tenant_id: 'tenant_id' }], - }); + const responsePromise = client.users.tenants.addMultiple('user_id', { tenants: [{ tenant_id: 'tenant_id' }] }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -48,16 +39,12 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('addMultiple: required and optional params', async () => { - const response = await client.users.tenants.addMultiple('user_id', { - tenants: [ - { - tenant_id: 'tenant_id', - profile: { foo: 'bar' }, - type: 'user', - user_id: 'user_id', - }, - ], - }); + const response = await client.users.tenants.addMultiple('user_id', { tenants: [{ + tenant_id: 'tenant_id', + profile: { foo: 'bar' }, + type: 'user', + user_id: 'user_id', + }] }); }); // Mock server tests are disabled @@ -75,9 +62,9 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('addSingle: required and optional params', async () => { const response = await client.users.tenants.addSingle('tenant_id', { - user_id: 'user_id', - profile: { foo: 'bar' }, - }); + user_id: 'user_id', + profile: { foo: 'bar' }, + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/users/tokens.test.ts b/tests/api-resources/users/tokens.test.ts index 91e4a7e3..cd536149 100644 --- a/tests/api-resources/users/tokens.test.ts +++ b/tests/api-resources/users/tokens.test.ts @@ -2,10 +2,7 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); +const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); describe('resource tokens', () => { // Mock server tests are disabled @@ -27,10 +24,7 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.users.tokens.update('token', { - user_id: 'user_id', - patch: [{ op: 'op', path: 'path' }], - }); + const responsePromise = client.users.tokens.update('token', { user_id: 'user_id', patch: [{ op: 'op', path: 'path' }] }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -42,16 +36,11 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { - const response = await client.users.tokens.update('token', { - user_id: 'user_id', - patch: [ - { - op: 'op', - path: 'path', - value: 'value', - }, - ], - }); + const response = await client.users.tokens.update('token', { user_id: 'user_id', patch: [{ + op: 'op', + path: 'path', + value: 'value', + }] }); }); // Mock server tests are disabled @@ -97,10 +86,7 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('addSingle: only required params', async () => { - const responsePromise = client.users.tokens.addSingle('token', { - user_id: 'user_id', - provider_key: 'firebase-fcm', - }); + const responsePromise = client.users.tokens.addSingle('token', { user_id: 'user_id', provider_key: 'firebase-fcm' }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -113,24 +99,24 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('addSingle: required and optional params', async () => { const response = await client.users.tokens.addSingle('token', { - user_id: 'user_id', - provider_key: 'firebase-fcm', - device: { - ad_id: 'ad_id', - app_id: 'app_id', - device_id: 'device_id', - manufacturer: 'manufacturer', - model: 'model', - platform: 'platform', - }, - expiry_date: 'string', - properties: {}, - tracking: { - ip: 'ip', - lat: 'lat', - long: 'long', - os_version: 'os_version', - }, - }); + user_id: 'user_id', + provider_key: 'firebase-fcm', + device: { + ad_id: 'ad_id', + app_id: 'app_id', + device_id: 'device_id', + manufacturer: 'manufacturer', + model: 'model', + platform: 'platform', + }, + expiry_date: 'string', + properties: {}, + tracking: { + ip: 'ip', + lat: 'lat', + long: 'long', + os_version: 'os_version', + }, + }); }); }); diff --git a/tests/index.test.ts b/tests/index.test.ts index 1b3e28ed..7c762b31 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -21,10 +21,10 @@ describe('instantiate client', () => { describe('defaultHeaders', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultHeaders: { 'X-My-Default-Header': '2' }, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + defaultHeaders: { 'X-My-Default-Header': '2' }, + apiKey: 'My API Key', +}) test('they are used in the request', async () => { const { req } = await client.buildRequest({ path: '/foo', method: 'post' }); @@ -49,193 +49,191 @@ describe('instantiate client', () => { expect(req.headers.has('x-my-default-header')).toBe(false); }); }); - describe('logging', () => { - const env = process.env; +describe('logging', () => { + const env = process.env; - beforeEach(() => { - process.env = { ...env }; - process.env['COURIER_LOG'] = undefined; - }); + beforeEach(() => { + process.env = { ...env }; + process.env['COURIER_LOG'] = undefined; + }); - afterEach(() => { - process.env = env; - }); + afterEach(() => { + process.env = env; + }); - const forceAPIResponseForClient = async (client: Courier) => { - await new APIPromise( - client, - Promise.resolve({ - response: new Response(), - controller: new AbortController(), - requestLogID: 'log_000000', - retryOfRequestLogID: undefined, - startTime: Date.now(), - options: { - method: 'get', - path: '/', - }, - }), - ); + const forceAPIResponseForClient = async (client: Courier) => { + await new APIPromise( + client, + Promise.resolve({ + response: new Response(), + controller: new AbortController(), + requestLogID: 'log_000000', + retryOfRequestLogID: undefined, + startTime: Date.now(), + options: { + method: 'get', + path: '/', + }, + }), + ); + }; + + test('debug logs when log level is debug', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), }; - test('debug logs when log level is debug', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; - - const client = new Courier({ - logger: logger, - logLevel: 'debug', - apiKey: 'My API Key', - }); + const client = new Courier({ + logger: logger, + logLevel: 'debug', + apiKey: 'My API Key', +}); - await forceAPIResponseForClient(client); - expect(debugMock).toHaveBeenCalled(); - }); + await forceAPIResponseForClient(client); + expect(debugMock).toHaveBeenCalled(); + }); - test('default logLevel is warn', async () => { - const client = new Courier({ apiKey: 'My API Key' }); - expect(client.logLevel).toBe('warn'); - }); + test('default logLevel is warn', async () => { + const client = new Courier({ apiKey: 'My API Key' }); + expect(client.logLevel).toBe('warn'); + }); - test('debug logs are skipped when log level is info', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; + test('debug logs are skipped when log level is info', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - const client = new Courier({ - logger: logger, - logLevel: 'info', - apiKey: 'My API Key', - }); + const client = new Courier({ + logger: logger, + logLevel: 'info', + apiKey: 'My API Key', +}); - await forceAPIResponseForClient(client); - expect(debugMock).not.toHaveBeenCalled(); - }); + await forceAPIResponseForClient(client); + expect(debugMock).not.toHaveBeenCalled(); + }); - test('debug logs happen with debug env var', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; + test('debug logs happen with debug env var', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - process.env['COURIER_LOG'] = 'debug'; - const client = new Courier({ logger: logger, apiKey: 'My API Key' }); - expect(client.logLevel).toBe('debug'); + process.env['COURIER_LOG'] = 'debug'; + const client = new Courier({ logger: logger, apiKey: 'My API Key' }); + expect(client.logLevel).toBe('debug'); - await forceAPIResponseForClient(client); - expect(debugMock).toHaveBeenCalled(); - }); + await forceAPIResponseForClient(client); + expect(debugMock).toHaveBeenCalled(); + }); - test('warn when env var level is invalid', async () => { - const warnMock = jest.fn(); - const logger = { - debug: jest.fn(), - info: jest.fn(), - warn: warnMock, - error: jest.fn(), - }; + test('warn when env var level is invalid', async () => { + const warnMock = jest.fn(); + const logger = { + debug: jest.fn(), + info: jest.fn(), + warn: warnMock, + error: jest.fn(), + }; - process.env['COURIER_LOG'] = 'not a log level'; - const client = new Courier({ logger: logger, apiKey: 'My API Key' }); - expect(client.logLevel).toBe('warn'); - expect(warnMock).toHaveBeenCalledWith( - 'process.env[\'COURIER_LOG\'] was set to "not a log level", expected one of ["off","error","warn","info","debug"]', - ); - }); + process.env['COURIER_LOG'] = 'not a log level'; + const client = new Courier({ logger: logger, apiKey: 'My API Key' }); + expect(client.logLevel).toBe('warn'); + expect(warnMock).toHaveBeenCalledWith('process.env[\'COURIER_LOG\'] was set to "not a log level", expected one of ["off","error","warn","info","debug"]'); + }); - test('client log level overrides env var', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; + test('client log level overrides env var', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - process.env['COURIER_LOG'] = 'debug'; - const client = new Courier({ - logger: logger, - logLevel: 'off', - apiKey: 'My API Key', - }); + process.env['COURIER_LOG'] = 'debug'; + const client = new Courier({ + logger: logger, + logLevel: 'off', + apiKey: 'My API Key', +}); - await forceAPIResponseForClient(client); - expect(debugMock).not.toHaveBeenCalled(); - }); + await forceAPIResponseForClient(client); + expect(debugMock).not.toHaveBeenCalled(); + }); - test('no warning logged for invalid env var level + valid client level', async () => { - const warnMock = jest.fn(); - const logger = { - debug: jest.fn(), - info: jest.fn(), - warn: warnMock, - error: jest.fn(), - }; + test('no warning logged for invalid env var level + valid client level', async () => { + const warnMock = jest.fn(); + const logger = { + debug: jest.fn(), + info: jest.fn(), + warn: warnMock, + error: jest.fn(), + }; - process.env['COURIER_LOG'] = 'not a log level'; - const client = new Courier({ - logger: logger, - logLevel: 'debug', - apiKey: 'My API Key', - }); - expect(client.logLevel).toBe('debug'); - expect(warnMock).not.toHaveBeenCalled(); - }); + process.env['COURIER_LOG'] = 'not a log level'; + const client = new Courier({ + logger: logger, + logLevel: 'debug', + apiKey: 'My API Key', +}); + expect(client.logLevel).toBe('debug'); + expect(warnMock).not.toHaveBeenCalled(); }); +}); describe('defaultQuery', () => { test('with null query params given', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultQuery: { apiVersion: 'foo' }, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + defaultQuery: { apiVersion: 'foo' }, + apiKey: 'My API Key', +}); expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo'); }); test('multiple default query params', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultQuery: { apiVersion: 'foo', hello: 'world' }, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + defaultQuery: { apiVersion: 'foo', hello: 'world' }, + apiKey: 'My API Key', +}); expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo&hello=world'); }); test('overriding with `undefined`', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultQuery: { hello: 'world' }, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + defaultQuery: { hello: 'world' }, + apiKey: 'My API Key', +}) expect(client.buildURL('/foo', { hello: undefined })).toEqual('http://localhost:5000/foo'); }); }); test('custom fetch', async () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - apiKey: 'My API Key', - fetch: (url) => { - return Promise.resolve( - new Response(JSON.stringify({ url, custom: true }), { - headers: { 'Content-Type': 'application/json' }, - }), - ); - }, - }); + baseURL: 'http://localhost:5000/', + apiKey: 'My API Key', + fetch: (url) => { + return Promise.resolve( + new Response(JSON.stringify({ url, custom: true }), { + headers: { 'Content-Type': 'application/json' }, + }), + ); +}, +}); const response = await client.get('/foo'); expect(response).toEqual({ url: 'http://localhost:5000/foo', custom: true }); @@ -244,35 +242,37 @@ describe('instantiate client', () => { test('explicit global fetch', async () => { // make sure the global fetch type is assignable to our Fetch type const client = new Courier({ - baseURL: 'http://localhost:5000/', - apiKey: 'My API Key', - fetch: defaultFetch, - }); + baseURL: 'http://localhost:5000/', + apiKey: 'My API Key', + fetch: defaultFetch, +}); }); test('custom signal', async () => { const client = new Courier({ - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', - apiKey: 'My API Key', - fetch: (...args) => { - return new Promise((resolve, reject) => - setTimeout( - () => - defaultFetch(...args) - .then(resolve) - .catch(reject), - 300, - ), - ); - }, - }); + baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010', + apiKey: 'My API Key', + fetch: (...args) => { + return new Promise((resolve, reject) => + setTimeout( + () => + defaultFetch(...args) + .then(resolve) + .catch(reject), + 300, + ), + ); +}, +}); const controller = new AbortController(); setTimeout(() => controller.abort(), 200); const spy = jest.spyOn(client, 'request'); - await expect(client.get('/foo', { signal: controller.signal })).rejects.toThrowError(APIUserAbortError); + await expect(client.get('/foo', { signal: controller.signal })).rejects.toThrowError( + APIUserAbortError, + ); expect(spy).toHaveBeenCalledTimes(1); }); @@ -284,10 +284,10 @@ describe('instantiate client', () => { }; const client = new Courier({ - baseURL: 'http://localhost:5000/', - apiKey: 'My API Key', - fetch: testFetch, - }); + baseURL: 'http://localhost:5000/', + apiKey: 'My API Key', + fetch: testFetch, +}); await client.patch('/foo'); expect(capturedRequest?.method).toEqual('PATCH'); @@ -322,35 +322,29 @@ describe('instantiate client', () => { test('empty env variable', () => { process.env['COURIER_BASE_URL'] = ''; // empty const client = new Courier({ apiKey: 'My API Key' }); - expect(client.baseURL).toEqual('https://api.courier.com'); + expect(client.baseURL).toEqual('https://api.courier.com') }); test('blank env variable', () => { process.env['COURIER_BASE_URL'] = ' '; // blank const client = new Courier({ apiKey: 'My API Key' }); - expect(client.baseURL).toEqual('https://api.courier.com'); + expect(client.baseURL).toEqual('https://api.courier.com') }); test('in request options', () => { const client = new Courier({ apiKey: 'My API Key' }); - expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual( - 'http://localhost:5000/option/foo', - ); + expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual('http://localhost:5000/option/foo'); }); test('in request options overridden by client options', () => { const client = new Courier({ apiKey: 'My API Key', baseURL: 'http://localhost:5000/client' }); - expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual( - 'http://localhost:5000/client/foo', - ); + expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual('http://localhost:5000/client/foo'); }); test('in request options overridden by env variable', () => { process.env['COURIER_BASE_URL'] = 'http://localhost:5000/env'; const client = new Courier({ apiKey: 'My API Key' }); - expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual( - 'http://localhost:5000/env/foo', - ); + expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual('http://localhost:5000/env/foo'); }); }); @@ -366,10 +360,10 @@ describe('instantiate client', () => { describe('withOptions', () => { test('creates a new client with overridden options', async () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - maxRetries: 3, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + maxRetries: 3, + apiKey: 'My API Key', + }); const newClient = client.withOptions({ maxRetries: 5, @@ -391,11 +385,11 @@ describe('instantiate client', () => { test('inherits options from the parent client', async () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultHeaders: { 'X-Test-Header': 'test-value' }, - defaultQuery: { 'test-param': 'test-value' }, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + defaultHeaders: { 'X-Test-Header': 'test-value' }, + defaultQuery: { 'test-param': 'test-value' }, + apiKey: 'My API Key', + }); const newClient = client.withOptions({ baseURL: 'http://localhost:5001/', @@ -410,10 +404,10 @@ describe('instantiate client', () => { test('respects runtime property changes when creating new client', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - timeout: 1000, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + timeout: 1000, + apiKey: 'My API Key', + }); // Modify the client properties directly after creation client.baseURL = 'http://localhost:6000/'; @@ -459,18 +453,13 @@ describe('request building', () => { describe('custom headers', () => { test('handles undefined', async () => { - const { req } = await client.buildRequest({ - path: '/foo', - method: 'post', - body: { value: 'hello' }, - headers: { 'X-Foo': 'baz', 'x-foo': 'bar', 'x-Foo': undefined, 'x-baz': 'bam', 'X-Baz': null }, - }); + const { req } = await client.buildRequest({ path: '/foo', method: 'post', body: { value: 'hello' }, headers: { 'X-Foo': 'baz', 'x-foo': 'bar', 'x-Foo': undefined, 'x-baz': 'bam', 'X-Baz': null } }); expect(req.headers.get('x-foo')).toEqual('bar'); expect(req.headers.get('x-Foo')).toEqual('bar'); expect(req.headers.get('X-Foo')).toEqual('bar'); expect(req.headers.get('x-baz')).toEqual(null); }); - }); + }) }); describe('default encoder', () => { @@ -547,40 +536,37 @@ describe('default encoder', () => { describe('retries', () => { test('retry on timeout', async () => { let count = 0; - const testFetch = async ( - url: string | URL | Request, - { signal }: RequestInit = {}, - ): Promise => { - if (count++ === 0) { - return new Promise( - (resolve, reject) => signal?.addEventListener('abort', () => reject(new Error('timed out'))), - ); - } - return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); - }; - - const client = new Courier({ - apiKey: 'My API Key', - timeout: 10, - fetch: testFetch, - }); + const testFetch = async (url: string | URL | Request, { signal }: RequestInit = {}): Promise => { + if (count++ === 0) { + return new Promise((resolve, reject) => + signal?.addEventListener('abort', () => reject(new Error('timed out'))), + ); + } + return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); + }; - expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 }); - expect(count).toEqual(2); - expect( - await client - .request({ path: '/foo', method: 'get' }) - .asResponse() - .then((r) => r.text()), - ).toEqual(JSON.stringify({ a: 1 })); - expect(count).toEqual(3); + const client = new Courier({ + apiKey: 'My API Key', + timeout: 10, + fetch: testFetch, }); + expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 }); + expect(count).toEqual(2); + expect( + await client + .request({ path: '/foo', method: 'get' }) + .asResponse() + .then((r) => r.text()), + ).toEqual(JSON.stringify({ a: 1 })); + expect(count).toEqual(3); + }); + test('retry count header', async () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++; + count++ if (count <= 2) { return new Response(undefined, { status: 429, @@ -594,10 +580,10 @@ describe('retries', () => { }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + }); expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 }); @@ -609,7 +595,7 @@ describe('retries', () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++; + count++ if (count <= 2) { return new Response(undefined, { status: 429, @@ -622,10 +608,10 @@ describe('retries', () => { return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + }); expect( await client.request({ @@ -642,7 +628,7 @@ describe('retries', () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++; + count++ if (count <= 2) { return new Response(undefined, { status: 429, @@ -655,11 +641,11 @@ describe('retries', () => { return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - defaultHeaders: { 'X-Stainless-Retry-Count': null }, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + defaultHeaders: { 'X-Stainless-Retry-Count': null }, + }); expect( await client.request({ @@ -675,7 +661,7 @@ describe('retries', () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++; + count++ if (count <= 2) { return new Response(undefined, { status: 429, @@ -688,10 +674,10 @@ describe('retries', () => { return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + }); expect( await client.request({ @@ -706,10 +692,7 @@ describe('retries', () => { test('retry on 429 with retry-after', async () => { let count = 0; - const testFetch = async ( - url: string | URL | Request, - { signal }: RequestInit = {}, - ): Promise => { + const testFetch = async (url: string | URL | Request, { signal }: RequestInit = {}): Promise => { if (count++ === 0) { return new Response(undefined, { status: 429, @@ -736,10 +719,7 @@ describe('retries', () => { test('retry on 429 with retry-after-ms', async () => { let count = 0; - const testFetch = async ( - url: string | URL | Request, - { signal }: RequestInit = {}, - ): Promise => { + const testFetch = async (url: string | URL | Request, { signal }: RequestInit = {}): Promise => { if (count++ === 0) { return new Response(undefined, { status: 429, diff --git a/tests/qs/utils.test.ts b/tests/qs/utils.test.ts index 5f290114..0a91b186 100644 --- a/tests/qs/utils.test.ts +++ b/tests/qs/utils.test.ts @@ -66,7 +66,7 @@ describe('merge()', function () { // st.equal(getCount, 1); expect(setCount).toEqual(0); expect(getCount).toEqual(1); - observed[0] = observed[0]; + observed[0] = observed[0]; // st.equal(setCount, 1); // st.equal(getCount, 2); expect(setCount).toEqual(1); diff --git a/tests/stringifyQuery.test.ts b/tests/stringifyQuery.test.ts index 315ab571..43a9c77f 100644 --- a/tests/stringifyQuery.test.ts +++ b/tests/stringifyQuery.test.ts @@ -2,20 +2,18 @@ import { stringifyQuery } from '@trycourier/courier/internal/utils/query'; -describe(stringifyQuery, () => { - for (const [input, expected] of [ - [{ a: '1', b: 2, c: true }, 'a=1&b=2&c=true'], - [{ a: null, b: false, c: undefined }, 'a=&b=false'], - [{ 'a/b': 1.28341 }, `${encodeURIComponent('a/b')}=1.28341`], - [ - { 'a/b': 'c/d', 'e=f': 'g&h' }, - `${encodeURIComponent('a/b')}=${encodeURIComponent('c/d')}&${encodeURIComponent( - 'e=f', - )}=${encodeURIComponent('g&h')}`, - ], - ] as const) { - it(`${JSON.stringify(input)} -> ${expected}`, () => { - expect(stringifyQuery(input)).toEqual(expected); - }); - } -}); +describe(stringifyQuery, () => { for (const [input, expected] of [ + [{ a: '1', b: 2, c: true }, 'a=1&b=2&c=true'], + [{ a: null, b: false, c: undefined }, 'a=&b=false'], + [{ 'a/b': 1.28341 }, `${encodeURIComponent('a/b')}=1.28341`], + [ + { 'a/b': 'c/d', 'e=f': 'g&h' }, + `${encodeURIComponent('a/b')}=${encodeURIComponent('c/d')}&${encodeURIComponent( + 'e=f', + )}=${encodeURIComponent('g&h')}`, + ], +] as const) { + it(`${JSON.stringify(input)} -> ${expected}`, () => { + expect(stringifyQuery(input)).toEqual(expected); + }); +} }) diff --git a/yarn.lock b/yarn.lock index f6eae3cd..18e7cbdc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -709,11 +709,6 @@ "@nodelib/fs.scandir" "2.1.5" fastq "^1.6.0" -"@pkgr/core@^0.2.4": - version "0.2.4" - resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.2.4.tgz#d897170a2b0ba51f78a099edccd968f7b103387c" - integrity sha512-ROFF39F6ZrnzSUEmQQZUar0Jt4xVoP9WnDRdWwF4NNcXs3xBTLgBUDoOwW141y1jP+S8nahIbdxbFC7IShw9Iw== - "@sinclair/typebox@^0.27.8": version "0.27.8" resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.27.8.tgz#6667fac16c436b5434a387a34dedb013198f6e6e" @@ -1515,14 +1510,6 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== -eslint-plugin-prettier@^5.4.1: - version "5.4.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.4.1.tgz#99b55d7dd70047886b2222fdd853665f180b36af" - integrity sha512-9dF+KuU/Ilkq27A8idRP7N2DH8iUR6qXcjF3FR2wETY21PZdBrIjwCau8oboyGj9b7etWmTGEeM8e7oOed6ZWg== - dependencies: - prettier-linter-helpers "^1.0.0" - synckit "^0.11.7" - eslint-plugin-unused-imports@^4.1.4: version "4.1.4" resolved "https://registry.yarnpkg.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.1.4.tgz#62ddc7446ccbf9aa7b6f1f0b00a980423cda2738" @@ -1674,11 +1661,6 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== -fast-diff@^1.1.2: - version "1.3.0" - resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0" - integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== - fast-glob@^3.3.2: version "3.3.2" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" @@ -2841,13 +2823,6 @@ prelude-ls@^1.2.1: resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== -prettier-linter-helpers@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b" - integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w== - dependencies: - fast-diff "^1.1.2" - prettier@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.1.1.tgz#6ba9f23165d690b6cbdaa88cb0807278f7019848" @@ -3144,13 +3119,6 @@ supports-preserve-symlinks-flag@^1.0.0: resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== -synckit@^0.11.7: - version "0.11.8" - resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.11.8.tgz#b2aaae998a4ef47ded60773ad06e7cb821f55457" - integrity sha512-+XZ+r1XGIJGeQk3VvXhT6xx/VpbHsRzsTkGgF6E5RX9TTXD0118l87puaEBZ566FhqblC6U0d4XnubznJDm30A== - dependencies: - "@pkgr/core" "^0.2.4" - test-exclude@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" From 619702960b9076a75bc7138a5218d06f4b3c5dc3 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 28 Apr 2026 02:09:24 +0000 Subject: [PATCH 03/12] chore(internal): codegen related update --- eslint.config.mjs | 3 + package.json | 1 + scripts/fast-format | 6 +- scripts/format | 3 +- scripts/lint | 3 - scripts/utils/postprocess-files.cjs | 9 +- src/api-promise.ts | 2 +- src/client.ts | 927 +++++++++++------- src/core/api-promise.ts | 9 +- src/core/error.ts | 46 +- src/error.ts | 2 +- src/index.ts | 16 +- src/internal/builtin-types.ts | 23 +- src/internal/detect-platform.ts | 6 +- src/internal/errors.ts | 14 +- src/internal/headers.ts | 4 +- src/internal/parse.ts | 12 +- src/internal/qs/utils.ts | 5 +- src/internal/request-options.ts | 6 +- src/internal/shim-types.ts | 4 +- src/internal/shims.ts | 4 +- src/internal/to-file.ts | 14 +- src/internal/types.ts | 50 +- src/internal/utils/log.ts | 37 +- src/internal/utils/query.ts | 2 +- src/internal/utils/uuid.ts | 8 +- src/resource.ts | 2 +- src/resources/audiences.ts | 24 +- src/resources/audit-events.ts | 7 +- src/resources/auth.ts | 2 +- src/resources/automations/automations.ts | 9 +- src/resources/automations/index.ts | 10 +- src/resources/automations/invoke.ts | 23 +- src/resources/brands.ts | 14 +- src/resources/bulk.ts | 19 +- src/resources/inbound.ts | 2 +- src/resources/index.ts | 198 +++- src/resources/journeys.ts | 13 +- src/resources/lists/index.ts | 20 +- src/resources/lists/lists.ts | 39 +- src/resources/lists/subscriptions.ts | 47 +- src/resources/messages.ts | 42 +- src/resources/notifications/checks.ts | 25 +- src/resources/notifications/index.ts | 43 +- src/resources/notifications/notifications.ts | 95 +- src/resources/profiles/index.ts | 20 +- src/resources/profiles/lists.ts | 14 +- src/resources/profiles/profiles.ts | 36 +- src/resources/providers/catalog.ts | 10 +- src/resources/providers/index.ts | 12 +- src/resources/providers/providers.ts | 14 +- src/resources/requests.ts | 5 +- src/resources/routing-strategies.ts | 29 +- src/resources/send.ts | 26 +- src/resources/shared.ts | 47 +- src/resources/tenants/index.ts | 30 +- src/resources/tenants/preferences/index.ts | 4 +- src/resources/tenants/preferences/items.ts | 20 +- .../tenants/preferences/preferences.ts | 2 +- src/resources/tenants/templates/index.ts | 11 +- src/resources/tenants/templates/templates.ts | 42 +- src/resources/tenants/templates/versions.ts | 17 +- src/resources/tenants/tenants.ts | 33 +- src/resources/translations.ts | 14 +- src/resources/users/index.ts | 33 +- src/resources/users/preferences.ts | 30 +- src/resources/users/tenants.ts | 40 +- src/resources/users/tokens.ts | 38 +- src/resources/users/users.ts | 37 +- src/uploads.ts | 2 +- src/version.ts | 2 +- tests/api-resources/audiences.test.ts | 17 +- tests/api-resources/audit-events.test.ts | 11 +- tests/api-resources/auth.test.ts | 17 +- .../automations/automations.test.ts | 14 +- .../api-resources/automations/invoke.test.ts | 67 +- tests/api-resources/brands.test.ts | 189 ++-- tests/api-resources/bulk.test.ts | 129 +-- tests/api-resources/inbound.test.ts | 43 +- tests/api-resources/journeys.test.ts | 11 +- tests/api-resources/lists/lists.test.ts | 43 +- .../api-resources/lists/subscriptions.test.ts | 127 ++- tests/api-resources/messages.test.ts | 50 +- .../notifications/checks.test.ts | 35 +- .../notifications/notifications.test.ts | 167 ++-- tests/api-resources/profiles/lists.test.ts | 49 +- tests/api-resources/profiles/profiles.test.ts | 33 +- tests/api-resources/providers/catalog.test.ts | 22 +- .../api-resources/providers/providers.test.ts | 31 +- tests/api-resources/requests.test.ts | 5 +- .../api-resources/routing-strategies.test.ts | 177 ++-- tests/api-resources/send.test.ts | 193 ++-- .../tenants/preferences/items.test.ts | 20 +- .../tenants/templates/templates.test.ts | 119 ++- .../tenants/templates/versions.test.ts | 15 +- tests/api-resources/tenants/tenants.test.ts | 60 +- tests/api-resources/translations.test.ts | 5 +- tests/api-resources/users/preferences.test.ts | 42 +- tests/api-resources/users/tenants.test.ts | 41 +- tests/api-resources/users/tokens.test.ts | 68 +- tests/index.test.ts | 498 +++++----- tests/qs/utils.test.ts | 2 +- tests/stringifyQuery.test.ts | 32 +- yarn.lock | 32 + 104 files changed, 3074 insertions(+), 1708 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index 07b28b78..7850bf49 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,6 +1,7 @@ // @ts-check import tseslint from 'typescript-eslint'; import unusedImports from 'eslint-plugin-unused-imports'; +import prettier from 'eslint-plugin-prettier'; export default tseslint.config( { @@ -13,9 +14,11 @@ export default tseslint.config( plugins: { '@typescript-eslint': tseslint.plugin, 'unused-imports': unusedImports, + prettier, }, rules: { 'no-unused-vars': 'off', + 'prettier/prettier': 'error', 'unused-imports/no-unused-imports': 'error', 'no-restricted-imports': [ 'error', diff --git a/package.json b/package.json index 7d86550e..8aeaadf7 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "@typescript-eslint/eslint-plugin": "8.31.1", "@typescript-eslint/parser": "8.31.1", "eslint": "^9.39.1", + "eslint-plugin-prettier": "^5.4.1", "eslint-plugin-unused-imports": "^4.1.4", "iconv-lite": "^0.6.3", "jest": "^29.4.0", diff --git a/scripts/fast-format b/scripts/fast-format index e1723136..53721ac0 100755 --- a/scripts/fast-format +++ b/scripts/fast-format @@ -31,8 +31,10 @@ if ! [ -z "$ESLINT_FILES" ]; then fi echo "==> Running prettier --write" -PRETTIER_FILES="$(grep '\.\([mc]?tsx?\|[mc]?jsx?\|json\)$' "$FILE_LIST" || true)" +# format things eslint didn't +PRETTIER_FILES="$(grep '\.\(js\|json\)$' "$FILE_LIST" || true)" if ! [ -z "$PRETTIER_FILES" ]; then echo "$PRETTIER_FILES" | xargs ./node_modules/.bin/prettier \ - --write --cache --cache-strategy metadata --no-error-on-unmatched-pattern + --write --cache --cache-strategy metadata --no-error-on-unmatched-pattern \ + '!**/dist' '!**/*.ts' '!**/*.mts' '!**/*.cts' '!**/*.js' '!**/*.mjs' '!**/*.cjs' fi diff --git a/scripts/format b/scripts/format index b1b2c17a..7a756401 100755 --- a/scripts/format +++ b/scripts/format @@ -8,4 +8,5 @@ echo "==> Running eslint --fix" ./node_modules/.bin/eslint --fix . echo "==> Running prettier --write" -./node_modules/.bin/prettier --write --cache --cache-strategy metadata . +# format things eslint didn't +./node_modules/.bin/prettier --write --cache --cache-strategy metadata . '!**/dist' '!**/*.ts' '!**/*.mts' '!**/*.cts' '!**/*.js' '!**/*.mjs' '!**/*.cjs' diff --git a/scripts/lint b/scripts/lint index 1f532548..3ffb78a6 100755 --- a/scripts/lint +++ b/scripts/lint @@ -4,9 +4,6 @@ set -e cd "$(dirname "$0")/.." -echo "==> Running prettier --check" -./node_modules/.bin/prettier --check . - echo "==> Running eslint" ./node_modules/.bin/eslint . diff --git a/scripts/utils/postprocess-files.cjs b/scripts/utils/postprocess-files.cjs index deae575e..a8cdeb7c 100644 --- a/scripts/utils/postprocess-files.cjs +++ b/scripts/utils/postprocess-files.cjs @@ -23,12 +23,19 @@ async function postprocess() { // strip out lib="dom", types="node", and types="react" references; these // are needed at build time, but would pollute the user's TS environment - const transformed = code.replace( + let transformed = code.replace( /^ *\/\/\/ * ' '.repeat(match.length - 1) + '\n', ); + // TypeScript's declaration emitter collapses /** @ts-ignore */ onto the same + // line as the type declaration, which doesn't work. So we convert to // @ts-ignore + // on its own line to properly suppresses errors. + if (file.endsWith('.d.ts') || file.endsWith('.d.mts') || file.endsWith('.d.cts')) { + transformed = transformed.replace(/\/\*\* @ts-ignore\b[^*]*\*\/ /gm, '// @ts-ignore\n'); + } + if (transformed !== code) { console.error(`wrote ${path.relative(process.cwd(), file)}`); await fs.promises.writeFile(file, transformed, 'utf8'); diff --git a/src/api-promise.ts b/src/api-promise.ts index 4e701286..8c775ee6 100644 --- a/src/api-promise.ts +++ b/src/api-promise.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/api-promise instead */ -export * from "./core/api-promise" \ No newline at end of file +export * from './core/api-promise'; diff --git a/src/client.ts b/src/client.ts index fc4e49f1..a55a0521 100644 --- a/src/client.ts +++ b/src/client.ts @@ -17,30 +17,194 @@ import * as Errors from './core/error'; import * as Uploads from './core/uploads'; import * as API from './resources/index'; import { APIPromise } from './core/api-promise'; -import { Audience, AudienceListMembersParams, AudienceListMembersResponse, AudienceListParams, AudienceListResponse, AudienceUpdateParams, AudienceUpdateResponse, Audiences } from './resources/audiences'; -import { AuditEvent, AuditEventListParams, AuditEventListResponse, AuditEvents } from './resources/audit-events'; +import { + Audience, + AudienceListMembersParams, + AudienceListMembersResponse, + AudienceListParams, + AudienceListResponse, + AudienceUpdateParams, + AudienceUpdateResponse, + Audiences, +} from './resources/audiences'; +import { + AuditEvent, + AuditEventListParams, + AuditEventListResponse, + AuditEvents, +} from './resources/audit-events'; import { Auth, AuthIssueTokenParams, AuthIssueTokenResponse } from './resources/auth'; -import { Brand, BrandColors, BrandCreateParams, BrandListParams, BrandListResponse, BrandSettings, BrandSettingsEmail, BrandSettingsInApp, BrandSnippet, BrandSnippets, BrandTemplate, BrandUpdateParams, Brands, EmailFooter, EmailHead, EmailHeader, Icons, Logo, WidgetBackground } from './resources/brands'; -import { Bulk, BulkAddUsersParams, BulkCreateJobParams, BulkCreateJobResponse, BulkListUsersParams, BulkListUsersResponse, BulkRetrieveJobResponse, InboundBulkMessage, InboundBulkMessageUser } from './resources/bulk'; +import { + Brand, + BrandColors, + BrandCreateParams, + BrandListParams, + BrandListResponse, + BrandSettings, + BrandSettingsEmail, + BrandSettingsInApp, + BrandSnippet, + BrandSnippets, + BrandTemplate, + BrandUpdateParams, + Brands, + EmailFooter, + EmailHead, + EmailHeader, + Icons, + Logo, + WidgetBackground, +} from './resources/brands'; +import { + Bulk, + BulkAddUsersParams, + BulkCreateJobParams, + BulkCreateJobResponse, + BulkListUsersParams, + BulkListUsersResponse, + BulkRetrieveJobResponse, + InboundBulkMessage, + InboundBulkMessageUser, +} from './resources/bulk'; import { Inbound, InboundTrackEventParams, InboundTrackEventResponse } from './resources/inbound'; -import { Journey, JourneyInvokeParams, JourneyListParams, Journeys, JourneysInvokeRequest, JourneysInvokeResponse, JourneysListResponse } from './resources/journeys'; -import { MessageContentResponse, MessageDetails, MessageHistoryParams, MessageHistoryResponse, MessageListParams, MessageListResponse, MessageRetrieveResponse, Messages } from './resources/messages'; +import { + Journey, + JourneyInvokeParams, + JourneyListParams, + Journeys, + JourneysInvokeRequest, + JourneysInvokeResponse, + JourneysListResponse, +} from './resources/journeys'; +import { + MessageContentResponse, + MessageDetails, + MessageHistoryParams, + MessageHistoryResponse, + MessageListParams, + MessageListResponse, + MessageRetrieveResponse, + Messages, +} from './resources/messages'; import { Requests } from './resources/requests'; -import { AssociatedNotificationListResponse, RoutingStrategies, RoutingStrategyCreateParams, RoutingStrategyCreateRequest, RoutingStrategyGetResponse, RoutingStrategyListNotificationsParams, RoutingStrategyListParams, RoutingStrategyListResponse, RoutingStrategyReplaceParams, RoutingStrategyReplaceRequest, RoutingStrategySummary } from './resources/routing-strategies'; +import { + AssociatedNotificationListResponse, + RoutingStrategies, + RoutingStrategyCreateParams, + RoutingStrategyCreateRequest, + RoutingStrategyGetResponse, + RoutingStrategyListNotificationsParams, + RoutingStrategyListParams, + RoutingStrategyListResponse, + RoutingStrategyReplaceParams, + RoutingStrategyReplaceRequest, + RoutingStrategySummary, +} from './resources/routing-strategies'; import { Send, SendMessageParams, SendMessageResponse } from './resources/send'; -import { TranslationRetrieveParams, TranslationRetrieveResponse, TranslationUpdateParams, Translations } from './resources/translations'; -import { AutomationInvokeResponse, AutomationListParams, AutomationTemplate, AutomationTemplateListResponse, Automations } from './resources/automations/automations'; -import { ListListParams, ListListResponse, ListRestoreParams, ListUpdateParams, Lists, PutSubscriptionsRecipient, SubscriptionList } from './resources/lists/lists'; -import { BaseCheck, Check, ElementWithChecksums, NotificationContentGetResponse, NotificationContentMutationResponse, NotificationContentPutRequest, NotificationCreateParams, NotificationElementPutRequest, NotificationGetContent, NotificationListParams, NotificationListResponse, NotificationListVersionsParams, NotificationLocalePutRequest, NotificationPublishParams, NotificationPutContentParams, NotificationPutElementParams, NotificationPutLocaleParams, NotificationReplaceParams, NotificationRetrieveContentParams, NotificationRetrieveContentResponse, NotificationRetrieveParams, NotificationTemplateCreateRequest, NotificationTemplatePayload, NotificationTemplatePublishRequest, NotificationTemplateResponse, NotificationTemplateState, NotificationTemplateSummary, NotificationTemplateUpdateRequest, NotificationTemplateVersionListResponse, Notifications, VersionNode } from './resources/notifications/notifications'; -import { ProfileCreateParams, ProfileCreateResponse, ProfileReplaceParams, ProfileReplaceResponse, ProfileRetrieveResponse, ProfileUpdateParams, Profiles, SubscribeToListsRequestItem } from './resources/profiles/profiles'; -import { Provider, ProviderCreateParams, ProviderListParams, ProviderListResponse, ProviderUpdateParams, Providers, ProvidersCatalogEntry } from './resources/providers/providers'; -import { BaseTemplateTenantAssociation, DefaultPreferences, PostTenantTemplatePublishRequest, PostTenantTemplatePublishResponse, PutTenantTemplateRequest, PutTenantTemplateResponse, SubscriptionTopicNew, Tenant, TenantAssociation, TenantListParams, TenantListResponse, TenantListUsersParams, TenantListUsersResponse, TenantTemplateInput, TenantUpdateParams, Tenants } from './resources/tenants/tenants'; +import { + TranslationRetrieveParams, + TranslationRetrieveResponse, + TranslationUpdateParams, + Translations, +} from './resources/translations'; +import { + AutomationInvokeResponse, + AutomationListParams, + AutomationTemplate, + AutomationTemplateListResponse, + Automations, +} from './resources/automations/automations'; +import { + ListListParams, + ListListResponse, + ListRestoreParams, + ListUpdateParams, + Lists, + PutSubscriptionsRecipient, + SubscriptionList, +} from './resources/lists/lists'; +import { + BaseCheck, + Check, + ElementWithChecksums, + NotificationContentGetResponse, + NotificationContentMutationResponse, + NotificationContentPutRequest, + NotificationCreateParams, + NotificationElementPutRequest, + NotificationGetContent, + NotificationListParams, + NotificationListResponse, + NotificationListVersionsParams, + NotificationLocalePutRequest, + NotificationPublishParams, + NotificationPutContentParams, + NotificationPutElementParams, + NotificationPutLocaleParams, + NotificationReplaceParams, + NotificationRetrieveContentParams, + NotificationRetrieveContentResponse, + NotificationRetrieveParams, + NotificationTemplateCreateRequest, + NotificationTemplatePayload, + NotificationTemplatePublishRequest, + NotificationTemplateResponse, + NotificationTemplateState, + NotificationTemplateSummary, + NotificationTemplateUpdateRequest, + NotificationTemplateVersionListResponse, + Notifications, + VersionNode, +} from './resources/notifications/notifications'; +import { + ProfileCreateParams, + ProfileCreateResponse, + ProfileReplaceParams, + ProfileReplaceResponse, + ProfileRetrieveResponse, + ProfileUpdateParams, + Profiles, + SubscribeToListsRequestItem, +} from './resources/profiles/profiles'; +import { + Provider, + ProviderCreateParams, + ProviderListParams, + ProviderListResponse, + ProviderUpdateParams, + Providers, + ProvidersCatalogEntry, +} from './resources/providers/providers'; +import { + BaseTemplateTenantAssociation, + DefaultPreferences, + PostTenantTemplatePublishRequest, + PostTenantTemplatePublishResponse, + PutTenantTemplateRequest, + PutTenantTemplateResponse, + SubscriptionTopicNew, + Tenant, + TenantAssociation, + TenantListParams, + TenantListResponse, + TenantListUsersParams, + TenantListUsersResponse, + TenantTemplateInput, + TenantUpdateParams, + Tenants, +} from './resources/tenants/tenants'; import { Users } from './resources/users/users'; import { type Fetch } from './internal/builtin-types'; import { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers'; import { FinalRequestOptions, RequestOptions } from './internal/request-options'; import { readEnv } from './internal/utils/env'; -import { type LogLevel, type Logger, formatRequestDetails, loggerFor, parseLogLevel } from './internal/utils/log'; +import { + type LogLevel, + type Logger, + formatRequestDetails, + loggerFor, + parseLogLevel, +} from './internal/utils/log'; import { isEmptyObj } from './internal/utils/values'; export interface ClientOptions { @@ -119,7 +283,7 @@ export interface ClientOptions { } /** - * API Client for interfacing with the Courier API. + * API Client for interfacing with the Courier API. */ export class Courier { apiKey: string; @@ -155,7 +319,7 @@ export class Courier { }: ClientOptions = {}) { if (apiKey === undefined) { throw new Errors.CourierError( - 'The COURIER_API_KEY environment variable is missing or empty; either provide it, or instantiate the Courier client with an apiKey option, like new Courier({ apiKey: \'My API Key\' }).' + "The COURIER_API_KEY environment variable is missing or empty; either provide it, or instantiate the Courier client with an apiKey option, like new Courier({ apiKey: 'My API Key' }).", ); } @@ -171,7 +335,10 @@ export class Courier { const defaultLogLevel = 'warn'; // Set default logLevel early so that we can log a warning in parseLogLevel. this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? parseLogLevel(readEnv('COURIER_LOG'), 'process.env[\'COURIER_LOG\']', this) ?? defaultLogLevel; + this.logLevel = + parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + parseLogLevel(readEnv('COURIER_LOG'), "process.env['COURIER_LOG']", this) ?? + defaultLogLevel; this.fetchOptions = options.fetchOptions; this.maxRetries = options.maxRetries ?? 2; this.fetch = options.fetch ?? Shims.getDefaultFetch(); @@ -196,7 +363,7 @@ export class Courier { fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, - ...options + ...options, }); return client; } @@ -209,7 +376,7 @@ export class Courier { } protected defaultQuery(): Record | undefined { - return this._options.defaultQuery + return this._options.defaultQuery; } protected validateHeaders({ values, nulls }: NullableHeaders) { @@ -241,7 +408,11 @@ export class Courier { return Errors.APIError.generate(status, error, message, headers); } - buildURL(path: string, query: Record | null | undefined, defaultBaseURL?: string | undefined): string { + buildURL( + path: string, + query: Record | null | undefined, + defaultBaseURL?: string | undefined, + ): string { const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL; const url = isAbsoluteURL(path) ? @@ -329,7 +500,9 @@ export class Courier { await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); await this.prepareRequest(req, { url, options }); @@ -338,7 +511,16 @@ export class Courier { const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ retryOfRequestLogID, method: options.method, url, options, headers: req.headers })); + loggerFor(this).debug( + `[${requestLogID}] sending request`, + formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers, + }), + ); if (options.signal?.aborted) { throw new Errors.APIUserAbortError(); @@ -357,21 +539,45 @@ export class Courier { // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')) + const isTimeout = + isAbortError(response) || + /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`) - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, message: response.message })); + loggerFor(this).info( + `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`, + ); + loggerFor(this).debug( + `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, + formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + }), + ); return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`) - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, message: response.message })); + loggerFor(this).info( + `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`, + ); + loggerFor(this).debug( + `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, + formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + }), + ); if (isTimeout) { throw new Errors.APIConnectionTimeoutError(); } throw new Errors.APIConnectionError({ cause: response }); } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${ + response.ok ? 'succeeded' : 'failed' + } with status ${response.status} in ${headersTime - startTime}ms`; if (!response.ok) { const shouldRetry = await this.shouldRetry(response); @@ -380,27 +586,60 @@ export class Courier { // We don't need the body of this response. await Shims.CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage}`) - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, durationMs: headersTime - startTime })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug( + `[${requestLogID}] response error (${retryMessage})`, + formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + }), + ); + return this.retryRequest( + options, + retriesRemaining, + retryOfRequestLogID ?? requestLogID, + response.headers, + ); } const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`) + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); const errText = await response.text().catch((err: any) => castToError(err).message); const errJSON = safeJSON(errText) as any; const errMessage = errJSON ? undefined : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, message: errMessage, durationMs: Date.now() - startTime })); + loggerFor(this).debug( + `[${requestLogID}] response error (${retryMessage})`, + formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime, + }), + ); const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); throw err; } - loggerFor(this).info(responseInfo) - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, durationMs: headersTime - startTime })); + loggerFor(this).info(responseInfo); + loggerFor(this).debug( + `[${requestLogID}] response start`, + formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + }), + ); return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; } @@ -417,7 +656,9 @@ export class Courier { const timeout = setTimeout(abort, ms); - const isReadableBody = ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) || (typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body); + const isReadableBody = + ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) || + (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); const fetchOptions: RequestInit = { signal: controller.signal as any, @@ -432,7 +673,6 @@ export class Courier { } try { - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare return await this.fetch.call(undefined, url, fetchOptions); } finally { @@ -533,11 +773,12 @@ export class Courier { const req: FinalizedRequestInit = { method, headers: reqHeaders, - ...(options.signal && { signal: options.signal}), - ...((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream && { duplex: "half" }), + ...(options.signal && { signal: options.signal }), + ...((globalThis as any).ReadableStream && + body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }), ...(body && { body }), - ...(this.fetchOptions as any ?? {}), - ...(options.fetchOptions as any ?? {}), + ...((this.fetchOptions as any) ?? {}), + ...((options.fetchOptions as any) ?? {}), }; return { req, url, timeout: options.timeout }; @@ -562,15 +803,17 @@ export class Courier { const headers = buildHeaders([ idempotencyHeaders, - {Accept: 'application/json', - 'User-Agent': this.getUserAgent(), - 'X-Stainless-Retry-Count': String(retryCount), - ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), - ...getPlatformHeaders()}, + { + Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...getPlatformHeaders(), + }, await this.authHeaders(options), this._options.defaultHeaders, bodyHeaders, - options.headers + options.headers, ]); this.validateHeaders(headers); @@ -597,11 +840,9 @@ export class Courier { ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || - ( - typeof body === 'string' && + (typeof body === 'string' && // Preserve legacy string encoding behavior for now - headers.values.has('content-type') - ) || + headers.values.has('content-type')) || // `Blob` is superset of `File` ((globalThis as any).Blob && body instanceof (globalThis as any).Blob) || // `FormData` -> `multipart/form-data` @@ -632,7 +873,7 @@ export class Courier { } static Courier = this; - static DEFAULT_TIMEOUT = 60000 // 1 minute + static DEFAULT_TIMEOUT = 60000; // 1 minute static CourierError = Errors.CourierError; static APIError = Errors.APIError; @@ -692,295 +933,291 @@ Courier.Translations = Translations; Courier.Users = Users; export declare namespace Courier { - export type RequestOptions = Opts.RequestOptions; - - export { - Send as Send, - type SendMessageResponse as SendMessageResponse, - type SendMessageParams as SendMessageParams -}; - -export { - Audiences as Audiences, - type Audience as Audience, - type AudienceUpdateResponse as AudienceUpdateResponse, - type AudienceListResponse as AudienceListResponse, - type AudienceListMembersResponse as AudienceListMembersResponse, - type AudienceUpdateParams as AudienceUpdateParams, - type AudienceListParams as AudienceListParams, - type AudienceListMembersParams as AudienceListMembersParams -}; - -export { - Providers as Providers, - type Provider as Provider, - type ProvidersCatalogEntry as ProvidersCatalogEntry, - type ProviderListResponse as ProviderListResponse, - type ProviderCreateParams as ProviderCreateParams, - type ProviderUpdateParams as ProviderUpdateParams, - type ProviderListParams as ProviderListParams -}; - -export { - AuditEvents as AuditEvents, - type AuditEvent as AuditEvent, - type AuditEventListResponse as AuditEventListResponse, - type AuditEventListParams as AuditEventListParams -}; - -export { - Auth as Auth, - type AuthIssueTokenResponse as AuthIssueTokenResponse, - type AuthIssueTokenParams as AuthIssueTokenParams -}; - -export { - Automations as Automations, - type AutomationInvokeResponse as AutomationInvokeResponse, - type AutomationTemplate as AutomationTemplate, - type AutomationTemplateListResponse as AutomationTemplateListResponse, - type AutomationListParams as AutomationListParams -}; - -export { - Journeys as Journeys, - type Journey as Journey, - type JourneysInvokeRequest as JourneysInvokeRequest, - type JourneysInvokeResponse as JourneysInvokeResponse, - type JourneysListResponse as JourneysListResponse, - type JourneyListParams as JourneyListParams, - type JourneyInvokeParams as JourneyInvokeParams -}; - -export { - Brands as Brands, - type Brand as Brand, - type BrandColors as BrandColors, - type BrandSettings as BrandSettings, - type BrandSettingsEmail as BrandSettingsEmail, - type BrandSettingsInApp as BrandSettingsInApp, - type BrandSnippet as BrandSnippet, - type BrandSnippets as BrandSnippets, - type BrandTemplate as BrandTemplate, - type EmailFooter as EmailFooter, - type EmailHead as EmailHead, - type EmailHeader as EmailHeader, - type Icons as Icons, - type Logo as Logo, - type WidgetBackground as WidgetBackground, - type BrandListResponse as BrandListResponse, - type BrandCreateParams as BrandCreateParams, - type BrandUpdateParams as BrandUpdateParams, - type BrandListParams as BrandListParams -}; - -export { - Bulk as Bulk, - type InboundBulkMessage as InboundBulkMessage, - type InboundBulkMessageUser as InboundBulkMessageUser, - type BulkCreateJobResponse as BulkCreateJobResponse, - type BulkListUsersResponse as BulkListUsersResponse, - type BulkRetrieveJobResponse as BulkRetrieveJobResponse, - type BulkAddUsersParams as BulkAddUsersParams, - type BulkCreateJobParams as BulkCreateJobParams, - type BulkListUsersParams as BulkListUsersParams -}; - -export { - Inbound as Inbound, - type InboundTrackEventResponse as InboundTrackEventResponse, - type InboundTrackEventParams as InboundTrackEventParams -}; - -export { - Lists as Lists, - type PutSubscriptionsRecipient as PutSubscriptionsRecipient, - type SubscriptionList as SubscriptionList, - type ListListResponse as ListListResponse, - type ListUpdateParams as ListUpdateParams, - type ListListParams as ListListParams, - type ListRestoreParams as ListRestoreParams -}; - -export { - Messages as Messages, - type MessageDetails as MessageDetails, - type MessageRetrieveResponse as MessageRetrieveResponse, - type MessageListResponse as MessageListResponse, - type MessageContentResponse as MessageContentResponse, - type MessageHistoryResponse as MessageHistoryResponse, - type MessageListParams as MessageListParams, - type MessageHistoryParams as MessageHistoryParams -}; - -export { - Requests as Requests -}; - -export { - Notifications as Notifications, - type BaseCheck as BaseCheck, - type Check as Check, - type ElementWithChecksums as ElementWithChecksums, - type NotificationContentGetResponse as NotificationContentGetResponse, - type NotificationContentMutationResponse as NotificationContentMutationResponse, - type NotificationContentPutRequest as NotificationContentPutRequest, - type NotificationElementPutRequest as NotificationElementPutRequest, - type NotificationGetContent as NotificationGetContent, - type NotificationLocalePutRequest as NotificationLocalePutRequest, - type NotificationTemplateCreateRequest as NotificationTemplateCreateRequest, - type NotificationTemplatePayload as NotificationTemplatePayload, - type NotificationTemplatePublishRequest as NotificationTemplatePublishRequest, - type NotificationTemplateResponse as NotificationTemplateResponse, - type NotificationTemplateState as NotificationTemplateState, - type NotificationTemplateSummary as NotificationTemplateSummary, - type NotificationTemplateUpdateRequest as NotificationTemplateUpdateRequest, - type NotificationTemplateVersionListResponse as NotificationTemplateVersionListResponse, - type VersionNode as VersionNode, - type NotificationListResponse as NotificationListResponse, - type NotificationRetrieveContentResponse as NotificationRetrieveContentResponse, - type NotificationCreateParams as NotificationCreateParams, - type NotificationRetrieveParams as NotificationRetrieveParams, - type NotificationListParams as NotificationListParams, - type NotificationListVersionsParams as NotificationListVersionsParams, - type NotificationPublishParams as NotificationPublishParams, - type NotificationPutContentParams as NotificationPutContentParams, - type NotificationPutElementParams as NotificationPutElementParams, - type NotificationPutLocaleParams as NotificationPutLocaleParams, - type NotificationReplaceParams as NotificationReplaceParams, - type NotificationRetrieveContentParams as NotificationRetrieveContentParams -}; - -export { - RoutingStrategies as RoutingStrategies, - type AssociatedNotificationListResponse as AssociatedNotificationListResponse, - type RoutingStrategyCreateRequest as RoutingStrategyCreateRequest, - type RoutingStrategyGetResponse as RoutingStrategyGetResponse, - type RoutingStrategyListResponse as RoutingStrategyListResponse, - type RoutingStrategyReplaceRequest as RoutingStrategyReplaceRequest, - type RoutingStrategySummary as RoutingStrategySummary, - type RoutingStrategyCreateParams as RoutingStrategyCreateParams, - type RoutingStrategyListParams as RoutingStrategyListParams, - type RoutingStrategyListNotificationsParams as RoutingStrategyListNotificationsParams, - type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams -}; - -export { - Profiles as Profiles, - type SubscribeToListsRequestItem as SubscribeToListsRequestItem, - type ProfileCreateResponse as ProfileCreateResponse, - type ProfileRetrieveResponse as ProfileRetrieveResponse, - type ProfileReplaceResponse as ProfileReplaceResponse, - type ProfileCreateParams as ProfileCreateParams, - type ProfileUpdateParams as ProfileUpdateParams, - type ProfileReplaceParams as ProfileReplaceParams -}; - -export { - Tenants as Tenants, - type BaseTemplateTenantAssociation as BaseTemplateTenantAssociation, - type DefaultPreferences as DefaultPreferences, - type PostTenantTemplatePublishRequest as PostTenantTemplatePublishRequest, - type PostTenantTemplatePublishResponse as PostTenantTemplatePublishResponse, - type PutTenantTemplateRequest as PutTenantTemplateRequest, - type PutTenantTemplateResponse as PutTenantTemplateResponse, - type SubscriptionTopicNew as SubscriptionTopicNew, - type Tenant as Tenant, - type TenantAssociation as TenantAssociation, - type TenantTemplateInput as TenantTemplateInput, - type TenantListResponse as TenantListResponse, - type TenantListUsersResponse as TenantListUsersResponse, - type TenantUpdateParams as TenantUpdateParams, - type TenantListParams as TenantListParams, - type TenantListUsersParams as TenantListUsersParams -}; - -export { - Translations as Translations, - type TranslationRetrieveResponse as TranslationRetrieveResponse, - type TranslationRetrieveParams as TranslationRetrieveParams, - type TranslationUpdateParams as TranslationUpdateParams -}; - -export { - Users as Users -}; - -export type AirshipProfile = API.AirshipProfile; -export type AirshipProfileAudience = API.AirshipProfileAudience; -export type Alignment = API.Alignment; -export type AudienceFilter = API.AudienceFilter; -export type AudienceFilterConfig = API.AudienceFilterConfig; -export type AudienceRecipient = API.AudienceRecipient; -export type Channel = API.Channel; -export type ChannelClassification = API.ChannelClassification; -export type ChannelMetadata = API.ChannelMetadata; -export type ChannelPreference = API.ChannelPreference; -export type DeviceType = API.DeviceType; -export type Discord = API.Discord; -export type ElementalActionNodeWithType = API.ElementalActionNodeWithType; -export type ElementalBaseNode = API.ElementalBaseNode; -export type ElementalChannelNode = API.ElementalChannelNode; -export type ElementalChannelNodeWithType = API.ElementalChannelNodeWithType; -export type ElementalContent = API.ElementalContent; -export type ElementalContentSugar = API.ElementalContentSugar; -export type ElementalDividerNodeWithType = API.ElementalDividerNodeWithType; -export type ElementalHTMLNodeWithType = API.ElementalHTMLNodeWithType; -export type ElementalImageNodeWithType = API.ElementalImageNodeWithType; -export type ElementalMetaNodeWithType = API.ElementalMetaNodeWithType; -export type ElementalNode = API.ElementalNode; -export type ElementalQuoteNodeWithType = API.ElementalQuoteNodeWithType; -export type ElementalTextNodeWithType = API.ElementalTextNodeWithType; -export type Expo = API.Expo; -export type FilterConfig = API.FilterConfig; -export type Intercom = API.Intercom; -export type IntercomRecipient = API.IntercomRecipient; -export type ListFilter = API.ListFilter; -export type ListPatternRecipient = API.ListPatternRecipient; -export type ListRecipient = API.ListRecipient; -export type MessageChannels = API.MessageChannels; -export type MessageContext = API.MessageContext; -export type MessageProviders = API.MessageProviders; -export type MessageProvidersType = API.MessageProvidersType; -export type MessageRouting = API.MessageRouting; -export type MessageRoutingChannel = API.MessageRoutingChannel; -export type Metadata = API.Metadata; -export type MsTeams = API.MsTeams; -export type MsTeamsBaseProperties = API.MsTeamsBaseProperties; -export type MsTeamsRecipient = API.MsTeamsRecipient; -export type MultipleTokens = API.MultipleTokens; -export type NotificationPreferenceDetails = API.NotificationPreferenceDetails; -export type Pagerduty = API.Pagerduty; -export type PagerdutyRecipient = API.PagerdutyRecipient; -export type Paging = API.Paging; -export type Preference = API.Preference; -export type PreferenceStatus = API.PreferenceStatus; -export type RecipientPreferences = API.RecipientPreferences; -export type Rule = API.Rule; -export type SendDirectMessage = API.SendDirectMessage; -export type SendToChannel = API.SendToChannel; -export type SendToMsTeamsChannelID = API.SendToMsTeamsChannelID; -export type SendToMsTeamsChannelName = API.SendToMsTeamsChannelName; -export type SendToMsTeamsConversationID = API.SendToMsTeamsConversationID; -export type SendToMsTeamsEmail = API.SendToMsTeamsEmail; -export type SendToMsTeamsUserID = API.SendToMsTeamsUserID; -export type SendToSlackChannel = API.SendToSlackChannel; -export type SendToSlackEmail = API.SendToSlackEmail; -export type SendToSlackUserID = API.SendToSlackUserID; -export type Slack = API.Slack; -export type SlackBaseProperties = API.SlackBaseProperties; -export type SlackRecipient = API.SlackRecipient; -export type TextStyle = API.TextStyle; -export type Timeouts = API.Timeouts; -export type Token = API.Token; -export type UserProfile = API.UserProfile; -export type UserProfileFirebaseToken = API.UserProfileFirebaseToken; -export type UserRecipient = API.UserRecipient; -export type Utm = API.Utm; -export type WebhookAuthMode = API.WebhookAuthMode; -export type WebhookAuthentication = API.WebhookAuthentication; -export type WebhookMethod = API.WebhookMethod; -export type WebhookProfile = API.WebhookProfile; -export type WebhookProfileType = API.WebhookProfileType; -export type WebhookRecipient = API.WebhookRecipient; - } + export type RequestOptions = Opts.RequestOptions; + + export { + Send as Send, + type SendMessageResponse as SendMessageResponse, + type SendMessageParams as SendMessageParams, + }; + + export { + Audiences as Audiences, + type Audience as Audience, + type AudienceUpdateResponse as AudienceUpdateResponse, + type AudienceListResponse as AudienceListResponse, + type AudienceListMembersResponse as AudienceListMembersResponse, + type AudienceUpdateParams as AudienceUpdateParams, + type AudienceListParams as AudienceListParams, + type AudienceListMembersParams as AudienceListMembersParams, + }; + + export { + Providers as Providers, + type Provider as Provider, + type ProvidersCatalogEntry as ProvidersCatalogEntry, + type ProviderListResponse as ProviderListResponse, + type ProviderCreateParams as ProviderCreateParams, + type ProviderUpdateParams as ProviderUpdateParams, + type ProviderListParams as ProviderListParams, + }; + + export { + AuditEvents as AuditEvents, + type AuditEvent as AuditEvent, + type AuditEventListResponse as AuditEventListResponse, + type AuditEventListParams as AuditEventListParams, + }; + + export { + Auth as Auth, + type AuthIssueTokenResponse as AuthIssueTokenResponse, + type AuthIssueTokenParams as AuthIssueTokenParams, + }; + + export { + Automations as Automations, + type AutomationInvokeResponse as AutomationInvokeResponse, + type AutomationTemplate as AutomationTemplate, + type AutomationTemplateListResponse as AutomationTemplateListResponse, + type AutomationListParams as AutomationListParams, + }; + + export { + Journeys as Journeys, + type Journey as Journey, + type JourneysInvokeRequest as JourneysInvokeRequest, + type JourneysInvokeResponse as JourneysInvokeResponse, + type JourneysListResponse as JourneysListResponse, + type JourneyListParams as JourneyListParams, + type JourneyInvokeParams as JourneyInvokeParams, + }; + + export { + Brands as Brands, + type Brand as Brand, + type BrandColors as BrandColors, + type BrandSettings as BrandSettings, + type BrandSettingsEmail as BrandSettingsEmail, + type BrandSettingsInApp as BrandSettingsInApp, + type BrandSnippet as BrandSnippet, + type BrandSnippets as BrandSnippets, + type BrandTemplate as BrandTemplate, + type EmailFooter as EmailFooter, + type EmailHead as EmailHead, + type EmailHeader as EmailHeader, + type Icons as Icons, + type Logo as Logo, + type WidgetBackground as WidgetBackground, + type BrandListResponse as BrandListResponse, + type BrandCreateParams as BrandCreateParams, + type BrandUpdateParams as BrandUpdateParams, + type BrandListParams as BrandListParams, + }; + + export { + Bulk as Bulk, + type InboundBulkMessage as InboundBulkMessage, + type InboundBulkMessageUser as InboundBulkMessageUser, + type BulkCreateJobResponse as BulkCreateJobResponse, + type BulkListUsersResponse as BulkListUsersResponse, + type BulkRetrieveJobResponse as BulkRetrieveJobResponse, + type BulkAddUsersParams as BulkAddUsersParams, + type BulkCreateJobParams as BulkCreateJobParams, + type BulkListUsersParams as BulkListUsersParams, + }; + + export { + Inbound as Inbound, + type InboundTrackEventResponse as InboundTrackEventResponse, + type InboundTrackEventParams as InboundTrackEventParams, + }; + + export { + Lists as Lists, + type PutSubscriptionsRecipient as PutSubscriptionsRecipient, + type SubscriptionList as SubscriptionList, + type ListListResponse as ListListResponse, + type ListUpdateParams as ListUpdateParams, + type ListListParams as ListListParams, + type ListRestoreParams as ListRestoreParams, + }; + + export { + Messages as Messages, + type MessageDetails as MessageDetails, + type MessageRetrieveResponse as MessageRetrieveResponse, + type MessageListResponse as MessageListResponse, + type MessageContentResponse as MessageContentResponse, + type MessageHistoryResponse as MessageHistoryResponse, + type MessageListParams as MessageListParams, + type MessageHistoryParams as MessageHistoryParams, + }; + + export { Requests as Requests }; + + export { + Notifications as Notifications, + type BaseCheck as BaseCheck, + type Check as Check, + type ElementWithChecksums as ElementWithChecksums, + type NotificationContentGetResponse as NotificationContentGetResponse, + type NotificationContentMutationResponse as NotificationContentMutationResponse, + type NotificationContentPutRequest as NotificationContentPutRequest, + type NotificationElementPutRequest as NotificationElementPutRequest, + type NotificationGetContent as NotificationGetContent, + type NotificationLocalePutRequest as NotificationLocalePutRequest, + type NotificationTemplateCreateRequest as NotificationTemplateCreateRequest, + type NotificationTemplatePayload as NotificationTemplatePayload, + type NotificationTemplatePublishRequest as NotificationTemplatePublishRequest, + type NotificationTemplateResponse as NotificationTemplateResponse, + type NotificationTemplateState as NotificationTemplateState, + type NotificationTemplateSummary as NotificationTemplateSummary, + type NotificationTemplateUpdateRequest as NotificationTemplateUpdateRequest, + type NotificationTemplateVersionListResponse as NotificationTemplateVersionListResponse, + type VersionNode as VersionNode, + type NotificationListResponse as NotificationListResponse, + type NotificationRetrieveContentResponse as NotificationRetrieveContentResponse, + type NotificationCreateParams as NotificationCreateParams, + type NotificationRetrieveParams as NotificationRetrieveParams, + type NotificationListParams as NotificationListParams, + type NotificationListVersionsParams as NotificationListVersionsParams, + type NotificationPublishParams as NotificationPublishParams, + type NotificationPutContentParams as NotificationPutContentParams, + type NotificationPutElementParams as NotificationPutElementParams, + type NotificationPutLocaleParams as NotificationPutLocaleParams, + type NotificationReplaceParams as NotificationReplaceParams, + type NotificationRetrieveContentParams as NotificationRetrieveContentParams, + }; + + export { + RoutingStrategies as RoutingStrategies, + type AssociatedNotificationListResponse as AssociatedNotificationListResponse, + type RoutingStrategyCreateRequest as RoutingStrategyCreateRequest, + type RoutingStrategyGetResponse as RoutingStrategyGetResponse, + type RoutingStrategyListResponse as RoutingStrategyListResponse, + type RoutingStrategyReplaceRequest as RoutingStrategyReplaceRequest, + type RoutingStrategySummary as RoutingStrategySummary, + type RoutingStrategyCreateParams as RoutingStrategyCreateParams, + type RoutingStrategyListParams as RoutingStrategyListParams, + type RoutingStrategyListNotificationsParams as RoutingStrategyListNotificationsParams, + type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams, + }; + + export { + Profiles as Profiles, + type SubscribeToListsRequestItem as SubscribeToListsRequestItem, + type ProfileCreateResponse as ProfileCreateResponse, + type ProfileRetrieveResponse as ProfileRetrieveResponse, + type ProfileReplaceResponse as ProfileReplaceResponse, + type ProfileCreateParams as ProfileCreateParams, + type ProfileUpdateParams as ProfileUpdateParams, + type ProfileReplaceParams as ProfileReplaceParams, + }; + + export { + Tenants as Tenants, + type BaseTemplateTenantAssociation as BaseTemplateTenantAssociation, + type DefaultPreferences as DefaultPreferences, + type PostTenantTemplatePublishRequest as PostTenantTemplatePublishRequest, + type PostTenantTemplatePublishResponse as PostTenantTemplatePublishResponse, + type PutTenantTemplateRequest as PutTenantTemplateRequest, + type PutTenantTemplateResponse as PutTenantTemplateResponse, + type SubscriptionTopicNew as SubscriptionTopicNew, + type Tenant as Tenant, + type TenantAssociation as TenantAssociation, + type TenantTemplateInput as TenantTemplateInput, + type TenantListResponse as TenantListResponse, + type TenantListUsersResponse as TenantListUsersResponse, + type TenantUpdateParams as TenantUpdateParams, + type TenantListParams as TenantListParams, + type TenantListUsersParams as TenantListUsersParams, + }; + + export { + Translations as Translations, + type TranslationRetrieveResponse as TranslationRetrieveResponse, + type TranslationRetrieveParams as TranslationRetrieveParams, + type TranslationUpdateParams as TranslationUpdateParams, + }; + + export { Users as Users }; + + export type AirshipProfile = API.AirshipProfile; + export type AirshipProfileAudience = API.AirshipProfileAudience; + export type Alignment = API.Alignment; + export type AudienceFilter = API.AudienceFilter; + export type AudienceFilterConfig = API.AudienceFilterConfig; + export type AudienceRecipient = API.AudienceRecipient; + export type Channel = API.Channel; + export type ChannelClassification = API.ChannelClassification; + export type ChannelMetadata = API.ChannelMetadata; + export type ChannelPreference = API.ChannelPreference; + export type DeviceType = API.DeviceType; + export type Discord = API.Discord; + export type ElementalActionNodeWithType = API.ElementalActionNodeWithType; + export type ElementalBaseNode = API.ElementalBaseNode; + export type ElementalChannelNode = API.ElementalChannelNode; + export type ElementalChannelNodeWithType = API.ElementalChannelNodeWithType; + export type ElementalContent = API.ElementalContent; + export type ElementalContentSugar = API.ElementalContentSugar; + export type ElementalDividerNodeWithType = API.ElementalDividerNodeWithType; + export type ElementalHTMLNodeWithType = API.ElementalHTMLNodeWithType; + export type ElementalImageNodeWithType = API.ElementalImageNodeWithType; + export type ElementalMetaNodeWithType = API.ElementalMetaNodeWithType; + export type ElementalNode = API.ElementalNode; + export type ElementalQuoteNodeWithType = API.ElementalQuoteNodeWithType; + export type ElementalTextNodeWithType = API.ElementalTextNodeWithType; + export type Expo = API.Expo; + export type FilterConfig = API.FilterConfig; + export type Intercom = API.Intercom; + export type IntercomRecipient = API.IntercomRecipient; + export type ListFilter = API.ListFilter; + export type ListPatternRecipient = API.ListPatternRecipient; + export type ListRecipient = API.ListRecipient; + export type MessageChannels = API.MessageChannels; + export type MessageContext = API.MessageContext; + export type MessageProviders = API.MessageProviders; + export type MessageProvidersType = API.MessageProvidersType; + export type MessageRouting = API.MessageRouting; + export type MessageRoutingChannel = API.MessageRoutingChannel; + export type Metadata = API.Metadata; + export type MsTeams = API.MsTeams; + export type MsTeamsBaseProperties = API.MsTeamsBaseProperties; + export type MsTeamsRecipient = API.MsTeamsRecipient; + export type MultipleTokens = API.MultipleTokens; + export type NotificationPreferenceDetails = API.NotificationPreferenceDetails; + export type Pagerduty = API.Pagerduty; + export type PagerdutyRecipient = API.PagerdutyRecipient; + export type Paging = API.Paging; + export type Preference = API.Preference; + export type PreferenceStatus = API.PreferenceStatus; + export type RecipientPreferences = API.RecipientPreferences; + export type Rule = API.Rule; + export type SendDirectMessage = API.SendDirectMessage; + export type SendToChannel = API.SendToChannel; + export type SendToMsTeamsChannelID = API.SendToMsTeamsChannelID; + export type SendToMsTeamsChannelName = API.SendToMsTeamsChannelName; + export type SendToMsTeamsConversationID = API.SendToMsTeamsConversationID; + export type SendToMsTeamsEmail = API.SendToMsTeamsEmail; + export type SendToMsTeamsUserID = API.SendToMsTeamsUserID; + export type SendToSlackChannel = API.SendToSlackChannel; + export type SendToSlackEmail = API.SendToSlackEmail; + export type SendToSlackUserID = API.SendToSlackUserID; + export type Slack = API.Slack; + export type SlackBaseProperties = API.SlackBaseProperties; + export type SlackRecipient = API.SlackRecipient; + export type TextStyle = API.TextStyle; + export type Timeouts = API.Timeouts; + export type Token = API.Token; + export type UserProfile = API.UserProfile; + export type UserProfileFirebaseToken = API.UserProfileFirebaseToken; + export type UserRecipient = API.UserRecipient; + export type Utm = API.Utm; + export type WebhookAuthMode = API.WebhookAuthMode; + export type WebhookAuthentication = API.WebhookAuthentication; + export type WebhookMethod = API.WebhookMethod; + export type WebhookProfile = API.WebhookProfile; + export type WebhookProfileType = API.WebhookProfileType; + export type WebhookRecipient = API.WebhookRecipient; +} diff --git a/src/core/api-promise.ts b/src/core/api-promise.ts index 75c7112c..8174c9f1 100644 --- a/src/core/api-promise.ts +++ b/src/core/api-promise.ts @@ -16,7 +16,10 @@ export class APIPromise extends Promise { constructor( client: Courier, private responsePromise: Promise, - private parseResponse: (client: Courier, props: APIResponseProps) => PromiseOrValue = defaultParseResponse, + private parseResponse: ( + client: Courier, + props: APIResponseProps, + ) => PromiseOrValue = defaultParseResponse, ) { super((resolve) => { // this is maybe a bit weird but this has to be a no-op to not implicitly @@ -28,7 +31,9 @@ export class APIPromise extends Promise { } _thenUnwrap(transform: (data: T, props: APIResponseProps) => U): APIPromise { - return new APIPromise(this.#client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + return new APIPromise(this.#client, this.responsePromise, async (client, props) => + transform(await this.parseResponse(client, props), props), + ); } /** diff --git a/src/core/error.ts b/src/core/error.ts index d91fdb38..fd075715 100644 --- a/src/core/error.ts +++ b/src/core/error.ts @@ -2,10 +2,13 @@ import { castToError } from '../internal/errors'; -export class CourierError extends Error { -} +export class CourierError extends Error {} -export class APIError extends CourierError { +export class APIError< + TStatus extends number | undefined = number | undefined, + THeaders extends Headers | undefined = Headers | undefined, + TError extends Object | undefined = Object | undefined, +> extends CourierError { /** HTTP status for the response that caused the error */ readonly status: TStatus; /** HTTP headers for the response that caused the error */ @@ -13,9 +16,6 @@ export class APIError { -} +export class BadRequestError extends APIError<400, Headers> {} -export class AuthenticationError extends APIError<401, Headers> { -} +export class AuthenticationError extends APIError<401, Headers> {} -export class PermissionDeniedError extends APIError<403, Headers> { -} +export class PermissionDeniedError extends APIError<403, Headers> {} -export class NotFoundError extends APIError<404, Headers> { -} +export class NotFoundError extends APIError<404, Headers> {} -export class ConflictError extends APIError<409, Headers> { -} +export class ConflictError extends APIError<409, Headers> {} -export class UnprocessableEntityError extends APIError<422, Headers> { -} +export class UnprocessableEntityError extends APIError<422, Headers> {} -export class RateLimitError extends APIError<429, Headers> { -} +export class RateLimitError extends APIError<429, Headers> {} -export class InternalServerError extends APIError { -} +export class InternalServerError extends APIError {} diff --git a/src/error.ts b/src/error.ts index d0832d34..fc55f46c 100644 --- a/src/error.ts +++ b/src/error.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/error instead */ -export * from "./core/error" \ No newline at end of file +export * from './core/error'; diff --git a/src/index.ts b/src/index.ts index 2ce795be..ff16c989 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,4 +5,18 @@ export { Courier as default } from './client'; export { type Uploadable, toFile } from './core/uploads'; export { APIPromise } from './core/api-promise'; export { Courier, type ClientOptions } from './client'; -export { CourierError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError } from './core/error'; +export { + CourierError, + APIError, + APIConnectionError, + APIConnectionTimeoutError, + APIUserAbortError, + NotFoundError, + ConflictError, + RateLimitError, + BadRequestError, + AuthenticationError, + InternalServerError, + PermissionDeniedError, + UnprocessableEntityError, +} from './core/error'; diff --git a/src/internal/builtin-types.ts b/src/internal/builtin-types.ts index 6059d5db..c23d3bde 100644 --- a/src/internal/builtin-types.ts +++ b/src/internal/builtin-types.ts @@ -1,23 +1,20 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export type Fetch = ( - input: string | URL | Request, - init?: RequestInit, -) => Promise +export type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise; /** * An alias to the builtin `RequestInit` type so we can * easily alias it in import statements if there are name clashes. - * - * https://developer.mozilla.org/docs/Web/API/RequestInit + * + * https://developer.mozilla.org/docs/Web/API/RequestInit */ type _RequestInit = RequestInit; /** * An alias to the builtin `Response` type so we can * easily alias it in import statements if there are name clashes. - * - * https://developer.mozilla.org/docs/Web/API/Response + * + * https://developer.mozilla.org/docs/Web/API/Response */ type _Response = Response; @@ -54,7 +51,15 @@ type _Array = Array; */ type _Record = Record; -export type { _Array as Array, _BodyInit as BodyInit, _HeadersInit as HeadersInit, _Record as Record, _RequestInfo as RequestInfo, _RequestInit as RequestInit, _Response as Response }; +export type { + _Array as Array, + _BodyInit as BodyInit, + _HeadersInit as HeadersInit, + _Record as Record, + _RequestInfo as RequestInfo, + _RequestInit as RequestInit, + _Response as Response, +}; /** * A copy of the builtin `EndingType` type as it isn't fully supported in certain diff --git a/src/internal/detect-platform.ts b/src/internal/detect-platform.ts index 394ede88..e82d95c9 100644 --- a/src/internal/detect-platform.ts +++ b/src/internal/detect-platform.ts @@ -25,7 +25,11 @@ function getDetectedPlatform(): DetectedPlatform { if (typeof EdgeRuntime !== 'undefined') { return 'edge'; } - if (Object.prototype.toString.call(typeof (globalThis as any).process !== 'undefined' ? (globalThis as any).process : 0) === '[object process]') { + if ( + Object.prototype.toString.call( + typeof (globalThis as any).process !== 'undefined' ? (globalThis as any).process : 0, + ) === '[object process]' + ) { return 'node'; } return 'unknown'; diff --git a/src/internal/errors.ts b/src/internal/errors.ts index c14a742b..82c7b14d 100644 --- a/src/internal/errors.ts +++ b/src/internal/errors.ts @@ -2,12 +2,12 @@ export function isAbortError(err: unknown) { return ( - typeof err === 'object' && err !== null && ( - // Spec-compliant fetch implementations - ('name' in err && (err as any).name === 'AbortError') || + typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && (err as any).name === 'AbortError') || // Expo fetch - ('message' in err && String((err as any).message).includes('FetchRequestCanceledException')) - ) + ('message' in err && String((err as any).message).includes('FetchRequestCanceledException'))) ); } @@ -24,10 +24,10 @@ export const castToError = (err: any): Error => { if (err.name) error.name = err.name; return error; } - } catch { } + } catch {} try { return new Error(JSON.stringify(err)); - } catch { } + } catch {} } return new Error(err); }; diff --git a/src/internal/headers.ts b/src/internal/headers.ts index fa2ea2b9..c724a9d2 100644 --- a/src/internal/headers.ts +++ b/src/internal/headers.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { isReadonlyArray } from "./utils/values"; +import { isReadonlyArray } from './utils/values'; type HeaderValue = string | undefined | null; export type HeadersLike = @@ -51,7 +51,7 @@ function* iterateHeaders(headers: HeadersLike): IterableIterator(client: Courier, props: APIResponseProps): Promise { const { response, requestLogID, retryOfRequestLogID, startTime } = props; const body = await (async () => { - // fetch refuses to read the body when the status code is 204. if (response.status === 204) { return null as T; @@ -43,6 +42,15 @@ export async function defaultParseResponse(client: Courier, props: APIRespons const text = await response.text(); return text as unknown as T; })(); - loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, body, durationMs: Date.now() - startTime })); + loggerFor(client).debug( + `[${requestLogID}] response parsed`, + formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + }), + ); return body; } diff --git a/src/internal/qs/utils.ts b/src/internal/qs/utils.ts index f21d955b..4cd56579 100644 --- a/src/internal/qs/utils.ts +++ b/src/internal/qs/utils.ts @@ -62,10 +62,7 @@ export function merge( if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { - if ( - (options && (options.plainObjects || options.allowPrototypes)) || - !has(Object.prototype, source) - ) { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { target[source] = true; } } else { diff --git a/src/internal/request-options.ts b/src/internal/request-options.ts index a8558b20..2aabf9aa 100644 --- a/src/internal/request-options.ts +++ b/src/internal/request-options.ts @@ -76,14 +76,10 @@ export type RequestOptions = { defaultBaseURL?: string | undefined; __binaryResponse?: boolean | undefined; - }; export type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit }; -export type RequestEncoder = (request: { - headers: NullableHeaders; - body: unknown; -}) => EncodedContent; +export type RequestEncoder = (request: { headers: NullableHeaders; body: unknown }) => EncodedContent; export const FallbackEncoder: RequestEncoder = ({ headers, body }) => { return { diff --git a/src/internal/shim-types.ts b/src/internal/shim-types.ts index accbf576..8ddf7b0a 100644 --- a/src/internal/shim-types.ts +++ b/src/internal/shim-types.ts @@ -19,8 +19,8 @@ type _ConditionalNodeReadableStream = typeof globalThis extends { ReadableStream: any } ? never : _NodeReadableStream; type _ReadableStream = NeverToAny< - ([0] extends [1 & _DOMReadableStream] ? never : _DOMReadableStream) | - ([0] extends [1 & _ConditionalNodeReadableStream] ? never : _ConditionalNodeReadableStream) + | ([0] extends [1 & _DOMReadableStream] ? never : _DOMReadableStream) + | ([0] extends [1 & _ConditionalNodeReadableStream] ? never : _ConditionalNodeReadableStream) >; export type { _ReadableStream as ReadableStream }; diff --git a/src/internal/shims.ts b/src/internal/shims.ts index 61f9949c..e011f197 100644 --- a/src/internal/shims.ts +++ b/src/internal/shims.ts @@ -27,7 +27,9 @@ export function makeReadableStream(...args: ReadableStreamArgs): ReadableStream if (typeof ReadableStream === 'undefined') { // Note: All of the platforms / runtimes we officially support already define // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. - throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); + throw new Error( + '`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`', + ); } return new ReadableStream(...args); diff --git a/src/internal/to-file.ts b/src/internal/to-file.ts index c72a2b41..30eada32 100644 --- a/src/internal/to-file.ts +++ b/src/internal/to-file.ts @@ -1,4 +1,4 @@ -import { BlobPart, getName, makeFile, isAsyncIterable } from "./uploads"; +import { BlobPart, getName, makeFile, isAsyncIterable } from './uploads'; import type { FilePropertyBag } from './builtin-types'; import { checkFileSupport } from './uploads'; @@ -65,8 +65,11 @@ const isResponseLike = (value: any): value is ResponseLike => typeof value.url === 'string' && typeof value.blob === 'function'; -export type ToFileInput = FileLike | ResponseLike | Exclude | AsyncIterable; - +export type ToFileInput = + | FileLike + | ResponseLike + | Exclude + | AsyncIterable; /** * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats @@ -116,9 +119,7 @@ export async function toFile( return makeFile(parts, name, options); } -async function getBytes( - value: BlobLikePart | AsyncIterable, -): Promise> { +async function getBytes(value: BlobLikePart | AsyncIterable): Promise> { let parts: Array = []; if ( typeof value === 'string' || @@ -151,4 +152,3 @@ function propsForError(value: unknown): string { const props = Object.getOwnPropertyNames(value); return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; } - diff --git a/src/internal/types.ts b/src/internal/types.ts index c45fee32..b668dfc0 100644 --- a/src/internal/types.ts +++ b/src/internal/types.ts @@ -7,34 +7,40 @@ export type KeysEnum = { [P in keyof Required]: true }; export type FinalizedRequestInit = RequestInit & { headers: Headers }; -type NotAny = [0] extends [(1 & T)] ? never : T; +type NotAny = [0] extends [1 & T] ? never : T; /** * Some environments overload the global fetch function, and Parameters only gets the last signature. */ -type OverloadedParameters = T extends { - (...args: infer A): unknown; - (...args: infer B): unknown; - (...args: infer C): unknown; - (...args: infer D): unknown; -} - ? A | B | C | D - : T extends { +type OverloadedParameters = + T extends ( + { (...args: infer A): unknown; (...args: infer B): unknown; (...args: infer C): unknown; + (...args: infer D): unknown; } - ? A | B | C - : T extends { + ) ? + A | B | C | D + : T extends ( + { + (...args: infer A): unknown; + (...args: infer B): unknown; + (...args: infer C): unknown; + } + ) ? + A | B | C + : T extends ( + { (...args: infer A): unknown; (...args: infer B): unknown; } - ? A | B - : T extends (...args: infer A) => unknown - ? A + ) ? + A | B + : T extends (...args: infer A) => unknown ? A : never; - +/* eslint-disable */ /** * These imports attempt to get types from a parent package's dependencies. * Unresolved bare specifiers can trigger [automatic type acquisition][1] in some projects, which @@ -57,19 +63,19 @@ type OverloadedParameters = T extends { * * [1]: https://www.typescriptlang.org/tsconfig/#typeAcquisition */ -/** @ts-ignore For users with \@types/node */ /* prettier-ignore */ +/** @ts-ignore For users with \@types/node */ type UndiciTypesRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with undici */ /* prettier-ignore */ +/** @ts-ignore For users with undici */ type UndiciRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with \@types/bun */ /* prettier-ignore */ +/** @ts-ignore For users with \@types/bun */ type BunRequestInit = globalThis.FetchRequestInit; -/** @ts-ignore For users with node-fetch@2 */ /* prettier-ignore */ +/** @ts-ignore For users with node-fetch@2 */ type NodeFetch2RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with node-fetch@3, doesn't need file extension because types are at ./@types/index.d.ts */ /* prettier-ignore */ +/** @ts-ignore For users with node-fetch@3, doesn't need file extension because types are at ./@types/index.d.ts */ type NodeFetch3RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users who use Deno */ /* prettier-ignore */ +/** @ts-ignore For users who use Deno */ type FetchRequestInit = NonNullable[1]>; - +/* eslint-enable */ type RequestInits = | NotAny diff --git a/src/internal/utils/log.ts b/src/internal/utils/log.ts index be2c27b4..dbbb7b33 100644 --- a/src/internal/utils/log.ts +++ b/src/internal/utils/log.ts @@ -4,7 +4,7 @@ import { hasOwn } from './values'; import { type Courier } from '../../client'; import { RequestOptions } from '../request-options'; -type LogFn = (message: string, ...rest: unknown[]) => void +type LogFn = (message: string, ...rest: unknown[]) => void; export type Logger = { error: LogFn; warn: LogFn; @@ -21,14 +21,22 @@ const levelNumbers = { debug: 500, }; -export const parseLogLevel = (maybeLevel: string | undefined, sourceName: string, client: Courier): LogLevel | undefined => { +export const parseLogLevel = ( + maybeLevel: string | undefined, + sourceName: string, + client: Courier, +): LogLevel | undefined => { if (!maybeLevel) { return undefined; } if (hasOwn(levelNumbers, maybeLevel)) { return maybeLevel; - }; - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + } + loggerFor(client).warn( + `${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify( + Object.keys(levelNumbers), + )}`, + ); return undefined; }; @@ -89,11 +97,24 @@ export const formatRequestDetails = (details: { body?: unknown; }) => { if (details.options) { - details.options = {...details.options}; + details.options = { ...details.options }; delete details.options['headers']; // redundant + leaks internals } if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, name.toLowerCase() === 'authorization' || name.toLowerCase() === 'cookie' || name.toLowerCase() === 'set-cookie' ? '***' : value])) + details.headers = Object.fromEntries( + (details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map( + ([name, value]) => [ + name, + ( + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie' + ) ? + '***' + : value, + ], + ), + ); } if ('retryOfRequestLogID' in details) { if (details.retryOfRequestLogID) { @@ -101,5 +122,5 @@ export const formatRequestDetails = (details: { } delete details.retryOfRequestLogID; } - return details -} + return details; +}; diff --git a/src/internal/utils/query.ts b/src/internal/utils/query.ts index 06e72d93..0139cacb 100644 --- a/src/internal/utils/query.ts +++ b/src/internal/utils/query.ts @@ -3,5 +3,5 @@ import * as qs from '../qs/stringify'; export function stringifyQuery(query: object | Record) { - return qs.stringify(query, { arrayFormat: 'comma' }) + return qs.stringify(query, { arrayFormat: 'comma' }); } diff --git a/src/internal/utils/uuid.ts b/src/internal/utils/uuid.ts index 53708ba6..b0e53aaf 100644 --- a/src/internal/utils/uuid.ts +++ b/src/internal/utils/uuid.ts @@ -10,10 +10,8 @@ export let uuid4 = function () { return crypto.randomUUID(); } const u8 = new Uint8Array(1); - const randomByte = crypto - ? () => crypto.getRandomValues(u8)[0]! - : () => (Math.random() * 0xff) & 0xff; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0]! : () => (Math.random() * 0xff) & 0xff; + return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16), ); -} +}; diff --git a/src/resource.ts b/src/resource.ts index 57a27a94..363e3516 100644 --- a/src/resource.ts +++ b/src/resource.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/resource instead */ -export * from "./core/resource" \ No newline at end of file +export * from './core/resource'; diff --git a/src/resources/audiences.ts b/src/resources/audiences.ts index 713f4788..c6942ae6 100644 --- a/src/resources/audiences.ts +++ b/src/resources/audiences.ts @@ -18,14 +18,21 @@ export class Audiences extends APIResource { /** * Creates or updates audience. */ - update(audienceID: string, body: AudienceUpdateParams, options?: RequestOptions): APIPromise { + update( + audienceID: string, + body: AudienceUpdateParams, + options?: RequestOptions, + ): APIPromise { return this._client.put(path`/audiences/${audienceID}`, { body, ...options }); } /** * Get the audiences associated with the authorization token. */ - list(query: AudienceListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: AudienceListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/audiences', { query, ...options }); } @@ -33,13 +40,20 @@ export class Audiences extends APIResource { * Deletes the specified audience. */ delete(audienceID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/audiences/${audienceID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/audiences/${audienceID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** * Get list of members of an audience. */ - listMembers(audienceID: string, query: AudienceListMembersParams | null | undefined = {}, options?: RequestOptions): APIPromise { + listMembers( + audienceID: string, + query: AudienceListMembersParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/audiences/${audienceID}/members`, { query, ...options }); } } @@ -149,6 +163,6 @@ export declare namespace Audiences { type AudienceListMembersResponse as AudienceListMembersResponse, type AudienceUpdateParams as AudienceUpdateParams, type AudienceListParams as AudienceListParams, - type AudienceListMembersParams as AudienceListMembersParams + type AudienceListMembersParams as AudienceListMembersParams, }; } diff --git a/src/resources/audit-events.ts b/src/resources/audit-events.ts index b5950eb6..11c35fc4 100644 --- a/src/resources/audit-events.ts +++ b/src/resources/audit-events.ts @@ -17,7 +17,10 @@ export class AuditEvents extends APIResource { /** * Fetch the list of audit events */ - list(query: AuditEventListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: AuditEventListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/audit-events', { query, ...options }); } } @@ -61,6 +64,6 @@ export declare namespace AuditEvents { export { type AuditEvent as AuditEvent, type AuditEventListResponse as AuditEventListResponse, - type AuditEventListParams as AuditEventListParams + type AuditEventListParams as AuditEventListParams, }; } diff --git a/src/resources/auth.ts b/src/resources/auth.ts index 8a3262af..0ce3ab19 100644 --- a/src/resources/auth.ts +++ b/src/resources/auth.ts @@ -65,6 +65,6 @@ export interface AuthIssueTokenParams { export declare namespace Auth { export { type AuthIssueTokenResponse as AuthIssueTokenResponse, - type AuthIssueTokenParams as AuthIssueTokenParams + type AuthIssueTokenParams as AuthIssueTokenParams, }; } diff --git a/src/resources/automations/automations.ts b/src/resources/automations/automations.ts index 6be3fa1b..6448ce72 100644 --- a/src/resources/automations/automations.ts +++ b/src/resources/automations/automations.ts @@ -18,7 +18,10 @@ export class Automations extends APIResource { * await client.automations.list(); * ``` */ - list(query: AutomationListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: AutomationListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/automations', { query, ...options }); } } @@ -84,12 +87,12 @@ export declare namespace Automations { type AutomationInvokeResponse as AutomationInvokeResponse, type AutomationTemplate as AutomationTemplate, type AutomationTemplateListResponse as AutomationTemplateListResponse, - type AutomationListParams as AutomationListParams + type AutomationListParams as AutomationListParams, }; export { Invoke as Invoke, type InvokeInvokeAdHocParams as InvokeInvokeAdHocParams, - type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams + type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams, }; } diff --git a/src/resources/automations/index.ts b/src/resources/automations/index.ts index 8ff76556..a1988573 100644 --- a/src/resources/automations/index.ts +++ b/src/resources/automations/index.ts @@ -1,4 +1,10 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Automations, type AutomationInvokeResponse, type AutomationTemplate, type AutomationTemplateListResponse, type AutomationListParams } from './automations';; -export { Invoke, type InvokeInvokeAdHocParams, type InvokeInvokeByTemplateParams } from './invoke';; +export { + Automations, + type AutomationInvokeResponse, + type AutomationTemplate, + type AutomationTemplateListResponse, + type AutomationListParams, +} from './automations'; +export { Invoke, type InvokeInvokeAdHocParams, type InvokeInvokeByTemplateParams } from './invoke'; diff --git a/src/resources/automations/invoke.ts b/src/resources/automations/invoke.ts index 8c0b9e1b..dbfebedf 100644 --- a/src/resources/automations/invoke.ts +++ b/src/resources/automations/invoke.ts @@ -33,7 +33,10 @@ export class Invoke extends APIResource { * }); * ``` */ - invokeAdHoc(body: InvokeInvokeAdHocParams, options?: RequestOptions): APIPromise { + invokeAdHoc( + body: InvokeInvokeAdHocParams, + options?: RequestOptions, + ): APIPromise { return this._client.post('/automations/invoke', { body, ...options }); } @@ -49,7 +52,11 @@ export class Invoke extends APIResource { * ); * ``` */ - invokeByTemplate(templateID: string, body: InvokeInvokeByTemplateParams, options?: RequestOptions): APIPromise { + invokeByTemplate( + templateID: string, + body: InvokeInvokeByTemplateParams, + options?: RequestOptions, + ): APIPromise { return this._client.post(path`/automations/${templateID}/invoke`, { body, ...options }); } } @@ -70,7 +77,15 @@ export interface InvokeInvokeAdHocParams { export namespace InvokeInvokeAdHocParams { export interface Automation { - steps: Array; + steps: Array< + | Automation.AutomationDelayStep + | Automation.AutomationSendStep + | Automation.AutomationSendListStep + | Automation.AutomationUpdateProfileStep + | Automation.AutomationCancelStep + | Automation.AutomationFetchDataStep + | Automation.AutomationInvokeStep + >; cancelation_token?: string | null; } @@ -167,6 +182,6 @@ export interface InvokeInvokeByTemplateParams { export declare namespace Invoke { export { type InvokeInvokeAdHocParams as InvokeInvokeAdHocParams, - type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams + type InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams, }; } diff --git a/src/resources/brands.ts b/src/resources/brands.ts index 342c1669..9a99a163 100644 --- a/src/resources/brands.ts +++ b/src/resources/brands.ts @@ -33,7 +33,10 @@ export class Brands extends APIResource { /** * Get the list of brands. */ - list(query: BrandListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: BrandListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/brands', { query, ...options }); } @@ -41,7 +44,10 @@ export class Brands extends APIResource { * Delete a brand by brand ID. */ delete(brandID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/brands/${brandID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/brands/${brandID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -68,7 +74,7 @@ export interface BrandColors { secondary?: string; -[k: string]: string | undefined + [k: string]: string | undefined; } export interface BrandSettings { @@ -232,6 +238,6 @@ export declare namespace Brands { type BrandListResponse as BrandListResponse, type BrandCreateParams as BrandCreateParams, type BrandUpdateParams as BrandUpdateParams, - type BrandListParams as BrandListParams + type BrandListParams as BrandListParams, }; } diff --git a/src/resources/bulk.ts b/src/resources/bulk.ts index 4d847204..923f1268 100644 --- a/src/resources/bulk.ts +++ b/src/resources/bulk.ts @@ -17,7 +17,11 @@ export class Bulk extends APIResource { * for email provider routing. */ addUsers(jobID: string, body: BulkAddUsersParams, options?: RequestOptions): APIPromise { - return this._client.post(path`/bulk/${jobID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.post(path`/bulk/${jobID}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -36,7 +40,11 @@ export class Bulk extends APIResource { /** * Get Bulk Job Users */ - listUsers(jobID: string, query: BulkListUsersParams | null | undefined = {}, options?: RequestOptions): APIPromise { + listUsers( + jobID: string, + query: BulkListUsersParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/bulk/${jobID}/users`, { query, ...options }); } @@ -51,7 +59,10 @@ export class Bulk extends APIResource { * Run a bulk job */ runJob(jobID: string, options?: RequestOptions): APIPromise { - return this._client.post(path`/bulk/${jobID}/run`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.post(path`/bulk/${jobID}/run`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -194,6 +205,6 @@ export declare namespace Bulk { type BulkRetrieveJobResponse as BulkRetrieveJobResponse, type BulkAddUsersParams as BulkAddUsersParams, type BulkCreateJobParams as BulkCreateJobParams, - type BulkListUsersParams as BulkListUsersParams + type BulkListUsersParams as BulkListUsersParams, }; } diff --git a/src/resources/inbound.ts b/src/resources/inbound.ts index 4fee7906..56d5d272 100644 --- a/src/resources/inbound.ts +++ b/src/resources/inbound.ts @@ -62,6 +62,6 @@ export interface InboundTrackEventParams { export declare namespace Inbound { export { type InboundTrackEventResponse as InboundTrackEventResponse, - type InboundTrackEventParams as InboundTrackEventParams + type InboundTrackEventParams as InboundTrackEventParams, }; } diff --git a/src/resources/index.ts b/src/resources/index.ts index d8dfc5f2..39e3d90d 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -1,22 +1,180 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export * from './shared';; -export { Audiences, type Audience, type AudienceUpdateResponse, type AudienceListResponse, type AudienceListMembersResponse, type AudienceUpdateParams, type AudienceListParams, type AudienceListMembersParams } from './audiences';; -export { AuditEvents, type AuditEvent, type AuditEventListResponse, type AuditEventListParams } from './audit-events';; -export { Auth, type AuthIssueTokenResponse, type AuthIssueTokenParams } from './auth';; -export { Automations, type AutomationInvokeResponse, type AutomationTemplate, type AutomationTemplateListResponse, type AutomationListParams } from './automations/automations';; -export { Brands, type Brand, type BrandColors, type BrandSettings, type BrandSettingsEmail, type BrandSettingsInApp, type BrandSnippet, type BrandSnippets, type BrandTemplate, type EmailFooter, type EmailHead, type EmailHeader, type Icons, type Logo, type WidgetBackground, type BrandListResponse, type BrandCreateParams, type BrandUpdateParams, type BrandListParams } from './brands';; -export { Bulk, type InboundBulkMessage, type InboundBulkMessageUser, type BulkCreateJobResponse, type BulkListUsersResponse, type BulkRetrieveJobResponse, type BulkAddUsersParams, type BulkCreateJobParams, type BulkListUsersParams } from './bulk';; -export { Inbound, type InboundTrackEventResponse, type InboundTrackEventParams } from './inbound';; -export { Journeys, type Journey, type JourneysInvokeRequest, type JourneysInvokeResponse, type JourneysListResponse, type JourneyListParams, type JourneyInvokeParams } from './journeys';; -export { Lists, type PutSubscriptionsRecipient, type SubscriptionList, type ListListResponse, type ListUpdateParams, type ListListParams, type ListRestoreParams } from './lists/lists';; -export { Messages, type MessageDetails, type MessageRetrieveResponse, type MessageListResponse, type MessageContentResponse, type MessageHistoryResponse, type MessageListParams, type MessageHistoryParams } from './messages';; -export { Notifications, type BaseCheck, type Check, type ElementWithChecksums, type NotificationContentGetResponse, type NotificationContentMutationResponse, type NotificationContentPutRequest, type NotificationElementPutRequest, type NotificationGetContent, type NotificationLocalePutRequest, type NotificationTemplateCreateRequest, type NotificationTemplatePayload, type NotificationTemplatePublishRequest, type NotificationTemplateResponse, type NotificationTemplateState, type NotificationTemplateSummary, type NotificationTemplateUpdateRequest, type NotificationTemplateVersionListResponse, type VersionNode, type NotificationListResponse, type NotificationRetrieveContentResponse, type NotificationCreateParams, type NotificationRetrieveParams, type NotificationListParams, type NotificationListVersionsParams, type NotificationPublishParams, type NotificationPutContentParams, type NotificationPutElementParams, type NotificationPutLocaleParams, type NotificationReplaceParams, type NotificationRetrieveContentParams } from './notifications/notifications';; -export { Profiles, type SubscribeToListsRequestItem, type ProfileCreateResponse, type ProfileRetrieveResponse, type ProfileReplaceResponse, type ProfileCreateParams, type ProfileUpdateParams, type ProfileReplaceParams } from './profiles/profiles';; -export { Providers, type Provider, type ProvidersCatalogEntry, type ProviderListResponse, type ProviderCreateParams, type ProviderUpdateParams, type ProviderListParams } from './providers/providers';; -export { Requests } from './requests';; -export { RoutingStrategies, type AssociatedNotificationListResponse, type RoutingStrategyCreateRequest, type RoutingStrategyGetResponse, type RoutingStrategyListResponse, type RoutingStrategyReplaceRequest, type RoutingStrategySummary, type RoutingStrategyCreateParams, type RoutingStrategyListParams, type RoutingStrategyListNotificationsParams, type RoutingStrategyReplaceParams } from './routing-strategies';; -export { Send, type SendMessageResponse, type SendMessageParams } from './send';; -export { Tenants, type BaseTemplateTenantAssociation, type DefaultPreferences, type PostTenantTemplatePublishRequest, type PostTenantTemplatePublishResponse, type PutTenantTemplateRequest, type PutTenantTemplateResponse, type SubscriptionTopicNew, type Tenant, type TenantAssociation, type TenantTemplateInput, type TenantListResponse, type TenantListUsersResponse, type TenantUpdateParams, type TenantListParams, type TenantListUsersParams } from './tenants/tenants';; -export { Translations, type TranslationRetrieveResponse, type TranslationRetrieveParams, type TranslationUpdateParams } from './translations';; -export { Users } from './users/users';; +export * from './shared'; +export { + Audiences, + type Audience, + type AudienceUpdateResponse, + type AudienceListResponse, + type AudienceListMembersResponse, + type AudienceUpdateParams, + type AudienceListParams, + type AudienceListMembersParams, +} from './audiences'; +export { + AuditEvents, + type AuditEvent, + type AuditEventListResponse, + type AuditEventListParams, +} from './audit-events'; +export { Auth, type AuthIssueTokenResponse, type AuthIssueTokenParams } from './auth'; +export { + Automations, + type AutomationInvokeResponse, + type AutomationTemplate, + type AutomationTemplateListResponse, + type AutomationListParams, +} from './automations/automations'; +export { + Brands, + type Brand, + type BrandColors, + type BrandSettings, + type BrandSettingsEmail, + type BrandSettingsInApp, + type BrandSnippet, + type BrandSnippets, + type BrandTemplate, + type EmailFooter, + type EmailHead, + type EmailHeader, + type Icons, + type Logo, + type WidgetBackground, + type BrandListResponse, + type BrandCreateParams, + type BrandUpdateParams, + type BrandListParams, +} from './brands'; +export { + Bulk, + type InboundBulkMessage, + type InboundBulkMessageUser, + type BulkCreateJobResponse, + type BulkListUsersResponse, + type BulkRetrieveJobResponse, + type BulkAddUsersParams, + type BulkCreateJobParams, + type BulkListUsersParams, +} from './bulk'; +export { Inbound, type InboundTrackEventResponse, type InboundTrackEventParams } from './inbound'; +export { + Journeys, + type Journey, + type JourneysInvokeRequest, + type JourneysInvokeResponse, + type JourneysListResponse, + type JourneyListParams, + type JourneyInvokeParams, +} from './journeys'; +export { + Lists, + type PutSubscriptionsRecipient, + type SubscriptionList, + type ListListResponse, + type ListUpdateParams, + type ListListParams, + type ListRestoreParams, +} from './lists/lists'; +export { + Messages, + type MessageDetails, + type MessageRetrieveResponse, + type MessageListResponse, + type MessageContentResponse, + type MessageHistoryResponse, + type MessageListParams, + type MessageHistoryParams, +} from './messages'; +export { + Notifications, + type BaseCheck, + type Check, + type ElementWithChecksums, + type NotificationContentGetResponse, + type NotificationContentMutationResponse, + type NotificationContentPutRequest, + type NotificationElementPutRequest, + type NotificationGetContent, + type NotificationLocalePutRequest, + type NotificationTemplateCreateRequest, + type NotificationTemplatePayload, + type NotificationTemplatePublishRequest, + type NotificationTemplateResponse, + type NotificationTemplateState, + type NotificationTemplateSummary, + type NotificationTemplateUpdateRequest, + type NotificationTemplateVersionListResponse, + type VersionNode, + type NotificationListResponse, + type NotificationRetrieveContentResponse, + type NotificationCreateParams, + type NotificationRetrieveParams, + type NotificationListParams, + type NotificationListVersionsParams, + type NotificationPublishParams, + type NotificationPutContentParams, + type NotificationPutElementParams, + type NotificationPutLocaleParams, + type NotificationReplaceParams, + type NotificationRetrieveContentParams, +} from './notifications/notifications'; +export { + Profiles, + type SubscribeToListsRequestItem, + type ProfileCreateResponse, + type ProfileRetrieveResponse, + type ProfileReplaceResponse, + type ProfileCreateParams, + type ProfileUpdateParams, + type ProfileReplaceParams, +} from './profiles/profiles'; +export { + Providers, + type Provider, + type ProvidersCatalogEntry, + type ProviderListResponse, + type ProviderCreateParams, + type ProviderUpdateParams, + type ProviderListParams, +} from './providers/providers'; +export { Requests } from './requests'; +export { + RoutingStrategies, + type AssociatedNotificationListResponse, + type RoutingStrategyCreateRequest, + type RoutingStrategyGetResponse, + type RoutingStrategyListResponse, + type RoutingStrategyReplaceRequest, + type RoutingStrategySummary, + type RoutingStrategyCreateParams, + type RoutingStrategyListParams, + type RoutingStrategyListNotificationsParams, + type RoutingStrategyReplaceParams, +} from './routing-strategies'; +export { Send, type SendMessageResponse, type SendMessageParams } from './send'; +export { + Tenants, + type BaseTemplateTenantAssociation, + type DefaultPreferences, + type PostTenantTemplatePublishRequest, + type PostTenantTemplatePublishResponse, + type PutTenantTemplateRequest, + type PutTenantTemplateResponse, + type SubscriptionTopicNew, + type Tenant, + type TenantAssociation, + type TenantTemplateInput, + type TenantListResponse, + type TenantListUsersResponse, + type TenantUpdateParams, + type TenantListParams, + type TenantListUsersParams, +} from './tenants/tenants'; +export { + Translations, + type TranslationRetrieveResponse, + type TranslationRetrieveParams, + type TranslationUpdateParams, +} from './translations'; +export { Users } from './users/users'; diff --git a/src/resources/journeys.ts b/src/resources/journeys.ts index 5b8a9b01..a7157480 100644 --- a/src/resources/journeys.ts +++ b/src/resources/journeys.ts @@ -14,7 +14,10 @@ export class Journeys extends APIResource { * const journeysListResponse = await client.journeys.list(); * ``` */ - list(query: JourneyListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: JourneyListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/journeys', { query, ...options }); } @@ -32,7 +35,11 @@ export class Journeys extends APIResource { * ); * ``` */ - invoke(templateID: string, body: JourneyInvokeParams, options?: RequestOptions): APIPromise { + invoke( + templateID: string, + body: JourneyInvokeParams, + options?: RequestOptions, + ): APIPromise { return this._client.post(path`/journeys/${templateID}/invoke`, { body, ...options }); } } @@ -162,6 +169,6 @@ export declare namespace Journeys { type JourneysInvokeResponse as JourneysInvokeResponse, type JourneysListResponse as JourneysListResponse, type JourneyListParams as JourneyListParams, - type JourneyInvokeParams as JourneyInvokeParams + type JourneyInvokeParams as JourneyInvokeParams, }; } diff --git a/src/resources/lists/index.ts b/src/resources/lists/index.ts index d2b5acdb..41a006b7 100644 --- a/src/resources/lists/index.ts +++ b/src/resources/lists/index.ts @@ -1,4 +1,20 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Lists, type PutSubscriptionsRecipient, type SubscriptionList, type ListListResponse, type ListUpdateParams, type ListListParams, type ListRestoreParams } from './lists';; -export { Subscriptions, type SubscriptionListResponse, type SubscriptionListParams, type SubscriptionAddParams, type SubscriptionSubscribeParams, type SubscriptionSubscribeUserParams, type SubscriptionUnsubscribeUserParams } from './subscriptions';; +export { + Lists, + type PutSubscriptionsRecipient, + type SubscriptionList, + type ListListResponse, + type ListUpdateParams, + type ListListParams, + type ListRestoreParams, +} from './lists'; +export { + Subscriptions, + type SubscriptionListResponse, + type SubscriptionListParams, + type SubscriptionAddParams, + type SubscriptionSubscribeParams, + type SubscriptionSubscribeUserParams, + type SubscriptionUnsubscribeUserParams, +} from './subscriptions'; diff --git a/src/resources/lists/lists.ts b/src/resources/lists/lists.ts index 9fa5e60e..3967f269 100644 --- a/src/resources/lists/lists.ts +++ b/src/resources/lists/lists.ts @@ -3,7 +3,15 @@ import { APIResource } from '../../core/resource'; import * as Shared from '../shared'; import * as SubscriptionsAPI from './subscriptions'; -import { SubscriptionAddParams, SubscriptionListParams, SubscriptionListResponse, SubscriptionSubscribeParams, SubscriptionSubscribeUserParams, SubscriptionUnsubscribeUserParams, Subscriptions } from './subscriptions'; +import { + SubscriptionAddParams, + SubscriptionListParams, + SubscriptionListResponse, + SubscriptionSubscribeParams, + SubscriptionSubscribeUserParams, + SubscriptionUnsubscribeUserParams, + Subscriptions, +} from './subscriptions'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -23,13 +31,20 @@ export class Lists extends APIResource { * Create or replace an existing list with the supplied values. */ update(listID: string, body: ListUpdateParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/lists/${listID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.put(path`/lists/${listID}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** * Returns all of the lists, with the ability to filter based on a pattern. */ - list(query: ListListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: ListListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/lists', { query, ...options }); } @@ -37,14 +52,21 @@ export class Lists extends APIResource { * Delete a list by list ID. */ delete(listID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/lists/${listID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/lists/${listID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** * Restore a previously deleted list. */ restore(listID: string, body: ListRestoreParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/lists/${listID}/restore`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.put(path`/lists/${listID}/restore`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -91,8 +113,7 @@ export interface ListListParams { pattern?: string | null; } -export interface ListRestoreParams { -} +export interface ListRestoreParams {} Lists.Subscriptions = Subscriptions; @@ -103,7 +124,7 @@ export declare namespace Lists { type ListListResponse as ListListResponse, type ListUpdateParams as ListUpdateParams, type ListListParams as ListListParams, - type ListRestoreParams as ListRestoreParams + type ListRestoreParams as ListRestoreParams, }; export { @@ -113,6 +134,6 @@ export declare namespace Lists { type SubscriptionAddParams as SubscriptionAddParams, type SubscriptionSubscribeParams as SubscriptionSubscribeParams, type SubscriptionSubscribeUserParams as SubscriptionSubscribeUserParams, - type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams + type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams, }; } diff --git a/src/resources/lists/subscriptions.ts b/src/resources/lists/subscriptions.ts index a1f2573f..4878baec 100644 --- a/src/resources/lists/subscriptions.ts +++ b/src/resources/lists/subscriptions.ts @@ -12,7 +12,11 @@ export class Subscriptions extends APIResource { /** * Get the list's subscriptions. */ - list(listID: string, query: SubscriptionListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + listID: string, + query: SubscriptionListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/lists/${listID}/subscriptions`, { query, ...options }); } @@ -21,7 +25,11 @@ export class Subscriptions extends APIResource { * subscriptions. If the list does not exist, it will be automatically created. */ add(listID: string, body: SubscriptionAddParams, options?: RequestOptions): APIPromise { - return this._client.post(path`/lists/${listID}/subscriptions`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.post(path`/lists/${listID}/subscriptions`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -29,24 +37,43 @@ export class Subscriptions extends APIResource { * list does not exist, it will be automatically created. */ subscribe(listID: string, body: SubscriptionSubscribeParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/lists/${listID}/subscriptions`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.put(path`/lists/${listID}/subscriptions`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** * Subscribe a user to an existing list (note: if the List does not exist, it will * be automatically created). */ - subscribeUser(userID: string, params: SubscriptionSubscribeUserParams, options?: RequestOptions): APIPromise { - const { list_id, ...body } = params - return this._client.put(path`/lists/${list_id}/subscriptions/${userID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + subscribeUser( + userID: string, + params: SubscriptionSubscribeUserParams, + options?: RequestOptions, + ): APIPromise { + const { list_id, ...body } = params; + return this._client.put(path`/lists/${list_id}/subscriptions/${userID}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** * Delete a subscription to a list by list ID and user ID. */ - unsubscribeUser(userID: string, params: SubscriptionUnsubscribeUserParams, options?: RequestOptions): APIPromise { - const { list_id } = params - return this._client.delete(path`/lists/${list_id}/subscriptions/${userID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + unsubscribeUser( + userID: string, + params: SubscriptionUnsubscribeUserParams, + options?: RequestOptions, + ): APIPromise { + const { list_id } = params; + return this._client.delete(path`/lists/${list_id}/subscriptions/${userID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -107,6 +134,6 @@ export declare namespace Subscriptions { type SubscriptionAddParams as SubscriptionAddParams, type SubscriptionSubscribeParams as SubscriptionSubscribeParams, type SubscriptionSubscribeUserParams as SubscriptionSubscribeUserParams, - type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams + type SubscriptionUnsubscribeUserParams as SubscriptionUnsubscribeUserParams, }; } diff --git a/src/resources/messages.ts b/src/resources/messages.ts index 70ccdb3d..43435ead 100644 --- a/src/resources/messages.ts +++ b/src/resources/messages.ts @@ -17,7 +17,10 @@ export class Messages extends APIResource { /** * Fetch the statuses of messages you've previously sent. */ - list(query: MessageListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: MessageListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/messages', { query, ...options }); } @@ -42,7 +45,11 @@ export class Messages extends APIResource { /** * Fetch the array of events of a message you've previously sent. */ - history(messageID: string, query: MessageHistoryParams | null | undefined = {}, options?: RequestOptions): APIPromise { + history( + messageID: string, + query: MessageHistoryParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/messages/${messageID}/history`, { query, ...options }); } } @@ -78,7 +85,22 @@ export interface MessageDetails { /** * The current status of the message. */ - status: 'CANCELED' | 'CLICKED' | 'DELAYED' | 'DELIVERED' | 'DIGESTED' | 'ENQUEUED' | 'FILTERED' | 'OPENED' | 'ROUTED' | 'SENT' | 'SIMULATED' | 'THROTTLED' | 'UNDELIVERABLE' | 'UNMAPPED' | 'UNROUTABLE'; + status: + | 'CANCELED' + | 'CLICKED' + | 'DELAYED' + | 'DELIVERED' + | 'DIGESTED' + | 'ENQUEUED' + | 'FILTERED' + | 'OPENED' + | 'ROUTED' + | 'SENT' + | 'SIMULATED' + | 'THROTTLED' + | 'UNDELIVERABLE' + | 'UNMAPPED' + | 'UNROUTABLE'; /** * A UTC timestamp at which the recipient clicked on a tracked link for the first @@ -106,7 +128,17 @@ export interface MessageDetails { /** * The reason for the current status of the message. */ - reason?: 'BOUNCED' | 'FAILED' | 'FILTERED' | 'NO_CHANNELS' | 'NO_PROVIDERS' | 'OPT_IN_REQUIRED' | 'PROVIDER_ERROR' | 'UNPUBLISHED' | 'UNSUBSCRIBED' | null; + reason?: + | 'BOUNCED' + | 'FAILED' + | 'FILTERED' + | 'NO_CHANNELS' + | 'NO_PROVIDERS' + | 'OPT_IN_REQUIRED' + | 'PROVIDER_ERROR' + | 'UNPUBLISHED' + | 'UNSUBSCRIBED' + | null; /** * A UTC timestamp at which Courier passed the message to the Integration provider. @@ -308,6 +340,6 @@ export declare namespace Messages { type MessageContentResponse as MessageContentResponse, type MessageHistoryResponse as MessageHistoryResponse, type MessageListParams as MessageListParams, - type MessageHistoryParams as MessageHistoryParams + type MessageHistoryParams as MessageHistoryParams, }; } diff --git a/src/resources/notifications/checks.ts b/src/resources/notifications/checks.ts index ec984fba..c8d0565e 100644 --- a/src/resources/notifications/checks.ts +++ b/src/resources/notifications/checks.ts @@ -28,8 +28,12 @@ export class Checks extends APIResource { * ); * ``` */ - update(submissionID: string, params: CheckUpdateParams, options?: RequestOptions): APIPromise { - const { id, ...body } = params + update( + submissionID: string, + params: CheckUpdateParams, + options?: RequestOptions, + ): APIPromise { + const { id, ...body } = params; return this._client.put(path`/notifications/${id}/${submissionID}/checks`, { body, ...options }); } @@ -44,8 +48,12 @@ export class Checks extends APIResource { * ); * ``` */ - list(submissionID: string, params: CheckListParams, options?: RequestOptions): APIPromise { - const { id } = params + list( + submissionID: string, + params: CheckListParams, + options?: RequestOptions, + ): APIPromise { + const { id } = params; return this._client.get(path`/notifications/${id}/${submissionID}/checks`, options); } @@ -60,8 +68,11 @@ export class Checks extends APIResource { * ``` */ delete(submissionID: string, params: CheckDeleteParams, options?: RequestOptions): APIPromise { - const { id } = params - return this._client.delete(path`/notifications/${id}/${submissionID}/checks`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { id } = params; + return this._client.delete(path`/notifications/${id}/${submissionID}/checks`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -105,6 +116,6 @@ export declare namespace Checks { type CheckListResponse as CheckListResponse, type CheckUpdateParams as CheckUpdateParams, type CheckListParams as CheckListParams, - type CheckDeleteParams as CheckDeleteParams + type CheckDeleteParams as CheckDeleteParams, }; } diff --git a/src/resources/notifications/index.ts b/src/resources/notifications/index.ts index fdf8c291..7d2862b3 100644 --- a/src/resources/notifications/index.ts +++ b/src/resources/notifications/index.ts @@ -1,4 +1,43 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Checks, type CheckUpdateResponse, type CheckListResponse, type CheckUpdateParams, type CheckListParams, type CheckDeleteParams } from './checks';; -export { Notifications, type BaseCheck, type Check, type ElementWithChecksums, type NotificationContentGetResponse, type NotificationContentMutationResponse, type NotificationContentPutRequest, type NotificationElementPutRequest, type NotificationGetContent, type NotificationLocalePutRequest, type NotificationTemplateCreateRequest, type NotificationTemplatePayload, type NotificationTemplatePublishRequest, type NotificationTemplateResponse, type NotificationTemplateState, type NotificationTemplateSummary, type NotificationTemplateUpdateRequest, type NotificationTemplateVersionListResponse, type VersionNode, type NotificationListResponse, type NotificationRetrieveContentResponse, type NotificationCreateParams, type NotificationRetrieveParams, type NotificationListParams, type NotificationListVersionsParams, type NotificationPublishParams, type NotificationPutContentParams, type NotificationPutElementParams, type NotificationPutLocaleParams, type NotificationReplaceParams, type NotificationRetrieveContentParams } from './notifications';; +export { + Checks, + type CheckUpdateResponse, + type CheckListResponse, + type CheckUpdateParams, + type CheckListParams, + type CheckDeleteParams, +} from './checks'; +export { + Notifications, + type BaseCheck, + type Check, + type ElementWithChecksums, + type NotificationContentGetResponse, + type NotificationContentMutationResponse, + type NotificationContentPutRequest, + type NotificationElementPutRequest, + type NotificationGetContent, + type NotificationLocalePutRequest, + type NotificationTemplateCreateRequest, + type NotificationTemplatePayload, + type NotificationTemplatePublishRequest, + type NotificationTemplateResponse, + type NotificationTemplateState, + type NotificationTemplateSummary, + type NotificationTemplateUpdateRequest, + type NotificationTemplateVersionListResponse, + type VersionNode, + type NotificationListResponse, + type NotificationRetrieveContentResponse, + type NotificationCreateParams, + type NotificationRetrieveParams, + type NotificationListParams, + type NotificationListVersionsParams, + type NotificationPublishParams, + type NotificationPutContentParams, + type NotificationPutElementParams, + type NotificationPutLocaleParams, + type NotificationReplaceParams, + type NotificationRetrieveContentParams, +} from './notifications'; diff --git a/src/resources/notifications/notifications.ts b/src/resources/notifications/notifications.ts index c4992083..94c877d9 100644 --- a/src/resources/notifications/notifications.ts +++ b/src/resources/notifications/notifications.ts @@ -3,7 +3,14 @@ import { APIResource } from '../../core/resource'; import * as Shared from '../shared'; import * as ChecksAPI from './checks'; -import { CheckDeleteParams, CheckListParams, CheckListResponse, CheckUpdateParams, CheckUpdateResponse, Checks } from './checks'; +import { + CheckDeleteParams, + CheckListParams, + CheckListResponse, + CheckUpdateParams, + CheckUpdateResponse, + Checks, +} from './checks'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -49,7 +56,11 @@ export class Notifications extends APIResource { * await client.notifications.retrieve('id'); * ``` */ - retrieve(id: string, query: NotificationRetrieveParams | null | undefined = {}, options?: RequestOptions): APIPromise { + retrieve( + id: string, + query: NotificationRetrieveParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/notifications/${id}`, { query, ...options }); } @@ -61,7 +72,10 @@ export class Notifications extends APIResource { * const notifications = await client.notifications.list(); * ``` */ - list(query: NotificationListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: NotificationListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/notifications', { query, ...options }); } @@ -74,7 +88,10 @@ export class Notifications extends APIResource { * ``` */ archive(id: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/notifications/${id}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/notifications/${id}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -86,7 +103,11 @@ export class Notifications extends APIResource { * await client.notifications.listVersions('id'); * ``` */ - listVersions(id: string, query: NotificationListVersionsParams | null | undefined = {}, options?: RequestOptions): APIPromise { + listVersions( + id: string, + query: NotificationListVersionsParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/notifications/${id}/versions`, { query, ...options }); } @@ -99,8 +120,16 @@ export class Notifications extends APIResource { * await client.notifications.publish('id'); * ``` */ - publish(id: string, body: NotificationPublishParams | null | undefined = {}, options?: RequestOptions): APIPromise { - return this._client.post(path`/notifications/${id}/publish`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + publish( + id: string, + body: NotificationPublishParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/notifications/${id}/publish`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -120,7 +149,11 @@ export class Notifications extends APIResource { * }); * ``` */ - putContent(id: string, body: NotificationPutContentParams, options?: RequestOptions): APIPromise { + putContent( + id: string, + body: NotificationPutContentParams, + options?: RequestOptions, + ): APIPromise { return this._client.put(path`/notifications/${id}/content`, { body, ...options }); } @@ -139,8 +172,12 @@ export class Notifications extends APIResource { * }); * ``` */ - putElement(elementID: string, params: NotificationPutElementParams, options?: RequestOptions): APIPromise { - const { id, ...body } = params + putElement( + elementID: string, + params: NotificationPutElementParams, + options?: RequestOptions, + ): APIPromise { + const { id, ...body } = params; return this._client.put(path`/notifications/${id}/elements/${elementID}`, { body, ...options }); } @@ -162,8 +199,12 @@ export class Notifications extends APIResource { * }); * ``` */ - putLocale(localeID: string, params: NotificationPutLocaleParams, options?: RequestOptions): APIPromise { - const { id, ...body } = params + putLocale( + localeID: string, + params: NotificationPutLocaleParams, + options?: RequestOptions, + ): APIPromise { + const { id, ...body } = params; return this._client.put(path`/notifications/${id}/locales/${localeID}`, { body, ...options }); } @@ -189,7 +230,11 @@ export class Notifications extends APIResource { * }); * ``` */ - replace(id: string, body: NotificationReplaceParams, options?: RequestOptions): APIPromise { + replace( + id: string, + body: NotificationReplaceParams, + options?: RequestOptions, + ): APIPromise { return this._client.put(path`/notifications/${id}`, { body, ...options }); } @@ -206,7 +251,11 @@ export class Notifications extends APIResource { * ); * ``` */ - retrieveContent(id: string, query: NotificationRetrieveContentParams | null | undefined = {}, options?: RequestOptions): APIPromise { + retrieveContent( + id: string, + query: NotificationRetrieveContentParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/notifications/${id}/content`, { query, ...options }); } } @@ -250,7 +299,7 @@ export interface ElementWithChecksums { */ locales?: { [key: string]: ElementWithChecksums.Locales }; -[k: string]: unknown + [k: string]: unknown; } export namespace ElementWithChecksums { @@ -359,7 +408,7 @@ export interface NotificationElementPutRequest { */ state?: NotificationTemplateState; -[k: string]: unknown + [k: string]: unknown; } export interface NotificationGetContent { @@ -451,7 +500,7 @@ export namespace NotificationLocalePutRequest { */ id: string; - [k: string]: unknown + [k: string]: unknown; } } @@ -581,7 +630,7 @@ export interface NotificationTemplateResponse extends NotificationTemplatePayloa /** * Template state. Defaults to `DRAFT`. */ -export type NotificationTemplateState = 'DRAFT' | 'PUBLISHED' +export type NotificationTemplateState = 'DRAFT' | 'PUBLISHED'; /** * V2 (CDS) template summary returned in list responses. @@ -718,7 +767,7 @@ export namespace NotificationListResponse { * Elemental content response for V2 templates. Contains versioned elements with * content checksums. */ -export type NotificationRetrieveContentResponse = NotificationContentGetResponse | NotificationGetContent +export type NotificationRetrieveContentResponse = NotificationContentGetResponse | NotificationGetContent; export interface NotificationCreateParams { /** @@ -846,7 +895,7 @@ export interface NotificationPutElementParams { */ state?: NotificationTemplateState; -[k: string]: unknown + [k: string]: unknown; } export interface NotificationPutLocaleParams { @@ -873,7 +922,7 @@ export namespace NotificationPutLocaleParams { */ id: string; - [k: string]: unknown + [k: string]: unknown; } } @@ -932,7 +981,7 @@ export declare namespace Notifications { type NotificationPutElementParams as NotificationPutElementParams, type NotificationPutLocaleParams as NotificationPutLocaleParams, type NotificationReplaceParams as NotificationReplaceParams, - type NotificationRetrieveContentParams as NotificationRetrieveContentParams + type NotificationRetrieveContentParams as NotificationRetrieveContentParams, }; export { @@ -941,6 +990,6 @@ export declare namespace Notifications { type CheckListResponse as CheckListResponse, type CheckUpdateParams as CheckUpdateParams, type CheckListParams as CheckListParams, - type CheckDeleteParams as CheckDeleteParams + type CheckDeleteParams as CheckDeleteParams, }; } diff --git a/src/resources/profiles/index.ts b/src/resources/profiles/index.ts index 27e208ba..87a750c4 100644 --- a/src/resources/profiles/index.ts +++ b/src/resources/profiles/index.ts @@ -1,4 +1,20 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Lists, type ListRetrieveResponse, type ListDeleteResponse, type ListSubscribeResponse, type ListRetrieveParams, type ListSubscribeParams } from './lists';; -export { Profiles, type SubscribeToListsRequestItem, type ProfileCreateResponse, type ProfileRetrieveResponse, type ProfileReplaceResponse, type ProfileCreateParams, type ProfileUpdateParams, type ProfileReplaceParams } from './profiles';; +export { + Lists, + type ListRetrieveResponse, + type ListDeleteResponse, + type ListSubscribeResponse, + type ListRetrieveParams, + type ListSubscribeParams, +} from './lists'; +export { + Profiles, + type SubscribeToListsRequestItem, + type ProfileCreateResponse, + type ProfileRetrieveResponse, + type ProfileReplaceResponse, + type ProfileCreateParams, + type ProfileUpdateParams, + type ProfileReplaceParams, +} from './profiles'; diff --git a/src/resources/profiles/lists.ts b/src/resources/profiles/lists.ts index 7659b38f..bc21195f 100644 --- a/src/resources/profiles/lists.ts +++ b/src/resources/profiles/lists.ts @@ -11,7 +11,11 @@ export class Lists extends APIResource { /** * Returns the subscribed lists for a specified user. */ - retrieve(userID: string, query: ListRetrieveParams | null | undefined = {}, options?: RequestOptions): APIPromise { + retrieve( + userID: string, + query: ListRetrieveParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/profiles/${userID}/lists`, { query, ...options }); } @@ -26,7 +30,11 @@ export class Lists extends APIResource { * Subscribes the given user to one or more lists. If the list does not exist, it * will be created. */ - subscribe(userID: string, body: ListSubscribeParams, options?: RequestOptions): APIPromise { + subscribe( + userID: string, + body: ListSubscribeParams, + options?: RequestOptions, + ): APIPromise { return this._client.post(path`/profiles/${userID}/lists`, { body, ...options }); } } @@ -90,6 +98,6 @@ export declare namespace Lists { type ListDeleteResponse as ListDeleteResponse, type ListSubscribeResponse as ListSubscribeResponse, type ListRetrieveParams as ListRetrieveParams, - type ListSubscribeParams as ListSubscribeParams + type ListSubscribeParams as ListSubscribeParams, }; } diff --git a/src/resources/profiles/profiles.ts b/src/resources/profiles/profiles.ts index 8fd58739..358fae68 100644 --- a/src/resources/profiles/profiles.ts +++ b/src/resources/profiles/profiles.ts @@ -3,7 +3,14 @@ import { APIResource } from '../../core/resource'; import * as Shared from '../shared'; import * as ListsAPI from './lists'; -import { ListDeleteResponse, ListRetrieveParams, ListRetrieveResponse, ListSubscribeParams, ListSubscribeResponse, Lists } from './lists'; +import { + ListDeleteResponse, + ListRetrieveParams, + ListRetrieveResponse, + ListSubscribeParams, + ListSubscribeResponse, + Lists, +} from './lists'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -16,7 +23,11 @@ export class Profiles extends APIResource { * Merge the supplied values with an existing profile or create a new profile if * one doesn't already exist. */ - create(userID: string, body: ProfileCreateParams, options?: RequestOptions): APIPromise { + create( + userID: string, + body: ProfileCreateParams, + options?: RequestOptions, + ): APIPromise { return this._client.post(path`/profiles/${userID}`, { body, ...options }); } @@ -31,14 +42,21 @@ export class Profiles extends APIResource { * Update a profile */ update(userID: string, body: ProfileUpdateParams, options?: RequestOptions): APIPromise { - return this._client.patch(path`/profiles/${userID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.patch(path`/profiles/${userID}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** * Deletes the specified user profile. */ delete(userID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/profiles/${userID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/profiles/${userID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -48,7 +66,11 @@ export class Profiles extends APIResource { * `PUT` update is a full replacement of the data. For partial updates, use the * [Patch](https://www.courier.com/docs/reference/profiles/patch/) request. */ - replace(userID: string, body: ProfileReplaceParams, options?: RequestOptions): APIPromise { + replace( + userID: string, + body: ProfileReplaceParams, + options?: RequestOptions, + ): APIPromise { return this._client.put(path`/profiles/${userID}`, { body, ...options }); } } @@ -117,7 +139,7 @@ export declare namespace Profiles { type ProfileReplaceResponse as ProfileReplaceResponse, type ProfileCreateParams as ProfileCreateParams, type ProfileUpdateParams as ProfileUpdateParams, - type ProfileReplaceParams as ProfileReplaceParams + type ProfileReplaceParams as ProfileReplaceParams, }; export { @@ -126,6 +148,6 @@ export declare namespace Profiles { type ListDeleteResponse as ListDeleteResponse, type ListSubscribeResponse as ListSubscribeResponse, type ListRetrieveParams as ListRetrieveParams, - type ListSubscribeParams as ListSubscribeParams + type ListSubscribeParams as ListSubscribeParams, }; } diff --git a/src/resources/providers/catalog.ts b/src/resources/providers/catalog.ts index 7536dcb7..b49b5b0a 100644 --- a/src/resources/providers/catalog.ts +++ b/src/resources/providers/catalog.ts @@ -13,7 +13,10 @@ export class Catalog extends APIResource { * `required`). Providers with no configurable schema return only `provider`, * `name`, and `description`. */ - list(query: CatalogListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: CatalogListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/providers/catalog', { query, ...options }); } } @@ -46,8 +49,5 @@ export interface CatalogListParams { } export declare namespace Catalog { - export { - type CatalogListResponse as CatalogListResponse, - type CatalogListParams as CatalogListParams - }; + export { type CatalogListResponse as CatalogListResponse, type CatalogListParams as CatalogListParams }; } diff --git a/src/resources/providers/index.ts b/src/resources/providers/index.ts index f3963617..48625736 100644 --- a/src/resources/providers/index.ts +++ b/src/resources/providers/index.ts @@ -1,4 +1,12 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Catalog, type CatalogListResponse, type CatalogListParams } from './catalog';; -export { Providers, type Provider, type ProvidersCatalogEntry, type ProviderListResponse, type ProviderCreateParams, type ProviderUpdateParams, type ProviderListParams } from './providers';; +export { Catalog, type CatalogListResponse, type CatalogListParams } from './catalog'; +export { + Providers, + type Provider, + type ProvidersCatalogEntry, + type ProviderListResponse, + type ProviderCreateParams, + type ProviderUpdateParams, + type ProviderListParams, +} from './providers'; diff --git a/src/resources/providers/providers.ts b/src/resources/providers/providers.ts index 19be01e2..4c649aa2 100644 --- a/src/resources/providers/providers.ts +++ b/src/resources/providers/providers.ts @@ -42,7 +42,10 @@ export class Providers extends APIResource { * List configured provider integrations for the current workspace. Supports * cursor-based pagination. */ - list(query: ProviderListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: ProviderListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/providers', { query, ...options }); } @@ -51,7 +54,10 @@ export class Providers extends APIResource { * by routing or notifications. */ delete(id: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/providers/${id}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/providers/${id}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -226,12 +232,12 @@ export declare namespace Providers { type ProviderListResponse as ProviderListResponse, type ProviderCreateParams as ProviderCreateParams, type ProviderUpdateParams as ProviderUpdateParams, - type ProviderListParams as ProviderListParams + type ProviderListParams as ProviderListParams, }; export { Catalog as Catalog, type CatalogListResponse as CatalogListResponse, - type CatalogListParams as CatalogListParams + type CatalogListParams as CatalogListParams, }; } diff --git a/src/resources/requests.ts b/src/resources/requests.ts index 130198ab..7c287eea 100644 --- a/src/resources/requests.ts +++ b/src/resources/requests.ts @@ -11,6 +11,9 @@ export class Requests extends APIResource { * Archive message */ archive(requestID: string, options?: RequestOptions): APIPromise { - return this._client.put(path`/requests/${requestID}/archive`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.put(path`/requests/${requestID}/archive`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } diff --git a/src/resources/routing-strategies.ts b/src/resources/routing-strategies.ts index cfdc9067..35593c32 100644 --- a/src/resources/routing-strategies.ts +++ b/src/resources/routing-strategies.ts @@ -27,7 +27,10 @@ export class RoutingStrategies extends APIResource { * }); * ``` */ - create(body: RoutingStrategyCreateParams, options?: RequestOptions): APIPromise { + create( + body: RoutingStrategyCreateParams, + options?: RequestOptions, + ): APIPromise { return this._client.post('/routing-strategies', { body, ...options }); } @@ -56,7 +59,10 @@ export class RoutingStrategies extends APIResource { * await client.routingStrategies.list(); * ``` */ - list(query: RoutingStrategyListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: RoutingStrategyListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/routing-strategies', { query, ...options }); } @@ -70,7 +76,10 @@ export class RoutingStrategies extends APIResource { * ``` */ archive(id: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/routing-strategies/${id}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/routing-strategies/${id}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -83,7 +92,11 @@ export class RoutingStrategies extends APIResource { * await client.routingStrategies.listNotifications('id'); * ``` */ - listNotifications(id: string, query: RoutingStrategyListNotificationsParams | null | undefined = {}, options?: RequestOptions): APIPromise { + listNotifications( + id: string, + query: RoutingStrategyListNotificationsParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/routing-strategies/${id}/notifications`, { query, ...options }); } @@ -104,7 +117,11 @@ export class RoutingStrategies extends APIResource { * }); * ``` */ - replace(id: string, body: RoutingStrategyReplaceParams, options?: RequestOptions): APIPromise { + replace( + id: string, + body: RoutingStrategyReplaceParams, + options?: RequestOptions, + ): APIPromise { return this._client.put(path`/routing-strategies/${id}`, { body, ...options }); } } @@ -403,6 +420,6 @@ export declare namespace RoutingStrategies { type RoutingStrategyCreateParams as RoutingStrategyCreateParams, type RoutingStrategyListParams as RoutingStrategyListParams, type RoutingStrategyListNotificationsParams as RoutingStrategyListNotificationsParams, - type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams + type RoutingStrategyReplaceParams as RoutingStrategyReplaceParams, }; } diff --git a/src/resources/send.ts b/src/resources/send.ts index 4bb59203..bc35c9f5 100644 --- a/src/resources/send.ts +++ b/src/resources/send.ts @@ -89,7 +89,26 @@ export namespace SendMessageParams { /** * The recipient or a list of recipients of the message */ - to?: Shared.UserRecipient | Shared.AudienceRecipient | Shared.ListRecipient | Shared.ListPatternRecipient | Shared.SlackRecipient | Shared.MsTeamsRecipient | Shared.PagerdutyRecipient | Shared.WebhookRecipient | Array | null; + to?: + | Shared.UserRecipient + | Shared.AudienceRecipient + | Shared.ListRecipient + | Shared.ListPatternRecipient + | Shared.SlackRecipient + | Shared.MsTeamsRecipient + | Shared.PagerdutyRecipient + | Shared.WebhookRecipient + | Array< + | Shared.UserRecipient + | Shared.AudienceRecipient + | Shared.ListRecipient + | Shared.ListPatternRecipient + | Shared.SlackRecipient + | Shared.MsTeamsRecipient + | Shared.PagerdutyRecipient + | Shared.WebhookRecipient + > + | null; } export namespace Message { @@ -168,8 +187,5 @@ export namespace SendMessageParams { } export declare namespace Send { - export { - type SendMessageResponse as SendMessageResponse, - type SendMessageParams as SendMessageParams - }; + export { type SendMessageResponse as SendMessageResponse, type SendMessageParams as SendMessageParams }; } diff --git a/src/resources/shared.ts b/src/resources/shared.ts index 41642f30..26816586 100644 --- a/src/resources/shared.ts +++ b/src/resources/shared.ts @@ -12,7 +12,7 @@ export interface AirshipProfileAudience { named_user: string; } -export type Alignment = 'center' | 'left' | 'right' | 'full' +export type Alignment = 'center' | 'left' | 'right' | 'full'; export interface AudienceFilter { /** @@ -81,7 +81,7 @@ export interface Channel { timeouts?: Timeouts | null; } -export type ChannelClassification = 'direct_message' | 'email' | 'push' | 'sms' | 'webhook' | 'inbox' +export type ChannelClassification = 'direct_message' | 'email' | 'push' | 'sms' | 'webhook' | 'inbox'; export interface ChannelMetadata { utm?: Utm | null; @@ -91,9 +91,9 @@ export interface ChannelPreference { channel: ChannelClassification; } -export type DeviceType = string +export type DeviceType = string; -export type Discord = SendToChannel | SendDirectMessage +export type Discord = SendToChannel | SendDirectMessage; export interface ElementalActionNodeWithType extends ElementalBaseNode { type?: 'action'; @@ -203,7 +203,15 @@ export interface ElementalMetaNodeWithType extends ElementalBaseNode { * [control flow docs](https://www.courier.com/docs/platform/content/elemental/control-flow/) * for more details. */ -export type ElementalNode = ElementalTextNodeWithType | ElementalMetaNodeWithType | ElementalChannelNodeWithType | ElementalImageNodeWithType | ElementalActionNodeWithType | ElementalDividerNodeWithType | ElementalQuoteNodeWithType | ElementalHTMLNodeWithType +export type ElementalNode = + | ElementalTextNodeWithType + | ElementalMetaNodeWithType + | ElementalChannelNodeWithType + | ElementalImageNodeWithType + | ElementalActionNodeWithType + | ElementalDividerNodeWithType + | ElementalQuoteNodeWithType + | ElementalHTMLNodeWithType; export interface ElementalQuoteNodeWithType extends ElementalBaseNode { type?: 'quote'; @@ -213,7 +221,7 @@ export interface ElementalTextNodeWithType extends ElementalBaseNode { type?: 'text'; } -export type Expo = Token | MultipleTokens +export type Expo = Token | MultipleTokens; /** * A filter rule that can be either a single condition (with path/value) or a @@ -288,7 +296,7 @@ export interface ListRecipient { list_id?: string | null; } -export type MessageChannels = { [key: string]: Channel } +export type MessageChannels = { [key: string]: Channel }; export interface MessageContext { /** @@ -297,7 +305,7 @@ export interface MessageContext { tenant_id?: string | null; } -export type MessageProviders = { [key: string]: MessageProvidersType } +export type MessageProviders = { [key: string]: MessageProvidersType }; export interface MessageProvidersType { /** @@ -321,13 +329,18 @@ export interface MessageRouting { method: 'all' | 'single'; } -export type MessageRoutingChannel = string | MessageRouting +export type MessageRoutingChannel = string | MessageRouting; export interface Metadata { utm?: Utm | null; } -export type MsTeams = SendToMsTeamsUserID | SendToMsTeamsEmail | SendToMsTeamsChannelID | SendToMsTeamsConversationID | SendToMsTeamsChannelName +export type MsTeams = + | SendToMsTeamsUserID + | SendToMsTeamsEmail + | SendToMsTeamsChannelID + | SendToMsTeamsConversationID + | SendToMsTeamsChannelName; export interface MsTeamsBaseProperties { service_url: string; @@ -387,7 +400,7 @@ export interface Preference { source?: 'subscription' | 'list' | 'recipient' | null; } -export type PreferenceStatus = 'OPTED_IN' | 'OPTED_OUT' | 'REQUIRED' +export type PreferenceStatus = 'OPTED_IN' | 'OPTED_OUT' | 'REQUIRED'; export interface RecipientPreferences { categories?: { [key: string]: NotificationPreferenceDetails } | null; @@ -469,7 +482,7 @@ export interface SendToSlackUserID { user_id: string; } -export type Slack = SendToSlackChannel | SendToSlackEmail | SendToSlackUserID +export type Slack = SendToSlackChannel | SendToSlackEmail | SendToSlackUserID; export interface SlackBaseProperties { access_token: string; @@ -482,7 +495,7 @@ export interface SlackRecipient { slack: Slack; } -export type TextStyle = 'text' | 'h1' | 'h2' | 'subtext' +export type TextStyle = 'text' | 'h1' | 'h2' | 'subtext'; export interface Timeouts { channel?: number | null; @@ -578,7 +591,7 @@ export namespace UserProfile { } } -export type UserProfileFirebaseToken = string | Array +export type UserProfileFirebaseToken = string | Array; export interface UserRecipient { /** @@ -649,7 +662,7 @@ export interface Utm { term?: string | null; } -export type WebhookAuthMode = 'none' | 'basic' | 'bearer' +export type WebhookAuthMode = 'none' | 'basic' | 'bearer'; export interface WebhookAuthentication { /** @@ -673,7 +686,7 @@ export interface WebhookAuthentication { username?: string | null; } -export type WebhookMethod = 'POST' | 'PUT' +export type WebhookMethod = 'POST' | 'PUT'; export interface WebhookProfile { /** @@ -704,7 +717,7 @@ export interface WebhookProfile { profile?: WebhookProfileType | null; } -export type WebhookProfileType = 'limited' | 'expanded' +export type WebhookProfileType = 'limited' | 'expanded'; /** * Send via webhook diff --git a/src/resources/tenants/index.ts b/src/resources/tenants/index.ts index 85927059..c5216c97 100644 --- a/src/resources/tenants/index.ts +++ b/src/resources/tenants/index.ts @@ -1,5 +1,29 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Preferences } from './preferences/index';; -export { Templates, type TemplateListResponse, type TemplateRetrieveParams, type TemplateListParams, type TemplatePublishParams, type TemplateReplaceParams } from './templates/index';; -export { Tenants, type BaseTemplateTenantAssociation, type DefaultPreferences, type PostTenantTemplatePublishRequest, type PostTenantTemplatePublishResponse, type PutTenantTemplateRequest, type PutTenantTemplateResponse, type SubscriptionTopicNew, type Tenant, type TenantAssociation, type TenantTemplateInput, type TenantListResponse, type TenantListUsersResponse, type TenantUpdateParams, type TenantListParams, type TenantListUsersParams } from './tenants';; +export { Preferences } from './preferences/index'; +export { + Templates, + type TemplateListResponse, + type TemplateRetrieveParams, + type TemplateListParams, + type TemplatePublishParams, + type TemplateReplaceParams, +} from './templates/index'; +export { + Tenants, + type BaseTemplateTenantAssociation, + type DefaultPreferences, + type PostTenantTemplatePublishRequest, + type PostTenantTemplatePublishResponse, + type PutTenantTemplateRequest, + type PutTenantTemplateResponse, + type SubscriptionTopicNew, + type Tenant, + type TenantAssociation, + type TenantTemplateInput, + type TenantListResponse, + type TenantListUsersResponse, + type TenantUpdateParams, + type TenantListParams, + type TenantListUsersParams, +} from './tenants'; diff --git a/src/resources/tenants/preferences/index.ts b/src/resources/tenants/preferences/index.ts index 4f64a618..9fe5bafc 100644 --- a/src/resources/tenants/preferences/index.ts +++ b/src/resources/tenants/preferences/index.ts @@ -1,4 +1,4 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Items, type ItemUpdateParams, type ItemDeleteParams } from './items';; -export { Preferences } from './preferences';; +export { Items, type ItemUpdateParams, type ItemDeleteParams } from './items'; +export { Preferences } from './preferences'; diff --git a/src/resources/tenants/preferences/items.ts b/src/resources/tenants/preferences/items.ts index 4ff3d429..5b93e99e 100644 --- a/src/resources/tenants/preferences/items.ts +++ b/src/resources/tenants/preferences/items.ts @@ -22,8 +22,12 @@ export class Items extends APIResource { * ``` */ update(topicID: string, params: ItemUpdateParams, options?: RequestOptions): APIPromise { - const { tenant_id, ...body } = params - return this._client.put(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { tenant_id, ...body } = params; + return this._client.put(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -37,8 +41,11 @@ export class Items extends APIResource { * ``` */ delete(topicID: string, params: ItemDeleteParams, options?: RequestOptions): APIPromise { - const { tenant_id } = params - return this._client.delete(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { tenant_id } = params; + return this._client.delete(path`/tenants/${tenant_id}/default_preferences/items/${topicID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -75,8 +82,5 @@ export interface ItemDeleteParams { } export declare namespace Items { - export { - type ItemUpdateParams as ItemUpdateParams, - type ItemDeleteParams as ItemDeleteParams - }; + export { type ItemUpdateParams as ItemUpdateParams, type ItemDeleteParams as ItemDeleteParams }; } diff --git a/src/resources/tenants/preferences/preferences.ts b/src/resources/tenants/preferences/preferences.ts index 573c76c2..231183c6 100644 --- a/src/resources/tenants/preferences/preferences.ts +++ b/src/resources/tenants/preferences/preferences.ts @@ -14,6 +14,6 @@ export declare namespace Preferences { export { Items as Items, type ItemUpdateParams as ItemUpdateParams, - type ItemDeleteParams as ItemDeleteParams + type ItemDeleteParams as ItemDeleteParams, }; } diff --git a/src/resources/tenants/templates/index.ts b/src/resources/tenants/templates/index.ts index 0417b524..d4f43150 100644 --- a/src/resources/tenants/templates/index.ts +++ b/src/resources/tenants/templates/index.ts @@ -1,4 +1,11 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Templates, type TemplateListResponse, type TemplateRetrieveParams, type TemplateListParams, type TemplatePublishParams, type TemplateReplaceParams } from './templates';; -export { Versions, type VersionRetrieveParams } from './versions';; +export { + Templates, + type TemplateListResponse, + type TemplateRetrieveParams, + type TemplateListParams, + type TemplatePublishParams, + type TemplateReplaceParams, +} from './templates'; +export { Versions, type VersionRetrieveParams } from './versions'; diff --git a/src/resources/tenants/templates/templates.ts b/src/resources/tenants/templates/templates.ts index 172aaaa7..52e39d5b 100644 --- a/src/resources/tenants/templates/templates.ts +++ b/src/resources/tenants/templates/templates.ts @@ -23,8 +23,12 @@ export class Templates extends APIResource { * }); * ``` */ - retrieve(templateID: string, params: TemplateRetrieveParams, options?: RequestOptions): APIPromise { - const { tenant_id } = params + retrieve( + templateID: string, + params: TemplateRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { tenant_id } = params; return this._client.get(path`/tenants/${tenant_id}/templates/${templateID}`, options); } @@ -38,7 +42,11 @@ export class Templates extends APIResource { * ); * ``` */ - list(tenantID: string, query: TemplateListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + tenantID: string, + query: TemplateListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/tenants/${tenantID}/templates`, { query, ...options }); } @@ -56,9 +64,16 @@ export class Templates extends APIResource { * }); * ``` */ - publish(templateID: string, params: TemplatePublishParams, options?: RequestOptions): APIPromise { - const { tenant_id, ...body } = params - return this._client.post(path`/tenants/${tenant_id}/templates/${templateID}/publish`, { body, ...options }); + publish( + templateID: string, + params: TemplatePublishParams, + options?: RequestOptions, + ): APIPromise { + const { tenant_id, ...body } = params; + return this._client.post(path`/tenants/${tenant_id}/templates/${templateID}/publish`, { + body, + ...options, + }); } /** @@ -81,8 +96,12 @@ export class Templates extends APIResource { * }); * ``` */ - replace(templateID: string, params: TemplateReplaceParams, options?: RequestOptions): APIPromise { - const { tenant_id, ...body } = params + replace( + templateID: string, + params: TemplateReplaceParams, + options?: RequestOptions, + ): APIPromise { + const { tenant_id, ...body } = params; return this._client.put(path`/tenants/${tenant_id}/templates/${templateID}`, { body, ...options }); } } @@ -196,11 +215,8 @@ export declare namespace Templates { type TemplateRetrieveParams as TemplateRetrieveParams, type TemplateListParams as TemplateListParams, type TemplatePublishParams as TemplatePublishParams, - type TemplateReplaceParams as TemplateReplaceParams + type TemplateReplaceParams as TemplateReplaceParams, }; - export { - Versions as Versions, - type VersionRetrieveParams as VersionRetrieveParams - }; + export { Versions as Versions, type VersionRetrieveParams as VersionRetrieveParams }; } diff --git a/src/resources/tenants/templates/versions.ts b/src/resources/tenants/templates/versions.ts index a0891111..62a07d6d 100644 --- a/src/resources/tenants/templates/versions.ts +++ b/src/resources/tenants/templates/versions.ts @@ -25,9 +25,16 @@ export class Versions extends APIResource { * ); * ``` */ - retrieve(version: string, params: VersionRetrieveParams, options?: RequestOptions): APIPromise { - const { tenant_id, template_id } = params - return this._client.get(path`/tenants/${tenant_id}/templates/${template_id}/versions/${version}`, options); + retrieve( + version: string, + params: VersionRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { tenant_id, template_id } = params; + return this._client.get( + path`/tenants/${tenant_id}/templates/${template_id}/versions/${version}`, + options, + ); } } @@ -44,7 +51,5 @@ export interface VersionRetrieveParams { } export declare namespace Versions { - export { - type VersionRetrieveParams as VersionRetrieveParams - }; + export { type VersionRetrieveParams as VersionRetrieveParams }; } diff --git a/src/resources/tenants/tenants.ts b/src/resources/tenants/tenants.ts index 48c28484..75aa7b31 100644 --- a/src/resources/tenants/tenants.ts +++ b/src/resources/tenants/tenants.ts @@ -6,7 +6,14 @@ import * as Shared from '../shared'; import * as PreferencesAPI from './preferences/preferences'; import { Preferences } from './preferences/preferences'; import * as TemplatesAPI from './templates/templates'; -import { TemplateListParams, TemplateListResponse, TemplatePublishParams, TemplateReplaceParams, TemplateRetrieveParams, Templates } from './templates/templates'; +import { + TemplateListParams, + TemplateListResponse, + TemplatePublishParams, + TemplateReplaceParams, + TemplateRetrieveParams, + Templates, +} from './templates/templates'; import { APIPromise } from '../../core/api-promise'; import { buildHeaders } from '../../internal/headers'; import { RequestOptions } from '../../internal/request-options'; @@ -50,7 +57,10 @@ export class Tenants extends APIResource { * const tenants = await client.tenants.list(); * ``` */ - list(query: TenantListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + query: TenantListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get('/tenants', { query, ...options }); } @@ -63,7 +73,10 @@ export class Tenants extends APIResource { * ``` */ delete(tenantID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/tenants/${tenantID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/tenants/${tenantID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -76,7 +89,11 @@ export class Tenants extends APIResource { * ); * ``` */ - listUsers(tenantID: string, query: TenantListUsersParams | null | undefined = {}, options?: RequestOptions): APIPromise { + listUsers( + tenantID: string, + query: TenantListUsersParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/tenants/${tenantID}/users`, { query, ...options }); } } @@ -436,12 +453,10 @@ export declare namespace Tenants { type TenantListUsersResponse as TenantListUsersResponse, type TenantUpdateParams as TenantUpdateParams, type TenantListParams as TenantListParams, - type TenantListUsersParams as TenantListUsersParams + type TenantListUsersParams as TenantListUsersParams, }; - export { - Preferences as Preferences - }; + export { Preferences as Preferences }; export { Templates as Templates, @@ -449,6 +464,6 @@ export declare namespace Tenants { type TemplateRetrieveParams as TemplateRetrieveParams, type TemplateListParams as TemplateListParams, type TemplatePublishParams as TemplatePublishParams, - type TemplateReplaceParams as TemplateReplaceParams + type TemplateReplaceParams as TemplateReplaceParams, }; } diff --git a/src/resources/translations.ts b/src/resources/translations.ts index 4a3d015a..ac89f265 100644 --- a/src/resources/translations.ts +++ b/src/resources/translations.ts @@ -11,7 +11,7 @@ export class Translations extends APIResource { * Get translations by locale */ retrieve(locale: string, params: TranslationRetrieveParams, options?: RequestOptions): APIPromise { - const { domain } = params + const { domain } = params; return this._client.get(path`/translations/${domain}/${locale}`, options); } @@ -19,12 +19,16 @@ export class Translations extends APIResource { * Update a translation */ update(locale: string, params: TranslationUpdateParams, options?: RequestOptions): APIPromise { - const { domain, body } = params - return this._client.put(path`/translations/${domain}/${locale}`, { body: body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { domain, body } = params; + return this._client.put(path`/translations/${domain}/${locale}`, { + body: body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } -export type TranslationRetrieveResponse = string +export type TranslationRetrieveResponse = string; export interface TranslationRetrieveParams { /** @@ -51,6 +55,6 @@ export declare namespace Translations { export { type TranslationRetrieveResponse as TranslationRetrieveResponse, type TranslationRetrieveParams as TranslationRetrieveParams, - type TranslationUpdateParams as TranslationUpdateParams + type TranslationUpdateParams as TranslationUpdateParams, }; } diff --git a/src/resources/users/index.ts b/src/resources/users/index.ts index dd5b467f..c654207f 100644 --- a/src/resources/users/index.ts +++ b/src/resources/users/index.ts @@ -1,6 +1,31 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export { Preferences, type TopicPreference, type PreferenceRetrieveResponse, type PreferenceRetrieveTopicResponse, type PreferenceUpdateOrCreateTopicResponse, type PreferenceRetrieveParams, type PreferenceRetrieveTopicParams, type PreferenceUpdateOrCreateTopicParams } from './preferences';; -export { Tenants, type TenantListResponse, type TenantListParams, type TenantAddMultipleParams, type TenantAddSingleParams, type TenantRemoveSingleParams } from './tenants';; -export { Tokens, type UserToken, type TokenRetrieveResponse, type TokenListResponse, type TokenRetrieveParams, type TokenUpdateParams, type TokenDeleteParams, type TokenAddSingleParams } from './tokens';; -export { Users } from './users';; +export { + Preferences, + type TopicPreference, + type PreferenceRetrieveResponse, + type PreferenceRetrieveTopicResponse, + type PreferenceUpdateOrCreateTopicResponse, + type PreferenceRetrieveParams, + type PreferenceRetrieveTopicParams, + type PreferenceUpdateOrCreateTopicParams, +} from './preferences'; +export { + Tenants, + type TenantListResponse, + type TenantListParams, + type TenantAddMultipleParams, + type TenantAddSingleParams, + type TenantRemoveSingleParams, +} from './tenants'; +export { + Tokens, + type UserToken, + type TokenRetrieveResponse, + type TokenListResponse, + type TokenRetrieveParams, + type TokenUpdateParams, + type TokenDeleteParams, + type TokenAddSingleParams, +} from './tokens'; +export { Users } from './users'; diff --git a/src/resources/users/preferences.ts b/src/resources/users/preferences.ts index 24a671da..223d96ba 100644 --- a/src/resources/users/preferences.ts +++ b/src/resources/users/preferences.ts @@ -17,7 +17,11 @@ export class Preferences extends APIResource { * ); * ``` */ - retrieve(userID: string, query: PreferenceRetrieveParams | null | undefined = {}, options?: RequestOptions): APIPromise { + retrieve( + userID: string, + query: PreferenceRetrieveParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/users/${userID}/preferences`, { query, ...options }); } @@ -32,8 +36,12 @@ export class Preferences extends APIResource { * }); * ``` */ - retrieveTopic(topicID: string, params: PreferenceRetrieveTopicParams, options?: RequestOptions): APIPromise { - const { user_id, ...query } = params + retrieveTopic( + topicID: string, + params: PreferenceRetrieveTopicParams, + options?: RequestOptions, + ): APIPromise { + const { user_id, ...query } = params; return this._client.get(path`/users/${user_id}/preferences/${topicID}`, { query, ...options }); } @@ -56,9 +64,17 @@ export class Preferences extends APIResource { * ); * ``` */ - updateOrCreateTopic(topicID: string, params: PreferenceUpdateOrCreateTopicParams, options?: RequestOptions): APIPromise { - const { user_id, tenant_id, ...body } = params - return this._client.put(path`/users/${user_id}/preferences/${topicID}`, { query: { tenant_id }, body, ...options }); + updateOrCreateTopic( + topicID: string, + params: PreferenceUpdateOrCreateTopicParams, + options?: RequestOptions, + ): APIPromise { + const { user_id, tenant_id, ...body } = params; + return this._client.put(path`/users/${user_id}/preferences/${topicID}`, { + query: { tenant_id }, + body, + ...options, + }); } } @@ -158,6 +174,6 @@ export declare namespace Preferences { type PreferenceUpdateOrCreateTopicResponse as PreferenceUpdateOrCreateTopicResponse, type PreferenceRetrieveParams as PreferenceRetrieveParams, type PreferenceRetrieveTopicParams as PreferenceRetrieveTopicParams, - type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams + type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams, }; } diff --git a/src/resources/users/tenants.ts b/src/resources/users/tenants.ts index 520a66aa..b68b7e02 100644 --- a/src/resources/users/tenants.ts +++ b/src/resources/users/tenants.ts @@ -16,7 +16,11 @@ export class Tenants extends APIResource { * const tenants = await client.users.tenants.list('user_id'); * ``` */ - list(userID: string, query: TenantListParams | null | undefined = {}, options?: RequestOptions): APIPromise { + list( + userID: string, + query: TenantListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { return this._client.get(path`/users/${userID}/tenants`, { query, ...options }); } @@ -33,7 +37,11 @@ export class Tenants extends APIResource { * ``` */ addMultiple(userID: string, body: TenantAddMultipleParams, options?: RequestOptions): APIPromise { - return this._client.put(path`/users/${userID}/tenants`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.put(path`/users/${userID}/tenants`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -50,8 +58,12 @@ export class Tenants extends APIResource { * ``` */ addSingle(tenantID: string, params: TenantAddSingleParams, options?: RequestOptions): APIPromise { - const { user_id, ...body } = params - return this._client.put(path`/users/${user_id}/tenants/${tenantID}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { user_id, ...body } = params; + return this._client.put(path`/users/${user_id}/tenants/${tenantID}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -63,7 +75,10 @@ export class Tenants extends APIResource { * ``` */ removeAll(userID: string, options?: RequestOptions): APIPromise { - return this._client.delete(path`/users/${userID}/tenants`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.delete(path`/users/${userID}/tenants`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -76,9 +91,16 @@ export class Tenants extends APIResource { * }); * ``` */ - removeSingle(tenantID: string, params: TenantRemoveSingleParams, options?: RequestOptions): APIPromise { - const { user_id } = params - return this._client.delete(path`/users/${user_id}/tenants/${tenantID}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + removeSingle( + tenantID: string, + params: TenantRemoveSingleParams, + options?: RequestOptions, + ): APIPromise { + const { user_id } = params; + return this._client.delete(path`/users/${user_id}/tenants/${tenantID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -154,6 +176,6 @@ export declare namespace Tenants { type TenantListParams as TenantListParams, type TenantAddMultipleParams as TenantAddMultipleParams, type TenantAddSingleParams as TenantAddSingleParams, - type TenantRemoveSingleParams as TenantRemoveSingleParams + type TenantRemoveSingleParams as TenantRemoveSingleParams, }; } diff --git a/src/resources/users/tokens.ts b/src/resources/users/tokens.ts index 986ebe9c..1e0c15fb 100644 --- a/src/resources/users/tokens.ts +++ b/src/resources/users/tokens.ts @@ -17,8 +17,12 @@ export class Tokens extends APIResource { * }); * ``` */ - retrieve(token: string, params: TokenRetrieveParams, options?: RequestOptions): APIPromise { - const { user_id } = params + retrieve( + token: string, + params: TokenRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { user_id } = params; return this._client.get(path`/users/${user_id}/tokens/${token}`, options); } @@ -34,8 +38,12 @@ export class Tokens extends APIResource { * ``` */ update(token: string, params: TokenUpdateParams, options?: RequestOptions): APIPromise { - const { user_id, ...body } = params - return this._client.patch(path`/users/${user_id}/tokens/${token}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { user_id, ...body } = params; + return this._client.patch(path`/users/${user_id}/tokens/${token}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -61,8 +69,11 @@ export class Tokens extends APIResource { * ``` */ delete(token: string, params: TokenDeleteParams, options?: RequestOptions): APIPromise { - const { user_id } = params - return this._client.delete(path`/users/${user_id}/tokens/${token}`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { user_id } = params; + return this._client.delete(path`/users/${user_id}/tokens/${token}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -74,7 +85,10 @@ export class Tokens extends APIResource { * ``` */ addMultiple(userID: string, options?: RequestOptions): APIPromise { - return this._client.put(path`/users/${userID}/tokens`, { ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + return this._client.put(path`/users/${userID}/tokens`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } /** @@ -89,8 +103,12 @@ export class Tokens extends APIResource { * ``` */ addSingle(token: string, params: TokenAddSingleParams, options?: RequestOptions): APIPromise { - const { user_id, ...body } = params - return this._client.put(path`/users/${user_id}/tokens/${token}`, { body, ...options, headers: buildHeaders([{Accept: '*/*'}, options?.headers]) }); + const { user_id, ...body } = params; + return this._client.put(path`/users/${user_id}/tokens/${token}`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } } @@ -350,6 +368,6 @@ export declare namespace Tokens { type TokenRetrieveParams as TokenRetrieveParams, type TokenUpdateParams as TokenUpdateParams, type TokenDeleteParams as TokenDeleteParams, - type TokenAddSingleParams as TokenAddSingleParams + type TokenAddSingleParams as TokenAddSingleParams, }; } diff --git a/src/resources/users/users.ts b/src/resources/users/users.ts index 88395fee..c2e1eb73 100644 --- a/src/resources/users/users.ts +++ b/src/resources/users/users.ts @@ -2,11 +2,36 @@ import { APIResource } from '../../core/resource'; import * as PreferencesAPI from './preferences'; -import { PreferenceRetrieveParams, PreferenceRetrieveResponse, PreferenceRetrieveTopicParams, PreferenceRetrieveTopicResponse, PreferenceUpdateOrCreateTopicParams, PreferenceUpdateOrCreateTopicResponse, Preferences, TopicPreference } from './preferences'; +import { + PreferenceRetrieveParams, + PreferenceRetrieveResponse, + PreferenceRetrieveTopicParams, + PreferenceRetrieveTopicResponse, + PreferenceUpdateOrCreateTopicParams, + PreferenceUpdateOrCreateTopicResponse, + Preferences, + TopicPreference, +} from './preferences'; import * as TenantsAPI from './tenants'; -import { TenantAddMultipleParams, TenantAddSingleParams, TenantListParams, TenantListResponse, TenantRemoveSingleParams, Tenants } from './tenants'; +import { + TenantAddMultipleParams, + TenantAddSingleParams, + TenantListParams, + TenantListResponse, + TenantRemoveSingleParams, + Tenants, +} from './tenants'; import * as TokensAPI from './tokens'; -import { TokenAddSingleParams, TokenDeleteParams, TokenListResponse, TokenRetrieveParams, TokenRetrieveResponse, TokenUpdateParams, Tokens, UserToken } from './tokens'; +import { + TokenAddSingleParams, + TokenDeleteParams, + TokenListResponse, + TokenRetrieveParams, + TokenRetrieveResponse, + TokenUpdateParams, + Tokens, + UserToken, +} from './tokens'; export class Users extends APIResource { preferences: PreferencesAPI.Preferences = new PreferencesAPI.Preferences(this._client); @@ -27,7 +52,7 @@ export declare namespace Users { type PreferenceUpdateOrCreateTopicResponse as PreferenceUpdateOrCreateTopicResponse, type PreferenceRetrieveParams as PreferenceRetrieveParams, type PreferenceRetrieveTopicParams as PreferenceRetrieveTopicParams, - type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams + type PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams, }; export { @@ -36,7 +61,7 @@ export declare namespace Users { type TenantListParams as TenantListParams, type TenantAddMultipleParams as TenantAddMultipleParams, type TenantAddSingleParams as TenantAddSingleParams, - type TenantRemoveSingleParams as TenantRemoveSingleParams + type TenantRemoveSingleParams as TenantRemoveSingleParams, }; export { @@ -47,6 +72,6 @@ export declare namespace Users { type TokenRetrieveParams as TokenRetrieveParams, type TokenUpdateParams as TokenUpdateParams, type TokenDeleteParams as TokenDeleteParams, - type TokenAddSingleParams as TokenAddSingleParams + type TokenAddSingleParams as TokenAddSingleParams, }; } diff --git a/src/uploads.ts b/src/uploads.ts index d5437085..b2ef6471 100644 --- a/src/uploads.ts +++ b/src/uploads.ts @@ -1,2 +1,2 @@ /** @deprecated Import from ./core/uploads instead */ -export * from "./core/uploads" \ No newline at end of file +export * from './core/uploads'; diff --git a/src/version.ts b/src/version.ts index 4bb2954d..4533200e 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '7.10.2';// x-release-please-version +export const VERSION = '7.10.2'; // x-release-please-version diff --git a/tests/api-resources/audiences.test.ts b/tests/api-resources/audiences.test.ts index ff776ad0..be870cdd 100644 --- a/tests/api-resources/audiences.test.ts +++ b/tests/api-resources/audiences.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource audiences', () => { // Mock server tests are disabled @@ -44,9 +47,9 @@ describe('resource audiences', () => { // Mock server tests are disabled test.skip('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.audiences.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.audiences.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -76,8 +79,8 @@ describe('resource audiences', () => { // Mock server tests are disabled test.skip('listMembers: 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.audiences.listMembers('audience_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.audiences.listMembers('audience_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/audit-events.test.ts b/tests/api-resources/audit-events.test.ts index 5cc5cbca..236efabb 100644 --- a/tests/api-resources/audit-events.test.ts +++ b/tests/api-resources/audit-events.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource auditEvents', () => { // Mock server tests are disabled @@ -32,8 +35,8 @@ describe('resource auditEvents', () => { // Mock server tests are disabled test.skip('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.auditEvents.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.auditEvents.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/auth.test.ts b/tests/api-resources/auth.test.ts index 63c291aa..7773e3d1 100644 --- a/tests/api-resources/auth.test.ts +++ b/tests/api-resources/auth.test.ts @@ -2,12 +2,19 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource auth', () => { // Mock server tests are disabled test.skip('issueToken: only required params', async () => { - const responsePromise = client.auth.issueToken({ expires_in: '$YOUR_NUMBER days', scope: 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands' }); + const responsePromise = client.auth.issueToken({ + expires_in: '$YOUR_NUMBER days', + scope: + 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands', + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -19,6 +26,10 @@ describe('resource auth', () => { // Mock server tests are disabled test.skip('issueToken: required and optional params', async () => { - const response = await client.auth.issueToken({ expires_in: '$YOUR_NUMBER days', scope: 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands' }); + const response = await client.auth.issueToken({ + expires_in: '$YOUR_NUMBER days', + scope: + 'user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands', + }); }); }); diff --git a/tests/api-resources/automations/automations.test.ts b/tests/api-resources/automations/automations.test.ts index a772c5f7..eb2e9248 100644 --- a/tests/api-resources/automations/automations.test.ts +++ b/tests/api-resources/automations/automations.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource automations', () => { // Mock server tests are disabled @@ -20,8 +23,11 @@ describe('resource automations', () => { // Mock server tests are disabled test.skip('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.automations.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.automations.list( + { cursor: 'cursor', version: 'published' }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/automations/invoke.test.ts b/tests/api-resources/automations/invoke.test.ts index 8887eb85..d52475be 100644 --- a/tests/api-resources/automations/invoke.test.ts +++ b/tests/api-resources/automations/invoke.test.ts @@ -2,12 +2,17 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource invoke', () => { // Mock server tests are disabled test.skip('invokeAdHoc: only required params', async () => { - const responsePromise = client.automations.invoke.invokeAdHoc({ automation: { steps: [{ action: 'delay' }, { action: 'send' }] } }); + const responsePromise = client.automations.invoke.invokeAdHoc({ + automation: { steps: [{ action: 'delay' }, { action: 'send' }] }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -20,29 +25,37 @@ describe('resource invoke', () => { // Mock server tests are disabled test.skip('invokeAdHoc: required and optional params', async () => { const response = await client.automations.invoke.invokeAdHoc({ - automation: { steps: [{ - action: 'delay', - duration: 'duration', - until: '20240408T080910.123', - }, { - action: 'send', - brand: 'brand', - data: { foo: 'bar' }, - profile: { foo: 'bar' }, - recipient: 'recipient', - template: '64TP5HKPFTM8VTK1Y75SJDQX9JK0', - }], cancelation_token: 'delay-send--user-yes--abc-123' }, - brand: 'brand', - data: { name: 'bar' }, - profile: { tenant_id: 'bar' }, - recipient: 'user-yes', - template: 'template', - }); + automation: { + steps: [ + { + action: 'delay', + duration: 'duration', + until: '20240408T080910.123', + }, + { + action: 'send', + brand: 'brand', + data: { foo: 'bar' }, + profile: { foo: 'bar' }, + recipient: 'recipient', + template: '64TP5HKPFTM8VTK1Y75SJDQX9JK0', + }, + ], + cancelation_token: 'delay-send--user-yes--abc-123', + }, + brand: 'brand', + data: { name: 'bar' }, + profile: { tenant_id: 'bar' }, + recipient: 'user-yes', + template: 'template', + }); }); // Mock server tests are disabled test.skip('invokeByTemplate: only required params', async () => { - const responsePromise = client.automations.invoke.invokeByTemplate('templateId', { recipient: 'recipient' }); + const responsePromise = client.automations.invoke.invokeByTemplate('templateId', { + recipient: 'recipient', + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -55,11 +68,11 @@ describe('resource invoke', () => { // Mock server tests are disabled test.skip('invokeByTemplate: required and optional params', async () => { const response = await client.automations.invoke.invokeByTemplate('templateId', { - recipient: 'recipient', - brand: 'brand', - data: { foo: 'bar' }, - profile: { foo: 'bar' }, - template: 'template', - }); + recipient: 'recipient', + brand: 'brand', + data: { foo: 'bar' }, + profile: { foo: 'bar' }, + template: 'template', + }); }); }); diff --git a/tests/api-resources/brands.test.ts b/tests/api-resources/brands.test.ts index cc49ddeb..d02ad9cc 100644 --- a/tests/api-resources/brands.test.ts +++ b/tests/api-resources/brands.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource brands', () => { // Mock server tests are disabled @@ -20,51 +23,51 @@ describe('resource brands', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.brands.create({ - name: 'name', - id: 'id', - settings: { - colors: { primary: 'primary', secondary: 'secondary' }, - email: { - footer: { content: 'content', inheritDefault: true }, - head: { inheritDefault: true, content: 'content' }, - header: { - logo: { href: 'href', image: 'image' }, - barColor: 'barColor', - inheritDefault: true, - }, - templateOverride: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - mjml: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - }, - footerBackgroundColor: 'footerBackgroundColor', - footerFullWidth: true, - }, - }, - inapp: { - colors: { primary: 'primary', secondary: 'secondary' }, - icons: { bell: 'bell', message: 'message' }, - widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, - borderRadius: 'borderRadius', - disableMessageIcon: true, - fontFamily: 'fontFamily', - placement: 'top', - }, - }, - snippets: { items: [{ name: 'name', value: 'value' }] }, - }); + name: 'name', + id: 'id', + settings: { + colors: { primary: 'primary', secondary: 'secondary' }, + email: { + footer: { content: 'content', inheritDefault: true }, + head: { inheritDefault: true, content: 'content' }, + header: { + logo: { href: 'href', image: 'image' }, + barColor: 'barColor', + inheritDefault: true, + }, + templateOverride: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + mjml: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + }, + footerBackgroundColor: 'footerBackgroundColor', + footerFullWidth: true, + }, + }, + inapp: { + colors: { primary: 'primary', secondary: 'secondary' }, + icons: { bell: 'bell', message: 'message' }, + widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, + borderRadius: 'borderRadius', + disableMessageIcon: true, + fontFamily: 'fontFamily', + placement: 'top', + }, + }, + snippets: { items: [{ name: 'name', value: 'value' }] }, + }); }); // Mock server tests are disabled @@ -94,50 +97,50 @@ describe('resource brands', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.brands.update('brand_id', { - name: 'name', - settings: { - colors: { primary: 'primary', secondary: 'secondary' }, - email: { - footer: { content: 'content', inheritDefault: true }, - head: { inheritDefault: true, content: 'content' }, - header: { - logo: { href: 'href', image: 'image' }, - barColor: 'barColor', - inheritDefault: true, - }, - templateOverride: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - mjml: { - enabled: true, - backgroundColor: 'backgroundColor', - blocksBackgroundColor: 'blocksBackgroundColor', - footer: 'footer', - head: 'head', - header: 'header', - width: 'width', - }, - footerBackgroundColor: 'footerBackgroundColor', - footerFullWidth: true, - }, - }, - inapp: { - colors: { primary: 'primary', secondary: 'secondary' }, - icons: { bell: 'bell', message: 'message' }, - widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, - borderRadius: 'borderRadius', - disableMessageIcon: true, - fontFamily: 'fontFamily', - placement: 'top', - }, - }, - snippets: { items: [{ name: 'name', value: 'value' }] }, - }); + name: 'name', + settings: { + colors: { primary: 'primary', secondary: 'secondary' }, + email: { + footer: { content: 'content', inheritDefault: true }, + head: { inheritDefault: true, content: 'content' }, + header: { + logo: { href: 'href', image: 'image' }, + barColor: 'barColor', + inheritDefault: true, + }, + templateOverride: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + mjml: { + enabled: true, + backgroundColor: 'backgroundColor', + blocksBackgroundColor: 'blocksBackgroundColor', + footer: 'footer', + head: 'head', + header: 'header', + width: 'width', + }, + footerBackgroundColor: 'footerBackgroundColor', + footerFullWidth: true, + }, + }, + inapp: { + colors: { primary: 'primary', secondary: 'secondary' }, + icons: { bell: 'bell', message: 'message' }, + widgetBackground: { bottomColor: 'bottomColor', topColor: 'topColor' }, + borderRadius: 'borderRadius', + disableMessageIcon: true, + fontFamily: 'fontFamily', + placement: 'top', + }, + }, + snippets: { items: [{ name: 'name', value: 'value' }] }, + }); }); // Mock server tests are disabled @@ -155,9 +158,9 @@ describe('resource brands', () => { // Mock server tests are disabled test.skip('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.brands.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.brands.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/bulk.test.ts b/tests/api-resources/bulk.test.ts index cb0c5761..2cec3e13 100644 --- a/tests/api-resources/bulk.test.ts +++ b/tests/api-resources/bulk.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource bulk', () => { // Mock server tests are disabled @@ -19,49 +22,61 @@ describe('resource bulk', () => { // Mock server tests are disabled test.skip('addUsers: required and optional params', async () => { - const response = await client.bulk.addUsers('job_id', { users: [{ - data: {}, - preferences: { - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - }, - profile: { foo: 'bar' }, - recipient: 'recipient', - to: { - account_id: 'account_id', - context: { tenant_id: 'tenant_id' }, - data: { foo: 'bar' }, - email: 'email', - list_id: 'list_id', - locale: 'locale', - phone_number: 'phone_number', - preferences: { - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - } }, - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - } }, - templateId: 'templateId', - }, - tenant_id: 'tenant_id', - user_id: 'user_id', - }, - }] }); + const response = await client.bulk.addUsers('job_id', { + users: [ + { + data: {}, + preferences: { + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + }, + profile: { foo: 'bar' }, + recipient: 'recipient', + to: { + account_id: 'account_id', + context: { tenant_id: 'tenant_id' }, + data: { foo: 'bar' }, + email: 'email', + list_id: 'list_id', + locale: 'locale', + phone_number: 'phone_number', + preferences: { + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + }, + }, + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + }, + }, + templateId: 'templateId', + }, + tenant_id: 'tenant_id', + user_id: 'user_id', + }, + }, + ], + }); }); // Mock server tests are disabled @@ -78,15 +93,17 @@ describe('resource bulk', () => { // Mock server tests are disabled test.skip('createJob: required and optional params', async () => { - const response = await client.bulk.createJob({ message: { - event: 'event', - brand: 'brand', - content: { body: 'body', title: 'title' }, - data: { foo: 'bar' }, - locale: { foo: { foo: 'bar' } }, - override: { foo: 'bar' }, - template: 'template', - } }); + const response = await client.bulk.createJob({ + message: { + event: 'event', + brand: 'brand', + content: { body: 'body', title: 'title' }, + data: { foo: 'bar' }, + locale: { foo: { foo: 'bar' } }, + override: { foo: 'bar' }, + template: 'template', + }, + }); }); // Mock server tests are disabled @@ -104,9 +121,9 @@ describe('resource bulk', () => { // Mock server tests are disabled test.skip('listUsers: 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.bulk.listUsers('job_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.bulk.listUsers('job_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/inbound.test.ts b/tests/api-resources/inbound.test.ts index b737f526..9e49a5b9 100644 --- a/tests/api-resources/inbound.test.ts +++ b/tests/api-resources/inbound.test.ts @@ -2,21 +2,24 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource inbound', () => { // Mock server tests are disabled test.skip('trackEvent: only required params', async () => { const responsePromise = client.inbound.trackEvent({ - event: 'New Order Placed', - messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', - properties: { - order_id: 'bar', - total_orders: 'bar', - last_order_id: 'bar', - }, - type: 'track', - }); + event: 'New Order Placed', + messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', + properties: { + order_id: 'bar', + total_orders: 'bar', + last_order_id: 'bar', + }, + type: 'track', + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -29,15 +32,15 @@ describe('resource inbound', () => { // Mock server tests are disabled test.skip('trackEvent: required and optional params', async () => { const response = await client.inbound.trackEvent({ - event: 'New Order Placed', - messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', - properties: { - order_id: 'bar', - total_orders: 'bar', - last_order_id: 'bar', - }, - type: 'track', - userId: '1234', - }); + event: 'New Order Placed', + messageId: '4c62c457-b329-4bea-9bfc-17bba86c393f', + properties: { + order_id: 'bar', + total_orders: 'bar', + last_order_id: 'bar', + }, + type: 'track', + userId: '1234', + }); }); }); diff --git a/tests/api-resources/journeys.test.ts b/tests/api-resources/journeys.test.ts index 41634daf..92d4b7a5 100644 --- a/tests/api-resources/journeys.test.ts +++ b/tests/api-resources/journeys.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource journeys', () => { // Mock server tests are disabled @@ -20,9 +23,9 @@ describe('resource journeys', () => { // Mock server tests are disabled test.skip('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.journeys.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.journeys.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/lists/lists.test.ts b/tests/api-resources/lists/lists.test.ts index d13103a8..0a69942b 100644 --- a/tests/api-resources/lists/lists.test.ts +++ b/tests/api-resources/lists/lists.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource lists', () => { // Mock server tests are disabled @@ -32,20 +35,24 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.lists.update('list_id', { - name: 'name', - preferences: { - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - }, - }); + name: 'name', + preferences: { + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + }, + }); }); // Mock server tests are disabled @@ -63,9 +70,9 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('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.lists.list({ cursor: 'cursor', pattern: 'pattern' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.lists.list({ cursor: 'cursor', pattern: 'pattern' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/lists/subscriptions.test.ts b/tests/api-resources/lists/subscriptions.test.ts index 62fe825a..ec7570f5 100644 --- a/tests/api-resources/lists/subscriptions.test.ts +++ b/tests/api-resources/lists/subscriptions.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource subscriptions', () => { // Mock server tests are disabled @@ -20,14 +23,16 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('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.lists.subscriptions.list('list_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.lists.subscriptions.list('list_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled test.skip('add: only required params', async () => { - const responsePromise = client.lists.subscriptions.add('list_id', { recipients: [{ recipientId: 'recipientId' }] }); + const responsePromise = client.lists.subscriptions.add('list_id', { + recipients: [{ recipientId: 'recipientId' }], + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -39,26 +44,36 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('add: required and optional params', async () => { - const response = await client.lists.subscriptions.add('list_id', { recipients: [{ - recipientId: 'recipientId', - preferences: { - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - }, - }] }); + const response = await client.lists.subscriptions.add('list_id', { + recipients: [ + { + recipientId: 'recipientId', + preferences: { + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + }, + }, + ], + }); }); // Mock server tests are disabled test.skip('subscribe: only required params', async () => { - const responsePromise = client.lists.subscriptions.subscribe('list_id', { recipients: [{ recipientId: 'recipientId' }] }); + const responsePromise = client.lists.subscriptions.subscribe('list_id', { + recipients: [{ recipientId: 'recipientId' }], + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -70,21 +85,29 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('subscribe: required and optional params', async () => { - const response = await client.lists.subscriptions.subscribe('list_id', { recipients: [{ - recipientId: 'recipientId', - preferences: { - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - }, - }] }); + const response = await client.lists.subscriptions.subscribe('list_id', { + recipients: [ + { + recipientId: 'recipientId', + preferences: { + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + }, + }, + ], + }); }); // Mock server tests are disabled @@ -102,20 +125,24 @@ describe('resource subscriptions', () => { // Mock server tests are disabled test.skip('subscribeUser: required and optional params', async () => { const response = await client.lists.subscriptions.subscribeUser('user_id', { - list_id: 'list_id', - preferences: { - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - }, - }); + list_id: 'list_id', + preferences: { + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + }, + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/messages.test.ts b/tests/api-resources/messages.test.ts index 57ce38ba..48000970 100644 --- a/tests/api-resources/messages.test.ts +++ b/tests/api-resources/messages.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource messages', () => { // Mock server tests are disabled @@ -32,24 +35,27 @@ describe('resource messages', () => { // Mock server tests are disabled test.skip('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.messages.list({ - archived: true, - cursor: 'cursor', - enqueued_after: 'enqueued_after', - event: 'event', - list: 'list', - messageId: 'messageId', - notification: 'notification', - provider: ['string'], - recipient: 'recipient', - status: ['string'], - tag: ['string'], - tags: 'tags', - tenant_id: 'tenant_id', - traceId: 'traceId', - }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.messages.list( + { + archived: true, + cursor: 'cursor', + enqueued_after: 'enqueued_after', + event: 'event', + list: 'list', + messageId: 'messageId', + notification: 'notification', + provider: ['string'], + recipient: 'recipient', + status: ['string'], + tag: ['string'], + tags: 'tags', + tenant_id: 'tenant_id', + traceId: 'traceId', + }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -91,8 +97,8 @@ describe('resource messages', () => { // Mock server tests are disabled test.skip('history: 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.messages.history('message_id', { type: 'type' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.messages.history('message_id', { type: 'type' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/notifications/checks.test.ts b/tests/api-resources/notifications/checks.test.ts index 9cfa58a6..cc4a65ab 100644 --- a/tests/api-resources/notifications/checks.test.ts +++ b/tests/api-resources/notifications/checks.test.ts @@ -2,16 +2,24 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource checks', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.notifications.checks.update('submissionId', { id: 'id', checks: [{ - id: 'id', - status: 'RESOLVED', - type: 'custom', - }] }); + const responsePromise = client.notifications.checks.update('submissionId', { + id: 'id', + checks: [ + { + id: 'id', + status: 'RESOLVED', + type: 'custom', + }, + ], + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -23,11 +31,16 @@ describe('resource checks', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { - const response = await client.notifications.checks.update('submissionId', { id: 'id', checks: [{ - id: 'id', - status: 'RESOLVED', - type: 'custom', - }] }); + const response = await client.notifications.checks.update('submissionId', { + id: 'id', + checks: [ + { + id: 'id', + status: 'RESOLVED', + type: 'custom', + }, + ], + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/notifications/notifications.test.ts b/tests/api-resources/notifications/notifications.test.ts index fde2400b..b5fcdfe3 100644 --- a/tests/api-resources/notifications/notifications.test.ts +++ b/tests/api-resources/notifications/notifications.test.ts @@ -2,19 +2,24 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource notifications', () => { // Mock server tests are disabled test.skip('create: only required params', async () => { - const responsePromise = client.notifications.create({ notification: { - brand: { id: 'brand_abc' }, - content: { elements: [{}], version: '2022-01-01' }, - name: 'Welcome Email', - routing: { strategy_id: 'rs_123' }, - subscription: { topic_id: 'marketing' }, - tags: ['onboarding', 'welcome'], - } }); + const responsePromise = client.notifications.create({ + notification: { + brand: { id: 'brand_abc' }, + content: { elements: [{}], version: '2022-01-01' }, + name: 'Welcome Email', + routing: { strategy_id: 'rs_123' }, + subscription: { topic_id: 'marketing' }, + tags: ['onboarding', 'welcome'], + }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -27,16 +32,16 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.notifications.create({ - notification: { - brand: { id: 'brand_abc' }, - content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, - name: 'Welcome Email', - routing: { strategy_id: 'rs_123' }, - subscription: { topic_id: 'marketing' }, - tags: ['onboarding', 'welcome'], - }, - state: 'DRAFT', - }); + notification: { + brand: { id: 'brand_abc' }, + content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, + name: 'Welcome Email', + routing: { strategy_id: 'rs_123' }, + subscription: { topic_id: 'marketing' }, + tags: ['onboarding', 'welcome'], + }, + state: 'DRAFT', + }); }); // Mock server tests are disabled @@ -54,9 +59,9 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('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.notifications.retrieve('id', { version: 'version' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.notifications.retrieve('id', { version: 'version' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -74,13 +79,16 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('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.notifications.list({ - cursor: 'cursor', - event_id: 'event_id', - notes: true, - }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.notifications.list( + { + cursor: 'cursor', + event_id: 'event_id', + notes: true, + }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -110,9 +118,13 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('listVersions: 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.notifications.listVersions('id', { cursor: 'cursor', limit: 10 }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.notifications.listVersions( + 'id', + { cursor: 'cursor', limit: 10 }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -130,9 +142,9 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('publish: 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.notifications.publish('id', { version: 'v321669910225' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.notifications.publish('id', { version: 'v321669910225' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -150,9 +162,9 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('putContent: required and optional params', async () => { const response = await client.notifications.putContent('id', { - content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, - state: 'DRAFT', - }); + content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, + state: 'DRAFT', + }); }); // Mock server tests are disabled @@ -170,20 +182,23 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('putElement: required and optional params', async () => { const response = await client.notifications.putElement('elementId', { - id: 'id', - type: 'text', - channels: ['string'], - data: { content: 'bar' }, - if: 'if', - loop: 'loop', - ref: 'ref', - state: 'DRAFT', - }); + id: 'id', + type: 'text', + channels: ['string'], + data: { content: 'bar' }, + if: 'if', + loop: 'loop', + ref: 'ref', + state: 'DRAFT', + }); }); // Mock server tests are disabled test.skip('putLocale: only required params', async () => { - const responsePromise = client.notifications.putLocale('localeId', { id: 'id', elements: [{ id: 'elem_1' }, { id: 'elem_2' }] }); + const responsePromise = client.notifications.putLocale('localeId', { + id: 'id', + elements: [{ id: 'elem_1' }, { id: 'elem_2' }], + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -196,22 +211,24 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('putLocale: required and optional params', async () => { const response = await client.notifications.putLocale('localeId', { - id: 'id', - elements: [{ id: 'elem_1' }, { id: 'elem_2' }], - state: 'DRAFT', - }); + id: 'id', + elements: [{ id: 'elem_1' }, { id: 'elem_2' }], + state: 'DRAFT', + }); }); // Mock server tests are disabled test.skip('replace: only required params', async () => { - const responsePromise = client.notifications.replace('id', { notification: { - brand: { id: 'id' }, - content: { elements: [{}], version: '2022-01-01' }, - name: 'Updated Name', - routing: { strategy_id: 'strategy_id' }, - subscription: { topic_id: 'topic_id' }, - tags: ['updated'], - } }); + const responsePromise = client.notifications.replace('id', { + notification: { + brand: { id: 'id' }, + content: { elements: [{}], version: '2022-01-01' }, + name: 'Updated Name', + routing: { strategy_id: 'strategy_id' }, + subscription: { topic_id: 'topic_id' }, + tags: ['updated'], + }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -224,16 +241,16 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('replace: required and optional params', async () => { const response = await client.notifications.replace('id', { - notification: { - brand: { id: 'id' }, - content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, - name: 'Updated Name', - routing: { strategy_id: 'strategy_id' }, - subscription: { topic_id: 'topic_id' }, - tags: ['updated'], - }, - state: 'PUBLISHED', - }); + notification: { + brand: { id: 'id' }, + content: { elements: [{ type: 'channel' }], version: '2022-01-01' }, + name: 'Updated Name', + routing: { strategy_id: 'strategy_id' }, + subscription: { topic_id: 'topic_id' }, + tags: ['updated'], + }, + state: 'PUBLISHED', + }); }); // Mock server tests are disabled @@ -251,8 +268,12 @@ describe('resource notifications', () => { // Mock server tests are disabled test.skip('retrieveContent: 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.notifications.retrieveContent('id', { version: 'version' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.notifications.retrieveContent( + 'id', + { version: 'version' }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/profiles/lists.test.ts b/tests/api-resources/profiles/lists.test.ts index 522abeb8..54fe8e00 100644 --- a/tests/api-resources/profiles/lists.test.ts +++ b/tests/api-resources/profiles/lists.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource lists', () => { // Mock server tests are disabled @@ -20,9 +23,9 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('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.profiles.lists.retrieve('user_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.profiles.lists.retrieve('user_id', { cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -51,20 +54,28 @@ describe('resource lists', () => { // Mock server tests are disabled test.skip('subscribe: required and optional params', async () => { - const response = await client.profiles.lists.subscribe('user_id', { lists: [{ - listId: 'listId', - preferences: { - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - } }, - }, - }] }); + const response = await client.profiles.lists.subscribe('user_id', { + lists: [ + { + listId: 'listId', + preferences: { + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + }, + }, + }, + }, + ], + }); }); }); diff --git a/tests/api-resources/profiles/profiles.test.ts b/tests/api-resources/profiles/profiles.test.ts index 9dcb9b59..65785844 100644 --- a/tests/api-resources/profiles/profiles.test.ts +++ b/tests/api-resources/profiles/profiles.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource profiles', () => { // Mock server tests are disabled @@ -36,11 +39,15 @@ describe('resource profiles', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.profiles.update('user_id', { patch: [{ - op: 'op', - path: 'path', - value: 'value', - }] }); + const responsePromise = client.profiles.update('user_id', { + patch: [ + { + op: 'op', + path: 'path', + value: 'value', + }, + ], + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -52,11 +59,15 @@ describe('resource profiles', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { - const response = await client.profiles.update('user_id', { patch: [{ - op: 'op', - path: 'path', - value: 'value', - }] }); + const response = await client.profiles.update('user_id', { + patch: [ + { + op: 'op', + path: 'path', + value: 'value', + }, + ], + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/providers/catalog.test.ts b/tests/api-resources/providers/catalog.test.ts index 27246cbd..f087e739 100644 --- a/tests/api-resources/providers/catalog.test.ts +++ b/tests/api-resources/providers/catalog.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource catalog', () => { // Mock server tests are disabled @@ -20,12 +23,15 @@ describe('resource catalog', () => { // Mock server tests are disabled test.skip('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.providers.catalog.list({ - channel: 'channel', - keys: 'keys', - name: 'name', - }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.providers.catalog.list( + { + channel: 'channel', + keys: 'keys', + name: 'name', + }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/providers/providers.test.ts b/tests/api-resources/providers/providers.test.ts index 2370c58f..3ea22cfc 100644 --- a/tests/api-resources/providers/providers.test.ts +++ b/tests/api-resources/providers/providers.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource providers', () => { // Mock server tests are disabled @@ -20,11 +23,11 @@ describe('resource providers', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.providers.create({ - provider: 'provider', - alias: 'alias', - settings: { foo: 'bar' }, - title: 'title', - }); + provider: 'provider', + alias: 'alias', + settings: { foo: 'bar' }, + title: 'title', + }); }); // Mock server tests are disabled @@ -54,11 +57,11 @@ describe('resource providers', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.providers.update('id', { - provider: 'provider', - alias: 'alias', - settings: { foo: 'bar' }, - title: 'title', - }); + provider: 'provider', + alias: 'alias', + settings: { foo: 'bar' }, + title: 'title', + }); }); // Mock server tests are disabled @@ -76,9 +79,9 @@ describe('resource providers', () => { // Mock server tests are disabled test.skip('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.providers.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.providers.list({ cursor: 'cursor' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled diff --git a/tests/api-resources/requests.test.ts b/tests/api-resources/requests.test.ts index ca8ca68c..104590ae 100644 --- a/tests/api-resources/requests.test.ts +++ b/tests/api-resources/requests.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource requests', () => { // Mock server tests are disabled diff --git a/tests/api-resources/routing-strategies.test.ts b/tests/api-resources/routing-strategies.test.ts index afd555ff..3f6de460 100644 --- a/tests/api-resources/routing-strategies.test.ts +++ b/tests/api-resources/routing-strategies.test.ts @@ -2,15 +2,18 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.routingStrategies.create({ - name: 'Email via SendGrid', - routing: { channels: ['email'], method: 'single' }, - }); + name: 'Email via SendGrid', + routing: { channels: ['email'], method: 'single' }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -23,38 +26,46 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.routingStrategies.create({ - name: 'Email via SendGrid', - routing: { channels: ['email'], method: 'single' }, - channels: { email: { - brand_id: 'brand_id', - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: { foo: 'bar' }, - providers: ['sendgrid', 'ses'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - } }, - description: 'Routes email through sendgrid with SES failover', - providers: { sendgrid: { - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: {}, - timeouts: 0, - } }, - tags: ['production', 'email'], - }); + name: 'Email via SendGrid', + routing: { channels: ['email'], method: 'single' }, + channels: { + email: { + brand_id: 'brand_id', + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: { foo: 'bar' }, + providers: ['sendgrid', 'ses'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + }, + }, + description: 'Routes email through sendgrid with SES failover', + providers: { + sendgrid: { + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: {}, + timeouts: 0, + }, + }, + tags: ['production', 'email'], + }); }); // Mock server tests are disabled @@ -84,9 +95,9 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('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.routingStrategies.list({ cursor: 'cursor', limit: 1 }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.routingStrategies.list({ cursor: 'cursor', limit: 1 }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -116,17 +127,21 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('listNotifications: 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.routingStrategies.listNotifications('id', { cursor: 'cursor', limit: 1 }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.routingStrategies.listNotifications( + 'id', + { cursor: 'cursor', limit: 1 }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled test.skip('replace: only required params', async () => { const responsePromise = client.routingStrategies.replace('id', { - name: 'Email via SendGrid v2', - routing: { channels: ['email'], method: 'single' }, - }); + name: 'Email via SendGrid v2', + routing: { channels: ['email'], method: 'single' }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -139,37 +154,45 @@ describe('resource routingStrategies', () => { // Mock server tests are disabled test.skip('replace: required and optional params', async () => { const response = await client.routingStrategies.replace('id', { - name: 'Email via SendGrid v2', - routing: { channels: ['email'], method: 'single' }, - channels: { email: { - brand_id: 'brand_id', - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: { foo: 'bar' }, - providers: ['ses', 'sendgrid'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - } }, - description: 'Updated routing with SES primary', - providers: { ses: { - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: {}, - timeouts: 0, - } }, - tags: ['production', 'email', 'v2'], - }); + name: 'Email via SendGrid v2', + routing: { channels: ['email'], method: 'single' }, + channels: { + email: { + brand_id: 'brand_id', + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: { foo: 'bar' }, + providers: ['ses', 'sendgrid'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + }, + }, + description: 'Updated routing with SES primary', + providers: { + ses: { + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: {}, + timeouts: 0, + }, + }, + tags: ['production', 'email', 'v2'], + }); }); }); diff --git a/tests/api-resources/send.test.ts b/tests/api-resources/send.test.ts index 88ce631c..2daf02a5 100644 --- a/tests/api-resources/send.test.ts +++ b/tests/api-resources/send.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource send', () => { // Mock server tests are disabled @@ -19,92 +22,106 @@ describe('resource send', () => { // Mock server tests are disabled test.skip('message: required and optional params', async () => { - const response = await client.send.message({ message: { - brand_id: 'brand_id', - channels: { foo: { - brand_id: 'brand_id', - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: { foo: 'bar' }, - providers: ['string'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - } }, - content: { body: 'body', title: 'title' }, - context: { tenant_id: 'tenant_id' }, - data: { foo: 'bar' }, - delay: { - duration: 0, - timezone: 'timezone', - until: 'until', - }, - expiry: { expires_in: 'string', expires_at: 'expires_at' }, - metadata: { - event: 'event', - tags: ['string'], - trace_id: 'trace_id', - utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - }, - }, - preferences: { subscription_topic_id: 'subscription_topic_id' }, - providers: { foo: { - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: { foo: 'bar' }, - timeouts: 0, - } }, - routing: { channels: ['string'], method: 'all' }, - template: 'template_id', - timeout: { - channel: { foo: 0 }, - criteria: 'no-escalation', - escalation: 0, - message: 0, - provider: { foo: 0 }, - }, - to: { - account_id: 'account_id', - context: { tenant_id: 'tenant_id' }, - data: { foo: 'bar' }, - email: 'email', - list_id: 'list_id', - locale: 'locale', - phone_number: 'phone_number', - preferences: { - notifications: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - } }, - categories: { foo: { - status: 'OPTED_IN', - channel_preferences: [{ channel: 'direct_message' }], - rules: [{ until: 'until', start: 'start' }], - source: 'subscription', - } }, - templateId: 'templateId', - }, - tenant_id: 'tenant_id', - user_id: 'user_id', - }, - } }); + const response = await client.send.message({ + message: { + brand_id: 'brand_id', + channels: { + foo: { + brand_id: 'brand_id', + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: { foo: 'bar' }, + providers: ['string'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + }, + }, + content: { body: 'body', title: 'title' }, + context: { tenant_id: 'tenant_id' }, + data: { foo: 'bar' }, + delay: { + duration: 0, + timezone: 'timezone', + until: 'until', + }, + expiry: { expires_in: 'string', expires_at: 'expires_at' }, + metadata: { + event: 'event', + tags: ['string'], + trace_id: 'trace_id', + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + preferences: { subscription_topic_id: 'subscription_topic_id' }, + providers: { + foo: { + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: { foo: 'bar' }, + timeouts: 0, + }, + }, + routing: { channels: ['string'], method: 'all' }, + template: 'template_id', + timeout: { + channel: { foo: 0 }, + criteria: 'no-escalation', + escalation: 0, + message: 0, + provider: { foo: 0 }, + }, + to: { + account_id: 'account_id', + context: { tenant_id: 'tenant_id' }, + data: { foo: 'bar' }, + email: 'email', + list_id: 'list_id', + locale: 'locale', + phone_number: 'phone_number', + preferences: { + notifications: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + }, + }, + categories: { + foo: { + status: 'OPTED_IN', + channel_preferences: [{ channel: 'direct_message' }], + rules: [{ until: 'until', start: 'start' }], + source: 'subscription', + }, + }, + templateId: 'templateId', + }, + tenant_id: 'tenant_id', + user_id: 'user_id', + }, + }, + }); }); }); diff --git a/tests/api-resources/tenants/preferences/items.test.ts b/tests/api-resources/tenants/preferences/items.test.ts index ee5d6276..f502f673 100644 --- a/tests/api-resources/tenants/preferences/items.test.ts +++ b/tests/api-resources/tenants/preferences/items.test.ts @@ -2,12 +2,18 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource items', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.tenants.preferences.items.update('topic_id', { tenant_id: 'tenant_id', status: 'OPTED_IN' }); + const responsePromise = client.tenants.preferences.items.update('topic_id', { + tenant_id: 'tenant_id', + status: 'OPTED_IN', + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -20,11 +26,11 @@ describe('resource items', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.tenants.preferences.items.update('topic_id', { - tenant_id: 'tenant_id', - status: 'OPTED_IN', - custom_routing: ['inbox'], - has_custom_routing: true, - }); + tenant_id: 'tenant_id', + status: 'OPTED_IN', + custom_routing: ['inbox'], + has_custom_routing: true, + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/tenants/templates/templates.test.ts b/tests/api-resources/tenants/templates/templates.test.ts index a4687699..94e7ae8e 100644 --- a/tests/api-resources/tenants/templates/templates.test.ts +++ b/tests/api-resources/tenants/templates/templates.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource templates', () => { // Mock server tests are disabled @@ -37,9 +40,13 @@ describe('resource templates', () => { // Mock server tests are disabled test.skip('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.tenants.templates.list('tenant_id', { cursor: 'cursor', limit: 0 }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.tenants.templates.list( + 'tenant_id', + { cursor: 'cursor', limit: 0 }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -56,15 +63,18 @@ describe('resource templates', () => { // Mock server tests are disabled test.skip('publish: required and optional params', async () => { - const response = await client.tenants.templates.publish('template_id', { tenant_id: 'tenant_id', version: 'version' }); + const response = await client.tenants.templates.publish('template_id', { + tenant_id: 'tenant_id', + version: 'version', + }); }); // Mock server tests are disabled test.skip('replace: only required params', async () => { const responsePromise = client.tenants.templates.replace('template_id', { - tenant_id: 'tenant_id', - template: { content: { elements: [{}], version: 'version' } }, - }); + tenant_id: 'tenant_id', + template: { content: { elements: [{}], version: 'version' } }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -77,45 +87,58 @@ describe('resource templates', () => { // Mock server tests are disabled test.skip('replace: required and optional params', async () => { const response = await client.tenants.templates.replace('template_id', { - tenant_id: 'tenant_id', - template: { - content: { elements: [{ - channels: ['string'], - if: 'if', - loop: 'loop', - ref: 'ref', - type: 'text', - }], version: 'version' }, - channels: { foo: { - brand_id: 'brand_id', - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: { foo: 'bar' }, - providers: ['string'], - routing_method: 'all', - timeouts: { channel: 0, provider: 0 }, - } }, - providers: { foo: { - if: 'if', - metadata: { utm: { - campaign: 'campaign', - content: 'content', - medium: 'medium', - source: 'source', - term: 'term', - } }, - override: { foo: 'bar' }, - timeouts: 0, - } }, - routing: { channels: ['string'], method: 'all' }, - }, - published: true, - }); + tenant_id: 'tenant_id', + template: { + content: { + elements: [ + { + channels: ['string'], + if: 'if', + loop: 'loop', + ref: 'ref', + type: 'text', + }, + ], + version: 'version', + }, + channels: { + foo: { + brand_id: 'brand_id', + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: { foo: 'bar' }, + providers: ['string'], + routing_method: 'all', + timeouts: { channel: 0, provider: 0 }, + }, + }, + providers: { + foo: { + if: 'if', + metadata: { + utm: { + campaign: 'campaign', + content: 'content', + medium: 'medium', + source: 'source', + term: 'term', + }, + }, + override: { foo: 'bar' }, + timeouts: 0, + }, + }, + routing: { channels: ['string'], method: 'all' }, + }, + published: true, + }); }); }); diff --git a/tests/api-resources/tenants/templates/versions.test.ts b/tests/api-resources/tenants/templates/versions.test.ts index 5ac199c2..fca12b6f 100644 --- a/tests/api-resources/tenants/templates/versions.test.ts +++ b/tests/api-resources/tenants/templates/versions.test.ts @@ -2,12 +2,18 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource versions', () => { // Mock server tests are disabled test.skip('retrieve: only required params', async () => { - const responsePromise = client.tenants.templates.versions.retrieve('version', { tenant_id: 'tenant_id', template_id: 'template_id' }); + const responsePromise = client.tenants.templates.versions.retrieve('version', { + tenant_id: 'tenant_id', + template_id: 'template_id', + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -19,6 +25,9 @@ describe('resource versions', () => { // Mock server tests are disabled test.skip('retrieve: required and optional params', async () => { - const response = await client.tenants.templates.versions.retrieve('version', { tenant_id: 'tenant_id', template_id: 'template_id' }); + const response = await client.tenants.templates.versions.retrieve('version', { + tenant_id: 'tenant_id', + template_id: 'template_id', + }); }); }); diff --git a/tests/api-resources/tenants/tenants.test.ts b/tests/api-resources/tenants/tenants.test.ts index e97a1685..3ea303e1 100644 --- a/tests/api-resources/tenants/tenants.test.ts +++ b/tests/api-resources/tenants/tenants.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource tenants', () => { // Mock server tests are disabled @@ -32,18 +35,22 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.tenants.update('tenant_id', { - name: 'name', - brand_id: 'brand_id', - default_preferences: { items: [{ - status: 'OPTED_OUT', - custom_routing: ['direct_message'], - has_custom_routing: true, - id: 'id', - }] }, - parent_tenant_id: 'parent_tenant_id', - properties: { foo: 'bar' }, - user_profile: { foo: 'bar' }, - }); + name: 'name', + brand_id: 'brand_id', + default_preferences: { + items: [ + { + status: 'OPTED_OUT', + custom_routing: ['direct_message'], + has_custom_routing: true, + id: 'id', + }, + ], + }, + parent_tenant_id: 'parent_tenant_id', + properties: { foo: 'bar' }, + user_profile: { foo: 'bar' }, + }); }); // Mock server tests are disabled @@ -61,13 +68,16 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('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.tenants.list({ - cursor: 'cursor', - limit: 0, - parent_tenant_id: 'parent_tenant_id', - }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.tenants.list( + { + cursor: 'cursor', + limit: 0, + parent_tenant_id: 'parent_tenant_id', + }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -97,8 +107,12 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('listUsers: 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.tenants.listUsers('tenant_id', { cursor: 'cursor', limit: 0 }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.tenants.listUsers( + 'tenant_id', + { cursor: 'cursor', limit: 0 }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); }); diff --git a/tests/api-resources/translations.test.ts b/tests/api-resources/translations.test.ts index 2fd26d45..3f0c1df9 100644 --- a/tests/api-resources/translations.test.ts +++ b/tests/api-resources/translations.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource translations', () => { // Mock server tests are disabled diff --git a/tests/api-resources/users/preferences.test.ts b/tests/api-resources/users/preferences.test.ts index db4409c9..51252679 100644 --- a/tests/api-resources/users/preferences.test.ts +++ b/tests/api-resources/users/preferences.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource preferences', () => { // Mock server tests are disabled @@ -20,9 +23,13 @@ describe('resource preferences', () => { // Mock server tests are disabled test.skip('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.users.preferences.retrieve('user_id', { tenant_id: 'tenant_id' }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.users.preferences.retrieve( + 'user_id', + { tenant_id: 'tenant_id' }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled @@ -39,15 +46,18 @@ describe('resource preferences', () => { // Mock server tests are disabled test.skip('retrieveTopic: required and optional params', async () => { - const response = await client.users.preferences.retrieveTopic('topic_id', { user_id: 'user_id', tenant_id: 'tenant_id' }); + const response = await client.users.preferences.retrieveTopic('topic_id', { + user_id: 'user_id', + tenant_id: 'tenant_id', + }); }); // Mock server tests are disabled test.skip('updateOrCreateTopic: only required params', async () => { const responsePromise = client.users.preferences.updateOrCreateTopic('topic_id', { - user_id: 'user_id', - topic: { status: 'OPTED_IN' }, - }); + user_id: 'user_id', + topic: { status: 'OPTED_IN' }, + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -60,13 +70,13 @@ describe('resource preferences', () => { // Mock server tests are disabled test.skip('updateOrCreateTopic: required and optional params', async () => { const response = await client.users.preferences.updateOrCreateTopic('topic_id', { - user_id: 'user_id', - topic: { - status: 'OPTED_IN', - custom_routing: ['inbox', 'email'], - has_custom_routing: true, - }, - tenant_id: 'tenant_id', - }); + user_id: 'user_id', + topic: { + status: 'OPTED_IN', + custom_routing: ['inbox', 'email'], + has_custom_routing: true, + }, + tenant_id: 'tenant_id', + }); }); }); diff --git a/tests/api-resources/users/tenants.test.ts b/tests/api-resources/users/tenants.test.ts index a9a27d1d..73c46f87 100644 --- a/tests/api-resources/users/tenants.test.ts +++ b/tests/api-resources/users/tenants.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource tenants', () => { // Mock server tests are disabled @@ -20,14 +23,20 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('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.users.tenants.list('user_id', { cursor: 'cursor', limit: 0 }, { path: '/_stainless_unknown_path' })) - .rejects - .toThrow(Courier.NotFoundError); + await expect( + client.users.tenants.list( + 'user_id', + { cursor: 'cursor', limit: 0 }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); }); // Mock server tests are disabled test.skip('addMultiple: only required params', async () => { - const responsePromise = client.users.tenants.addMultiple('user_id', { tenants: [{ tenant_id: 'tenant_id' }] }); + const responsePromise = client.users.tenants.addMultiple('user_id', { + tenants: [{ tenant_id: 'tenant_id' }], + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -39,12 +48,16 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('addMultiple: required and optional params', async () => { - const response = await client.users.tenants.addMultiple('user_id', { tenants: [{ - tenant_id: 'tenant_id', - profile: { foo: 'bar' }, - type: 'user', - user_id: 'user_id', - }] }); + const response = await client.users.tenants.addMultiple('user_id', { + tenants: [ + { + tenant_id: 'tenant_id', + profile: { foo: 'bar' }, + type: 'user', + user_id: 'user_id', + }, + ], + }); }); // Mock server tests are disabled @@ -62,9 +75,9 @@ describe('resource tenants', () => { // Mock server tests are disabled test.skip('addSingle: required and optional params', async () => { const response = await client.users.tenants.addSingle('tenant_id', { - user_id: 'user_id', - profile: { foo: 'bar' }, - }); + user_id: 'user_id', + profile: { foo: 'bar' }, + }); }); // Mock server tests are disabled diff --git a/tests/api-resources/users/tokens.test.ts b/tests/api-resources/users/tokens.test.ts index cd536149..91e4a7e3 100644 --- a/tests/api-resources/users/tokens.test.ts +++ b/tests/api-resources/users/tokens.test.ts @@ -2,7 +2,10 @@ import Courier from '@trycourier/courier'; -const client = new Courier({ apiKey: 'My API Key', baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010' }); +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); describe('resource tokens', () => { // Mock server tests are disabled @@ -24,7 +27,10 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('update: only required params', async () => { - const responsePromise = client.users.tokens.update('token', { user_id: 'user_id', patch: [{ op: 'op', path: 'path' }] }); + const responsePromise = client.users.tokens.update('token', { + user_id: 'user_id', + patch: [{ op: 'op', path: 'path' }], + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -36,11 +42,16 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('update: required and optional params', async () => { - const response = await client.users.tokens.update('token', { user_id: 'user_id', patch: [{ - op: 'op', - path: 'path', - value: 'value', - }] }); + const response = await client.users.tokens.update('token', { + user_id: 'user_id', + patch: [ + { + op: 'op', + path: 'path', + value: 'value', + }, + ], + }); }); // Mock server tests are disabled @@ -86,7 +97,10 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('addSingle: only required params', async () => { - const responsePromise = client.users.tokens.addSingle('token', { user_id: 'user_id', provider_key: 'firebase-fcm' }); + const responsePromise = client.users.tokens.addSingle('token', { + user_id: 'user_id', + provider_key: 'firebase-fcm', + }); const rawResponse = await responsePromise.asResponse(); expect(rawResponse).toBeInstanceOf(Response); const response = await responsePromise; @@ -99,24 +113,24 @@ describe('resource tokens', () => { // Mock server tests are disabled test.skip('addSingle: required and optional params', async () => { const response = await client.users.tokens.addSingle('token', { - user_id: 'user_id', - provider_key: 'firebase-fcm', - device: { - ad_id: 'ad_id', - app_id: 'app_id', - device_id: 'device_id', - manufacturer: 'manufacturer', - model: 'model', - platform: 'platform', - }, - expiry_date: 'string', - properties: {}, - tracking: { - ip: 'ip', - lat: 'lat', - long: 'long', - os_version: 'os_version', - }, - }); + user_id: 'user_id', + provider_key: 'firebase-fcm', + device: { + ad_id: 'ad_id', + app_id: 'app_id', + device_id: 'device_id', + manufacturer: 'manufacturer', + model: 'model', + platform: 'platform', + }, + expiry_date: 'string', + properties: {}, + tracking: { + ip: 'ip', + lat: 'lat', + long: 'long', + os_version: 'os_version', + }, + }); }); }); diff --git a/tests/index.test.ts b/tests/index.test.ts index 7c762b31..1b3e28ed 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -21,10 +21,10 @@ describe('instantiate client', () => { describe('defaultHeaders', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultHeaders: { 'X-My-Default-Header': '2' }, - apiKey: 'My API Key', -}) + baseURL: 'http://localhost:5000/', + defaultHeaders: { 'X-My-Default-Header': '2' }, + apiKey: 'My API Key', + }); test('they are used in the request', async () => { const { req } = await client.buildRequest({ path: '/foo', method: 'post' }); @@ -49,191 +49,193 @@ describe('instantiate client', () => { expect(req.headers.has('x-my-default-header')).toBe(false); }); }); -describe('logging', () => { - const env = process.env; + describe('logging', () => { + const env = process.env; - beforeEach(() => { - process.env = { ...env }; - process.env['COURIER_LOG'] = undefined; - }); + beforeEach(() => { + process.env = { ...env }; + process.env['COURIER_LOG'] = undefined; + }); - afterEach(() => { - process.env = env; - }); + afterEach(() => { + process.env = env; + }); - const forceAPIResponseForClient = async (client: Courier) => { - await new APIPromise( - client, - Promise.resolve({ - response: new Response(), - controller: new AbortController(), - requestLogID: 'log_000000', - retryOfRequestLogID: undefined, - startTime: Date.now(), - options: { - method: 'get', - path: '/', - }, - }), - ); - }; - - test('debug logs when log level is debug', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), + const forceAPIResponseForClient = async (client: Courier) => { + await new APIPromise( + client, + Promise.resolve({ + response: new Response(), + controller: new AbortController(), + requestLogID: 'log_000000', + retryOfRequestLogID: undefined, + startTime: Date.now(), + options: { + method: 'get', + path: '/', + }, + }), + ); }; - const client = new Courier({ - logger: logger, - logLevel: 'debug', - apiKey: 'My API Key', -}); + test('debug logs when log level is debug', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - await forceAPIResponseForClient(client); - expect(debugMock).toHaveBeenCalled(); - }); + const client = new Courier({ + logger: logger, + logLevel: 'debug', + apiKey: 'My API Key', + }); - test('default logLevel is warn', async () => { - const client = new Courier({ apiKey: 'My API Key' }); - expect(client.logLevel).toBe('warn'); - }); + await forceAPIResponseForClient(client); + expect(debugMock).toHaveBeenCalled(); + }); - test('debug logs are skipped when log level is info', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; + test('default logLevel is warn', async () => { + const client = new Courier({ apiKey: 'My API Key' }); + expect(client.logLevel).toBe('warn'); + }); - const client = new Courier({ - logger: logger, - logLevel: 'info', - apiKey: 'My API Key', -}); + test('debug logs are skipped when log level is info', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - await forceAPIResponseForClient(client); - expect(debugMock).not.toHaveBeenCalled(); - }); + const client = new Courier({ + logger: logger, + logLevel: 'info', + apiKey: 'My API Key', + }); - test('debug logs happen with debug env var', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; + await forceAPIResponseForClient(client); + expect(debugMock).not.toHaveBeenCalled(); + }); - process.env['COURIER_LOG'] = 'debug'; - const client = new Courier({ logger: logger, apiKey: 'My API Key' }); - expect(client.logLevel).toBe('debug'); + test('debug logs happen with debug env var', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - await forceAPIResponseForClient(client); - expect(debugMock).toHaveBeenCalled(); - }); + process.env['COURIER_LOG'] = 'debug'; + const client = new Courier({ logger: logger, apiKey: 'My API Key' }); + expect(client.logLevel).toBe('debug'); - test('warn when env var level is invalid', async () => { - const warnMock = jest.fn(); - const logger = { - debug: jest.fn(), - info: jest.fn(), - warn: warnMock, - error: jest.fn(), - }; + await forceAPIResponseForClient(client); + expect(debugMock).toHaveBeenCalled(); + }); - process.env['COURIER_LOG'] = 'not a log level'; - const client = new Courier({ logger: logger, apiKey: 'My API Key' }); - expect(client.logLevel).toBe('warn'); - expect(warnMock).toHaveBeenCalledWith('process.env[\'COURIER_LOG\'] was set to "not a log level", expected one of ["off","error","warn","info","debug"]'); - }); + test('warn when env var level is invalid', async () => { + const warnMock = jest.fn(); + const logger = { + debug: jest.fn(), + info: jest.fn(), + warn: warnMock, + error: jest.fn(), + }; - test('client log level overrides env var', async () => { - const debugMock = jest.fn(); - const logger = { - debug: debugMock, - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; + process.env['COURIER_LOG'] = 'not a log level'; + const client = new Courier({ logger: logger, apiKey: 'My API Key' }); + expect(client.logLevel).toBe('warn'); + expect(warnMock).toHaveBeenCalledWith( + 'process.env[\'COURIER_LOG\'] was set to "not a log level", expected one of ["off","error","warn","info","debug"]', + ); + }); - process.env['COURIER_LOG'] = 'debug'; - const client = new Courier({ - logger: logger, - logLevel: 'off', - apiKey: 'My API Key', -}); + test('client log level overrides env var', async () => { + const debugMock = jest.fn(); + const logger = { + debug: debugMock, + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - await forceAPIResponseForClient(client); - expect(debugMock).not.toHaveBeenCalled(); - }); + process.env['COURIER_LOG'] = 'debug'; + const client = new Courier({ + logger: logger, + logLevel: 'off', + apiKey: 'My API Key', + }); - test('no warning logged for invalid env var level + valid client level', async () => { - const warnMock = jest.fn(); - const logger = { - debug: jest.fn(), - info: jest.fn(), - warn: warnMock, - error: jest.fn(), - }; + await forceAPIResponseForClient(client); + expect(debugMock).not.toHaveBeenCalled(); + }); - process.env['COURIER_LOG'] = 'not a log level'; - const client = new Courier({ - logger: logger, - logLevel: 'debug', - apiKey: 'My API Key', -}); - expect(client.logLevel).toBe('debug'); - expect(warnMock).not.toHaveBeenCalled(); + test('no warning logged for invalid env var level + valid client level', async () => { + const warnMock = jest.fn(); + const logger = { + debug: jest.fn(), + info: jest.fn(), + warn: warnMock, + error: jest.fn(), + }; + + process.env['COURIER_LOG'] = 'not a log level'; + const client = new Courier({ + logger: logger, + logLevel: 'debug', + apiKey: 'My API Key', + }); + expect(client.logLevel).toBe('debug'); + expect(warnMock).not.toHaveBeenCalled(); + }); }); -}); describe('defaultQuery', () => { test('with null query params given', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultQuery: { apiVersion: 'foo' }, - apiKey: 'My API Key', -}); + baseURL: 'http://localhost:5000/', + defaultQuery: { apiVersion: 'foo' }, + apiKey: 'My API Key', + }); expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo'); }); test('multiple default query params', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultQuery: { apiVersion: 'foo', hello: 'world' }, - apiKey: 'My API Key', -}); + baseURL: 'http://localhost:5000/', + defaultQuery: { apiVersion: 'foo', hello: 'world' }, + apiKey: 'My API Key', + }); expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo&hello=world'); }); test('overriding with `undefined`', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultQuery: { hello: 'world' }, - apiKey: 'My API Key', -}) + baseURL: 'http://localhost:5000/', + defaultQuery: { hello: 'world' }, + apiKey: 'My API Key', + }); expect(client.buildURL('/foo', { hello: undefined })).toEqual('http://localhost:5000/foo'); }); }); test('custom fetch', async () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - apiKey: 'My API Key', - fetch: (url) => { - return Promise.resolve( - new Response(JSON.stringify({ url, custom: true }), { - headers: { 'Content-Type': 'application/json' }, - }), - ); -}, -}); + baseURL: 'http://localhost:5000/', + apiKey: 'My API Key', + fetch: (url) => { + return Promise.resolve( + new Response(JSON.stringify({ url, custom: true }), { + headers: { 'Content-Type': 'application/json' }, + }), + ); + }, + }); const response = await client.get('/foo'); expect(response).toEqual({ url: 'http://localhost:5000/foo', custom: true }); @@ -242,37 +244,35 @@ describe('logging', () => { test('explicit global fetch', async () => { // make sure the global fetch type is assignable to our Fetch type const client = new Courier({ - baseURL: 'http://localhost:5000/', - apiKey: 'My API Key', - fetch: defaultFetch, -}); + baseURL: 'http://localhost:5000/', + apiKey: 'My API Key', + fetch: defaultFetch, + }); }); test('custom signal', async () => { const client = new Courier({ - baseURL: process.env["TEST_API_BASE_URL"] ?? 'http://127.0.0.1:4010', - apiKey: 'My API Key', - fetch: (...args) => { - return new Promise((resolve, reject) => - setTimeout( - () => - defaultFetch(...args) - .then(resolve) - .catch(reject), - 300, - ), - ); -}, -}); + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', + apiKey: 'My API Key', + fetch: (...args) => { + return new Promise((resolve, reject) => + setTimeout( + () => + defaultFetch(...args) + .then(resolve) + .catch(reject), + 300, + ), + ); + }, + }); const controller = new AbortController(); setTimeout(() => controller.abort(), 200); const spy = jest.spyOn(client, 'request'); - await expect(client.get('/foo', { signal: controller.signal })).rejects.toThrowError( - APIUserAbortError, - ); + await expect(client.get('/foo', { signal: controller.signal })).rejects.toThrowError(APIUserAbortError); expect(spy).toHaveBeenCalledTimes(1); }); @@ -284,10 +284,10 @@ describe('logging', () => { }; const client = new Courier({ - baseURL: 'http://localhost:5000/', - apiKey: 'My API Key', - fetch: testFetch, -}); + baseURL: 'http://localhost:5000/', + apiKey: 'My API Key', + fetch: testFetch, + }); await client.patch('/foo'); expect(capturedRequest?.method).toEqual('PATCH'); @@ -322,29 +322,35 @@ describe('logging', () => { test('empty env variable', () => { process.env['COURIER_BASE_URL'] = ''; // empty const client = new Courier({ apiKey: 'My API Key' }); - expect(client.baseURL).toEqual('https://api.courier.com') + expect(client.baseURL).toEqual('https://api.courier.com'); }); test('blank env variable', () => { process.env['COURIER_BASE_URL'] = ' '; // blank const client = new Courier({ apiKey: 'My API Key' }); - expect(client.baseURL).toEqual('https://api.courier.com') + expect(client.baseURL).toEqual('https://api.courier.com'); }); test('in request options', () => { const client = new Courier({ apiKey: 'My API Key' }); - expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual('http://localhost:5000/option/foo'); + expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual( + 'http://localhost:5000/option/foo', + ); }); test('in request options overridden by client options', () => { const client = new Courier({ apiKey: 'My API Key', baseURL: 'http://localhost:5000/client' }); - expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual('http://localhost:5000/client/foo'); + expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual( + 'http://localhost:5000/client/foo', + ); }); test('in request options overridden by env variable', () => { process.env['COURIER_BASE_URL'] = 'http://localhost:5000/env'; const client = new Courier({ apiKey: 'My API Key' }); - expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual('http://localhost:5000/env/foo'); + expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual( + 'http://localhost:5000/env/foo', + ); }); }); @@ -360,10 +366,10 @@ describe('logging', () => { describe('withOptions', () => { test('creates a new client with overridden options', async () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - maxRetries: 3, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + maxRetries: 3, + apiKey: 'My API Key', + }); const newClient = client.withOptions({ maxRetries: 5, @@ -385,11 +391,11 @@ describe('logging', () => { test('inherits options from the parent client', async () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - defaultHeaders: { 'X-Test-Header': 'test-value' }, - defaultQuery: { 'test-param': 'test-value' }, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + defaultHeaders: { 'X-Test-Header': 'test-value' }, + defaultQuery: { 'test-param': 'test-value' }, + apiKey: 'My API Key', + }); const newClient = client.withOptions({ baseURL: 'http://localhost:5001/', @@ -404,10 +410,10 @@ describe('logging', () => { test('respects runtime property changes when creating new client', () => { const client = new Courier({ - baseURL: 'http://localhost:5000/', - timeout: 1000, - apiKey: 'My API Key', - }); + baseURL: 'http://localhost:5000/', + timeout: 1000, + apiKey: 'My API Key', + }); // Modify the client properties directly after creation client.baseURL = 'http://localhost:6000/'; @@ -453,13 +459,18 @@ describe('request building', () => { describe('custom headers', () => { test('handles undefined', async () => { - const { req } = await client.buildRequest({ path: '/foo', method: 'post', body: { value: 'hello' }, headers: { 'X-Foo': 'baz', 'x-foo': 'bar', 'x-Foo': undefined, 'x-baz': 'bam', 'X-Baz': null } }); + const { req } = await client.buildRequest({ + path: '/foo', + method: 'post', + body: { value: 'hello' }, + headers: { 'X-Foo': 'baz', 'x-foo': 'bar', 'x-Foo': undefined, 'x-baz': 'bam', 'X-Baz': null }, + }); expect(req.headers.get('x-foo')).toEqual('bar'); expect(req.headers.get('x-Foo')).toEqual('bar'); expect(req.headers.get('X-Foo')).toEqual('bar'); expect(req.headers.get('x-baz')).toEqual(null); }); - }) + }); }); describe('default encoder', () => { @@ -536,37 +547,40 @@ describe('default encoder', () => { describe('retries', () => { test('retry on timeout', async () => { let count = 0; - const testFetch = async (url: string | URL | Request, { signal }: RequestInit = {}): Promise => { - if (count++ === 0) { - return new Promise((resolve, reject) => - signal?.addEventListener('abort', () => reject(new Error('timed out'))), - ); - } - return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); - }; - - const client = new Courier({ - apiKey: 'My API Key', - timeout: 10, - fetch: testFetch, - }); + const testFetch = async ( + url: string | URL | Request, + { signal }: RequestInit = {}, + ): Promise => { + if (count++ === 0) { + return new Promise( + (resolve, reject) => signal?.addEventListener('abort', () => reject(new Error('timed out'))), + ); + } + return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); + }; - expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 }); - expect(count).toEqual(2); - expect( - await client - .request({ path: '/foo', method: 'get' }) - .asResponse() - .then((r) => r.text()), - ).toEqual(JSON.stringify({ a: 1 })); - expect(count).toEqual(3); + const client = new Courier({ + apiKey: 'My API Key', + timeout: 10, + fetch: testFetch, }); + expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 }); + expect(count).toEqual(2); + expect( + await client + .request({ path: '/foo', method: 'get' }) + .asResponse() + .then((r) => r.text()), + ).toEqual(JSON.stringify({ a: 1 })); + expect(count).toEqual(3); + }); + test('retry count header', async () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++ + count++; if (count <= 2) { return new Response(undefined, { status: 429, @@ -580,10 +594,10 @@ describe('retries', () => { }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + }); expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 }); @@ -595,7 +609,7 @@ describe('retries', () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++ + count++; if (count <= 2) { return new Response(undefined, { status: 429, @@ -608,10 +622,10 @@ describe('retries', () => { return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + }); expect( await client.request({ @@ -628,7 +642,7 @@ describe('retries', () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++ + count++; if (count <= 2) { return new Response(undefined, { status: 429, @@ -641,11 +655,11 @@ describe('retries', () => { return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - defaultHeaders: { 'X-Stainless-Retry-Count': null }, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + defaultHeaders: { 'X-Stainless-Retry-Count': null }, + }); expect( await client.request({ @@ -661,7 +675,7 @@ describe('retries', () => { let count = 0; let capturedRequest: RequestInit | undefined; const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise => { - count++ + count++; if (count <= 2) { return new Response(undefined, { status: 429, @@ -674,10 +688,10 @@ describe('retries', () => { return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } }); }; const client = new Courier({ - apiKey: 'My API Key', - fetch: testFetch, - maxRetries: 4, - }); + apiKey: 'My API Key', + fetch: testFetch, + maxRetries: 4, + }); expect( await client.request({ @@ -692,7 +706,10 @@ describe('retries', () => { test('retry on 429 with retry-after', async () => { let count = 0; - const testFetch = async (url: string | URL | Request, { signal }: RequestInit = {}): Promise => { + const testFetch = async ( + url: string | URL | Request, + { signal }: RequestInit = {}, + ): Promise => { if (count++ === 0) { return new Response(undefined, { status: 429, @@ -719,7 +736,10 @@ describe('retries', () => { test('retry on 429 with retry-after-ms', async () => { let count = 0; - const testFetch = async (url: string | URL | Request, { signal }: RequestInit = {}): Promise => { + const testFetch = async ( + url: string | URL | Request, + { signal }: RequestInit = {}, + ): Promise => { if (count++ === 0) { return new Response(undefined, { status: 429, diff --git a/tests/qs/utils.test.ts b/tests/qs/utils.test.ts index 0a91b186..5f290114 100644 --- a/tests/qs/utils.test.ts +++ b/tests/qs/utils.test.ts @@ -66,7 +66,7 @@ describe('merge()', function () { // st.equal(getCount, 1); expect(setCount).toEqual(0); expect(getCount).toEqual(1); - observed[0] = observed[0]; + observed[0] = observed[0]; // st.equal(setCount, 1); // st.equal(getCount, 2); expect(setCount).toEqual(1); diff --git a/tests/stringifyQuery.test.ts b/tests/stringifyQuery.test.ts index 43a9c77f..315ab571 100644 --- a/tests/stringifyQuery.test.ts +++ b/tests/stringifyQuery.test.ts @@ -2,18 +2,20 @@ import { stringifyQuery } from '@trycourier/courier/internal/utils/query'; -describe(stringifyQuery, () => { for (const [input, expected] of [ - [{ a: '1', b: 2, c: true }, 'a=1&b=2&c=true'], - [{ a: null, b: false, c: undefined }, 'a=&b=false'], - [{ 'a/b': 1.28341 }, `${encodeURIComponent('a/b')}=1.28341`], - [ - { 'a/b': 'c/d', 'e=f': 'g&h' }, - `${encodeURIComponent('a/b')}=${encodeURIComponent('c/d')}&${encodeURIComponent( - 'e=f', - )}=${encodeURIComponent('g&h')}`, - ], -] as const) { - it(`${JSON.stringify(input)} -> ${expected}`, () => { - expect(stringifyQuery(input)).toEqual(expected); - }); -} }) +describe(stringifyQuery, () => { + for (const [input, expected] of [ + [{ a: '1', b: 2, c: true }, 'a=1&b=2&c=true'], + [{ a: null, b: false, c: undefined }, 'a=&b=false'], + [{ 'a/b': 1.28341 }, `${encodeURIComponent('a/b')}=1.28341`], + [ + { 'a/b': 'c/d', 'e=f': 'g&h' }, + `${encodeURIComponent('a/b')}=${encodeURIComponent('c/d')}&${encodeURIComponent( + 'e=f', + )}=${encodeURIComponent('g&h')}`, + ], + ] as const) { + it(`${JSON.stringify(input)} -> ${expected}`, () => { + expect(stringifyQuery(input)).toEqual(expected); + }); + } +}); diff --git a/yarn.lock b/yarn.lock index 18e7cbdc..f6eae3cd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -709,6 +709,11 @@ "@nodelib/fs.scandir" "2.1.5" fastq "^1.6.0" +"@pkgr/core@^0.2.4": + version "0.2.4" + resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.2.4.tgz#d897170a2b0ba51f78a099edccd968f7b103387c" + integrity sha512-ROFF39F6ZrnzSUEmQQZUar0Jt4xVoP9WnDRdWwF4NNcXs3xBTLgBUDoOwW141y1jP+S8nahIbdxbFC7IShw9Iw== + "@sinclair/typebox@^0.27.8": version "0.27.8" resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.27.8.tgz#6667fac16c436b5434a387a34dedb013198f6e6e" @@ -1510,6 +1515,14 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== +eslint-plugin-prettier@^5.4.1: + version "5.4.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.4.1.tgz#99b55d7dd70047886b2222fdd853665f180b36af" + integrity sha512-9dF+KuU/Ilkq27A8idRP7N2DH8iUR6qXcjF3FR2wETY21PZdBrIjwCau8oboyGj9b7etWmTGEeM8e7oOed6ZWg== + dependencies: + prettier-linter-helpers "^1.0.0" + synckit "^0.11.7" + eslint-plugin-unused-imports@^4.1.4: version "4.1.4" resolved "https://registry.yarnpkg.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.1.4.tgz#62ddc7446ccbf9aa7b6f1f0b00a980423cda2738" @@ -1661,6 +1674,11 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== +fast-diff@^1.1.2: + version "1.3.0" + resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0" + integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== + fast-glob@^3.3.2: version "3.3.2" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" @@ -2823,6 +2841,13 @@ prelude-ls@^1.2.1: resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== +prettier-linter-helpers@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b" + integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w== + dependencies: + fast-diff "^1.1.2" + prettier@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.1.1.tgz#6ba9f23165d690b6cbdaa88cb0807278f7019848" @@ -3119,6 +3144,13 @@ supports-preserve-symlinks-flag@^1.0.0: resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== +synckit@^0.11.7: + version "0.11.8" + resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.11.8.tgz#b2aaae998a4ef47ded60773ad06e7cb821f55457" + integrity sha512-+XZ+r1XGIJGeQk3VvXhT6xx/VpbHsRzsTkGgF6E5RX9TTXD0118l87puaEBZ566FhqblC6U0d4XnubznJDm30A== + dependencies: + "@pkgr/core" "^0.2.4" + test-exclude@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" From e7a078f8e44790bf9332c5c06891d3fa9b148ee7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 28 Apr 2026 02:10:13 +0000 Subject: [PATCH 04/12] feat: support setting headers via env --- src/client.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/client.ts b/src/client.ts index a55a0521..28051714 100644 --- a/src/client.ts +++ b/src/client.ts @@ -344,6 +344,18 @@ export class Courier { this.fetch = options.fetch ?? Shims.getDefaultFetch(); this.#encoder = Opts.FallbackEncoder; + const customHeadersEnv = readEnv('COURIER_CUSTOM_HEADERS'); + if (customHeadersEnv) { + const parsed: Record = {}; + for (const line of customHeadersEnv.split('\n')) { + const colon = line.indexOf(':'); + if (colon >= 0) { + parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim(); + } + } + options.defaultHeaders = { ...parsed, ...options.defaultHeaders }; + } + this._options = options; this.apiKey = apiKey; From 94cc1583b4dcfe832929c142efaf5bf8b371b42f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 29 Apr 2026 02:21:20 +0000 Subject: [PATCH 05/12] chore(format): run eslint and prettier separately --- .github/workflows/release-doctor.yml | 1 - eslint.config.mjs | 3 --- package.json | 1 - scripts/fast-format | 9 +++----- scripts/format | 3 +-- scripts/lint | 3 +++ src/internal/types.ts | 14 ++++++------ yarn.lock | 32 ---------------------------- 8 files changed, 13 insertions(+), 53 deletions(-) diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 8fe0b398..87ce9ad5 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -19,4 +19,3 @@ jobs: bash ./bin/check-release-environment env: NPM_TOKEN: ${{ secrets.COURIER_NPM_TOKEN || secrets.NPM_TOKEN }} - diff --git a/eslint.config.mjs b/eslint.config.mjs index 7850bf49..07b28b78 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,7 +1,6 @@ // @ts-check import tseslint from 'typescript-eslint'; import unusedImports from 'eslint-plugin-unused-imports'; -import prettier from 'eslint-plugin-prettier'; export default tseslint.config( { @@ -14,11 +13,9 @@ export default tseslint.config( plugins: { '@typescript-eslint': tseslint.plugin, 'unused-imports': unusedImports, - prettier, }, rules: { 'no-unused-vars': 'off', - 'prettier/prettier': 'error', 'unused-imports/no-unused-imports': 'error', 'no-restricted-imports': [ 'error', diff --git a/package.json b/package.json index 8aeaadf7..7d86550e 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,6 @@ "@typescript-eslint/eslint-plugin": "8.31.1", "@typescript-eslint/parser": "8.31.1", "eslint": "^9.39.1", - "eslint-plugin-prettier": "^5.4.1", "eslint-plugin-unused-imports": "^4.1.4", "iconv-lite": "^0.6.3", "jest": "^29.4.0", diff --git a/scripts/fast-format b/scripts/fast-format index 53721ac0..f1873aef 100755 --- a/scripts/fast-format +++ b/scripts/fast-format @@ -31,10 +31,7 @@ if ! [ -z "$ESLINT_FILES" ]; then fi echo "==> Running prettier --write" -# format things eslint didn't -PRETTIER_FILES="$(grep '\.\(js\|json\)$' "$FILE_LIST" || true)" -if ! [ -z "$PRETTIER_FILES" ]; then - echo "$PRETTIER_FILES" | xargs ./node_modules/.bin/prettier \ - --write --cache --cache-strategy metadata --no-error-on-unmatched-pattern \ - '!**/dist' '!**/*.ts' '!**/*.mts' '!**/*.cts' '!**/*.js' '!**/*.mjs' '!**/*.cjs' +if ! [ -z "$FILE_LIST" ]; then + cat "$FILE_LIST" | xargs ./node_modules/.bin/prettier \ + --write --cache --cache-strategy metadata --no-error-on-unmatched-pattern --ignore-unknown fi diff --git a/scripts/format b/scripts/format index 7a756401..b1b2c17a 100755 --- a/scripts/format +++ b/scripts/format @@ -8,5 +8,4 @@ echo "==> Running eslint --fix" ./node_modules/.bin/eslint --fix . echo "==> Running prettier --write" -# format things eslint didn't -./node_modules/.bin/prettier --write --cache --cache-strategy metadata . '!**/dist' '!**/*.ts' '!**/*.mts' '!**/*.cts' '!**/*.js' '!**/*.mjs' '!**/*.cjs' +./node_modules/.bin/prettier --write --cache --cache-strategy metadata . diff --git a/scripts/lint b/scripts/lint index 3ffb78a6..1f532548 100755 --- a/scripts/lint +++ b/scripts/lint @@ -4,6 +4,9 @@ set -e cd "$(dirname "$0")/.." +echo "==> Running prettier --check" +./node_modules/.bin/prettier --check . + echo "==> Running eslint" ./node_modules/.bin/eslint . diff --git a/src/internal/types.ts b/src/internal/types.ts index b668dfc0..a050513a 100644 --- a/src/internal/types.ts +++ b/src/internal/types.ts @@ -40,7 +40,6 @@ type OverloadedParameters = : T extends (...args: infer A) => unknown ? A : never; -/* eslint-disable */ /** * These imports attempt to get types from a parent package's dependencies. * Unresolved bare specifiers can trigger [automatic type acquisition][1] in some projects, which @@ -63,19 +62,18 @@ type OverloadedParameters = * * [1]: https://www.typescriptlang.org/tsconfig/#typeAcquisition */ -/** @ts-ignore For users with \@types/node */ +/** @ts-ignore For users with \@types/node */ /* prettier-ignore */ type UndiciTypesRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with undici */ +/** @ts-ignore For users with undici */ /* prettier-ignore */ type UndiciRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with \@types/bun */ +/** @ts-ignore For users with \@types/bun */ /* prettier-ignore */ type BunRequestInit = globalThis.FetchRequestInit; -/** @ts-ignore For users with node-fetch@2 */ +/** @ts-ignore For users with node-fetch@2 */ /* prettier-ignore */ type NodeFetch2RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users with node-fetch@3, doesn't need file extension because types are at ./@types/index.d.ts */ +/** @ts-ignore For users with node-fetch@3, doesn't need file extension because types are at ./@types/index.d.ts */ /* prettier-ignore */ type NodeFetch3RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; -/** @ts-ignore For users who use Deno */ +/** @ts-ignore For users who use Deno */ /* prettier-ignore */ type FetchRequestInit = NonNullable[1]>; -/* eslint-enable */ type RequestInits = | NotAny diff --git a/yarn.lock b/yarn.lock index f6eae3cd..18e7cbdc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -709,11 +709,6 @@ "@nodelib/fs.scandir" "2.1.5" fastq "^1.6.0" -"@pkgr/core@^0.2.4": - version "0.2.4" - resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.2.4.tgz#d897170a2b0ba51f78a099edccd968f7b103387c" - integrity sha512-ROFF39F6ZrnzSUEmQQZUar0Jt4xVoP9WnDRdWwF4NNcXs3xBTLgBUDoOwW141y1jP+S8nahIbdxbFC7IShw9Iw== - "@sinclair/typebox@^0.27.8": version "0.27.8" resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.27.8.tgz#6667fac16c436b5434a387a34dedb013198f6e6e" @@ -1515,14 +1510,6 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== -eslint-plugin-prettier@^5.4.1: - version "5.4.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.4.1.tgz#99b55d7dd70047886b2222fdd853665f180b36af" - integrity sha512-9dF+KuU/Ilkq27A8idRP7N2DH8iUR6qXcjF3FR2wETY21PZdBrIjwCau8oboyGj9b7etWmTGEeM8e7oOed6ZWg== - dependencies: - prettier-linter-helpers "^1.0.0" - synckit "^0.11.7" - eslint-plugin-unused-imports@^4.1.4: version "4.1.4" resolved "https://registry.yarnpkg.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.1.4.tgz#62ddc7446ccbf9aa7b6f1f0b00a980423cda2738" @@ -1674,11 +1661,6 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== -fast-diff@^1.1.2: - version "1.3.0" - resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0" - integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== - fast-glob@^3.3.2: version "3.3.2" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" @@ -2841,13 +2823,6 @@ prelude-ls@^1.2.1: resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== -prettier-linter-helpers@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b" - integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w== - dependencies: - fast-diff "^1.1.2" - prettier@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.1.1.tgz#6ba9f23165d690b6cbdaa88cb0807278f7019848" @@ -3144,13 +3119,6 @@ supports-preserve-symlinks-flag@^1.0.0: resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== -synckit@^0.11.7: - version "0.11.8" - resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.11.8.tgz#b2aaae998a4ef47ded60773ad06e7cb821f55457" - integrity sha512-+XZ+r1XGIJGeQk3VvXhT6xx/VpbHsRzsTkGgF6E5RX9TTXD0118l87puaEBZ566FhqblC6U0d4XnubznJDm30A== - dependencies: - "@pkgr/core" "^0.2.4" - test-exclude@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" From 11c441f4002ca137670e4e7bed3811d8c293f689 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 1 May 2026 02:19:05 +0000 Subject: [PATCH 06/12] codegen metadata --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index effa635e..71498595 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier%2Fcourier-3f78581b4e078a1f620d9f587f18d77bcde6d20f56b0e4ae798648f4236494fb.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-3f78581b4e078a1f620d9f587f18d77bcde6d20f56b0e4ae798648f4236494fb.yml openapi_spec_hash: 6bd33e0396d85e11bb46f0d549af93a3 config_hash: afcc4f6f8c33ca3f338589e32e086f56 From 90a80f71f05ae746c6e5cdb8b6b04a9fa02a6110 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 1 May 2026 02:23:53 +0000 Subject: [PATCH 07/12] codegen metadata --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 71498595..a59050a6 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-3f78581b4e078a1f620d9f587f18d77bcde6d20f56b0e4ae798648f4236494fb.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-2fca943954773292b6ca82dcb420c6500d118d2fbbe1cd4718afcb804f6c818c.yml openapi_spec_hash: 6bd33e0396d85e11bb46f0d549af93a3 config_hash: afcc4f6f8c33ca3f338589e32e086f56 From ce91d48d8a4be2500a03433a03bafd8142d78e08 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 8 May 2026 02:14:42 +0000 Subject: [PATCH 08/12] chore: redact api-key headers in debug logs --- src/internal/utils/log.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/internal/utils/log.ts b/src/internal/utils/log.ts index dbbb7b33..4ddc254a 100644 --- a/src/internal/utils/log.ts +++ b/src/internal/utils/log.ts @@ -107,6 +107,8 @@ export const formatRequestDetails = (details: { name, ( name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'api-key' || + name.toLowerCase() === 'x-api-key' || name.toLowerCase() === 'cookie' || name.toLowerCase() === 'set-cookie' ) ? From c659b6ccc44ba64d7d04a20cd96342519060aea7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 13 May 2026 02:06:20 +0000 Subject: [PATCH 09/12] ci: pin GitHub Actions to commit SHAs Pin all GitHub Actions referenced in generated workflows (both first-party `actions/*` and third-party) to immutable commit SHAs. Updating pinned actions is now a deliberate codegen-side bump rather than implicit on every workflow run. --- .github/workflows/ci.yml | 14 +++++++------- .github/workflows/publish-npm.yml | 4 ++-- .github/workflows/release-doctor.yml | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aa6f6adf..83a317ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,10 +21,10 @@ jobs: runs-on: ${{ github.repository == 'stainless-sdks/courier-typescript' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata') steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' @@ -43,10 +43,10 @@ jobs: contents: read id-token: write steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' @@ -61,7 +61,7 @@ jobs: github.repository == 'stainless-sdks/courier-typescript' && !startsWith(github.ref, 'refs/heads/stl/') id: github-oidc - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: core.setOutput('github_token', await core.getIDToken()); @@ -80,10 +80,10 @@ jobs: runs-on: ${{ github.repository == 'stainless-sdks/courier-typescript' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 0bd63d73..d4cee411 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -14,10 +14,10 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up Node - uses: actions/setup-node@v3 + uses: actions/setup-node@3235b876344d2a9aa001b8d1453c930bba69e610 # v3.9.1 with: node-version: '20' diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 87ce9ad5..ad46a4bd 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -12,7 +12,7 @@ jobs: if: github.repository == 'trycourier/courier-node' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Check release environment run: | From 297d6eb106b494cb56f3722a124a096736f1f83a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 14 May 2026 23:55:06 +0000 Subject: [PATCH 10/12] feat(api): add journeys CRUD/publish/versioning, templates sub-resource, types --- .stats.yml | 8 +- api.md | 59 +- src/client.ts | 84 +- src/resources/index.ts | 35 +- src/resources/journeys.ts | 173 +--- src/resources/journeys/index.ts | 54 + src/resources/journeys/journeys.ts | 939 ++++++++++++++++++ src/resources/journeys/templates.ts | 310 ++++++ tests/api-resources/journeys.test.ts | 42 - tests/api-resources/journeys/journeys.test.ts | 182 ++++ .../api-resources/journeys/templates.test.ts | 202 ++++ 11 files changed, 1854 insertions(+), 234 deletions(-) create mode 100644 src/resources/journeys/index.ts create mode 100644 src/resources/journeys/journeys.ts create mode 100644 src/resources/journeys/templates.ts delete mode 100644 tests/api-resources/journeys.test.ts create mode 100644 tests/api-resources/journeys/journeys.test.ts create mode 100644 tests/api-resources/journeys/templates.test.ts diff --git a/.stats.yml b/.stats.yml index a59050a6..eb39c6b7 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-2fca943954773292b6ca82dcb420c6500d118d2fbbe1cd4718afcb804f6c818c.yml -openapi_spec_hash: 6bd33e0396d85e11bb46f0d549af93a3 -config_hash: afcc4f6f8c33ca3f338589e32e086f56 +configured_endpoints: 116 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-389afcb57163d4391f72d240c33a82d0522b958400603f137981480cda54558a.yml +openapi_spec_hash: c861d7fcd81ad5bfdaf8da0f5a84f497 +config_hash: e40fec72c1ab30fded57c222ace689b5 diff --git a/api.md b/api.md index 3d9ffa24..a9343982 100644 --- a/api.md +++ b/api.md @@ -178,15 +178,62 @@ Methods: Types: -- Journey -- JourneysInvokeRequest -- JourneysInvokeResponse -- JourneysListResponse +- CreateJourneyRequest +- Journey +- JourneyAINode +- JourneyAPIInvokeTriggerNode +- JourneyConditionAtom +- JourneyConditionGroup +- JourneyConditionNestedGroup +- JourneyConditionsField +- JourneyDelayDurationNode +- JourneyDelayUntilNode +- JourneyExitNode +- JourneyFetchGetDeleteNode +- JourneyFetchPostPutNode +- JourneyMergeStrategy +- JourneyNode +- JourneyPublishRequest +- JourneyResponse +- JourneySegmentTriggerNode +- JourneySendNode +- JourneyState +- JourneyTemplateCreateRequest +- JourneyTemplateGetResponse +- JourneyTemplateListResponse +- JourneyTemplatePublishRequest +- JourneyTemplateReplaceRequest +- JourneyTemplateSummary +- JourneyThrottleDynamicNode +- JourneyThrottleStaticNode +- JourneyVersionItem +- JourneyVersionsListResponse +- JourneysInvokeRequest +- JourneysInvokeResponse +- JourneysListResponse Methods: -- client.journeys.list({ ...params }) -> JourneysListResponse -- client.journeys.invoke(templateID, { ...params }) -> JourneysInvokeResponse +- client.journeys.create({ ...params }) -> JourneyResponse +- client.journeys.retrieve(templateID, { ...params }) -> JourneyResponse +- client.journeys.list({ ...params }) -> JourneysListResponse +- client.journeys.archive(templateID) -> void +- client.journeys.invoke(templateID, { ...params }) -> JourneysInvokeResponse +- client.journeys.listVersions(templateID) -> JourneyVersionsListResponse +- client.journeys.publish(templateID, { ...params }) -> JourneyResponse +- client.journeys.replace(templateID, { ...params }) -> JourneyResponse + +## Templates + +Methods: + +- client.journeys.templates.create(templateID, { ...params }) -> JourneyTemplateGetResponse +- client.journeys.templates.retrieve(notificationID, { ...params }) -> JourneyTemplateGetResponse +- client.journeys.templates.list(templateID, { ...params }) -> JourneyTemplateListResponse +- client.journeys.templates.archive(notificationID, { ...params }) -> void +- client.journeys.templates.listVersions(notificationID, { ...params }) -> NotificationTemplateVersionListResponse +- client.journeys.templates.publish(notificationID, { ...params }) -> void +- client.journeys.templates.replace(notificationID, { ...params }) -> JourneyTemplateGetResponse # Brands diff --git a/src/client.ts b/src/client.ts index 28051714..87734246 100644 --- a/src/client.ts +++ b/src/client.ts @@ -67,15 +67,6 @@ import { InboundBulkMessageUser, } from './resources/bulk'; import { Inbound, InboundTrackEventParams, InboundTrackEventResponse } from './resources/inbound'; -import { - Journey, - JourneyInvokeParams, - JourneyListParams, - Journeys, - JourneysInvokeRequest, - JourneysInvokeResponse, - JourneysListResponse, -} from './resources/journeys'; import { MessageContentResponse, MessageDetails, @@ -114,6 +105,48 @@ import { AutomationTemplateListResponse, Automations, } from './resources/automations/automations'; +import { + CreateJourneyRequest, + Journey, + JourneyAINode, + JourneyAPIInvokeTriggerNode, + JourneyConditionAtom, + JourneyConditionGroup, + JourneyConditionNestedGroup, + JourneyConditionsField, + JourneyCreateParams, + JourneyDelayDurationNode, + JourneyDelayUntilNode, + JourneyExitNode, + JourneyFetchGetDeleteNode, + JourneyFetchPostPutNode, + JourneyInvokeParams, + JourneyListParams, + JourneyMergeStrategy, + JourneyNode, + JourneyPublishParams, + JourneyPublishRequest, + JourneyReplaceParams, + JourneyResponse, + JourneyRetrieveParams, + JourneySegmentTriggerNode, + JourneySendNode, + JourneyState, + JourneyTemplateCreateRequest, + JourneyTemplateGetResponse, + JourneyTemplateListResponse, + JourneyTemplatePublishRequest, + JourneyTemplateReplaceRequest, + JourneyTemplateSummary, + JourneyThrottleDynamicNode, + JourneyThrottleStaticNode, + JourneyVersionItem, + JourneyVersionsListResponse, + Journeys, + JourneysInvokeRequest, + JourneysInvokeResponse, + JourneysListResponse, +} from './resources/journeys/journeys'; import { ListListParams, ListListResponse, @@ -997,12 +1030,45 @@ export declare namespace Courier { export { Journeys as Journeys, + type CreateJourneyRequest as CreateJourneyRequest, type Journey as Journey, + type JourneyAINode as JourneyAINode, + type JourneyAPIInvokeTriggerNode as JourneyAPIInvokeTriggerNode, + type JourneyConditionAtom as JourneyConditionAtom, + type JourneyConditionGroup as JourneyConditionGroup, + type JourneyConditionNestedGroup as JourneyConditionNestedGroup, + type JourneyConditionsField as JourneyConditionsField, + type JourneyDelayDurationNode as JourneyDelayDurationNode, + type JourneyDelayUntilNode as JourneyDelayUntilNode, + type JourneyExitNode as JourneyExitNode, + type JourneyFetchGetDeleteNode as JourneyFetchGetDeleteNode, + type JourneyFetchPostPutNode as JourneyFetchPostPutNode, + type JourneyMergeStrategy as JourneyMergeStrategy, + type JourneyNode as JourneyNode, + type JourneyPublishRequest as JourneyPublishRequest, + type JourneyResponse as JourneyResponse, + type JourneySegmentTriggerNode as JourneySegmentTriggerNode, + type JourneySendNode as JourneySendNode, + type JourneyState as JourneyState, + type JourneyTemplateCreateRequest as JourneyTemplateCreateRequest, + type JourneyTemplateGetResponse as JourneyTemplateGetResponse, + type JourneyTemplateListResponse as JourneyTemplateListResponse, + type JourneyTemplatePublishRequest as JourneyTemplatePublishRequest, + type JourneyTemplateReplaceRequest as JourneyTemplateReplaceRequest, + type JourneyTemplateSummary as JourneyTemplateSummary, + type JourneyThrottleDynamicNode as JourneyThrottleDynamicNode, + type JourneyThrottleStaticNode as JourneyThrottleStaticNode, + type JourneyVersionItem as JourneyVersionItem, + type JourneyVersionsListResponse as JourneyVersionsListResponse, type JourneysInvokeRequest as JourneysInvokeRequest, type JourneysInvokeResponse as JourneysInvokeResponse, type JourneysListResponse as JourneysListResponse, + type JourneyCreateParams as JourneyCreateParams, + type JourneyRetrieveParams as JourneyRetrieveParams, type JourneyListParams as JourneyListParams, type JourneyInvokeParams as JourneyInvokeParams, + type JourneyPublishParams as JourneyPublishParams, + type JourneyReplaceParams as JourneyReplaceParams, }; export { diff --git a/src/resources/index.ts b/src/resources/index.ts index 39e3d90d..66263e95 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -60,13 +60,46 @@ export { export { Inbound, type InboundTrackEventResponse, type InboundTrackEventParams } from './inbound'; export { Journeys, + type CreateJourneyRequest, type Journey, + type JourneyAINode, + type JourneyAPIInvokeTriggerNode, + type JourneyConditionAtom, + type JourneyConditionGroup, + type JourneyConditionNestedGroup, + type JourneyConditionsField, + type JourneyDelayDurationNode, + type JourneyDelayUntilNode, + type JourneyExitNode, + type JourneyFetchGetDeleteNode, + type JourneyFetchPostPutNode, + type JourneyMergeStrategy, + type JourneyNode, + type JourneyPublishRequest, + type JourneyResponse, + type JourneySegmentTriggerNode, + type JourneySendNode, + type JourneyState, + type JourneyTemplateCreateRequest, + type JourneyTemplateGetResponse, + type JourneyTemplateListResponse, + type JourneyTemplatePublishRequest, + type JourneyTemplateReplaceRequest, + type JourneyTemplateSummary, + type JourneyThrottleDynamicNode, + type JourneyThrottleStaticNode, + type JourneyVersionItem, + type JourneyVersionsListResponse, type JourneysInvokeRequest, type JourneysInvokeResponse, type JourneysListResponse, + type JourneyCreateParams, + type JourneyRetrieveParams, type JourneyListParams, type JourneyInvokeParams, -} from './journeys'; + type JourneyPublishParams, + type JourneyReplaceParams, +} from './journeys/journeys'; export { Lists, type PutSubscriptionsRecipient, diff --git a/src/resources/journeys.ts b/src/resources/journeys.ts index a7157480..24b7a0b2 100644 --- a/src/resources/journeys.ts +++ b/src/resources/journeys.ts @@ -1,174 +1,3 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { APIResource } from '../core/resource'; -import { APIPromise } from '../core/api-promise'; -import { RequestOptions } from '../internal/request-options'; -import { path } from '../internal/utils/path'; - -export class Journeys extends APIResource { - /** - * Get the list of journeys. - * - * @example - * ```ts - * const journeysListResponse = await client.journeys.list(); - * ``` - */ - list( - query: JourneyListParams | null | undefined = {}, - options?: RequestOptions, - ): APIPromise { - return this._client.get('/journeys', { query, ...options }); - } - - /** - * Invoke a journey run from a journey template. - * - * @example - * ```ts - * const journeysInvokeResponse = await client.journeys.invoke( - * 'templateId', - * { - * data: { order_id: 'order-456', amount: 99.99 }, - * user_id: 'user-123', - * }, - * ); - * ``` - */ - invoke( - templateID: string, - body: JourneyInvokeParams, - options?: RequestOptions, - ): APIPromise { - return this._client.post(path`/journeys/${templateID}/invoke`, { body, ...options }); - } -} - -/** - * A journey template representing an automation workflow. - */ -export interface Journey { - /** - * The unique identifier of the journey. - */ - id: string; - - /** - * The name of the journey. - */ - name: string; - - /** - * The version of the journey (published or draft). - */ - version: 'published' | 'draft'; - - /** - * ISO 8601 timestamp when the journey was created. - */ - createdAt?: string; - - /** - * ISO 8601 timestamp when the journey was last updated. - */ - updatedAt?: string; -} - -/** - * Request body for invoking a journey. Requires either a user identifier or a - * profile with contact information. User identifiers can be provided via user_id - * field, or resolved from profile/data objects (user_id, userId, or anonymousId - * fields). - */ -export interface JourneysInvokeRequest { - /** - * Data payload passed to the journey. The expected shape can be predefined using - * the schema builder in the journey editor. This data is available in journey - * steps for condition evaluation and template variable interpolation. Can also - * contain user identifiers (user_id, userId, anonymousId) if not provided - * elsewhere. - */ - data?: { [key: string]: unknown }; - - /** - * Profile data for the user. Can contain contact information (email, - * phone_number), user identifiers (user_id, userId, anonymousId), or any custom - * profile fields. Profile fields are merged with any existing stored profile for - * the user. Include context.tenant_id to load a tenant-scoped profile for - * multi-tenant scenarios. - */ - profile?: { [key: string]: unknown }; - - /** - * A unique identifier for the user. If not provided, the system will attempt to - * resolve the user identifier from profile or data objects. - */ - user_id?: string; -} - -export interface JourneysInvokeResponse { - /** - * A unique identifier for the journey run that was created. - */ - runId: string; -} - -export interface JourneysListResponse { - /** - * A cursor token for pagination. Present when there are more results available. - */ - cursor?: string; - - templates?: Array; -} - -export interface JourneyListParams { - /** - * A cursor token for pagination. Use the cursor from the previous response to - * fetch the next page of results. - */ - cursor?: string; - - /** - * The version of journeys to retrieve. Accepted values are published (for - * published journeys) or draft (for draft journeys). Defaults to published. - */ - version?: 'published' | 'draft'; -} - -export interface JourneyInvokeParams { - /** - * Data payload passed to the journey. The expected shape can be predefined using - * the schema builder in the journey editor. This data is available in journey - * steps for condition evaluation and template variable interpolation. Can also - * contain user identifiers (user_id, userId, anonymousId) if not provided - * elsewhere. - */ - data?: { [key: string]: unknown }; - - /** - * Profile data for the user. Can contain contact information (email, - * phone_number), user identifiers (user_id, userId, anonymousId), or any custom - * profile fields. Profile fields are merged with any existing stored profile for - * the user. Include context.tenant_id to load a tenant-scoped profile for - * multi-tenant scenarios. - */ - profile?: { [key: string]: unknown }; - - /** - * A unique identifier for the user. If not provided, the system will attempt to - * resolve the user identifier from profile or data objects. - */ - user_id?: string; -} - -export declare namespace Journeys { - export { - type Journey as Journey, - type JourneysInvokeRequest as JourneysInvokeRequest, - type JourneysInvokeResponse as JourneysInvokeResponse, - type JourneysListResponse as JourneysListResponse, - type JourneyListParams as JourneyListParams, - type JourneyInvokeParams as JourneyInvokeParams, - }; -} +export * from './journeys/index'; diff --git a/src/resources/journeys/index.ts b/src/resources/journeys/index.ts new file mode 100644 index 00000000..3217441f --- /dev/null +++ b/src/resources/journeys/index.ts @@ -0,0 +1,54 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Journeys, + type CreateJourneyRequest, + type Journey, + type JourneyAINode, + type JourneyAPIInvokeTriggerNode, + type JourneyConditionAtom, + type JourneyConditionGroup, + type JourneyConditionNestedGroup, + type JourneyConditionsField, + type JourneyDelayDurationNode, + type JourneyDelayUntilNode, + type JourneyExitNode, + type JourneyFetchGetDeleteNode, + type JourneyFetchPostPutNode, + type JourneyMergeStrategy, + type JourneyNode, + type JourneyPublishRequest, + type JourneyResponse, + type JourneySegmentTriggerNode, + type JourneySendNode, + type JourneyState, + type JourneyTemplateCreateRequest, + type JourneyTemplateGetResponse, + type JourneyTemplateListResponse, + type JourneyTemplatePublishRequest, + type JourneyTemplateReplaceRequest, + type JourneyTemplateSummary, + type JourneyThrottleDynamicNode, + type JourneyThrottleStaticNode, + type JourneyVersionItem, + type JourneyVersionsListResponse, + type JourneysInvokeRequest, + type JourneysInvokeResponse, + type JourneysListResponse, + type JourneyCreateParams, + type JourneyRetrieveParams, + type JourneyListParams, + type JourneyInvokeParams, + type JourneyPublishParams, + type JourneyReplaceParams, +} from './journeys'; +export { + Templates, + type TemplateCreateParams, + type TemplateRetrieveParams, + type TemplateListParams, + type TemplateArchiveParams, + type TemplateListVersionsParams, + type TemplatePublishParams, + type TemplateReplaceParams, +} from './templates'; diff --git a/src/resources/journeys/journeys.ts b/src/resources/journeys/journeys.ts new file mode 100644 index 00000000..d0666e5a --- /dev/null +++ b/src/resources/journeys/journeys.ts @@ -0,0 +1,939 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as JourneysAPI from './journeys'; +import * as Shared from '../shared'; +import * as TemplatesAPI from './templates'; +import { + TemplateArchiveParams, + TemplateCreateParams, + TemplateListParams, + TemplateListVersionsParams, + TemplatePublishParams, + TemplateReplaceParams, + TemplateRetrieveParams, + Templates, +} from './templates'; +import { APIPromise } from '../../core/api-promise'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class Journeys extends APIResource { + templates: TemplatesAPI.Templates = new TemplatesAPI.Templates(this._client); + + /** + * Create a new journey. The journey is created in DRAFT state. Use POST + * /journeys/{templateId}/publish to make it live. + * + * @example + * ```ts + * const journeyResponse = await client.journeys.create({ + * name: 'Welcome Journey', + * nodes: [ + * { + * id: 'trigger-1', + * type: 'trigger', + * trigger_type: 'api', + * }, + * { id: 'send-1', type: 'send' }, + * ], + * enabled: true, + * state: 'DRAFT', + * }); + * ``` + */ + create(body: JourneyCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/journeys', { body, ...options }); + } + + /** + * Fetch a journey by id. Pass `?version=draft` (default `published`) to retrieve + * the working draft, or `?version=vN` to retrieve a historical version. + * + * @example + * ```ts + * const journeyResponse = await client.journeys.retrieve('x'); + * ``` + */ + retrieve( + templateID: string, + query: JourneyRetrieveParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + return this._client.get(path`/journeys/${templateID}`, { query, ...options }); + } + + /** + * Get the list of journeys. + * + * @example + * ```ts + * const journeysListResponse = await client.journeys.list(); + * ``` + */ + list( + query: JourneyListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + return this._client.get('/journeys', { query, ...options }); + } + + /** + * Archive a journey. Archived journeys cannot be invoked. Existing journey runs + * continue to completion. + * + * @example + * ```ts + * await client.journeys.archive('x'); + * ``` + */ + archive(templateID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/journeys/${templateID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + + /** + * Invoke a journey run from a journey template. + * + * @example + * ```ts + * const journeysInvokeResponse = await client.journeys.invoke( + * 'templateId', + * { + * data: { order_id: 'order-456', amount: 99.99 }, + * user_id: 'user-123', + * }, + * ); + * ``` + */ + invoke( + templateID: string, + body: JourneyInvokeParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/journeys/${templateID}/invoke`, { body, ...options }); + } + + /** + * List published versions of a journey, ordered most recent first. + * + * @example + * ```ts + * const journeyVersionsListResponse = + * await client.journeys.listVersions('x'); + * ``` + */ + listVersions(templateID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/journeys/${templateID}/versions`, options); + } + + /** + * Publish the current draft as a new version. Optionally rollback to a prior + * version by passing `{ version: 'vN' }`. + * + * @example + * ```ts + * const journeyResponse = await client.journeys.publish('x'); + * ``` + */ + publish( + templateID: string, + body: JourneyPublishParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/journeys/${templateID}/publish`, { body, ...options }); + } + + /** + * Replace the journey draft. Updates the working draft only; call POST + * /journeys/{templateId}/publish to make it live. + * + * @example + * ```ts + * const journeyResponse = await client.journeys.replace('x', { + * name: 'Welcome Journey v2', + * nodes: [], + * enabled: true, + * state: 'DRAFT', + * }); + * ``` + */ + replace( + templateID: string, + body: JourneyReplaceParams, + options?: RequestOptions, + ): APIPromise { + return this._client.put(path`/journeys/${templateID}`, { body, ...options }); + } +} + +export interface CreateJourneyRequest { + name: string; + + nodes: Array; + + enabled?: boolean; + + state?: JourneyState; +} + +/** + * A journey template representing an automation workflow. + */ +export interface Journey { + /** + * The unique identifier of the journey. + */ + id: string; + + /** + * The name of the journey. + */ + name: string; + + /** + * The version of the journey (published or draft). + */ + version: 'published' | 'draft'; + + /** + * ISO 8601 timestamp when the journey was created. + */ + createdAt?: string; + + /** + * ISO 8601 timestamp when the journey was last updated. + */ + updatedAt?: string; +} + +export interface JourneyAINode { + /** + * A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv. + */ + output_schema: { [key: string]: unknown }; + + type: 'ai'; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; + + model?: string; + + user_prompt?: string; + + web_search?: boolean; +} + +export interface JourneyAPIInvokeTriggerNode { + trigger_type: 'api-invoke'; + + type: 'trigger'; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; + + /** + * A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv. + */ + schema?: { [key: string]: unknown }; +} + +/** + * A single condition expressed as a positional tuple of strings. + * + * - Binary form (3 elements): `[path, operator, value]` where `operator` is one of + * `is equal`, `is not equal`, `contains`, `does not contain`, `starts with`, + * `ends with`, `greater than`, `greater than or equal`, `less than`, + * `less than or equal`. + * + * Example: `["user.tier", "is equal", "gold"]`. + * + * - Unary form (2 elements): `[path, operator]` where `operator` is one of + * `exists`, `does not exist`. + * + * Example: `["user.email", "exists"]`. + * + * The first element is a non-empty dot-path. The second element is the operator + * (must come from one of the two operator sets above). For the binary form, the + * third element is the comparison value (string). Runtime validation of the + * operator value and arity is performed by the backend; SDKs surface this as a + * string list. + */ +export type JourneyConditionAtom = Array; + +/** + * A leaf condition group. Exactly one of `AND` or `OR` must be present at runtime; + * each is a list of `JourneyConditionAtom` tuples. + */ +export interface JourneyConditionGroup { + AND?: Array; + + OR?: Array; +} + +/** + * A nested condition group. Exactly one of `AND` or `OR` must be present at + * runtime; each is a list of `JourneyConditionGroup` items. + */ +export interface JourneyConditionNestedGroup { + AND?: Array; + + OR?: Array; +} + +/** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ +export type JourneyConditionsField = + | JourneyConditionAtom + | JourneyConditionGroup + | JourneyConditionNestedGroup; + +export interface JourneyDelayDurationNode { + duration: string; + + mode: 'duration'; + + type: 'delay'; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; +} + +export interface JourneyDelayUntilNode { + mode: 'until'; + + type: 'delay'; + + until: string; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; +} + +export interface JourneyExitNode { + type: 'exit'; + + id?: string; +} + +export interface JourneyFetchGetDeleteNode { + merge_strategy: JourneyMergeStrategy; + + method: 'get' | 'delete'; + + type: 'fetch'; + + url: string; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; + + headers?: { [key: string]: string }; + + query_params?: { [key: string]: string }; + + /** + * A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv. + */ + response_schema?: { [key: string]: unknown }; +} + +export interface JourneyFetchPostPutNode { + merge_strategy: JourneyMergeStrategy; + + method: 'post' | 'put'; + + type: 'fetch'; + + url: string; + + id?: string; + + body?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; + + headers?: { [key: string]: string }; + + query_params?: { [key: string]: string }; + + /** + * A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv. + */ + response_schema?: { [key: string]: unknown }; +} + +export type JourneyMergeStrategy = 'overwrite' | 'soft-merge' | 'replace' | 'none'; + +/** + * A single node in a journey DAG. Discriminated by `type` plus a secondary + * discriminator on some variants (`trigger_type` for trigger, `mode` for delay, + * `method` for fetch, `scope` for throttle). Each variant is exported as a + * separate schema for SDK type quality. + */ +export type JourneyNode = + | JourneyAPIInvokeTriggerNode + | JourneySegmentTriggerNode + | JourneySendNode + | JourneyDelayDurationNode + | JourneyDelayUntilNode + | JourneyFetchGetDeleteNode + | JourneyFetchPostPutNode + | JourneyAINode + | JourneyThrottleStaticNode + | JourneyThrottleDynamicNode + | JourneyExitNode + | JourneyNode.JourneyBranchNode; + +export namespace JourneyNode { + /** + * Branch node. Routes to one of `paths[]` whose `conditions` match, else falls + * through to `default.nodes`. Inlined rather than referenced so the recursive + * `nodes: JourneyNode[]` cycle stays within a single generated module (Stainless + * Python forward-ref resolution does not span modules well for this recursion + * shape). + */ + export interface JourneyBranchNode { + default: JourneyBranchNode.Default; + + paths: Array; + + type: 'branch'; + + id?: string; + } + + export namespace JourneyBranchNode { + export interface Default { + nodes: Array; + + label?: string; + } + + export interface Path { + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions: JourneysAPI.JourneyConditionsField; + + nodes: Array; + + label?: string; + } + } +} + +export interface JourneyPublishRequest { + version?: string; +} + +export interface JourneyResponse { + id: string; + + created: number | null; + + creator: string | null; + + enabled: boolean; + + name: string; + + nodes: Array; + + published: number | null; + + state: JourneyState; + + updated: number | null; + + updater: string | null; +} + +export interface JourneySegmentTriggerNode { + request_type: 'identify' | 'group' | 'track'; + + trigger_type: 'segment'; + + type: 'trigger'; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; + + event_id?: string; +} + +export interface JourneySendNode { + message: JourneySendNode.Message; + + type: 'send'; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; +} + +export namespace JourneySendNode { + export interface Message { + template: string; + + data?: { [key: string]: unknown }; + + delay?: Message.Delay; + + to?: Message.To; + } + + export namespace Message { + export interface Delay { + until: string; + + timezone?: string; + } + + export interface To { + email_override?: string; + + phone_number_override?: string; + + user_id_override?: string; + } + } +} + +export type JourneyState = 'DRAFT' | 'PUBLISHED'; + +export interface JourneyTemplateCreateRequest { + channel: string; + + notification: JourneyTemplateCreateRequest.Notification; + + providerKey?: string; + + state?: string; +} + +export namespace JourneyTemplateCreateRequest { + export interface Notification { + brand: Notification.Brand | null; + + content: Notification.Content; + + name: string; + + subscription: Notification.Subscription | null; + + tags: Array; + } + + export namespace Notification { + export interface Brand { + id: string; + } + + export interface Content { + elements: Array; + + version: '2022-01-01'; + + scope?: 'default' | 'strict'; + } + + export interface Subscription { + topic_id: string; + } + } +} + +export interface JourneyTemplateGetResponse { + id: string; + + brand: JourneyTemplateGetResponse.Brand | null; + + content: JourneyTemplateGetResponse.Content; + + created: number; + + creator: string; + + name: string; + + state: 'DRAFT' | 'PUBLISHED'; + + subscription: JourneyTemplateGetResponse.Subscription | null; + + tags: Array; + + updated?: number; + + updater?: string; +} + +export namespace JourneyTemplateGetResponse { + export interface Brand { + id: string; + } + + export interface Content { + elements: Array; + + version: '2022-01-01'; + + scope?: 'default' | 'strict'; + } + + export interface Subscription { + topic_id: string; + } +} + +export interface JourneyTemplateListResponse { + paging: Shared.Paging; + + results: Array; +} + +export interface JourneyTemplatePublishRequest { + version?: string; +} + +export interface JourneyTemplateReplaceRequest { + notification: JourneyTemplateReplaceRequest.Notification; + + state?: string; +} + +export namespace JourneyTemplateReplaceRequest { + export interface Notification { + brand: Notification.Brand | null; + + content: Notification.Content; + + name: string; + + subscription: Notification.Subscription | null; + + tags: Array; + } + + export namespace Notification { + export interface Brand { + id: string; + } + + export interface Content { + elements: Array; + + version: '2022-01-01'; + + scope?: 'default' | 'strict'; + } + + export interface Subscription { + topic_id: string; + } + } +} + +export interface JourneyTemplateSummary { + id: string; + + created: number; + + creator: string; + + name: string; + + state: string; + + tags: Array; + + updated?: number; + + updater?: string; +} + +export interface JourneyThrottleDynamicNode { + max_allowed: number; + + period: string; + + scope: 'dynamic'; + + throttle_key: string; + + type: 'throttle'; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; +} + +export interface JourneyThrottleStaticNode { + max_allowed: number; + + period: string; + + scope: 'user' | 'global'; + + type: 'throttle'; + + id?: string; + + /** + * Condition spec for a journey node. Accepts a single condition atom, an AND/OR + * group, or an AND/OR nested group. Omit the `conditions` property entirely to + * express "no conditions". + */ + conditions?: JourneyConditionsField; +} + +export interface JourneyVersionItem { + created: number | null; + + creator: string | null; + + name: string; + + published: number | null; + + version: string; +} + +export interface JourneyVersionsListResponse { + paging: Shared.Paging; + + results: Array; +} + +/** + * Request body for invoking a journey. Requires either a user identifier or a + * profile with contact information. User identifiers can be provided via user_id + * field, or resolved from profile/data objects (user_id, userId, or anonymousId + * fields). + */ +export interface JourneysInvokeRequest { + /** + * Data payload passed to the journey. The expected shape can be predefined using + * the schema builder in the journey editor. This data is available in journey + * steps for condition evaluation and template variable interpolation. Can also + * contain user identifiers (user_id, userId, anonymousId) if not provided + * elsewhere. + */ + data?: { [key: string]: unknown }; + + /** + * Profile data for the user. Can contain contact information (email, + * phone_number), user identifiers (user_id, userId, anonymousId), or any custom + * profile fields. Profile fields are merged with any existing stored profile for + * the user. Include context.tenant_id to load a tenant-scoped profile for + * multi-tenant scenarios. + */ + profile?: { [key: string]: unknown }; + + /** + * A unique identifier for the user. If not provided, the system will attempt to + * resolve the user identifier from profile or data objects. + */ + user_id?: string; +} + +export interface JourneysInvokeResponse { + /** + * A unique identifier for the journey run that was created. + */ + runId: string; +} + +export interface JourneysListResponse { + /** + * A cursor token for pagination. Present when there are more results available. + */ + cursor?: string; + + templates?: Array; +} + +export interface JourneyCreateParams { + name: string; + + nodes: Array; + + enabled?: boolean; + + state?: JourneyState; +} + +export interface JourneyRetrieveParams { + version?: string; +} + +export interface JourneyListParams { + /** + * A cursor token for pagination. Use the cursor from the previous response to + * fetch the next page of results. + */ + cursor?: string; + + /** + * The version of journeys to retrieve. Accepted values are published (for + * published journeys) or draft (for draft journeys). Defaults to published. + */ + version?: 'published' | 'draft'; +} + +export interface JourneyInvokeParams { + /** + * Data payload passed to the journey. The expected shape can be predefined using + * the schema builder in the journey editor. This data is available in journey + * steps for condition evaluation and template variable interpolation. Can also + * contain user identifiers (user_id, userId, anonymousId) if not provided + * elsewhere. + */ + data?: { [key: string]: unknown }; + + /** + * Profile data for the user. Can contain contact information (email, + * phone_number), user identifiers (user_id, userId, anonymousId), or any custom + * profile fields. Profile fields are merged with any existing stored profile for + * the user. Include context.tenant_id to load a tenant-scoped profile for + * multi-tenant scenarios. + */ + profile?: { [key: string]: unknown }; + + /** + * A unique identifier for the user. If not provided, the system will attempt to + * resolve the user identifier from profile or data objects. + */ + user_id?: string; +} + +export interface JourneyPublishParams { + version?: string; +} + +export interface JourneyReplaceParams { + name: string; + + nodes: Array; + + enabled?: boolean; + + state?: JourneyState; +} + +Journeys.Templates = Templates; + +export declare namespace Journeys { + export { + type CreateJourneyRequest as CreateJourneyRequest, + type Journey as Journey, + type JourneyAINode as JourneyAINode, + type JourneyAPIInvokeTriggerNode as JourneyAPIInvokeTriggerNode, + type JourneyConditionAtom as JourneyConditionAtom, + type JourneyConditionGroup as JourneyConditionGroup, + type JourneyConditionNestedGroup as JourneyConditionNestedGroup, + type JourneyConditionsField as JourneyConditionsField, + type JourneyDelayDurationNode as JourneyDelayDurationNode, + type JourneyDelayUntilNode as JourneyDelayUntilNode, + type JourneyExitNode as JourneyExitNode, + type JourneyFetchGetDeleteNode as JourneyFetchGetDeleteNode, + type JourneyFetchPostPutNode as JourneyFetchPostPutNode, + type JourneyMergeStrategy as JourneyMergeStrategy, + type JourneyNode as JourneyNode, + type JourneyPublishRequest as JourneyPublishRequest, + type JourneyResponse as JourneyResponse, + type JourneySegmentTriggerNode as JourneySegmentTriggerNode, + type JourneySendNode as JourneySendNode, + type JourneyState as JourneyState, + type JourneyTemplateCreateRequest as JourneyTemplateCreateRequest, + type JourneyTemplateGetResponse as JourneyTemplateGetResponse, + type JourneyTemplateListResponse as JourneyTemplateListResponse, + type JourneyTemplatePublishRequest as JourneyTemplatePublishRequest, + type JourneyTemplateReplaceRequest as JourneyTemplateReplaceRequest, + type JourneyTemplateSummary as JourneyTemplateSummary, + type JourneyThrottleDynamicNode as JourneyThrottleDynamicNode, + type JourneyThrottleStaticNode as JourneyThrottleStaticNode, + type JourneyVersionItem as JourneyVersionItem, + type JourneyVersionsListResponse as JourneyVersionsListResponse, + type JourneysInvokeRequest as JourneysInvokeRequest, + type JourneysInvokeResponse as JourneysInvokeResponse, + type JourneysListResponse as JourneysListResponse, + type JourneyCreateParams as JourneyCreateParams, + type JourneyRetrieveParams as JourneyRetrieveParams, + type JourneyListParams as JourneyListParams, + type JourneyInvokeParams as JourneyInvokeParams, + type JourneyPublishParams as JourneyPublishParams, + type JourneyReplaceParams as JourneyReplaceParams, + }; + + export { + Templates as Templates, + type TemplateCreateParams as TemplateCreateParams, + type TemplateRetrieveParams as TemplateRetrieveParams, + type TemplateListParams as TemplateListParams, + type TemplateArchiveParams as TemplateArchiveParams, + type TemplateListVersionsParams as TemplateListVersionsParams, + type TemplatePublishParams as TemplatePublishParams, + type TemplateReplaceParams as TemplateReplaceParams, + }; +} diff --git a/src/resources/journeys/templates.ts b/src/resources/journeys/templates.ts new file mode 100644 index 00000000..7e35922c --- /dev/null +++ b/src/resources/journeys/templates.ts @@ -0,0 +1,310 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as Shared from '../shared'; +import * as JourneysAPI from './journeys'; +import * as NotificationsAPI from '../notifications/notifications'; +import { APIPromise } from '../../core/api-promise'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class Templates extends APIResource { + /** + * Create a notification template scoped to this journey. The template is created + * in DRAFT state. + * + * @example + * ```ts + * const journeyTemplateGetResponse = + * await client.journeys.templates.create('x', { + * channel: 'email', + * notification: { + * name: 'Welcome email', + * tags: [], + * brand: null, + * subscription: null, + * content: { + * version: '2022-01-01', + * elements: [{ type: 'text' }], + * }, + * }, + * }); + * ``` + */ + create( + templateID: string, + body: TemplateCreateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/journeys/${templateID}/templates`, { body, ...options }); + } + + /** + * Fetch a journey-scoped notification template by id. Pass `?version=draft` + * (default `published`) to retrieve the working draft, or `?version=vN` for a + * historical version. + * + * @example + * ```ts + * const journeyTemplateGetResponse = + * await client.journeys.templates.retrieve('x', { + * templateId: 'x', + * }); + * ``` + */ + retrieve( + notificationID: string, + params: TemplateRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { templateId } = params; + return this._client.get(path`/journeys/${templateId}/templates/${notificationID}`, options); + } + + /** + * List notification templates scoped to this journey. Templates scoped to a + * journey can only be referenced from `send` nodes of the same journey. + * + * @example + * ```ts + * const journeyTemplateListResponse = + * await client.journeys.templates.list('x'); + * ``` + */ + list( + templateID: string, + query: TemplateListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + return this._client.get(path`/journeys/${templateID}/templates`, { query, ...options }); + } + + /** + * Archive a journey-scoped notification template. Archived templates cannot be + * sent. + * + * @example + * ```ts + * await client.journeys.templates.archive('x', { + * templateId: 'x', + * }); + * ``` + */ + archive(notificationID: string, params: TemplateArchiveParams, options?: RequestOptions): APIPromise { + const { templateId } = params; + return this._client.delete(path`/journeys/${templateId}/templates/${notificationID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + + /** + * List published versions of a journey-scoped notification template, ordered most + * recent first. + * + * @example + * ```ts + * const notificationTemplateVersionListResponse = + * await client.journeys.templates.listVersions('x', { + * templateId: 'x', + * }); + * ``` + */ + listVersions( + notificationID: string, + params: TemplateListVersionsParams, + options?: RequestOptions, + ): APIPromise { + const { templateId } = params; + return this._client.get(path`/journeys/${templateId}/templates/${notificationID}/versions`, options); + } + + /** + * Publish the current draft of a journey-scoped notification template. + * + * @example + * ```ts + * await client.journeys.templates.publish('x', { + * templateId: 'x', + * }); + * ``` + */ + publish(notificationID: string, params: TemplatePublishParams, options?: RequestOptions): APIPromise { + const { templateId, ...body } = params; + return this._client.post(path`/journeys/${templateId}/templates/${notificationID}/publish`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + + /** + * Replace a journey-scoped notification template draft. + * + * @example + * ```ts + * const journeyTemplateGetResponse = + * await client.journeys.templates.replace('x', { + * templateId: 'x', + * notification: { + * brand: { id: 'id' }, + * content: { elements: [{}], version: '2022-01-01' }, + * name: 'name', + * subscription: { topic_id: 'topic_id' }, + * tags: ['string'], + * }, + * }); + * ``` + */ + replace( + notificationID: string, + params: TemplateReplaceParams, + options?: RequestOptions, + ): APIPromise { + const { templateId, ...body } = params; + return this._client.put(path`/journeys/${templateId}/templates/${notificationID}`, { body, ...options }); + } +} + +export interface TemplateCreateParams { + channel: string; + + notification: TemplateCreateParams.Notification; + + providerKey?: string; + + state?: string; +} + +export namespace TemplateCreateParams { + export interface Notification { + brand: Notification.Brand | null; + + content: Notification.Content; + + name: string; + + subscription: Notification.Subscription | null; + + tags: Array; + } + + export namespace Notification { + export interface Brand { + id: string; + } + + export interface Content { + elements: Array; + + version: '2022-01-01'; + + scope?: 'default' | 'strict'; + } + + export interface Subscription { + topic_id: string; + } + } +} + +export interface TemplateRetrieveParams { + /** + * Journey id + */ + templateId: string; +} + +export interface TemplateListParams { + cursor?: string; + + limit?: number; +} + +export interface TemplateArchiveParams { + /** + * Journey id + */ + templateId: string; +} + +export interface TemplateListVersionsParams { + /** + * Journey id + */ + templateId: string; +} + +export interface TemplatePublishParams { + /** + * Path param: Journey id + */ + templateId: string; + + /** + * Body param + */ + version?: string; +} + +export interface TemplateReplaceParams { + /** + * Path param: Journey id + */ + templateId: string; + + /** + * Body param + */ + notification: TemplateReplaceParams.Notification; + + /** + * Body param + */ + state?: string; +} + +export namespace TemplateReplaceParams { + export interface Notification { + brand: Notification.Brand | null; + + content: Notification.Content; + + name: string; + + subscription: Notification.Subscription | null; + + tags: Array; + } + + export namespace Notification { + export interface Brand { + id: string; + } + + export interface Content { + elements: Array; + + version: '2022-01-01'; + + scope?: 'default' | 'strict'; + } + + export interface Subscription { + topic_id: string; + } + } +} + +export declare namespace Templates { + export { + type TemplateCreateParams as TemplateCreateParams, + type TemplateRetrieveParams as TemplateRetrieveParams, + type TemplateListParams as TemplateListParams, + type TemplateArchiveParams as TemplateArchiveParams, + type TemplateListVersionsParams as TemplateListVersionsParams, + type TemplatePublishParams as TemplatePublishParams, + type TemplateReplaceParams as TemplateReplaceParams, + }; +} diff --git a/tests/api-resources/journeys.test.ts b/tests/api-resources/journeys.test.ts deleted file mode 100644 index 92d4b7a5..00000000 --- a/tests/api-resources/journeys.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import Courier from '@trycourier/courier'; - -const client = new Courier({ - apiKey: 'My API Key', - baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', -}); - -describe('resource journeys', () => { - // Mock server tests are disabled - test.skip('list', async () => { - const responsePromise = client.journeys.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); - }); - - // Mock server tests are disabled - test.skip('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.journeys.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' }), - ).rejects.toThrow(Courier.NotFoundError); - }); - - // Mock server tests are disabled - test.skip('invoke', async () => { - const responsePromise = client.journeys.invoke('templateId', {}); - 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); - }); -}); diff --git a/tests/api-resources/journeys/journeys.test.ts b/tests/api-resources/journeys/journeys.test.ts new file mode 100644 index 00000000..621004b7 --- /dev/null +++ b/tests/api-resources/journeys/journeys.test.ts @@ -0,0 +1,182 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import Courier from '@trycourier/courier'; + +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); + +describe('resource journeys', () => { + // Mock server tests are disabled + test.skip('create: only required params', async () => { + const responsePromise = client.journeys.create({ + name: 'Welcome Journey', + nodes: [ + { trigger_type: 'api-invoke', type: 'trigger' }, + { trigger_type: 'api-invoke', type: 'trigger' }, + ], + }); + 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); + }); + + // Mock server tests are disabled + test.skip('create: required and optional params', async () => { + const response = await client.journeys.create({ + name: 'Welcome Journey', + nodes: [ + { + trigger_type: 'api-invoke', + type: 'trigger', + id: 'trigger-1', + conditions: ['string', 'string'], + schema: { foo: 'bar' }, + }, + { + trigger_type: 'api-invoke', + type: 'trigger', + id: 'send-1', + conditions: ['string', 'string'], + schema: { foo: 'bar' }, + }, + ], + enabled: true, + state: 'DRAFT', + }); + }); + + // Mock server tests are disabled + test.skip('retrieve', async () => { + const responsePromise = client.journeys.retrieve('x'); + 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); + }); + + // Mock server tests are disabled + test.skip('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.journeys.retrieve('x', { version: 'published' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); + }); + + // Mock server tests are disabled + test.skip('list', async () => { + const responsePromise = client.journeys.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); + }); + + // Mock server tests are disabled + test.skip('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.journeys.list({ cursor: 'cursor', version: 'published' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); + }); + + // Mock server tests are disabled + test.skip('archive', async () => { + const responsePromise = client.journeys.archive('x'); + 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); + }); + + // Mock server tests are disabled + test.skip('invoke', async () => { + const responsePromise = client.journeys.invoke('templateId', {}); + 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); + }); + + // Mock server tests are disabled + test.skip('listVersions', async () => { + const responsePromise = client.journeys.listVersions('x'); + 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); + }); + + // Mock server tests are disabled + test.skip('publish', async () => { + const responsePromise = client.journeys.publish('x'); + 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); + }); + + // Mock server tests are disabled + test.skip('publish: 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.journeys.publish('x', { version: 'v321669910225' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Courier.NotFoundError); + }); + + // Mock server tests are disabled + test.skip('replace: only required params', async () => { + const responsePromise = client.journeys.replace('x', { + name: 'Welcome Journey v2', + nodes: [{ trigger_type: 'api-invoke', type: 'trigger' }], + }); + 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); + }); + + // Mock server tests are disabled + test.skip('replace: required and optional params', async () => { + const response = await client.journeys.replace('x', { + name: 'Welcome Journey v2', + nodes: [ + { + trigger_type: 'api-invoke', + type: 'trigger', + id: 'x', + conditions: ['string', 'string'], + schema: { foo: 'bar' }, + }, + ], + enabled: true, + state: 'DRAFT', + }); + }); +}); diff --git a/tests/api-resources/journeys/templates.test.ts b/tests/api-resources/journeys/templates.test.ts new file mode 100644 index 00000000..608e7141 --- /dev/null +++ b/tests/api-resources/journeys/templates.test.ts @@ -0,0 +1,202 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import Courier from '@trycourier/courier'; + +const client = new Courier({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); + +describe('resource templates', () => { + // Mock server tests are disabled + test.skip('create: only required params', async () => { + const responsePromise = client.journeys.templates.create('x', { + channel: 'email', + notification: { + brand: { id: 'id' }, + content: { elements: [{}], version: '2022-01-01' }, + name: 'Welcome email', + subscription: { topic_id: 'topic_id' }, + tags: ['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); + }); + + // Mock server tests are disabled + test.skip('create: required and optional params', async () => { + const response = await client.journeys.templates.create('x', { + channel: 'email', + notification: { + brand: { id: 'id' }, + content: { + elements: [ + { + channels: ['string'], + if: 'if', + loop: 'loop', + ref: 'ref', + type: 'text', + }, + ], + version: '2022-01-01', + scope: 'default', + }, + name: 'Welcome email', + subscription: { topic_id: 'topic_id' }, + tags: ['string'], + }, + providerKey: 'x', + state: 'state', + }); + }); + + // Mock server tests are disabled + test.skip('retrieve: only required params', async () => { + const responsePromise = client.journeys.templates.retrieve('x', { templateId: 'x' }); + 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); + }); + + // Mock server tests are disabled + test.skip('retrieve: required and optional params', async () => { + const response = await client.journeys.templates.retrieve('x', { templateId: 'x' }); + }); + + // Mock server tests are disabled + test.skip('list', async () => { + const responsePromise = client.journeys.templates.list('x'); + 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); + }); + + // Mock server tests are disabled + test.skip('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.journeys.templates.list( + 'x', + { cursor: 'cursor', limit: 1 }, + { path: '/_stainless_unknown_path' }, + ), + ).rejects.toThrow(Courier.NotFoundError); + }); + + // Mock server tests are disabled + test.skip('archive: only required params', async () => { + const responsePromise = client.journeys.templates.archive('x', { templateId: 'x' }); + 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); + }); + + // Mock server tests are disabled + test.skip('archive: required and optional params', async () => { + const response = await client.journeys.templates.archive('x', { templateId: 'x' }); + }); + + // Mock server tests are disabled + test.skip('listVersions: only required params', async () => { + const responsePromise = client.journeys.templates.listVersions('x', { templateId: 'x' }); + 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); + }); + + // Mock server tests are disabled + test.skip('listVersions: required and optional params', async () => { + const response = await client.journeys.templates.listVersions('x', { templateId: 'x' }); + }); + + // Mock server tests are disabled + test.skip('publish: only required params', async () => { + const responsePromise = client.journeys.templates.publish('x', { templateId: 'x' }); + 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); + }); + + // Mock server tests are disabled + test.skip('publish: required and optional params', async () => { + const response = await client.journeys.templates.publish('x', { + templateId: 'x', + version: 'v321669910225', + }); + }); + + // Mock server tests are disabled + test.skip('replace: only required params', async () => { + const responsePromise = client.journeys.templates.replace('x', { + templateId: 'x', + notification: { + brand: { id: 'id' }, + content: { elements: [{}], version: '2022-01-01' }, + name: 'name', + subscription: { topic_id: 'topic_id' }, + tags: ['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); + }); + + // Mock server tests are disabled + test.skip('replace: required and optional params', async () => { + const response = await client.journeys.templates.replace('x', { + templateId: 'x', + notification: { + brand: { id: 'id' }, + content: { + elements: [ + { + channels: ['string'], + if: 'if', + loop: 'loop', + ref: 'ref', + type: 'text', + }, + ], + version: '2022-01-01', + scope: 'default', + }, + name: 'name', + subscription: { topic_id: 'topic_id' }, + tags: ['string'], + }, + state: 'state', + }); + }); +}); From c5769b4bfd047d0b3914f35403a2a6bac9a207c4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 15 May 2026 17:18:41 +0000 Subject: [PATCH 11/12] feat: [SUP-607] Add DELETE endpoint for Courier Create tenant templates --- .stats.yml | 8 ++--- api.md | 1 + src/resources/tenants/index.ts | 1 + src/resources/tenants/templates/index.ts | 1 + src/resources/tenants/templates/templates.ts | 32 +++++++++++++++++++ src/resources/tenants/tenants.ts | 2 ++ .../tenants/templates/templates.test.ts | 17 ++++++++++ 7 files changed, 58 insertions(+), 4 deletions(-) diff --git a/.stats.yml b/.stats.yml index eb39c6b7..d43ae964 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 116 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-389afcb57163d4391f72d240c33a82d0522b958400603f137981480cda54558a.yml -openapi_spec_hash: c861d7fcd81ad5bfdaf8da0f5a84f497 -config_hash: e40fec72c1ab30fded57c222ace689b5 +configured_endpoints: 117 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-ebe0d758a32897eaf20f252329168bbe2c2da7f580bb871357e63f4b451c684e.yml +openapi_spec_hash: ba0c3cf85aa82f17744e217258a55b2e +config_hash: 10bd597dd6cc89023541bc551b6532b8 diff --git a/api.md b/api.md index a9343982..d25051f7 100644 --- a/api.md +++ b/api.md @@ -492,6 +492,7 @@ Methods: - client.tenants.templates.retrieve(templateID, { ...params }) -> BaseTemplateTenantAssociation - client.tenants.templates.list(tenantID, { ...params }) -> TemplateListResponse +- client.tenants.templates.delete(templateID, { ...params }) -> void - client.tenants.templates.publish(templateID, { ...params }) -> PostTenantTemplatePublishResponse - client.tenants.templates.replace(templateID, { ...params }) -> PutTenantTemplateResponse diff --git a/src/resources/tenants/index.ts b/src/resources/tenants/index.ts index c5216c97..8249babd 100644 --- a/src/resources/tenants/index.ts +++ b/src/resources/tenants/index.ts @@ -6,6 +6,7 @@ export { type TemplateListResponse, type TemplateRetrieveParams, type TemplateListParams, + type TemplateDeleteParams, type TemplatePublishParams, type TemplateReplaceParams, } from './templates/index'; diff --git a/src/resources/tenants/templates/index.ts b/src/resources/tenants/templates/index.ts index d4f43150..f56deb7e 100644 --- a/src/resources/tenants/templates/index.ts +++ b/src/resources/tenants/templates/index.ts @@ -5,6 +5,7 @@ export { type TemplateListResponse, type TemplateRetrieveParams, type TemplateListParams, + type TemplateDeleteParams, type TemplatePublishParams, type TemplateReplaceParams, } from './templates'; diff --git a/src/resources/tenants/templates/templates.ts b/src/resources/tenants/templates/templates.ts index 52e39d5b..262ca3d5 100644 --- a/src/resources/tenants/templates/templates.ts +++ b/src/resources/tenants/templates/templates.ts @@ -6,6 +6,7 @@ import * as TenantsAPI from '../tenants'; import * as VersionsAPI from './versions'; import { VersionRetrieveParams, Versions } from './versions'; import { APIPromise } from '../../../core/api-promise'; +import { buildHeaders } from '../../../internal/headers'; import { RequestOptions } from '../../../internal/request-options'; import { path } from '../../../internal/utils/path'; @@ -50,6 +51,29 @@ export class Templates extends APIResource { return this._client.get(path`/tenants/${tenantID}/templates`, { query, ...options }); } + /** + * Deletes the tenant's notification template with the given `template_id`. + * + * Returns **204 No Content** with an empty body on success. + * + * Returns **404** if there is no template with this ID for the tenant, including a + * second `DELETE` after a successful removal. + * + * @example + * ```ts + * await client.tenants.templates.delete('template_id', { + * tenant_id: 'tenant_id', + * }); + * ``` + */ + delete(templateID: string, params: TemplateDeleteParams, options?: RequestOptions): APIPromise { + const { tenant_id } = params; + return this._client.delete(path`/tenants/${tenant_id}/templates/${templateID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + /** * Publishes a specific version of a notification template for a tenant. * @@ -174,6 +198,13 @@ export interface TemplateListParams { limit?: number | null; } +export interface TemplateDeleteParams { + /** + * Id of the tenant that owns the template. + */ + tenant_id: string; +} + export interface TemplatePublishParams { /** * Path param: Id of the tenant that owns the template. @@ -214,6 +245,7 @@ export declare namespace Templates { type TemplateListResponse as TemplateListResponse, type TemplateRetrieveParams as TemplateRetrieveParams, type TemplateListParams as TemplateListParams, + type TemplateDeleteParams as TemplateDeleteParams, type TemplatePublishParams as TemplatePublishParams, type TemplateReplaceParams as TemplateReplaceParams, }; diff --git a/src/resources/tenants/tenants.ts b/src/resources/tenants/tenants.ts index 75aa7b31..1ac5e1f0 100644 --- a/src/resources/tenants/tenants.ts +++ b/src/resources/tenants/tenants.ts @@ -7,6 +7,7 @@ import * as PreferencesAPI from './preferences/preferences'; import { Preferences } from './preferences/preferences'; import * as TemplatesAPI from './templates/templates'; import { + TemplateDeleteParams, TemplateListParams, TemplateListResponse, TemplatePublishParams, @@ -463,6 +464,7 @@ export declare namespace Tenants { type TemplateListResponse as TemplateListResponse, type TemplateRetrieveParams as TemplateRetrieveParams, type TemplateListParams as TemplateListParams, + type TemplateDeleteParams as TemplateDeleteParams, type TemplatePublishParams as TemplatePublishParams, type TemplateReplaceParams as TemplateReplaceParams, }; diff --git a/tests/api-resources/tenants/templates/templates.test.ts b/tests/api-resources/tenants/templates/templates.test.ts index 94e7ae8e..2230eb3f 100644 --- a/tests/api-resources/tenants/templates/templates.test.ts +++ b/tests/api-resources/tenants/templates/templates.test.ts @@ -49,6 +49,23 @@ describe('resource templates', () => { ).rejects.toThrow(Courier.NotFoundError); }); + // Mock server tests are disabled + test.skip('delete: only required params', async () => { + const responsePromise = client.tenants.templates.delete('template_id', { tenant_id: 'tenant_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); + }); + + // Mock server tests are disabled + test.skip('delete: required and optional params', async () => { + const response = await client.tenants.templates.delete('template_id', { tenant_id: 'tenant_id' }); + }); + // Mock server tests are disabled test.skip('publish: only required params', async () => { const responsePromise = client.tenants.templates.publish('template_id', { tenant_id: 'tenant_id' }); From cbe4cb829941b4fbd9aba17ed5a7226d4c37de20 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 15 May 2026 17:19:09 +0000 Subject: [PATCH 12/12] release: 7.11.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ package.json | 2 +- src/version.ts | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1c3fc076..1421b84e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "7.10.2" + ".": "7.11.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index a61ec82d..2f7353b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 7.11.0 (2026-05-15) + +Full Changelog: [v7.10.2...v7.11.0](https://github.com/trycourier/courier-node/compare/v7.10.2...v7.11.0) + +### Features + +* [SUP-607] Add DELETE endpoint for Courier Create tenant templates ([c5769b4](https://github.com/trycourier/courier-node/commit/c5769b4bfd047d0b3914f35403a2a6bac9a207c4)) +* **api:** add journeys CRUD/publish/versioning, templates sub-resource, types ([297d6eb](https://github.com/trycourier/courier-node/commit/297d6eb106b494cb56f3722a124a096736f1f83a)) +* support setting headers via env ([e7a078f](https://github.com/trycourier/courier-node/commit/e7a078f8e44790bf9332c5c06891d3fa9b148ee7)) + + +### Chores + +* **format:** run eslint and prettier separately ([94cc158](https://github.com/trycourier/courier-node/commit/94cc1583b4dcfe832929c142efaf5bf8b371b42f)) +* **formatter:** run prettier and eslint separately ([ee1ac34](https://github.com/trycourier/courier-node/commit/ee1ac34270e0607eb8f6f6ea884b37a7c9167e3d)) +* **internal:** codegen related update ([6197029](https://github.com/trycourier/courier-node/commit/619702960b9076a75bc7138a5218d06f4b3c5dc3)) +* **internal:** more robust bootstrap script ([1625ecf](https://github.com/trycourier/courier-node/commit/1625ecf85ab5a9550217acb1b6655c9ea5611fa3)) +* redact api-key headers in debug logs ([ce91d48](https://github.com/trycourier/courier-node/commit/ce91d48d8a4be2500a03433a03bafd8142d78e08)) + ## 7.10.2 (2026-04-14) Full Changelog: [v7.10.1...v7.10.2](https://github.com/trycourier/courier-node/compare/v7.10.1...v7.10.2) diff --git a/package.json b/package.json index 7d86550e..d26d2840 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@trycourier/courier", - "version": "7.10.2", + "version": "7.11.0", "description": "The official TypeScript library for the Courier API", "author": "Courier ", "types": "dist/index.d.ts", diff --git a/src/version.ts b/src/version.ts index 4533200e..c00d803e 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '7.10.2'; // x-release-please-version +export const VERSION = '7.11.0'; // x-release-please-version