diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97c756f..516f9e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,6 +40,9 @@ jobs: - name: Conformance working-directory: . run: node stand-in/conformance.mjs -- node sdk/typescript/examples/conformance.mjs + - name: Conformance (API v2) + working-directory: . + run: node stand-in/conformance.mjs --v2 -- node sdk/typescript/examples/conformance-v2.mjs - run: npm pack --dry-run php: @@ -72,6 +75,8 @@ jobs: node-version: "26" - name: Conformance run: node stand-in/conformance.mjs -- php sdk/php/examples/conformance.php + - name: Conformance (API v2) + run: node stand-in/conformance.mjs --v2 -- php sdk/php/examples/conformance-v2.php php-without-curl: # ext-curl is optional (only the built-in CurlTransport needs it): the SDK must @@ -124,6 +129,9 @@ jobs: - name: Conformance working-directory: . run: node stand-in/conformance.mjs -- python sdk/python/examples/conformance.py + - name: Conformance (API v2) + working-directory: . + run: node stand-in/conformance.mjs --v2 -- python sdk/python/examples/conformance_v2.py dotnet: name: .NET 10 and 11 @@ -140,11 +148,14 @@ jobs: - run: dotnet build sdk/dotnet -warnaserror - run: dotnet test sdk/dotnet --no-build - run: dotnet build sdk/dotnet/examples/Conformance -c Release -warnaserror + - run: dotnet build sdk/dotnet/examples/ConformanceV2 -c Release -warnaserror - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: "26" - name: Conformance run: node stand-in/conformance.mjs -- dotnet sdk/dotnet/examples/Conformance/bin/Release/net10.0/Conformance.dll + - name: Conformance (API v2) + run: node stand-in/conformance.mjs --v2 -- dotnet sdk/dotnet/examples/ConformanceV2/bin/Release/net10.0/ConformanceV2.dll - run: dotnet pack sdk/dotnet/src/Supertext.Sdk -c Release -o sdk/dotnet/artifacts -warnaserror java: @@ -172,6 +183,8 @@ jobs: node-version: "26" - name: Conformance run: node ../../stand-in/conformance.mjs -- java -cp target/classes examples/Conformance.java + - name: Conformance (API v2) + run: node ../../stand-in/conformance.mjs --v2 -- java -cp target/classes examples/ConformanceV2.java kotlin: name: Kotlin (Java ${{ matrix.java }}) @@ -198,3 +211,5 @@ jobs: node-version: "26" - name: Conformance run: node ../../stand-in/conformance.mjs -- java -cp 'target/classes:target/test-classes:target/lib/*' ConformanceKt + - name: Conformance (API v2) + run: node ../../stand-in/conformance.mjs --v2 -- java -cp 'target/classes:target/test-classes:target/lib/*' ConformanceV2Kt diff --git a/.github/workflows/live-v2.yml b/.github/workflows/live-v2.yml new file mode 100644 index 0000000..203f1ba --- /dev/null +++ b/.github/workflows/live-v2.yml @@ -0,0 +1,55 @@ +name: Live API v2 + +# Runs scripts/live-v2.mjs against Supertext's platform API with the TypeScript v2 client: key check, +# account, features, a quote and one small translation (a few characters of credit). Weekly, by hand, +# and on changes to the v2 client or the check. Needs the secret SUPERTEXT_API_KEY_V2. Then +# scripts/compare-links.mjs prints how API v1 and v2 keep links in sample sentences (diagnostic). +# See docs/DEVELOPER.md → Tests and CI. +on: + pull_request: + paths: ["sdk/typescript/src/v2/**", "scripts/live-v2.mjs", "scripts/compare-links.mjs", ".github/workflows/live-v2.yml"] + push: + branches: [main] + paths: ["sdk/typescript/src/v2/**", "scripts/live-v2.mjs", "scripts/compare-links.mjs", ".github/workflows/live-v2.yml"] + schedule: + - cron: "41 5 * * 2" + workflow_dispatch: + +permissions: + contents: read + +jobs: + live: + name: Live API v2 + runs-on: ubuntu-latest + defaults: + run: + working-directory: sdk/typescript + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + package-manager-cache: false + - run: npm ci + - run: npm run build + - name: Check against the live API + working-directory: . + env: + SUPERTEXT_API_KEY_V2: ${{ secrets.SUPERTEXT_API_KEY_V2 }} + run: | + if [ -z "$SUPERTEXT_API_KEY_V2" ]; then + echo "::warning::Secret SUPERTEXT_API_KEY_V2 is not set: API v2 can't be checked live." + exit 0 + fi + node scripts/live-v2.mjs + + - name: Compare links and formatting (API v1 and v2) + if: success() || failure() + working-directory: . + env: + SUPERTEXT_API_KEY: ${{ secrets.SUPERTEXT_API_KEY }} + SUPERTEXT_API_KEY_V2: ${{ secrets.SUPERTEXT_API_KEY_V2 }} + run: node scripts/compare-links.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 24a3be0..5a4c9fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,14 @@ All SDKs in this repository share one version. Format: one section per release, ### Added +- **API v2: Supertext's platform API** (`https://api-platform.supertext.com/v1/`, workspace keys sent as `Authorization: Bearer st_live_…`) in a `v2` namespace next to `v1` in all six SDKs (TypeScript `supertext-sdk/v2`, PHP `Supertext\Sdk\V2`, Python `supertext.v2`, .NET `Supertext.Sdk.V2`, Java and Kotlin `com.supertext.sdk.v2`), with vectors in `spec/v2/` (`auth-header`, `errors`, `batching`, `webhooks`, `api-key-check`, `conformance`, and Supertext's `openapi.json`), a stand-in (`stand-in/stand-in-v2.mjs`) and conformance programs (`node stand-in/conformance.mjs --v2 -- `, in CI for every SDK). `translateTexts` takes the same keyed segments as v1 and sends them as direct text requests (up to 10,000 characters each; HTML segments with `tag_handling: html`; a longer segment through the file endpoint, blanks unchanged). Also: `translateText`/`quoteText`, AI translation of any supported document (`translateFile`, `translateHtml`, the single steps, `quoteFile`; glossary, OCR), language detection, human review (`orderFusedText`/`orderFusedFile` with status, result and quotes; idempotency key for text orders), `getAccount`, `getFeatures`, `validateApiKey`, `checkApiKey` (the v1 `ApiKeyCheck`, on `GET account`), webhooks (create, list, get, update, delete, test) and `verifyWebhook` / `Webhooks.verify` (Standard Webhooks signatures, 5-minute tolerance, `invalid_webhook`). One error type with the v2 codes (`insufficient_credit`, `invalid_request`, `conflict`, …) and Supertext's problem fields (`detail`, `apiErrorCode`, `errorId`, `reason`). v1 is unchanged. Integration guide → *API v2*, API reference → *API v2*. The *Live API v2* workflow checks the TypeScript v2 client against the live API weekly (secret `SUPERTEXT_API_KEY_V2`). + - **Publishing to npm and Maven Central** in `release.yml` (jobs *Publish to npm* and *Publish to Maven Central*, a `release` profile in the Java and Kotlin poms), and *Run workflow* with a version publishes an existing release to the registries that don't have it yet. They start working once the accounts and secrets are set up (`docs/DEVELOPER.md` → *Releasing*). +### Changed + +- Java: `Transport.Response` keeps the body as bytes (new constructor `Response(int, Map, byte[])` and `getBodyBytes()`; `getBody()` still decodes UTF-8), so binary documents download intact; `JdkHttpTransport` reads bytes. `HtmlDocument.content(Segment)` is public. Kotlin: `HttpResponseData` gets `bodyBytes` and `HttpResponseData.ofBytes(status, headers, bytes)` for the same reason. Existing transports keep working. + ## 0.7.0 — 2026-11-26 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index ed61f30..dc44f50 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,7 +26,8 @@ Wherever the docs or a README mention the API key, show both links: "No Supertex - **Rich text:** each `data-st-id` element is translated on its own: one per paragraph with inline tags, never one per formatted run. - **Languages:** only the codes `GET features` lists (`spec/languages.json`): 32 bare sources; 41 targets, regional only for de/en/fr/it/pt (`de-CH`, `en-US`), script for zh/sr (`zh-Hans`, `sr-Latn`), `gsw-u-sd-chzh`/`chbe`, bare for the rest (`es`, `nl`, `sl`). Anything else: HTTP 404 `INVALID_LANGUAGE_PAIR`. Politeness on a target without it (en, gsw, rm, sq, sr): HTTP 400 `FEATURE_ERROR`. **Defaults only where obvious:** the SDK resolves a CMS target by the plugin's mapping (a combo box per CMS language, `suggestTarget` preselected), else an exact match (case, `_`/`-`), else a default (`defaultTargets`: bare de/en/fr/it/pt → `de-DE`/`en-US`/`fr-FR`/`it-IT`/`pt-PT`, zh → `zh-Hans`, sr → `sr-Latn`, zh-TW/HK/MO → `zh-Hant`, zh-CN/SG → `zh-Hans`, a region of a bare target → the bare target: `es-ES` → `es`), else `unsupported_language`. Nothing else is guessed (`en-IE`, `de-LI`, `gsw`, `sr-RS` need a mapping). The client sends codes as given. - **Translation files:** Supertext's web app keeps an uploaded HTML file's `` (the `supertext:*` metas) and the `data-st-id` attributes, so `TranslationFiles` HTML exports import back unchanged (confirmed October 2026). -- **Versioned API:** everything API-bound is in the `v1` namespace of each SDK; a later API version gets `v2` next to it (and `spec/v2/`). +- **Versioned API:** everything API-bound is in the `v1` namespace of each SDK; Supertext's platform API is `v2` next to it (`spec/v2/`, `stand-in/stand-in-v2.mjs`, `conformance.mjs --v2`). A behaviour change to v2 also touches all six SDKs. +- **API v2 (platform API, November 2026):** base `https://api-platform.supertext.com/v1/`, `Authorization: Bearer st_live_…` (strip a pasted `Bearer `). Errors are problem+json (`code`, `detail`, `error_id`; 402 `reason`), e.g. 401 `api_key_invalid`. `translate/ai/text` takes ≤ 10,000 characters (`tag_handling: html` for HTML segments); longer segments go through `translate/ai/file` as HTML. Key check: `GET account`. Webhooks: Standard Webhooks (HMAC-SHA256, `whsec_` base64 secret, 300 s). **Commando Center:** the SDK only provides the API key check (`checkApiKey()`, `apiKeyFingerprint`, `ApiKeyCheck`; `spec/api-key-check.json`) and `SDK_VERSION`. Version reports and the ping endpoint live in **Supertext Plugin Health** (Commando-Center-Supertext-Translation → `plugin-health/`), which calls exactly these: never rename them or the check's fields (`status`, `checkedAt`, `httpStatus`, `errorCode`, `fingerprint`). There is no `spec/commando/` here any more. diff --git a/README.md b/README.md index 368c4fa..04190e7 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ You need a Supertext API key. No Supertext account yet? Create one at [supertext PHP is on Packagist, Python on PyPI and .NET on NuGet (from 0.6.0). npm and Maven Central (Java, Kotlin) aren't set up yet; until they are, use the files attached to a [release](https://github.com/Supertext/Supertext-API-SDK-Guide/releases) or build from this repository. -All six offer the same things, named the way each language expects, in a **`v1` namespace** for the API version (TypeScript `supertext-sdk/v1`, PHP `Supertext\Sdk\V1`, Python `supertext.v1`, .NET `Supertext.Sdk.V1`, Java and Kotlin `com.supertext.sdk.v1`), so a later API version can sit next to it: +All six offer the same things, named the way each language expects, in a **`v1` namespace** for the API version (TypeScript `supertext-sdk/v1`, PHP `Supertext\Sdk\V1`, Python `supertext.v1`, .NET `Supertext.Sdk.V1`, Java and Kotlin `com.supertext.sdk.v1`), with API v2 next to it (below): - `translateTexts(segments, target, source?, politeness?)`: many keyed texts (plain or HTML) in one go, split into documents under the size limit, translated one after the other, read back by key. - `translateHtml(html, target, source?, politeness?)`: one HTML document, the full round trip. @@ -35,6 +35,8 @@ All six offer the same things, named the way each language expects, in a **`v1` - One error type with stable codes (`authentication_failure`, `invalid_language_pair`, `quota_exceeded`, …) to show users a message in their language. - Built in: the `Supertext-Auth-Key` header (pasted prefixes stripped), the exact multipart upload the API accepts, HTTP 429 retries with `Retry-After`, polling with a timeout, and deleting the file afterwards, also after errors. +**API v2** (Supertext's platform API, `https://api-platform.supertext.com/v1/`, workspace keys `st_live_…`) is in a **`v2` namespace** next to it (TypeScript `supertext-sdk/v2`, PHP `Supertext\Sdk\V2`, Python `supertext.v2`, .NET `Supertext.Sdk.V2`, Java and Kotlin `com.supertext.sdk.v2`): `translateTexts` with the same keyed segments, now as direct text requests (10,000 characters each, HTML with `tag_handling`); `translateText`, AI translation of DOCX, PPTX, XLSX, PDF and other documents (`translateFile`), language detection, quotes, human review (`orderFusedText`, `orderFusedFile`), the account, webhooks with a signature check (`verifyWebhook`), and errors from Supertext's problem answers (`insufficient_credit`, `invalid_request`, …). See the [guide](docs/integration-guide.md#16-api-v2-the-supertext-platform-api). + Quick look (TypeScript; the others are in their READMEs): ```ts diff --git a/docs/DEVELOPER.md b/docs/DEVELOPER.md index 9026ac9..ea1a23e 100644 --- a/docs/DEVELOPER.md +++ b/docs/DEVELOPER.md @@ -7,8 +7,10 @@ For people working on this repository. To build an integration, read the [integr ``` docs/ integration guide, API reference, this file spec/ shared test vectors (JSON) every SDK must pass +spec/v2/ the same for API v2, with Supertext's openapi.json stand-in/stand-in.mjs stand-in for the Supertext API (Node, no dependencies) -stand-in/conformance.mjs runs an SDK's conformance program against the stand-in +stand-in/stand-in-v2.mjs stand-in for API v2 (api-platform.supertext.com) +stand-in/conformance.mjs runs an SDK's conformance program against the stand-in (--v2: API v2) sdk/typescript/ npm supertext-sdk sdk/php/ Packagist supertext/supertext-sdk (composer.json is at the repo root) sdk/python/ PyPI supertext-sdk (import supertext) @@ -20,8 +22,8 @@ sdk/kotlin/ Maven com.supertext:supertext-sdk-kotlin ## How the SDKs stay the same 1. **The spec is the source of truth.** Behaviour is defined by the vectors in [`spec/`](../spec/) (each file's `description` states the rules) and summarised in the integration guide. Every SDK's tests load the vector files directly from `spec/`. -2. **Conformance.** Every SDK has a small conformance program (`examples/conformance.*`): it reads a request as JSON on stdin, calls `translateTexts` against `SUPERTEXT_API_URL`/`SUPERTEXT_API_KEY` and prints the result as JSON. `node stand-in/conformance.mjs -- ` runs the scenarios in [`spec/conformance.json`](../spec/conformance.json) against a fresh stand-in each (429 retry, language codes sent as given, key prefix, auth failure, failed translation, file deleted, blank input, a code Supertext doesn't offer, politeness where it isn't offered). -3. **Same API, idiomatic names, versioned.** Everything that talks to the API lives in a `v1` namespace (TypeScript `supertext-sdk/v1` / `v1.…`, PHP `Supertext\Sdk\V1`, Python `supertext.v1`, .NET `Supertext.Sdk.V1`, Java and Kotlin `com.supertext.sdk.v1`); only the SDK version (`SDK_VERSION`, `SdkInfo`), the generic HTTP layer and the translation files (`TranslationFiles`: TypeScript `supertext-sdk`, PHP `Supertext\Sdk\Files`, Python `supertext.files`, .NET `Supertext.Sdk.Files`, Java and Kotlin `com.supertext.sdk.files`; they don't call the API) are outside it. A later API version gets `v2` next to it, and `spec/` then gets a `v2/` folder. Inside: `translateTexts`, `translateHtml`, the single steps, `getFeatures`, `Languages`, `HtmlDocument`, one error type with the fixed string codes, and the review service's `pendingCorrections`/`acknowledgeCorrections` (`Correction`). The translation files have their own error type (`invalid_job`, `invalid_file`, `missing_metadata`, `too_large`). Durations are milliseconds in TypeScript and seconds (or `TimeSpan`/`Duration`) elsewhere; the defaults are the same (poll 2 s, timeout 180 s, request timeout 30 s, 4 retries, 900,000 characters per document). +2. **Conformance.** Every SDK has a small conformance program (`examples/conformance.*`): it reads a request as JSON on stdin, calls `translateTexts` against `SUPERTEXT_API_URL`/`SUPERTEXT_API_KEY` and prints the result as JSON. `node stand-in/conformance.mjs -- ` runs the scenarios in [`spec/conformance.json`](../spec/conformance.json) against a fresh stand-in each (429 retry, language codes sent as given, key prefix, auth failure, failed translation, file deleted, blank input, a code Supertext doesn't offer, politeness where it isn't offered). API v2 has its own program (`examples/conformance-v2.*`, `ConformanceV2`) and scenarios ([`spec/v2/conformance.json`](../spec/v2/conformance.json)): `node stand-in/conformance.mjs --v2 -- ` runs them against `stand-in/stand-in-v2.mjs` (429 retry and `Bearer` prefix, the file fallback for long segments, invalid key, no credit, a pair Supertext rejects, a failed translation, blank input). +3. **Same API, idiomatic names, versioned.** Everything that talks to the API lives in a `v1` namespace (TypeScript `supertext-sdk/v1` / `v1.…`, PHP `Supertext\Sdk\V1`, Python `supertext.v1`, .NET `Supertext.Sdk.V1`, Java and Kotlin `com.supertext.sdk.v1`); only the SDK version (`SDK_VERSION`, `SdkInfo`), the generic HTTP layer and the translation files (`TranslationFiles`: TypeScript `supertext-sdk`, PHP `Supertext\Sdk\Files`, Python `supertext.files`, .NET `Supertext.Sdk.Files`, Java and Kotlin `com.supertext.sdk.files`; they don't call the API) are outside it. API v2 (Supertext's platform API, `https://api-platform.supertext.com/v1/`) is in a `v2` namespace next to it (TypeScript `supertext-sdk/v2`, PHP `Supertext\Sdk\V2`, Python `supertext.v2`, .NET `Supertext.Sdk.V2`, Java and Kotlin `com.supertext.sdk.v2`) with its vectors in `spec/v2/`; it reuses v1's `Segment`, `Politeness`, `Languages`, `HtmlDocument` (for the file fallback), the retry delays and `ApiKeyCheck`, and has its own client, error type (codes in `spec/v2/errors.json`) and webhook check. Inside v1: `translateTexts`, `translateHtml`, the single steps, `getFeatures`, `Languages`, `HtmlDocument`, one error type with the fixed string codes, and the review service's `pendingCorrections`/`acknowledgeCorrections` (`Correction`). The translation files have their own error type (`invalid_job`, `invalid_file`, `missing_metadata`, `too_large`). Durations are milliseconds in TypeScript and seconds (or `TimeSpan`/`Duration`) elsewhere; the defaults are the same (poll 2 s, timeout 180 s, request timeout 30 s, 4 retries, 900,000 characters per document). 4. **No runtime dependencies** (the .NET SDK uses only the base library, the Kotlin SDK only the Kotlin standard library). Each SDK has an injectable HTTP layer, sleep and clock for tests. The translation files parse XML with a small hand-written parser in every SDK (no DTDs, no recursion), so uploaded files behave the same everywhere and nothing is ever expanded. To change behaviour: change the vector (or add one), then every SDK and its tests, the guide and `CHANGELOG.md`, in one commit. @@ -32,16 +34,16 @@ To change behaviour: change the vector (or add one), then every SDK and its test | SDK | Commands | | --- | --- | -| TypeScript | `cd sdk/typescript && npm ci && npm run typecheck && npm test && npm run build`, then `node stand-in/conformance.mjs -- node sdk/typescript/examples/conformance.mjs` | -| PHP | `composer install`, `vendor/bin/phpunit -c sdk/php/phpunit.xml.dist`, `vendor/bin/phpstan analyse -c sdk/php/phpstan.neon` (level 8), `node stand-in/conformance.mjs -- php sdk/php/examples/conformance.php` | -| Python | `cd sdk/python && pip install pytest mypy ruff build && ruff check . && ruff format --check . && mypy --strict && pytest`, then `node stand-in/conformance.mjs -- python3 sdk/python/examples/conformance.py` | -| .NET | `dotnet build sdk/dotnet -warnaserror && dotnet test sdk/dotnet`, `dotnet build sdk/dotnet/examples/Conformance -c Release`, then `node stand-in/conformance.mjs -- dotnet sdk/dotnet/examples/Conformance/bin/Release/net10.0/Conformance.dll`. The tests run on .NET 10 and 11 (xUnit v3 on Microsoft.Testing.Platform; the root `global.json` opts `dotnet test` into its runner) | -| Java | `cd sdk/java && mvn -B verify`, then `node ../../stand-in/conformance.mjs -- java -cp target/classes examples/Conformance.java` | -| Kotlin | `cd sdk/kotlin && mvn -B verify`, then `node ../../stand-in/conformance.mjs -- java -cp 'target/classes:target/test-classes:target/lib/*' ConformanceKt` (`verify` compiles `examples/Conformance.kt` with the tests and copies the Kotlin standard library to `target/lib`) | +| TypeScript | `cd sdk/typescript && npm ci && npm run typecheck && npm test && npm run build`, then `node stand-in/conformance.mjs -- node sdk/typescript/examples/conformance.mjs` and `node stand-in/conformance.mjs --v2 -- node sdk/typescript/examples/conformance-v2.mjs` | +| PHP | `composer install`, `vendor/bin/phpunit -c sdk/php/phpunit.xml.dist`, `vendor/bin/phpstan analyse -c sdk/php/phpstan.neon` (level 8), `node stand-in/conformance.mjs -- php sdk/php/examples/conformance.php`, `node stand-in/conformance.mjs --v2 -- php sdk/php/examples/conformance-v2.php` | +| Python | `cd sdk/python && pip install pytest mypy ruff build && ruff check . && ruff format --check . && mypy --strict && pytest`, then `node stand-in/conformance.mjs -- python3 sdk/python/examples/conformance.py` and `node stand-in/conformance.mjs --v2 -- python3 sdk/python/examples/conformance_v2.py` | +| .NET | `dotnet build sdk/dotnet -warnaserror && dotnet test sdk/dotnet`, `dotnet build sdk/dotnet/examples/Conformance -c Release`, then `node stand-in/conformance.mjs -- dotnet sdk/dotnet/examples/Conformance/bin/Release/net10.0/Conformance.dll`; the same with `examples/ConformanceV2` and `--v2` for API v2. The tests run on .NET 10 and 11 (xUnit v3 on Microsoft.Testing.Platform; the root `global.json` opts `dotnet test` into its runner) | +| Java | `cd sdk/java && mvn -B verify`, then `node ../../stand-in/conformance.mjs -- java -cp target/classes examples/Conformance.java` and `node ../../stand-in/conformance.mjs --v2 -- java -cp target/classes examples/ConformanceV2.java` | +| Kotlin | `cd sdk/kotlin && mvn -B verify`, then `node ../../stand-in/conformance.mjs -- java -cp 'target/classes:target/test-classes:target/lib/*' ConformanceKt`, and with `--v2` and `ConformanceV2Kt` for API v2 (`verify` compiles `examples/Conformance.kt` and `ConformanceV2.kt` with the tests and copies the Kotlin standard library to `target/lib`) | CI matrix: Node 22/24/26, PHP 8.2–8.6 (plus PHP 8.3 without ext-curl, which only the built-in transport needs), Python 3.11–3.15, .NET 10/11, Java 11/17/21/25 (Java and Kotlin). Minimum versions follow vendor support: a runtime is dropped when it reaches end of life (Java 11 stays while vendors such as Eclipse Temurin still support it). -Nothing in the SDK tests talks to the live API; only the language list check below does. Before a release, run each SDK's conformance program once against the live API with a test key (`SUPERTEXT_API_URL=https://api.supertext.com/v1/`, `SUPERTEXT_API_KEY=…`, a request with a few real sentences on stdin) and check the translations. +Nothing in the SDK tests talks to the live API; only the language list check below and the *Live API v2* workflow do. Before a release, run each SDK's conformance program once against the live API with a test key (`SUPERTEXT_API_URL=https://api.supertext.com/v1/`, `SUPERTEXT_API_KEY=…`, a request with a few real sentences on stdin) and check the translations; for API v2 the same with a workspace key and `SUPERTEXT_API_URL=https://api-platform.supertext.com/v1/` (text requests cost credit: keep it short). The *Live API v2* workflow (`.github/workflows/live-v2.yml`, weekly, by hand and on changes to the TypeScript v2 client) runs `scripts/live-v2.mjs` with the secret `SUPERTEXT_API_KEY_V2`: key check, account, features, a quote and one small translation (`SUPERTEXT_API_KEY_V2=… node scripts/live-v2.mjs` after `npm run build` in `sdk/typescript`). ## Code quality and security checks diff --git a/docs/api-reference.md b/docs/api-reference.md index 3d09c83..8d262cf 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -77,3 +77,27 @@ JSON body `{ "corrections": [{ "id", "version" }] }` (at most 1000): the plugin ## Commando Center (version reports) Not part of the Supertext API and not part of the SDKs: plugins report their versions with Supertext Plugin Health. The protocol (report schema, the plugin's ping endpoint) and Plugin Health are in [Commando-Center-Supertext-Translation](https://github.com/Supertext/Commando-Center-Supertext-Translation) (`docs/DEVELOPER.md` → *Report protocol*, `plugin-health/`). + +## API v2 (Supertext platform API) + +The newer API, in the SDKs' `v2` namespace (integration guide → *API v2*). Full description: [`spec/v2/openapi.json`](../spec/v2/openapi.json) (copy of `https://api-platform.supertext.com/v1/openapi.json`, November 2026) and Supertext's [documentation](https://www.supertext.com/en/neo/documentation/api). + +Base URL: `https://api-platform.supertext.com/v1/`. Headers: `Authorization: Bearer ` on every request, `Accept: application/json, application/problem+json`, `User-Agent` as in v1. No Supertext account yet? Create one at https://www.supertext.com/person/en/account/signin. Generate your API key at https://www.supertext.com/en/integrations/api (supertext.com → Integrations → API; requires the Admin role). + +| Endpoint | What it does | +| --- | --- | +| `GET account` | Cost-free: `workspace_id`, `workspace_name`, `api_key_name`, `api_key_prefix`, `api_key_expires_at`. The SDKs' key check uses it | +| `GET features` | Language pairs and features (`source_lang`, `target_lang` query filters), as in v1 | +| `POST translate/ai/text` (`/quote`) | JSON `{text: [...], target_lang, source_lang?, politeness? (more/less), glossary? {term: translation} (≤ 100), tag_handling? (none/xml/html)}`, ≤ 10,000 characters → `{translated_text: [...], detected_source_lang, enforced_terms, request_id}`; the quote answers `{character_count, prices}` | +| `POST translate/ai/file` (`/quote`) | Multipart: `file`, `target_lang`, `source_lang`, `politeness`, `glossary` (a JSON string), `use_ocr` → `202 {file_id}` | +| `GET translate/ai/file/{id}/status` | `{status: translating/done/error/deleted, error, estimated_duration_left_in_seconds, detected_source_lang}` | +| `GET translate/ai/file/{id}/translation` | The document (`Content-Disposition` names it); `202` while it isn't ready; 24 hours | +| `DELETE translate/ai/file/{id}` | Deletes the document and its translation | +| `POST detect-languages/text` / `file` (`/quote`) | `{detected_languages: [{lang_code, confidence, supports_translation}]}` | +| `POST translate/fused/text` / `file` (`/quote`) | Human review; `source_lang` required, `briefing`, `Idempotency-Key` header (text) → `202 {translation_id, briefing_applied, service_label}`; quote: `prices`, `estimated_duration_in_seconds`, `word_count` | +| `GET translate/fused/{text,file}/{id}/status`, `/translation` | `in_progress`/`completed`/`failed`; the translation `202` until delivered | +| `GET/POST webhooks`, `GET/PATCH/DELETE webhooks/{id}`, `POST webhooks/{id}/test` | Webhooks; the `secret` (`whsec_…`) only in the create answer; test at most every 5 s | + +**Errors** are `application/problem+json`: `{type, title, status, detail, code, error_id}` (402 adds `reason`), e.g. `401 {"code": "api_key_invalid", …}` (live API, November 2026). 401/403 key, 402 no credit, 404, 409, 413, 422 validation (language pairs, options), 429 rate limit (retried like v1), 5xx. SDK mapping: [`spec/v2/errors.json`](../spec/v2/errors.json). + +**Webhook deliveries** carry `webhook-id`, `webhook-timestamp` and `webhook-signature` (`v1,`, several separated by spaces) over `{id}.{timestamp}.{raw body}`, keyed with the base64-decoded part of the secret after `whsec_` ([Standard Webhooks](https://www.standardwebhooks.com/)); tolerance 300 s. SDK behaviour: [`spec/v2/webhooks.json`](../spec/v2/webhooks.json). diff --git a/docs/integration-guide.md b/docs/integration-guide.md index 9c10eb1..77f739f 100644 --- a/docs/integration-guide.md +++ b/docs/integration-guide.md @@ -21,7 +21,8 @@ Contents: 13. [Testing](#13-testing) 14. [The API key check and version reports](#14-the-api-key-check-and-version-reports) 15. [Translation files: XLIFF and HTML](#15-translation-files-xliff-and-html) -16. [Checklist](#16-checklist) +16. [API v2: the Supertext platform API](#16-api-v2-the-supertext-platform-api) +17. [Checklist](#17-checklist) The HTTP details are summarised in the [API reference](api-reference.md). @@ -358,7 +359,36 @@ An alternative to the API: the integration exports an item's segments as a file, **In the plugin UI:** *Export for translation* (format: XLIFF or HTML; target languages; for list views several items) and *Import translation* (file upload, then a summary: imported, skipped because the source changed, untranslated, invalid). File names like `--.xlf` help people keep files apart; the SDK doesn't depend on them. -## 16. Checklist +## 16. API v2: the Supertext platform API + +Supertext's newer API (documentation: [supertext.com/en/neo/documentation/api](https://www.supertext.com/en/neo/documentation/api), OpenAPI: [`spec/v2/openapi.json`](../spec/v2/openapi.json)) is very similar, at a new address and with more functions: text translation in one request without a document, AI translation of real documents (DOCX, PPTX, XLSX, PDF with OCR, SRT, …), language detection, quotes before anything is charged, human review ("fused" translations), the account behind a key, and webhooks. The SDKs have it as **`v2`** next to `v1` (TypeScript `supertext-sdk/v2`, PHP `Supertext\Sdk\V2`, Python `supertext.v2`, .NET `Supertext.Sdk.V2`, Java and Kotlin `com.supertext.sdk.v2`), so an integration moves when it's ready; both can be used side by side. Everything above about segments, rich text, writing back, security and testing applies unchanged. + +**What is different:** + +| | API v1 | API v2 | +| --- | --- | --- | +| Base URL | `https://api.supertext.com/v1/` | `https://api-platform.supertext.com/v1/` | +| Key | `Authorization: Supertext-Auth-Key ` | `Authorization: Bearer st_live_…` (a workspace key; a pasted `Bearer ` is stripped, blank = `missing_api_key`, nothing sent; [`spec/v2/auth-header.json`](../spec/v2/auth-header.json)) | +| Texts | packed into an HTML document, uploaded, polled | `POST translate/ai/text`: up to 10,000 characters per request, answered at once; HTML segments with `tag_handling: html` | +| Documents | HTML only | any supported format, `glossary`, `use_ocr` | +| Errors | `error_code` in a JSON body | `application/problem+json` with `code`, `detail`, `error_id` (and `reason` on 402) | +| Key check | `GET features` | `GET account` (cost-free; also returns workspace and key name) | + +No Supertext account yet? Create one at [supertext.com](https://www.supertext.com/person/en/account/signin). Generate your API key at [supertext.com → Integrations → API](https://www.supertext.com/en/integrations/api) (requires the Admin role); v2 takes the workspace keys (`st_live_…`) described in the [v2 documentation](https://www.supertext.com/en/neo/documentation/api). + +**`translateTexts` in v2** takes the same keyed segments as in v1 and returns the same keys in input order ([`spec/v2/batching.json`](../spec/v2/batching.json)): blank segments come back unchanged without being sent; plain-text segments go in `translate/ai/text` requests of at most 10,000 characters, HTML segments in separate requests with `tag_handling: html` (so each one is still translated on its own, section 7); a single segment longer than the limit goes through the file endpoint as an HTML document, exactly like v1. Language codes are sent as given: resolve CMS languages with `Languages` (section 6) first; a blank target is `unsupported_language` without a request. Politeness and the glossary (at most 100 terms) are passed through. + +**Single steps:** `translateText` (one request, with `detectedSourceLang` and the glossary terms enforced) and `quoteText`; `submitFile` → `getFileStatus`/`waitForFile` → `downloadFile` (`null` while not ready) → `deleteFile`, or all of it in `translateFile` (it always deletes, also after errors) and `translateHtml`; `quoteFile`; `detectLanguage`/`detectFileLanguage` and their quotes; `getAccount`, `getFeatures`, `validateApiKey`, `checkApiKey` (the same `ApiKeyCheck` as v1, fingerprint of the key without `Bearer`; [`spec/v2/api-key-check.json`](../spec/v2/api-key-check.json)). Names follow each language (`translate_texts`, `TranslateTextsAsync`). + +**Human review** (`orderFusedText`/`orderFusedFile`, `getFusedTextStatus`/`getFusedFileStatus`, `getFusedText`/`downloadFusedFile`, `quoteFusedText`/`quoteFusedFile`): a reviewer checks the AI translation; it can take hours, so don't wait in a request: store the `translationId`, then poll on a schedule or let a webhook tell you. The source language is required. Pass an `idempotencyKey` (for example the item and language) for text orders, so a retried request doesn't order twice. Always show the quote (`prices`, estimated duration) before ordering: orders are charged when accepted. + +**Webhooks** (`createWebhook`, `listWebhooks`, `getWebhook`, `updateWebhook`, `deleteWebhook`, `testWebhook`): the secret (`whsec_…`) is returned only by `createWebhook`; store it like the API key (it isn't in `toString`). Verify every delivery with `verifyWebhook` / `Webhooks.verify(secret, headers, rawBody)` before trusting it ([`spec/v2/webhooks.json`](../spec/v2/webhooks.json)): Standard Webhooks, HMAC-SHA256 over `webhook-id.webhook-timestamp.body` with the base64 part of the secret, constant-time comparison, timestamps more than 5 minutes off refused. Any failure is `invalid_webhook`: answer 400 and do nothing. Pass the raw body as received; parsing and re-serialising it breaks the signature. Treat a verified event as a hint and fetch the status, because deliveries can repeat or arrive out of order. + +**Errors** ([`spec/v2/errors.json`](../spec/v2/errors.json)): one error type per SDK (`SupertextException` / `SupertextError`) with these codes: `missing_api_key`, `authentication_failure` (401, 403), `insufficient_credit` (402: tell the user to top up their Supertext account), `invalid_request` (422: a language pair or option Supertext doesn't take), `unsupported_language` (blank code, nothing sent), `not_found`, `conflict` (409), `payload_too_large`, `too_many_requests`, `service_unavailable` (5xx), `unexpected_status`, `transport_error`, `incomplete_response`, `translation_error`, `file_deleted`, `timeout`, `invalid_webhook`. `detail` is Supertext's `detail` (else the answer without tags, at most 200 characters), `apiErrorCode` its `code`, `errorId` its `error_id` (quote it to Supertext support), `reason` the 402 reason. HTTP 429 is retried as in v1 (section 9). The key never appears in an error. + +**Testing:** [`stand-in/stand-in-v2.mjs`](../stand-in/stand-in-v2.mjs) answers the v2 endpoints with real translations of the sample texts and has the same test hooks as the v1 stand-in (key `invalid` → 401, `no-credit` → 402, a 429 on the first billable request); every SDK passes `node stand-in/conformance.mjs --v2 -- ` ([`spec/v2/conformance.json`](../spec/v2/conformance.json)). + +## 17. Checklist - [ ] `Authorization: Supertext-Auth-Key `, pasted prefix stripped, blank key = no request - [ ] Language mapping per CMS language (combo box of the Supertext targets, `suggestTarget` preselected), defaults only from `Languages.defaultTarget`; `unsupported_language` shown with where to map it; formal/informal only where the target supports it @@ -375,3 +405,4 @@ An alternative to the API: the integration exports an item's segments as a file, - [ ] Version reports and the ping endpoint with Supertext Plugin Health (*Send version information to Supertext* setting, on by default; reports from server code only) - [ ] Translation files (if offered): `TranslationFiles` for both formats, the item found by `reference`, segments collected again for the import, `source_changed` asked about, upload size and permissions checked - [ ] Tests with a fake HTTP layer and against the stand-in; a manual round against the live API +- [ ] API v2 (if used): `Bearer` workspace key, `insufficient_credit` shown with what to do, quotes shown before human-review orders, webhooks verified with the raw body diff --git a/scripts/compare-links.mjs b/scripts/compare-links.mjs new file mode 100644 index 0000000..1982ada --- /dev/null +++ b/scripts/compare-links.mjs @@ -0,0 +1,69 @@ +// Compares how API v1 (Classic) and API v2 (platform) keep links and formatting in HTML segments: +// each sample sentence is translated by both into a few languages and printed side by side, with +// whether the links (href values, as a set and in order) and the inline tags came back intact. +// Diagnostic only: it always exits 0. Needs a built sdk/typescript and SUPERTEXT_API_KEY (v1) +// and/or SUPERTEXT_API_KEY_V2 (v2). +// +// SUPERTEXT_API_KEY=… SUPERTEXT_API_KEY_V2=… node scripts/compare-links.mjs +import { SupertextClient as V1 } from '../sdk/typescript/dist/v1/index.js' +import { SupertextClient as V2 } from '../sdk/typescript/dist/v2/index.js' + +const SAMPLES = [ + ['two links in one list', '

Damaged on arrival? See damaged chocolate, the first step or our shop.

'], + ['one link mid-sentence', '

You can return any order within 14 days of delivery.

'], + ['link at the start', '

Free shipping applies to all orders over CHF 50.

'], + ['two adjacent links', '

Please read our terms and conditions and our privacy policy before ordering.

'], + ['link inside bold', '

Questions? Call us or write to us any time.

'], + ['bold, italic and a link', '

Our new autumn pralines are in the shop now.

'], + ['long link text', '

Before you order, read our short guide to choosing the right chocolate for your occasion.

'], + ['link on one word', '

Track your parcel here.

'], + ['three links, short sentence', '

Pay with card, TWINT or invoice.

'], + ['link with a list', ''], +] +const TARGETS = ['de-CH', 'fr-CH', 'it-CH'] + +const hrefs = (html) => [...html.matchAll(/href="([^"]*)"/g)].map((m) => m[1]) +const tags = (html) => [...html.matchAll(/<\/?([a-z]+)/g)].map((m) => m[1]).sort().join(',') +function verdict(source, out) { + const s = hrefs(source) + const t = hrefs(out) + if ([...s].sort().join(' ') !== [...t].sort().join(' ')) return `LINKS ${t.length}/${s.length}: ${t.join(' ')}` + if (tags(source) !== tags(out)) return `TAGS ${tags(out)} (source ${tags(source)})` + return s.join(' ') === t.join(' ') ? 'ok' : `ok, order ${t.join(' ')}` +} + +const clients = [] +if (process.env.SUPERTEXT_API_KEY) clients.push(['v1', new V1(process.env.SUPERTEXT_API_KEY, { userAgent: 'Supertext-API-SDK-Guide-compare' })]) +if (process.env.SUPERTEXT_API_KEY_V2) clients.push(['v2', new V2(process.env.SUPERTEXT_API_KEY_V2, { userAgent: 'Supertext-API-SDK-Guide-compare' })]) +if (clients.length === 0) { + console.log('No key set: nothing to compare.') + process.exit(0) +} + +const tally = Object.fromEntries(clients.map(([name]) => [name, { ok: 0, problems: 0 }])) +for (const target of TARGETS) { + // One request per API and language (v1: one document; v2: text requests), so the rate limit isn't a problem. + const segments = Object.fromEntries(SAMPLES.map(([name, html]) => [name, { text: html, html: true }])) + const results = {} + for (const [name, client] of clients) { + try { + results[name] = await client.translateTexts(segments, target, { sourceLang: 'en' }) + } catch (error) { + results[name] = null + console.log(`${name} ${target}: ${error.code ?? error} ${error.detail ?? ''}`) + } + } + for (const [sample, source] of SAMPLES) { + console.log(`\n=== ${target} · ${sample}\n en ${source}`) + for (const [name] of clients) { + const out = results[name]?.[sample] + if (out === undefined) continue + const v = verdict(source, out) + tally[name][v.startsWith('ok') ? 'ok' : 'problems']++ + console.log(` ${name} ${out}\n → ${v}`) + } + } +} +console.log('\nSummary (links and tags intact, per API):') +for (const [name, t] of Object.entries(tally)) console.log(` ${name}: ${t.ok} ok, ${t.problems} with problems`) +process.exit(0) diff --git a/scripts/live-v2.mjs b/scripts/live-v2.mjs new file mode 100644 index 0000000..4af91cc --- /dev/null +++ b/scripts/live-v2.mjs @@ -0,0 +1,83 @@ +// Live check of the TypeScript v2 client against Supertext's platform API: key check, account, features, +// a quote, one small translateTexts (plain and HTML; costs a few characters of credit) and the error for a +// wrong key. Needs SUPERTEXT_API_KEY_V2 and a built sdk/typescript (npm run build). Exit code 1 on a failure. +// +// SUPERTEXT_API_KEY_V2=… node scripts/live-v2.mjs +import { SupertextClient, SupertextError } from '../sdk/typescript/dist/v2/index.js' + +const key = process.env.SUPERTEXT_API_KEY_V2 ?? '' +if (!key) { + console.error('SUPERTEXT_API_KEY_V2 is not set') + process.exit(2) +} +const client = new SupertextClient(key, { userAgent: 'Supertext-API-SDK-Guide-live-check' }) +let failed = 0 +async function check(name, run) { + try { + const note = await run() + console.log(`ok ${name}${note ? `: ${note}` : ''}`) + } catch (error) { + failed++ + const e = error instanceof SupertextError ? `${error.code} (HTTP ${error.status ?? '-'}) ${error.detail ?? ''}` : String(error) + console.log(`FAIL ${name}: ${e}`) + } +} +const expect = (ok, message) => { + if (!ok) throw new Error(message) +} + +await check('checkApiKey', async () => { + const c = await client.checkApiKey() + expect(c.status === 'ok', `status ${c.status}, HTTP ${c.httpStatus}, ${c.errorCode ?? ''}`) +}) +await check('getAccount', async () => { + const a = await client.getAccount() + expect(a.workspaceId !== '', 'no workspace id') + return `key prefix ${a.apiKeyPrefix}` +}) +await check('getFeatures', async () => { + const f = await client.getFeatures({ sourceLang: 'en', targetLang: 'de-CH' }) + expect(f.length > 0, 'en → de-CH not listed') + return f[0].features.join(', ') +}) +await check('quoteText', async () => { + const q = await client.quoteText(['Hello world'], 'de-CH', { sourceLang: 'en' }) + expect(q.characterCount > 0, `character count ${q.characterCount}`) + return `${q.characterCount} characters` +}) +await check('translateTexts', async () => { + const out = await client.translateTexts( + { title: 'Good morning', body: { text: '

Our new shop opens on Monday.

', html: true }, blank: ' ' }, + 'de-CH', + { sourceLang: 'en' }, + ) + expect(Object.keys(out).join() === 'title,body,blank', `keys ${Object.keys(out).join()}`) + expect(out.blank === ' ', 'blank segment changed') + expect(out.title.trim() !== '' && out.title !== 'Good morning', `title ${JSON.stringify(out.title)}`) + expect(/[^<]+<\/b>/.test(out.body), `markup lost: ${out.body}`) + return `${JSON.stringify(out.title)} / ${out.body}` +}) +// A paragraph with three links, two of them in one sentence (the HubSpot plugin's sample article): +// every link must come back once, with its own text. +const LINKS = + '

Damaged on arrival? See damaged chocolate, the first step or our shop.

' +const hrefs = (html) => [...html.matchAll(/href="([^"]*)"/g)].map((m) => m[1]) +for (const target of ['de-CH', 'fr-CH', 'it-CH']) { + await check(`links kept (${target})`, async () => { + const out = await client.translateTexts({ p: { text: LINKS, html: true } }, target, { sourceLang: 'en' }) + console.log(` ${out.p}`) + const got = hrefs(out.p).sort().join(' ') + expect(got === hrefs(LINKS).sort().join(' '), `links ${hrefs(out.p).join(' ')}`) + }) +} +await check('wrong key', async () => { + try { + await new SupertextClient('st_live_wrong').getAccount() + } catch (error) { + expect(error instanceof SupertextError && error.code === 'authentication_failure', `got ${error?.code ?? error}`) + expect(!String(error.message).includes('st_live_wrong'), 'key in message') + return `${error.status} ${error.apiErrorCode ?? ''}` + } + throw new Error('no error') +}) +process.exit(failed ? 1 : 0) diff --git a/sdk/dotnet/README.md b/sdk/dotnet/README.md index b51771e..3cba25f 100644 --- a/sdk/dotnet/README.md +++ b/sdk/dotnet/README.md @@ -2,7 +2,7 @@ Client for the Supertext AI translation API: translate HTML and texts, with the supported languages, rate-limit retries and HTML packing handled for you. NuGet package `Supertext.Sdk`, `net10.0` (runs on .NET 10 and later; tested on .NET 10 and 11), no dependencies. -Everything that talks to the API v1 is in the namespace **`Supertext.Sdk.V1`**. A later API version gets `Supertext.Sdk.V2` next to it, so an integration can move at its own pace. Only the SDK's version, `Supertext.Sdk.SdkInfo.Version`, is outside the versioned namespace. +Everything that talks to the API v1 is in the namespace **`Supertext.Sdk.V1`**. API v2 is in `Supertext.Sdk.V2` next to it (see [API v2](#api-v2)), so an integration can move at its own pace. Only the SDK's version, `Supertext.Sdk.SdkInfo.Version`, is outside the versioned namespace. It packages what Supertext's CMS plugins learned against the live API (October 2026). Background and the protocol: [integration guide](../../docs/integration-guide.md). @@ -135,6 +135,28 @@ Version reports to the Supertext Commando Center and its ping endpoint are [Supe Also public: `SupertextClient.AuthHeader(key)`, `SupertextClient.RetryDelayMs(attempt, retryAfter)`, `HtmlDocument.Build` / `Parse` if you build documents yourself. +## API v2 + +Supertext's platform API (`https://api-platform.supertext.com/v1/`, `Authorization: Bearer st_live_…`) is in `Supertext.Sdk.V2`, next to v1. `TranslateTextsAsync` takes the same segments and returns the same keys; texts go in direct requests of up to 10,000 characters (HTML segments with `tag_handling` html), a longer segment through the file endpoint. No Supertext account yet? Create one at https://www.supertext.com/person/en/account/signin. Generate your API key at https://www.supertext.com/en/integrations/api (supertext.com → Integrations → API; requires the Admin role); API v2 takes the workspace keys (`st_live_…`) described in [Supertext's v2 documentation](https://www.supertext.com/en/neo/documentation/api). + +```csharp +using Supertext.Sdk.V1; // Segment, Politeness +using V2 = Supertext.Sdk.V2; + +var client = new V2.SupertextClient(Environment.GetEnvironmentVariable("SUPERTEXT_API_KEY")); +var german = await client.TranslateTextsAsync(new Dictionary +{ + ["title"] = new("Hello & welcome"), + ["body"] = new("

Our new shop opens on Monday.

", Html: true), +}, "de-CH", sourceLang: "en", politeness: Politeness.More, glossary: new Dictionary { ["shop"] = "Laden" }); +var docx = await client.TranslateFileAsync(await File.ReadAllBytesAsync("offer.docx"), "offer.docx", "fr-CH"); // Content, FileName + +// In your webhook endpoint: the raw body, before parsing it +var evt = V2.Webhooks.Verify(secret, request.Headers.Select(h => KeyValuePair.Create(h.Key, h.Value.ToString())), rawBody); +``` + +What else is there: `TranslateTextAsync` (one request, with the detected source language and enforced glossary terms) and `QuoteTextAsync`; documents with `TranslateFileAsync` (upload, wait, download, always delete) or the single steps `SubmitFileAsync`, `GetFileStatusAsync`, `WaitForFileAsync`, `DownloadFileAsync` (`null` while not ready), `DeleteFileAsync`, and `QuoteFileAsync`; `DetectLanguageAsync`, `DetectFileLanguageAsync` and their quotes; human review with `QuoteFusedTextAsync`/`OrderFusedTextAsync`, `GetFusedTextStatusAsync`, `GetFusedTextAsync` (and the same for files: `OrderFusedFileAsync`, `GetFusedFileStatusAsync`, `DownloadFusedFileAsync`); `GetAccountAsync`, `GetFeaturesAsync`, `ValidateApiKeyAsync`, `CheckApiKeyAsync` (same `ApiKeyCheck` as v1, on `GET account`); webhooks (`CreateWebhookAsync`, whose secret is returned only once, `ListWebhooksAsync`, `GetWebhookAsync`, `UpdateWebhookAsync`, `DeleteWebhookAsync`, `TestWebhookAsync`). Errors are one type with the codes of `spec/v2/errors.json` (`insufficient_credit`, `invalid_request`, `authentication_failure`, …) and Supertext's `detail`, `ApiErrorCode`, `ErrorId` and `Reason` (`SupertextException`). More: [integration guide → API v2](../../docs/integration-guide.md#16-api-v2-the-supertext-platform-api). + ## Translation files For texts translated outside the API (a CAT tool, a translator, Supertext's web app), `Supertext.Sdk.Files.TranslationFiles` exports segments as an XLIFF 1.2 file (one `` per job) or as an HTML file (the `HtmlDocument` document with the job's metadata in its head), and imports them again. It isn't tied to an API version and makes no requests (test vectors: `spec/translation-file.json`). diff --git a/sdk/dotnet/Supertext.Sdk.sln b/sdk/dotnet/Supertext.Sdk.sln index d922585..5e5f2a2 100644 --- a/sdk/dotnet/Supertext.Sdk.sln +++ b/sdk/dotnet/Supertext.Sdk.sln @@ -1,45 +1,52 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FD50D7C1-C11D-4EBD-AE7D-39BD0C80E373}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Supertext.Sdk", "src\Supertext.Sdk\Supertext.Sdk.csproj", "{F4E543FD-6DA1-427C-BF54-3E91FEC33F74}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{C1E7FAFD-E60E-4D27-BC5F-77599EB3407E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Supertext.Sdk.Tests", "tests\Supertext.Sdk.Tests\Supertext.Sdk.Tests.csproj", "{FEAFA139-A4F6-469D-A16D-39E2539F91DF}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{FAE6ED0E-7676-41E7-82C6-87939E540C46}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Conformance", "examples\Conformance\Conformance.csproj", "{7A121F38-6688-4F5D-947D-92C24E1175A1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Release|Any CPU.Build.0 = Release|Any CPU - {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Release|Any CPU.Build.0 = Release|Any CPU - {7A121F38-6688-4F5D-947D-92C24E1175A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7A121F38-6688-4F5D-947D-92C24E1175A1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7A121F38-6688-4F5D-947D-92C24E1175A1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7A121F38-6688-4F5D-947D-92C24E1175A1}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {F4E543FD-6DA1-427C-BF54-3E91FEC33F74} = {FD50D7C1-C11D-4EBD-AE7D-39BD0C80E373} - {FEAFA139-A4F6-469D-A16D-39E2539F91DF} = {C1E7FAFD-E60E-4D27-BC5F-77599EB3407E} - {7A121F38-6688-4F5D-947D-92C24E1175A1} = {FAE6ED0E-7676-41E7-82C6-87939E540C46} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FD50D7C1-C11D-4EBD-AE7D-39BD0C80E373}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Supertext.Sdk", "src\Supertext.Sdk\Supertext.Sdk.csproj", "{F4E543FD-6DA1-427C-BF54-3E91FEC33F74}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{C1E7FAFD-E60E-4D27-BC5F-77599EB3407E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Supertext.Sdk.Tests", "tests\Supertext.Sdk.Tests\Supertext.Sdk.Tests.csproj", "{FEAFA139-A4F6-469D-A16D-39E2539F91DF}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{FAE6ED0E-7676-41E7-82C6-87939E540C46}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Conformance", "examples\Conformance\Conformance.csproj", "{7A121F38-6688-4F5D-947D-92C24E1175A1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConformanceV2", "examples\ConformanceV2\ConformanceV2.csproj", "{3B8E2C51-9D4F-4A6E-8C17-5F2A9D0B6E43}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F4E543FD-6DA1-427C-BF54-3E91FEC33F74}.Release|Any CPU.Build.0 = Release|Any CPU + {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FEAFA139-A4F6-469D-A16D-39E2539F91DF}.Release|Any CPU.Build.0 = Release|Any CPU + {7A121F38-6688-4F5D-947D-92C24E1175A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A121F38-6688-4F5D-947D-92C24E1175A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7A121F38-6688-4F5D-947D-92C24E1175A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7A121F38-6688-4F5D-947D-92C24E1175A1}.Release|Any CPU.Build.0 = Release|Any CPU + {3B8E2C51-9D4F-4A6E-8C17-5F2A9D0B6E43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3B8E2C51-9D4F-4A6E-8C17-5F2A9D0B6E43}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3B8E2C51-9D4F-4A6E-8C17-5F2A9D0B6E43}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3B8E2C51-9D4F-4A6E-8C17-5F2A9D0B6E43}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {F4E543FD-6DA1-427C-BF54-3E91FEC33F74} = {FD50D7C1-C11D-4EBD-AE7D-39BD0C80E373} + {FEAFA139-A4F6-469D-A16D-39E2539F91DF} = {C1E7FAFD-E60E-4D27-BC5F-77599EB3407E} + {7A121F38-6688-4F5D-947D-92C24E1175A1} = {FAE6ED0E-7676-41E7-82C6-87939E540C46} + {3B8E2C51-9D4F-4A6E-8C17-5F2A9D0B6E43} = {FAE6ED0E-7676-41E7-82C6-87939E540C46} + EndGlobalSection +EndGlobal diff --git a/sdk/dotnet/examples/ConformanceV2/ConformanceV2.csproj b/sdk/dotnet/examples/ConformanceV2/ConformanceV2.csproj new file mode 100644 index 0000000..ad75201 --- /dev/null +++ b/sdk/dotnet/examples/ConformanceV2/ConformanceV2.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + enable + enable + false + + + + + + + diff --git a/sdk/dotnet/examples/ConformanceV2/Program.cs b/sdk/dotnet/examples/ConformanceV2/Program.cs new file mode 100644 index 0000000..e9d8170 --- /dev/null +++ b/sdk/dotnet/examples/ConformanceV2/Program.cs @@ -0,0 +1,53 @@ +// v2 conformance program for stand-in/conformance.mjs --v2 (see spec/v2/conformance.json). +// +// node stand-in/conformance.mjs --v2 -- dotnet sdk/dotnet/examples/ConformanceV2/bin/Release/net10.0/ConformanceV2.dll +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using Supertext.Sdk.V1; +using Supertext.Sdk.V2; +using SupertextClient = Supertext.Sdk.V2.SupertextClient; +using SupertextClientOptions = Supertext.Sdk.V2.SupertextClientOptions; +using SupertextException = Supertext.Sdk.V2.SupertextException; + +Console.InputEncoding = new System.Text.UTF8Encoding(false); +Console.OutputEncoding = new System.Text.UTF8Encoding(false); + +var request = JsonNode.Parse(Console.In.ReadToEnd())!.AsObject(); +var segments = request["segments"]!.AsArray() + .Select(s => new KeyValuePair((string)s!["key"]!, new Segment((string)s["text"]!, (bool?)s["html"] ?? false))) + .ToList(); +var politeness = (string?)request["politeness"] switch +{ + "more" => Politeness.More, + "less" => Politeness.Less, + _ => Politeness.Default, +}; + +var client = new SupertextClient( + Environment.GetEnvironmentVariable("SUPERTEXT_API_KEY"), + new SupertextClientOptions + { + BaseUrl = Environment.GetEnvironmentVariable("SUPERTEXT_API_URL") ?? SupertextClient.LiveBaseUrl, + PollInterval = TimeSpan.FromMilliseconds(100), + }); + +JsonObject output; +try +{ + var translations = await client.TranslateTextsAsync(segments, (string)request["targetLang"]!, (string?)request["sourceLang"], politeness, + maxCharacters: (int?)request["maxCharacters"] ?? SupertextClient.DefaultMaxTextCharacters); + var result = new JsonObject(); + foreach (var (key, text) in translations) + { + result[key] = text; + } + output = new JsonObject { ["translations"] = result }; +} +catch (SupertextException e) +{ + output = new JsonObject { ["error"] = new JsonObject { ["code"] = e.Code, ["status"] = e.Status } }; +} + +Console.Out.Write(output.ToJsonString(new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping })); +Console.Out.WriteLine(); diff --git a/sdk/dotnet/src/Supertext.Sdk/V2/Models.cs b/sdk/dotnet/src/Supertext.Sdk/V2/Models.cs new file mode 100644 index 0000000..aaf126f --- /dev/null +++ b/sdk/dotnet/src/Supertext.Sdk/V2/Models.cs @@ -0,0 +1,103 @@ +namespace Supertext.Sdk.V2; + +/// How inline markup in texts is handled. +public enum TagHandling +{ + /// Plain text. + None, + + /// XML, parsed strictly. + Xml, + + /// HTML, malformed markup tolerated. + Html, +} + +/// Settings of the v2 client. +public sealed class SupertextClientOptions +{ + /// Default: the live API. A trailing slash is added if missing. + public string BaseUrl { get; init; } = SupertextClient.LiveBaseUrl; + + /// Wait between status polls. Default 2 s. + public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(2); + + /// Give up waiting for an AI file translation after this long. Default 180 s. + public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(180); + + /// Timeout of a single HTTP request. Default 30 s. + public TimeSpan RequestTimeout { get; init; } = TimeSpan.FromSeconds(30); + + /// Retries after HTTP 429. Default 4. + public int MaxRetries { get; init; } = 4; + + /// Appended to the User-Agent, e.g. Umbraco-Supertext-Translation/1.2.0. + public string? UserAgent { get; init; } + + /// Your HttpClient (proxies, tests). Default: one shared instance. + public HttpClient? HttpClient { get; init; } + + /// Sleep implementation (tests). + public Func? Sleep { get; init; } + + /// Clock (tests). + public TimeProvider? TimeProvider { get; init; } +} + +/// The answer of POST translate/ai/text: one translation per input text, same order. +public sealed record TextTranslation(IReadOnlyList Translations, string? DetectedSourceLang, IReadOnlyDictionary? EnforcedTerms, string? RequestId); + +/// What a request would cost; prices keyed by lower-case currency code, not rounded to the cent. +public sealed record Quote(int CharacterCount, IReadOnlyDictionary Prices); + +/// Status of an AI file translation: translating, done, error, deleted. +public sealed record FileStatus(string Status, string? Error, int? EstimatedSecondsLeft, string? DetectedSourceLang); + +/// A downloaded document; the file name comes from Content-Disposition when present. +public sealed record DownloadedFile(byte[] Content, string? FileName); + +/// A language detection found. +public sealed record DetectedLanguage(string LangCode, double? Confidence, bool SupportsTranslation); + +/// The workspace and key behind the API key. +public sealed record Account(string WorkspaceId, string WorkspaceName, string ApiKeyName, string ApiKeyPrefix, string ApiKeyExpiresAt); + +/// One language pair from GET features (supports_politeness, supports_glossary, supports_fused_translation). +public sealed record FeatureSupport(string SourceLang, string TargetLang, IReadOnlyList Features); + +/// An accepted human-review order. : Optimisation (true) or Verification; the label is for display. +public sealed record FusedOrder(string TranslationId, bool BriefingApplied, string ServiceLabel, string? RequestId); + +/// Status of a human-review order: in_progress, completed, failed. Negative seconds: the promised time has passed. +public sealed record FusedStatus(string Status, string? DetectedSourceLang, int EstimatedSecondsLeft, string? Error); + +/// What a human-review order would cost and how long it would take; for files only. +public sealed record FusedQuote(IReadOnlyDictionary Prices, int EstimatedDurationSeconds, int WordCount, int? CharacterCount, bool BriefingApplied, string ServiceLabel); + +/// A registered webhook. (whsec_…) only on the result of CreateWebhookAsync, shown once. +public sealed record Webhook( + string Id, + string Url, + IReadOnlyList EventTypes, + string? Description, + string Status, + string? DisabledReason, + string CreatedAt, + string? LastDeliveryAt, + string? LastFailureAt, + string? LastFailureReason, + int ConsecutiveFailures, + string? Secret = null) +{ + /// Keeps the secret out of logs. + public override string ToString() => $"Webhook {{ Id = {Id}, Url = {Url}, Status = {Status} }}"; +} + +/// The answer of a test event. +public sealed record WebhookTestResult(bool Delivered, int? StatusCode, string? Error, int DurationMs); + +/// A verified webhook event. is the webhook-id header: de-duplicate on it. +public sealed record WebhookEvent(string Id, string Type, string Timestamp, System.Text.Json.JsonElement Data); + +/// One planned request of TranslateTextsAsync: kind text, html or file. +public sealed record PlannedRequest(string Kind, IReadOnlyList Keys); diff --git a/sdk/dotnet/src/Supertext.Sdk/V2/SupertextClient.cs b/sdk/dotnet/src/Supertext.Sdk/V2/SupertextClient.cs new file mode 100644 index 0000000..e6bba0e --- /dev/null +++ b/sdk/dotnet/src/Supertext.Sdk/V2/SupertextClient.cs @@ -0,0 +1,893 @@ +using System.Globalization; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Supertext.Sdk.V1; +using V1Client = Supertext.Sdk.V1.SupertextClient; + +namespace Supertext.Sdk.V2; + +/// +/// Client for the Supertext API v2 (https://api-platform.supertext.com/v1, workspace keys sent as +/// Bearer st_live_…): text translation in one request, AI file translation, language detection, +/// human review ("fused"), quotes, the account and webhooks. Thread-safe; reuse one instance per key. +/// +public sealed partial class SupertextClient +{ + /// The live API. + public const string LiveBaseUrl = "https://api-platform.supertext.com/v1/"; + + /// Characters per POST translate/ai/text: the API's limit. + public const int DefaultMaxTextCharacters = 10_000; + + private const string SdkUserAgent = "supertext-sdk-dotnet"; + + private readonly string apiKey; + private readonly Uri baseUri; + private readonly HttpClient http; + private readonly SupertextClientOptions options; + private readonly Func sleep; + private readonly TimeProvider clock; + private readonly string userAgent; + + /// Creates a client. A blank key doesn't throw here: the first request throws missing_api_key. + public SupertextClient(string? apiKey, SupertextClientOptions? options = null) + { + this.apiKey = apiKey ?? string.Empty; + this.options = options ?? new SupertextClientOptions(); + var baseUrl = this.options.BaseUrl; + baseUri = new Uri(baseUrl.EndsWith('/') ? baseUrl : baseUrl + "/", UriKind.Absolute); + http = this.options.HttpClient ?? V1Client.SharedHttpClient.Value; + sleep = this.options.Sleep ?? Task.Delay; + clock = this.options.TimeProvider ?? TimeProvider.System; + userAgent = string.IsNullOrWhiteSpace(this.options.UserAgent) ? SdkUserAgent : SdkUserAgent + " " + this.options.UserAgent.Trim(); + } + + /// Bearer <key> for a key as pasted (spec/v2/auth-header.json). + /// missing_api_key for a blank key. + public static string AuthHeader(string? apiKey) + { + var key = BearerPrefix().Replace((apiKey ?? string.Empty).Trim(' ', '\t', '\n', '\r', '\f'), string.Empty).Trim(' ', '\t', '\n', '\r', '\f'); + if (key.Length == 0) + { + throw new SupertextException(SupertextErrorCodes.MissingApiKey); + } + return "Bearer " + key; + } + + /// SHA-256 (lower-case hex) of the key as sends it; empty for a blank key. + public static string FingerprintOf(string? apiKey) + { + string header; + try + { + header = AuthHeader(apiKey); + } + catch (SupertextException) + { + return string.Empty; + } + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(header["Bearer ".Length..]))).ToLowerInvariant(); + } + + /// Splits segments into requests (spec/v2/batching.json). + public static IReadOnlyList PlanRequests(IEnumerable> segments, int maxCharacters = DefaultMaxTextCharacters) + { + ArgumentNullException.ThrowIfNull(segments); + var plain = new List>(); + var html = new List>(); + var oversized = new List>(); + foreach (var pair in segments) + { + if (V1Client.IsBlank(pair.Value.Text)) + { + continue; + } + (CodePoints(pair.Value.Text) > maxCharacters ? oversized : pair.Value.Html ? html : plain).Add(pair); + } + var result = new List(); + foreach (var (kind, list) in new[] { ("text", plain), ("html", html) }) + { + var current = new List(); + long size = 0; + foreach (var pair in list) + { + var length = CodePoints(pair.Value.Text); + if (current.Count > 0 && size + length > maxCharacters) + { + result.Add(new PlannedRequest(kind, current)); + current = []; + size = 0; + } + current.Add(pair.Key); + size += length; + } + if (current.Count > 0) + { + result.Add(new PlannedRequest(kind, current)); + } + } + foreach (var batch in V1Client.Batches(oversized, V1Client.DefaultMaxCharacters)) + { + result.Add(new PlannedRequest("file", batch.Select(p => p.Key).ToList())); + } + return result; + } + + // ---- account and features + + /// The workspace and key behind the API key. Cost-free. + public async Task GetAccountAsync(CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Get, "account", null, cancellationToken).ConfigureAwait(false); + var r = o.RootElement; + return new Account(Text(r, "workspace_id"), Text(r, "workspace_name"), Text(r, "api_key_name"), Text(r, "api_key_prefix"), Text(r, "api_key_expires_at")); + } + + /// The language pairs and their features, optionally filtered. Cost-free. + public async Task> GetFeaturesAsync(string? sourceLang = null, string? targetLang = null, CancellationToken cancellationToken = default) + { + var query = new List(); + if (!string.IsNullOrEmpty(sourceLang)) + { + query.Add("source_lang=" + Uri.EscapeDataString(sourceLang)); + } + if (!string.IsNullOrEmpty(targetLang)) + { + query.Add("target_lang=" + Uri.EscapeDataString(targetLang)); + } + using var o = await JsonAsync(HttpMethod.Get, query.Count == 0 ? "features" : "features?" + string.Join('&', query), null, cancellationToken).ConfigureAwait(false); + var result = new List(); + if (o.RootElement.TryGetProperty("supported_features", out var list) && list.ValueKind == JsonValueKind.Array) + { + foreach (var item in list.EnumerateArray()) + { + if (TextOrNull(item, "source_lang") is { } s && TextOrNull(item, "target_lang") is { } t) + { + result.Add(new FeatureSupport(s, t, Strings(item, "features"))); + } + } + } + return result; + } + + /// Throws unless the key is accepted (GET account). + public async Task ValidateApiKeyAsync(CancellationToken cancellationToken = default) => + await SendAsync(HttpMethod.Get, "account", null, cancellationToken).ConfigureAwait(false); + + /// The automatic key check (spec/v2/api-key-check.json). Never throws. + public async Task CheckApiKeyAsync(CancellationToken cancellationToken = default) + { + var checkedAt = ApiKeyCheck.IsoSeconds(clock.GetUtcNow()); + var fingerprint = FingerprintOf(apiKey); + if (fingerprint.Length == 0) + { + return new ApiKeyCheck(ApiKeyCheckStatus.Missing, checkedAt, null, null, string.Empty); + } + try + { + var timeout = ApiKeyCheck.Timeout < options.RequestTimeout ? ApiKeyCheck.Timeout : options.RequestTimeout; + var response = await SendAsync(HttpMethod.Get, "account", null, cancellationToken, timeout).ConfigureAwait(false); + return new ApiKeyCheck(ApiKeyCheckStatus.Ok, checkedAt, response.Status, null, fingerprint); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + return KeyCheckFromException(e, checkedAt, fingerprint); + } + } + + /// The key check for a failed GET account. + public static ApiKeyCheck KeyCheckFromException(Exception error, string checkedAt, string fingerprint) + { + if (error is not SupertextException e) + { + return new ApiKeyCheck(ApiKeyCheckStatus.Error, checkedAt, null, null, fingerprint); + } + var errorCode = string.IsNullOrEmpty(e.ApiErrorCode) ? null : e.ApiErrorCode.Length > 100 ? e.ApiErrorCode[..100] : e.ApiErrorCode; + var status = e.Code == SupertextErrorCodes.MissingApiKey ? ApiKeyCheckStatus.Missing + : e.Status is 401 or 403 ? ApiKeyCheckStatus.Invalid + : e.Status is null or >= 500 ? ApiKeyCheckStatus.Unreachable + : ApiKeyCheckStatus.Error; + return new ApiKeyCheck(status, checkedAt, e.Status, errorCode, fingerprint); + } + + // ---- text + + /// One POST translate/ai/text: the translations in input order. Codes are sent as given. + public async Task TranslateTextAsync(IReadOnlyList texts, string targetLang, string? sourceLang = null, + Politeness politeness = Politeness.Default, IReadOnlyDictionary? glossary = null, TagHandling tagHandling = TagHandling.None, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(texts); + var body = TextPayload(texts, targetLang, sourceLang, politeness, glossary, tagHandling); + using var o = await JsonAsync(HttpMethod.Post, "translate/ai/text", JsonContent(body), cancellationToken).ConfigureAwait(false); + var r = o.RootElement; + var translations = Strings(r, "translated_text"); + if (!r.TryGetProperty("translated_text", out var raw) || raw.ValueKind != JsonValueKind.Array || translations.Count != texts.Count) + { + throw new SupertextException(SupertextErrorCodes.IncompleteResponse, detail: $"expected {texts.Count} translations"); + } + return new TextTranslation(translations, TextOrNull(r, "detected_source_lang"), StringMap(r, "enforced_terms"), TextOrNull(r, "request_id")); + } + + /// What would cost (a free dry run). + public async Task QuoteTextAsync(IReadOnlyList texts, string targetLang, string? sourceLang = null, + Politeness politeness = Politeness.Default, IReadOnlyDictionary? glossary = null, TagHandling tagHandling = TagHandling.None, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(texts); + using var o = await JsonAsync(HttpMethod.Post, "translate/ai/text/quote", JsonContent(TextPayload(texts, targetLang, sourceLang, politeness, glossary, tagHandling)), cancellationToken).ConfigureAwait(false); + return ToQuote(o.RootElement); + } + + /// + /// Translates keyed texts (spec/v2/batching.json): the same keys in input order, blanks unchanged. + /// Up to 10,000 characters per request; a longer segment goes through an HTML file. + /// + public async Task> TranslateTextsAsync(IEnumerable> segments, string targetLang, + string? sourceLang = null, Politeness politeness = Politeness.Default, IReadOnlyDictionary? glossary = null, + int maxCharacters = DefaultMaxTextCharacters, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(segments); + Required(targetLang); + var input = segments.ToList(); + var result = new TranslationResult(input); + var lookup = input.ToDictionary(p => p.Key, p => p.Value); + foreach (var planned in PlanRequests(input, maxCharacters)) + { + var batch = planned.Keys.Select(k => lookup[k]).ToList(); + if (planned.Kind == "file") + { + var html = await TranslateHtmlAsync(HtmlDocument.Build(batch), targetLang, sourceLang, politeness, glossary, cancellationToken).ConfigureAwait(false); + var parsed = HtmlDocument.Parse(html, batch); + var missing = planned.Keys.Where((_, i) => parsed[i] is null).ToList(); + if (missing.Count > 0) + { + throw new SupertextException(SupertextErrorCodes.IncompleteResponse, detail: "missing: " + string.Join(", ", missing)); + } + for (var i = 0; i < batch.Count; i++) + { + result.Set(planned.Keys[i], parsed[i]!); + } + } + else + { + var answer = await TranslateTextAsync(batch.Select(s => s.Text).ToList(), targetLang, sourceLang, politeness, glossary, + planned.Kind == "html" ? TagHandling.Html : TagHandling.None, cancellationToken).ConfigureAwait(false); + for (var i = 0; i < batch.Count; i++) + { + result.Set(planned.Keys[i], answer.Translations[i]); + } + } + } + return result; + } + + // ---- AI file translation + + /// Uploads a document for AI translation; returns the file id. + public async Task SubmitFileAsync(byte[] content, string fileName, string targetLang, string? sourceLang = null, + Politeness politeness = Politeness.Default, IReadOnlyDictionary? glossary = null, bool? useOcr = null, + CancellationToken cancellationToken = default) + { + var form = FileForm(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr); + using var o = await JsonAsync(HttpMethod.Post, "translate/ai/file", form, cancellationToken).ConfigureAwait(false); + return TextOrNull(o.RootElement, "file_id") ?? throw new SupertextException(SupertextErrorCodes.IncompleteResponse, detail: "no file_id"); + } + + /// The status of an AI file translation. + public async Task GetFileStatusAsync(string fileId, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Get, FilePath(fileId) + "/status", null, cancellationToken).ConfigureAwait(false); + var r = o.RootElement; + return new FileStatus(Text(r, "status"), TextOrNull(r, "error"), IntOrNull(r, "estimated_duration_left_in_seconds"), TextOrNull(r, "detected_source_lang")); + } + + /// Polls until done; throws translation_error, file_deleted or timeout. + public async Task WaitForFileAsync(string fileId, CancellationToken cancellationToken = default) + { + var started = clock.GetTimestamp(); + while (true) + { + var status = await GetFileStatusAsync(fileId, cancellationToken).ConfigureAwait(false); + if (status.Status == "done") + { + return status; + } + if (SupertextException.ForStatusValue("file", status.Status, status.Error) is { } error) + { + throw error; + } + if (clock.GetElapsedTime(started) + options.PollInterval > options.Timeout) + { + throw new SupertextException(SupertextErrorCodes.Timeout); + } + await sleep(options.PollInterval, cancellationToken).ConfigureAwait(false); + } + } + + /// The translated document, or null while it isn't ready (HTTP 202). Available for 24 hours. + public async Task DownloadFileAsync(string fileId, CancellationToken cancellationToken = default) => + Download(await SendAsync(HttpMethod.Get, FilePath(fileId) + "/translation", null, cancellationToken).ConfigureAwait(false)); + + /// Deletes the document and its translation. Never throws. + public async Task DeleteFileAsync(string fileId, CancellationToken cancellationToken = default) + { + try + { + await SendAsync(HttpMethod.Delete, FilePath(fileId), null, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is SupertextException or OperationCanceledException) + { + // Best effort: files expire after 24 hours anyway. + } + } + + /// Upload, wait, download, and always delete. + public async Task TranslateFileAsync(byte[] content, string fileName, string targetLang, string? sourceLang = null, + Politeness politeness = Politeness.Default, IReadOnlyDictionary? glossary = null, bool? useOcr = null, + CancellationToken cancellationToken = default) + { + var fileId = await SubmitFileAsync(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr, cancellationToken).ConfigureAwait(false); + try + { + await WaitForFileAsync(fileId, cancellationToken).ConfigureAwait(false); + var file = await DownloadFileAsync(fileId, cancellationToken).ConfigureAwait(false); + if (file is null || file.Content.Length == 0) + { + throw new SupertextException(SupertextErrorCodes.IncompleteResponse, detail: "empty document"); + } + return file; + } + finally + { + await DeleteFileAsync(fileId, CancellationToken.None).ConfigureAwait(false); + } + } + + /// One HTML document through the file endpoint (as content.html). + public async Task TranslateHtmlAsync(string html, string targetLang, string? sourceLang = null, + Politeness politeness = Politeness.Default, IReadOnlyDictionary? glossary = null, CancellationToken cancellationToken = default) + { + var file = await TranslateFileAsync(Encoding.UTF8.GetBytes(html), "content.html", targetLang, sourceLang, politeness, glossary, null, cancellationToken).ConfigureAwait(false); + return Encoding.UTF8.GetString(file.Content); + } + + /// What translating a document would cost. + public async Task QuoteFileAsync(byte[] content, string fileName, string targetLang, string? sourceLang = null, + Politeness politeness = Politeness.Default, IReadOnlyDictionary? glossary = null, bool? useOcr = null, + CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "translate/ai/file/quote", FileForm(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr), cancellationToken).ConfigureAwait(false); + return ToQuote(o.RootElement); + } + + // ---- language detection + + /// The language of a text (the first 500 characters are read). Empty when none was found. + public async Task> DetectLanguageAsync(string text, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "detect-languages/text", JsonContent(new Dictionary { ["text"] = text }), cancellationToken).ConfigureAwait(false); + return Detected(o.RootElement); + } + + /// What a detection would cost. + public async Task QuoteDetectionAsync(string text, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "detect-languages/text/quote", JsonContent(new Dictionary { ["text"] = text }), cancellationToken).ConfigureAwait(false); + return ToQuote(o.RootElement); + } + + /// The language of a document. + public async Task> DetectFileLanguageAsync(byte[] content, string fileName, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "detect-languages/file", Multipart([], content, fileName), cancellationToken).ConfigureAwait(false); + return Detected(o.RootElement); + } + + /// What detecting a document's language would cost. + public async Task QuoteFileDetectionAsync(byte[] content, string fileName, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "detect-languages/file/quote", Multipart([], content, fileName), cancellationToken).ConfigureAwait(false); + return ToQuote(o.RootElement); + } + + // ---- human review ("fused") + + /// Orders a reviewed translation of a text; the source language is required. Charged when accepted. + public async Task OrderFusedTextAsync(string text, string sourceLang, string targetLang, Politeness politeness = Politeness.Default, + string? briefing = null, string? idempotencyKey = null, CancellationToken cancellationToken = default) + { + var extra = string.IsNullOrEmpty(idempotencyKey) ? null : new Dictionary { ["Idempotency-Key"] = idempotencyKey }; + using var o = await JsonAsync(HttpMethod.Post, "translate/fused/text", JsonContent(FusedPayload(text, sourceLang, targetLang, politeness, briefing)), cancellationToken, extra).ConfigureAwait(false); + return ToFusedOrder(o.RootElement); + } + + /// The status of a human-review text order. + public async Task GetFusedTextStatusAsync(string translationId, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Get, "translate/fused/text/" + Uri.EscapeDataString(translationId) + "/status", null, cancellationToken).ConfigureAwait(false); + return ToFusedStatus(o.RootElement); + } + + /// The reviewed text, or null while it isn't delivered yet (HTTP 202). + public async Task GetFusedTextAsync(string translationId, CancellationToken cancellationToken = default) + { + var response = await SendAsync(HttpMethod.Get, "translate/fused/text/" + Uri.EscapeDataString(translationId) + "/translation", null, cancellationToken).ConfigureAwait(false); + if (response.Status == 202) + { + return null; + } + using var o = Parse(response.Body); + return o.RootElement.TryGetProperty("translated_text", out var v) && v.ValueKind == JsonValueKind.String + ? v.GetString()! + : throw new SupertextException(SupertextErrorCodes.IncompleteResponse, detail: "no translated_text"); + } + + /// What a human-review text order would cost and how long it would take. + public async Task QuoteFusedTextAsync(string text, string sourceLang, string targetLang, Politeness politeness = Politeness.Default, + string? briefing = null, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "translate/fused/text/quote", JsonContent(FusedPayload(text, sourceLang, targetLang, politeness, briefing)), cancellationToken).ConfigureAwait(false); + return ToFusedQuote(o.RootElement); + } + + /// Orders a reviewed translation of a document (PDFs come back as DOCX). + public async Task OrderFusedFileAsync(byte[] content, string fileName, string sourceLang, string targetLang, + Politeness politeness = Politeness.Default, string? briefing = null, bool? useOcr = null, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "translate/fused/file", FusedForm(content, fileName, sourceLang, targetLang, politeness, briefing, useOcr), cancellationToken).ConfigureAwait(false); + return ToFusedOrder(o.RootElement); + } + + /// The status of a human-review document order. + public async Task GetFusedFileStatusAsync(string translationId, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Get, "translate/fused/file/" + Uri.EscapeDataString(translationId) + "/status", null, cancellationToken).ConfigureAwait(false); + return ToFusedStatus(o.RootElement); + } + + /// The reviewed document, or null until a reviewer delivers (HTTP 202). + public async Task DownloadFusedFileAsync(string translationId, CancellationToken cancellationToken = default) => + Download(await SendAsync(HttpMethod.Get, "translate/fused/file/" + Uri.EscapeDataString(translationId) + "/translation", null, cancellationToken).ConfigureAwait(false)); + + /// What a human-review document order would cost and how long it would take. + public async Task QuoteFusedFileAsync(byte[] content, string fileName, string sourceLang, string targetLang, + Politeness politeness = Politeness.Default, string? briefing = null, bool? useOcr = null, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "translate/fused/file/quote", FusedForm(content, fileName, sourceLang, targetLang, politeness, briefing, useOcr), cancellationToken).ConfigureAwait(false); + return ToFusedQuote(o.RootElement); + } + + // ---- webhooks + + /// This key's webhooks. + public async Task> ListWebhooksAsync(CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Get, "webhooks", null, cancellationToken).ConfigureAwait(false); + return o.RootElement.TryGetProperty("items", out var items) && items.ValueKind == JsonValueKind.Array + ? items.EnumerateArray().Select(i => ToWebhook(i, false)).ToList() + : []; + } + + /// Registers a webhook; the result's secret is shown only once: store it. + public async Task CreateWebhookAsync(string url, IReadOnlyList eventTypes, string? description = null, CancellationToken cancellationToken = default) + { + var body = new Dictionary { ["url"] = url, ["event_types"] = eventTypes }; + if (description is not null) + { + body["description"] = description; + } + using var o = await JsonAsync(HttpMethod.Post, "webhooks", JsonContent(body), cancellationToken).ConfigureAwait(false); + return ToWebhook(o.RootElement, true); + } + + /// One webhook. + public async Task GetWebhookAsync(string webhookId, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Get, "webhooks/" + Uri.EscapeDataString(webhookId), null, cancellationToken).ConfigureAwait(false); + return ToWebhook(o.RootElement, false); + } + + /// Changes only the fields given; sends description null. + public async Task UpdateWebhookAsync(string webhookId, string? url = null, IReadOnlyList? eventTypes = null, string? description = null, + bool? enabled = null, bool clearDescription = false, CancellationToken cancellationToken = default) + { + var body = new Dictionary(); + if (url is not null) + { + body["url"] = url; + } + if (eventTypes is not null) + { + body["event_types"] = eventTypes; + } + if (description is not null || clearDescription) + { + body["description"] = description; + } + if (enabled is not null) + { + body["enabled"] = enabled; + } + using var o = await JsonAsync(HttpMethod.Patch, "webhooks/" + Uri.EscapeDataString(webhookId), JsonContent(body), cancellationToken).ConfigureAwait(false); + return ToWebhook(o.RootElement, false); + } + + /// Deletes a webhook. + public async Task DeleteWebhookAsync(string webhookId, CancellationToken cancellationToken = default) => + await SendAsync(HttpMethod.Delete, "webhooks/" + Uri.EscapeDataString(webhookId), null, cancellationToken).ConfigureAwait(false); + + /// Sends a test event (at most one per 5 seconds). + public async Task TestWebhookAsync(string webhookId, CancellationToken cancellationToken = default) + { + using var o = await JsonAsync(HttpMethod.Post, "webhooks/" + Uri.EscapeDataString(webhookId) + "/test", null, cancellationToken).ConfigureAwait(false); + var r = o.RootElement; + return new WebhookTestResult(r.TryGetProperty("delivered", out var d) && d.ValueKind == JsonValueKind.True, IntOrNull(r, "status_code"), TextOrNull(r, "error"), IntOrNull(r, "duration_ms") ?? 0); + } + + // ---- HTTP + + private sealed record Response(int Status, byte[] Body, string? ContentDisposition) + { + public string Text => Encoding.UTF8.GetString(Body); + } + + private sealed record Payload(byte[] Bytes, string ContentType); + + private async Task JsonAsync(HttpMethod method, string path, Payload? body, CancellationToken cancellationToken, Dictionary? extra = null) + { + var response = await SendAsync(method, path, body, cancellationToken, null, extra).ConfigureAwait(false); + return Parse(response.Body); + } + + private static JsonDocument Parse(byte[] body) + { + try + { + var doc = JsonDocument.Parse(body); + if (doc.RootElement.ValueKind == JsonValueKind.Object) + { + return doc; + } + doc.Dispose(); + } + catch (JsonException) + { + // Not JSON: treated as an empty object. + } + return JsonDocument.Parse("{}"); + } + + private async Task SendAsync(HttpMethod method, string path, Payload? body, CancellationToken cancellationToken, + TimeSpan? requestTimeout = null, Dictionary? extra = null) + { + var timeoutAfter = requestTimeout ?? options.RequestTimeout; + var authorization = AuthHeader(apiKey); + var key = authorization["Bearer ".Length..]; + var uri = new Uri(baseUri, path); + for (var attempt = 0; ; attempt++) + { + using var request = new HttpRequestMessage(method, uri); + if (body is not null) + { + request.Content = new ByteArrayContent(body.Bytes); + request.Content.Headers.TryAddWithoutValidation("Content-Type", body.ContentType); + } + if (extra is not null) + { + foreach (var (name, value) in extra) + { + request.Headers.TryAddWithoutValidation(name, value); + } + } + request.Headers.TryAddWithoutValidation("Authorization", authorization); + request.Headers.TryAddWithoutValidation("Accept", "application/json, application/problem+json"); + request.Headers.TryAddWithoutValidation("User-Agent", userAgent); + + int status; + byte[] bytes; + string? retryAfter = null; + string? disposition = null; + using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + timeout.CancelAfter(timeoutAfter); + try + { + using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false); + status = (int)response.StatusCode; + if (response.Headers.NonValidated.TryGetValues("Retry-After", out var values)) + { + retryAfter = values.FirstOrDefault(); + } + if (response.Content.Headers.NonValidated.TryGetValues("Content-Disposition", out var cd)) + { + disposition = cd.FirstOrDefault(); + } + bytes = await response.Content.ReadAsByteArrayAsync(timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (OperationCanceledException e) + { + throw new SupertextException(SupertextErrorCodes.TransportError, + detail: $"Request timed out after {timeoutAfter.TotalSeconds.ToString(CultureInfo.InvariantCulture)} s", innerException: e); + } + catch (Exception e) when (e is HttpRequestException or IOException or InvalidOperationException) + { + var message = e.Message.Replace(key, "***", StringComparison.Ordinal); + throw new SupertextException(SupertextErrorCodes.TransportError, detail: message, innerException: message == e.Message ? e : null); + } + } + if (status is >= 200 and < 300) + { + return new Response(status, bytes, disposition); + } + if (status == 429 && attempt < options.MaxRetries) + { + await sleep(TimeSpan.FromMilliseconds(V1Client.RetryDelayMs(attempt, retryAfter)), cancellationToken).ConfigureAwait(false); + continue; + } + throw SupertextException.ForResponse(status, Encoding.UTF8.GetString(bytes).Replace(key, "***", StringComparison.Ordinal)); + } + } + + // ---- payloads + + private static string Required(string? code) + { + var value = (code ?? string.Empty).Trim(' ', '\t', '\n', '\r', '\f'); + return value.Length == 0 ? throw new SupertextException(SupertextErrorCodes.UnsupportedLanguage) : value; + } + + private static string? PolitenessValue(Politeness politeness) => politeness switch + { + Politeness.More => "more", + Politeness.Less => "less", + _ => null, + }; + + private static Dictionary TextPayload(IReadOnlyList texts, string targetLang, string? sourceLang, Politeness politeness, + IReadOnlyDictionary? glossary, TagHandling tagHandling) + { + var body = new Dictionary { ["text"] = texts, ["target_lang"] = Required(targetLang) }; + var source = (sourceLang ?? string.Empty).Trim(' ', '\t', '\n', '\r', '\f'); + if (source.Length > 0) + { + body["source_lang"] = source; + } + if (PolitenessValue(politeness) is { } p) + { + body["politeness"] = p; + } + if (glossary is { Count: > 0 }) + { + body["glossary"] = glossary; + } + if (tagHandling != TagHandling.None) + { + body["tag_handling"] = tagHandling == TagHandling.Html ? "html" : "xml"; + } + return body; + } + + private static Payload FileForm(byte[] content, string fileName, string targetLang, string? sourceLang, Politeness politeness, + IReadOnlyDictionary? glossary, bool? useOcr) + { + var fields = new List<(string, string)> { ("target_lang", Required(targetLang)) }; + var source = (sourceLang ?? string.Empty).Trim(' ', '\t', '\n', '\r', '\f'); + if (source.Length > 0) + { + fields.Add(("source_lang", source)); + } + if (PolitenessValue(politeness) is { } p) + { + fields.Add(("politeness", p)); + } + if (glossary is { Count: > 0 }) + { + fields.Add(("glossary", JsonSerializer.Serialize(glossary, JsonOptions))); + } + if (useOcr is not null) + { + fields.Add(("use_ocr", useOcr.Value ? "true" : "false")); + } + return Multipart(fields, content, fileName); + } + + private static Dictionary FusedPayload(string text, string sourceLang, string targetLang, Politeness politeness, string? briefing) + { + var body = new Dictionary { ["text"] = text, ["source_lang"] = Required(sourceLang), ["target_lang"] = Required(targetLang) }; + if (PolitenessValue(politeness) is { } p) + { + body["politeness"] = p; + } + if (!string.IsNullOrEmpty(briefing)) + { + body["briefing"] = briefing; + } + return body; + } + + private static Payload FusedForm(byte[] content, string fileName, string sourceLang, string targetLang, Politeness politeness, string? briefing, bool? useOcr) + { + var fields = new List<(string, string)> { ("target_lang", Required(targetLang)), ("source_lang", Required(sourceLang)) }; + if (PolitenessValue(politeness) is { } p) + { + fields.Add(("politeness", p)); + } + if (!string.IsNullOrEmpty(briefing)) + { + fields.Add(("briefing", briefing)); + } + if (useOcr is not null) + { + fields.Add(("use_ocr", useOcr.Value ? "true" : "false")); + } + return Multipart(fields, content, fileName); + } + + private static readonly JsonSerializerOptions JsonOptions = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + + private static Payload JsonContent(Dictionary value) => + new(JsonSerializer.SerializeToUtf8Bytes(value, JsonOptions), "application/json"); + + private static Payload Multipart(IEnumerable<(string Name, string Value)> fields, byte[] content, string fileName) + { + ArgumentNullException.ThrowIfNull(content); + var boundary = "----supertext-" + Convert.ToHexString(RandomNumberGenerator.GetBytes(12)).ToLowerInvariant(); + using var stream = new MemoryStream(); + void Write(string s) + { + var b = Encoding.UTF8.GetBytes(s); + stream.Write(b, 0, b.Length); + } + foreach (var (name, value) in fields) + { + Write($"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"); + } + var safe = UnsafeFileNameChars().Replace(fileName ?? "file", "_"); + Write($"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{safe}\"\r\nContent-Type: {ContentTypeFor(fileName ?? string.Empty)}\r\n\r\n"); + stream.Write(content, 0, content.Length); + Write($"\r\n--{boundary}--\r\n"); + return new Payload(stream.ToArray(), "multipart/form-data; boundary=" + boundary); + } + + private static readonly Dictionary Types = new(StringComparer.OrdinalIgnoreCase) + { + ["html"] = "text/html", + ["htm"] = "text/html", + ["txt"] = "text/plain", + ["srt"] = "application/x-subrip", + ["pdf"] = "application/pdf", + ["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + }; + + /// The Content-Type for a file name's extension; else application/octet-stream. + public static string ContentTypeFor(string fileName) + { + var dot = (fileName ?? string.Empty).LastIndexOf('.'); + return dot >= 0 && Types.TryGetValue(fileName![(dot + 1)..], out var type) ? type : "application/octet-stream"; + } + + /// The file name of a Content-Disposition header (filename*=UTF-8''… preferred). + public static string? FileNameFrom(string? disposition) + { + if (string.IsNullOrEmpty(disposition)) + { + return null; + } + var star = FileNameStar().Match(disposition); + if (star.Success) + { + try + { + return Uri.UnescapeDataString(star.Groups[1].Value.Trim()); + } + catch (UriFormatException) + { + // fall through + } + } + var plain = FileNamePlain().Match(disposition); + return plain.Success ? (plain.Groups[1].Success ? plain.Groups[1].Value : plain.Groups[2].Value) : null; + } + + // ---- answers + + private static string Text(JsonElement o, string name) => TextOrNull(o, name) ?? string.Empty; + + private static string? TextOrNull(JsonElement o, string name) => + o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String && v.GetString() is { Length: > 0 } s ? s : null; + + private static int? IntOrNull(JsonElement o, string name) => + o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var i) ? i : null; + + private static List Strings(JsonElement o, string name) => + o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Array + ? v.EnumerateArray().Where(x => x.ValueKind == JsonValueKind.String).Select(x => x.GetString()!).ToList() + : []; + + private static Dictionary? StringMap(JsonElement o, string name) => + o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Object + ? v.EnumerateObject().Where(p => p.Value.ValueKind == JsonValueKind.String).ToDictionary(p => p.Name, p => p.Value.GetString()!) + : null; + + private static Dictionary Prices(JsonElement o) => + o.TryGetProperty("prices", out var v) && v.ValueKind == JsonValueKind.Object + ? v.EnumerateObject().Where(p => p.Value.ValueKind == JsonValueKind.Number).ToDictionary(p => p.Name, p => p.Value.GetDouble()) + : []; + + private static Quote ToQuote(JsonElement o) => new(IntOrNull(o, "character_count") ?? 0, Prices(o)); + + private static List Detected(JsonElement o) + { + var result = new List(); + if (o.TryGetProperty("detected_languages", out var list) && list.ValueKind == JsonValueKind.Array) + { + foreach (var d in list.EnumerateArray()) + { + if (TextOrNull(d, "lang_code") is { } code) + { + double? confidence = d.TryGetProperty("confidence", out var c) && c.ValueKind == JsonValueKind.Number ? c.GetDouble() : null; + result.Add(new DetectedLanguage(code, confidence, d.TryGetProperty("supports_translation", out var s) && s.ValueKind == JsonValueKind.True)); + } + } + } + return result; + } + + private static FusedOrder ToFusedOrder(JsonElement o) => new( + TextOrNull(o, "translation_id") ?? throw new SupertextException(SupertextErrorCodes.IncompleteResponse, detail: "no translation_id"), + o.TryGetProperty("briefing_applied", out var b) && b.ValueKind == JsonValueKind.True, + Text(o, "service_label"), + TextOrNull(o, "request_id")); + + private static FusedStatus ToFusedStatus(JsonElement o) => + new(Text(o, "status"), TextOrNull(o, "detected_source_lang"), IntOrNull(o, "estimated_duration_left_in_seconds") ?? 0, TextOrNull(o, "error")); + + private static FusedQuote ToFusedQuote(JsonElement o) => new( + Prices(o), IntOrNull(o, "estimated_duration_in_seconds") ?? 0, IntOrNull(o, "word_count") ?? 0, IntOrNull(o, "character_count"), + o.TryGetProperty("briefing_applied", out var b) && b.ValueKind == JsonValueKind.True, Text(o, "service_label")); + + private static Webhook ToWebhook(JsonElement o, bool withSecret) => new( + Text(o, "id"), Text(o, "url"), Strings(o, "event_types"), TextOrNull(o, "description"), Text(o, "status"), TextOrNull(o, "disabled_reason"), + Text(o, "created_at"), TextOrNull(o, "last_delivery_at"), TextOrNull(o, "last_failure_at"), TextOrNull(o, "last_failure_reason"), + IntOrNull(o, "consecutive_failures") ?? 0, withSecret ? Text(o, "secret") : null); + + private static DownloadedFile? Download(Response response) => + response.Status == 202 ? null : new DownloadedFile(response.Body, FileNameFrom(response.ContentDisposition)); + + private static string FilePath(string fileId) => "translate/ai/file/" + Uri.EscapeDataString(fileId); + + private static int CodePoints(string s) + { + var count = s.Length; + for (var i = 1; i < s.Length; i++) + { + if (char.IsSurrogatePair(s[i - 1], s[i])) + { + count--; + } + } + return count; + } + + [GeneratedRegex(@"^bearer(?:[ \t\n\r\f]+|$)", RegexOptions.IgnoreCase)] + private static partial Regex BearerPrefix(); + + [GeneratedRegex("[\"\\r\\n\\\\]")] + private static partial Regex UnsafeFileNameChars(); + + [GeneratedRegex(@"filename\*\s*=\s*UTF-8''([^;]+)", RegexOptions.IgnoreCase)] + private static partial Regex FileNameStar(); + + [GeneratedRegex(@"filename\s*=\s*(?:""([^""]*)""|([^;\s]+))", RegexOptions.IgnoreCase)] + private static partial Regex FileNamePlain(); +} diff --git a/sdk/dotnet/src/Supertext.Sdk/V2/SupertextException.cs b/sdk/dotnet/src/Supertext.Sdk/V2/SupertextException.cs new file mode 100644 index 0000000..e2cf073 --- /dev/null +++ b/sdk/dotnet/src/Supertext.Sdk/V2/SupertextException.cs @@ -0,0 +1,192 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Supertext.Sdk.V2; + +/// The error codes of the v2 client: fixed strings shared by all Supertext SDKs. +public static class SupertextErrorCodes +{ + /// No key configured; nothing was sent. + public const string MissingApiKey = "missing_api_key"; + /// HTTP 401/403. + public const string AuthenticationFailure = "authentication_failure"; + /// HTTP 402: the credit balance doesn't cover the request (Reason insufficient_credit). + public const string InsufficientCredit = "insufficient_credit"; + /// HTTP 422: validation, e.g. a language the API doesn't offer. + public const string InvalidRequest = "invalid_request"; + /// A blank language code; nothing was sent. + public const string UnsupportedLanguage = "unsupported_language"; + /// HTTP 404. + public const string NotFound = "not_found"; + /// HTTP 409, e.g. webhook_limit_reached. + public const string Conflict = "conflict"; + /// HTTP 413. + public const string PayloadTooLarge = "payload_too_large"; + /// HTTP 429 after the retries. + public const string TooManyRequests = "too_many_requests"; + /// HTTP 5xx. + public const string ServiceUnavailable = "service_unavailable"; + /// Any other HTTP status. + public const string UnexpectedStatus = "unexpected_status"; + /// No HTTP answer. + public const string TransportError = "transport_error"; + /// The answer lacks what it should carry. + public const string IncompleteResponse = "incomplete_response"; + /// Status error (AI file) or failed (human review). + public const string TranslationError = "translation_error"; + /// The file was deleted before it could be downloaded. + public const string FileDeleted = "file_deleted"; + /// Waited longer than the timeout. + public const string Timeout = "timeout"; + /// A webhook request that isn't a valid, signed event. + public const string InvalidWebhook = "invalid_webhook"; +} + +/// +/// Any failure of the v2 client (spec/v2/errors.json). is the API's explanation +/// (safe to show), the problem's code, its +/// error_id (quote it to support), its reason. Never contains the API key. +/// +public sealed partial class SupertextException : Exception +{ + private static readonly Dictionary Messages = new() + { + [SupertextErrorCodes.MissingApiKey] = "No Supertext API key is configured.", + [SupertextErrorCodes.AuthenticationFailure] = "Supertext rejected the API key. Please check it.", + [SupertextErrorCodes.InsufficientCredit] = "The Supertext credit balance does not cover this request. Please top up.", + [SupertextErrorCodes.InvalidRequest] = "Supertext rejected the request.", + [SupertextErrorCodes.UnsupportedLanguage] = "This language has no Supertext language code. Map it to a Supertext language.", + [SupertextErrorCodes.NotFound] = "Not found at Supertext (expired or already deleted).", + [SupertextErrorCodes.Conflict] = "Supertext refused the change.", + [SupertextErrorCodes.PayloadTooLarge] = "The document is too large for Supertext.", + [SupertextErrorCodes.TooManyRequests] = "Too many requests to Supertext. Please try again shortly.", + [SupertextErrorCodes.ServiceUnavailable] = "The Supertext service is unavailable.", + [SupertextErrorCodes.UnexpectedStatus] = "Supertext sent an unexpected HTTP status.", + [SupertextErrorCodes.TransportError] = "Could not reach Supertext.", + [SupertextErrorCodes.IncompleteResponse] = "The Supertext answer is incomplete.", + [SupertextErrorCodes.TranslationError] = "Supertext failed to translate.", + [SupertextErrorCodes.FileDeleted] = "The Supertext file was deleted before it could be downloaded.", + [SupertextErrorCodes.Timeout] = "Timed out waiting for the Supertext translation to finish.", + [SupertextErrorCodes.InvalidWebhook] = "The webhook request is not a valid, signed Supertext event.", + }; + + /// Creates an error. + public SupertextException(string code, int? status = null, string? detail = null, string? apiErrorCode = null, + string? errorId = null, string? reason = null, Exception? innerException = null) + : base(BuildMessage(code, status, detail, errorId), innerException) + { + Code = code; + Status = status; + Detail = string.IsNullOrEmpty(detail) ? null : detail; + ApiErrorCode = apiErrorCode; + ErrorId = errorId; + Reason = reason; + } + + /// One of . + public string Code { get; } + + /// The HTTP status, when the error comes from an answer. + public int? Status { get; } + + /// The API's explanation, at most 200 characters. + public string? Detail { get; } + + /// The problem's code, e.g. validation_error. + public string? ApiErrorCode { get; } + + /// The problem's error_id: quote it to Supertext support. + public string? ErrorId { get; } + + /// The problem's reason, e.g. insufficient_credit. + public string? Reason { get; } + + private static string BuildMessage(string code, int? status, string? detail, string? errorId) + { + var text = Messages.GetValueOrDefault(code, "Supertext request failed."); + if (status is not null) + { + text += $" HTTP {status}."; + } + if (!string.IsNullOrEmpty(detail)) + { + text += " " + detail; + } + if (!string.IsNullOrEmpty(errorId)) + { + text += $" (error id {errorId})"; + } + return text; + } + + /// Maps a non-2xx answer (problem+json) to an error. + public static SupertextException ForResponse(int status, string body) + { + string? Text(string name) + { + try + { + using var doc = JsonDocument.Parse(body); + return doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty(name, out var v) + && v.ValueKind == JsonValueKind.String && v.GetString() is { Length: > 0 } s ? s : null; + } + catch (JsonException) + { + return null; + } + } + var detail = Cut(Text("detail") ?? Tags().Replace(body, string.Empty)); + var code = status switch + { + 401 or 403 => SupertextErrorCodes.AuthenticationFailure, + 402 => SupertextErrorCodes.InsufficientCredit, + 404 => SupertextErrorCodes.NotFound, + 409 => SupertextErrorCodes.Conflict, + 413 => SupertextErrorCodes.PayloadTooLarge, + 422 => SupertextErrorCodes.InvalidRequest, + 429 => SupertextErrorCodes.TooManyRequests, + >= 500 and <= 599 => SupertextErrorCodes.ServiceUnavailable, + _ => SupertextErrorCodes.UnexpectedStatus, + }; + return new SupertextException(code, status, detail, Text("code"), Text("error_id"), Text("reason")); + } + + /// The error for a polled status, or null: AI file (file) error/deleted, human review (fused) failed. + public static SupertextException? ForStatusValue(string kind, string status, string? error = null) + { + var detail = Cut(error ?? string.Empty); + return (kind, status) switch + { + ("file", "error") or ("fused", "failed") => new SupertextException(SupertextErrorCodes.TranslationError, detail: detail), + ("file", "deleted") => new SupertextException(SupertextErrorCodes.FileDeleted), + _ => null, + }; + } + + private static string? Cut(string text) + { + var trimmed = text.Trim(' ', '\t', '\n', '\r', '\f'); + if (trimmed.Length == 0) + { + return null; + } + // At most 200 code points. + var count = 0; + for (var i = 0; i < trimmed.Length; i++) + { + if (count == 200) + { + return trimmed[..i]; + } + if (char.IsHighSurrogate(trimmed[i]) && i + 1 < trimmed.Length && char.IsLowSurrogate(trimmed[i + 1])) + { + i++; + } + count++; + } + return trimmed; + } + + [GeneratedRegex("<[^>]*>")] + private static partial Regex Tags(); +} diff --git a/sdk/dotnet/src/Supertext.Sdk/V2/Webhooks.cs b/sdk/dotnet/src/Supertext.Sdk/V2/Webhooks.cs new file mode 100644 index 0000000..13d5500 --- /dev/null +++ b/sdk/dotnet/src/Supertext.Sdk/V2/Webhooks.cs @@ -0,0 +1,86 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +namespace Supertext.Sdk.V2; + +/// Verifies webhook requests the Standard Webhooks way (spec/v2/webhooks.json). +public static class Webhooks +{ + /// How far a webhook's timestamp may be from now, either way. + public const int ToleranceSeconds = 300; + + /// + /// The verified event; throws otherwise. Pass the raw + /// body exactly as received, before any JSON parsing. + /// + /// The whsec_… secret from the create answer. + /// Request headers; names in any case. + /// The body as received (signed over its UTF-8 bytes). + /// Current time (tests); default the system clock. + public static WebhookEvent Verify(string secret, IEnumerable> headers, string rawBody, DateTimeOffset? now = null) + { + ArgumentNullException.ThrowIfNull(headers); + var encoded = (secret ?? string.Empty).StartsWith("whsec_", StringComparison.Ordinal) ? secret![6..] : secret ?? string.Empty; + byte[] key; + try + { + key = encoded.Length > 0 && encoded.Length % 4 == 0 ? Convert.FromBase64String(encoded) : []; + } + catch (FormatException) + { + throw Invalid(); + } + if (key.Length == 0) + { + throw Invalid(); + } + string? Header(string name) => headers.Where(h => string.Equals(h.Key, name, StringComparison.OrdinalIgnoreCase)).Select(h => h.Value).FirstOrDefault(); + var id = Header("webhook-id"); + var timestamp = Header("webhook-timestamp"); + var signatures = Header("webhook-signature"); + if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(timestamp) || signatures is null + || !timestamp.All(char.IsAsciiDigit) || !long.TryParse(timestamp, out var seconds)) + { + throw Invalid(); + } + if (Math.Abs((now ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds() - seconds) > ToleranceSeconds) + { + throw Invalid(); + } + var expected = Encoding.ASCII.GetBytes(Convert.ToBase64String(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes($"{id}.{timestamp}.{rawBody}")))); + var matched = false; + foreach (var entry in signatures.Split(' ')) + { + var comma = entry.IndexOf(',', StringComparison.Ordinal); + if (comma > 0 && entry[..comma] == "v1" + && CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(entry[(comma + 1)..]), expected)) + { + matched = true; + } + } + if (!matched) + { + throw Invalid(); + } + try + { + using var doc = JsonDocument.Parse(rawBody); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object + || !root.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String + || !root.TryGetProperty("timestamp", out var time) || time.ValueKind != JsonValueKind.String) + { + throw Invalid(); + } + var data = root.TryGetProperty("data", out var d) && d.ValueKind == JsonValueKind.Object ? d.Clone() : JsonDocument.Parse("{}").RootElement.Clone(); + return new WebhookEvent(id, type.GetString()!, time.GetString()!, data); + } + catch (JsonException) + { + throw Invalid(); + } + } + + private static SupertextException Invalid() => new(SupertextErrorCodes.InvalidWebhook); +} diff --git a/sdk/dotnet/tests/Supertext.Sdk.Tests/V2Tests.cs b/sdk/dotnet/tests/Supertext.Sdk.Tests/V2Tests.cs new file mode 100644 index 0000000..7773dfb --- /dev/null +++ b/sdk/dotnet/tests/Supertext.Sdk.Tests/V2Tests.cs @@ -0,0 +1,300 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Supertext.Sdk.V1; +using V2 = Supertext.Sdk.V2; + +namespace Supertext.Sdk.Tests; + +/// API v2: the shared vectors in spec/v2/ and the client against a scripted handler. +public class V2Tests +{ + private const string Base = "https://api-platform.supertext.com/v1/"; + + public static IEnumerable AuthCases() => Spec.Cases("v2/auth-header.json", "cases"); + public static IEnumerable ErrorCases() => Spec.Cases("v2/errors.json", "http"); + public static IEnumerable StatusCases() => Spec.Cases("v2/errors.json", "fileStatus"); + public static IEnumerable BatchingCases() => Spec.Cases("v2/batching.json", "cases", "name"); + public static IEnumerable WebhookCases() => Spec.Cases("v2/webhooks.json", "cases", "name"); + public static IEnumerable KeyCheckCases() => Spec.Cases("v2/api-key-check.json", "apiKeyCheck"); + + private static JsonElement Case(string json) => JsonDocument.Parse(json).RootElement.Clone(); + + private static string? NullableInt(JsonElement e, string name) => e.GetProperty(name).ValueKind == JsonValueKind.Null ? null : e.GetProperty(name).GetInt32().ToString(System.Globalization.CultureInfo.InvariantCulture); + + [Theory] + [MemberData(nameof(AuthCases))] + public void AuthHeader(string name, string json) + { + _ = name; + var c = Case(json); + var key = c.GetProperty("apiKey").GetString(); + if (c.Str("error") is { } error) + { + Assert.Equal(error, Assert.Throws(() => V2.SupertextClient.AuthHeader(key)).Code); + } + else + { + Assert.Equal(c.Str("header"), V2.SupertextClient.AuthHeader(key)); + } + } + + [Theory] + [MemberData(nameof(ErrorCases))] + public void Errors(string name, string json) + { + _ = name; + var c = Case(json); + var e = V2.SupertextException.ForResponse(c.GetProperty("status").GetInt32(), c.GetProperty("body").GetString()!); + Assert.Equal(c.Str("code"), e.Code); + Assert.Equal(c.GetProperty("status").GetInt32(), e.Status); + Assert.Equal(c.Str("apiErrorCode"), e.ApiErrorCode); + Assert.Equal(c.Str("errorId"), e.ErrorId); + Assert.Equal(c.Str("reason"), e.Reason); + Assert.Equal(c.Str("detail"), e.Detail); + } + + [Theory] + [MemberData(nameof(StatusCases))] + public void StatusValues(string name, string json) + { + _ = name; + var c = Case(json); + var e = V2.SupertextException.ForStatusValue(c.Str("kind")!, c.Str("status")!, c.Str("error")); + Assert.Equal(c.Str("code"), e?.Code); + Assert.Equal(c.Str("detail"), e?.Detail); + } + + [Theory] + [MemberData(nameof(BatchingCases))] + public void Batching(string name, string json) + { + _ = name; + var c = Case(json); + var segments = c.GetProperty("segments").EnumerateArray() + .Select(s => new KeyValuePair(s.Str("key")!, new Segment(s.Str("text")!, s.GetProperty("html").GetBoolean()))).ToList(); + var plan = V2.SupertextClient.PlanRequests(segments, c.GetProperty("maxCharacters").GetInt32()) + .Select(r => new { kind = r.Kind, keys = r.Keys }).ToList(); + Assert.Equal(c.GetProperty("batches").GetRawText().Replace(" ", "", StringComparison.Ordinal).Replace("\n", "", StringComparison.Ordinal), JsonSerializer.Serialize(plan)); + Assert.Equal(V2.SupertextClient.DefaultMaxTextCharacters, Spec.Load("v2/batching.json").GetProperty("defaultMaxCharacters").GetInt32()); + } + + [Theory] + [MemberData(nameof(WebhookCases))] + public void Webhooks(string name, string json) + { + _ = name; + var c = Case(json); + var headers = c.GetProperty("headers").EnumerateObject().Select(p => new KeyValuePair(p.Name, p.Value.GetString()!)).ToList(); + var now = DateTimeOffset.FromUnixTimeSeconds(c.GetProperty("now").GetInt64()); + if (c.Str("error") is { } error) + { + Assert.Equal(error, Assert.Throws(() => V2.Webhooks.Verify(c.Str("secret")!, headers, c.Str("body")!, now)).Code); + } + else + { + var e = V2.Webhooks.Verify(c.Str("secret")!, headers, c.Str("body")!, now); + var expected = c.GetProperty("event"); + Assert.Equal(expected.Str("id"), e.Id); + Assert.Equal(expected.Str("type"), e.Type); + Assert.Equal(expected.Str("timestamp"), e.Timestamp); + Assert.True(JsonElement.DeepEquals(expected.GetProperty("data"), e.Data)); + } + } + + [Fact] + public void Fingerprints() + { + foreach (var c in Spec.Load("v2/api-key-check.json").GetProperty("fingerprint").EnumerateArray()) + { + Assert.Equal(c.Str("fingerprint"), V2.SupertextClient.FingerprintOf(c.Str("apiKey"))); + } + } + + [Theory] + [MemberData(nameof(KeyCheckCases))] + public async Task KeyCheck(string name, string json) + { + _ = name; + var c = Case(json); + var answer = c.GetProperty("answer"); + var api = new Scripted(answer.TryGetProperty("transportError", out _) + ? _ => throw new HttpRequestException("down") + : _ => Answer(answer.GetProperty("status").GetInt32(), answer.Str("body")!)); + var check = await Client(api, "st_live_abc123").CheckApiKeyAsync(); + Assert.Equal(c.Str("status"), check.Status); + Assert.Equal(NullableInt(c, "httpStatus"), check.HttpStatus?.ToString(System.Globalization.CultureInfo.InvariantCulture)); + Assert.Equal(c.Str("errorCode"), check.ErrorCode); + Assert.Equal(V2.SupertextClient.FingerprintOf("st_live_abc123"), check.Fingerprint); + Assert.Equal(["GET account"], api.Calls()); + } + + private sealed record Call(HttpMethod Method, string Url, Dictionary Headers, string Body); + + private sealed class Scripted(params Func[] answers) : HttpMessageHandler + { + private readonly Queue> queue = new(answers); + + public List Requests { get; } = []; + + public List Calls() => Requests.Select(r => $"{r.Method} {r.Url[Base.Length..]}").ToList(); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var headers = request.Headers.ToDictionary(h => h.Key, h => string.Join(",", h.Value), StringComparer.OrdinalIgnoreCase); + var body = request.Content is null ? string.Empty : Encoding.UTF8.GetString(await request.Content.ReadAsByteArrayAsync(cancellationToken)); + if (request.Content is not null) + { + headers["Content-Type"] = request.Content.Headers.NonValidated.TryGetValues("Content-Type", out var ct) ? ct.First() : string.Empty; + } + var call = new Call(request.Method, request.RequestUri!.ToString(), headers, body); + Requests.Add(call); + return queue.Dequeue()(call); + } + } + + private static HttpResponseMessage Answer(int status, string body, string? retryAfter = null, string? disposition = null) + { + var response = new HttpResponseMessage((HttpStatusCode)status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + if (retryAfter is not null) + { + response.Headers.TryAddWithoutValidation("Retry-After", retryAfter); + } + if (disposition is not null) + { + response.Content.Headers.TryAddWithoutValidation("Content-Disposition", disposition); + } + return response; + } + + private static Func Js(string body, int status = 200, string? retryAfter = null) => _ => Answer(status, body, retryAfter); + + private static V2.SupertextClient Client(Scripted api, string key = "k", FakeTime? time = null) => + new(key, new V2.SupertextClientOptions { HttpClient = new HttpClient(api), Sleep = (time ?? new FakeTime()).Sleep, TimeProvider = time ?? new FakeTime() }); + + private static JsonElement Body(Call call) => JsonDocument.Parse(call.Body).RootElement.Clone(); + + [Fact] + public async Task TranslateText() + { + var api = new Scripted(Js("""{"request_id":"r1","detected_source_lang":"en","translated_text":["Hallo"],"enforced_terms":{"shop":"Laden"}}""")); + var r = await Client(api, " Bearer st_live_k ").TranslateTextAsync(["Hello"], "de-CH", "en", Politeness.More, new Dictionary { ["shop"] = "Laden" }, V2.TagHandling.Html); + Assert.Equal(["Hallo"], r.Translations); + Assert.Equal(("en", "r1", "Laden"), (r.DetectedSourceLang, r.RequestId, r.EnforcedTerms!["shop"])); + Assert.Equal("Bearer st_live_k", api.Requests[0].Headers["Authorization"]); + Assert.Equal("application/json", api.Requests[0].Headers["Content-Type"]); + Assert.Equal("""{"text":["Hello"],"target_lang":"de-CH","source_lang":"en","politeness":"more","glossary":{"shop":"Laden"},"tag_handling":"html"}""", api.Requests[0].Body); + + var wrong = new Scripted(Js("""{"translated_text":["x"]}""")); + Assert.Equal("incomplete_response", (await Assert.ThrowsAsync(() => Client(wrong).TranslateTextAsync(["a", "b"], "de-CH"))).Code); + } + + [Fact] + public async Task RetriesThenProblemAndNeverLeaksTheKey() + { + var time = new FakeTime(); + var api = new Scripted(Js("""{"code":"rate_limited"}""", 429, "2"), Js("""{"code":"payment_required","detail":"Top up.","error_id":"e1","reason":"insufficient_credit"}""", 402)); + var e = await Assert.ThrowsAsync(() => Client(api, time: time).TranslateTextAsync(["a"], "de-CH")); + Assert.Equal(("insufficient_credit", "insufficient_credit", "e1", "Top up."), (e.Code, e.Reason, e.ErrorId, e.Detail)); + Assert.Equal([TimeSpan.FromSeconds(2)], time.Sleeps); + + var leak = new Scripted(_ => new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("bad key st_live_secret123") }); + var e2 = await Assert.ThrowsAsync(() => Client(leak, "st_live_secret123").GetAccountAsync()); + Assert.DoesNotContain("st_live_secret123", e2.Message, StringComparison.Ordinal); + Assert.Equal("bad key ***", e2.Detail); + } + + [Fact] + public async Task TranslateTextsUsesTextHtmlAndFile() + { + var api = new Scripted( + c => Answer(200, JsonSerializer.Serialize(new { translated_text = Body(c).GetProperty("text").EnumerateArray().Select(t => "T:" + t.GetString()) })), + c => Answer(200, JsonSerializer.Serialize(new { translated_text = Body(c).GetProperty("text").EnumerateArray().Select(t => "H:" + t.GetString()) })), + Js("""{"file_id":"f1"}""", 202), + Js("""{"status":"done"}"""), + _ => Answer(200, "
LONG
\n", disposition: "attachment; filename=\"c.html\""), + Js("""{"status":"deleted"}""")); + var segments = new List> { new("a", "one"), new("b", new Segment("two", true)), new("c", " "), new("d", "long text here") }; + var result = await Client(api).TranslateTextsAsync(segments, "de-CH", maxCharacters: 10); + Assert.Equal(["a", "b", "c", "d"], result.Keys); + Assert.Equal(["T:one", "H:two", " ", "LONG"], result.Values); + Assert.Equal(["POST translate/ai/text", "POST translate/ai/text", "POST translate/ai/file", "GET translate/ai/file/f1/status", "GET translate/ai/file/f1/translation", "DELETE translate/ai/file/f1"], api.Calls()); + Assert.False(Body(api.Requests[0]).TryGetProperty("tag_handling", out _)); + Assert.Equal("html", Body(api.Requests[1]).GetProperty("tag_handling").GetString()); + Assert.Contains("Content-Type: text/html\r\n", api.Requests[2].Body, StringComparison.Ordinal); + } + + [Fact] + public async Task FailedFileDeletes() + { + var api = new Scripted(Js("""{"file_id":"f1"}""", 202), Js("""{"status":"translating"}"""), Js("""{"status":"error","error":"Corrupt."}"""), Js("{}")); + var e = await Assert.ThrowsAsync(() => Client(api).TranslateFileAsync([1, 2], "a.docx", "fr-CH", glossary: new Dictionary { ["a"] = "b" }, useOcr: false)); + Assert.Equal(("translation_error", "Corrupt."), (e.Code, e.Detail)); + Assert.Equal(HttpMethod.Delete, api.Requests[^1].Method); + Assert.Contains("wordprocessingml.document", api.Requests[0].Body, StringComparison.Ordinal); + Assert.Contains("name=\"glossary\"\r\n\r\n{\"a\":\"b\"}", api.Requests[0].Body, StringComparison.Ordinal); + Assert.Contains("name=\"use_ocr\"\r\n\r\nfalse", api.Requests[0].Body, StringComparison.Ordinal); + } + + [Fact] + public async Task NotReadyFusedFeaturesDetectionQuotes() + { + var api = new Scripted( + Js("""{"status":"in_progress"}""", 202), + Js("""{"status":"in_progress"}""", 202), + Js("""{"translated_text":"Geprüft"}"""), + Js("""{"translation_id":"u-1","briefing_applied":true,"service_label":"Optimisation","request_id":"r"}""", 202), + Js("""{"supported_features":[{"source_lang":"en","target_lang":"de-CH","features":["supports_politeness"]},{"bad":1}]}"""), + Js("""{"detected_languages":[{"lang_code":"en","confidence":0.9,"supports_translation":true}]}"""), + Js("""{"character_count":5,"prices":{"chf":0.0001,"bad":"x"}}""")); + var c = Client(api); + Assert.Null(await c.DownloadFileAsync("x")); + Assert.Null(await c.GetFusedTextAsync("t")); + Assert.Equal("Geprüft", await c.GetFusedTextAsync("t")); + var order = await c.OrderFusedTextAsync("Hello", "en", "de-CH", briefing: "Friendly", idempotencyKey: "idem-1"); + Assert.Equal(new V2.FusedOrder("u-1", true, "Optimisation", "r"), order); + Assert.Equal("idem-1", api.Requests[3].Headers["Idempotency-Key"]); + Assert.Equal("""{"text":"Hello","source_lang":"en","target_lang":"de-CH","briefing":"Friendly"}""", api.Requests[3].Body); + var features = await c.GetFeaturesAsync("en", "de-CH"); + Assert.Equal(("en", "de-CH", "supports_politeness"), (features.Single().SourceLang, features.Single().TargetLang, features.Single().Features.Single())); + Assert.Equal(Base + "features?source_lang=en&target_lang=de-CH", api.Requests[4].Url); + Assert.Equal([new V2.DetectedLanguage("en", 0.9, true)], await c.DetectLanguageAsync("Hello")); + var q = await c.QuoteTextAsync(["Hello"], "de-CH"); + Assert.Equal((5, 0.0001, 1), (q.CharacterCount, q.Prices["chf"], q.Prices.Count)); + } + + [Fact] + public async Task WebhookCrud() + { + const string hook = """{"id":"h1","url":"https://cms.example/hook","event_types":["translation.ai_file.completed"],"description":null,"status":"active","disabled_reason":null,"created_at":"2026","last_delivery_at":null,"last_failure_at":null,"last_failure_reason":null,"consecutive_failures":0"""; + var api = new Scripted(Js(hook + ""","secret":"whsec_abc"}""", 201), Js("""{"items":[""" + hook + "}]}"), Js(hook + "}"), _ => new HttpResponseMessage(HttpStatusCode.NoContent), Js("""{"delivered":true,"status_code":200,"error":null,"duration_ms":42}""")); + var c = Client(api); + var created = await c.CreateWebhookAsync("https://cms.example/hook", ["translation.ai_file.completed"]); + Assert.Equal("whsec_abc", created.Secret); + Assert.DoesNotContain("whsec_abc", created.ToString(), StringComparison.Ordinal); + Assert.Equal("""{"url":"https://cms.example/hook","event_types":["translation.ai_file.completed"]}""", api.Requests[0].Body); + Assert.Single(await c.ListWebhooksAsync()); + await c.UpdateWebhookAsync("h1", enabled: true, clearDescription: true); + Assert.Equal("""{"description":null,"enabled":true}""", api.Requests[2].Body); + Assert.Equal(HttpMethod.Patch, api.Requests[2].Method); + await c.DeleteWebhookAsync("h1"); + Assert.Equal(new V2.WebhookTestResult(true, 200, null, 42), await c.TestWebhookAsync("h1")); + } + + [Fact] + public async Task NothingSentForBlankTargetOrKey() + { + var api = new Scripted(); + Assert.Equal("unsupported_language", (await Assert.ThrowsAsync(() => Client(api).TranslateTextsAsync([new("a", "x")], " "))).Code); + Assert.Equal("missing_api_key", (await Assert.ThrowsAsync(() => Client(api, " ").GetAccountAsync())).Code); + Assert.Empty(api.Requests); + } + + [Fact] + public void FileNameFrom() + { + Assert.Equal("a b.docx", V2.SupertextClient.FileNameFrom("attachment; filename=\"a b.docx\"")); + Assert.Equal("Zürich.docx", V2.SupertextClient.FileNameFrom("attachment; filename=x.pdf; filename*=UTF-8''Z%C3%BCrich.docx")); + Assert.Null(V2.SupertextClient.FileNameFrom(null)); + } +} diff --git a/sdk/java/README.md b/sdk/java/README.md index 0c8902f..f89f0e3 100644 --- a/sdk/java/README.md +++ b/sdk/java/README.md @@ -16,7 +16,7 @@ Java 11+, no runtime dependencies (uses `java.net.http.HttpClient`). For the pro Gradle: `implementation("com.supertext:supertext-sdk:0.2.1")`. -Everything that talks to the API is versioned: API v1 lives in the package `com.supertext.sdk.v1`. A later API version gets `com.supertext.sdk.v2` next to it, so an integration can move at its own pace. Version-neutral parts stay in `com.supertext.sdk`: `SdkInfo.VERSION` (this SDK's version) and the HTTP layer (`Transport`, `JdkHttpTransport`). +Everything that talks to the API is versioned: API v1 lives in the package `com.supertext.sdk.v1`. API v2 is in `com.supertext.sdk.v2` next to it (see [API v2](#api-v2)), so an integration can move at its own pace. Version-neutral parts stay in `com.supertext.sdk`: `SdkInfo.VERSION` (this SDK's version) and the HTTP layer (`Transport`, `JdkHttpTransport`). ## API key @@ -151,6 +151,33 @@ SupertextClient.builder(apiKey) `translateTexts(segments, target, source, politeness, maxCharacters)` sets the document size (default `SupertextClient.DEFAULT_MAX_CHARACTERS`, 900,000). +## API v2 + +Supertext's platform API (`https://api-platform.supertext.com/v1/`, `Authorization: Bearer st_live_…`) is in `com.supertext.sdk.v2`, next to v1. `translateTexts` takes the same segments and returns the same keys; texts go in direct requests of up to 10,000 characters (HTML segments with `TagHandling.HTML`), a longer segment through the file endpoint. No Supertext account yet? Create one at https://www.supertext.com/person/en/account/signin. Generate your API key at https://www.supertext.com/en/integrations/api (supertext.com → Integrations → API; requires the Admin role); API v2 takes the workspace keys (`st_live_…`) described in [Supertext's v2 documentation](https://www.supertext.com/en/neo/documentation/api). + +```java +import com.supertext.sdk.v1.Politeness; +import com.supertext.sdk.v1.Segment; +import com.supertext.sdk.v2.DownloadedFile; +import com.supertext.sdk.v2.SupertextClient; +import com.supertext.sdk.v2.WebhookEvent; +import com.supertext.sdk.v2.Webhooks; + +SupertextClient client = SupertextClient.builder(System.getenv("SUPERTEXT_API_KEY")).build(); +Map segments = new LinkedHashMap<>(); +segments.put("title", Segment.text("Hello & welcome")); +segments.put("body", Segment.html("

Our new shop opens on Monday.

")); +Map german = client.translateTexts(segments, "de-CH", "en", Politeness.MORE, Map.of("shop", "Laden"), + SupertextClient.DEFAULT_MAX_TEXT_CHARACTERS); +DownloadedFile docx = client.translateFile(Files.readAllBytes(Path.of("offer.docx")), "offer.docx", "fr-CH", null, + Politeness.DEFAULT, null, null); // getContent(), getFileName() + +// In your webhook endpoint: the raw body, before parsing it +WebhookEvent event = Webhooks.verify(System.getenv("SUPERTEXT_WEBHOOK_SECRET"), headers, rawBody); +``` + +What else is there: `translateText` (one request, with the detected source language and enforced glossary terms) and `quoteText`; documents with `translateFile` (upload, wait, download, always delete) or the single steps `submitFile`, `getFileStatus`, `waitForFile`, `downloadFile` (`null` while not ready), `deleteFile`, and `quoteFile`; `detectLanguage`, `detectFileLanguage` and their quotes; human review with `quoteFusedText`/`orderFusedText`, `getFusedTextStatus`, `getFusedText` (and the same for files: `orderFusedFile`, `getFusedFileStatus`, `downloadFusedFile`); `getAccount`, `getFeatures`, `validateApiKey`, `checkApiKey` (same `ApiKeyCheck` as v1, on `GET account`); webhooks (`createWebhook`, whose secret is returned only once, `listWebhooks`, `getWebhook`, `updateWebhook`, `deleteWebhook`, `testWebhook`). Errors are one type with the codes of `spec/v2/errors.json` (`insufficient_credit`, `invalid_request`, `authentication_failure`, …) and Supertext's `detail`, `apiErrorCode`, `errorId` and `reason`. More: [integration guide → API v2](../../docs/integration-guide.md#16-api-v2-the-supertext-platform-api). + ## Translation files For texts translated outside the API (a CAT tool, a translator, Supertext's web app), `com.supertext.sdk.files.TranslationFiles` exports segments as an XLIFF 1.2 file (one `` per job) or as the HTML document `HtmlDocument.build` makes, with the job's metadata, and imports the translated file again. Not tied to an API version: nothing here calls the API. Behaviour shared by all Supertext SDKs: `spec/translation-file.json`. diff --git a/sdk/java/examples/ConformanceV2.java b/sdk/java/examples/ConformanceV2.java new file mode 100644 index 0000000..9355d41 --- /dev/null +++ b/sdk/java/examples/ConformanceV2.java @@ -0,0 +1,173 @@ +import com.supertext.sdk.v1.Politeness; +import com.supertext.sdk.v1.Segment; +import com.supertext.sdk.v2.SupertextClient; +import com.supertext.sdk.v2.SupertextException; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * v2 conformance program for stand-in/conformance.mjs --v2 (see spec/v2/conformance.json): reads one + * request as JSON on stdin, translates it with the v2 client's translateTexts (language codes passed + * through as given) and prints the result as JSON. + * + *
+ * mvn -q package -DskipTests
+ * node ../../stand-in/conformance.mjs --v2 -- java -cp target/classes examples/ConformanceV2.java
+ * 
+ * + * Single-file source program (Java 11+), so it carries its own small JSON reader and writer: the SDK has no JSON dependency. + */ +public final class ConformanceV2 { + + public static void main(String[] args) throws Exception { + PrintStream out = new PrintStream(System.out, true, "UTF-8"); + @SuppressWarnings("unchecked") + Map request = (Map) new Reader(readAll(System.in)).parse(); + + Map segments = new LinkedHashMap<>(); + for (Object item : (List) request.get("segments")) { + Map s = (Map) item; + segments.put((String) s.get("key"), new Segment((String) s.get("text"), Boolean.TRUE.equals(s.get("html")))); + } + SupertextClient client = SupertextClient.builder(System.getenv("SUPERTEXT_API_KEY")) + .baseUrl(System.getenv("SUPERTEXT_API_URL")) + .pollInterval(Duration.ofMillis(100)) + .build(); + try { + Object max = request.get("maxCharacters"); + Map translations = client.translateTexts(segments, (String) request.get("targetLang"), + (String) request.get("sourceLang"), Politeness.fromValue((String) request.get("politeness")), null, + max == null ? SupertextClient.DEFAULT_MAX_TEXT_CHARACTERS : ((Number) max).intValue()); + StringBuilder json = new StringBuilder("{\"translations\":{"); + String separator = ""; + for (Map.Entry entry : translations.entrySet()) { + json.append(separator).append(quote(entry.getKey())).append(':').append(quote(entry.getValue())); + separator = ","; + } + out.println(json.append("}}")); + } catch (SupertextException e) { + out.println("{\"error\":{\"code\":" + quote(e.getCode().value()) + ",\"status\":" + + (e.getStatus() == null ? "null" : e.getStatus()) + "}}"); + } + } + + private static String readAll(InputStream in) throws IOException { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + in.transferTo(buffer); + return buffer.toString(StandardCharsets.UTF_8); + } + + private static String quote(String s) { + StringBuilder out = new StringBuilder("\""); + for (char c : s.toCharArray()) { + switch (c) { + case '"': out.append("\\\""); break; + case '\\': out.append("\\\\"); break; + case '\n': out.append("\\n"); break; + case '\r': out.append("\\r"); break; + case '\t': out.append("\\t"); break; + default: + if (c < 0x20) { + out.append(String.format("\\u%04x", (int) c)); + } else { + out.append(c); + } + } + } + return out.append('"').toString(); + } + + /** Just enough JSON for the request: objects, arrays, strings, booleans, null, numbers. */ + private static final class Reader { + private final String s; + private int i; + + Reader(String s) { + this.s = s; + } + + Object parse() { + skip(); + char c = s.charAt(i); + if (c == '{') { + Map map = new LinkedHashMap<>(); + i++; + skip(); + if (s.charAt(i) == '}') { + i++; + return map; + } + do { + skip(); + String key = (String) parse(); + skip(); + i++; // ':' + map.put(key, parse()); + skip(); + } while (s.charAt(i++) == ','); + return map; + } + if (c == '[') { + List list = new ArrayList<>(); + i++; + skip(); + if (s.charAt(i) == ']') { + i++; + return list; + } + do { + list.add(parse()); + skip(); + } while (s.charAt(i++) == ','); + return list; + } + if (c == '"') { + StringBuilder out = new StringBuilder(); + i++; + while ((c = s.charAt(i++)) != '"') { + if (c != '\\') { + out.append(c); + continue; + } + char e = s.charAt(i++); + switch (e) { + case 'n': out.append('\n'); break; + case 'r': out.append('\r'); break; + case 't': out.append('\t'); break; + case 'b': out.append('\b'); break; + case 'f': out.append('\f'); break; + case 'u': out.append((char) Integer.parseInt(s.substring(i, i + 4), 16)); i += 4; break; + default: out.append(e); + } + } + return out.toString(); + } + for (String word : new String[] {"true", "false", "null"}) { + if (s.startsWith(word, i)) { + i += word.length(); + return word.equals("null") ? null : Boolean.valueOf(word); + } + } + int start = i; + while (i < s.length() && "-+.eE0123456789".indexOf(s.charAt(i)) >= 0) { + i++; + } + return Double.valueOf(s.substring(start, i)); + } + + private void skip() { + while (i < s.length() && Character.isWhitespace(s.charAt(i))) { + i++; + } + } + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/JdkHttpTransport.java b/sdk/java/src/main/java/com/supertext/sdk/JdkHttpTransport.java index 12b1411..1f72b72 100644 --- a/sdk/java/src/main/java/com/supertext/sdk/JdkHttpTransport.java +++ b/sdk/java/src/main/java/com/supertext/sdk/JdkHttpTransport.java @@ -4,7 +4,6 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; @@ -41,8 +40,8 @@ public Response send(Request request) throws IOException, InterruptedException { builder.method(request.getMethod(), body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(body)); - // The API answers in UTF-8; decode as such whatever the Content-Type says. - HttpResponse response = http.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + // Bytes: downloads can be binary documents. Response#getBody() decodes UTF-8, whatever the Content-Type says. + HttpResponse response = http.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray()); Map headers = new LinkedHashMap<>(); for (Map.Entry> header : response.headers().map().entrySet()) { if (!header.getValue().isEmpty()) { diff --git a/sdk/java/src/main/java/com/supertext/sdk/Transport.java b/sdk/java/src/main/java/com/supertext/sdk/Transport.java index cb5933e..285a3c5 100644 --- a/sdk/java/src/main/java/com/supertext/sdk/Transport.java +++ b/sdk/java/src/main/java/com/supertext/sdk/Transport.java @@ -64,20 +64,31 @@ public Duration getTimeout() { final class Response { private final int status; private final Map headers; - private final String body; + private final byte[] body; /** * @param headers first value per header name (looked up case-insensitively) * @param body the body decoded as UTF-8 ({@code ""} for none) */ public Response(int status, Map headers, String body) { + this(status, headers, body == null ? new byte[0] : body.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + /** + * An answer with the body as bytes (downloads of binary documents). + * + * @param status HTTP status + * @param headers response headers (names are matched case-insensitively) + * @param body the body; {@code null} for none + */ + public Response(int status, Map headers, byte[] body) { this.status = status; TreeMap map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); if (headers != null) { map.putAll(headers); } this.headers = Collections.unmodifiableMap(map); - this.body = body == null ? "" : body; + this.body = body == null ? new byte[0] : body.clone(); } public int getStatus() { @@ -89,8 +100,14 @@ public String getHeader(String name) { return headers.get(name); } + /** The body decoded as UTF-8 (the API answers in UTF-8). */ public String getBody() { - return body; + return new String(body, java.nio.charset.StandardCharsets.UTF_8); + } + + /** The body as bytes. */ + public byte[] getBodyBytes() { + return body.clone(); } } } diff --git a/sdk/java/src/main/java/com/supertext/sdk/v1/HtmlDocument.java b/sdk/java/src/main/java/com/supertext/sdk/v1/HtmlDocument.java index 6ded7a9..56ff0c3 100644 --- a/sdk/java/src/main/java/com/supertext/sdk/v1/HtmlDocument.java +++ b/sdk/java/src/main/java/com/supertext/sdk/v1/HtmlDocument.java @@ -115,8 +115,8 @@ private static String trimOuter(String inner) { return OUTER_WHITESPACE.matcher(inner).replaceAll(""); } - /** What goes between {@code
} and {@code
} for a segment. */ - static String content(Segment segment) { + /** What goes between {@code
} and {@code
} for a segment (escaped plain text, or the HTML as it is). */ + public static String content(Segment segment) { if (segment.isHtml()) { return segment.getText(); } diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/Account.java b/sdk/java/src/main/java/com/supertext/sdk/v2/Account.java new file mode 100644 index 0000000..c4070bc --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/Account.java @@ -0,0 +1,80 @@ +package com.supertext.sdk.v2; + +import java.util.Objects; + +/** The workspace and key behind the API key. */ +public final class Account { + private final String workspaceId; + private final String workspaceName; + private final String apiKeyName; + private final String apiKeyPrefix; + private final String apiKeyExpiresAt; + + /** + * Creates the value. + * + * @param workspaceId workspace id + * @param workspaceName workspace name + * @param apiKeyName the key's name + * @param apiKeyPrefix the key's prefix + * @param apiKeyExpiresAt when the key expires + */ + public Account(String workspaceId, String workspaceName, String apiKeyName, String apiKeyPrefix, String apiKeyExpiresAt) { + this.workspaceId = workspaceId; + this.workspaceName = workspaceName; + this.apiKeyName = apiKeyName; + this.apiKeyPrefix = apiKeyPrefix; + this.apiKeyExpiresAt = apiKeyExpiresAt; + } + + /** @return workspace id */ + public String getWorkspaceId() { + return workspaceId; + } + + /** @return workspace name */ + public String getWorkspaceName() { + return workspaceName; + } + + /** @return the key's name */ + public String getApiKeyName() { + return apiKeyName; + } + + /** @return the key's prefix */ + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + /** @return when the key expires */ + public String getApiKeyExpiresAt() { + return apiKeyExpiresAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Account)) { + return false; + } + Account other = (Account) o; + return Objects.equals(workspaceId, other.workspaceId) + && Objects.equals(workspaceName, other.workspaceName) + && Objects.equals(apiKeyName, other.apiKeyName) + && Objects.equals(apiKeyPrefix, other.apiKeyPrefix) + && Objects.equals(apiKeyExpiresAt, other.apiKeyExpiresAt); + } + + @Override + public int hashCode() { + return Objects.hash(workspaceId, workspaceName, apiKeyName, apiKeyPrefix, apiKeyExpiresAt); + } + + @Override + public String toString() { + return "Account{" + "workspaceId=" + workspaceId + ", " + "workspaceName=" + workspaceName + ", " + "apiKeyName=" + apiKeyName + ", " + "apiKeyPrefix=" + apiKeyPrefix + ", " + "apiKeyExpiresAt=" + apiKeyExpiresAt + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/DetectedLanguage.java b/sdk/java/src/main/java/com/supertext/sdk/v2/DetectedLanguage.java new file mode 100644 index 0000000..0e5ed2b --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/DetectedLanguage.java @@ -0,0 +1,62 @@ +package com.supertext.sdk.v2; + +import java.util.Objects; + +/** A language the detection found. */ +public final class DetectedLanguage { + private final String langCode; + private final Double confidence; + private final boolean supportsTranslation; + + /** + * Creates the value. + * + * @param langCode BCP 47 code + * @param confidence 0 to 1; {@code null} when unknown + * @param supportsTranslation false when it can't be translated + */ + public DetectedLanguage(String langCode, Double confidence, boolean supportsTranslation) { + this.langCode = langCode; + this.confidence = confidence; + this.supportsTranslation = supportsTranslation; + } + + /** @return BCP 47 code */ + public String getLangCode() { + return langCode; + } + + /** @return 0 to 1; {@code null} when unknown */ + public Double getConfidence() { + return confidence; + } + + /** @return false when it can't be translated */ + public boolean isSupportsTranslation() { + return supportsTranslation; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DetectedLanguage)) { + return false; + } + DetectedLanguage other = (DetectedLanguage) o; + return Objects.equals(langCode, other.langCode) + && Objects.equals(confidence, other.confidence) + && supportsTranslation == other.supportsTranslation; + } + + @Override + public int hashCode() { + return Objects.hash(langCode, confidence, supportsTranslation); + } + + @Override + public String toString() { + return "DetectedLanguage{" + "langCode=" + langCode + ", " + "confidence=" + confidence + ", " + "supportsTranslation=" + supportsTranslation + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/DownloadedFile.java b/sdk/java/src/main/java/com/supertext/sdk/v2/DownloadedFile.java new file mode 100644 index 0000000..7d170fb --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/DownloadedFile.java @@ -0,0 +1,54 @@ +package com.supertext.sdk.v2; + +import java.util.Arrays; +import java.util.Objects; + +/** A downloaded document. */ +public final class DownloadedFile { + private final byte[] content; + private final String fileName; + + /** + * Creates the value. + * + * @param content the document + * @param fileName from {@code Content-Disposition}, when present + */ + public DownloadedFile(byte[] content, String fileName) { + this.content = content == null ? new byte[0] : content.clone(); + this.fileName = fileName; + } + + /** @return the document */ + public byte[] getContent() { + return content.clone(); + } + + /** @return from {@code Content-Disposition}, when present */ + public String getFileName() { + return fileName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DownloadedFile)) { + return false; + } + DownloadedFile other = (DownloadedFile) o; + return Arrays.equals(content, other.content) + && Objects.equals(fileName, other.fileName); + } + + @Override + public int hashCode() { + return Objects.hash(Arrays.hashCode(content), fileName); + } + + @Override + public String toString() { + return "DownloadedFile{" + "content=" + content.length + " bytes" + ", " + "fileName=" + fileName + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/ErrorCode.java b/sdk/java/src/main/java/com/supertext/sdk/v2/ErrorCode.java new file mode 100644 index 0000000..e9daf25 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/ErrorCode.java @@ -0,0 +1,77 @@ +package com.supertext.sdk.v2; + +/** The error codes of the v2 client: fixed strings shared by all Supertext SDKs (spec/v2/errors.json). */ +public enum ErrorCode { + /** No key configured; nothing was sent. */ + MISSING_API_KEY("missing_api_key", "No Supertext API key is configured."), + /** HTTP 401/403. */ + AUTHENTICATION_FAILURE("authentication_failure", "Supertext rejected the API key. Please check it."), + /** HTTP 402: the credit balance doesn't cover the request. */ + INSUFFICIENT_CREDIT("insufficient_credit", "The Supertext credit balance does not cover this request. Please top up."), + /** HTTP 422: validation, e.g. a language the API doesn't offer. */ + INVALID_REQUEST("invalid_request", "Supertext rejected the request."), + /** A blank language code; nothing was sent. */ + UNSUPPORTED_LANGUAGE("unsupported_language", "This language has no Supertext language code. Map it to a Supertext language."), + /** HTTP 404. */ + NOT_FOUND("not_found", "Not found at Supertext (expired or already deleted)."), + /** HTTP 409, e.g. webhook_limit_reached. */ + CONFLICT("conflict", "Supertext refused the change."), + /** HTTP 413. */ + PAYLOAD_TOO_LARGE("payload_too_large", "The document is too large for Supertext."), + /** HTTP 429 after the retries. */ + TOO_MANY_REQUESTS("too_many_requests", "Too many requests to Supertext. Please try again shortly."), + /** HTTP 5xx. */ + SERVICE_UNAVAILABLE("service_unavailable", "The Supertext service is unavailable."), + /** Any other HTTP status. */ + UNEXPECTED_STATUS("unexpected_status", "Supertext sent an unexpected HTTP status."), + /** No HTTP answer. */ + TRANSPORT_ERROR("transport_error", "Could not reach Supertext."), + /** The answer lacks what it should carry. */ + INCOMPLETE_RESPONSE("incomplete_response", "The Supertext answer is incomplete."), + /** Status error (AI file) or failed (human review). */ + TRANSLATION_ERROR("translation_error", "Supertext failed to translate."), + /** The file was deleted before it could be downloaded. */ + FILE_DELETED("file_deleted", "The Supertext file was deleted before it could be downloaded."), + /** Waited longer than the timeout. */ + TIMEOUT("timeout", "Timed out waiting for the Supertext translation to finish."), + /** A webhook request that isn't a valid, signed event. */ + INVALID_WEBHOOK("invalid_webhook", "The webhook request is not a valid, signed Supertext event."); + + private final String value; + private final String message; + + ErrorCode(String value, String message) { + this.value = value; + this.message = message; + } + + /** @return the shared string, e.g. {@code insufficient_credit} */ + public String value() { + return value; + } + + /** @return an English message */ + public String message() { + return message; + } + + /** + * The code for a shared string. + * + * @param value e.g. {@code not_found} + * @return the code + */ + public static ErrorCode fromValue(String value) { + for (ErrorCode code : values()) { + if (code.value.equals(value)) { + return code; + } + } + throw new IllegalArgumentException("Unknown Supertext error code: " + value); + } + + @Override + public String toString() { + return value; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/FeatureSupport.java b/sdk/java/src/main/java/com/supertext/sdk/v2/FeatureSupport.java new file mode 100644 index 0000000..ffd9f73 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/FeatureSupport.java @@ -0,0 +1,65 @@ +package com.supertext.sdk.v2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** One language pair from {@code GET features}. */ +public final class FeatureSupport { + private final String sourceLang; + private final String targetLang; + private final List features; + + /** + * Creates the value. + * + * @param sourceLang source code + * @param targetLang target code + * @param features {@code supports_politeness}, {@code supports_glossary}, {@code supports_fused_translation} + */ + public FeatureSupport(String sourceLang, String targetLang, List features) { + this.sourceLang = sourceLang; + this.targetLang = targetLang; + this.features = features == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(features)); + } + + /** @return source code */ + public String getSourceLang() { + return sourceLang; + } + + /** @return target code */ + public String getTargetLang() { + return targetLang; + } + + /** @return {@code supports_politeness}, {@code supports_glossary}, {@code supports_fused_translation} */ + public List getFeatures() { + return features; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof FeatureSupport)) { + return false; + } + FeatureSupport other = (FeatureSupport) o; + return Objects.equals(sourceLang, other.sourceLang) + && Objects.equals(targetLang, other.targetLang) + && Objects.equals(features, other.features); + } + + @Override + public int hashCode() { + return Objects.hash(sourceLang, targetLang, features); + } + + @Override + public String toString() { + return "FeatureSupport{" + "sourceLang=" + sourceLang + ", " + "targetLang=" + targetLang + ", " + "features=" + features + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/FileStatus.java b/sdk/java/src/main/java/com/supertext/sdk/v2/FileStatus.java new file mode 100644 index 0000000..b1927e0 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/FileStatus.java @@ -0,0 +1,71 @@ +package com.supertext.sdk.v2; + +import java.util.Objects; + +/** Status of an AI file translation. */ +public final class FileStatus { + private final String status; + private final String error; + private final Integer estimatedSecondsLeft; + private final String detectedSourceLang; + + /** + * Creates the value. + * + * @param status {@code translating}, {@code done}, {@code error}, {@code deleted} + * @param error what went wrong, for {@code error} + * @param estimatedSecondsLeft time remaining, when known + * @param detectedSourceLang the source language used + */ + public FileStatus(String status, String error, Integer estimatedSecondsLeft, String detectedSourceLang) { + this.status = status; + this.error = error; + this.estimatedSecondsLeft = estimatedSecondsLeft; + this.detectedSourceLang = detectedSourceLang; + } + + /** @return {@code translating}, {@code done}, {@code error}, {@code deleted} */ + public String getStatus() { + return status; + } + + /** @return what went wrong, for {@code error} */ + public String getError() { + return error; + } + + /** @return time remaining, when known */ + public Integer getEstimatedSecondsLeft() { + return estimatedSecondsLeft; + } + + /** @return the source language used */ + public String getDetectedSourceLang() { + return detectedSourceLang; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof FileStatus)) { + return false; + } + FileStatus other = (FileStatus) o; + return Objects.equals(status, other.status) + && Objects.equals(error, other.error) + && Objects.equals(estimatedSecondsLeft, other.estimatedSecondsLeft) + && Objects.equals(detectedSourceLang, other.detectedSourceLang); + } + + @Override + public int hashCode() { + return Objects.hash(status, error, estimatedSecondsLeft, detectedSourceLang); + } + + @Override + public String toString() { + return "FileStatus{" + "status=" + status + ", " + "error=" + error + ", " + "estimatedSecondsLeft=" + estimatedSecondsLeft + ", " + "detectedSourceLang=" + detectedSourceLang + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/FusedOrder.java b/sdk/java/src/main/java/com/supertext/sdk/v2/FusedOrder.java new file mode 100644 index 0000000..203bb6d --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/FusedOrder.java @@ -0,0 +1,71 @@ +package com.supertext.sdk.v2; + +import java.util.Objects; + +/** An accepted human-review order. */ +public final class FusedOrder { + private final String translationId; + private final boolean briefingApplied; + private final String serviceLabel; + private final String requestId; + + /** + * Creates the value. + * + * @param translationId the order id + * @param briefingApplied true: Optimisation (with briefing); false: Verification + * @param serviceLabel for display only + * @param requestId the request id + */ + public FusedOrder(String translationId, boolean briefingApplied, String serviceLabel, String requestId) { + this.translationId = translationId; + this.briefingApplied = briefingApplied; + this.serviceLabel = serviceLabel; + this.requestId = requestId; + } + + /** @return the order id */ + public String getTranslationId() { + return translationId; + } + + /** @return true: Optimisation (with briefing); false: Verification */ + public boolean isBriefingApplied() { + return briefingApplied; + } + + /** @return for display only */ + public String getServiceLabel() { + return serviceLabel; + } + + /** @return the request id */ + public String getRequestId() { + return requestId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof FusedOrder)) { + return false; + } + FusedOrder other = (FusedOrder) o; + return Objects.equals(translationId, other.translationId) + && briefingApplied == other.briefingApplied + && Objects.equals(serviceLabel, other.serviceLabel) + && Objects.equals(requestId, other.requestId); + } + + @Override + public int hashCode() { + return Objects.hash(translationId, briefingApplied, serviceLabel, requestId); + } + + @Override + public String toString() { + return "FusedOrder{" + "translationId=" + translationId + ", " + "briefingApplied=" + briefingApplied + ", " + "serviceLabel=" + serviceLabel + ", " + "requestId=" + requestId + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/FusedQuote.java b/sdk/java/src/main/java/com/supertext/sdk/v2/FusedQuote.java new file mode 100644 index 0000000..01b07d0 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/FusedQuote.java @@ -0,0 +1,92 @@ +package com.supertext.sdk.v2; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** What a human-review order would cost and how long it would take. */ +public final class FusedQuote { + private final Map prices; + private final int estimatedDurationSeconds; + private final int wordCount; + private final Integer characterCount; + private final boolean briefingApplied; + private final String serviceLabel; + + /** + * Creates the value. + * + * @param prices keyed by lower-case currency code + * @param estimatedDurationSeconds expected delivery time + * @param wordCount source words priced + * @param characterCount files only + * @param briefingApplied Optimisation (true) or Verification + * @param serviceLabel for display only + */ + public FusedQuote(Map prices, int estimatedDurationSeconds, int wordCount, Integer characterCount, boolean briefingApplied, String serviceLabel) { + this.prices = prices == null ? Collections.emptyMap() : Collections.unmodifiableMap(new LinkedHashMap<>(prices)); + this.estimatedDurationSeconds = estimatedDurationSeconds; + this.wordCount = wordCount; + this.characterCount = characterCount; + this.briefingApplied = briefingApplied; + this.serviceLabel = serviceLabel; + } + + /** @return keyed by lower-case currency code */ + public Map getPrices() { + return prices; + } + + /** @return expected delivery time */ + public int getEstimatedDurationSeconds() { + return estimatedDurationSeconds; + } + + /** @return source words priced */ + public int getWordCount() { + return wordCount; + } + + /** @return files only */ + public Integer getCharacterCount() { + return characterCount; + } + + /** @return Optimisation (true) or Verification */ + public boolean isBriefingApplied() { + return briefingApplied; + } + + /** @return for display only */ + public String getServiceLabel() { + return serviceLabel; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof FusedQuote)) { + return false; + } + FusedQuote other = (FusedQuote) o; + return Objects.equals(prices, other.prices) + && estimatedDurationSeconds == other.estimatedDurationSeconds + && wordCount == other.wordCount + && Objects.equals(characterCount, other.characterCount) + && briefingApplied == other.briefingApplied + && Objects.equals(serviceLabel, other.serviceLabel); + } + + @Override + public int hashCode() { + return Objects.hash(prices, estimatedDurationSeconds, wordCount, characterCount, briefingApplied, serviceLabel); + } + + @Override + public String toString() { + return "FusedQuote{" + "prices=" + prices + ", " + "estimatedDurationSeconds=" + estimatedDurationSeconds + ", " + "wordCount=" + wordCount + ", " + "characterCount=" + characterCount + ", " + "briefingApplied=" + briefingApplied + ", " + "serviceLabel=" + serviceLabel + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/FusedStatus.java b/sdk/java/src/main/java/com/supertext/sdk/v2/FusedStatus.java new file mode 100644 index 0000000..4b4ceff --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/FusedStatus.java @@ -0,0 +1,71 @@ +package com.supertext.sdk.v2; + +import java.util.Objects; + +/** Status of a human-review order. */ +public final class FusedStatus { + private final String status; + private final String detectedSourceLang; + private final int estimatedSecondsLeft; + private final String error; + + /** + * Creates the value. + * + * @param status {@code in_progress}, {@code completed}, {@code failed} + * @param detectedSourceLang the source language + * @param estimatedSecondsLeft negative: the promised time has passed + * @param error why it failed + */ + public FusedStatus(String status, String detectedSourceLang, int estimatedSecondsLeft, String error) { + this.status = status; + this.detectedSourceLang = detectedSourceLang; + this.estimatedSecondsLeft = estimatedSecondsLeft; + this.error = error; + } + + /** @return {@code in_progress}, {@code completed}, {@code failed} */ + public String getStatus() { + return status; + } + + /** @return the source language */ + public String getDetectedSourceLang() { + return detectedSourceLang; + } + + /** @return negative: the promised time has passed */ + public int getEstimatedSecondsLeft() { + return estimatedSecondsLeft; + } + + /** @return why it failed */ + public String getError() { + return error; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof FusedStatus)) { + return false; + } + FusedStatus other = (FusedStatus) o; + return Objects.equals(status, other.status) + && Objects.equals(detectedSourceLang, other.detectedSourceLang) + && estimatedSecondsLeft == other.estimatedSecondsLeft + && Objects.equals(error, other.error); + } + + @Override + public int hashCode() { + return Objects.hash(status, detectedSourceLang, estimatedSecondsLeft, error); + } + + @Override + public String toString() { + return "FusedStatus{" + "status=" + status + ", " + "detectedSourceLang=" + detectedSourceLang + ", " + "estimatedSecondsLeft=" + estimatedSecondsLeft + ", " + "error=" + error + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/Json.java b/sdk/java/src/main/java/com/supertext/sdk/v2/Json.java new file mode 100644 index 0000000..4e36bb4 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/Json.java @@ -0,0 +1,293 @@ +package com.supertext.sdk.v2; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Minimal JSON reader and writer, so the SDK has no runtime dependencies. The API answers with a few flat + * fields ({@code file_id}, {@code status}, {@code error_code}); this reads any valid JSON into + * {@link Map} (insertion-ordered), {@link List}, {@link String}, {@link Double}, {@link Boolean} or {@code null}, + * and writes those types (plus other {@link Number}s) back as compact JSON. + */ +final class Json { + + private final String s; + private int i; + + private Json(String s) { + this.s = s; + } + + /** Parses a JSON text; throws {@link IllegalArgumentException} when it isn't valid JSON. */ + static Object parse(String text) { + Json p = new Json(text); + p.skip(); + Object value = p.value(); + p.skip(); + if (p.i != text.length()) { + throw p.fail("trailing characters"); + } + return value; + } + + /** The string field {@code name} of a JSON object text, or {@code null} (not JSON, not an object, missing or not a string). */ + static String stringField(String text, String name) { + if (text == null) { + return null; + } + try { + Object value = parse(text); + if (value instanceof Map) { + Object field = ((Map) value).get(name); + return field instanceof String ? (String) field : null; + } + } catch (IllegalArgumentException e) { + // Not JSON: no field. + } + return null; + } + + /** Compact JSON for maps (string keys), lists, strings, numbers, booleans and {@code null}. */ + static String write(Object value) { + StringBuilder out = new StringBuilder(); + write(out, value); + return out.toString(); + } + + private static void write(StringBuilder out, Object value) { + if (value == null) { + out.append("null"); + } else if (value instanceof String) { + quote(out, (String) value); + } else if (value instanceof Boolean) { + out.append(value.toString()); + } else if (value instanceof Double || value instanceof Float) { + double d = ((Number) value).doubleValue(); + if (Double.isNaN(d) || Double.isInfinite(d)) { + out.append("null"); + } else if (d == Math.rint(d) && Math.abs(d) < 1e15) { + out.append((long) d); + } else { + out.append(d); + } + } else if (value instanceof Number) { + out.append(value.toString()); + } else if (value instanceof Map) { + out.append('{'); + boolean first = true; + for (Map.Entry entry : ((Map) value).entrySet()) { + if (!first) { + out.append(','); + } + first = false; + quote(out, String.valueOf(entry.getKey())); + out.append(':'); + write(out, entry.getValue()); + } + out.append('}'); + } else if (value instanceof List) { + out.append('['); + boolean first = true; + for (Object item : (List) value) { + if (!first) { + out.append(','); + } + first = false; + write(out, item); + } + out.append(']'); + } else { + throw new IllegalArgumentException("Cannot write " + value.getClass().getName() + " as JSON"); + } + } + + private static void quote(StringBuilder out, String text) { + out.append('"'); + for (int k = 0; k < text.length(); k++) { + char c = text.charAt(k); + switch (c) { + case '"': out.append("\\\""); break; + case '\\': out.append("\\\\"); break; + case '\n': out.append("\\n"); break; + case '\r': out.append("\\r"); break; + case '\t': out.append("\\t"); break; + case '\b': out.append("\\b"); break; + case '\f': out.append("\\f"); break; + default: + if (c < 0x20 || c == 0x2028 || c == 0x2029) { + out.append(String.format("\\u%04x", (int) c)); + } else { + out.append(c); + } + } + } + out.append('"'); + } + + private Object value() { + if (i >= s.length()) { + throw fail("unexpected end"); + } + char c = s.charAt(i); + switch (c) { + case '{': return object(); + case '[': return array(); + case '"': return string(); + case 't': return literal("true", Boolean.TRUE); + case 'f': return literal("false", Boolean.FALSE); + case 'n': return literal("null", null); + default: + if (c == '-' || (c >= '0' && c <= '9')) { + return number(); + } + throw fail("unexpected character"); + } + } + + private Map object() { + Map map = new LinkedHashMap<>(); + i++; + skip(); + if (peek() == '}') { + i++; + return map; + } + while (true) { + skip(); + if (peek() != '"') { + throw fail("expected a key"); + } + String key = string(); + skip(); + expect(':'); + skip(); + map.put(key, value()); + skip(); + if (peek() == ',') { + i++; + } else { + expect('}'); + return map; + } + } + } + + private List array() { + List list = new ArrayList<>(); + i++; + skip(); + if (peek() == ']') { + i++; + return list; + } + while (true) { + skip(); + list.add(value()); + skip(); + if (peek() == ',') { + i++; + } else { + expect(']'); + return list; + } + } + } + + private String string() { + i++; // opening quote + StringBuilder out = new StringBuilder(); + while (true) { + if (i >= s.length()) { + throw fail("unterminated string"); + } + char c = s.charAt(i++); + if (c == '"') { + return out.toString(); + } + if (c < 0x20) { + throw fail("control character in string"); + } + if (c != '\\') { + out.append(c); + continue; + } + if (i >= s.length()) { + throw fail("unterminated escape"); + } + char e = s.charAt(i++); + switch (e) { + case '"': out.append('"'); break; + case '\\': out.append('\\'); break; + case '/': out.append('/'); break; + case 'b': out.append('\b'); break; + case 'f': out.append('\f'); break; + case 'n': out.append('\n'); break; + case 'r': out.append('\r'); break; + case 't': out.append('\t'); break; + case 'u': + if (i + 4 > s.length()) { + throw fail("bad unicode escape"); + } + try { + out.append((char) Integer.parseInt(s.substring(i, i + 4), 16)); + } catch (NumberFormatException ex) { + throw fail("bad unicode escape"); + } + i += 4; + break; + default: + throw fail("bad escape"); + } + } + } + + private Double number() { + int start = i; + if (peek() == '-') { + i++; + } + while (i < s.length() && "0123456789.eE+-".indexOf(s.charAt(i)) >= 0) { + i++; + } + try { + return Double.valueOf(s.substring(start, i)); + } catch (NumberFormatException e) { + throw fail("bad number"); + } + } + + private Object literal(String word, Object value) { + if (!s.startsWith(word, i)) { + throw fail("unexpected literal"); + } + i += word.length(); + return value; + } + + private char peek() { + return i < s.length() ? s.charAt(i) : '\0'; + } + + private void expect(char c) { + if (peek() != c) { + throw fail("expected '" + c + "'"); + } + i++; + } + + private void skip() { + while (i < s.length()) { + char c = s.charAt(i); + if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { + return; + } + i++; + } + } + + private IllegalArgumentException fail(String why) { + return new IllegalArgumentException("Invalid JSON at " + i + ": " + why); + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/PlannedRequest.java b/sdk/java/src/main/java/com/supertext/sdk/v2/PlannedRequest.java new file mode 100644 index 0000000..1cb1d80 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/PlannedRequest.java @@ -0,0 +1,56 @@ +package com.supertext.sdk.v2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** One request of {@code translateTexts}: kind {@code text}, {@code html} or {@code file}. */ +public final class PlannedRequest { + private final String kind; + private final List keys; + + /** + * Creates the value. + * + * @param kind {@code text}, {@code html} or {@code file} + * @param keys the segment keys, in order + */ + public PlannedRequest(String kind, List keys) { + this.kind = kind; + this.keys = keys == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(keys)); + } + + /** @return {@code text}, {@code html} or {@code file} */ + public String getKind() { + return kind; + } + + /** @return the segment keys, in order */ + public List getKeys() { + return keys; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof PlannedRequest)) { + return false; + } + PlannedRequest other = (PlannedRequest) o; + return Objects.equals(kind, other.kind) + && Objects.equals(keys, other.keys); + } + + @Override + public int hashCode() { + return Objects.hash(kind, keys); + } + + @Override + public String toString() { + return "PlannedRequest{" + "kind=" + kind + ", " + "keys=" + keys + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/Quote.java b/sdk/java/src/main/java/com/supertext/sdk/v2/Quote.java new file mode 100644 index 0000000..c982017 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/Quote.java @@ -0,0 +1,56 @@ +package com.supertext.sdk.v2; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** What a request would cost (a free dry run). */ +public final class Quote { + private final int characterCount; + private final Map prices; + + /** + * Creates the value. + * + * @param characterCount characters metered + * @param prices keyed by lower-case currency code; not rounded to the cent + */ + public Quote(int characterCount, Map prices) { + this.characterCount = characterCount; + this.prices = prices == null ? Collections.emptyMap() : Collections.unmodifiableMap(new LinkedHashMap<>(prices)); + } + + /** @return characters metered */ + public int getCharacterCount() { + return characterCount; + } + + /** @return keyed by lower-case currency code; not rounded to the cent */ + public Map getPrices() { + return prices; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Quote)) { + return false; + } + Quote other = (Quote) o; + return characterCount == other.characterCount + && Objects.equals(prices, other.prices); + } + + @Override + public int hashCode() { + return Objects.hash(characterCount, prices); + } + + @Override + public String toString() { + return "Quote{" + "characterCount=" + characterCount + ", " + "prices=" + prices + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/SupertextClient.java b/sdk/java/src/main/java/com/supertext/sdk/v2/SupertextClient.java new file mode 100644 index 0000000..f789f43 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/SupertextClient.java @@ -0,0 +1,1379 @@ +package com.supertext.sdk.v2; + +import com.supertext.sdk.JdkHttpTransport; +import com.supertext.sdk.Transport; +import com.supertext.sdk.v1.ApiKeyCheck; +import com.supertext.sdk.v1.HtmlDocument; +import com.supertext.sdk.v1.Politeness; +import com.supertext.sdk.v1.Segment; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.LongSupplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Client for the Supertext API v2 (https://api-platform.supertext.com/v1, workspace keys sent as + * {@code Bearer st_live_…}): text translation in one request, AI file translation, language detection, + * human review ("fused"), quotes, the account and webhooks. Thread-safe; build one per key. + */ +public final class SupertextClient { + + /** The live API. */ + public static final String LIVE_BASE_URL = "https://api-platform.supertext.com/v1/"; + + /** Characters per {@code POST translate/ai/text}: the API's limit. */ + public static final int DEFAULT_MAX_TEXT_CHARACTERS = 10_000; + + private static final int DEFAULT_MAX_FILE_CHARACTERS = 900_000; + private static final Pattern BEARER = Pattern.compile("^bearer(?:[ \\t\\n\\r\\f]+|$)", Pattern.CASE_INSENSITIVE); + private static final Pattern FILENAME_STAR = Pattern.compile("filename\\*\\s*=\\s*UTF-8''([^;]+)", Pattern.CASE_INSENSITIVE); + private static final Pattern FILENAME_PLAIN = Pattern.compile("filename\\s*=\\s*(?:\"([^\"]*)\"|([^;\\s]+))", Pattern.CASE_INSENSITIVE); + private static final SecureRandom RANDOM = new SecureRandom(); + private static final Map TYPES = new LinkedHashMap<>(); + + static { + TYPES.put("html", "text/html"); + TYPES.put("htm", "text/html"); + TYPES.put("txt", "text/plain"); + TYPES.put("srt", "application/x-subrip"); + TYPES.put("pdf", "application/pdf"); + TYPES.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + TYPES.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); + TYPES.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + } + + /** How the client waits (tests replace it). */ + @FunctionalInterface + public interface Sleeper { + /** + * Waits. + * + * @param duration how long + * @throws InterruptedException when interrupted + */ + void sleep(Duration duration) throws InterruptedException; + } + + /** How inline markup in texts is handled. */ + public enum TagHandling { + /** Plain text. */ + NONE, + /** XML, parsed strictly. */ + XML, + /** HTML, malformed markup tolerated. */ + HTML + } + + private final String apiKey; + private final String baseUrl; + private final Duration pollInterval; + private final Duration timeout; + private final Duration requestTimeout; + private final int maxRetries; + private final String userAgent; + private final Transport transport; + private final Sleeper sleeper; + private final LongSupplier nanoTime; + private final Clock wallClock; + + private SupertextClient(Builder b) { + this.apiKey = b.apiKey == null ? "" : b.apiKey; + String base = b.baseUrl == null || b.baseUrl.trim().isEmpty() ? LIVE_BASE_URL : b.baseUrl.trim(); + this.baseUrl = base.endsWith("/") ? base : base + "/"; + this.pollInterval = b.pollInterval; + this.timeout = b.timeout; + this.requestTimeout = b.requestTimeout; + this.maxRetries = b.maxRetries; + String agent = "supertext-sdk-java"; + this.userAgent = b.userAgent == null || b.userAgent.trim().isEmpty() ? agent : agent + " " + b.userAgent.trim(); + this.transport = b.transport != null ? b.transport : new JdkHttpTransport(); + this.sleeper = b.sleeper != null ? b.sleeper : d -> Thread.sleep(d.toMillis()); + this.nanoTime = b.nanoTime != null ? b.nanoTime : System::nanoTime; + this.wallClock = b.wallClock != null ? b.wallClock : Clock.systemUTC(); + } + + /** + * A builder; a blank key doesn't throw here: the first request throws {@code missing_api_key}. + * + * @param apiKey the key as pasted (a leading {@code Bearer } is stripped) + * @return the builder + */ + public static Builder builder(String apiKey) { + return new Builder(apiKey); + } + + @Override + public String toString() { + return "SupertextClient{baseUrl=" + baseUrl + "}"; + } + + // ---- protocol helpers + + /** + * {@code Bearer } for a key as pasted (spec/v2/auth-header.json). + * + * @param apiKey the key + * @return the header value + * @throws SupertextException {@code missing_api_key} for a blank key + */ + public static String authHeader(String apiKey) { + String key = trimAscii(BEARER.matcher(trimAscii(apiKey == null ? "" : apiKey)).replaceFirst("")); + if (key.isEmpty()) { + throw new SupertextException(ErrorCode.MISSING_API_KEY); + } + return "Bearer " + key; + } + + /** + * SHA-256 (lower-case hex) of the key as {@link #authHeader(String)} sends it; {@code ""} for a blank key. + * + * @param apiKey the key + * @return the fingerprint + */ + public static String fingerprint(String apiKey) { + String key; + try { + key = authHeader(apiKey).substring("Bearer ".length()); + } catch (SupertextException e) { + return ""; + } + try { + byte[] hash = MessageDigest.getInstance("SHA-256").digest(key.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(64); + for (byte x : hash) { + hex.append(Character.forDigit((x >> 4) & 0xf, 16)).append(Character.forDigit(x & 0xf, 16)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available", e); + } + } + + /** + * Splits segments into requests (spec/v2/batching.json). + * + * @param segments key → segment, in order + * @param maxCharacters characters per text request + * @return the requests + */ + public static List planRequests(Map segments, int maxCharacters) { + Map plain = new LinkedHashMap<>(); + Map html = new LinkedHashMap<>(); + List oversized = new ArrayList<>(); + Map big = new LinkedHashMap<>(); + for (Map.Entry e : segments.entrySet()) { + String text = e.getValue().getText(); + if (isBlank(text)) { + continue; + } + int length = text.codePointCount(0, text.length()); + if (length > maxCharacters) { + oversized.add(e.getKey()); + big.put(e.getKey(), e.getValue()); + } else if (e.getValue().isHtml()) { + html.put(e.getKey(), length); + } else { + plain.put(e.getKey(), length); + } + } + List out = new ArrayList<>(); + split("text", plain, maxCharacters, out); + split("html", html, maxCharacters, out); + List current = new ArrayList<>(); + long size = 0; + for (String key : oversized) { + String content = HtmlDocument.content(big.get(key)); + long length = content.codePointCount(0, content.length()); + if (!current.isEmpty() && size + length > DEFAULT_MAX_FILE_CHARACTERS) { + out.add(new PlannedRequest("file", current)); + current = new ArrayList<>(); + size = 0; + } + current.add(key); + size += length; + } + if (!current.isEmpty()) { + out.add(new PlannedRequest("file", current)); + } + return out; + } + + private static void split(String kind, Map lengths, int maxCharacters, List out) { + List current = new ArrayList<>(); + long size = 0; + for (Map.Entry e : lengths.entrySet()) { + if (!current.isEmpty() && size + e.getValue() > maxCharacters) { + out.add(new PlannedRequest(kind, current)); + current = new ArrayList<>(); + size = 0; + } + current.add(e.getKey()); + size += e.getValue(); + } + if (!current.isEmpty()) { + out.add(new PlannedRequest(kind, current)); + } + } + + /** + * The Content-Type for a file name's extension; else {@code application/octet-stream}. + * + * @param fileName the file name + * @return the type + */ + public static String contentTypeFor(String fileName) { + int dot = fileName == null ? -1 : fileName.lastIndexOf('.'); + String type = dot < 0 ? null : TYPES.get(fileName.substring(dot + 1).toLowerCase(Locale.ROOT)); + return type != null ? type : "application/octet-stream"; + } + + /** + * The file name of a {@code Content-Disposition} header ({@code filename*=UTF-8''…} preferred). + * + * @param disposition the header, or {@code null} + * @return the file name, or {@code null} + */ + public static String fileNameFrom(String disposition) { + if (disposition == null || disposition.isEmpty()) { + return null; + } + Matcher star = FILENAME_STAR.matcher(disposition); + if (star.find()) { + try { + return URLDecoder.decode(star.group(1).trim().replace("+", "%2B"), "UTF-8"); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + // fall through to the plain parameter + } + } + Matcher plain = FILENAME_PLAIN.matcher(disposition); + return plain.find() ? (plain.group(1) != null ? plain.group(1) : plain.group(2)) : null; + } + + // ---- account and features + + /** + * The workspace and key behind the API key. Cost-free. + * + * @return the account + * @throws InterruptedException when interrupted + */ + public Account getAccount() throws InterruptedException { + Map o = json("GET", "account", null, null, null); + return new Account(text(o, "workspace_id"), text(o, "workspace_name"), text(o, "api_key_name"), text(o, "api_key_prefix"), text(o, "api_key_expires_at")); + } + + /** + * The language pairs and their features, optionally filtered. Cost-free. + * + * @param sourceLang only this source, or {@code null} + * @param targetLang only this target, or {@code null} + * @return the pairs + * @throws InterruptedException when interrupted + */ + public List getFeatures(String sourceLang, String targetLang) throws InterruptedException { + List query = new ArrayList<>(); + if (sourceLang != null && !sourceLang.isEmpty()) { + query.add("source_lang=" + encode(sourceLang)); + } + if (targetLang != null && !targetLang.isEmpty()) { + query.add("target_lang=" + encode(targetLang)); + } + Map o = json("GET", query.isEmpty() ? "features" : "features?" + String.join("&", query), null, null, null); + List result = new ArrayList<>(); + Object list = o.get("supported_features"); + if (list instanceof List) { + for (Object item : (List) list) { + Map m = object(item); + if (m.get("source_lang") instanceof String && m.get("target_lang") instanceof String) { + result.add(new FeatureSupport((String) m.get("source_lang"), (String) m.get("target_lang"), strings(m.get("features")))); + } + } + } + return result; + } + + /** + * All language pairs and their features. + * + * @return the pairs + * @throws InterruptedException when interrupted + */ + public List getFeatures() throws InterruptedException { + return getFeatures(null, null); + } + + /** + * Throws unless the key is accepted ({@code GET account}). + * + * @throws InterruptedException when interrupted + */ + public void validateApiKey() throws InterruptedException { + request("GET", "account", null, null, requestTimeout, null); + } + + /** + * The automatic key check (spec/v2/api-key-check.json). Never throws (except when interrupted). + * + * @return the check + * @throws InterruptedException when interrupted + */ + public ApiKeyCheck checkApiKey() throws InterruptedException { + String checkedAt = ApiKeyCheck.isoSeconds(wallClock.instant()); + String fingerprint = fingerprint(apiKey); + if (fingerprint.isEmpty()) { + return new ApiKeyCheck(ApiKeyCheck.Status.MISSING, checkedAt, null, null, ""); + } + try { + Duration t = ApiKeyCheck.TIMEOUT.compareTo(requestTimeout) < 0 ? ApiKeyCheck.TIMEOUT : requestTimeout; + Transport.Response response = request("GET", "account", null, null, t, null); + return new ApiKeyCheck(ApiKeyCheck.Status.OK, checkedAt, response.getStatus(), null, fingerprint); + } catch (RuntimeException e) { + return keyCheckFromError(e, checkedAt, fingerprint); + } + } + + /** + * The key check for a failed {@code GET account}. + * + * @param error what was thrown + * @param checkedAt when + * @param fingerprint the key's fingerprint + * @return the check + */ + public static ApiKeyCheck keyCheckFromError(Throwable error, String checkedAt, String fingerprint) { + if (!(error instanceof SupertextException)) { + return new ApiKeyCheck(ApiKeyCheck.Status.ERROR, checkedAt, null, null, fingerprint); + } + SupertextException e = (SupertextException) error; + Integer http = e.getStatus(); + ApiKeyCheck.Status status; + if (e.getCode() == ErrorCode.MISSING_API_KEY) { + status = ApiKeyCheck.Status.MISSING; + } else if (http != null && (http == 401 || http == 403)) { + status = ApiKeyCheck.Status.INVALID; + } else if (http == null || http >= 500) { + status = ApiKeyCheck.Status.UNREACHABLE; + } else { + status = ApiKeyCheck.Status.ERROR; + } + String code = e.getApiErrorCode(); + return new ApiKeyCheck(status, checkedAt, http, code == null ? null : code.substring(0, Math.min(100, code.length())), fingerprint); + } + + // ---- text + + /** + * One {@code POST translate/ai/text}: the translations in input order. Codes are sent as given. + * + * @param texts the texts + * @param targetLang target (BCP 47) + * @param sourceLang source, or {@code null} to detect + * @param politeness formal or informal address + * @param glossary source → target terms (at most 100), or {@code null} + * @param tagHandling how inline markup is handled + * @return the translations + * @throws InterruptedException when interrupted + */ + public TextTranslation translateText(List texts, String targetLang, String sourceLang, Politeness politeness, + Map glossary, TagHandling tagHandling) throws InterruptedException { + Map o = json("POST", "translate/ai/text", jsonBytes(textPayload(texts, targetLang, sourceLang, politeness, glossary, tagHandling)), "application/json", null); + List translations = strings(o.get("translated_text")); + if (!(o.get("translated_text") instanceof List) || translations.size() != texts.size()) { + throw new SupertextException(ErrorCode.INCOMPLETE_RESPONSE, null, "expected " + texts.size() + " translations", null, null, null, null); + } + return new TextTranslation(translations, textOrNull(o, "detected_source_lang"), stringMap(o.get("enforced_terms")), textOrNull(o, "request_id")); + } + + /** + * What {@link #translateText} would cost (a free dry run). + * + * @param texts the texts + * @param targetLang target + * @param sourceLang source, or {@code null} + * @param politeness formal or informal address + * @param glossary glossary, or {@code null} + * @param tagHandling how inline markup is handled + * @return the quote + * @throws InterruptedException when interrupted + */ + public Quote quoteText(List texts, String targetLang, String sourceLang, Politeness politeness, + Map glossary, TagHandling tagHandling) throws InterruptedException { + return quote(json("POST", "translate/ai/text/quote", jsonBytes(textPayload(texts, targetLang, sourceLang, politeness, glossary, tagHandling)), "application/json", null)); + } + + /** + * Translates keyed texts (spec/v2/batching.json): the same keys in input order, blanks unchanged. + * + * @param segments key → segment, in order + * @param targetLang target + * @return key → translation + * @throws InterruptedException when interrupted + */ + public Map translateTexts(Map segments, String targetLang) throws InterruptedException { + return translateTexts(segments, targetLang, null, Politeness.DEFAULT, null, DEFAULT_MAX_TEXT_CHARACTERS); + } + + /** + * Translates keyed texts (spec/v2/batching.json): the same keys in input order, blanks unchanged. Up to + * {@code maxCharacters} per request; a longer segment goes through an HTML file. + * + * @param segments key → segment, in order + * @param targetLang target + * @param sourceLang source, or {@code null} + * @param politeness formal or informal address + * @param glossary glossary, or {@code null} + * @param maxCharacters characters per text request + * @return key → translation + * @throws InterruptedException when interrupted + */ + public Map translateTexts(Map segments, String targetLang, String sourceLang, Politeness politeness, + Map glossary, int maxCharacters) throws InterruptedException { + required(targetLang); + Map result = new LinkedHashMap<>(); + for (Map.Entry e : segments.entrySet()) { + result.put(e.getKey(), e.getValue().getText()); + } + for (PlannedRequest planned : planRequests(segments, maxCharacters)) { + List batch = new ArrayList<>(); + for (String key : planned.getKeys()) { + batch.add(segments.get(key)); + } + if (planned.getKind().equals("file")) { + List parsed = HtmlDocument.parse(translateHtml(HtmlDocument.build(batch), targetLang, sourceLang, politeness, glossary), batch); + List missing = new ArrayList<>(); + for (int i = 0; i < batch.size(); i++) { + if (parsed.get(i) == null) { + missing.add(planned.getKeys().get(i)); + } else { + result.put(planned.getKeys().get(i), parsed.get(i)); + } + } + if (!missing.isEmpty()) { + throw new SupertextException(ErrorCode.INCOMPLETE_RESPONSE, null, "missing: " + String.join(", ", missing), null, null, null, null); + } + } else { + List texts = new ArrayList<>(); + for (Segment s : batch) { + texts.add(s.getText()); + } + TextTranslation answer = translateText(texts, targetLang, sourceLang, politeness, glossary, + planned.getKind().equals("html") ? TagHandling.HTML : TagHandling.NONE); + for (int i = 0; i < batch.size(); i++) { + result.put(planned.getKeys().get(i), answer.getTranslations().get(i)); + } + } + } + return Collections.unmodifiableMap(result); + } + + // ---- AI file translation + + /** + * Uploads a document for AI translation; returns the file id. + * + * @param content the document + * @param fileName its name (the extension sets the Content-Type) + * @param targetLang target + * @param sourceLang source, or {@code null} + * @param politeness formal or informal address + * @param glossary glossary, or {@code null} + * @param useOcr read a PDF with OCR; {@code null} to leave it out + * @return the file id + * @throws InterruptedException when interrupted + */ + public String submitFile(byte[] content, String fileName, String targetLang, String sourceLang, Politeness politeness, + Map glossary, Boolean useOcr) throws InterruptedException { + Multipart form = fileForm(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr); + String fileId = textOrNull(json("POST", "translate/ai/file", form.body, form.contentType, null), "file_id"); + if (fileId == null) { + throw new SupertextException(ErrorCode.INCOMPLETE_RESPONSE, null, "no file_id", null, null, null, null); + } + return fileId; + } + + /** + * The status of an AI file translation. + * + * @param fileId the file id + * @return the status + * @throws InterruptedException when interrupted + */ + public FileStatus getFileStatus(String fileId) throws InterruptedException { + Map o = json("GET", filePath(fileId) + "/status", null, null, null); + return new FileStatus(text(o, "status"), textOrNull(o, "error"), intOrNull(o.get("estimated_duration_left_in_seconds")), textOrNull(o, "detected_source_lang")); + } + + /** + * Polls until {@code done}; throws {@code translation_error}, {@code file_deleted} or {@code timeout}. + * + * @param fileId the file id + * @return the final status + * @throws InterruptedException when interrupted + */ + public FileStatus waitForFile(String fileId) throws InterruptedException { + long started = nanoTime.getAsLong(); + while (true) { + FileStatus status = getFileStatus(fileId); + if (status.getStatus().equals("done")) { + return status; + } + SupertextException error = SupertextException.forStatusValue("file", status.getStatus(), status.getError()); + if (error != null) { + throw error; + } + if (Duration.ofNanos(nanoTime.getAsLong() - started).plus(pollInterval).compareTo(timeout) > 0) { + throw new SupertextException(ErrorCode.TIMEOUT); + } + sleeper.sleep(pollInterval); + } + } + + /** + * The translated document, or {@code null} while it isn't ready (HTTP 202). + * + * @param fileId the file id + * @return the document, or {@code null} + * @throws InterruptedException when interrupted + */ + public DownloadedFile downloadFile(String fileId) throws InterruptedException { + return download(request("GET", filePath(fileId) + "/translation", null, null, requestTimeout, null)); + } + + /** + * Deletes the document and its translation. Never throws (except when interrupted). + * + * @param fileId the file id + * @throws InterruptedException when interrupted + */ + public void deleteFile(String fileId) throws InterruptedException { + try { + request("DELETE", filePath(fileId), null, null, requestTimeout, null); + } catch (SupertextException e) { + // Best effort: files expire after 24 hours anyway. + } + } + + /** + * Upload, wait, download, and always delete. + * + * @param content the document + * @param fileName its name + * @param targetLang target + * @param sourceLang source, or {@code null} + * @param politeness formal or informal address + * @param glossary glossary, or {@code null} + * @param useOcr OCR for PDFs, or {@code null} + * @return the translated document + * @throws InterruptedException when interrupted + */ + public DownloadedFile translateFile(byte[] content, String fileName, String targetLang, String sourceLang, Politeness politeness, + Map glossary, Boolean useOcr) throws InterruptedException { + String fileId = submitFile(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr); + try { + waitForFile(fileId); + DownloadedFile file = downloadFile(fileId); + if (file == null || file.getContent().length == 0) { + throw new SupertextException(ErrorCode.INCOMPLETE_RESPONSE, null, "empty document", null, null, null, null); + } + return file; + } finally { + deleteFile(fileId); + } + } + + /** + * One HTML document through the file endpoint (as {@code content.html}). + * + * @param html the document + * @param targetLang target + * @param sourceLang source, or {@code null} + * @param politeness formal or informal address + * @param glossary glossary, or {@code null} + * @return the translated document + * @throws InterruptedException when interrupted + */ + public String translateHtml(String html, String targetLang, String sourceLang, Politeness politeness, Map glossary) + throws InterruptedException { + return new String(translateFile(html.getBytes(StandardCharsets.UTF_8), "content.html", targetLang, sourceLang, politeness, glossary, null).getContent(), + StandardCharsets.UTF_8); + } + + /** + * What translating a document would cost. + * + * @param content the document + * @param fileName its name + * @param targetLang target + * @param sourceLang source, or {@code null} + * @param politeness formal or informal address + * @param glossary glossary, or {@code null} + * @param useOcr OCR for PDFs, or {@code null} + * @return the quote + * @throws InterruptedException when interrupted + */ + public Quote quoteFile(byte[] content, String fileName, String targetLang, String sourceLang, Politeness politeness, + Map glossary, Boolean useOcr) throws InterruptedException { + Multipart form = fileForm(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr); + return quote(json("POST", "translate/ai/file/quote", form.body, form.contentType, null)); + } + + // ---- language detection + + /** + * The language of a text (the first 500 characters are read). Empty when none was found. + * + * @param text the text + * @return what was found + * @throws InterruptedException when interrupted + */ + public List detectLanguage(String text) throws InterruptedException { + return detected(json("POST", "detect-languages/text", jsonBytes(Collections.singletonMap("text", text)), "application/json", null)); + } + + /** + * What a detection would cost. + * + * @param text the text + * @return the quote + * @throws InterruptedException when interrupted + */ + public Quote quoteDetection(String text) throws InterruptedException { + return quote(json("POST", "detect-languages/text/quote", jsonBytes(Collections.singletonMap("text", text)), "application/json", null)); + } + + /** + * The language of a document. + * + * @param content the document + * @param fileName its name + * @return what was found + * @throws InterruptedException when interrupted + */ + public List detectFileLanguage(byte[] content, String fileName) throws InterruptedException { + Multipart form = multipart(Collections.emptyList(), content, fileName); + return detected(json("POST", "detect-languages/file", form.body, form.contentType, null)); + } + + /** + * What detecting a document's language would cost. + * + * @param content the document + * @param fileName its name + * @return the quote + * @throws InterruptedException when interrupted + */ + public Quote quoteFileDetection(byte[] content, String fileName) throws InterruptedException { + Multipart form = multipart(Collections.emptyList(), content, fileName); + return quote(json("POST", "detect-languages/file/quote", form.body, form.contentType, null)); + } + + // ---- human review ("fused") + + /** + * Orders a reviewed translation of a text; the source language is required. Charged when accepted. + * + * @param text the text + * @param sourceLang source + * @param targetLang target + * @param politeness formal or informal address + * @param briefing instructions for the reviewer (orders Optimisation), or {@code null} + * @param idempotencyKey sent as {@code Idempotency-Key}, or {@code null} + * @return the order + * @throws InterruptedException when interrupted + */ + public FusedOrder orderFusedText(String text, String sourceLang, String targetLang, Politeness politeness, String briefing, String idempotencyKey) + throws InterruptedException { + Map extra = idempotencyKey == null || idempotencyKey.isEmpty() ? null : Collections.singletonMap("Idempotency-Key", idempotencyKey); + return fusedOrder(json("POST", "translate/fused/text", jsonBytes(fusedPayload(text, sourceLang, targetLang, politeness, briefing)), "application/json", extra)); + } + + /** + * The status of a human-review text order. + * + * @param translationId the order id + * @return the status + * @throws InterruptedException when interrupted + */ + public FusedStatus getFusedTextStatus(String translationId) throws InterruptedException { + return fusedStatus(json("GET", "translate/fused/text/" + encode(translationId) + "/status", null, null, null)); + } + + /** + * The reviewed text, or {@code null} while it isn't delivered yet (HTTP 202). + * + * @param translationId the order id + * @return the text, or {@code null} + * @throws InterruptedException when interrupted + */ + public String getFusedText(String translationId) throws InterruptedException { + Transport.Response response = request("GET", "translate/fused/text/" + encode(translationId) + "/translation", null, null, requestTimeout, null); + if (response.getStatus() == 202) { + return null; + } + Object value = parseObject(response.getBody()).get("translated_text"); + if (!(value instanceof String)) { + throw new SupertextException(ErrorCode.INCOMPLETE_RESPONSE, null, "no translated_text", null, null, null, null); + } + return (String) value; + } + + /** + * What a human-review text order would cost and how long it would take. + * + * @param text the text + * @param sourceLang source + * @param targetLang target + * @param politeness formal or informal address + * @param briefing briefing, or {@code null} + * @return the quote + * @throws InterruptedException when interrupted + */ + public FusedQuote quoteFusedText(String text, String sourceLang, String targetLang, Politeness politeness, String briefing) throws InterruptedException { + return fusedQuote(json("POST", "translate/fused/text/quote", jsonBytes(fusedPayload(text, sourceLang, targetLang, politeness, briefing)), "application/json", null)); + } + + /** + * Orders a reviewed translation of a document (PDFs come back as DOCX). + * + * @param content the document + * @param fileName its name + * @param sourceLang source + * @param targetLang target + * @param politeness formal or informal address + * @param briefing briefing, or {@code null} + * @param useOcr OCR for PDFs, or {@code null} + * @return the order + * @throws InterruptedException when interrupted + */ + public FusedOrder orderFusedFile(byte[] content, String fileName, String sourceLang, String targetLang, Politeness politeness, String briefing, Boolean useOcr) + throws InterruptedException { + Multipart form = fusedForm(content, fileName, sourceLang, targetLang, politeness, briefing, useOcr); + return fusedOrder(json("POST", "translate/fused/file", form.body, form.contentType, null)); + } + + /** + * The status of a human-review document order. + * + * @param translationId the order id + * @return the status + * @throws InterruptedException when interrupted + */ + public FusedStatus getFusedFileStatus(String translationId) throws InterruptedException { + return fusedStatus(json("GET", "translate/fused/file/" + encode(translationId) + "/status", null, null, null)); + } + + /** + * The reviewed document, or {@code null} until a reviewer delivers (HTTP 202). + * + * @param translationId the order id + * @return the document, or {@code null} + * @throws InterruptedException when interrupted + */ + public DownloadedFile downloadFusedFile(String translationId) throws InterruptedException { + return download(request("GET", "translate/fused/file/" + encode(translationId) + "/translation", null, null, requestTimeout, null)); + } + + /** + * What a human-review document order would cost and how long it would take. + * + * @param content the document + * @param fileName its name + * @param sourceLang source + * @param targetLang target + * @param politeness formal or informal address + * @param briefing briefing, or {@code null} + * @param useOcr OCR for PDFs, or {@code null} + * @return the quote + * @throws InterruptedException when interrupted + */ + public FusedQuote quoteFusedFile(byte[] content, String fileName, String sourceLang, String targetLang, Politeness politeness, String briefing, Boolean useOcr) + throws InterruptedException { + Multipart form = fusedForm(content, fileName, sourceLang, targetLang, politeness, briefing, useOcr); + return fusedQuote(json("POST", "translate/fused/file/quote", form.body, form.contentType, null)); + } + + // ---- webhooks + + /** + * This key's webhooks. + * + * @return the webhooks + * @throws InterruptedException when interrupted + */ + public List listWebhooks() throws InterruptedException { + Object items = json("GET", "webhooks", null, null, null).get("items"); + List result = new ArrayList<>(); + if (items instanceof List) { + for (Object item : (List) items) { + result.add(webhook(object(item), false)); + } + } + return result; + } + + /** + * Registers a webhook; the result's secret is shown only once: store it. + * + * @param url where events go ({@code https}) + * @param eventTypes the event types + * @param description a note, or {@code null} + * @return the webhook with its secret + * @throws InterruptedException when interrupted + */ + public Webhook createWebhook(String url, List eventTypes, String description) throws InterruptedException { + Map body = new LinkedHashMap<>(); + body.put("url", url); + body.put("event_types", eventTypes); + if (description != null) { + body.put("description", description); + } + return webhook(json("POST", "webhooks", jsonBytes(body), "application/json", null), true); + } + + /** + * One webhook. + * + * @param webhookId the id + * @return the webhook + * @throws InterruptedException when interrupted + */ + public Webhook getWebhook(String webhookId) throws InterruptedException { + return webhook(json("GET", "webhooks/" + encode(webhookId), null, null, null), false); + } + + /** + * Changes only the fields given ({@code null}: unchanged). + * + * @param webhookId the id + * @param url new URL, or {@code null} + * @param eventTypes new event types, or {@code null} + * @param description new note, or {@code null} + * @param enabled {@code true} switches a disabled webhook back on, or {@code null} + * @param clearDescription sends description null + * @return the webhook + * @throws InterruptedException when interrupted + */ + public Webhook updateWebhook(String webhookId, String url, List eventTypes, String description, Boolean enabled, boolean clearDescription) + throws InterruptedException { + Map body = new LinkedHashMap<>(); + if (url != null) { + body.put("url", url); + } + if (eventTypes != null) { + body.put("event_types", eventTypes); + } + if (description != null || clearDescription) { + body.put("description", description); + } + if (enabled != null) { + body.put("enabled", enabled); + } + return webhook(json("PATCH", "webhooks/" + encode(webhookId), jsonBytes(body), "application/json", null), false); + } + + /** + * Deletes a webhook. + * + * @param webhookId the id + * @throws InterruptedException when interrupted + */ + public void deleteWebhook(String webhookId) throws InterruptedException { + request("DELETE", "webhooks/" + encode(webhookId), null, null, requestTimeout, null); + } + + /** + * Sends a test event (at most one per 5 seconds). + * + * @param webhookId the id + * @return what happened + * @throws InterruptedException when interrupted + */ + public WebhookTestResult testWebhook(String webhookId) throws InterruptedException { + Map o = json("POST", "webhooks/" + encode(webhookId) + "/test", null, null, null); + Integer duration = intOrNull(o.get("duration_ms")); + return new WebhookTestResult(Boolean.TRUE.equals(o.get("delivered")), intOrNull(o.get("status_code")), textOrNull(o, "error"), duration == null ? 0 : duration); + } + + // ---- HTTP + + private Map json(String method, String path, byte[] body, String contentType, Map extra) throws InterruptedException { + return parseObject(request(method, path, body, contentType, requestTimeout, extra).getBody()); + } + + private Transport.Response request(String method, String path, byte[] body, String contentType, Duration requestTimeout, + Map extra) throws InterruptedException { + String authorization = authHeader(apiKey); + String key = authorization.substring("Bearer ".length()); + Map headers = new LinkedHashMap<>(); + if (extra != null) { + headers.putAll(extra); + } + headers.put("Authorization", authorization); + headers.put("Accept", "application/json, application/problem+json"); + headers.put("User-Agent", userAgent); + if (contentType != null) { + headers.put("Content-Type", contentType); + } + Transport.Request request = new Transport.Request(method, URI.create(baseUrl + path), headers, body, requestTimeout); + for (int attempt = 0; ; attempt++) { + Transport.Response response; + try { + response = transport.send(request); + } catch (IOException e) { + String message = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); + String detail = message.replace(key, "***"); + throw new SupertextException(ErrorCode.TRANSPORT_ERROR, null, detail, null, null, null, detail.equals(message) ? e : null); + } + int status = response.getStatus(); + if (status >= 200 && status < 300) { + return response; + } + if (status == 429 && attempt < maxRetries) { + sleeper.sleep(Duration.ofMillis(com.supertext.sdk.v1.SupertextClient.retryDelayMs(attempt, response.getHeader("Retry-After")))); + continue; + } + throw SupertextException.forResponse(status, response.getBody().replace(key, "***")); + } + } + + // ---- payloads + + private static final class Multipart { + final byte[] body; + final String contentType; + + Multipart(byte[] body, String contentType) { + this.body = body; + this.contentType = contentType; + } + } + + private static String required(String code) { + String value = trimAscii(code == null ? "" : code); + if (value.isEmpty()) { + throw new SupertextException(ErrorCode.UNSUPPORTED_LANGUAGE); + } + return value; + } + + private static String politeness(Politeness politeness) { + return politeness == Politeness.MORE ? "more" : politeness == Politeness.LESS ? "less" : null; + } + + private static Map textPayload(List texts, String targetLang, String sourceLang, Politeness politeness, + Map glossary, TagHandling tagHandling) { + Map body = new LinkedHashMap<>(); + body.put("text", new ArrayList<>(texts)); + body.put("target_lang", required(targetLang)); + String source = trimAscii(sourceLang == null ? "" : sourceLang); + if (!source.isEmpty()) { + body.put("source_lang", source); + } + if (politeness(politeness) != null) { + body.put("politeness", politeness(politeness)); + } + if (glossary != null && !glossary.isEmpty()) { + body.put("glossary", new LinkedHashMap<>(glossary)); + } + if (tagHandling == TagHandling.HTML) { + body.put("tag_handling", "html"); + } else if (tagHandling == TagHandling.XML) { + body.put("tag_handling", "xml"); + } + return body; + } + + private static Multipart fileForm(byte[] content, String fileName, String targetLang, String sourceLang, Politeness politeness, + Map glossary, Boolean useOcr) { + List fields = new ArrayList<>(); + fields.add(new String[] {"target_lang", required(targetLang)}); + String source = trimAscii(sourceLang == null ? "" : sourceLang); + if (!source.isEmpty()) { + fields.add(new String[] {"source_lang", source}); + } + if (politeness(politeness) != null) { + fields.add(new String[] {"politeness", politeness(politeness)}); + } + if (glossary != null && !glossary.isEmpty()) { + fields.add(new String[] {"glossary", Json.write(new LinkedHashMap<>(glossary))}); + } + if (useOcr != null) { + fields.add(new String[] {"use_ocr", useOcr ? "true" : "false"}); + } + return multipart(fields, content, fileName); + } + + private static Map fusedPayload(String text, String sourceLang, String targetLang, Politeness politeness, String briefing) { + Map body = new LinkedHashMap<>(); + body.put("text", text); + body.put("source_lang", required(sourceLang)); + body.put("target_lang", required(targetLang)); + if (politeness(politeness) != null) { + body.put("politeness", politeness(politeness)); + } + if (briefing != null && !briefing.isEmpty()) { + body.put("briefing", briefing); + } + return body; + } + + private static Multipart fusedForm(byte[] content, String fileName, String sourceLang, String targetLang, Politeness politeness, String briefing, Boolean useOcr) { + List fields = new ArrayList<>(); + fields.add(new String[] {"target_lang", required(targetLang)}); + fields.add(new String[] {"source_lang", required(sourceLang)}); + if (politeness(politeness) != null) { + fields.add(new String[] {"politeness", politeness(politeness)}); + } + if (briefing != null && !briefing.isEmpty()) { + fields.add(new String[] {"briefing", briefing}); + } + if (useOcr != null) { + fields.add(new String[] {"use_ocr", useOcr ? "true" : "false"}); + } + return multipart(fields, content, fileName); + } + + private static byte[] jsonBytes(Object value) { + return Json.write(value).getBytes(StandardCharsets.UTF_8); + } + + private static Multipart multipart(List fields, byte[] content, String fileName) { + byte[] random = new byte[12]; + RANDOM.nextBytes(random); + StringBuilder hex = new StringBuilder(); + for (byte x : random) { + hex.append(Character.forDigit((x >> 4) & 0xf, 16)).append(Character.forDigit(x & 0xf, 16)); + } + String boundary = "----supertext-" + hex; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + StringBuilder head = new StringBuilder(); + for (String[] field : fields) { + head.append("--").append(boundary).append("\r\nContent-Disposition: form-data; name=\"").append(field[0]).append("\"\r\n\r\n") + .append(field[1]).append("\r\n"); + } + String name = fileName == null ? "file" : fileName.replaceAll("[\"\\r\\n\\\\]", "_"); + head.append("--").append(boundary).append("\r\nContent-Disposition: form-data; name=\"file\"; filename=\"").append(name) + .append("\"\r\nContent-Type: ").append(contentTypeFor(fileName)).append("\r\n\r\n"); + byte[] headBytes = head.toString().getBytes(StandardCharsets.UTF_8); + out.write(headBytes, 0, headBytes.length); + byte[] data = content == null ? new byte[0] : content; + out.write(data, 0, data.length); + byte[] tail = ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8); + out.write(tail, 0, tail.length); + return new Multipart(out.toByteArray(), "multipart/form-data; boundary=" + boundary); + } + + // ---- answers + + private static Map parseObject(String body) { + try { + return object(Json.parse(body)); + } catch (IllegalArgumentException e) { + return Collections.emptyMap(); + } + } + + private static Map object(Object value) { + return value instanceof Map ? (Map) value : Collections.emptyMap(); + } + + private static String text(Map o, String name) { + Object v = o.get(name); + return v instanceof String ? (String) v : ""; + } + + private static String textOrNull(Map o, String name) { + Object v = o.get(name); + return v instanceof String && !((String) v).isEmpty() ? (String) v : null; + } + + private static Integer intOrNull(Object v) { + if (v instanceof Number) { + double d = ((Number) v).doubleValue(); + if (d == Math.rint(d) && Math.abs(d) <= Integer.MAX_VALUE) { + return (int) d; + } + } + return null; + } + + private static List strings(Object v) { + List out = new ArrayList<>(); + if (v instanceof List) { + for (Object item : (List) v) { + if (item instanceof String) { + out.add((String) item); + } + } + } + return out; + } + + private static Map stringMap(Object v) { + if (!(v instanceof Map)) { + return null; + } + Map out = new LinkedHashMap<>(); + for (Map.Entry e : ((Map) v).entrySet()) { + if (e.getValue() instanceof String) { + out.put(String.valueOf(e.getKey()), (String) e.getValue()); + } + } + return out; + } + + private static Map prices(Object v) { + Map out = new LinkedHashMap<>(); + for (Map.Entry e : object(v).entrySet()) { + if (e.getValue() instanceof Number) { + out.put(String.valueOf(e.getKey()), ((Number) e.getValue()).doubleValue()); + } + } + return out; + } + + private static Quote quote(Map o) { + Integer count = intOrNull(o.get("character_count")); + return new Quote(count == null ? 0 : count, prices(o.get("prices"))); + } + + private static List detected(Map o) { + List out = new ArrayList<>(); + Object list = o.get("detected_languages"); + if (list instanceof List) { + for (Object item : (List) list) { + Map d = object(item); + if (d.get("lang_code") instanceof String) { + Object c = d.get("confidence"); + out.add(new DetectedLanguage((String) d.get("lang_code"), c instanceof Number ? ((Number) c).doubleValue() : null, + Boolean.TRUE.equals(d.get("supports_translation")))); + } + } + } + return out; + } + + private static FusedOrder fusedOrder(Map o) { + String id = textOrNull(o, "translation_id"); + if (id == null) { + throw new SupertextException(ErrorCode.INCOMPLETE_RESPONSE, null, "no translation_id", null, null, null, null); + } + return new FusedOrder(id, Boolean.TRUE.equals(o.get("briefing_applied")), text(o, "service_label"), textOrNull(o, "request_id")); + } + + private static FusedStatus fusedStatus(Map o) { + Integer left = intOrNull(o.get("estimated_duration_left_in_seconds")); + return new FusedStatus(text(o, "status"), textOrNull(o, "detected_source_lang"), left == null ? 0 : left, textOrNull(o, "error")); + } + + private static FusedQuote fusedQuote(Map o) { + Integer duration = intOrNull(o.get("estimated_duration_in_seconds")); + Integer words = intOrNull(o.get("word_count")); + return new FusedQuote(prices(o.get("prices")), duration == null ? 0 : duration, words == null ? 0 : words, intOrNull(o.get("character_count")), + Boolean.TRUE.equals(o.get("briefing_applied")), text(o, "service_label")); + } + + private static Webhook webhook(Map o, boolean withSecret) { + Integer failures = intOrNull(o.get("consecutive_failures")); + return new Webhook(text(o, "id"), text(o, "url"), strings(o.get("event_types")), textOrNull(o, "description"), text(o, "status"), + textOrNull(o, "disabled_reason"), text(o, "created_at"), textOrNull(o, "last_delivery_at"), textOrNull(o, "last_failure_at"), + textOrNull(o, "last_failure_reason"), failures == null ? 0 : failures, withSecret ? text(o, "secret") : null); + } + + private static DownloadedFile download(Transport.Response response) { + if (response.getStatus() == 202) { + return null; + } + return new DownloadedFile(response.getBodyBytes(), fileNameFrom(response.getHeader("Content-Disposition"))); + } + + private static String filePath(String fileId) { + return "translate/ai/file/" + encode(fileId); + } + + private static String encode(String value) { + try { + return URLEncoder.encode(value, "UTF-8").replace("+", "%20"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } + + static String trimAscii(String text) { + int start = 0; + int end = text.length(); + while (start < end && SupertextException.isAsciiSpace(text.charAt(start))) { + start++; + } + while (end > start && SupertextException.isAsciiSpace(text.charAt(end - 1))) { + end--; + } + return text.substring(start, end); + } + + private static boolean isBlank(String text) { + return trimAscii(text).isEmpty(); + } + + /** Builds a {@link SupertextClient}. */ + public static final class Builder { + private final String apiKey; + private String baseUrl = LIVE_BASE_URL; + private Duration pollInterval = Duration.ofSeconds(2); + private Duration timeout = Duration.ofSeconds(180); + private Duration requestTimeout = Duration.ofSeconds(30); + private int maxRetries = 4; + private String userAgent; + private Transport transport; + private Sleeper sleeper; + private LongSupplier nanoTime; + private Clock wallClock; + + private Builder(String apiKey) { + this.apiKey = apiKey; + } + + /** + * Sets baseUrl. + * + * @param baseUrl the API's base URL (default the live API) + * @return this + */ + public Builder baseUrl(String baseUrl) { + this.baseUrl = baseUrl; + return this; + } + + /** + * Sets pollInterval. + * + * @param pollInterval wait between status polls (default 2 s) + * @return this + */ + public Builder pollInterval(Duration pollInterval) { + this.pollInterval = positive(pollInterval, "pollInterval"); + return this; + } + + /** + * Sets timeout. + * + * @param timeout give up waiting for an AI file translation after this long (default 180 s) + * @return this + */ + public Builder timeout(Duration timeout) { + this.timeout = positive(timeout, "timeout"); + return this; + } + + /** + * Sets requestTimeout. + * + * @param requestTimeout timeout of a single HTTP request (default 30 s) + * @return this + */ + public Builder requestTimeout(Duration requestTimeout) { + this.requestTimeout = positive(requestTimeout, "requestTimeout"); + return this; + } + + /** + * Sets maxRetries. + * + * @param maxRetries retries after HTTP 429 (default 4) + * @return this + */ + public Builder maxRetries(int maxRetries) { + if (maxRetries < 0) { + throw new IllegalArgumentException("maxRetries must not be negative"); + } + this.maxRetries = maxRetries; + return this; + } + + /** + * Sets userAgent. + * + * @param userAgent appended to the User-Agent + * @return this + */ + public Builder userAgent(String userAgent) { + this.userAgent = userAgent; + return this; + } + + /** + * Sets transport. + * + * @param transport the HTTP layer (default the JDK's HttpClient) + * @return this + */ + public Builder transport(Transport transport) { + this.transport = transport; + return this; + } + + /** + * Sets sleeper. + * + * @param sleeper how to wait (tests) + * @return this + */ + public Builder sleeper(Sleeper sleeper) { + this.sleeper = sleeper; + return this; + } + + /** + * Sets nanoTime. + * + * @param nanoTime monotonic clock (tests) + * @return this + */ + public Builder nanoTime(LongSupplier nanoTime) { + this.nanoTime = nanoTime; + return this; + } + + /** + * Sets wallClock. + * + * @param wallClock clock for the key check's time (tests) + * @return this + */ + public Builder wallClock(Clock wallClock) { + this.wallClock = wallClock; + return this; + } + + /** @return the client */ + public SupertextClient build() { + return new SupertextClient(this); + } + + private static Duration positive(Duration value, String name) { + if (value == null || value.isNegative() || value.isZero()) { + throw new IllegalArgumentException(name + " must be positive"); + } + return value; + } + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/SupertextException.java b/sdk/java/src/main/java/com/supertext/sdk/v2/SupertextException.java new file mode 100644 index 0000000..d6111b9 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/SupertextException.java @@ -0,0 +1,186 @@ +package com.supertext.sdk.v2; + +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Any failure of the v2 client (spec/v2/errors.json). {@link #getDetail()} is the API's explanation (safe to + * show), {@link #getApiErrorCode()} the problem's {@code code}, {@link #getErrorId()} its {@code error_id} + * (quote it to support), {@link #getReason()} its {@code reason}. Never contains the API key. + */ +public class SupertextException extends RuntimeException { + + private static final long serialVersionUID = 1L; + private static final Pattern TAGS = Pattern.compile("<[^>]*>"); + + private final ErrorCode code; + private final Integer status; + private final String detail; + private final String apiErrorCode; + private final String errorId; + private final String reason; + + /** + * An error with only a code. + * + * @param code the code + */ + public SupertextException(ErrorCode code) { + this(code, null, null, null, null, null, null); + } + + /** + * An error with everything that is known; {@code null} for what isn't. + * + * @param code the code + * @param status HTTP status + * @param detail the API's explanation + * @param apiErrorCode the problem's {@code code} + * @param errorId the problem's {@code error_id} + * @param reason the problem's {@code reason} + * @param cause the cause + */ + public SupertextException(ErrorCode code, Integer status, String detail, String apiErrorCode, String errorId, String reason, Throwable cause) { + super(message(code, status, empty(detail), empty(errorId)), cause); + this.code = code; + this.status = status; + this.detail = empty(detail); + this.apiErrorCode = empty(apiErrorCode); + this.errorId = empty(errorId); + this.reason = empty(reason); + } + + private static String message(ErrorCode code, Integer status, String detail, String errorId) { + String message = code.message(); + if (status != null) { + message += " HTTP " + status + "."; + } + if (detail != null) { + message += " Details: " + detail; + } + if (errorId != null) { + message += " (error id " + errorId + ")"; + } + return message; + } + + private static String empty(String value) { + return value == null || value.isEmpty() ? null : value; + } + + /** @return what went wrong */ + public ErrorCode getCode() { + return code; + } + + /** @return the HTTP status, or {@code null} */ + public Integer getStatus() { + return status; + } + + /** @return the API's explanation, at most 200 characters, or {@code null} */ + public String getDetail() { + return detail; + } + + /** @return the problem's {@code code}, or {@code null} */ + public String getApiErrorCode() { + return apiErrorCode; + } + + /** @return the problem's {@code error_id}, or {@code null} */ + public String getErrorId() { + return errorId; + } + + /** @return the problem's {@code reason}, e.g. {@code insufficient_credit}, or {@code null} */ + public String getReason() { + return reason; + } + + /** + * Maps a non-2xx answer (problem+json) to an error. + * + * @param status HTTP status + * @param body the body + * @return the error + */ + public static SupertextException forResponse(int status, String body) { + Map json = null; + try { + Object parsed = Json.parse(body); + if (parsed instanceof Map) { + json = (Map) parsed; + } + } catch (IllegalArgumentException e) { + // Not JSON. + } + String apiDetail = text(json, "detail"); + String detail = cut(apiDetail != null ? apiDetail : TAGS.matcher(body).replaceAll("")); + ErrorCode code; + if (status == 401 || status == 403) { + code = ErrorCode.AUTHENTICATION_FAILURE; + } else if (status == 402) { + code = ErrorCode.INSUFFICIENT_CREDIT; + } else if (status == 404) { + code = ErrorCode.NOT_FOUND; + } else if (status == 409) { + code = ErrorCode.CONFLICT; + } else if (status == 413) { + code = ErrorCode.PAYLOAD_TOO_LARGE; + } else if (status == 422) { + code = ErrorCode.INVALID_REQUEST; + } else if (status == 429) { + code = ErrorCode.TOO_MANY_REQUESTS; + } else if (status >= 500 && status <= 599) { + code = ErrorCode.SERVICE_UNAVAILABLE; + } else { + code = ErrorCode.UNEXPECTED_STATUS; + } + return new SupertextException(code, status, detail, text(json, "code"), text(json, "error_id"), text(json, "reason"), null); + } + + /** + * The error for a polled status, or {@code null}: AI file ({@code file}) error/deleted, human review ({@code fused}) failed. + * + * @param kind {@code file} or {@code fused} + * @param status the polled status + * @param error the status body's {@code error} + * @return the error, or {@code null} + */ + public static SupertextException forStatusValue(String kind, String status, String error) { + String detail = cut(error == null ? "" : error); + if (("file".equals(kind) && "error".equals(status)) || ("fused".equals(kind) && "failed".equals(status))) { + return new SupertextException(ErrorCode.TRANSLATION_ERROR, null, detail, null, null, null, null); + } + if ("file".equals(kind) && "deleted".equals(status)) { + return new SupertextException(ErrorCode.FILE_DELETED); + } + return null; + } + + private static String text(Map json, String name) { + Object value = json == null ? null : json.get(name); + return value instanceof String && !((String) value).isEmpty() ? (String) value : null; + } + + private static String cut(String text) { + int start = 0; + int end = text.length(); + while (start < end && isAsciiSpace(text.charAt(start))) { + start++; + } + while (end > start && isAsciiSpace(text.charAt(end - 1))) { + end--; + } + String trimmed = text.substring(start, end); + if (trimmed.isEmpty()) { + return null; + } + return trimmed.codePointCount(0, trimmed.length()) <= 200 ? trimmed : trimmed.substring(0, trimmed.offsetByCodePoints(0, 200)); + } + + static boolean isAsciiSpace(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/TextTranslation.java b/sdk/java/src/main/java/com/supertext/sdk/v2/TextTranslation.java new file mode 100644 index 0000000..99282f8 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/TextTranslation.java @@ -0,0 +1,76 @@ +package com.supertext.sdk.v2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** The answer of {@code POST translate/ai/text}: one translation per input text, same order. */ +public final class TextTranslation { + private final List translations; + private final String detectedSourceLang; + private final Map enforcedTerms; + private final String requestId; + + /** + * Creates the value. + * + * @param translations one translation per input text, same order + * @param detectedSourceLang the source language used, detected when none was sent; {@code null} if unknown + * @param enforcedTerms glossary terms applied; {@code null} when no glossary was sent + * @param requestId the request id; quote it to support + */ + public TextTranslation(List translations, String detectedSourceLang, Map enforcedTerms, String requestId) { + this.translations = translations == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(translations)); + this.detectedSourceLang = detectedSourceLang; + this.enforcedTerms = enforcedTerms == null ? null : Collections.unmodifiableMap(new LinkedHashMap<>(enforcedTerms)); + this.requestId = requestId; + } + + /** @return one translation per input text, same order */ + public List getTranslations() { + return translations; + } + + /** @return the source language used, detected when none was sent; {@code null} if unknown */ + public String getDetectedSourceLang() { + return detectedSourceLang; + } + + /** @return glossary terms applied; {@code null} when no glossary was sent */ + public Map getEnforcedTerms() { + return enforcedTerms; + } + + /** @return the request id; quote it to support */ + public String getRequestId() { + return requestId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof TextTranslation)) { + return false; + } + TextTranslation other = (TextTranslation) o; + return Objects.equals(translations, other.translations) + && Objects.equals(detectedSourceLang, other.detectedSourceLang) + && Objects.equals(enforcedTerms, other.enforcedTerms) + && Objects.equals(requestId, other.requestId); + } + + @Override + public int hashCode() { + return Objects.hash(translations, detectedSourceLang, enforcedTerms, requestId); + } + + @Override + public String toString() { + return "TextTranslation{" + "translations=" + translations + ", " + "detectedSourceLang=" + detectedSourceLang + ", " + "enforcedTerms=" + enforcedTerms + ", " + "requestId=" + requestId + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/Webhook.java b/sdk/java/src/main/java/com/supertext/sdk/v2/Webhook.java new file mode 100644 index 0000000..2544c52 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/Webhook.java @@ -0,0 +1,146 @@ +package com.supertext.sdk.v2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** A registered webhook. */ +public final class Webhook { + private final String id; + private final String url; + private final List eventTypes; + private final String description; + private final String status; + private final String disabledReason; + private final String createdAt; + private final String lastDeliveryAt; + private final String lastFailureAt; + private final String lastFailureReason; + private final int consecutiveFailures; + private final String secret; + + /** + * Creates the value. + * + * @param id id + * @param url where events go + * @param eventTypes subscribed event types + * @param description your note + * @param status {@code active} or {@code disabled} + * @param disabledReason {@code gone} or {@code failing} + * @param createdAt created + * @param lastDeliveryAt last delivery + * @param lastFailureAt last failure + * @param lastFailureReason e.g. {@code http_500} + * @param consecutiveFailures failures in a row + * @param secret the signing secret ({@code whsec_…}), only on the result of create, shown once + */ + public Webhook(String id, String url, List eventTypes, String description, String status, String disabledReason, String createdAt, String lastDeliveryAt, String lastFailureAt, String lastFailureReason, int consecutiveFailures, String secret) { + this.id = id; + this.url = url; + this.eventTypes = eventTypes == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(eventTypes)); + this.description = description; + this.status = status; + this.disabledReason = disabledReason; + this.createdAt = createdAt; + this.lastDeliveryAt = lastDeliveryAt; + this.lastFailureAt = lastFailureAt; + this.lastFailureReason = lastFailureReason; + this.consecutiveFailures = consecutiveFailures; + this.secret = secret; + } + + /** @return id */ + public String getId() { + return id; + } + + /** @return where events go */ + public String getUrl() { + return url; + } + + /** @return subscribed event types */ + public List getEventTypes() { + return eventTypes; + } + + /** @return your note */ + public String getDescription() { + return description; + } + + /** @return {@code active} or {@code disabled} */ + public String getStatus() { + return status; + } + + /** @return {@code gone} or {@code failing} */ + public String getDisabledReason() { + return disabledReason; + } + + /** @return created */ + public String getCreatedAt() { + return createdAt; + } + + /** @return last delivery */ + public String getLastDeliveryAt() { + return lastDeliveryAt; + } + + /** @return last failure */ + public String getLastFailureAt() { + return lastFailureAt; + } + + /** @return e.g. {@code http_500} */ + public String getLastFailureReason() { + return lastFailureReason; + } + + /** @return failures in a row */ + public int getConsecutiveFailures() { + return consecutiveFailures; + } + + /** @return the signing secret ({@code whsec_…}), only on the result of create, shown once */ + public String getSecret() { + return secret; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Webhook)) { + return false; + } + Webhook other = (Webhook) o; + return Objects.equals(id, other.id) + && Objects.equals(url, other.url) + && Objects.equals(eventTypes, other.eventTypes) + && Objects.equals(description, other.description) + && Objects.equals(status, other.status) + && Objects.equals(disabledReason, other.disabledReason) + && Objects.equals(createdAt, other.createdAt) + && Objects.equals(lastDeliveryAt, other.lastDeliveryAt) + && Objects.equals(lastFailureAt, other.lastFailureAt) + && Objects.equals(lastFailureReason, other.lastFailureReason) + && consecutiveFailures == other.consecutiveFailures + && Objects.equals(secret, other.secret); + } + + @Override + public int hashCode() { + return Objects.hash(id, url, eventTypes, description, status, disabledReason, createdAt, lastDeliveryAt, lastFailureAt, lastFailureReason, consecutiveFailures, secret); + } + + @Override + public String toString() { + return "Webhook{" + "id=" + id + ", " + "url=" + url + ", " + "eventTypes=" + eventTypes + ", " + "description=" + description + ", " + "status=" + status + ", " + "disabledReason=" + disabledReason + ", " + "createdAt=" + createdAt + ", " + "lastDeliveryAt=" + lastDeliveryAt + ", " + "lastFailureAt=" + lastFailureAt + ", " + "lastFailureReason=" + lastFailureReason + ", " + "consecutiveFailures=" + consecutiveFailures + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/WebhookEvent.java b/sdk/java/src/main/java/com/supertext/sdk/v2/WebhookEvent.java new file mode 100644 index 0000000..1dcd7d9 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/WebhookEvent.java @@ -0,0 +1,74 @@ +package com.supertext.sdk.v2; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** A verified webhook event. {@link #getId()} is the {@code webhook-id} header: de-duplicate on it. */ +public final class WebhookEvent { + private final String id; + private final String type; + private final String timestamp; + private final Map data; + + /** + * Creates the value. + * + * @param id the webhook-id header + * @param type the event type + * @param timestamp when it happened (UTC) + * @param data the event's data (ids, statuses, amounts) + */ + public WebhookEvent(String id, String type, String timestamp, Map data) { + this.id = id; + this.type = type; + this.timestamp = timestamp; + this.data = data == null ? Collections.emptyMap() : Collections.unmodifiableMap(new LinkedHashMap<>(data)); + } + + /** @return the webhook-id header */ + public String getId() { + return id; + } + + /** @return the event type */ + public String getType() { + return type; + } + + /** @return when it happened (UTC) */ + public String getTimestamp() { + return timestamp; + } + + /** @return the event's data (ids, statuses, amounts) */ + public Map getData() { + return data; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof WebhookEvent)) { + return false; + } + WebhookEvent other = (WebhookEvent) o; + return Objects.equals(id, other.id) + && Objects.equals(type, other.type) + && Objects.equals(timestamp, other.timestamp) + && Objects.equals(data, other.data); + } + + @Override + public int hashCode() { + return Objects.hash(id, type, timestamp, data); + } + + @Override + public String toString() { + return "WebhookEvent{" + "id=" + id + ", " + "type=" + type + ", " + "timestamp=" + timestamp + ", " + "data=" + data + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/WebhookTestResult.java b/sdk/java/src/main/java/com/supertext/sdk/v2/WebhookTestResult.java new file mode 100644 index 0000000..6597ce1 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/WebhookTestResult.java @@ -0,0 +1,71 @@ +package com.supertext.sdk.v2; + +import java.util.Objects; + +/** The answer of a test event. */ +public final class WebhookTestResult { + private final boolean delivered; + private final Integer statusCode; + private final String error; + private final int durationMs; + + /** + * Creates the value. + * + * @param delivered true when the endpoint answered 2xx + * @param statusCode the endpoint's status + * @param error why no answer arrived + * @param durationMs how long it took + */ + public WebhookTestResult(boolean delivered, Integer statusCode, String error, int durationMs) { + this.delivered = delivered; + this.statusCode = statusCode; + this.error = error; + this.durationMs = durationMs; + } + + /** @return true when the endpoint answered 2xx */ + public boolean isDelivered() { + return delivered; + } + + /** @return the endpoint's status */ + public Integer getStatusCode() { + return statusCode; + } + + /** @return why no answer arrived */ + public String getError() { + return error; + } + + /** @return how long it took */ + public int getDurationMs() { + return durationMs; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof WebhookTestResult)) { + return false; + } + WebhookTestResult other = (WebhookTestResult) o; + return delivered == other.delivered + && Objects.equals(statusCode, other.statusCode) + && Objects.equals(error, other.error) + && durationMs == other.durationMs; + } + + @Override + public int hashCode() { + return Objects.hash(delivered, statusCode, error, durationMs); + } + + @Override + public String toString() { + return "WebhookTestResult{" + "delivered=" + delivered + ", " + "statusCode=" + statusCode + ", " + "error=" + error + ", " + "durationMs=" + durationMs + "}"; + } +} diff --git a/sdk/java/src/main/java/com/supertext/sdk/v2/Webhooks.java b/sdk/java/src/main/java/com/supertext/sdk/v2/Webhooks.java new file mode 100644 index 0000000..fb10aa4 --- /dev/null +++ b/sdk/java/src/main/java/com/supertext/sdk/v2/Webhooks.java @@ -0,0 +1,120 @@ +package com.supertext.sdk.v2; + +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** Verifies webhook requests the Standard Webhooks way (spec/v2/webhooks.json). */ +public final class Webhooks { + + /** How far a webhook's timestamp may be from now, either way. */ + public static final long TOLERANCE_SECONDS = 300; + + private Webhooks() { + } + + /** + * The verified event, with the system clock. + * + * @param secret the {@code whsec_…} secret from the create answer + * @param headers the request headers (names in any case) + * @param rawBody the body as received, before any JSON parsing + * @return the event + * @throws SupertextException {@link ErrorCode#INVALID_WEBHOOK} + */ + public static WebhookEvent verify(String secret, Map headers, String rawBody) { + return verify(secret, headers, rawBody, Instant.now()); + } + + /** + * The verified event. + * + * @param secret the {@code whsec_…} secret from the create answer + * @param headers the request headers (names in any case) + * @param rawBody the body as received, before any JSON parsing + * @param now the current time + * @return the event + * @throws SupertextException {@link ErrorCode#INVALID_WEBHOOK} + */ + public static WebhookEvent verify(String secret, Map headers, String rawBody, Instant now) { + String encoded = secret == null ? "" : secret.startsWith("whsec_") ? secret.substring(6) : secret; + byte[] key; + try { + key = encoded.length() % 4 == 0 ? Base64.getDecoder().decode(encoded) : new byte[0]; + } catch (IllegalArgumentException e) { + throw invalid(); + } + if (key.length == 0 || headers == null || rawBody == null) { + throw invalid(); + } + String id = header(headers, "webhook-id"); + String timestamp = header(headers, "webhook-timestamp"); + String signatures = header(headers, "webhook-signature"); + if (id == null || id.isEmpty() || timestamp == null || signatures == null || !timestamp.matches("[0-9]{1,18}")) { + throw invalid(); + } + if (Math.abs(now.getEpochSecond() - Long.parseLong(timestamp)) > TOLERANCE_SECONDS) { + throw invalid(); + } + byte[] expected; + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key, "HmacSHA256")); + expected = Base64.getEncoder().encode(mac.doFinal((id + "." + timestamp + "." + rawBody).getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException | InvalidKeyException e) { + throw new IllegalStateException("HmacSHA256 is not available", e); + } + boolean matched = false; + for (String entry : signatures.split(" ")) { + int comma = entry.indexOf(','); + if (comma > 0 && entry.substring(0, comma).equals("v1") + && MessageDigest.isEqual(entry.substring(comma + 1).getBytes(StandardCharsets.US_ASCII), expected)) { + matched = true; + } + } + if (!matched) { + throw invalid(); + } + Object parsed; + try { + parsed = Json.parse(rawBody); + } catch (IllegalArgumentException e) { + throw invalid(); + } + if (!(parsed instanceof Map)) { + throw invalid(); + } + Map event = (Map) parsed; + if (!(event.get("type") instanceof String) || !(event.get("timestamp") instanceof String)) { + throw invalid(); + } + Map data = new LinkedHashMap<>(); + if (event.get("data") instanceof Map) { + for (Map.Entry e : ((Map) event.get("data")).entrySet()) { + data.put(String.valueOf(e.getKey()), e.getValue()); + } + } + return new WebhookEvent(id, (String) event.get("type"), (String) event.get("timestamp"), Collections.unmodifiableMap(data)); + } + + private static String header(Map headers, String name) { + for (Map.Entry entry : headers.entrySet()) { + if (entry.getKey() != null && entry.getKey().equalsIgnoreCase(name)) { + return entry.getValue(); + } + } + return null; + } + + private static SupertextException invalid() { + return new SupertextException(ErrorCode.INVALID_WEBHOOK); + } +} diff --git a/sdk/java/src/test/java/com/supertext/sdk/v2/V2Test.java b/sdk/java/src/test/java/com/supertext/sdk/v2/V2Test.java new file mode 100644 index 0000000..d12bf67 --- /dev/null +++ b/sdk/java/src/test/java/com/supertext/sdk/v2/V2Test.java @@ -0,0 +1,374 @@ +package com.supertext.sdk.v2; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.supertext.sdk.Transport; +import com.supertext.sdk.v1.ApiKeyCheck; +import com.supertext.sdk.v1.Politeness; +import com.supertext.sdk.v1.Segment; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +/** API v2: the shared vectors in spec/v2/ and the client against a scripted transport. */ +class V2Test { + + private static final String BASE = "https://api-platform.supertext.com/v1/"; + + @SuppressWarnings("unchecked") + private static Map spec(String name) { + try { + String dir = System.getProperty("supertext.spec.dir", "../../spec"); + return (Map) Json.parse(new String(Files.readAllBytes(Paths.get(dir, "v2", name)), StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @SuppressWarnings("unchecked") + private static List> cases(Map spec, String key) { + return (List>) spec.get(key); + } + + private static String codeOf(Runnable run) { + return assertThrows(SupertextException.class, run::run).getCode().value(); + } + + private static Integer integer(Object v) { + return v == null ? null : ((Number) v).intValue(); + } + + @TestFactory + Stream authHeader() { + return cases(spec("auth-header.json"), "cases").stream().map(c -> DynamicTest.dynamicTest("key \"" + c.get("apiKey") + "\"", () -> { + String key = (String) c.get("apiKey"); + if (c.containsKey("error")) { + assertEquals(c.get("error"), codeOf(() -> SupertextClient.authHeader(key))); + } else { + assertEquals(c.get("header"), SupertextClient.authHeader(key)); + } + })); + } + + @TestFactory + Stream errors() { + return cases(spec("errors.json"), "http").stream().map(c -> DynamicTest.dynamicTest(c.get("status") + " " + c.get("code"), () -> { + SupertextException e = SupertextException.forResponse(integer(c.get("status")), (String) c.get("body")); + assertEquals(c.get("code"), e.getCode().value()); + assertEquals(integer(c.get("status")), e.getStatus()); + assertEquals(c.get("apiErrorCode"), e.getApiErrorCode()); + assertEquals(c.get("errorId"), e.getErrorId()); + assertEquals(c.get("reason"), e.getReason()); + assertEquals(c.get("detail"), e.getDetail()); + })); + } + + @TestFactory + Stream statusValues() { + return cases(spec("errors.json"), "fileStatus").stream().map(c -> DynamicTest.dynamicTest(c.get("kind") + " " + c.get("status"), () -> { + SupertextException e = SupertextException.forStatusValue((String) c.get("kind"), (String) c.get("status"), (String) c.get("error")); + assertEquals(c.get("code"), e == null ? null : e.getCode().value()); + assertEquals(c.get("detail"), e == null ? null : e.getDetail()); + })); + } + + @TestFactory + Stream batching() { + Map s = spec("batching.json"); + assertEquals(SupertextClient.DEFAULT_MAX_TEXT_CHARACTERS, integer(s.get("defaultMaxCharacters"))); + return cases(s, "cases").stream().map(c -> DynamicTest.dynamicTest((String) c.get("name"), () -> { + Map segments = new LinkedHashMap<>(); + for (Map seg : cases(c, "segments")) { + segments.put((String) seg.get("key"), new Segment((String) seg.get("text"), Boolean.TRUE.equals(seg.get("html")))); + } + List> plan = new ArrayList<>(); + for (PlannedRequest r : SupertextClient.planRequests(segments, integer(c.get("maxCharacters")))) { + Map m = new LinkedHashMap<>(); + m.put("kind", r.getKind()); + m.put("keys", r.getKeys()); + plan.add(m); + } + assertEquals(c.get("batches"), plan); + })); + } + + @TestFactory + Stream webhooks() { + return cases(spec("webhooks.json"), "cases").stream().map(c -> DynamicTest.dynamicTest((String) c.get("name"), () -> { + @SuppressWarnings("unchecked") + Map headers = (Map) c.get("headers"); + Instant now = Instant.ofEpochSecond(((Number) c.get("now")).longValue()); + if (c.containsKey("error")) { + assertEquals(c.get("error"), codeOf(() -> Webhooks.verify((String) c.get("secret"), headers, (String) c.get("body"), now))); + } else { + WebhookEvent e = Webhooks.verify((String) c.get("secret"), headers, (String) c.get("body"), now); + Map m = new LinkedHashMap<>(); + m.put("id", e.getId()); + m.put("type", e.getType()); + m.put("timestamp", e.getTimestamp()); + m.put("data", e.getData()); + assertEquals(c.get("event"), m); + } + })); + } + + @TestFactory + Stream keyCheck() { + Map s = spec("api-key-check.json"); + for (Map c : cases(s, "fingerprint")) { + assertEquals(c.get("fingerprint"), SupertextClient.fingerprint((String) c.get("apiKey"))); + } + return cases(s, "apiKeyCheck").stream().map(c -> DynamicTest.dynamicTest(String.valueOf(c.get("status")), () -> { + @SuppressWarnings("unchecked") + Map answer = (Map) c.get("answer"); + Fake fake = new Fake(); + if (answer.containsKey("transportError")) { + fake.fail(new IOException("down")); + } else { + fake.answer(integer(answer.get("status")), (String) answer.get("body")); + } + ApiKeyCheck check = client(fake, "st_live_abc123").checkApiKey(); + assertEquals(c.get("status"), check.getStatus().value()); + assertEquals(integer(c.get("httpStatus")), check.getHttpStatus()); + assertEquals(c.get("errorCode"), check.getErrorCode()); + assertEquals(SupertextClient.fingerprint("st_live_abc123"), check.getFingerprint()); + assertEquals(Collections.singletonList("GET account"), fake.calls()); + })); + } + + // ---- client + + private static final class Fake implements Transport { + final List requests = new ArrayList<>(); + private final Deque answers = new ArrayDeque<>(); + + Fake answer(int status, String body) { + answers.add(new Response(status, Collections.emptyMap(), body)); + return this; + } + + Fake answer(int status, String body, Map headers) { + answers.add(new Response(status, headers, body)); + return this; + } + + Fake answer(Function handler) { + answers.add(handler); + return this; + } + + Fake fail(IOException error) { + answers.add(error); + return this; + } + + @Override + @SuppressWarnings("unchecked") + public Response send(Request request) throws IOException { + requests.add(request); + Object next = answers.poll(); + if (next == null) { + throw new AssertionError("unexpected request " + request.getMethod() + " " + request.getUri()); + } + if (next instanceof IOException) { + throw (IOException) next; + } + if (next instanceof Function) { + return ((Function) next).apply(request); + } + return (Response) next; + } + + List calls() { + List out = new ArrayList<>(); + for (Request r : requests) { + out.add(r.getMethod() + " " + r.getUri().toString().substring(BASE.length())); + } + return out; + } + + String body(int i) { + return new String(requests.get(i).getBody(), StandardCharsets.UTF_8); + } + } + + private static SupertextClient client(Fake fake, String key) { + return SupertextClient.builder(key).transport(fake).sleeper(d -> { }) + .wallClock(Clock.fixed(Instant.parse("2026-11-01T00:00:00Z"), ZoneOffset.UTC)).build(); + } + + @Test + void translateText() throws Exception { + Fake fake = new Fake().answer(200, "{\"request_id\":\"r1\",\"detected_source_lang\":\"en\",\"translated_text\":[\"Hallo\"],\"enforced_terms\":{\"shop\":\"Laden\"}}"); + TextTranslation r = client(fake, " Bearer st_live_k ").translateText(Collections.singletonList("Hello"), "de-CH", "en", Politeness.MORE, + Collections.singletonMap("shop", "Laden"), SupertextClient.TagHandling.HTML); + assertEquals(new TextTranslation(Collections.singletonList("Hallo"), "en", Collections.singletonMap("shop", "Laden"), "r1"), r); + assertEquals("Bearer st_live_k", fake.requests.get(0).getHeaders().get("Authorization")); + assertEquals("application/json", fake.requests.get(0).getHeaders().get("Content-Type")); + assertEquals("{\"text\":[\"Hello\"],\"target_lang\":\"de-CH\",\"source_lang\":\"en\",\"politeness\":\"more\",\"glossary\":{\"shop\":\"Laden\"},\"tag_handling\":\"html\"}", fake.body(0)); + Fake wrong = new Fake().answer(200, "{\"translated_text\":[\"x\"]}"); + assertEquals("incomplete_response", codeOf(() -> { + try { + client(wrong, "k").translateText(Arrays.asList("a", "b"), "de-CH", null, Politeness.DEFAULT, null, SupertextClient.TagHandling.NONE); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + })); + } + + @Test + void retriesThenProblemAndNeverLeaksTheKey() throws Exception { + List waits = new ArrayList<>(); + Fake fake = new Fake().answer(429, "{\"code\":\"rate_limited\"}", Collections.singletonMap("Retry-After", "2")) + .answer(402, "{\"code\":\"payment_required\",\"detail\":\"Top up.\",\"error_id\":\"e1\",\"reason\":\"insufficient_credit\"}"); + SupertextClient c = SupertextClient.builder("k").transport(fake).sleeper(waits::add).build(); + SupertextException e = assertThrows(SupertextException.class, + () -> c.translateText(Collections.singletonList("a"), "de-CH", null, Politeness.DEFAULT, null, SupertextClient.TagHandling.NONE)); + assertEquals(Arrays.asList("insufficient_credit", "insufficient_credit", "e1", "Top up."), Arrays.asList(e.getCode().value(), e.getReason(), e.getErrorId(), e.getDetail())); + assertEquals(Collections.singletonList(Duration.ofSeconds(2)), waits); + + Fake leak = new Fake().answer(401, "bad key st_live_secret123"); + SupertextException e2 = assertThrows(SupertextException.class, () -> client(leak, "st_live_secret123").getAccount()); + assertFalse(e2.getMessage().contains("st_live_secret123")); + assertEquals("bad key ***", e2.getDetail()); + assertFalse(client(leak, "st_live_secret123").toString().contains("st_live_secret123")); + } + + @Test + void translateTextsUsesTextHtmlAndFile() throws Exception { + Fake fake = new Fake() + .answer(r -> new Transport.Response(200, Collections.emptyMap(), "{\"translated_text\":[\"T:one\"]}")) + .answer(r -> new Transport.Response(200, Collections.emptyMap(), "{\"translated_text\":[\"H:two\"]}")) + .answer(202, "{\"file_id\":\"f1\"}") + .answer(200, "{\"status\":\"done\"}") + .answer(200, "
LONG
\n", Collections.singletonMap("Content-Disposition", "attachment; filename=\"c.html\"")) + .answer(200, "{\"status\":\"deleted\"}"); + Map segments = new LinkedHashMap<>(); + segments.put("a", Segment.text("one")); + segments.put("b", Segment.html("two")); + segments.put("c", Segment.text(" ")); + segments.put("d", Segment.text("long text here")); + Map out = client(fake, "k").translateTexts(segments, "de-CH", null, Politeness.DEFAULT, null, 10); + assertEquals(Arrays.asList("a", "b", "c", "d"), new ArrayList<>(out.keySet())); + assertEquals(Arrays.asList("T:one", "H:two", " ", "LONG"), new ArrayList<>(out.values())); + assertEquals(Arrays.asList("POST translate/ai/text", "POST translate/ai/text", "POST translate/ai/file", "GET translate/ai/file/f1/status", + "GET translate/ai/file/f1/translation", "DELETE translate/ai/file/f1"), fake.calls()); + assertFalse(fake.body(0).contains("tag_handling")); + assertTrue(fake.body(1).contains("\"tag_handling\":\"html\"")); + assertTrue(fake.body(2).contains("Content-Type: text/html\r\n")); + } + + @Test + void failedFileDeletesAndBinaryDownloads() throws Exception { + Fake fake = new Fake().answer(202, "{\"file_id\":\"f1\"}").answer(200, "{\"status\":\"translating\"}") + .answer(200, "{\"status\":\"error\",\"error\":\"Corrupt.\"}").answer(200, "{}"); + SupertextException e = assertThrows(SupertextException.class, () -> client(fake, "k").translateFile(new byte[] {1, 2}, "a.docx", "fr-CH", null, + Politeness.DEFAULT, Collections.singletonMap("a", "b"), false)); + assertEquals(Arrays.asList("translation_error", "Corrupt."), Arrays.asList(e.getCode().value(), e.getDetail())); + assertEquals("DELETE", fake.requests.get(3).getMethod()); + assertTrue(fake.body(0).contains("wordprocessingml.document")); + assertTrue(fake.body(0).contains("name=\"glossary\"\r\n\r\n{\"a\":\"b\"}")); + assertTrue(fake.body(0).contains("name=\"use_ocr\"\r\n\r\nfalse")); + + byte[] docx = {80, 75, 3, 4, (byte) 0xff, (byte) 0xfe, 0}; + Fake binary = new Fake().answer(r -> new Transport.Response(200, Collections.singletonMap("Content-Disposition", "attachment; filename=\"a.fr-CH.docx\""), docx)); + DownloadedFile file = client(binary, "k").downloadFile("f1"); + assertArrayEquals(docx, file.getContent()); + assertEquals("a.fr-CH.docx", file.getFileName()); + } + + @Test + void notReadyFusedFeaturesDetectionQuotes() throws Exception { + Fake fake = new Fake() + .answer(202, "{\"status\":\"in_progress\"}") + .answer(202, "{\"status\":\"in_progress\"}") + .answer(200, "{\"translated_text\":\"Geprüft\"}") + .answer(202, "{\"translation_id\":\"u-1\",\"briefing_applied\":true,\"service_label\":\"Optimisation\",\"request_id\":\"r\"}") + .answer(200, "{\"supported_features\":[{\"source_lang\":\"en\",\"target_lang\":\"de-CH\",\"features\":[\"supports_politeness\"]},{\"bad\":1}]}") + .answer(200, "{\"detected_languages\":[{\"lang_code\":\"en\",\"confidence\":0.9,\"supports_translation\":true}]}") + .answer(200, "{\"character_count\":5,\"prices\":{\"chf\":0.0001,\"bad\":\"x\"}}"); + SupertextClient c = client(fake, "k"); + assertNull(c.downloadFile("x")); + assertNull(c.getFusedText("t")); + assertEquals("Geprüft", c.getFusedText("t")); + assertEquals(new FusedOrder("u-1", true, "Optimisation", "r"), c.orderFusedText("Hello", "en", "de-CH", Politeness.DEFAULT, "Friendly", "idem-1")); + assertEquals("idem-1", fake.requests.get(3).getHeaders().get("Idempotency-Key")); + assertEquals("{\"text\":\"Hello\",\"source_lang\":\"en\",\"target_lang\":\"de-CH\",\"briefing\":\"Friendly\"}", fake.body(3)); + assertEquals(Collections.singletonList(new FeatureSupport("en", "de-CH", Collections.singletonList("supports_politeness"))), c.getFeatures("en", "de-CH")); + assertEquals(BASE + "features?source_lang=en&target_lang=de-CH", fake.requests.get(4).getUri().toString()); + assertEquals(Collections.singletonList(new DetectedLanguage("en", 0.9, true)), c.detectLanguage("Hello")); + assertEquals(new Quote(5, Collections.singletonMap("chf", 0.0001)), c.quoteText(Collections.singletonList("Hello"), "de-CH", null, Politeness.DEFAULT, null, SupertextClient.TagHandling.NONE)); + } + + @Test + void webhookCrud() throws Exception { + String hook = "{\"id\":\"h1\",\"url\":\"https://cms.example/hook\",\"event_types\":[\"translation.ai_file.completed\"],\"description\":null,\"status\":\"active\"," + + "\"disabled_reason\":null,\"created_at\":\"2026\",\"last_delivery_at\":null,\"last_failure_at\":null,\"last_failure_reason\":null,\"consecutive_failures\":0"; + Fake fake = new Fake().answer(201, hook + ",\"secret\":\"whsec_abc\"}").answer(200, "{\"items\":[" + hook + "}]}").answer(200, hook + "}") + .answer(204, "").answer(200, "{\"delivered\":true,\"status_code\":200,\"error\":null,\"duration_ms\":42}"); + SupertextClient c = client(fake, "k"); + Webhook created = c.createWebhook("https://cms.example/hook", Collections.singletonList("translation.ai_file.completed"), null); + assertEquals("whsec_abc", created.getSecret()); + assertFalse(created.toString().contains("whsec_abc")); + assertEquals("{\"url\":\"https://cms.example/hook\",\"event_types\":[\"translation.ai_file.completed\"]}", fake.body(0)); + assertEquals(1, c.listWebhooks().size()); + c.updateWebhook("h1", null, null, null, true, true); + assertEquals("{\"description\":null,\"enabled\":true}", fake.body(2)); + assertEquals("PATCH", fake.requests.get(2).getMethod()); + c.deleteWebhook("h1"); + assertEquals(new WebhookTestResult(true, 200, null, 42), c.testWebhook("h1")); + } + + @Test + void nothingSentForBlankTargetOrKey() { + Fake fake = new Fake(); + assertEquals("unsupported_language", codeOf(() -> { + try { + client(fake, "k").translateTexts(Collections.singletonMap("a", Segment.text("x")), " "); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + })); + assertEquals("missing_api_key", codeOf(() -> { + try { + client(fake, " ").getAccount(); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + })); + assertTrue(fake.requests.isEmpty()); + } + + @Test + void fileNameFrom() { + assertEquals("a b.docx", SupertextClient.fileNameFrom("attachment; filename=\"a b.docx\"")); + assertEquals("Zürich.docx", SupertextClient.fileNameFrom("attachment; filename=x.pdf; filename*=UTF-8''Z%C3%BCrich.docx")); + assertNull(SupertextClient.fileNameFrom(null)); + } +} diff --git a/sdk/kotlin/README.md b/sdk/kotlin/README.md index 8816cbf..f1010b0 100644 --- a/sdk/kotlin/README.md +++ b/sdk/kotlin/README.md @@ -21,7 +21,7 @@ implementation("com.supertext:supertext-sdk-kotlin:0.7.0") The package isn't on Maven Central yet; until it is, use the jar attached to a [release](https://github.com/Supertext/Supertext-API-SDK-Guide/releases) or build it from `sdk/kotlin` (`mvn package`). -Everything that talks to the API is versioned: API v1 lives in the package `com.supertext.sdk.v1`. A later API version gets `com.supertext.sdk.v2` next to it, so an integration can move at its own pace. Version-neutral parts stay in `com.supertext.sdk`: `SDK_VERSION` (this SDK's version) and the HTTP layer (`Transport`, `JdkHttpTransport`). +Everything that talks to the API is versioned: API v1 lives in the package `com.supertext.sdk.v1`. API v2 is in `com.supertext.sdk.v2` next to it (see [API v2](#api-v2)), so an integration can move at its own pace. Version-neutral parts stay in `com.supertext.sdk`: `SDK_VERSION` (this SDK's version) and the HTTP layer (`Transport`, `JdkHttpTransport`). ## API key @@ -170,6 +170,32 @@ SupertextClient( `translateTexts(segments, target, source, politeness, maxCharacters)` sets the document size (default `SupertextClient.DEFAULT_MAX_CHARACTERS`, 900,000). Durations must be positive and `maxRetries` not negative (`IllegalArgumentException`); a blank key doesn't fail here, the first request throws `missing_api_key` without sending anything. +## API v2 + +Supertext's platform API (`https://api-platform.supertext.com/v1/`, `Authorization: Bearer st_live_…`) is in `com.supertext.sdk.v2`, next to v1. `translateTexts` takes the same segments and returns the same keys; texts go in direct requests of up to 10,000 characters (HTML segments with `TagHandling.HTML`), a longer segment through the file endpoint. Calls block, as in v1. No Supertext account yet? Create one at https://www.supertext.com/person/en/account/signin. Generate your API key at https://www.supertext.com/en/integrations/api (supertext.com → Integrations → API; requires the Admin role); API v2 takes the workspace keys (`st_live_…`) described in [Supertext's v2 documentation](https://www.supertext.com/en/neo/documentation/api). + +```kotlin +import com.supertext.sdk.v1.Politeness +import com.supertext.sdk.v1.Segment +import com.supertext.sdk.v2.SupertextClient +import com.supertext.sdk.v2.Webhooks + +val client = SupertextClient(System.getenv("SUPERTEXT_API_KEY")) +val german = client.translateTexts( + linkedMapOf("title" to Segment.text("Hello & welcome"), "body" to Segment.html("

Our new shop opens on Monday.

")), + "de-CH", + sourceLang = "en", + politeness = Politeness.MORE, + glossary = mapOf("shop" to "Laden"), +) +val docx = client.translateFile(File("offer.docx").readBytes(), "offer.docx", "fr-CH") // content, fileName + +// In your webhook endpoint: the raw body, before parsing it +val event = Webhooks.verify(System.getenv("SUPERTEXT_WEBHOOK_SECRET"), headers, rawBody) +``` + +What else is there: `translateText` (one request, with the detected source language and enforced glossary terms) and `quoteText`; documents with `translateFile` (upload, wait, download, always delete) or the single steps `submitFile`, `getFileStatus`, `waitForFile`, `downloadFile` (`null` while not ready), `deleteFile`, and `quoteFile`; `detectLanguage`, `detectFileLanguage` and their quotes; human review with `quoteFusedText`/`orderFusedText`, `getFusedTextStatus`, `getFusedText` (and the same for files: `orderFusedFile`, `getFusedFileStatus`, `downloadFusedFile`); `getAccount`, `getFeatures`, `validateApiKey`, `checkApiKey` (same `ApiKeyCheck` as v1, on `GET account`); webhooks (`createWebhook`, whose secret is returned only once, `listWebhooks`, `getWebhook`, `updateWebhook`, `deleteWebhook`, `testWebhook`). Errors are one type with the codes of `spec/v2/errors.json` (`insufficient_credit`, `invalid_request`, `authentication_failure`, …) and Supertext's `detail`, `apiErrorCode`, `errorId` and `reason`. More: [integration guide → API v2](../../docs/integration-guide.md#16-api-v2-the-supertext-platform-api). + ## Translation files For texts translated outside the API (a CAT tool, a translator, Supertext's web app), `com.supertext.sdk.files.TranslationFiles` exports segments as an XLIFF 1.2 file (one `` per job) or as the HTML document `HtmlDocument.build` makes, with the job's metadata, and imports the translated file again. Not tied to an API version: nothing here calls the API. Behaviour shared by all Supertext SDKs: `spec/translation-file.json`. diff --git a/sdk/kotlin/examples/ConformanceV2.kt b/sdk/kotlin/examples/ConformanceV2.kt new file mode 100644 index 0000000..db6476e --- /dev/null +++ b/sdk/kotlin/examples/ConformanceV2.kt @@ -0,0 +1,142 @@ +// v2 conformance program for stand-in/conformance.mjs --v2 (see spec/v2/conformance.json): reads one request as +// JSON on stdin, translates it with the v2 client's translateTexts (language codes passed through as given) and +// prints the result as JSON. +// +// mvn -q package -DskipTests (compiles this file with the tests and copies the Kotlin stdlib to target/lib) +// node ../../stand-in/conformance.mjs --v2 -- java -cp 'target/classes:target/test-classes:target/lib/*' ConformanceV2Kt +// +// It carries its own small JSON reader and writer: the SDK has no JSON dependency. + + +import com.supertext.sdk.v1.Politeness +import com.supertext.sdk.v1.Segment +import com.supertext.sdk.v2.SupertextClient +import com.supertext.sdk.v2.SupertextException +import java.io.PrintStream +import kotlin.time.Duration.Companion.milliseconds + +fun main() { + val out = PrintStream(System.out, true, "UTF-8") + val request = V2JsonReader(System.`in`.readBytes().toString(Charsets.UTF_8)).parse() as Map<*, *> + + val segments = LinkedHashMap() + for (item in request["segments"] as List<*>) { + val s = item as Map<*, *> + segments[s["key"] as String] = Segment(s["text"] as String, s["html"] == true) + } + val client = SupertextClient( + System.getenv("SUPERTEXT_API_KEY"), + baseUrl = System.getenv("SUPERTEXT_API_URL"), + pollInterval = 100.milliseconds, + ) + try { + val translations = client.translateTexts( + segments, + request["targetLang"] as String? ?: "", + request["sourceLang"] as String?, + Politeness.fromValue(request["politeness"] as String?), + maxCharacters = (request["maxCharacters"] as Number?)?.toInt() ?: SupertextClient.DEFAULT_MAX_TEXT_CHARACTERS, + ) + out.println(translations.entries.joinToString(",", "{\"translations\":{", "}}") { quote(it.key) + ":" + quote(it.value) }) + } catch (e: SupertextException) { + out.println("{\"error\":{\"code\":${quote(e.code.value)},\"status\":${e.status ?: "null"}}}") + } +} + +private fun quote(s: String): String = buildString { + append('"') + for (c in s) { + when (c) { + '"' -> append("\\\"") + '\\' -> append("\\\\") + '\n' -> append("\\n") + '\r' -> append("\\r") + '\t' -> append("\\t") + else -> if (c.code < 0x20) append(String.format("\\u%04x", c.code)) else append(c) + } + } + append('"') +} + +/** Just enough JSON for the request: objects, arrays, strings, booleans, null, numbers. */ +private class V2JsonReader(private val s: String) { + private var i = 0 + + fun parse(): Any? { + skip() + when (val c = s[i]) { + '{' -> { + val map = LinkedHashMap() + i++ + skip() + if (s[i] == '}') { + i++ + return map + } + do { + skip() + val key = parse() as String + skip() + i++ // ':' + map[key] = parse() + skip() + } while (s[i++] == ',') + return map + } + '[' -> { + val list = ArrayList() + i++ + skip() + if (s[i] == ']') { + i++ + return list + } + do { + list.add(parse()) + skip() + } while (s[i++] == ',') + return list + } + '"' -> { + val out = StringBuilder() + i++ + while (true) { + val ch = s[i++] + if (ch == '"') break + if (ch != '\\') { + out.append(ch) + continue + } + when (val e = s[i++]) { + 'n' -> out.append('\n') + 'r' -> out.append('\r') + 't' -> out.append('\t') + 'b' -> out.append('\b') + 'f' -> out.append('\u000c') + 'u' -> { + out.append(s.substring(i, i + 4).toInt(16).toChar()) + i += 4 + } + else -> out.append(e) + } + } + return out.toString() + } + else -> { + for (word in listOf("true", "false", "null")) { + if (s.startsWith(word, i)) { + i += word.length + return if (word == "null") null else word.toBoolean() + } + } + val start = i + while (i < s.length && "-+.eE0123456789".indexOf(s[i]) >= 0) i++ + return s.substring(start, i).toDoubleOrNull() ?: error("bad JSON at $start: $c") + } + } + } + + private fun skip() { + while (i < s.length && s[i].isWhitespace()) i++ + } +} diff --git a/sdk/kotlin/src/main/kotlin/com/supertext/sdk/Transport.kt b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/Transport.kt index 985c664..3b9bc6d 100644 --- a/sdk/kotlin/src/main/kotlin/com/supertext/sdk/Transport.kt +++ b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/Transport.kt @@ -49,20 +49,34 @@ public class HttpRequestData( * @param headers first value per header name (looked up case-insensitively) * @param body the body decoded as UTF-8 (`""` for none) */ -public class HttpResponseData( +public class HttpResponseData private constructor( public val status: Int, - headers: Map? = null, - body: String? = null, + headers: Map?, + private val bytes: ByteArray, ) { + public constructor(status: Int, headers: Map? = null, body: String? = null) : + this(status, headers, (body ?: "").toByteArray(StandardCharsets.UTF_8)) + private val headerMap: Map = TreeMap(String.CASE_INSENSITIVE_ORDER).apply { if (headers != null) putAll(headers) } - public val body: String = body ?: "" + /** The body decoded as UTF-8 (the API answers in UTF-8). */ + public val body: String get() = String(bytes, StandardCharsets.UTF_8) + + /** The body as bytes (downloads of binary documents). */ + public val bodyBytes: ByteArray get() = bytes.copyOf() /** A header's value, or `null`; the name is case-insensitive. */ public fun header(name: String): String? = headerMap[name] override fun toString(): String = "HTTP $status" + + public companion object { + /** An answer with the body as bytes. */ + @JvmStatic + public fun ofBytes(status: Int, headers: Map?, body: ByteArray): HttpResponseData = + HttpResponseData(status, headers, body.copyOf()) + } } /** The default [Transport]: the JDK's [HttpClient]. */ @@ -85,12 +99,12 @@ public class JdkHttpTransport( request.method, if (body == null) HttpRequest.BodyPublishers.noBody() else HttpRequest.BodyPublishers.ofByteArray(body), ) - // The API answers in UTF-8; decode as such whatever the Content-Type says. - val response = http.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)) + // Bytes: downloads can be binary documents. HttpResponseData.body decodes UTF-8, whatever the Content-Type says. + val response = http.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray()) val headers = LinkedHashMap() for ((name, values) in response.headers().map()) { if (values.isNotEmpty()) headers[name] = values[0] } - return HttpResponseData(response.statusCode(), headers, response.body()) + return HttpResponseData.ofBytes(response.statusCode(), headers, response.body()) } } diff --git a/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Errors.kt b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Errors.kt new file mode 100644 index 0000000..1b5b9f4 --- /dev/null +++ b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Errors.kt @@ -0,0 +1,147 @@ +package com.supertext.sdk.v2 + +import com.supertext.sdk.v1.Json + +/** The error codes of the v2 client: fixed strings shared by all Supertext SDKs (spec/v2/errors.json). */ +public enum class ErrorCode( + /** The shared string, e.g. `insufficient_credit`. */ + public val value: String, + /** An English message. */ + public val message: String, +) { + /** No key configured; nothing was sent. */ + MISSING_API_KEY("missing_api_key", "No Supertext API key is configured."), + + /** HTTP 401/403. */ + AUTHENTICATION_FAILURE("authentication_failure", "Supertext rejected the API key. Please check it."), + + /** HTTP 402: the credit balance doesn't cover the request. */ + INSUFFICIENT_CREDIT("insufficient_credit", "The Supertext credit balance does not cover this request. Please top up."), + + /** HTTP 422: validation, e.g. a language the API doesn't offer. */ + INVALID_REQUEST("invalid_request", "Supertext rejected the request."), + + /** A blank language code; nothing was sent. */ + UNSUPPORTED_LANGUAGE("unsupported_language", "This language has no Supertext language code. Map it to a Supertext language."), + + /** HTTP 404. */ + NOT_FOUND("not_found", "Not found at Supertext (expired or already deleted)."), + + /** HTTP 409, e.g. webhook_limit_reached. */ + CONFLICT("conflict", "Supertext refused the change."), + + /** HTTP 413. */ + PAYLOAD_TOO_LARGE("payload_too_large", "The document is too large for Supertext."), + + /** HTTP 429 after the retries. */ + TOO_MANY_REQUESTS("too_many_requests", "Too many requests to Supertext. Please try again shortly."), + + /** HTTP 5xx. */ + SERVICE_UNAVAILABLE("service_unavailable", "The Supertext service is unavailable."), + + /** Any other HTTP status. */ + UNEXPECTED_STATUS("unexpected_status", "Supertext sent an unexpected HTTP status."), + + /** No HTTP answer. */ + TRANSPORT_ERROR("transport_error", "Could not reach Supertext."), + + /** The answer lacks what it should carry. */ + INCOMPLETE_RESPONSE("incomplete_response", "The Supertext answer is incomplete."), + + /** Status error (AI file) or failed (human review). */ + TRANSLATION_ERROR("translation_error", "Supertext failed to translate."), + + /** The file was deleted before it could be downloaded. */ + FILE_DELETED("file_deleted", "The Supertext file was deleted before it could be downloaded."), + + /** Waited longer than the timeout. */ + TIMEOUT("timeout", "Timed out waiting for the Supertext translation to finish."), + + /** A webhook request that isn't a valid, signed event. */ + INVALID_WEBHOOK("invalid_webhook", "The webhook request is not a valid, signed Supertext event."), + ; + + override fun toString(): String = value +} + +/** + * Any failure of the v2 client (spec/v2/errors.json). [detail] is the API's explanation (safe to show), + * [apiErrorCode] the problem's `code`, [errorId] its `error_id` (quote it to support), [reason] its `reason`. + * Never contains the API key. + */ +public class SupertextException( + public val code: ErrorCode, + public val status: Int? = null, + detail: String? = null, + apiErrorCode: String? = null, + errorId: String? = null, + reason: String? = null, + cause: Throwable? = null, +) : RuntimeException(buildMessage(code, status, detail?.ifEmpty { null }, errorId?.ifEmpty { null }), cause) { + /** The API's explanation, at most 200 characters. */ + public val detail: String? = detail?.ifEmpty { null } + + /** The problem's `code`, e.g. `validation_error`. */ + public val apiErrorCode: String? = apiErrorCode?.ifEmpty { null } + + /** The problem's `error_id`: quote it to Supertext support. */ + public val errorId: String? = errorId?.ifEmpty { null } + + /** The problem's `reason`, e.g. `insufficient_credit`. */ + public val reason: String? = reason?.ifEmpty { null } + + public companion object { + private val TAGS = Regex("<[^>]*>") + + private fun buildMessage(code: ErrorCode, status: Int?, detail: String?, errorId: String?): String = buildString { + append(code.message) + if (status != null) append(" HTTP ").append(status).append('.') + if (detail != null) append(" Details: ").append(detail) + if (errorId != null) append(" (error id ").append(errorId).append(')') + } + + /** Maps a non-2xx answer (problem+json) to an error. */ + @JvmStatic + public fun forResponse(status: Int, body: String): SupertextException { + val json = try { + Json.parse(body) as? Map<*, *> + } catch (e: IllegalArgumentException) { + null + } + fun text(name: String): String? = (json?.get(name) as? String)?.ifEmpty { null } + val detail = cut(text("detail") ?: TAGS.replace(body, "")) + val code = when { + status == 401 || status == 403 -> ErrorCode.AUTHENTICATION_FAILURE + status == 402 -> ErrorCode.INSUFFICIENT_CREDIT + status == 404 -> ErrorCode.NOT_FOUND + status == 409 -> ErrorCode.CONFLICT + status == 413 -> ErrorCode.PAYLOAD_TOO_LARGE + status == 422 -> ErrorCode.INVALID_REQUEST + status == 429 -> ErrorCode.TOO_MANY_REQUESTS + status in 500..599 -> ErrorCode.SERVICE_UNAVAILABLE + else -> ErrorCode.UNEXPECTED_STATUS + } + return SupertextException(code, status, detail, text("code"), text("error_id"), text("reason")) + } + + /** The error for a polled status, or `null`: AI file (`file`) error/deleted, human review (`fused`) failed. */ + @JvmStatic + public fun forStatusValue(kind: String, status: String, error: String?): SupertextException? { + val detail = cut(error ?: "") + return when { + (kind == "file" && status == "error") || (kind == "fused" && status == "failed") -> + SupertextException(ErrorCode.TRANSLATION_ERROR, detail = detail) + kind == "file" && status == "deleted" -> SupertextException(ErrorCode.FILE_DELETED) + else -> null + } + } + + internal fun isAsciiSpace(c: Char): Boolean = c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\u000c' + + private fun cut(text: String): String? { + val trimmed = text.trim(::isAsciiSpace) + if (trimmed.isEmpty()) return null + return if (trimmed.codePointCount(0, trimmed.length) <= 200) trimmed else trimmed.substring(0, trimmed.offsetByCodePoints(0, 200)) + } + } +} diff --git a/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/SupertextClient.kt b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/SupertextClient.kt new file mode 100644 index 0000000..1713c2d --- /dev/null +++ b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/SupertextClient.kt @@ -0,0 +1,698 @@ +package com.supertext.sdk.v2 + +import com.supertext.sdk.HttpRequestData +import com.supertext.sdk.HttpResponseData +import com.supertext.sdk.JdkHttpTransport +import com.supertext.sdk.Transport +import com.supertext.sdk.v1.ApiKeyCheck +import com.supertext.sdk.v1.HtmlDocument +import com.supertext.sdk.v1.Json +import com.supertext.sdk.v1.Politeness +import com.supertext.sdk.v1.Segment +import com.supertext.sdk.v1.Sleeper +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.net.URI +import java.net.URLDecoder +import java.net.URLEncoder +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.security.SecureRandom +import java.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.nanoseconds +import kotlin.time.Duration.Companion.seconds +import com.supertext.sdk.v1.SupertextClient as V1Client + +/** + * Client for the Supertext API v2 (https://api-platform.supertext.com/v1, workspace keys sent as + * `Bearer st_live_…`): text translation in one request, AI file translation, language detection, human review + * ("fused"), quotes, the account and webhooks. Calls block: from coroutines, run them on an IO dispatcher. + * A blank key doesn't throw here: the first request throws `missing_api_key`. + */ +public class SupertextClient @JvmOverloads constructor( + apiKey: String?, + baseUrl: String? = LIVE_BASE_URL, + private val pollInterval: Duration = 2.seconds, + private val timeout: Duration = 180.seconds, + private val requestTimeout: Duration = 30.seconds, + private val maxRetries: Int = 4, + userAgent: String? = null, + private val transport: Transport = JdkHttpTransport(), + private val sleeper: Sleeper = Sleeper { Thread.sleep(it.inWholeMilliseconds) }, + private val nanoTime: () -> Long = System::nanoTime, + private val wallClock: Clock = Clock.systemUTC(), +) { + private val apiKey: String = apiKey ?: "" + private val baseUrl: String = (if (baseUrl.isNullOrBlank()) LIVE_BASE_URL else baseUrl.trim()).let { if (it.endsWith("/")) it else "$it/" } + private val userAgent: String = if (userAgent.isNullOrBlank()) SDK_USER_AGENT else "$SDK_USER_AGENT ${userAgent.trim()}" + + init { + require(pollInterval.isPositive()) { "pollInterval must be positive" } + require(timeout.isPositive()) { "timeout must be positive" } + require(requestTimeout.isPositive()) { "requestTimeout must be positive" } + require(maxRetries >= 0) { "maxRetries must not be negative" } + } + + override fun toString(): String = "SupertextClient(baseUrl=$baseUrl)" + + public companion object { + /** The live API. */ + public const val LIVE_BASE_URL: String = "https://api-platform.supertext.com/v1/" + + /** Characters per `POST translate/ai/text`: the API's limit. */ + public const val DEFAULT_MAX_TEXT_CHARACTERS: Int = 10_000 + + private const val DEFAULT_MAX_FILE_CHARACTERS = 900_000 + private const val SDK_USER_AGENT = "supertext-sdk-kotlin" + private val BEARER = Regex("^bearer(?:[ \\t\\n\\r\\u000c]+|$)", RegexOption.IGNORE_CASE) + private val FILENAME_STAR = Regex("filename\\*\\s*=\\s*UTF-8''([^;]+)", RegexOption.IGNORE_CASE) + private val FILENAME_PLAIN = Regex("filename\\s*=\\s*(?:\"([^\"]*)\"|([^;\\s]+))", RegexOption.IGNORE_CASE) + private val RANDOM = SecureRandom() + private val TYPES = mapOf( + "html" to "text/html", + "htm" to "text/html", + "txt" to "text/plain", + "srt" to "application/x-subrip", + "pdf" to "application/pdf", + "docx" to "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "pptx" to "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "xlsx" to "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) + + private fun trimAscii(text: String): String = text.trim(SupertextException::isAsciiSpace) + + /** `Bearer ` for a key as pasted (spec/v2/auth-header.json); throws `missing_api_key` for a blank key. */ + @JvmStatic + public fun authHeader(apiKey: String?): String { + val key = trimAscii(BEARER.replaceFirst(trimAscii(apiKey ?: ""), "")) + if (key.isEmpty()) throw SupertextException(ErrorCode.MISSING_API_KEY) + return "Bearer $key" + } + + /** SHA-256 (lower-case hex) of the key as [authHeader] sends it; `""` for a blank key. */ + @JvmStatic + public fun fingerprint(apiKey: String?): String { + val key = try { + authHeader(apiKey).removePrefix("Bearer ") + } catch (e: SupertextException) { + return "" + } + return MessageDigest.getInstance("SHA-256").digest(key.toByteArray(StandardCharsets.UTF_8)).joinToString("") { "%02x".format(it) } + } + + /** Splits segments into requests (spec/v2/batching.json). */ + @JvmStatic + @JvmOverloads + public fun planRequests(segments: Map, maxCharacters: Int = DEFAULT_MAX_TEXT_CHARACTERS): List { + val plain = LinkedHashMap() + val html = LinkedHashMap() + val oversized = ArrayList() + for ((key, segment) in segments) { + if (trimAscii(segment.text).isEmpty()) continue + val length = segment.text.codePointCount(0, segment.text.length) + when { + length > maxCharacters -> oversized += key + segment.html -> html[key] = length + else -> plain[key] = length + } + } + val out = ArrayList() + fun split(kind: String, lengths: Map, limit: Int) { + var current = ArrayList() + var size = 0L + for ((key, length) in lengths) { + if (current.isNotEmpty() && size + length > limit) { + out += PlannedRequest(kind, current) + current = ArrayList() + size = 0 + } + current += key + size += length + } + if (current.isNotEmpty()) out += PlannedRequest(kind, current) + } + split("text", plain, maxCharacters) + split("html", html, maxCharacters) + split("file", oversized.associateWith { HtmlDocument.content(segments.getValue(it)).let { c -> c.codePointCount(0, c.length) } }, DEFAULT_MAX_FILE_CHARACTERS) + return out + } + + /** The Content-Type for a file name's extension; else `application/octet-stream`. */ + @JvmStatic + public fun contentTypeFor(fileName: String?): String = + fileName?.substringAfterLast('.', "")?.lowercase()?.let { TYPES[it] } ?: "application/octet-stream" + + /** The file name of a `Content-Disposition` header (`filename*=UTF-8''…` preferred). */ + @JvmStatic + public fun fileNameFrom(disposition: String?): String? { + if (disposition.isNullOrEmpty()) return null + FILENAME_STAR.find(disposition)?.let { m -> + try { + return URLDecoder.decode(m.groupValues[1].trim().replace("+", "%2B"), "UTF-8") + } catch (e: IllegalArgumentException) { + // fall through to the plain parameter + } + } + val plain = FILENAME_PLAIN.find(disposition) ?: return null + return plain.groups[1]?.value ?: plain.groups[2]?.value + } + + /** The key check for a failed `GET account`. */ + @JvmStatic + public fun keyCheckFromError(error: Throwable, checkedAt: String, fingerprint: String): ApiKeyCheck { + val e = error as? SupertextException ?: return ApiKeyCheck(ApiKeyCheck.Status.ERROR, checkedAt, null, null, fingerprint) + val http = e.status + val status = when { + e.code == ErrorCode.MISSING_API_KEY -> ApiKeyCheck.Status.MISSING + http == 401 || http == 403 -> ApiKeyCheck.Status.INVALID + http == null || http >= 500 -> ApiKeyCheck.Status.UNREACHABLE + else -> ApiKeyCheck.Status.ERROR + } + return ApiKeyCheck(status, checkedAt, http, e.apiErrorCode?.take(100), fingerprint) + } + + private fun encode(value: String): String = URLEncoder.encode(value, "UTF-8").replace("+", "%20") + } + + // ---- account and features + + /** The workspace and key behind the API key. Cost-free. */ + public fun getAccount(): Account { + val o = json("GET", "account") + return Account(text(o, "workspace_id"), text(o, "workspace_name"), text(o, "api_key_name"), text(o, "api_key_prefix"), text(o, "api_key_expires_at")) + } + + /** The language pairs and their features, optionally filtered. Cost-free. */ + @JvmOverloads + public fun getFeatures(sourceLang: String? = null, targetLang: String? = null): List { + val query = listOfNotNull( + sourceLang?.takeIf { it.isNotEmpty() }?.let { "source_lang=${encode(it)}" }, + targetLang?.takeIf { it.isNotEmpty() }?.let { "target_lang=${encode(it)}" }, + ) + val list = json("GET", if (query.isEmpty()) "features" else "features?" + query.joinToString("&"))["supported_features"] as? List<*> + ?: return emptyList() + return list.mapNotNull { item -> + val m = item as? Map<*, *> ?: return@mapNotNull null + val source = m["source_lang"] as? String ?: return@mapNotNull null + val target = m["target_lang"] as? String ?: return@mapNotNull null + FeatureSupport(source, target, strings(m["features"])) + } + } + + /** Throws unless the key is accepted (`GET account`). */ + public fun validateApiKey() { + request("GET", "account") + } + + /** The automatic key check (spec/v2/api-key-check.json). Never throws (except when interrupted). */ + public fun checkApiKey(): ApiKeyCheck { + val checkedAt = ApiKeyCheck.isoSeconds(wallClock.instant()) + val fingerprint = fingerprint(apiKey) + if (fingerprint.isEmpty()) return ApiKeyCheck(ApiKeyCheck.Status.MISSING, checkedAt, null, null, "") + return try { + val response = request("GET", "account", timeout = minOf(requestTimeout, ApiKeyCheck.TIMEOUT)) + ApiKeyCheck(ApiKeyCheck.Status.OK, checkedAt, response.status, null, fingerprint) + } catch (e: RuntimeException) { + keyCheckFromError(e, checkedAt, fingerprint) + } + } + + // ---- text + + /** One `POST translate/ai/text`: the translations in input order. Codes are sent as given. */ + @JvmOverloads + public fun translateText( + texts: List, + targetLang: String, + sourceLang: String? = null, + politeness: Politeness = Politeness.DEFAULT, + glossary: Map? = null, + tagHandling: TagHandling = TagHandling.NONE, + ): TextTranslation { + val o = json("POST", "translate/ai/text", jsonBytes(textPayload(texts, targetLang, sourceLang, politeness, glossary, tagHandling)), "application/json") + val translations = strings(o["translated_text"]) + if (o["translated_text"] !is List<*> || translations.size != texts.size) { + throw SupertextException(ErrorCode.INCOMPLETE_RESPONSE, detail = "expected ${texts.size} translations") + } + return TextTranslation(translations, textOrNull(o, "detected_source_lang"), stringMap(o["enforced_terms"]), textOrNull(o, "request_id")) + } + + /** What [translateText] would cost (a free dry run). */ + @JvmOverloads + public fun quoteText( + texts: List, + targetLang: String, + sourceLang: String? = null, + politeness: Politeness = Politeness.DEFAULT, + glossary: Map? = null, + tagHandling: TagHandling = TagHandling.NONE, + ): Quote = quote(json("POST", "translate/ai/text/quote", jsonBytes(textPayload(texts, targetLang, sourceLang, politeness, glossary, tagHandling)), "application/json")) + + /** + * Translates keyed texts (spec/v2/batching.json): the same keys in input order, blanks unchanged. Up to + * [maxCharacters] per request; a longer segment goes through an HTML file. + */ + @JvmOverloads + public fun translateTexts( + segments: Map, + targetLang: String, + sourceLang: String? = null, + politeness: Politeness = Politeness.DEFAULT, + glossary: Map? = null, + maxCharacters: Int = DEFAULT_MAX_TEXT_CHARACTERS, + ): Map { + required(targetLang) + val result = LinkedHashMap() + for ((key, segment) in segments) result[key] = segment.text + for (planned in planRequests(segments, maxCharacters)) { + val batch = planned.keys.map { segments.getValue(it) } + if (planned.kind == "file") { + val parsed = HtmlDocument.parse(translateHtml(HtmlDocument.build(batch), targetLang, sourceLang, politeness, glossary), batch) + val missing = planned.keys.filterIndexed { i, _ -> parsed[i] == null } + if (missing.isNotEmpty()) throw SupertextException(ErrorCode.INCOMPLETE_RESPONSE, detail = "missing: " + missing.joinToString(", ")) + planned.keys.forEachIndexed { i, key -> result[key] = parsed[i]!! } + } else { + val answer = translateText(batch.map { it.text }, targetLang, sourceLang, politeness, glossary, + if (planned.kind == "html") TagHandling.HTML else TagHandling.NONE) + planned.keys.forEachIndexed { i, key -> result[key] = answer.translations[i] } + } + } + return result + } + + // ---- AI file translation + + /** Uploads a document for AI translation; returns the file id. */ + @JvmOverloads + public fun submitFile( + content: ByteArray, + fileName: String, + targetLang: String, + sourceLang: String? = null, + politeness: Politeness = Politeness.DEFAULT, + glossary: Map? = null, + useOcr: Boolean? = null, + ): String { + val form = fileForm(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr) + return textOrNull(json("POST", "translate/ai/file", form.first, form.second), "file_id") + ?: throw SupertextException(ErrorCode.INCOMPLETE_RESPONSE, detail = "no file_id") + } + + /** The status of an AI file translation. */ + public fun getFileStatus(fileId: String): FileStatus { + val o = json("GET", "translate/ai/file/${encode(fileId)}/status") + return FileStatus(text(o, "status"), textOrNull(o, "error"), intOrNull(o["estimated_duration_left_in_seconds"]), textOrNull(o, "detected_source_lang")) + } + + /** Polls until `done`; throws `translation_error`, `file_deleted` or `timeout`. */ + public fun waitForFile(fileId: String): FileStatus { + val start = nanoTime() + while (true) { + val status = getFileStatus(fileId) + if (status.status == "done") return status + SupertextException.forStatusValue("file", status.status, status.error)?.let { throw it } + if ((nanoTime() - start).nanoseconds + pollInterval > timeout) throw SupertextException(ErrorCode.TIMEOUT) + sleeper.sleep(pollInterval) + } + } + + /** The translated document, or `null` while it isn't ready (HTTP 202). Available for 24 hours. */ + public fun downloadFile(fileId: String): DownloadedFile? = download(request("GET", "translate/ai/file/${encode(fileId)}/translation")) + + /** Deletes the document and its translation. Never throws (except when interrupted). */ + public fun deleteFile(fileId: String) { + try { + request("DELETE", "translate/ai/file/${encode(fileId)}") + } catch (e: SupertextException) { + // Best effort: files expire after 24 hours anyway. + } + } + + /** Upload, wait, download, and always delete. */ + @JvmOverloads + public fun translateFile( + content: ByteArray, + fileName: String, + targetLang: String, + sourceLang: String? = null, + politeness: Politeness = Politeness.DEFAULT, + glossary: Map? = null, + useOcr: Boolean? = null, + ): DownloadedFile { + val fileId = submitFile(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr) + try { + waitForFile(fileId) + val file = downloadFile(fileId) + if (file == null || file.content.isEmpty()) throw SupertextException(ErrorCode.INCOMPLETE_RESPONSE, detail = "empty document") + return file + } finally { + deleteFile(fileId) + } + } + + /** One HTML document through the file endpoint (as `content.html`). */ + @JvmOverloads + public fun translateHtml( + html: String, + targetLang: String, + sourceLang: String? = null, + politeness: Politeness = Politeness.DEFAULT, + glossary: Map? = null, + ): String = String(translateFile(html.toByteArray(StandardCharsets.UTF_8), "content.html", targetLang, sourceLang, politeness, glossary).content, StandardCharsets.UTF_8) + + /** What translating a document would cost. */ + @JvmOverloads + public fun quoteFile( + content: ByteArray, + fileName: String, + targetLang: String, + sourceLang: String? = null, + politeness: Politeness = Politeness.DEFAULT, + glossary: Map? = null, + useOcr: Boolean? = null, + ): Quote { + val form = fileForm(content, fileName, targetLang, sourceLang, politeness, glossary, useOcr) + return quote(json("POST", "translate/ai/file/quote", form.first, form.second)) + } + + // ---- language detection + + /** The language of a text (the first 500 characters are read). Empty when none was found. */ + public fun detectLanguage(text: String): List = + detected(json("POST", "detect-languages/text", jsonBytes(mapOf("text" to text)), "application/json")) + + /** What a detection would cost. */ + public fun quoteDetection(text: String): Quote = + quote(json("POST", "detect-languages/text/quote", jsonBytes(mapOf("text" to text)), "application/json")) + + /** The language of a document. */ + public fun detectFileLanguage(content: ByteArray, fileName: String): List { + val form = multipart(emptyList(), content, fileName) + return detected(json("POST", "detect-languages/file", form.first, form.second)) + } + + /** What detecting a document's language would cost. */ + public fun quoteFileDetection(content: ByteArray, fileName: String): Quote { + val form = multipart(emptyList(), content, fileName) + return quote(json("POST", "detect-languages/file/quote", form.first, form.second)) + } + + // ---- human review ("fused") + + /** Orders a reviewed translation of a text; the source language is required. Charged when accepted. */ + @JvmOverloads + public fun orderFusedText( + text: String, + sourceLang: String, + targetLang: String, + politeness: Politeness = Politeness.DEFAULT, + briefing: String? = null, + idempotencyKey: String? = null, + ): FusedOrder { + val extra = if (idempotencyKey.isNullOrEmpty()) emptyMap() else mapOf("Idempotency-Key" to idempotencyKey) + return fusedOrder(json("POST", "translate/fused/text", jsonBytes(fusedPayload(text, sourceLang, targetLang, politeness, briefing)), "application/json", extra)) + } + + /** The status of a human-review text order. */ + public fun getFusedTextStatus(translationId: String): FusedStatus = fusedStatus(json("GET", "translate/fused/text/${encode(translationId)}/status")) + + /** The reviewed text, or `null` while it isn't delivered yet (HTTP 202). */ + public fun getFusedText(translationId: String): String? { + val response = request("GET", "translate/fused/text/${encode(translationId)}/translation") + if (response.status == 202) return null + return parseObject(response.body)["translated_text"] as? String + ?: throw SupertextException(ErrorCode.INCOMPLETE_RESPONSE, detail = "no translated_text") + } + + /** What a human-review text order would cost and how long it would take. */ + @JvmOverloads + public fun quoteFusedText(text: String, sourceLang: String, targetLang: String, politeness: Politeness = Politeness.DEFAULT, briefing: String? = null): FusedQuote = + fusedQuote(json("POST", "translate/fused/text/quote", jsonBytes(fusedPayload(text, sourceLang, targetLang, politeness, briefing)), "application/json")) + + /** Orders a reviewed translation of a document (PDFs come back as DOCX). */ + @JvmOverloads + public fun orderFusedFile( + content: ByteArray, + fileName: String, + sourceLang: String, + targetLang: String, + politeness: Politeness = Politeness.DEFAULT, + briefing: String? = null, + useOcr: Boolean? = null, + ): FusedOrder { + val form = fusedForm(content, fileName, sourceLang, targetLang, politeness, briefing, useOcr) + return fusedOrder(json("POST", "translate/fused/file", form.first, form.second)) + } + + /** The status of a human-review document order. */ + public fun getFusedFileStatus(translationId: String): FusedStatus = fusedStatus(json("GET", "translate/fused/file/${encode(translationId)}/status")) + + /** The reviewed document, or `null` until a reviewer delivers (HTTP 202). */ + public fun downloadFusedFile(translationId: String): DownloadedFile? = download(request("GET", "translate/fused/file/${encode(translationId)}/translation")) + + /** What a human-review document order would cost and how long it would take. */ + @JvmOverloads + public fun quoteFusedFile( + content: ByteArray, + fileName: String, + sourceLang: String, + targetLang: String, + politeness: Politeness = Politeness.DEFAULT, + briefing: String? = null, + useOcr: Boolean? = null, + ): FusedQuote { + val form = fusedForm(content, fileName, sourceLang, targetLang, politeness, briefing, useOcr) + return fusedQuote(json("POST", "translate/fused/file/quote", form.first, form.second)) + } + + // ---- webhooks + + /** This key's webhooks. */ + public fun listWebhooks(): List = (json("GET", "webhooks")["items"] as? List<*>)?.map { webhook(it as? Map<*, *> ?: emptyMap(), false) } ?: emptyList() + + /** Registers a webhook; the result's secret is shown only once: store it. */ + @JvmOverloads + public fun createWebhook(url: String, eventTypes: List, description: String? = null): Webhook { + val body = linkedMapOf("url" to url, "event_types" to eventTypes) + if (description != null) body["description"] = description + return webhook(json("POST", "webhooks", jsonBytes(body), "application/json"), true) + } + + /** One webhook. */ + public fun getWebhook(webhookId: String): Webhook = webhook(json("GET", "webhooks/${encode(webhookId)}"), false) + + /** Changes only the fields given (`null`: unchanged); [clearDescription] sends description null. */ + @JvmOverloads + public fun updateWebhook( + webhookId: String, + url: String? = null, + eventTypes: List? = null, + description: String? = null, + enabled: Boolean? = null, + clearDescription: Boolean = false, + ): Webhook { + val body = linkedMapOf() + if (url != null) body["url"] = url + if (eventTypes != null) body["event_types"] = eventTypes + if (description != null || clearDescription) body["description"] = description + if (enabled != null) body["enabled"] = enabled + return webhook(json("PATCH", "webhooks/${encode(webhookId)}", jsonBytes(body), "application/json"), false) + } + + /** Deletes a webhook. */ + public fun deleteWebhook(webhookId: String) { + request("DELETE", "webhooks/${encode(webhookId)}") + } + + /** Sends a test event (at most one per 5 seconds). */ + public fun testWebhook(webhookId: String): WebhookTestResult { + val o = json("POST", "webhooks/${encode(webhookId)}/test") + return WebhookTestResult(o["delivered"] == true, intOrNull(o["status_code"]), textOrNull(o, "error"), intOrNull(o["duration_ms"]) ?: 0) + } + + // ---- HTTP + + private fun json(method: String, path: String, body: ByteArray? = null, contentType: String? = null, extra: Map = emptyMap()): Map<*, *> = + parseObject(request(method, path, body, contentType, requestTimeout, extra).body) + + private fun request( + method: String, + path: String, + body: ByteArray? = null, + contentType: String? = null, + timeout: Duration = requestTimeout, + extra: Map = emptyMap(), + ): HttpResponseData { + val authorization = authHeader(apiKey) + val key = authorization.removePrefix("Bearer ") + val headers = LinkedHashMap(extra) + headers["Authorization"] = authorization + headers["Accept"] = "application/json, application/problem+json" + headers["User-Agent"] = userAgent + if (contentType != null) headers["Content-Type"] = contentType + val request = HttpRequestData(method, URI.create(baseUrl + path), headers, body, timeout) + var attempt = 0 + while (true) { + val response = try { + transport.send(request) + } catch (e: IOException) { + val message = e.message ?: e.javaClass.simpleName + val detail = message.replace(key, "***") + throw SupertextException(ErrorCode.TRANSPORT_ERROR, detail = detail, cause = if (detail == message) e else null) + } + val status = response.status + if (status in 200..299) return response + if (status == 429 && attempt < maxRetries) { + sleeper.sleep(V1Client.retryDelayMs(attempt, response.header("Retry-After")).milliseconds) + attempt++ + continue + } + throw SupertextException.forResponse(status, response.body.replace(key, "***")) + } + } + + // ---- payloads + + private fun required(code: String?): String = trimAscii(code ?: "").ifEmpty { throw SupertextException(ErrorCode.UNSUPPORTED_LANGUAGE) } + + private fun politenessValue(politeness: Politeness): String? = when (politeness) { + Politeness.MORE -> "more" + Politeness.LESS -> "less" + else -> null + } + + private fun textPayload( + texts: List, + targetLang: String, + sourceLang: String?, + politeness: Politeness, + glossary: Map?, + tagHandling: TagHandling, + ): Map { + val body = linkedMapOf("text" to texts.toList(), "target_lang" to required(targetLang)) + trimAscii(sourceLang ?: "").takeIf { it.isNotEmpty() }?.let { body["source_lang"] = it } + politenessValue(politeness)?.let { body["politeness"] = it } + if (!glossary.isNullOrEmpty()) body["glossary"] = LinkedHashMap(glossary) + if (tagHandling != TagHandling.NONE) body["tag_handling"] = tagHandling.value + return body + } + + private fun fileForm( + content: ByteArray, + fileName: String, + targetLang: String, + sourceLang: String?, + politeness: Politeness, + glossary: Map?, + useOcr: Boolean?, + ): Pair { + val fields = arrayListOf("target_lang" to required(targetLang)) + trimAscii(sourceLang ?: "").takeIf { it.isNotEmpty() }?.let { fields += "source_lang" to it } + politenessValue(politeness)?.let { fields += "politeness" to it } + if (!glossary.isNullOrEmpty()) fields += "glossary" to Json.write(LinkedHashMap(glossary)) + if (useOcr != null) fields += "use_ocr" to useOcr.toString() + return multipart(fields, content, fileName) + } + + private fun fusedPayload(text: String, sourceLang: String, targetLang: String, politeness: Politeness, briefing: String?): Map { + val body = linkedMapOf("text" to text, "source_lang" to required(sourceLang), "target_lang" to required(targetLang)) + politenessValue(politeness)?.let { body["politeness"] = it } + if (!briefing.isNullOrEmpty()) body["briefing"] = briefing + return body + } + + private fun fusedForm( + content: ByteArray, + fileName: String, + sourceLang: String, + targetLang: String, + politeness: Politeness, + briefing: String?, + useOcr: Boolean?, + ): Pair { + val fields = arrayListOf("target_lang" to required(targetLang), "source_lang" to required(sourceLang)) + politenessValue(politeness)?.let { fields += "politeness" to it } + if (!briefing.isNullOrEmpty()) fields += "briefing" to briefing + if (useOcr != null) fields += "use_ocr" to useOcr.toString() + return multipart(fields, content, fileName) + } + + private fun jsonBytes(value: Any?): ByteArray = Json.write(value).toByteArray(StandardCharsets.UTF_8) + + private fun multipart(fields: List>, content: ByteArray, fileName: String): Pair { + val random = ByteArray(12).also { RANDOM.nextBytes(it) } + val boundary = "----supertext-" + random.joinToString("") { "%02x".format(it) } + val out = ByteArrayOutputStream() + val head = StringBuilder() + for ((name, value) in fields) head.append("--$boundary\r\nContent-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n") + val safe = fileName.replace(Regex("[\"\\r\\n\\\\]"), "_") + head.append("--$boundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"$safe\"\r\nContent-Type: ${contentTypeFor(fileName)}\r\n\r\n") + out.write(head.toString().toByteArray(StandardCharsets.UTF_8)) + out.write(content) + out.write("\r\n--$boundary--\r\n".toByteArray(StandardCharsets.UTF_8)) + return out.toByteArray() to "multipart/form-data; boundary=$boundary" + } + + // ---- answers + + private fun parseObject(body: String): Map<*, *> = try { + Json.parse(body) as? Map<*, *> ?: emptyMap() + } catch (e: IllegalArgumentException) { + emptyMap() + } + + private fun text(o: Map<*, *>, name: String): String = o[name] as? String ?: "" + + private fun textOrNull(o: Map<*, *>, name: String): String? = (o[name] as? String)?.ifEmpty { null } + + private fun intOrNull(v: Any?): Int? { + val d = (v as? Number)?.toDouble() ?: return null + return if (d == Math.rint(d) && kotlin.math.abs(d) <= Int.MAX_VALUE) d.toInt() else null + } + + private fun strings(v: Any?): List = (v as? List<*>)?.filterIsInstance() ?: emptyList() + + private fun stringMap(v: Any?): Map? = + (v as? Map<*, *>)?.entries?.filter { it.value is String }?.associate { it.key.toString() to it.value as String } + + private fun prices(v: Any?): Map = + (v as? Map<*, *>)?.entries?.filter { it.value is Number }?.associate { it.key.toString() to (it.value as Number).toDouble() } ?: emptyMap() + + private fun quote(o: Map<*, *>): Quote = Quote(intOrNull(o["character_count"]) ?: 0, prices(o["prices"])) + + private fun detected(o: Map<*, *>): List = (o["detected_languages"] as? List<*>)?.mapNotNull { item -> + val d = item as? Map<*, *> ?: return@mapNotNull null + val code = d["lang_code"] as? String ?: return@mapNotNull null + DetectedLanguage(code, (d["confidence"] as? Number)?.toDouble(), d["supports_translation"] == true) + } ?: emptyList() + + private fun fusedOrder(o: Map<*, *>): FusedOrder = FusedOrder( + textOrNull(o, "translation_id") ?: throw SupertextException(ErrorCode.INCOMPLETE_RESPONSE, detail = "no translation_id"), + o["briefing_applied"] == true, + text(o, "service_label"), + textOrNull(o, "request_id"), + ) + + private fun fusedStatus(o: Map<*, *>): FusedStatus = + FusedStatus(text(o, "status"), textOrNull(o, "detected_source_lang"), intOrNull(o["estimated_duration_left_in_seconds"]) ?: 0, textOrNull(o, "error")) + + private fun fusedQuote(o: Map<*, *>): FusedQuote = FusedQuote( + prices(o["prices"]), + intOrNull(o["estimated_duration_in_seconds"]) ?: 0, + intOrNull(o["word_count"]) ?: 0, + intOrNull(o["character_count"]), + o["briefing_applied"] == true, + text(o, "service_label"), + ) + + private fun webhook(o: Map<*, *>, withSecret: Boolean): Webhook = Webhook( + text(o, "id"), text(o, "url"), strings(o["event_types"]), textOrNull(o, "description"), text(o, "status"), textOrNull(o, "disabled_reason"), + text(o, "created_at"), textOrNull(o, "last_delivery_at"), textOrNull(o, "last_failure_at"), textOrNull(o, "last_failure_reason"), + intOrNull(o["consecutive_failures"]) ?: 0, if (withSecret) text(o, "secret") else null, + ) + + private fun download(response: HttpResponseData): DownloadedFile? = + if (response.status == 202) null else DownloadedFile(response.bodyBytes, fileNameFrom(response.header("Content-Disposition"))) +} diff --git a/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Types.kt b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Types.kt new file mode 100644 index 0000000..f375847 --- /dev/null +++ b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Types.kt @@ -0,0 +1,104 @@ +package com.supertext.sdk.v2 + +/** How inline markup in texts is handled. */ +public enum class TagHandling( + /** The API value. */ + public val value: String, +) { + /** Plain text. */ + NONE("none"), + + /** XML, parsed strictly. */ + XML("xml"), + + /** HTML, malformed markup tolerated. */ + HTML("html"), +} + +/** The answer of `POST translate/ai/text`: one translation per input text, same order. */ +public data class TextTranslation( + val translations: List, + val detectedSourceLang: String?, + /** Glossary terms applied; `null` when no glossary was sent. */ + val enforcedTerms: Map?, + val requestId: String?, +) + +/** What a request would cost; prices keyed by lower-case currency code, not rounded to the cent. */ +public data class Quote(val characterCount: Int, val prices: Map) + +/** Status of an AI file translation: `translating`, `done`, `error`, `deleted`. */ +public data class FileStatus(val status: String, val error: String?, val estimatedSecondsLeft: Int?, val detectedSourceLang: String?) + +/** A downloaded document; the file name comes from `Content-Disposition` when present. */ +public class DownloadedFile(content: ByteArray, public val fileName: String?) { + private val bytes = content.copyOf() + + /** The document. */ + public val content: ByteArray get() = bytes.copyOf() + + override fun equals(other: Any?): Boolean = other is DownloadedFile && bytes.contentEquals(other.bytes) && fileName == other.fileName + + override fun hashCode(): Int = 31 * bytes.contentHashCode() + (fileName?.hashCode() ?: 0) + + override fun toString(): String = "DownloadedFile(fileName=$fileName, ${bytes.size} bytes)" +} + +/** A language the detection found. */ +public data class DetectedLanguage(val langCode: String, val confidence: Double?, val supportsTranslation: Boolean) + +/** The workspace and key behind the API key. */ +public data class Account( + val workspaceId: String, + val workspaceName: String, + val apiKeyName: String, + val apiKeyPrefix: String, + val apiKeyExpiresAt: String, +) + +/** One language pair from `GET features` (`supports_politeness`, `supports_glossary`, `supports_fused_translation`). */ +public data class FeatureSupport(val sourceLang: String, val targetLang: String, val features: List) + +/** An accepted human-review order: [briefingApplied] Optimisation (true) or Verification; the label is for display. */ +public data class FusedOrder(val translationId: String, val briefingApplied: Boolean, val serviceLabel: String, val requestId: String?) + +/** Status of a human-review order: `in_progress`, `completed`, `failed`. Negative seconds: the promised time has passed. */ +public data class FusedStatus(val status: String, val detectedSourceLang: String?, val estimatedSecondsLeft: Int, val error: String?) + +/** What a human-review order would cost and how long it would take; [characterCount] for files only. */ +public data class FusedQuote( + val prices: Map, + val estimatedDurationSeconds: Int, + val wordCount: Int, + val characterCount: Int?, + val briefingApplied: Boolean, + val serviceLabel: String, +) + +/** A registered webhook. [secret] (`whsec_…`) only on the result of `createWebhook`, shown once. */ +public data class Webhook( + val id: String, + val url: String, + val eventTypes: List, + val description: String?, + val status: String, + val disabledReason: String?, + val createdAt: String, + val lastDeliveryAt: String?, + val lastFailureAt: String?, + val lastFailureReason: String?, + val consecutiveFailures: Int, + val secret: String? = null, +) { + /** Keeps the secret out of logs. */ + override fun toString(): String = "Webhook(id=$id, url=$url, status=$status)" +} + +/** The answer of a test event. */ +public data class WebhookTestResult(val delivered: Boolean, val statusCode: Int?, val error: String?, val durationMs: Int) + +/** A verified webhook event. [id] is the `webhook-id` header: de-duplicate on it. */ +public data class WebhookEvent(val id: String, val type: String, val timestamp: String, val data: Map) + +/** One request of `translateTexts`: kind `text`, `html` or `file`. */ +public data class PlannedRequest(val kind: String, val keys: List) diff --git a/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Webhooks.kt b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Webhooks.kt new file mode 100644 index 0000000..d6bd794 --- /dev/null +++ b/sdk/kotlin/src/main/kotlin/com/supertext/sdk/v2/Webhooks.kt @@ -0,0 +1,59 @@ +package com.supertext.sdk.v2 + +import com.supertext.sdk.v1.Json +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.time.Instant +import java.util.Base64 +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +/** Verifies webhook requests the Standard Webhooks way (spec/v2/webhooks.json). */ +public object Webhooks { + /** How far a webhook's timestamp may be from now, either way. */ + public const val TOLERANCE_SECONDS: Long = 300 + + private val DIGITS = Regex("[0-9]{1,18}") + + /** + * The verified event; throws [ErrorCode.INVALID_WEBHOOK] otherwise. Pass the raw body exactly as received, + * before any JSON parsing; header names in any case. + */ + @JvmStatic + @JvmOverloads + public fun verify(secret: String?, headers: Map, rawBody: String, now: Instant = Instant.now()): WebhookEvent { + val s = secret ?: "" + val encoded = if (s.startsWith("whsec_")) s.substring(6) else s + val key = try { + if (encoded.length % 4 == 0) Base64.getDecoder().decode(encoded) else ByteArray(0) + } catch (e: IllegalArgumentException) { + throw invalid() + } + if (key.isEmpty()) throw invalid() + fun header(name: String): String? = headers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value + val id = header("webhook-id") + val timestamp = header("webhook-timestamp") + val signatures = header("webhook-signature") + if (id.isNullOrEmpty() || timestamp == null || signatures == null || !DIGITS.matches(timestamp)) throw invalid() + if (kotlin.math.abs(now.epochSecond - timestamp.toLong()) > TOLERANCE_SECONDS) throw invalid() + val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) } + val expected = Base64.getEncoder().encode(mac.doFinal("$id.$timestamp.$rawBody".toByteArray(StandardCharsets.UTF_8))) + val matched = signatures.split(' ').any { entry -> + val comma = entry.indexOf(',') + comma > 0 && entry.substring(0, comma) == "v1" && + MessageDigest.isEqual(entry.substring(comma + 1).toByteArray(StandardCharsets.US_ASCII), expected) + } + if (!matched) throw invalid() + val event = try { + Json.parse(rawBody) as? Map<*, *> + } catch (e: IllegalArgumentException) { + null + } ?: throw invalid() + val type = event["type"] as? String ?: throw invalid() + val time = event["timestamp"] as? String ?: throw invalid() + val data = (event["data"] as? Map<*, *>)?.entries?.associate { it.key.toString() to it.value } ?: emptyMap() + return WebhookEvent(id, type, time, data) + } + + private fun invalid(): SupertextException = SupertextException(ErrorCode.INVALID_WEBHOOK) +} diff --git a/sdk/kotlin/src/test/kotlin/com/supertext/sdk/v2/V2Test.kt b/sdk/kotlin/src/test/kotlin/com/supertext/sdk/v2/V2Test.kt new file mode 100644 index 0000000..d08f219 --- /dev/null +++ b/sdk/kotlin/src/test/kotlin/com/supertext/sdk/v2/V2Test.kt @@ -0,0 +1,248 @@ +package com.supertext.sdk.v2 + +import com.supertext.sdk.HttpResponseData +import com.supertext.sdk.v1.FakeTransport +import com.supertext.sdk.v1.Politeness +import com.supertext.sdk.v1.RecordingSleeper +import com.supertext.sdk.v1.Segment +import com.supertext.sdk.v1.Spec +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DynamicTest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestFactory +import org.junit.jupiter.api.assertThrows +import java.io.IOException +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset + +/** API v2: the shared vectors in spec/v2/ and the client against a scripted transport. */ +class V2Test { + private val base = "https://api-platform.supertext.com/v1/" + + private fun spec(name: String) = Spec.load("v2/$name") + + private fun int(v: Any?): Int? = (v as Number?)?.toInt() + + private fun codeOf(run: () -> Unit): String = assertThrows { run() }.code.value + + private fun client(fake: FakeTransport, key: String) = + SupertextClient(key, transport = fake, sleeper = RecordingSleeper(), wallClock = Clock.fixed(Instant.parse("2026-11-01T00:00:00Z"), ZoneOffset.UTC)) + + private fun FakeTransport.calls() = requests.map { "${it.method} ${it.uri.toString().removePrefix(base)}" } + + private fun FakeTransport.body(i: Int) = FakeTransport.body(requests[i])!! + + @TestFactory + fun authHeader(): List = Spec.list(spec("auth-header.json"), "cases").map { c -> + DynamicTest.dynamicTest("key \"${c["apiKey"]}\"") { + val key = c["apiKey"] as String? + if (c.containsKey("error")) { + assertEquals(c["error"], codeOf { SupertextClient.authHeader(key) }) + } else { + assertEquals(c["header"], SupertextClient.authHeader(key)) + } + } + } + + @TestFactory + fun errors(): List = Spec.list(spec("errors.json"), "http").map { c -> + DynamicTest.dynamicTest("${c["status"]} ${c["code"]}") { + val e = SupertextException.forResponse(int(c["status"])!!, c["body"] as String) + assertEquals(c["code"], e.code.value) + assertEquals(int(c["status"]), e.status) + assertEquals(c["apiErrorCode"], e.apiErrorCode) + assertEquals(c["errorId"], e.errorId) + assertEquals(c["reason"], e.reason) + assertEquals(c["detail"], e.detail) + } + } + + @TestFactory + fun statusValues(): List = Spec.list(spec("errors.json"), "fileStatus").map { c -> + DynamicTest.dynamicTest("${c["kind"]} ${c["status"]}") { + val e = SupertextException.forStatusValue(c["kind"] as String, c["status"] as String, c["error"] as String?) + assertEquals(c["code"], e?.code?.value) + assertEquals(c["detail"], e?.detail) + } + } + + @TestFactory + fun batching(): List { + val s = spec("batching.json") + assertEquals(SupertextClient.DEFAULT_MAX_TEXT_CHARACTERS, int(s["defaultMaxCharacters"])) + return Spec.list(s, "cases").map { c -> + DynamicTest.dynamicTest(c["name"] as String) { + val segments = LinkedHashMap() + for (seg in Spec.list(c, "segments")) segments[seg["key"] as String] = Segment(seg["text"] as String, seg["html"] == true) + val plan = SupertextClient.planRequests(segments, int(c["maxCharacters"])!!).map { mapOf("kind" to it.kind, "keys" to it.keys) } + assertEquals(c["batches"], plan) + } + } + } + + @TestFactory + fun webhooks(): List = Spec.list(spec("webhooks.json"), "cases").map { c -> + DynamicTest.dynamicTest(c["name"] as String) { + val headers = Spec.strings(c["headers"])!! + val now = Instant.ofEpochSecond((c["now"] as Number).toLong()) + if (c.containsKey("error")) { + assertEquals(c["error"], codeOf { Webhooks.verify(c["secret"] as String?, headers, c["body"] as String, now) }) + } else { + val e = Webhooks.verify(c["secret"] as String?, headers, c["body"] as String, now) + assertEquals(c["event"], mapOf("id" to e.id, "type" to e.type, "timestamp" to e.timestamp, "data" to e.data)) + } + } + } + + @TestFactory + fun keyCheck(): List { + val s = spec("api-key-check.json") + for (c in Spec.list(s, "fingerprint")) assertEquals(c["fingerprint"], SupertextClient.fingerprint(c["apiKey"] as String?)) + return Spec.list(s, "apiKeyCheck").map { c -> + DynamicTest.dynamicTest(c["status"].toString()) { + val answer = Spec.obj(c["answer"]) + val fake = FakeTransport() + if (answer.containsKey("transportError")) fake.fail(IOException("down")) else fake.answer(int(answer["status"])!!, answer["body"] as String?) + val check = client(fake, "st_live_abc123").checkApiKey() + assertEquals(c["status"], check.status.value) + assertEquals(int(c["httpStatus"]), check.httpStatus) + assertEquals(c["errorCode"], check.errorCode) + assertEquals(SupertextClient.fingerprint("st_live_abc123"), check.fingerprint) + assertEquals(listOf("GET account"), fake.calls()) + } + } + } + + @Test + fun translateText() { + val fake = FakeTransport().answer(200, """{"request_id":"r1","detected_source_lang":"en","translated_text":["Hallo"],"enforced_terms":{"shop":"Laden"}}""") + val r = client(fake, " Bearer st_live_k ").translateText(listOf("Hello"), "de-CH", "en", Politeness.MORE, mapOf("shop" to "Laden"), TagHandling.HTML) + assertEquals(TextTranslation(listOf("Hallo"), "en", mapOf("shop" to "Laden"), "r1"), r) + assertEquals("Bearer st_live_k", fake.requests[0].headers["Authorization"]) + assertEquals("application/json", fake.requests[0].headers["Content-Type"]) + assertEquals("""{"text":["Hello"],"target_lang":"de-CH","source_lang":"en","politeness":"more","glossary":{"shop":"Laden"},"tag_handling":"html"}""", fake.body(0)) + val wrong = FakeTransport().answer(200, """{"translated_text":["x"]}""") + assertEquals("incomplete_response", codeOf { client(wrong, "k").translateText(listOf("a", "b"), "de-CH") }) + } + + @Test + fun retriesThenProblemAndNeverLeaksTheKey() { + val sleeper = RecordingSleeper() + val fake = FakeTransport().answer(429, """{"code":"rate_limited"}""", mapOf("Retry-After" to "2")) + .answer(402, """{"code":"payment_required","detail":"Top up.","error_id":"e1","reason":"insufficient_credit"}""") + val e = assertThrows { SupertextClient("k", transport = fake, sleeper = sleeper).translateText(listOf("a"), "de-CH") } + assertEquals(listOf("insufficient_credit", "insufficient_credit", "e1", "Top up."), listOf(e.code.value, e.reason, e.errorId, e.detail)) + assertEquals(listOf(2000L), sleeper.slept) + + val leak = FakeTransport().answer(401, "bad key st_live_secret123") + val e2 = assertThrows { client(leak, "st_live_secret123").getAccount() } + assertFalse(e2.message!!.contains("st_live_secret123")) + assertEquals("bad key ***", e2.detail) + assertFalse(client(leak, "st_live_secret123").toString().contains("st_live_secret123")) + } + + @Test + fun translateTextsUsesTextHtmlAndFile() { + val fake = FakeTransport() + .answer(200, """{"translated_text":["T:one"]}""") + .answer(200, """{"translated_text":["H:two"]}""") + .answer(202, """{"file_id":"f1"}""") + .answer(200, """{"status":"done"}""") + .answer(200, "
LONG
\n", mapOf("Content-Disposition" to "attachment; filename=\"c.html\"")) + .answer(200, """{"status":"deleted"}""") + val segments = linkedMapOf("a" to Segment.text("one"), "b" to Segment.html("two"), "c" to Segment.text(" "), "d" to Segment.text("long text here")) + val out = client(fake, "k").translateTexts(segments, "de-CH", maxCharacters = 10) + assertEquals(listOf("a", "b", "c", "d"), out.keys.toList()) + assertEquals(listOf("T:one", "H:two", " ", "LONG"), out.values.toList()) + assertEquals( + listOf("POST translate/ai/text", "POST translate/ai/text", "POST translate/ai/file", "GET translate/ai/file/f1/status", + "GET translate/ai/file/f1/translation", "DELETE translate/ai/file/f1"), + fake.calls(), + ) + assertFalse(fake.body(0).contains("tag_handling")) + assertTrue(fake.body(1).contains("\"tag_handling\":\"html\"")) + assertTrue(fake.body(2).contains("Content-Type: text/html\r\n")) + } + + @Test + fun failedFileDeletesAndBinaryDownloads() { + val fake = FakeTransport().answer(202, """{"file_id":"f1"}""").answer(200, """{"status":"translating"}""") + .answer(200, """{"status":"error","error":"Corrupt."}""").answer(200, "{}") + val e = assertThrows { + client(fake, "k").translateFile(byteArrayOf(1, 2), "a.docx", "fr-CH", glossary = mapOf("a" to "b"), useOcr = false) + } + assertEquals(listOf("translation_error", "Corrupt."), listOf(e.code.value, e.detail)) + assertEquals("DELETE", fake.requests[3].method) + assertTrue(fake.body(0).contains("wordprocessingml.document")) + assertTrue(fake.body(0).contains("name=\"glossary\"\r\n\r\n{\"a\":\"b\"}")) + assertTrue(fake.body(0).contains("name=\"use_ocr\"\r\n\r\nfalse")) + + val docx = byteArrayOf(80, 75, 3, 4, 0xff.toByte(), 0xfe.toByte(), 0) + val binary = FakeTransport().handler { HttpResponseData.ofBytes(200, mapOf("Content-Disposition" to "attachment; filename=\"a.fr-CH.docx\""), docx) } + val file = client(binary, "k").downloadFile("f1")!! + assertArrayEquals(docx, file.content) + assertEquals("a.fr-CH.docx", file.fileName) + } + + @Test + fun notReadyFusedFeaturesDetectionQuotes() { + val fake = FakeTransport() + .answer(202, """{"status":"in_progress"}""") + .answer(202, """{"status":"in_progress"}""") + .answer(200, """{"translated_text":"Geprüft"}""") + .answer(202, """{"translation_id":"u-1","briefing_applied":true,"service_label":"Optimisation","request_id":"r"}""") + .answer(200, """{"supported_features":[{"source_lang":"en","target_lang":"de-CH","features":["supports_politeness"]},{"bad":1}]}""") + .answer(200, """{"detected_languages":[{"lang_code":"en","confidence":0.9,"supports_translation":true}]}""") + .answer(200, """{"character_count":5,"prices":{"chf":0.0001,"bad":"x"}}""") + val c = client(fake, "k") + assertNull(c.downloadFile("x")) + assertNull(c.getFusedText("t")) + assertEquals("Geprüft", c.getFusedText("t")) + assertEquals(FusedOrder("u-1", true, "Optimisation", "r"), c.orderFusedText("Hello", "en", "de-CH", briefing = "Friendly", idempotencyKey = "idem-1")) + assertEquals("idem-1", fake.requests[3].headers["Idempotency-Key"]) + assertEquals("""{"text":"Hello","source_lang":"en","target_lang":"de-CH","briefing":"Friendly"}""", fake.body(3)) + assertEquals(listOf(FeatureSupport("en", "de-CH", listOf("supports_politeness"))), c.getFeatures("en", "de-CH")) + assertEquals(base + "features?source_lang=en&target_lang=de-CH", fake.requests[4].uri.toString()) + assertEquals(listOf(DetectedLanguage("en", 0.9, true)), c.detectLanguage("Hello")) + assertEquals(Quote(5, mapOf("chf" to 0.0001)), c.quoteText(listOf("Hello"), "de-CH")) + } + + @Test + fun webhookCrud() { + val hook = """{"id":"h1","url":"https://cms.example/hook","event_types":["translation.ai_file.completed"],"description":null,"status":"active",""" + + """"disabled_reason":null,"created_at":"2026","last_delivery_at":null,"last_failure_at":null,"last_failure_reason":null,"consecutive_failures":0""" + val fake = FakeTransport().answer(201, "$hook,\"secret\":\"whsec_abc\"}").answer(200, "{\"items\":[$hook}]}").answer(200, "$hook}") + .answer(204, "").answer(200, """{"delivered":true,"status_code":200,"error":null,"duration_ms":42}""") + val c = client(fake, "k") + val created = c.createWebhook("https://cms.example/hook", listOf("translation.ai_file.completed")) + assertEquals("whsec_abc", created.secret) + assertFalse(created.toString().contains("whsec_abc")) + assertEquals("""{"url":"https://cms.example/hook","event_types":["translation.ai_file.completed"]}""", fake.body(0)) + assertEquals(1, c.listWebhooks().size) + c.updateWebhook("h1", enabled = true, clearDescription = true) + assertEquals("""{"description":null,"enabled":true}""", fake.body(2)) + assertEquals("PATCH", fake.requests[2].method) + c.deleteWebhook("h1") + assertEquals(WebhookTestResult(true, 200, null, 42), c.testWebhook("h1")) + } + + @Test + fun nothingSentForBlankTargetOrKey() { + val fake = FakeTransport() + assertEquals("unsupported_language", codeOf { client(fake, "k").translateTexts(mapOf("a" to Segment.text("x")), " ") }) + assertEquals("missing_api_key", codeOf { client(fake, " ").getAccount() }) + assertTrue(fake.requests.isEmpty()) + } + + @Test + fun fileNameFrom() { + assertEquals("a b.docx", SupertextClient.fileNameFrom("attachment; filename=\"a b.docx\"")) + assertEquals("Zürich.docx", SupertextClient.fileNameFrom("attachment; filename=x.pdf; filename*=UTF-8''Z%C3%BCrich.docx")) + assertNull(SupertextClient.fileNameFrom(null)) + } +} diff --git a/sdk/php/README.md b/sdk/php/README.md index 0fdd1d7..7c552aa 100644 --- a/sdk/php/README.md +++ b/sdk/php/README.md @@ -16,7 +16,7 @@ You need an API key. No Supertext account yet? Create one at https://www.superte ## Quick start -Everything that talks to the API is in the namespace of its API version, `Supertext\Sdk\V1` (a later API version gets `Supertext\Sdk\V2` next to it, so integrations can move at their own pace). Only the HTTP transport (`Supertext\Sdk\Http`) and `Supertext\Sdk\Supertext::SDK_VERSION` are version-neutral. +Everything that talks to the API is in the namespace of its API version, `Supertext\Sdk\V1` (API v2 is in `Supertext\Sdk\V2` next to it, see [API v2](#api-v2), so integrations can move at their own pace). Only the HTTP transport (`Supertext\Sdk\Http`) and `Supertext\Sdk\Supertext::SDK_VERSION` are version-neutral. ```php use Supertext\Sdk\V1\Client; @@ -181,6 +181,32 @@ Every Supertext plugin checks its API key automatically (test vectors: `spec/api Version reports to the Supertext Commando Center and its ping endpoint are [Supertext Plugin Health](https://github.com/Supertext/Commando-Center-Supertext-Translation/tree/main/plugin-health), not this SDK. Its key checker is `fn ($key) => (new Client($key))->checkApiKey()` with `Protocol::apiKeyFingerprint` as the fingerprint, and its `sdkVersion` is `Supertext\Sdk\Supertext::SDK_VERSION`. +## API v2 + +Supertext's platform API (`https://api-platform.supertext.com/v1/`, `Authorization: Bearer st_live_…`) is in `Supertext\Sdk\V2`, next to v1. `translateTexts()` takes the same segments and returns the same keys; texts go in direct requests of up to 10,000 characters (HTML segments with `tag_handling` html), a longer segment through the file endpoint. No Supertext account yet? Create one at https://www.supertext.com/person/en/account/signin. Generate your API key at https://www.supertext.com/en/integrations/api (supertext.com → Integrations → API; requires the Admin role); API v2 takes the workspace keys (`st_live_…`) described in [Supertext's v2 documentation](https://www.supertext.com/en/neo/documentation/api). + +```php +use Supertext\Sdk\V1\Politeness; +use Supertext\Sdk\V1\Segment; +use Supertext\Sdk\V2\Client; +use Supertext\Sdk\V2\Webhooks; + +$client = new Client((string) getenv('SUPERTEXT_API_KEY')); +$german = $client->translateTexts( + ['title' => 'Hello & welcome', 'body' => Segment::html('

Our new shop opens on Monday.

')], + 'de-CH', + sourceLang: 'en', + politeness: Politeness::MORE, + glossary: ['shop' => 'Laden'], +); +$docx = $client->translateFile(file_get_contents('offer.docx'), 'offer.docx', 'fr-CH'); // ->content, ->filename + +// In your webhook endpoint: the raw body, before parsing it +$event = Webhooks::verify((string) getenv('SUPERTEXT_WEBHOOK_SECRET'), getallheaders(), file_get_contents('php://input')); +``` + +What else is there: `translateText` (one request, with the detected source language and enforced glossary terms) and `quoteText`; documents with `translateFile` (upload, wait, download, always delete) or the single steps `submitFile`, `getFileStatus`, `waitForFile`, `downloadFile` (`null` while not ready), `deleteFile`, and `quoteFile`; `detectLanguage`, `detectFileLanguage` and their quotes; human review with `quoteFusedText`/`orderFusedText`, `getFusedTextStatus`, `getFusedText` (and the same for files: `orderFusedFile`, `getFusedFileStatus`, `downloadFusedFile`); `getAccount`, `getFeatures`, `validateApiKey`, `checkApiKey` (same `ApiKeyCheck` as v1, on `GET account`); webhooks (`createWebhook`, whose secret is returned only once, `listWebhooks`, `getWebhook`, `updateWebhook`, `deleteWebhook`, `testWebhook`). Errors are one type with the codes of `spec/v2/errors.json` (`insufficient_credit`, `invalid_request`, `authentication_failure`, …) and Supertext's `detail`, `apiErrorCode`, `errorId` and `reason`. More: [integration guide → API v2](../../docs/integration-guide.md#16-api-v2-the-supertext-platform-api). + ## Translation files For translations made outside the API (a CAT tool, a translator, Supertext's web app), `Supertext\Sdk\Files\TranslationFiles` exports segments as an XLIFF 1.2 or HTML file and imports the translated file again (test vectors: `spec/translation-file.json`). It is not tied to an API version and never calls the API. diff --git a/sdk/php/examples/conformance-v2.php b/sdk/php/examples/conformance-v2.php new file mode 100644 index 0000000..9af8464 --- /dev/null +++ b/sdk/php/examples/conformance-v2.php @@ -0,0 +1,51 @@ +translateTexts( + $segments, + (string) $input['targetLang'], + isset($input['sourceLang']) ? (string) $input['sourceLang'] : null, + isset($input['politeness']) ? (string) $input['politeness'] : Politeness::DEFAULT, + maxCharacters: isset($input['maxCharacters']) ? (int) $input['maxCharacters'] : Protocol::DEFAULT_MAX_TEXT_CHARACTERS, + ); + $translations = new stdClass(); + foreach ($keys as $index => $key) { + $translations->{$key} = $translated[$index]; + } + $output = ['translations' => $translations]; +} catch (SupertextException $e) { + $output = ['error' => ['code' => $e->errorCode, 'status' => $e->status]]; +} + +echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), "\n"; diff --git a/sdk/php/src/V2/Account.php b/sdk/php/src/V2/Account.php new file mode 100644 index 0000000..73337c4 --- /dev/null +++ b/sdk/php/src/V2/Account.php @@ -0,0 +1,18 @@ +baseUrl = rtrim($baseUrl !== '' ? $baseUrl : Protocol::LIVE_BASE_URL, '/') . '/'; + $userAgent = $userAgent === null ? '' : trim($userAgent); + $this->userAgent = $userAgent === '' ? self::USER_AGENT : self::USER_AGENT . ' ' . $userAgent; + $this->transport = $transport ?? new CurlTransport(); + $this->sleep = $sleep ?? static function (float $seconds): void { + if ($seconds > 0) { + usleep((int) round($seconds * 1_000_000)); + } + }; + $this->clock = $clock ?? static fn (): float => hrtime(true) / 1e9; + $this->now = $now ?? static fn (): float => microtime(true); + } + + /** Keeps the key out of var_dump() and print_r(). */ + public function __debugInfo(): array + { + return ['baseUrl' => $this->baseUrl, 'userAgent' => $this->userAgent]; + } + + // ---- account and features + + /** The workspace and key behind the API key. Cost-free. */ + public function getAccount(): Account + { + $o = $this->json('GET', 'account'); + + return new Account(Json::text($o, 'workspace_id'), Json::text($o, 'workspace_name'), Json::text($o, 'api_key_name'), Json::text($o, 'api_key_prefix'), Json::text($o, 'api_key_expires_at')); + } + + /** + * The language pairs and their features, optionally filtered. Cost-free. + * + * @return list + */ + public function getFeatures(?string $sourceLang = null, ?string $targetLang = null): array + { + $query = http_build_query(array_filter(['source_lang' => $sourceLang, 'target_lang' => $targetLang], static fn ($v) => $v !== null && $v !== ''), '', '&', PHP_QUERY_RFC3986); + $list = $this->json('GET', $query === '' ? 'features' : 'features?' . $query)->supported_features ?? null; + $out = []; + foreach (\is_array($list) ? $list : [] as $item) { + $item = Json::object($item); + $source = $item->source_lang ?? null; + $target = $item->target_lang ?? null; + if (\is_string($source) && \is_string($target)) { + $out[] = new FeatureSupport($source, $target, Json::strings($item, 'features')); + } + } + + return $out; + } + + /** Throws unless the key is accepted (GET account). */ + public function validateApiKey(): void + { + $this->request('GET', 'account'); + } + + /** The automatic key check (spec/v2/api-key-check.json). Never throws. */ + public function checkApiKey(): ApiKeyCheck + { + $checkedAt = ApiKeyCheck::timestamp(($this->now)()); + $fingerprint = Protocol::apiKeyFingerprint($this->apiKey); + if ($fingerprint === '') { + return new ApiKeyCheck(ApiKeyCheck::MISSING, $checkedAt, null, null, ''); + } + try { + $response = $this->request('GET', 'account', timeout: min((float) ApiKeyCheck::TIMEOUT, $this->requestTimeout)); + + return new ApiKeyCheck(ApiKeyCheck::OK, $checkedAt, $response->status, null, $fingerprint); + } catch (\Throwable $e) { + return self::keyCheckFromError($e, $checkedAt, $fingerprint); + } + } + + /** The key check for a failed GET account. */ + public static function keyCheckFromError(\Throwable $error, string $checkedAt, string $fingerprint): ApiKeyCheck + { + if (!$error instanceof SupertextException) { + return new ApiKeyCheck(ApiKeyCheck::ERROR, $checkedAt, null, null, $fingerprint); + } + $status = match (true) { + $error->errorCode === SupertextException::MISSING_API_KEY => ApiKeyCheck::MISSING, + $error->status === 401, $error->status === 403 => ApiKeyCheck::INVALID, + $error->status === null, $error->status >= 500 => ApiKeyCheck::UNREACHABLE, + default => ApiKeyCheck::ERROR, + }; + + return new ApiKeyCheck($status, $checkedAt, $error->status, $error->apiErrorCode === null ? null : substr($error->apiErrorCode, 0, 100), $fingerprint); + } + + // ---- text + + /** + * One POST translate/ai/text: the translations in input order. Codes are sent as given. + * + * @param list $texts + * @param array|null $glossary source → target terms, at most 100 + * @param string $tagHandling none, xml or html + */ + public function translateText(array $texts, string $targetLang, ?string $sourceLang = null, string $politeness = Politeness::DEFAULT, ?array $glossary = null, string $tagHandling = 'none'): TextTranslation + { + $o = $this->json('POST', 'translate/ai/text', self::jsonBody(self::textPayload($texts, $targetLang, $sourceLang, $politeness, $glossary, $tagHandling)), 'application/json'); + $translations = Json::strings($o, 'translated_text'); + if (!\is_array($o->translated_text ?? null) || \count($translations) !== \count($texts)) { + throw new SupertextException(SupertextException::INCOMPLETE_RESPONSE, null, 'expected ' . \count($texts) . ' translations'); + } + + return new TextTranslation($translations, Json::textOrNull($o, 'detected_source_lang'), Json::stringMap($o, 'enforced_terms'), Json::textOrNull($o, 'request_id')); + } + + /** + * What translateText() would cost (a free dry run). + * + * @param list $texts + * @param array|null $glossary + */ + public function quoteText(array $texts, string $targetLang, ?string $sourceLang = null, string $politeness = Politeness::DEFAULT, ?array $glossary = null, string $tagHandling = 'none'): Quote + { + return self::quote($this->json('POST', 'translate/ai/text/quote', self::jsonBody(self::textPayload($texts, $targetLang, $sourceLang, $politeness, $glossary, $tagHandling)), 'application/json')); + } + + /** + * Translates texts by key (spec/v2/batching.json): the same keys in the same order, blanks unchanged. + * Up to 10,000 characters per request; a longer segment goes through an HTML file. + * + * @template K of array-key + * + * @param array $segments + * @param array|null $glossary + * + * @return array + */ + public function translateTexts(array $segments, string $targetLang, ?string $sourceLang = null, string $politeness = Politeness::DEFAULT, ?array $glossary = null, int $maxCharacters = Protocol::DEFAULT_MAX_TEXT_CHARACTERS): array + { + if (trim($targetLang, " \t\n\r\f") === '') { + throw new SupertextException(SupertextException::UNSUPPORTED_LANGUAGE); + } + $items = []; + $result = []; + foreach ($segments as $key => $segment) { + $items[$key] = $segment instanceof Segment ? $segment : Segment::text($segment); + $result[$key] = $items[$key]->text; + } + foreach (Protocol::planRequests($items, $maxCharacters) as [$kind, $keys]) { + $batch = array_map(static fn ($k) => $items[$k], $keys); + if ($kind === 'file') { + $parsed = HtmlDocument::parse($this->translateHtml(HtmlDocument::build($batch), $targetLang, $sourceLang, $politeness, $glossary), $batch); + $missing = []; + foreach ($parsed as $i => $text) { + if ($text === null) { + $missing[] = (string) $keys[$i]; + } else { + $result[$keys[$i]] = $text; + } + } + if ($missing !== []) { + throw new SupertextException(SupertextException::INCOMPLETE_RESPONSE, null, 'missing: ' . implode(', ', $missing)); + } + } else { + $out = $this->translateText(array_map(static fn (Segment $s) => $s->text, $batch), $targetLang, $sourceLang, $politeness, $glossary, $kind === 'html' ? 'html' : 'none'); + foreach ($keys as $i => $key) { + $result[$key] = $out->translations[$i]; + } + } + } + + return $result; + } + + // ---- AI file translation + + /** + * Uploads a document for AI translation; returns the file id. + * + * @param array|null $glossary + */ + public function submitFile(string $content, string $filename, string $targetLang, ?string $sourceLang = null, string $politeness = Politeness::DEFAULT, ?array $glossary = null, ?bool $useOcr = null): string + { + [$body, $type] = self::fileForm($content, $filename, $targetLang, $sourceLang, $politeness, $glossary, $useOcr); + $fileId = Json::textOrNull($this->json('POST', 'translate/ai/file', $body, $type), 'file_id'); + if ($fileId === null) { + throw new SupertextException(SupertextException::INCOMPLETE_RESPONSE, null, 'no file_id'); + } + + return $fileId; + } + + public function getFileStatus(string $fileId): FileStatus + { + $o = $this->json('GET', 'translate/ai/file/' . rawurlencode($fileId) . '/status'); + + return new FileStatus(Json::text($o, 'status'), Json::textOrNull($o, 'error'), Json::intOrNull($o, 'estimated_duration_left_in_seconds'), Json::textOrNull($o, 'detected_source_lang')); + } + + /** Polls until done; throws translation_error, file_deleted or timeout. */ + public function waitForFile(string $fileId): FileStatus + { + $start = ($this->clock)(); + while (true) { + $status = $this->getFileStatus($fileId); + if ($status->status === 'done') { + return $status; + } + $error = SupertextException::forStatusValue('file', $status->status, $status->error); + if ($error !== null) { + throw $error; + } + if (($this->clock)() - $start + $this->pollInterval > $this->timeout) { + throw new SupertextException(SupertextException::TIMEOUT); + } + ($this->sleep)($this->pollInterval); + } + } + + /** The translated document, or null while it isn't ready (HTTP 202). */ + public function downloadFile(string $fileId): ?DownloadedFile + { + return self::download($this->request('GET', 'translate/ai/file/' . rawurlencode($fileId) . '/translation')); + } + + /** Deletes the document and its translation. Never throws. */ + public function deleteFile(string $fileId): void + { + try { + $this->request('DELETE', 'translate/ai/file/' . rawurlencode($fileId)); + } catch (\Throwable) { + // Best effort: files expire after 24 hours anyway. + } + } + + /** + * Upload, wait, download, and always delete. + * + * @param array|null $glossary + */ + public function translateFile(string $content, string $filename, string $targetLang, ?string $sourceLang = null, string $politeness = Politeness::DEFAULT, ?array $glossary = null, ?bool $useOcr = null): DownloadedFile + { + $fileId = $this->submitFile($content, $filename, $targetLang, $sourceLang, $politeness, $glossary, $useOcr); + try { + $this->waitForFile($fileId); + $file = $this->downloadFile($fileId); + if ($file === null || $file->content === '') { + throw new SupertextException(SupertextException::INCOMPLETE_RESPONSE, null, 'empty document'); + } + + return $file; + } finally { + $this->deleteFile($fileId); + } + } + + /** + * One HTML document through the file endpoint (as content.html). + * + * @param array|null $glossary + */ + public function translateHtml(string $html, string $targetLang, ?string $sourceLang = null, string $politeness = Politeness::DEFAULT, ?array $glossary = null): string + { + return $this->translateFile($html, 'content.html', $targetLang, $sourceLang, $politeness, $glossary)->content; + } + + /** @param array|null $glossary */ + public function quoteFile(string $content, string $filename, string $targetLang, ?string $sourceLang = null, string $politeness = Politeness::DEFAULT, ?array $glossary = null, ?bool $useOcr = null): Quote + { + [$body, $type] = self::fileForm($content, $filename, $targetLang, $sourceLang, $politeness, $glossary, $useOcr); + + return self::quote($this->json('POST', 'translate/ai/file/quote', $body, $type)); + } + + // ---- language detection + + /** + * The language of a text (the first 500 characters are read). Empty when none was found. + * + * @return list + */ + public function detectLanguage(string $text): array + { + return self::detected($this->json('POST', 'detect-languages/text', self::jsonBody(['text' => $text]), 'application/json')); + } + + public function quoteDetection(string $text): Quote + { + return self::quote($this->json('POST', 'detect-languages/text/quote', self::jsonBody(['text' => $text]), 'application/json')); + } + + /** @return list */ + public function detectFileLanguage(string $content, string $filename): array + { + [$body, $type] = self::multipart([], $content, $filename); + + return self::detected($this->json('POST', 'detect-languages/file', $body, $type)); + } + + public function quoteFileDetection(string $content, string $filename): Quote + { + [$body, $type] = self::multipart([], $content, $filename); + + return self::quote($this->json('POST', 'detect-languages/file/quote', $body, $type)); + } + + // ---- human review ("fused") + + /** Orders a reviewed translation; the source language is required. Charged when accepted. */ + public function orderFusedText(string $text, string $sourceLang, string $targetLang, string $politeness = Politeness::DEFAULT, ?string $briefing = null, ?string $idempotencyKey = null): FusedOrder + { + $extra = $idempotencyKey !== null && $idempotencyKey !== '' ? ['Idempotency-Key' => $idempotencyKey] : []; + + return self::fusedOrder($this->json('POST', 'translate/fused/text', self::jsonBody(self::fusedPayload($text, $sourceLang, $targetLang, $politeness, $briefing)), 'application/json', $extra)); + } + + public function getFusedTextStatus(string $translationId): FusedStatus + { + return self::fusedStatus($this->json('GET', 'translate/fused/text/' . rawurlencode($translationId) . '/status')); + } + + /** The reviewed text, or null while it isn't delivered yet (HTTP 202). */ + public function getFusedText(string $translationId): ?string + { + $response = $this->request('GET', 'translate/fused/text/' . rawurlencode($translationId) . '/translation'); + if ($response->status === 202) { + return null; + } + $value = Json::parse($response->body)->translated_text ?? null; + if (!\is_string($value)) { + throw new SupertextException(SupertextException::INCOMPLETE_RESPONSE, null, 'no translated_text'); + } + + return $value; + } + + public function quoteFusedText(string $text, string $sourceLang, string $targetLang, string $politeness = Politeness::DEFAULT, ?string $briefing = null): FusedQuote + { + return self::fusedQuote($this->json('POST', 'translate/fused/text/quote', self::jsonBody(self::fusedPayload($text, $sourceLang, $targetLang, $politeness, $briefing)), 'application/json')); + } + + /** Orders a reviewed translation of a document (PDFs come back as DOCX). */ + public function orderFusedFile(string $content, string $filename, string $sourceLang, string $targetLang, string $politeness = Politeness::DEFAULT, ?string $briefing = null, ?bool $useOcr = null): FusedOrder + { + [$body, $type] = self::fusedForm($content, $filename, $sourceLang, $targetLang, $politeness, $briefing, $useOcr); + + return self::fusedOrder($this->json('POST', 'translate/fused/file', $body, $type)); + } + + public function getFusedFileStatus(string $translationId): FusedStatus + { + return self::fusedStatus($this->json('GET', 'translate/fused/file/' . rawurlencode($translationId) . '/status')); + } + + /** The reviewed document, or null until a reviewer delivers (HTTP 202). */ + public function downloadFusedFile(string $translationId): ?DownloadedFile + { + return self::download($this->request('GET', 'translate/fused/file/' . rawurlencode($translationId) . '/translation')); + } + + public function quoteFusedFile(string $content, string $filename, string $sourceLang, string $targetLang, string $politeness = Politeness::DEFAULT, ?string $briefing = null, ?bool $useOcr = null): FusedQuote + { + [$body, $type] = self::fusedForm($content, $filename, $sourceLang, $targetLang, $politeness, $briefing, $useOcr); + + return self::fusedQuote($this->json('POST', 'translate/fused/file/quote', $body, $type)); + } + + // ---- webhooks + + /** @return list */ + public function listWebhooks(): array + { + $items = $this->json('GET', 'webhooks')->items ?? null; + + return \is_array($items) ? array_values(array_map(static fn ($i) => self::webhook(Json::object($i)), $items)) : []; + } + + /** + * Registers a webhook; the result's secret is shown only once: store it. + * + * @param list $eventTypes + */ + public function createWebhook(string $url, array $eventTypes, ?string $description = null): Webhook + { + $body = ['url' => $url, 'event_types' => $eventTypes]; + if ($description !== null) { + $body['description'] = $description; + } + + return self::webhook($this->json('POST', 'webhooks', self::jsonBody($body), 'application/json'), true); + } + + public function getWebhook(string $webhookId): Webhook + { + return self::webhook($this->json('GET', 'webhooks/' . rawurlencode($webhookId))); + } + + /** + * Changes only the fields given. `clearDescription` sends description null. + * + * @param list|null $eventTypes + */ + public function updateWebhook(string $webhookId, ?string $url = null, ?array $eventTypes = null, ?string $description = null, ?bool $enabled = null, bool $clearDescription = false): Webhook + { + $body = []; + if ($url !== null) { + $body['url'] = $url; + } + if ($eventTypes !== null) { + $body['event_types'] = $eventTypes; + } + if ($description !== null || $clearDescription) { + $body['description'] = $description; + } + if ($enabled !== null) { + $body['enabled'] = $enabled; + } + + return self::webhook($this->json('PATCH', 'webhooks/' . rawurlencode($webhookId), self::jsonBody($body === [] ? new \stdClass() : $body), 'application/json')); + } + + public function deleteWebhook(string $webhookId): void + { + $this->request('DELETE', 'webhooks/' . rawurlencode($webhookId)); + } + + /** Sends a test event (at most one per 5 seconds). */ + public function testWebhook(string $webhookId): WebhookTestResult + { + $o = $this->json('POST', 'webhooks/' . rawurlencode($webhookId) . '/test'); + + return new WebhookTestResult(($o->delivered ?? null) === true, Json::intOrNull($o, 'status_code'), Json::textOrNull($o, 'error'), Json::intOrNull($o, 'duration_ms') ?? 0); + } + + // ---- HTTP + + /** @param array $extra */ + private function json(string $method, string $path, ?string $body = null, ?string $contentType = null, array $extra = []): \stdClass + { + return Json::parse($this->request($method, $path, $body, $contentType, null, $extra)->body); + } + + /** @param array $extra */ + private function request(string $method, string $path, ?string $body = null, ?string $contentType = null, ?float $timeout = null, array $extra = []): HttpResponse + { + $authorization = Protocol::authHeader($this->apiKey); + $key = substr($authorization, \strlen('Bearer ')); + $headers = $extra + [ + 'Authorization' => $authorization, + 'Accept' => 'application/json, application/problem+json', + 'User-Agent' => $this->userAgent, + ]; + if ($contentType !== null) { + $headers['Content-Type'] = $contentType; + } + $request = new HttpRequest($method, $this->baseUrl . $path, $headers, $body, $timeout ?? $this->requestTimeout); + for ($attempt = 0; ; $attempt++) { + try { + $response = $this->transport->send($request); + } catch (\Throwable $e) { + $message = trim($e->getMessage()); + $detail = str_replace($key, '***', $message); + throw new SupertextException(SupertextException::TRANSPORT_ERROR, null, $detail !== '' ? $detail : null, previous: $detail === $message ? $e : null); + } + if ($response->status !== 429 || $attempt >= $this->maxRetries) { + break; + } + ($this->sleep)(V1Protocol::retryDelayMs($attempt, $response->header('Retry-After')) / 1000); + } + if ($response->status >= 200 && $response->status < 300) { + return $response; + } + + throw SupertextException::forResponse($response->status, str_replace($key, '***', $response->body)); + } + + // ---- payloads + + private static function required(?string $code): string + { + $value = trim($code ?? '', " \t\n\r\f"); + if ($value === '') { + throw new SupertextException(SupertextException::UNSUPPORTED_LANGUAGE); + } + + return $value; + } + + /** + * @param list $texts + * @param array|null $glossary + * + * @return array + */ + private static function textPayload(array $texts, string $targetLang, ?string $sourceLang, string $politeness, ?array $glossary, string $tagHandling): array + { + $body = ['text' => $texts, 'target_lang' => self::required($targetLang)]; + $source = trim($sourceLang ?? '', " \t\n\r\f"); + if ($source !== '') { + $body['source_lang'] = $source; + } + if ($politeness === Politeness::MORE || $politeness === Politeness::LESS) { + $body['politeness'] = $politeness; + } + if ($glossary !== null && $glossary !== []) { + $body['glossary'] = (object) $glossary; + } + if ($tagHandling !== '' && $tagHandling !== 'none') { + $body['tag_handling'] = $tagHandling; + } + + return $body; + } + + /** + * @param array|null $glossary + * + * @return array{0: string, 1: string} + */ + private static function fileForm(string $content, string $filename, string $targetLang, ?string $sourceLang, string $politeness, ?array $glossary, ?bool $useOcr): array + { + $fields = ['target_lang' => self::required($targetLang)]; + $source = trim($sourceLang ?? '', " \t\n\r\f"); + if ($source !== '') { + $fields['source_lang'] = $source; + } + if ($politeness === Politeness::MORE || $politeness === Politeness::LESS) { + $fields['politeness'] = $politeness; + } + if ($glossary !== null && $glossary !== []) { + $fields['glossary'] = self::jsonBody((object) $glossary); + } + if ($useOcr !== null) { + $fields['use_ocr'] = $useOcr ? 'true' : 'false'; + } + + return self::multipart($fields, $content, $filename); + } + + /** @return array */ + private static function fusedPayload(string $text, string $sourceLang, string $targetLang, string $politeness, ?string $briefing): array + { + $body = ['text' => $text, 'source_lang' => self::required($sourceLang), 'target_lang' => self::required($targetLang)]; + if ($politeness === Politeness::MORE || $politeness === Politeness::LESS) { + $body['politeness'] = $politeness; + } + if ($briefing !== null && $briefing !== '') { + $body['briefing'] = $briefing; + } + + return $body; + } + + /** @return array{0: string, 1: string} */ + private static function fusedForm(string $content, string $filename, string $sourceLang, string $targetLang, string $politeness, ?string $briefing, ?bool $useOcr): array + { + $fields = ['target_lang' => self::required($targetLang), 'source_lang' => self::required($sourceLang)]; + if ($politeness === Politeness::MORE || $politeness === Politeness::LESS) { + $fields['politeness'] = $politeness; + } + if ($briefing !== null && $briefing !== '') { + $fields['briefing'] = $briefing; + } + if ($useOcr !== null) { + $fields['use_ocr'] = $useOcr ? 'true' : 'false'; + } + + return self::multipart($fields, $content, $filename); + } + + private static function jsonBody(mixed $value): string + { + return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); + } + + /** + * @param array $fields + * + * @return array{0: string, 1: string} + */ + private static function multipart(array $fields, string $content, string $filename): array + { + $boundary = '----supertext-' . bin2hex(random_bytes(12)); + $body = ''; + foreach ($fields as $name => $value) { + $body .= "--{$boundary}\r\nContent-Disposition: form-data; name=\"{$name}\"\r\n\r\n{$value}\r\n"; + } + $safe = (string) preg_replace('/["\r\n\\\\]/', '_', $filename); + $body .= "--{$boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{$safe}\"\r\n" + . 'Content-Type: ' . Protocol::contentTypeFor($filename) . "\r\n\r\n{$content}\r\n--{$boundary}--\r\n"; + + return [$body, 'multipart/form-data; boundary=' . $boundary]; + } + + // ---- answers + + private static function quote(\stdClass $o): Quote + { + return new Quote(Json::intOrNull($o, 'character_count') ?? 0, Json::prices($o)); + } + + /** @return list */ + private static function detected(\stdClass $o): array + { + $out = []; + foreach (\is_array($o->detected_languages ?? null) ? $o->detected_languages : [] as $item) { + $d = Json::object($item); + if (\is_string($d->lang_code ?? null)) { + $out[] = new DetectedLanguage($d->lang_code, Json::numberOrNull($d, 'confidence'), ($d->supports_translation ?? null) === true); + } + } + + return $out; + } + + private static function fusedOrder(\stdClass $o): FusedOrder + { + $id = Json::textOrNull($o, 'translation_id'); + if ($id === null) { + throw new SupertextException(SupertextException::INCOMPLETE_RESPONSE, null, 'no translation_id'); + } + + return new FusedOrder($id, ($o->briefing_applied ?? null) === true, Json::text($o, 'service_label'), Json::textOrNull($o, 'request_id')); + } + + private static function fusedStatus(\stdClass $o): FusedStatus + { + return new FusedStatus(Json::text($o, 'status'), Json::textOrNull($o, 'detected_source_lang'), Json::intOrNull($o, 'estimated_duration_left_in_seconds') ?? 0, Json::textOrNull($o, 'error')); + } + + private static function fusedQuote(\stdClass $o): FusedQuote + { + return new FusedQuote(Json::prices($o), Json::intOrNull($o, 'estimated_duration_in_seconds') ?? 0, Json::intOrNull($o, 'word_count') ?? 0, Json::intOrNull($o, 'character_count'), ($o->briefing_applied ?? null) === true, Json::text($o, 'service_label')); + } + + private static function webhook(\stdClass $o, bool $withSecret = false): Webhook + { + return new Webhook( + Json::text($o, 'id'), + Json::text($o, 'url'), + Json::strings($o, 'event_types'), + Json::textOrNull($o, 'description'), + Json::text($o, 'status'), + Json::textOrNull($o, 'disabled_reason'), + Json::text($o, 'created_at'), + Json::textOrNull($o, 'last_delivery_at'), + Json::textOrNull($o, 'last_failure_at'), + Json::textOrNull($o, 'last_failure_reason'), + Json::intOrNull($o, 'consecutive_failures') ?? 0, + $withSecret ? Json::text($o, 'secret') : null, + ); + } + + private static function download(HttpResponse $response): ?DownloadedFile + { + return $response->status === 202 ? null : new DownloadedFile($response->body, Protocol::filenameFrom($response->header('Content-Disposition'))); + } +} diff --git a/sdk/php/src/V2/DetectedLanguage.php b/sdk/php/src/V2/DetectedLanguage.php new file mode 100644 index 0000000..cf91c40 --- /dev/null +++ b/sdk/php/src/V2/DetectedLanguage.php @@ -0,0 +1,16 @@ + */ + public readonly array $features, + ) { + } +} diff --git a/sdk/php/src/V2/FileStatus.php b/sdk/php/src/V2/FileStatus.php new file mode 100644 index 0000000..946809f --- /dev/null +++ b/sdk/php/src/V2/FileStatus.php @@ -0,0 +1,17 @@ + */ + public readonly array $prices, + public readonly int $estimatedDurationSeconds, + public readonly int $wordCount, + public readonly ?int $characterCount, + public readonly bool $briefingApplied, + public readonly string $serviceLabel, + ) { + } +} diff --git a/sdk/php/src/V2/FusedStatus.php b/sdk/php/src/V2/FusedStatus.php new file mode 100644 index 0000000..4c196fb --- /dev/null +++ b/sdk/php/src/V2/FusedStatus.php @@ -0,0 +1,17 @@ +{$name} ?? null; + + return \is_string($v) ? $v : ''; + } + + public static function textOrNull(\stdClass $o, string $name): ?string + { + $v = $o->{$name} ?? null; + + return \is_string($v) && $v !== '' ? $v : null; + } + + public static function intOrNull(\stdClass $o, string $name): ?int + { + $v = $o->{$name} ?? null; + + return \is_int($v) ? $v : null; + } + + public static function numberOrNull(\stdClass $o, string $name): ?float + { + $v = $o->{$name} ?? null; + + return \is_int($v) || \is_float($v) ? (float) $v : null; + } + + /** @return list */ + public static function strings(\stdClass $o, string $name): array + { + $v = $o->{$name} ?? null; + + return \is_array($v) ? array_values(array_filter($v, '\is_string')) : []; + } + + /** @return array|null */ + public static function stringMap(\stdClass $o, string $name): ?array + { + $v = $o->{$name} ?? null; + if (!$v instanceof \stdClass) { + return null; + } + $out = []; + foreach ((array) $v as $key => $value) { + if (\is_string($value)) { + $out[(string) $key] = $value; + } + } + + return $out; + } + + /** @return array */ + public static function prices(\stdClass $o): array + { + $out = []; + foreach ((array) self::object($o->prices ?? null) as $key => $value) { + if (\is_int($value) || \is_float($value)) { + $out[(string) $key] = (float) $value; + } + } + + return $out; + } + + /** @return array */ + public static function toArray(\stdClass $o): array + { + $out = []; + foreach ((array) $o as $key => $value) { + $out[(string) $key] = $value instanceof \stdClass ? self::toArray($value) : (\is_array($value) ? self::listToArray($value) : $value); + } + + return $out; + } + + /** + * @param array $list + * + * @return array + */ + private static function listToArray(array $list): array + { + return array_map(static fn ($v) => $v instanceof \stdClass ? self::toArray($v) : (\is_array($v) ? self::listToArray($v) : $v), $list); + } +} diff --git a/sdk/php/src/V2/Protocol.php b/sdk/php/src/V2/Protocol.php new file mode 100644 index 0000000..3162332 --- /dev/null +++ b/sdk/php/src/V2/Protocol.php @@ -0,0 +1,157 @@ + 'text/html', + 'htm' => 'text/html', + 'txt' => 'text/plain', + 'srt' => 'application/x-subrip', + 'pdf' => 'application/pdf', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ]; + + private function __construct() + { + } + + /** + * `Bearer ` for a key as an administrator pasted it (spec/v2/auth-header.json). + * + * @throws SupertextException missing_api_key for a blank key + */ + public static function authHeader(#[\SensitiveParameter] string $apiKey): string + { + $key = trim((string) preg_replace('/^Bearer(?:[ \t\n\r\f]+|$)/i', '', trim($apiKey, " \t\n\r\f")), " \t\n\r\f"); + if ($key === '') { + throw new SupertextException(SupertextException::MISSING_API_KEY); + } + + return 'Bearer ' . $key; + } + + /** SHA-256 (lower-case hex) of the key as authHeader() sends it; '' for a blank key. */ + public static function apiKeyFingerprint(#[\SensitiveParameter] ?string $apiKey): string + { + try { + return hash('sha256', substr(self::authHeader($apiKey ?? ''), \strlen('Bearer '))); + } catch (SupertextException) { + return ''; + } + } + + /** + * Splits segments into requests (spec/v2/batching.json): a list of [kind, keys], kind 'text', + * 'html' or 'file'. Keys are the array keys of $segments. + * + * @template K of array-key + * + * @param array $segments + * + * @return list}> + */ + public static function planRequests(array $segments, int $maxCharacters = self::DEFAULT_MAX_TEXT_CHARACTERS): array + { + $plain = []; + $html = []; + $oversized = []; + foreach ($segments as $key => $segment) { + if ($segment->isBlank()) { + continue; + } + $length = Utf8::length($segment->text); + if ($length > $maxCharacters) { + $oversized[$key] = $segment; + } elseif ($segment->html) { + $html[$key] = $length; + } else { + $plain[$key] = $length; + } + } + $out = []; + foreach (self::split($plain, $maxCharacters) as $keys) { + $out[] = ['text', $keys]; + } + foreach (self::split($html, $maxCharacters) as $keys) { + $out[] = ['html', $keys]; + } + foreach (V1Client::batches($oversized) as $batch) { + $out[] = ['file', array_keys($batch)]; + } + + return $out; + } + + /** + * @template K of array-key + * + * @param array $lengths + * + * @return list> + */ + private static function split(array $lengths, int $maxCharacters): array + { + $out = []; + $current = []; + $size = 0; + foreach ($lengths as $key => $length) { + if ($current !== [] && $size + $length > $maxCharacters) { + $out[] = $current; + $current = []; + $size = 0; + } + $current[] = $key; + $size += $length; + } + if ($current !== []) { + $out[] = $current; + } + + return $out; + } + + /** The Content-Type for a file name's extension (the formats the API takes); else application/octet-stream. */ + public static function contentTypeFor(string $filename): string + { + $dot = strrpos($filename, '.'); + + return $dot === false ? 'application/octet-stream' : (self::TYPES[strtolower(substr($filename, $dot + 1))] ?? 'application/octet-stream'); + } + + /** The file name of a Content-Disposition header (filename*=UTF-8''… preferred). */ + public static function filenameFrom(?string $disposition): ?string + { + if ($disposition === null || $disposition === '') { + return null; + } + if (preg_match("/filename\\*\\s*=\\s*UTF-8''([^;]+)/i", $disposition, $m) === 1) { + $name = rawurldecode(trim($m[1])); + if (preg_match('//u', $name) === 1) { + return $name; + } + } + if (preg_match('/filename\s*=\s*(?:"([^"]*)"|([^;\s]+))/i', $disposition, $m) === 1) { + return ($m[2] ?? '') !== '' ? $m[2] : $m[1]; + } + + return null; + } +} diff --git a/sdk/php/src/V2/Quote.php b/sdk/php/src/V2/Quote.php new file mode 100644 index 0000000..ad94532 --- /dev/null +++ b/sdk/php/src/V2/Quote.php @@ -0,0 +1,16 @@ + keyed by lower-case currency code; not rounded to the cent */ + public readonly array $prices, + ) { + } +} diff --git a/sdk/php/src/V2/SupertextException.php b/sdk/php/src/V2/SupertextException.php new file mode 100644 index 0000000..6814e88 --- /dev/null +++ b/sdk/php/src/V2/SupertextException.php @@ -0,0 +1,122 @@ + 'No Supertext API key is configured.', + self::AUTHENTICATION_FAILURE => 'Supertext rejected the API key. Please check it.', + self::INSUFFICIENT_CREDIT => 'The Supertext credit balance does not cover this request. Please top up.', + self::INVALID_REQUEST => 'Supertext rejected the request.', + self::UNSUPPORTED_LANGUAGE => 'This language has no Supertext language code. Map it to a Supertext language.', + self::NOT_FOUND => 'Not found at Supertext (expired or already deleted).', + self::CONFLICT => 'Supertext refused the change.', + self::PAYLOAD_TOO_LARGE => 'The document is too large for Supertext.', + self::TOO_MANY_REQUESTS => 'Too many requests to Supertext. Please try again shortly.', + self::SERVICE_UNAVAILABLE => 'The Supertext service is unavailable.', + self::UNEXPECTED_STATUS => 'Supertext sent an unexpected HTTP status.', + self::TRANSPORT_ERROR => 'Could not reach Supertext.', + self::INCOMPLETE_RESPONSE => 'The Supertext answer is incomplete.', + self::TRANSLATION_ERROR => 'Supertext failed to translate.', + self::FILE_DELETED => 'The Supertext file was deleted before it could be downloaded.', + self::TIMEOUT => 'Timed out waiting for the Supertext translation to finish.', + self::INVALID_WEBHOOK => 'The webhook request is not a valid, signed Supertext event.', + ]; + + public function __construct( + public readonly string $errorCode, + public readonly ?int $status = null, + public readonly ?string $detail = null, + public readonly ?string $apiErrorCode = null, + public readonly ?string $errorId = null, + public readonly ?string $reason = null, + ?\Throwable $previous = null, + ) { + $message = self::MESSAGES[$errorCode] ?? 'Supertext request failed.'; + if ($status !== null) { + $message .= ' (HTTP ' . $status . ')'; + } + if ($detail !== null && $detail !== '') { + $message .= ' ' . $detail; + } + if ($errorId !== null) { + $message .= ' (error id ' . $errorId . ')'; + } + parent::__construct($message, $status ?? 0, $previous); + } + + /** Maps a non-2xx answer (problem+json) to an exception. */ + public static function forResponse(int $status, string $body): self + { + $data = json_decode($body); + $text = static function (string $name) use ($data): ?string { + $value = $data instanceof \stdClass ? ($data->{$name} ?? null) : null; + + return \is_string($value) && $value !== '' ? $value : null; + }; + $detail = self::cut($text('detail') ?? (string) preg_replace('/<[^>]*>/', '', $body)); + $code = match (true) { + $status === 401, $status === 403 => self::AUTHENTICATION_FAILURE, + $status === 402 => self::INSUFFICIENT_CREDIT, + $status === 404 => self::NOT_FOUND, + $status === 409 => self::CONFLICT, + $status === 413 => self::PAYLOAD_TOO_LARGE, + $status === 422 => self::INVALID_REQUEST, + $status === 429 => self::TOO_MANY_REQUESTS, + $status >= 500 && $status <= 599 => self::SERVICE_UNAVAILABLE, + default => self::UNEXPECTED_STATUS, + }; + + return new self($code, $status, $detail, $text('code'), $text('error_id'), $text('reason')); + } + + /** The error for a polled status, or null: AI file ("file") error/deleted, human review ("fused") failed. */ + public static function forStatusValue(string $kind, string $status, ?string $error = null): ?self + { + $detail = self::cut($error ?? ''); + + return match (true) { + $kind === 'file' && $status === 'error', $kind === 'fused' && $status === 'failed' => new self(self::TRANSLATION_ERROR, null, $detail), + $kind === 'file' && $status === 'deleted' => new self(self::FILE_DELETED), + default => null, + }; + } + + private static function cut(string $text): ?string + { + $text = trim($text, " \t\n\r\f"); + if ($text === '') { + return null; + } + $cut = preg_match('/^.{0,200}/su', $text, $m) === 1 ? $m[0] : substr($text, 0, 200); + + return $cut; + } +} diff --git a/sdk/php/src/V2/TextTranslation.php b/sdk/php/src/V2/TextTranslation.php new file mode 100644 index 0000000..007c657 --- /dev/null +++ b/sdk/php/src/V2/TextTranslation.php @@ -0,0 +1,19 @@ + one translation per input text, same order */ + public readonly array $translations, + public readonly ?string $detectedSourceLang, + /** @var array|null glossary terms applied; null when no glossary was sent */ + public readonly ?array $enforcedTerms, + public readonly ?string $requestId, + ) { + } +} diff --git a/sdk/php/src/V2/Webhook.php b/sdk/php/src/V2/Webhook.php new file mode 100644 index 0000000..baa48bf --- /dev/null +++ b/sdk/php/src/V2/Webhook.php @@ -0,0 +1,26 @@ + */ + public readonly array $eventTypes, + public readonly ?string $description, + public readonly string $status, + public readonly ?string $disabledReason, + public readonly string $createdAt, + public readonly ?string $lastDeliveryAt, + public readonly ?string $lastFailureAt, + public readonly ?string $lastFailureReason, + public readonly int $consecutiveFailures, + #[\SensitiveParameter] public readonly ?string $secret = null, + ) { + } +} diff --git a/sdk/php/src/V2/WebhookEvent.php b/sdk/php/src/V2/WebhookEvent.php new file mode 100644 index 0000000..017ca5e --- /dev/null +++ b/sdk/php/src/V2/WebhookEvent.php @@ -0,0 +1,18 @@ + */ + public readonly array $data, + ) { + } +} diff --git a/sdk/php/src/V2/WebhookTestResult.php b/sdk/php/src/V2/WebhookTestResult.php new file mode 100644 index 0000000..733d59a --- /dev/null +++ b/sdk/php/src/V2/WebhookTestResult.php @@ -0,0 +1,17 @@ +> $headers header names in any case + */ + public static function verify(#[\SensitiveParameter] string $secret, array $headers, string $rawBody, ?int $now = null): WebhookEvent + { + $encoded = str_starts_with($secret, 'whsec_') ? substr($secret, \strlen('whsec_')) : $secret; + $key = $encoded !== '' && \strlen($encoded) % 4 === 0 && preg_match('#^[A-Za-z0-9+/]*={0,2}$#', $encoded) === 1 + ? base64_decode($encoded, true) + : false; + if ($key === false || $key === '') { + throw self::invalid(); + } + $id = self::header($headers, 'webhook-id'); + $timestamp = self::header($headers, 'webhook-timestamp'); + $signatures = self::header($headers, 'webhook-signature'); + if ($id === null || $id === '' || $timestamp === null || $signatures === null || preg_match('/^[0-9]+$/', $timestamp) !== 1) { + throw self::invalid(); + } + if (abs(($now ?? time()) - (int) $timestamp) > self::TOLERANCE_SECONDS) { + throw self::invalid(); + } + $expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true)); + $matched = false; + foreach (explode(' ', $signatures) as $entry) { + $parts = explode(',', $entry, 2); + if (\count($parts) === 2 && $parts[0] === 'v1' && hash_equals($expected, $parts[1])) { + $matched = true; + } + } + if (!$matched) { + throw self::invalid(); + } + $event = json_decode($rawBody); + if (!$event instanceof \stdClass || !\is_string($event->type ?? null) || !\is_string($event->timestamp ?? null)) { + throw self::invalid(); + } + $data = $event->data ?? null; + + return new WebhookEvent($id, $event->type, $event->timestamp, $data instanceof \stdClass ? Json::toArray($data) : []); + } + + /** @param array> $headers */ + private static function header(array $headers, string $name): ?string + { + foreach ($headers as $key => $value) { + if (strcasecmp((string) $key, $name) === 0) { + return \is_array($value) ? ($value[0] ?? null) : $value; + } + } + + return null; + } + + private static function invalid(): SupertextException + { + return new SupertextException(SupertextException::INVALID_WEBHOOK); + } +} diff --git a/sdk/php/tests/V2Test.php b/sdk/php/tests/V2Test.php new file mode 100644 index 0000000..466201f --- /dev/null +++ b/sdk/php/tests/V2Test.php @@ -0,0 +1,288 @@ + */ + private static function spec(string $name): array + { + $json = file_get_contents(__DIR__ . '/../../../spec/v2/' . $name); + self::assertIsString($json); + $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + self::assertIsArray($data); + + return $data; + } + + /** @return iterable}> */ + private static function cases(string $file, string $key, string $label): iterable + { + foreach (self::spec($file)[$key] as $i => $case) { + yield $i . ' ' . substr(json_encode($case[$label], JSON_THROW_ON_ERROR), 0, 50) => [$case]; + } + } + + private static function codeOf(callable $fn): string + { + try { + $fn(); + } catch (SupertextException $e) { + return $e->errorCode; + } + self::fail('expected a SupertextException'); + } + + /** @return iterable}> */ + public static function authCases(): iterable + { + return self::cases('auth-header.json', 'cases', 'apiKey'); + } + + /** @param array $c */ + #[DataProvider('authCases')] + public function testAuthHeader(array $c): void + { + if (isset($c['error'])) { + self::assertSame($c['error'], self::codeOf(static fn () => Protocol::authHeader($c['apiKey']))); + } else { + self::assertSame($c['header'], Protocol::authHeader($c['apiKey'])); + } + } + + /** @return iterable}> */ + public static function errorCases(): iterable + { + return self::cases('errors.json', 'http', 'body'); + } + + /** @param array $c */ + #[DataProvider('errorCases')] + public function testErrors(array $c): void + { + $e = SupertextException::forResponse($c['status'], $c['body']); + self::assertSame([$c['code'], $c['status'], $c['apiErrorCode'], $c['errorId'], $c['reason'], $c['detail']], [$e->errorCode, $e->status, $e->apiErrorCode, $e->errorId, $e->reason, $e->detail]); + } + + /** @return iterable}> */ + public static function statusCases(): iterable + { + return self::cases('errors.json', 'fileStatus', 'status'); + } + + /** @param array $c */ + #[DataProvider('statusCases')] + public function testStatusValues(array $c): void + { + $e = SupertextException::forStatusValue($c['kind'], $c['status'], $c['error']); + self::assertSame([$c['code'], $c['detail']], [$e?->errorCode, $e?->detail]); + } + + /** @return iterable}> */ + public static function batchingCases(): iterable + { + return self::cases('batching.json', 'cases', 'name'); + } + + /** @param array $c */ + #[DataProvider('batchingCases')] + public function testBatching(array $c): void + { + $segments = []; + foreach ($c['segments'] as $s) { + $segments[$s['key']] = new Segment($s['text'], $s['html']); + } + $plan = array_map(static fn ($r) => ['kind' => $r[0], 'keys' => $r[1]], Protocol::planRequests($segments, $c['maxCharacters'])); + self::assertSame($c['batches'], $plan); + self::assertSame(self::spec('batching.json')['defaultMaxCharacters'], Protocol::DEFAULT_MAX_TEXT_CHARACTERS); + } + + /** @return iterable}> */ + public static function webhookCases(): iterable + { + return self::cases('webhooks.json', 'cases', 'name'); + } + + /** @param array $c */ + #[DataProvider('webhookCases')] + public function testWebhooks(array $c): void + { + if (isset($c['error'])) { + self::assertSame($c['error'], self::codeOf(static fn () => Webhooks::verify($c['secret'], $c['headers'], $c['body'], $c['now']))); + } else { + $e = Webhooks::verify($c['secret'], $c['headers'], $c['body'], $c['now']); + self::assertSame($c['event'], ['id' => $e->id, 'type' => $e->type, 'timestamp' => $e->timestamp, 'data' => $e->data]); + } + } + + public function testKeyCheck(): void + { + $s = self::spec('api-key-check.json'); + foreach ($s['fingerprint'] as $c) { + self::assertSame($c['fingerprint'], Protocol::apiKeyFingerprint($c['apiKey'])); + } + foreach ($s['apiKeyCheck'] as $c) { + $answer = $c['answer']; + $fake = FakeTransport::queue([isset($answer['transportError']) ? new \RuntimeException('down') : new HttpResponse($answer['status'], $answer['body'])]); + $check = (new Client('st_live_abc123', transport: $fake, now: static fn () => 1793491200.0))->checkApiKey(); + self::assertSame([$c['status'], $c['httpStatus'], $c['errorCode']], [$check->status, $check->httpStatus, $check->errorCode]); + self::assertSame(Protocol::apiKeyFingerprint('st_live_abc123'), $check->fingerprint); + self::assertSame(['GET account'], $fake->calls(self::BASE)); + } + } + + private static function js(mixed $value, int $status = 200, array $headers = []): HttpResponse + { + return new HttpResponse($status, json_encode($value, JSON_THROW_ON_ERROR), $headers); + } + + /** @return array */ + private static function body(HttpRequest $r): array + { + $data = json_decode((string) $r->body, true, 512, JSON_THROW_ON_ERROR); + self::assertIsArray($data); + + return $data; + } + + public function testTranslateText(): void + { + $fake = FakeTransport::queue([self::js(['request_id' => 'r1', 'detected_source_lang' => 'en', 'translated_text' => ['Hallo'], 'enforced_terms' => ['shop' => 'Laden']])]); + $out = (new Client(' Bearer st_live_k ', transport: $fake))->translateText(['Hello'], 'de-CH', 'en', 'more', ['shop' => 'Laden'], 'html'); + self::assertSame([['Hallo'], 'en', ['shop' => 'Laden'], 'r1'], [$out->translations, $out->detectedSourceLang, $out->enforcedTerms, $out->requestId]); + self::assertSame('Bearer st_live_k', $fake->requests[0]->headers['Authorization']); + self::assertSame(['text' => ['Hello'], 'target_lang' => 'de-CH', 'source_lang' => 'en', 'politeness' => 'more', 'glossary' => ['shop' => 'Laden'], 'tag_handling' => 'html'], self::body($fake->requests[0])); + self::assertSame('incomplete_response', self::codeOf(static fn () => (new Client('k', transport: FakeTransport::queue([self::js(['translated_text' => ['x']])])))->translateText(['a', 'b'], 'de-CH'))); + } + + public function testRetryThenProblemAndNoKey(): void + { + $waits = []; + $fake = FakeTransport::queue([self::js(['code' => 'rate_limited'], 429, ['Retry-After' => '2']), self::js(['code' => 'payment_required', 'detail' => 'Top up.', 'error_id' => 'e1', 'reason' => 'insufficient_credit'], 402)]); + try { + (new Client('k', transport: $fake, sleep: static function (float $s) use (&$waits): void { + $waits[] = $s; + }))->translateText(['a'], 'de-CH'); + self::fail('expected an exception'); + } catch (SupertextException $e) { + self::assertSame(['insufficient_credit', 'insufficient_credit', 'e1', 'Top up.'], [$e->errorCode, $e->reason, $e->errorId, $e->detail]); + } + self::assertSame([2.0], $waits); + + try { + (new Client('st_live_secret123', transport: FakeTransport::queue([new HttpResponse(401, 'bad key st_live_secret123')])))->getAccount(); + self::fail('expected an exception'); + } catch (SupertextException $e) { + self::assertStringNotContainsString('st_live_secret123', $e->getMessage()); + self::assertSame('bad key ***', $e->detail); + } + } + + public function testTranslateTexts(): void + { + $fake = FakeTransport::queue([ + new HttpResponse(200, '{"translated_text":["T:one"]}'), + new HttpResponse(200, '{"translated_text":["H:two"]}'), + self::js(['file_id' => 'f1'], 202), + self::js(['status' => 'done']), + new HttpResponse(200, "
LONG
\n", ['Content-Disposition' => 'attachment; filename="c.html"']), + self::js(['status' => 'deleted']), + ]); + $out = (new Client('k', transport: $fake, sleep: static fn (float $s) => null))->translateTexts(['a' => 'one', 'b' => Segment::html('two'), 'c' => ' ', 'd' => 'long text here'], 'de-CH', maxCharacters: 10); + self::assertSame(['a' => 'T:one', 'b' => 'H:two', 'c' => ' ', 'd' => 'LONG'], $out); + self::assertSame(['POST translate/ai/text', 'POST translate/ai/text', 'POST translate/ai/file', 'GET translate/ai/file/f1/status', 'GET translate/ai/file/f1/translation', 'DELETE translate/ai/file/f1'], $fake->calls(self::BASE)); + self::assertArrayNotHasKey('tag_handling', self::body($fake->requests[0])); + self::assertSame('html', self::body($fake->requests[1])['tag_handling']); + self::assertStringContainsString("Content-Type: text/html\r\n", (string) $fake->requests[2]->body); + } + + public function testFailedFileDeletes(): void + { + $fake = FakeTransport::queue([self::js(['file_id' => 'f1'], 202), self::js(['status' => 'translating']), self::js(['status' => 'error', 'error' => 'Corrupt.']), self::js([])]); + try { + (new Client('k', transport: $fake, sleep: static fn (float $s) => null))->translateFile("\x01\x02", 'a.docx', 'fr-CH', glossary: ['a' => 'b'], useOcr: false); + self::fail('expected an exception'); + } catch (SupertextException $e) { + self::assertSame(['translation_error', 'Corrupt.'], [$e->errorCode, $e->detail]); + } + self::assertSame('DELETE', $fake->requests[3]->method); + $upload = (string) $fake->requests[0]->body; + self::assertStringContainsString('wordprocessingml.document', $upload); + self::assertStringContainsString("name=\"glossary\"\r\n\r\n{\"a\":\"b\"}", $upload); + self::assertStringContainsString("name=\"use_ocr\"\r\n\r\nfalse", $upload); + } + + public function testNotReadyFusedAndExtras(): void + { + $fake = FakeTransport::queue([ + self::js(['status' => 'in_progress'], 202), + self::js(['status' => 'in_progress'], 202), + self::js(['translated_text' => 'Geprüft']), + self::js(['translation_id' => 'u-1', 'briefing_applied' => true, 'service_label' => 'Optimisation', 'request_id' => 'r'], 202), + self::js(['supported_features' => [['source_lang' => 'en', 'target_lang' => 'de-CH', 'features' => ['supports_politeness']], ['bad' => 1]]]), + self::js(['detected_languages' => [['lang_code' => 'en', 'confidence' => 0.9, 'supports_translation' => true]]]), + self::js(['character_count' => 5, 'prices' => ['chf' => 0.0001, 'bad' => 'x']]), + ]); + $c = new Client('k', transport: $fake); + self::assertNull($c->downloadFile('x')); + self::assertNull($c->getFusedText('t')); + self::assertSame('Geprüft', $c->getFusedText('t')); + $order = $c->orderFusedText('Hello', 'en', 'de-CH', briefing: 'Friendly', idempotencyKey: 'idem-1'); + self::assertSame(['u-1', true, 'Optimisation'], [$order->translationId, $order->briefingApplied, $order->serviceLabel]); + self::assertSame('idem-1', $fake->requests[3]->headers['Idempotency-Key']); + self::assertSame(['text' => 'Hello', 'source_lang' => 'en', 'target_lang' => 'de-CH', 'briefing' => 'Friendly'], self::body($fake->requests[3])); + self::assertEquals([new FeatureSupport('en', 'de-CH', ['supports_politeness'])], $c->getFeatures('en', 'de-CH')); + self::assertSame(self::BASE . 'features?source_lang=en&target_lang=de-CH', $fake->requests[4]->url); + self::assertEquals([new DetectedLanguage('en', 0.9, true)], $c->detectLanguage('Hello')); + $q = $c->quoteText(['Hello'], 'de-CH'); + self::assertSame([5, ['chf' => 0.0001]], [$q->characterCount, $q->prices]); + } + + public function testWebhookCrud(): void + { + $hook = ['id' => 'h1', 'url' => 'https://cms.example/hook', 'event_types' => ['translation.ai_file.completed'], 'description' => null, 'status' => 'active', 'disabled_reason' => null, 'created_at' => '2026', 'last_delivery_at' => null, 'last_failure_at' => null, 'last_failure_reason' => null, 'consecutive_failures' => 0]; + $fake = FakeTransport::queue([self::js($hook + ['secret' => 'whsec_abc'], 201), self::js(['items' => [$hook]]), self::js($hook), new HttpResponse(204), self::js(['delivered' => true, 'status_code' => 200, 'error' => null, 'duration_ms' => 42])]); + $c = new Client('k', transport: $fake); + self::assertSame('whsec_abc', $c->createWebhook($hook['url'], $hook['event_types'])->secret); + self::assertSame(['url' => $hook['url'], 'event_types' => $hook['event_types']], self::body($fake->requests[0])); + self::assertCount(1, $c->listWebhooks()); + $c->updateWebhook('h1', enabled: true, clearDescription: true); + self::assertSame(['description' => null, 'enabled' => true], self::body($fake->requests[2])); + self::assertSame('PATCH', $fake->requests[2]->method); + $c->deleteWebhook('h1'); + $t = $c->testWebhook('h1'); + self::assertSame([true, 200, null, 42], [$t->delivered, $t->statusCode, $t->error, $t->durationMs]); + } + + public function testNothingSent(): void + { + $never = FakeTransport::queue([]); + self::assertSame('unsupported_language', self::codeOf(static fn () => (new Client('k', transport: $never))->translateTexts(['a' => 'x'], ' '))); + self::assertSame('missing_api_key', self::codeOf(static fn () => (new Client(' ', transport: $never))->getAccount())); + self::assertSame([], $never->requests); + } + + public function testFilenameFrom(): void + { + self::assertSame('a b.docx', Protocol::filenameFrom('attachment; filename="a b.docx"')); + self::assertSame('Zürich.docx', Protocol::filenameFrom("attachment; filename=x.pdf; filename*=UTF-8''Z%C3%BCrich.docx")); + self::assertNull(Protocol::filenameFrom(null)); + } +} diff --git a/sdk/python/README.md b/sdk/python/README.md index 3a4c902..7d4a68e 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -15,7 +15,7 @@ pip install supertext-sdk from supertext import v1 # or: from supertext.v1 import SupertextClient ``` -Everything that talks to the API lives in `supertext.v1` (API v1). A later API version gets `supertext.v2` next to it, so an integration moves when it's ready. The top-level package holds only `v1` and `SDK_VERSION`. +Everything that talks to the API lives in `supertext.v1` (API v1). API v2 is in `supertext.v2` next to it (see [API v2](#api-v2)), so an integration moves when it's ready. The top-level package holds only `v1`, `v2` and `SDK_VERSION`. ## API key @@ -175,6 +175,31 @@ v1.SupertextClient( A blank key doesn't fail in the constructor, only on the first request. The transport (`supertext.transport`, re-exported from `supertext.v1`) is shared by all API versions. A custom `transport` raises `OSError` when there's no HTTP answer; the client turns that into `transport_error`. +## API v2 + +Supertext's platform API (`https://api-platform.supertext.com/v1/`, `Authorization: Bearer st_live_…`) is in `supertext.v2`, next to v1. `translate_texts` takes the same segments and returns the same keys; texts go in direct requests of up to 10,000 characters (HTML segments with `tag_handling="html"`), a longer segment through the file endpoint. No Supertext account yet? Create one at https://www.supertext.com/person/en/account/signin. Generate your API key at https://www.supertext.com/en/integrations/api (supertext.com → Integrations → API; requires the Admin role); API v2 takes the workspace keys (`st_live_…`) described in [Supertext's v2 documentation](https://www.supertext.com/en/neo/documentation/api). + +```python +import os +from supertext import v2 + +client = v2.SupertextClient(os.environ.get("SUPERTEXT_API_KEY")) +german = client.translate_texts( + {"title": "Hello & welcome", "body": v2.Segment("

Our new shop opens on Monday.

", html=True)}, + "de-CH", + source_lang="en", + politeness="more", + glossary={"shop": "Laden"}, +) +with open("offer.docx", "rb") as f: + docx = client.translate_file(f.read(), "offer.docx", "fr-CH") # .content, .filename + +# In your webhook endpoint: the raw body, before parsing it +event = v2.verify_webhook(os.environ["SUPERTEXT_WEBHOOK_SECRET"], request.headers, request.body) +``` + +What else is there: `translate_text` (one request, with the detected source language and enforced glossary terms) and `quote_text`; documents with `translate_file` (upload, wait, download, always delete) or the single steps `submit_file`, `get_file_status`, `wait_for_file`, `download_file` (`None` while not ready), `delete_file`, and `quote_file`; `detect_language`, `detect_file_language` and their quotes; human review with `quote_fused_text`/`order_fused_text`, `get_fused_text_status`, `get_fused_text` (and the same for files: `order_fused_file`, `get_fused_file_status`, `download_fused_file`); `get_account`, `get_features`, `validate_api_key`, `check_api_key` (same `ApiKeyCheck` as v1, on `GET account`); webhooks (`create_webhook`, whose secret is returned only once, `list_webhooks`, `get_webhook`, `update_webhook`, `delete_webhook`, `test_webhook`). Errors are one type with the codes of `spec/v2/errors.json` (`insufficient_credit`, `invalid_request`, `authentication_failure`, …) and Supertext's `detail`, `api_error_code`, `error_id` and `reason`. More: [integration guide → API v2](../../docs/integration-guide.md#16-api-v2-the-supertext-platform-api). + ## Translation files `supertext.files` exports segments as an XLIFF 1.2 or HTML file, to be translated outside the API (a CAT tool, a translator, Supertext's web app), and imports the translated file again (test vectors: `spec/translation-file.json`). It doesn't call the API, so it isn't versioned with it. diff --git a/sdk/python/examples/conformance_v2.py b/sdk/python/examples/conformance_v2.py new file mode 100644 index 0000000..1227e1a --- /dev/null +++ b/sdk/python/examples/conformance_v2.py @@ -0,0 +1,46 @@ +"""v2 conformance program for stand-in/conformance.mjs --v2 (see spec/v2/conformance.json). + +node stand-in/conformance.mjs --v2 -- python3 sdk/python/examples/conformance_v2.py +""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) + +from supertext import v2 + + +def main() -> int: + request = json.load(sys.stdin.buffer) + client = v2.SupertextClient( + os.environ.get("SUPERTEXT_API_KEY", ""), + base_url=os.environ.get("SUPERTEXT_API_URL") or v2.LIVE_BASE_URL, + poll_interval=0.1, + ) + segments = {s["key"]: v2.Segment(s["text"], bool(s.get("html", False))) for s in request["segments"]} + options: dict[str, object] = {} + if "maxCharacters" in request: + options["max_characters"] = request["maxCharacters"] + try: + translations = client.translate_texts( + segments, + request["targetLang"], + request.get("sourceLang"), + request.get("politeness") or "default", + **options, # type: ignore[arg-type] + ) + output: dict[str, object] = {"translations": translations} + except v2.SupertextError as error: + output = {"error": {"code": error.code, "status": error.status}} + json.dump(output, sys.stdout) + sys.stdout.write("\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/sdk/python/src/supertext/__init__.py b/sdk/python/src/supertext/__init__.py index f7bedc6..2e1c37a 100644 --- a/sdk/python/src/supertext/__init__.py +++ b/sdk/python/src/supertext/__init__.py @@ -1,16 +1,17 @@ """Supertext SDK. Everything that talks to the API is versioned with it: from supertext import v1 # or: from supertext.v1 import SupertextClient + from supertext import v2 # the platform API (api-platform.supertext.com) client = v1.SupertextClient(api_key) -A later API version gets ``supertext.v2`` next to ``v1``. The HTTP layer every version shares is + The HTTP layer every version shares is :mod:`supertext.transport` (also re-exported from ``supertext.v1``). """ -from . import v1 +from . import v1, v2 from .version import SDK_VERSION __version__ = SDK_VERSION -__all__ = ["SDK_VERSION", "__version__", "v1"] +__all__ = ["SDK_VERSION", "__version__", "v1", "v2"] diff --git a/sdk/python/src/supertext/v2/__init__.py b/sdk/python/src/supertext/v2/__init__.py new file mode 100644 index 0000000..0223bb3 --- /dev/null +++ b/sdk/python/src/supertext/v2/__init__.py @@ -0,0 +1,89 @@ +"""Supertext API v2: the Supertext platform API (https://api-platform.supertext.com/v1, workspace keys +sent as ``Bearer st_live_…``). Text translation in one request, AI file translation, language detection, +human review, quotes, the account and webhooks. Lives next to :mod:`supertext.v1` (the AI file +translation API), so integrations move at their own pace. + + from supertext import v2 + + client = v2.SupertextClient(api_key) + texts = client.translate_texts({"title": "Hello", "body": v2.Segment("

Hi

", html=True)}, "de-CH") + +Keys: workspace admins create them in the Supertext workspace under API keys. +""" + +from ..transport import HttpRequest, HttpResponse, Transport, UrllibTransport +from ..v1.api_key_check import KEY_CHECK_TIMEOUT, ApiKeyCheck, ApiKeyCheckStatus +from ..v1.html_document import HtmlDocument, Segment +from .client import ( + DEFAULT_MAX_TEXT_CHARACTERS, + LIVE_BASE_URL, + Account, + DetectedLanguage, + DownloadedFile, + FeatureSupport, + FileContent, + FileStatus, + FusedOrder, + FusedQuote, + FusedStatus, + PlannedRequest, + Politeness, + Quote, + SupertextClient, + TagHandling, + TextTranslation, + Webhook, + WebhookTestResult, + api_key_fingerprint, + auth_header, + content_type_for, + filename_from, + key_check_from_error, + plan_requests, +) +from .errors import ErrorCode, SupertextError, error_for_response, error_for_status_value +from .webhooks import WEBHOOK_TOLERANCE_SECONDS, WebhookEvent, verify_webhook + +__all__ = [ + "DEFAULT_MAX_TEXT_CHARACTERS", + "KEY_CHECK_TIMEOUT", + "LIVE_BASE_URL", + "WEBHOOK_TOLERANCE_SECONDS", + "Account", + "ApiKeyCheck", + "ApiKeyCheckStatus", + "DetectedLanguage", + "DownloadedFile", + "ErrorCode", + "FeatureSupport", + "FileContent", + "FileStatus", + "FusedOrder", + "FusedQuote", + "FusedStatus", + "HtmlDocument", + "HttpRequest", + "HttpResponse", + "PlannedRequest", + "Politeness", + "Quote", + "Segment", + "SupertextClient", + "SupertextError", + "TagHandling", + "TextTranslation", + "Transport", + "UrllibTransport", + "Webhook", + "WebhookEvent", + "WebhookTestResult", + "api_key_fingerprint", + "auth_header", + "content_type_for", + "error_for_response", + "error_for_status_value", + "filename_from", + "key_check_from_error", + "plan_requests", + "verify_webhook", +] diff --git a/sdk/python/src/supertext/v2/client.py b/sdk/python/src/supertext/v2/client.py new file mode 100644 index 0000000..33d5324 --- /dev/null +++ b/sdk/python/src/supertext/v2/client.py @@ -0,0 +1,949 @@ +"""Client for the Supertext API v2 (api-platform.supertext.com/v1, Bearer keys).""" + +from __future__ import annotations + +import contextlib +import json +import re +import time +import uuid +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any, Final, Literal +from urllib.parse import quote, unquote, urlencode + +from ..transport import HttpRequest, HttpResponse, Transport, UrllibTransport +from ..v1 import html_document +from ..v1.api_key_check import KEY_CHECK_TIMEOUT, ApiKeyCheck, ApiKeyCheckStatus, iso_seconds +from ..v1.api_key_check import api_key_fingerprint as v1_api_key_fingerprint +from ..v1.client import plan_batches, retry_delay_ms +from ..v1.html_document import Segment +from .errors import ErrorCode, SupertextError, error_for_response, error_for_status_value + +LIVE_BASE_URL: Final = "https://api-platform.supertext.com/v1/" + +DEFAULT_MAX_TEXT_CHARACTERS: Final = 10_000 +"""Characters per ``POST translate/ai/text``: the API's limit.""" + +Politeness = Literal["default", "more", "less"] +TagHandling = Literal["none", "xml", "html"] +FileContent = bytes | str + +_USER_AGENT: Final = "supertext-sdk-python" +_ASCII_SPACE: Final = " \t\n\r\f" +_BEARER = re.compile(r"^bearer(?:[ \t\n\r\f]+|$)", re.IGNORECASE) + + +def auth_header(api_key: str | None) -> str: + """The ``Authorization`` value for a pasted key (spec/v2/auth-header.json): ``Bearer ``.""" + key = _BEARER.sub("", (api_key or "").strip(_ASCII_SPACE)).strip(_ASCII_SPACE) + if not key: + raise SupertextError(ErrorCode.MISSING_API_KEY) + return f"Bearer {key}" + + +def api_key_fingerprint(api_key: str | None) -> str: + """SHA-256 (lower-case hex) of the key as :func:`auth_header` sends it; '' for a blank key.""" + try: + key = auth_header(api_key)[len("Bearer ") :] + except SupertextError: + return "" + # The same SHA-256 as v1's fingerprint: v1 strips exactly the prefix added here and hashes the key. + return v1_api_key_fingerprint("Supertext-Auth-Key " + key) + + +def key_check_from_error(error: BaseException, checked_at: str, fingerprint: str) -> ApiKeyCheck: + """The check for a failed ``GET account``.""" + if not isinstance(error, SupertextError): + return ApiKeyCheck("error", checked_at, None, None, fingerprint) + http_status = error.status + status: ApiKeyCheckStatus + if error.code == ErrorCode.MISSING_API_KEY: + status = "missing" + elif http_status in (401, 403): + status = "invalid" + elif http_status is None or http_status >= 500: + status = "unreachable" + else: + status = "error" + return ApiKeyCheck( + status, checked_at, http_status, error.api_error_code[:100] if error.api_error_code else None, fingerprint + ) + + +def _blank(text: str) -> bool: + return not text.strip(_ASCII_SPACE) + + +@dataclass(frozen=True) +class PlannedRequest: + """``text``: plain texts; ``html``: HTML (tag_handling html); ``file``: an HTML document for translate/ai/file.""" + + kind: Literal["text", "html", "file"] + keys: list[str] + + +def plan_requests( + segments: Mapping[str, Segment], max_characters: int = DEFAULT_MAX_TEXT_CHARACTERS +) -> list[PlannedRequest]: + """Splits segments into requests (spec/v2/batching.json).""" + plain: list[str] = [] + html: list[str] = [] + oversized: dict[str, Segment] = {} + for key, segment in segments.items(): + if _blank(segment.text): + continue + if len(segment.text) > max_characters: + oversized[key] = segment + else: + (html if segment.html else plain).append(key) + out: list[PlannedRequest] = [] + for kind, keys in (("text", plain), ("html", html)): + current: list[str] = [] + size = 0 + for key in keys: + length = len(segments[key].text) + if current and size + length > max_characters: + out.append(PlannedRequest(kind, current)) # type: ignore[arg-type] + current, size = [], 0 + current.append(key) + size += length + if current: + out.append(PlannedRequest(kind, current)) # type: ignore[arg-type] + out.extend(PlannedRequest("file", batch) for batch in plan_batches(oversized)) + return out + + +@dataclass(frozen=True) +class TextTranslation: + translations: list[str] + """One translation per input text, same order.""" + detected_source_lang: str | None = None + enforced_terms: dict[str, str] | None = None + """Glossary terms applied; ``None`` when no glossary was sent.""" + request_id: str | None = None + + +@dataclass(frozen=True) +class Quote: + character_count: int + prices: dict[str, float] + """Keyed by lower-case currency code; not rounded to the cent.""" + + +@dataclass(frozen=True) +class FileStatus: + status: str + """``translating``, ``done``, ``error``, ``deleted``.""" + error: str | None = None + estimated_seconds_left: int | None = None + detected_source_lang: str | None = None + + +@dataclass(frozen=True) +class DownloadedFile: + content: bytes + filename: str | None = None + """From ``Content-Disposition``, when present.""" + + +@dataclass(frozen=True) +class DetectedLanguage: + lang_code: str + confidence: float | None + supports_translation: bool + + +@dataclass(frozen=True) +class Account: + workspace_id: str + workspace_name: str + api_key_name: str + api_key_prefix: str + api_key_expires_at: str + + +@dataclass(frozen=True) +class FeatureSupport: + source_lang: str + target_lang: str + features: tuple[str, ...] + """``supports_politeness``, ``supports_glossary``, ``supports_fused_translation``.""" + + +@dataclass(frozen=True) +class FusedOrder: + translation_id: str + briefing_applied: bool + """True: Optimisation (with briefing); False: Verification.""" + service_label: str + request_id: str | None = None + + +@dataclass(frozen=True) +class FusedStatus: + status: str + """``in_progress``, ``completed``, ``failed``.""" + detected_source_lang: str | None + estimated_seconds_left: int + """Negative: the promised delivery time has passed.""" + error: str | None + + +@dataclass(frozen=True) +class FusedQuote: + prices: dict[str, float] + estimated_duration_seconds: int + word_count: int + character_count: int | None + """Files only.""" + briefing_applied: bool + service_label: str + + +@dataclass(frozen=True) +class Webhook: + id: str + url: str + event_types: tuple[str, ...] + description: str | None + status: str + disabled_reason: str | None + created_at: str + last_delivery_at: str | None + last_failure_at: str | None + last_failure_reason: str | None + consecutive_failures: int + secret: str | None = field(default=None, repr=False) + """Only on :meth:`SupertextClient.create_webhook`: the signing secret (``whsec_…``), shown once.""" + + +@dataclass(frozen=True) +class WebhookTestResult: + delivered: bool + status_code: int | None + error: str | None + duration_ms: int + + +_UNSET: Any = object() + +_TYPES: Final = { + "html": "text/html", + "htm": "text/html", + "txt": "text/plain", + "srt": "application/x-subrip", + "pdf": "application/pdf", + "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", +} + + +def content_type_for(filename: str) -> str: + """The Content-Type for a file name's extension; else ``application/octet-stream``.""" + _, dot, ext = filename.rpartition(".") + return _TYPES.get(ext.lower(), "application/octet-stream") if dot else "application/octet-stream" + + +def filename_from(disposition: str | None) -> str | None: + """The file name of a ``Content-Disposition`` header (``filename*=UTF-8''…`` preferred).""" + if not disposition: + return None + star = re.search(r"filename\*\s*=\s*UTF-8''([^;]+)", disposition, re.IGNORECASE) + if star: + with contextlib.suppress(UnicodeDecodeError): + return unquote(star.group(1).strip(), errors="strict") + plain = re.search(r'filename\s*=\s*(?:"([^"]*)"|([^;\s]+))', disposition, re.IGNORECASE) + return (plain.group(1) if plain.group(1) is not None else plain.group(2)) if plain else None + + +class SupertextClient: + """Client for the Supertext API v2. + + A blank API key doesn't fail here: the first request raises ``SupertextError(missing_api_key)`` + without sending anything. Times are in seconds. + """ + + def __init__( + self, + api_key: str | None, + *, + base_url: str = LIVE_BASE_URL, + poll_interval: float = 2.0, + timeout: float = 180.0, + request_timeout: float = 30.0, + max_retries: int = 4, + user_agent: str | None = None, + transport: Transport | None = None, + sleep: Callable[[float], None] = time.sleep, + clock: Callable[[], float] = time.monotonic, + now: Callable[[], float] = time.time, + ) -> None: + self._api_key = api_key or "" + self.base_url = (base_url or LIVE_BASE_URL).rstrip("/") + "/" + self.poll_interval = poll_interval + self.timeout = timeout + self.request_timeout = request_timeout + self.max_retries = max_retries + self.user_agent = f"{_USER_AGENT} {user_agent}" if user_agent else _USER_AGENT + self._transport: Transport = transport or UrllibTransport() + self._sleep = sleep + self._clock = clock + self._now = now + + def __repr__(self) -> str: + return f"SupertextClient(base_url={self.base_url!r})" + + # -- Account and features ---------------------------------------------------------------- + + def get_account(self) -> Account: + """The workspace and key behind the API key. Cost-free.""" + o = self._json("GET", "account") + return Account( + *( + _text(o.get(k)) + for k in ("workspace_id", "workspace_name", "api_key_name", "api_key_prefix", "api_key_expires_at") + ) + ) + + def get_features(self, source_lang: str | None = None, target_lang: str | None = None) -> list[FeatureSupport]: + """The language pairs and their features, optionally filtered. Cost-free.""" + query = {k: v for k, v in (("source_lang", source_lang), ("target_lang", target_lang)) if v} + items = self._json("GET", "features?" + urlencode(query) if query else "features").get("supported_features") + result = [] + for item in items if isinstance(items, list) else []: + entry = item if isinstance(item, dict) else {} + source, target = entry.get("source_lang"), entry.get("target_lang") + if isinstance(source, str) and isinstance(target, str): + result.append(FeatureSupport(source, target, tuple(_strings(entry.get("features"))))) + return result + + def validate_api_key(self) -> None: + """Raises :class:`SupertextError` unless the key is accepted (``GET account``).""" + self._request("GET", "account") + + def check_api_key(self) -> ApiKeyCheck: + """The automatic key check (spec/v2/api-key-check.json). Never raises.""" + checked_at = iso_seconds(self._now()) + fingerprint = api_key_fingerprint(self._api_key) + if not fingerprint: + return ApiKeyCheck("missing", checked_at, None, None, fingerprint) + try: + response = self._request("GET", "account", timeout=min(KEY_CHECK_TIMEOUT, self.request_timeout)) + except Exception as error: + return key_check_from_error(error, checked_at, fingerprint) + return ApiKeyCheck("ok", checked_at, response.status, None, fingerprint) + + # -- Text -------------------------------------------------------------------------------- + + def translate_text( + self, + texts: Sequence[str], + target_lang: str, + source_lang: str | None = None, + politeness: Politeness = "default", + glossary: Mapping[str, str] | None = None, + tag_handling: TagHandling = "none", + ) -> TextTranslation: + """One ``POST translate/ai/text``: the translations in input order. Codes are sent as given.""" + o = self._json( + "POST", + "translate/ai/text", + _json_body(_text_payload(texts, target_lang, source_lang, politeness, glossary, tag_handling)), + ) + raw = o.get("translated_text") + translations = _strings(raw) + if not isinstance(raw, list) or len(translations) != len(texts): + raise SupertextError(ErrorCode.INCOMPLETE_RESPONSE, detail=f"expected {len(texts)} translations") + return TextTranslation( + translations, + _text_or_none(o.get("detected_source_lang")), + _string_map(o.get("enforced_terms")), + _text_or_none(o.get("request_id")), + ) + + def quote_text( + self, + texts: Sequence[str], + target_lang: str, + source_lang: str | None = None, + politeness: Politeness = "default", + glossary: Mapping[str, str] | None = None, + tag_handling: TagHandling = "none", + ) -> Quote: + """What :meth:`translate_text` would cost (a free dry run).""" + return _quote( + self._json( + "POST", + "translate/ai/text/quote", + _json_body(_text_payload(texts, target_lang, source_lang, politeness, glossary, tag_handling)), + ) + ) + + def translate_texts( + self, + segments: Mapping[str, Segment | str], + target_lang: str, + source_lang: str | None = None, + politeness: Politeness = "default", + glossary: Mapping[str, str] | None = None, + max_characters: int = DEFAULT_MAX_TEXT_CHARACTERS, + ) -> dict[str, str]: + """Translates texts by key (spec/v2/batching.json); ``{key: translation}`` in input order, blanks unchanged.""" + if not (target_lang or "").strip(_ASCII_SPACE): + raise SupertextError(ErrorCode.UNSUPPORTED_LANGUAGE) + items = {key: value if isinstance(value, Segment) else Segment(value) for key, value in segments.items()} + result = {key: segment.text for key, segment in items.items()} + for planned in plan_requests(items, max_characters): + batch = [items[key] for key in planned.keys] + if planned.kind == "file": + translated = self.translate_html( + html_document.build(batch), target_lang, source_lang, politeness, glossary + ) + texts = html_document.parse(translated, batch) + missing = [key for key, text in zip(planned.keys, texts, strict=True) if text is None] + if missing: + raise SupertextError(ErrorCode.INCOMPLETE_RESPONSE, detail="missing: " + ", ".join(missing)) + result.update({key: text or "" for key, text in zip(planned.keys, texts, strict=True)}) + else: + out = self.translate_text( + [s.text for s in batch], + target_lang, + source_lang, + politeness, + glossary, + "html" if planned.kind == "html" else "none", + ) + result.update(zip(planned.keys, out.translations, strict=True)) + return result + + # -- AI file translation ------------------------------------------------------------------- + + def submit_file( + self, + content: FileContent, + filename: str, + target_lang: str, + source_lang: str | None = None, + politeness: Politeness = "default", + glossary: Mapping[str, str] | None = None, + use_ocr: bool | None = None, + ) -> str: + """Uploads a document for AI translation and returns its file id.""" + body = _file_form(content, filename, target_lang, source_lang, politeness, glossary, use_ocr) + file_id = _text_or_none(self._json("POST", "translate/ai/file", body).get("file_id")) + if file_id is None: + raise SupertextError(ErrorCode.INCOMPLETE_RESPONSE, detail="no file_id") + return file_id + + def get_file_status(self, file_id: str) -> FileStatus: + o = self._json("GET", f"translate/ai/file/{quote(file_id, safe='')}/status") + return FileStatus( + _text(o.get("status")), + _text_or_none(o.get("error")), + _int_or_none(o.get("estimated_duration_left_in_seconds")), + _text_or_none(o.get("detected_source_lang")), + ) + + def wait_for_file(self, file_id: str) -> FileStatus: + """Polls until ``done``; raises ``translation_error``, ``file_deleted`` or ``timeout``.""" + started = self._clock() + while True: + status = self.get_file_status(file_id) + if status.status == "done": + return status + failure = error_for_status_value("file", status.status, status.error) + if failure: + raise failure + if self._clock() + self.poll_interval - started > self.timeout: + raise SupertextError(ErrorCode.TIMEOUT) + self._sleep(self.poll_interval) + + def download_file(self, file_id: str) -> DownloadedFile | None: + """The translated document, or ``None`` while it isn't ready (HTTP 202).""" + return _download(self._request("GET", f"translate/ai/file/{quote(file_id, safe='')}/translation")) + + def delete_file(self, file_id: str) -> None: + """Deletes the document and its translation. Never raises.""" + with contextlib.suppress(Exception): + self._request("DELETE", f"translate/ai/file/{quote(file_id, safe='')}") + + def translate_file( + self, + content: FileContent, + filename: str, + target_lang: str, + source_lang: str | None = None, + politeness: Politeness = "default", + glossary: Mapping[str, str] | None = None, + use_ocr: bool | None = None, + ) -> DownloadedFile: + """Upload, wait, download, and always delete.""" + file_id = self.submit_file(content, filename, target_lang, source_lang, politeness, glossary, use_ocr) + try: + self.wait_for_file(file_id) + downloaded = self.download_file(file_id) + if downloaded is None or not downloaded.content: + raise SupertextError(ErrorCode.INCOMPLETE_RESPONSE, detail="empty document") + return downloaded + finally: + self.delete_file(file_id) + + def translate_html( + self, + html: str, + target_lang: str, + source_lang: str | None = None, + politeness: Politeness = "default", + glossary: Mapping[str, str] | None = None, + ) -> str: + """One HTML document through the file endpoint (as ``content.html``).""" + return self.translate_file(html, "content.html", target_lang, source_lang, politeness, glossary).content.decode( + "utf-8", errors="replace" + ) + + def quote_file( + self, + content: FileContent, + filename: str, + target_lang: str, + source_lang: str | None = None, + politeness: Politeness = "default", + glossary: Mapping[str, str] | None = None, + use_ocr: bool | None = None, + ) -> Quote: + return _quote( + self._json( + "POST", + "translate/ai/file/quote", + _file_form(content, filename, target_lang, source_lang, politeness, glossary, use_ocr), + ) + ) + + # -- Language detection -------------------------------------------------------------------- + + def detect_language(self, text: str) -> list[DetectedLanguage]: + """The language of a text (the first 500 characters are read). Empty when none was found.""" + return _detected(self._json("POST", "detect-languages/text", _json_body({"text": text}))) + + def quote_detection(self, text: str) -> Quote: + return _quote(self._json("POST", "detect-languages/text/quote", _json_body({"text": text}))) + + def detect_file_language(self, content: FileContent, filename: str) -> list[DetectedLanguage]: + return _detected(self._json("POST", "detect-languages/file", _multipart([], content, filename))) + + def quote_file_detection(self, content: FileContent, filename: str) -> Quote: + return _quote(self._json("POST", "detect-languages/file/quote", _multipart([], content, filename))) + + # -- Human review ("fused") ------------------------------------------------------------------ + + def order_fused_text( + self, + text: str, + source_lang: str, + target_lang: str, + politeness: Politeness = "default", + briefing: str | None = None, + idempotency_key: str | None = None, + ) -> FusedOrder: + """Orders a reviewed translation; the source language is required. Charged when accepted.""" + extra = {"Idempotency-Key": idempotency_key} if idempotency_key else {} + return _fused_order( + self._json( + "POST", + "translate/fused/text", + _json_body(_fused_payload(text, source_lang, target_lang, politeness, briefing)), + extra, + ) + ) + + def get_fused_text_status(self, translation_id: str) -> FusedStatus: + return _fused_status(self._json("GET", f"translate/fused/text/{quote(translation_id, safe='')}/status")) + + def get_fused_text(self, translation_id: str) -> str | None: + """The reviewed text, or ``None`` while it isn't delivered yet (HTTP 202).""" + response = self._request("GET", f"translate/fused/text/{quote(translation_id, safe='')}/translation") + if response.status == 202: + return None + value = _parse_object(response.text).get("translated_text") + if not isinstance(value, str): + raise SupertextError(ErrorCode.INCOMPLETE_RESPONSE, detail="no translated_text") + return value + + def quote_fused_text( + self, + text: str, + source_lang: str, + target_lang: str, + politeness: Politeness = "default", + briefing: str | None = None, + ) -> FusedQuote: + return _fused_quote( + self._json( + "POST", + "translate/fused/text/quote", + _json_body(_fused_payload(text, source_lang, target_lang, politeness, briefing)), + ) + ) + + def order_fused_file( + self, + content: FileContent, + filename: str, + source_lang: str, + target_lang: str, + politeness: Politeness = "default", + briefing: str | None = None, + use_ocr: bool | None = None, + ) -> FusedOrder: + """Orders a reviewed translation of a document (PDFs come back as DOCX).""" + return _fused_order( + self._json( + "POST", + "translate/fused/file", + _fused_form(content, filename, source_lang, target_lang, politeness, briefing, use_ocr), + ) + ) + + def get_fused_file_status(self, translation_id: str) -> FusedStatus: + return _fused_status(self._json("GET", f"translate/fused/file/{quote(translation_id, safe='')}/status")) + + def download_fused_file(self, translation_id: str) -> DownloadedFile | None: + """The reviewed document, or ``None`` until a reviewer delivers (HTTP 202).""" + return _download(self._request("GET", f"translate/fused/file/{quote(translation_id, safe='')}/translation")) + + def quote_fused_file( + self, + content: FileContent, + filename: str, + source_lang: str, + target_lang: str, + politeness: Politeness = "default", + briefing: str | None = None, + use_ocr: bool | None = None, + ) -> FusedQuote: + return _fused_quote( + self._json( + "POST", + "translate/fused/file/quote", + _fused_form(content, filename, source_lang, target_lang, politeness, briefing, use_ocr), + ) + ) + + # -- Webhooks ------------------------------------------------------------------------------ + + def list_webhooks(self) -> list[Webhook]: + items = self._json("GET", "webhooks").get("items") + return [_webhook(_object(i)) for i in items] if isinstance(items, list) else [] + + def create_webhook(self, url: str, event_types: Sequence[str], description: str | None = _UNSET) -> Webhook: + """Registers a webhook; the result's ``secret`` is shown only once: store it.""" + body: dict[str, Any] = {"url": url, "event_types": list(event_types)} + if description is not _UNSET: + body["description"] = description + return _webhook(self._json("POST", "webhooks", _json_body(body)), with_secret=True) + + def get_webhook(self, webhook_id: str) -> Webhook: + return _webhook(self._json("GET", f"webhooks/{quote(webhook_id, safe='')}")) + + def update_webhook( + self, + webhook_id: str, + *, + url: str | None = None, + event_types: Sequence[str] | None = None, + description: str | None = _UNSET, + enabled: bool | None = None, + ) -> Webhook: + """Changes only the fields given; ``description=None`` clears it, ``enabled=True`` switches it back on.""" + body: dict[str, Any] = {} + if url is not None: + body["url"] = url + if event_types is not None: + body["event_types"] = list(event_types) + if description is not _UNSET: + body["description"] = description + if enabled is not None: + body["enabled"] = enabled + return _webhook(self._json("PATCH", f"webhooks/{quote(webhook_id, safe='')}", _json_body(body))) + + def delete_webhook(self, webhook_id: str) -> None: + self._request("DELETE", f"webhooks/{quote(webhook_id, safe='')}") + + def test_webhook(self, webhook_id: str) -> WebhookTestResult: + """Sends a test event (at most one per 5 seconds).""" + o = self._json("POST", f"webhooks/{quote(webhook_id, safe='')}/test") + return WebhookTestResult( + o.get("delivered") is True, + _int_or_none(o.get("status_code")), + _text_or_none(o.get("error")), + _int_or_none(o.get("duration_ms")) or 0, + ) + + # -- HTTP ---------------------------------------------------------------------------------- + + def _json( + self, method: str, path: str, body: tuple[bytes, str] | None = None, extra: Mapping[str, str] | None = None + ) -> dict[str, Any]: + return _parse_object(self._request(method, path, body=body, extra=extra).text) + + def _request( + self, + method: str, + path: str, + *, + body: tuple[bytes, str] | None = None, + timeout: float | None = None, + extra: Mapping[str, str] | None = None, + ) -> HttpResponse: + authorization = auth_header(self._api_key) + key = authorization[len("Bearer ") :] + headers = { + **(extra or {}), + "Authorization": authorization, + "Accept": "application/json, application/problem+json", + "User-Agent": self.user_agent, + } + if body is not None: + headers["Content-Type"] = body[1] + request = HttpRequest( + method, + self.base_url + path, + headers, + body[0] if body else None, + self.request_timeout if timeout is None else timeout, + ) + attempt = 0 + while True: + try: + response = self._transport(request) + except OSError as error: + raise SupertextError( + ErrorCode.TRANSPORT_ERROR, detail=(str(error) or type(error).__name__).replace(key, "***") + ) from None + if response.status != 429 or attempt >= self.max_retries: + break + self._sleep(retry_delay_ms(attempt, response.header("Retry-After")) / 1000) + attempt += 1 + if 200 <= response.status < 300: + return response + raise error_for_response(response.status, response.text.replace(key, "***")) + + +# -- Payloads -------------------------------------------------------------------------------------- + + +def _required(code: str | None) -> str: + value = (code or "").strip(_ASCII_SPACE) + if not value: + raise SupertextError(ErrorCode.UNSUPPORTED_LANGUAGE) + return value + + +def _text_payload( + texts: Sequence[str], + target_lang: str, + source_lang: str | None, + politeness: str, + glossary: Mapping[str, str] | None, + tag_handling: str, +) -> dict[str, Any]: + body: dict[str, Any] = {"text": list(texts), "target_lang": _required(target_lang)} + source = (source_lang or "").strip(_ASCII_SPACE) + if source: + body["source_lang"] = source + if politeness in ("more", "less"): + body["politeness"] = politeness + if glossary: + body["glossary"] = dict(glossary) + if tag_handling and tag_handling != "none": + body["tag_handling"] = tag_handling + return body + + +def _file_form( + content: FileContent, + filename: str, + target_lang: str, + source_lang: str | None, + politeness: str, + glossary: Mapping[str, str] | None, + use_ocr: bool | None, +) -> tuple[bytes, str]: + fields = [("target_lang", _required(target_lang))] + source = (source_lang or "").strip(_ASCII_SPACE) + if source: + fields.append(("source_lang", source)) + if politeness in ("more", "less"): + fields.append(("politeness", politeness)) + if glossary: + fields.append(("glossary", json.dumps(dict(glossary), ensure_ascii=False, separators=(",", ":")))) + if use_ocr is not None: + fields.append(("use_ocr", "true" if use_ocr else "false")) + return _multipart(fields, content, filename) + + +def _fused_payload( + text: str, source_lang: str, target_lang: str, politeness: str, briefing: str | None +) -> dict[str, Any]: + body: dict[str, Any] = {"text": text, "source_lang": _required(source_lang), "target_lang": _required(target_lang)} + if politeness in ("more", "less"): + body["politeness"] = politeness + if briefing: + body["briefing"] = briefing + return body + + +def _fused_form( + content: FileContent, + filename: str, + source_lang: str, + target_lang: str, + politeness: str, + briefing: str | None, + use_ocr: bool | None, +) -> tuple[bytes, str]: + fields = [("target_lang", _required(target_lang)), ("source_lang", _required(source_lang))] + if politeness in ("more", "less"): + fields.append(("politeness", politeness)) + if briefing: + fields.append(("briefing", briefing)) + if use_ocr is not None: + fields.append(("use_ocr", "true" if use_ocr else "false")) + return _multipart(fields, content, filename) + + +def _json_body(value: object) -> tuple[bytes, str]: + return json.dumps(value, ensure_ascii=False).encode("utf-8"), "application/json" + + +def _multipart(fields: list[tuple[str, str]], content: FileContent, filename: str) -> tuple[bytes, str]: + boundary = "supertext-" + uuid.uuid4().hex + safe_name = re.sub(r'["\r\n\\]', "_", filename) + data = content.encode("utf-8") if isinstance(content, str) else bytes(content) + parts = [ + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode() + for name, value in fields + ] + parts.append( + f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{safe_name}"\r\n' + f"Content-Type: {content_type_for(filename)}\r\n\r\n".encode() + + data + + f"\r\n--{boundary}--\r\n".encode() + ) + return b"".join(parts), f"multipart/form-data; boundary={boundary}" + + +# -- Answers (fields only count with the documented types) ---------------------------------------- + + +def _parse_object(text: str) -> dict[str, Any]: + try: + data = json.loads(text) + except ValueError: + return {} + return data if isinstance(data, dict) else {} + + +def _object(value: object) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + +def _text(value: object) -> str: + return value if isinstance(value, str) else "" + + +def _text_or_none(value: object) -> str | None: + return value if isinstance(value, str) and value else None + + +def _int_or_none(value: object) -> int | None: + return value if isinstance(value, int) and not isinstance(value, bool) else None + + +def _number(value: object) -> float | None: + return float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None + + +def _strings(value: object) -> list[str]: + return [v for v in value if isinstance(v, str)] if isinstance(value, list) else [] + + +def _string_map(value: object) -> dict[str, str] | None: + return {k: v for k, v in value.items() if isinstance(v, str)} if isinstance(value, dict) else None + + +def _prices(value: object) -> dict[str, float]: + return {k: float(v) for k, v in _object(value).items() if _number(v) is not None} + + +def _quote(o: dict[str, Any]) -> Quote: + return Quote(_int_or_none(o.get("character_count")) or 0, _prices(o.get("prices"))) + + +def _detected(o: dict[str, Any]) -> list[DetectedLanguage]: + items = o.get("detected_languages") + out = [] + for item in items if isinstance(items, list) else []: + d = _object(item) + if isinstance(d.get("lang_code"), str): + out.append( + DetectedLanguage(d["lang_code"], _number(d.get("confidence")), d.get("supports_translation") is True) + ) + return out + + +def _fused_order(o: dict[str, Any]) -> FusedOrder: + translation_id = _text_or_none(o.get("translation_id")) + if translation_id is None: + raise SupertextError(ErrorCode.INCOMPLETE_RESPONSE, detail="no translation_id") + return FusedOrder( + translation_id, + o.get("briefing_applied") is True, + _text(o.get("service_label")), + _text_or_none(o.get("request_id")), + ) + + +def _fused_status(o: dict[str, Any]) -> FusedStatus: + return FusedStatus( + _text(o.get("status")), + _text_or_none(o.get("detected_source_lang")), + _int_or_none(o.get("estimated_duration_left_in_seconds")) or 0, + _text_or_none(o.get("error")), + ) + + +def _fused_quote(o: dict[str, Any]) -> FusedQuote: + return FusedQuote( + _prices(o.get("prices")), + _int_or_none(o.get("estimated_duration_in_seconds")) or 0, + _int_or_none(o.get("word_count")) or 0, + _int_or_none(o.get("character_count")), + o.get("briefing_applied") is True, + _text(o.get("service_label")), + ) + + +def _webhook(o: dict[str, Any], with_secret: bool = False) -> Webhook: + return Webhook( + id=_text(o.get("id")), + url=_text(o.get("url")), + event_types=tuple(_strings(o.get("event_types"))), + description=_text_or_none(o.get("description")), + status=_text(o.get("status")), + disabled_reason=_text_or_none(o.get("disabled_reason")), + created_at=_text(o.get("created_at")), + last_delivery_at=_text_or_none(o.get("last_delivery_at")), + last_failure_at=_text_or_none(o.get("last_failure_at")), + last_failure_reason=_text_or_none(o.get("last_failure_reason")), + consecutive_failures=_int_or_none(o.get("consecutive_failures")) or 0, + secret=_text(o.get("secret")) if with_secret else None, + ) + + +def _download(response: HttpResponse) -> DownloadedFile | None: + if response.status == 202: + return None + return DownloadedFile(response.body, filename_from(response.header("Content-Disposition"))) diff --git a/sdk/python/src/supertext/v2/errors.py b/sdk/python/src/supertext/v2/errors.py new file mode 100644 index 0000000..507db91 --- /dev/null +++ b/sdk/python/src/supertext/v2/errors.py @@ -0,0 +1,152 @@ +"""The one exception the v2 client raises, and its error codes (spec/v2/errors.json).""" + +from __future__ import annotations + +import contextlib +import json +import re +from typing import Final, Literal + +_ASCII_SPACE: Final = " \t\n\r\f" + + +class ErrorCode: + """The values of :attr:`SupertextError.code`. The strings are fixed and shared by all Supertext SDKs.""" + + MISSING_API_KEY: Final = "missing_api_key" + AUTHENTICATION_FAILURE: Final = "authentication_failure" + INSUFFICIENT_CREDIT: Final = "insufficient_credit" + INVALID_REQUEST: Final = "invalid_request" + UNSUPPORTED_LANGUAGE: Final = "unsupported_language" + NOT_FOUND: Final = "not_found" + CONFLICT: Final = "conflict" + PAYLOAD_TOO_LARGE: Final = "payload_too_large" + TOO_MANY_REQUESTS: Final = "too_many_requests" + SERVICE_UNAVAILABLE: Final = "service_unavailable" + UNEXPECTED_STATUS: Final = "unexpected_status" + TRANSPORT_ERROR: Final = "transport_error" + INCOMPLETE_RESPONSE: Final = "incomplete_response" + TRANSLATION_ERROR: Final = "translation_error" + FILE_DELETED: Final = "file_deleted" + TIMEOUT: Final = "timeout" + INVALID_WEBHOOK: Final = "invalid_webhook" + + +_MESSAGES: Final = { + ErrorCode.MISSING_API_KEY: "No Supertext API key is configured.", + ErrorCode.AUTHENTICATION_FAILURE: "Supertext rejected the API key. Please check it.", + ErrorCode.INSUFFICIENT_CREDIT: "The Supertext credit balance does not cover this request. Please top up.", + ErrorCode.INVALID_REQUEST: "Supertext rejected the request.", + ErrorCode.UNSUPPORTED_LANGUAGE: "This language has no Supertext language code. Map it to a Supertext language.", + ErrorCode.NOT_FOUND: "Not found at Supertext (expired or already deleted).", + ErrorCode.CONFLICT: "Supertext refused the change.", + ErrorCode.PAYLOAD_TOO_LARGE: "The document is too large for Supertext.", + ErrorCode.TOO_MANY_REQUESTS: "Too many requests to Supertext. Please try again shortly.", + ErrorCode.SERVICE_UNAVAILABLE: "The Supertext service is unavailable.", + ErrorCode.UNEXPECTED_STATUS: "Supertext sent an unexpected HTTP status.", + ErrorCode.TRANSPORT_ERROR: "Could not reach Supertext.", + ErrorCode.INCOMPLETE_RESPONSE: "The Supertext answer is incomplete.", + ErrorCode.TRANSLATION_ERROR: "Supertext failed to translate.", + ErrorCode.FILE_DELETED: "The Supertext file was deleted before it could be downloaded.", + ErrorCode.TIMEOUT: "Timed out waiting for the Supertext translation to finish.", + ErrorCode.INVALID_WEBHOOK: "The webhook request is not a valid, signed Supertext event.", +} + + +class SupertextError(Exception): + """Any failure of the v2 client. + + ``code`` is one of :class:`ErrorCode`. ``detail`` is the API's explanation (safe to show), + ``api_error_code`` the problem's ``code``, ``error_id`` its ``error_id`` (quote it to support), + ``reason`` its ``reason`` (e.g. ``insufficient_credit``). The API key never appears in any of these. + """ + + def __init__( + self, + code: str, + *, + status: int | None = None, + detail: str | None = None, + api_error_code: str | None = None, + error_id: str | None = None, + reason: str | None = None, + ) -> None: + self.code = code + self.message = _MESSAGES.get(code, "Supertext request failed.") + self.status = status + self.detail = detail + self.api_error_code = api_error_code + self.error_id = error_id + self.reason = reason + super().__init__(self.message) + + def __str__(self) -> str: + text = self.message + if self.status is not None: + text += f" (HTTP {self.status})" + if self.detail: + text += f" {self.detail}" + if self.error_id: + text += f" (error id {self.error_id})" + return text + + def __repr__(self) -> str: + return f"SupertextError(code={self.code!r}, status={self.status!r}, detail={self.detail!r})" + + +def _cut(text: str) -> str | None: + return text.strip(_ASCII_SPACE)[:200] or None + + +def error_for_response(status: int, body: str) -> SupertextError: + """Maps a non-2xx answer (problem+json) to a :class:`SupertextError`.""" + data: object = None + with contextlib.suppress(ValueError): + data = json.loads(body) if body.strip() else None + fields = data if isinstance(data, dict) else {} + + def text(name: str) -> str | None: + value = fields.get(name) + return value if isinstance(value, str) and value else None + + detail = _cut(text("detail") or re.sub(r"<[^>]*>", "", body)) + if status in (401, 403): + code = ErrorCode.AUTHENTICATION_FAILURE + elif status == 402: + code = ErrorCode.INSUFFICIENT_CREDIT + elif status == 404: + code = ErrorCode.NOT_FOUND + elif status == 409: + code = ErrorCode.CONFLICT + elif status == 413: + code = ErrorCode.PAYLOAD_TOO_LARGE + elif status == 422: + code = ErrorCode.INVALID_REQUEST + elif status == 429: + code = ErrorCode.TOO_MANY_REQUESTS + elif 500 <= status <= 599: + code = ErrorCode.SERVICE_UNAVAILABLE + else: + code = ErrorCode.UNEXPECTED_STATUS + return SupertextError( + code, + status=status, + detail=detail, + api_error_code=text("code"), + error_id=text("error_id"), + reason=text("reason"), + ) + + +def error_for_status_value( + kind: Literal["file", "fused"], status: str, error: str | None = None +) -> SupertextError | None: + """The error for a polled status, or ``None``: AI file ``error``/``deleted``, human review ``failed``.""" + detail = _cut(error or "") + if kind == "file" and status == "error": + return SupertextError(ErrorCode.TRANSLATION_ERROR, detail=detail) + if kind == "file" and status == "deleted": + return SupertextError(ErrorCode.FILE_DELETED) + if kind == "fused" and status == "failed": + return SupertextError(ErrorCode.TRANSLATION_ERROR, detail=detail) + return None diff --git a/sdk/python/src/supertext/v2/webhooks.py b/sdk/python/src/supertext/v2/webhooks.py new file mode 100644 index 0000000..cfb3805 --- /dev/null +++ b/sdk/python/src/supertext/v2/webhooks.py @@ -0,0 +1,90 @@ +"""Verifying webhook requests (Standard Webhooks; spec/v2/webhooks.json).""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import hmac +import json +import re +import time +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any, Final + +from .errors import ErrorCode, SupertextError + +WEBHOOK_TOLERANCE_SECONDS: Final = 300 +"""How far a webhook's timestamp may be from now, either way.""" + +_BASE64 = re.compile(r"[A-Za-z0-9+/]*={0,2}") + + +@dataclass(frozen=True) +class WebhookEvent: + """A verified event. ``id`` is the ``webhook-id`` header: de-duplicate on it (delivery is at least once).""" + + id: str + type: str + timestamp: str + data: dict[str, Any] = field(default_factory=dict) + + +def _invalid() -> SupertextError: + return SupertextError(ErrorCode.INVALID_WEBHOOK) + + +def _header(headers: Mapping[str, str], name: str) -> str | None: + for key, value in headers.items(): + if key.lower() == name: + return value + return None + + +def verify_webhook( + secret: str, headers: Mapping[str, str], raw_body: str | bytes, now: float | None = None +) -> WebhookEvent: + """Verifies a webhook request and returns its event; raises ``SupertextError(invalid_webhook)`` otherwise. + + Pass the raw body as received (bytes, or a str that is encoded as UTF-8), before any JSON parsing. + """ + encoded = (secret or "")[len("whsec_") :] if (secret or "").startswith("whsec_") else (secret or "") + if not encoded or len(encoded) % 4 or not _BASE64.fullmatch(encoded): + raise _invalid() + try: + key = base64.b64decode(encoded, validate=True) + except (binascii.Error, ValueError): + raise _invalid() from None + if not key: + raise _invalid() + webhook_id = _header(headers, "webhook-id") + timestamp = _header(headers, "webhook-timestamp") + signatures = _header(headers, "webhook-signature") + if not webhook_id or not timestamp or not signatures or not timestamp.isascii() or not timestamp.isdigit(): + raise _invalid() + current = time.time() if now is None else now + if abs(current - int(timestamp)) > WEBHOOK_TOLERANCE_SECONDS: + raise _invalid() + body = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8") + signed = webhook_id.encode("utf-8") + b"." + timestamp.encode("ascii") + b"." + body + expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode("ascii") + matched = False + for entry in signatures.split(" "): + version, _, signature = entry.partition(",") + if version == "v1" and signature and hmac.compare_digest(signature.encode(), expected.encode()): + matched = True + if not matched: + raise _invalid() + try: + data = json.loads(body.decode("utf-8")) + except (ValueError, UnicodeDecodeError): + raise _invalid() from None + if ( + not isinstance(data, dict) + or not isinstance(data.get("type"), str) + or not isinstance(data.get("timestamp"), str) + ): + raise _invalid() + payload = data.get("data") + return WebhookEvent(webhook_id, data["type"], data["timestamp"], payload if isinstance(payload, dict) else {}) diff --git a/sdk/python/tests/test_v2.py b/sdk/python/tests/test_v2.py new file mode 100644 index 0000000..01f323f --- /dev/null +++ b/sdk/python/tests/test_v2.py @@ -0,0 +1,338 @@ +"""API v2: the shared vectors in spec/v2/ and the client against a scripted transport.""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from typing import Any + +import pytest +from conftest import spec as _spec + +from supertext import v2 +from supertext.v2 import HttpRequest, HttpResponse, SupertextClient, SupertextError + + +def spec(name: str) -> Any: + return _spec("v2/" + name) + + +def code_of(fn: Callable[[], object]) -> str: + with pytest.raises(SupertextError) as info: + fn() + return info.value.code + + +@pytest.mark.parametrize("case", spec("auth-header.json")["cases"], ids=lambda c: repr(c["apiKey"])) +def test_auth_header(case: dict[str, Any]) -> None: + if "error" in case: + assert code_of(lambda: v2.auth_header(case["apiKey"])) == case["error"] + else: + assert v2.auth_header(case["apiKey"]) == case["header"] + + +@pytest.mark.parametrize("case", spec("errors.json")["http"], ids=lambda c: f"{c['status']}") +def test_errors(case: dict[str, Any]) -> None: + e = v2.error_for_response(case["status"], case["body"]) + assert (e.code, e.status, e.api_error_code, e.error_id, e.reason, e.detail) == ( + case["code"], + case["status"], + case["apiErrorCode"], + case["errorId"], + case["reason"], + case["detail"], + ) + + +@pytest.mark.parametrize("case", spec("errors.json")["fileStatus"], ids=lambda c: f"{c['kind']}-{c['status']}") +def test_status_values(case: dict[str, Any]) -> None: + e = v2.error_for_status_value(case["kind"], case["status"], case["error"]) + assert (e.code if e else None, e.detail if e else None) == (case["code"], case["detail"]) + + +def test_batching_default() -> None: + assert spec("batching.json")["defaultMaxCharacters"] == v2.DEFAULT_MAX_TEXT_CHARACTERS + + +@pytest.mark.parametrize("case", spec("batching.json")["cases"], ids=lambda c: c["name"]) +def test_batching(case: dict[str, Any]) -> None: + segments = {s["key"]: v2.Segment(s["text"], s["html"]) for s in case["segments"]} + plan = [{"kind": r.kind, "keys": r.keys} for r in v2.plan_requests(segments, case["maxCharacters"])] + assert plan == case["batches"] + + +@pytest.mark.parametrize("case", spec("webhooks.json")["cases"], ids=lambda c: c["name"]) +def test_webhooks(case: dict[str, Any]) -> None: + if "error" in case: + assert ( + code_of(lambda: v2.verify_webhook(case["secret"], case["headers"], case["body"], case["now"])) + == case["error"] + ) + else: + event = v2.verify_webhook(case["secret"], case["headers"], case["body"], case["now"]) + assert {"id": event.id, "type": event.type, "timestamp": event.timestamp, "data": event.data} == case["event"] + assert v2.verify_webhook(case["secret"], case["headers"], case["body"].encode(), case["now"]) == event + + +@pytest.mark.parametrize("case", spec("api-key-check.json")["fingerprint"], ids=lambda c: repr(c["apiKey"])) +def test_fingerprint(case: dict[str, Any]) -> None: + assert v2.api_key_fingerprint(case["apiKey"]) == case["fingerprint"] + + +@pytest.mark.parametrize("case", spec("api-key-check.json")["apiKeyCheck"], ids=lambda c: json.dumps(c["answer"])[:40]) +def test_key_check(case: dict[str, Any]) -> None: + urls: list[str] = [] + + def transport(request: HttpRequest) -> HttpResponse: + urls.append(request.url) + if case["answer"].get("transportError"): + raise OSError("down") + return HttpResponse(case["answer"]["status"], case["answer"]["body"].encode()) + + check = SupertextClient("st_live_abc123", transport=transport, now=lambda: 1793491200).check_api_key() + assert (check.status, check.http_status, check.error_code) == ( + case["status"], + case["httpStatus"], + case["errorCode"], + ) + assert check.fingerprint == v2.api_key_fingerprint("st_live_abc123") + assert urls == ["https://api-platform.supertext.com/v1/account"] + + +class Script: + def __init__(self, *answers: HttpResponse | Callable[[HttpRequest], HttpResponse]) -> None: + self.answers = list(answers) + self.requests: list[HttpRequest] = [] + + def __call__(self, request: HttpRequest) -> HttpResponse: + self.requests.append(request) + answer = self.answers.pop(0) + return answer(request) if callable(answer) else answer + + def paths(self) -> list[str]: + return [f"{r.method} {r.url.removeprefix(v2.LIVE_BASE_URL)}" for r in self.requests] + + +def js(value: object, status: int = 200, headers: dict[str, str] | None = None) -> HttpResponse: + return HttpResponse(status, json.dumps(value).encode(), {k.lower(): v for k, v in (headers or {}).items()}) + + +def body(request: HttpRequest) -> Any: + return json.loads(request.body or b"") + + +def test_translate_text() -> None: + t = Script( + js( + { + "request_id": "r1", + "detected_source_lang": "en", + "translated_text": ["Hallo"], + "enforced_terms": {"shop": "Laden"}, + } + ) + ) + out = SupertextClient(" Bearer st_live_k ", transport=t).translate_text( + ["Hello"], "de-CH", "en", "more", {"shop": "Laden"}, "html" + ) + assert out == v2.TextTranslation(["Hallo"], "en", {"shop": "Laden"}, "r1") + assert t.requests[0].headers["Authorization"] == "Bearer st_live_k" + assert body(t.requests[0]) == { + "text": ["Hello"], + "target_lang": "de-CH", + "source_lang": "en", + "politeness": "more", + "glossary": {"shop": "Laden"}, + "tag_handling": "html", + } + + +def test_wrong_count_is_incomplete() -> None: + t = Script(js({"translated_text": ["one"]})) + assert ( + code_of(lambda: SupertextClient("k", transport=t).translate_text(["a", "b"], "de-CH")) == "incomplete_response" + ) + + +def test_retry_then_problem() -> None: + waits: list[float] = [] + t = Script( + js({"code": "rate_limited"}, 429, {"Retry-After": "2"}), + js({"code": "payment_required", "detail": "Top up.", "error_id": "e1", "reason": "insufficient_credit"}, 402), + ) + with pytest.raises(SupertextError) as info: + SupertextClient("k", transport=t, sleep=waits.append).translate_text(["a"], "de-CH") + assert (info.value.code, info.value.reason, info.value.error_id, info.value.detail) == ( + "insufficient_credit", + "insufficient_credit", + "e1", + "Top up.", + ) + assert waits == [2.0] + + +def test_key_never_in_messages() -> None: + t = Script(HttpResponse(401, b"bad key st_live_secret123")) + with pytest.raises(SupertextError) as info: + SupertextClient("st_live_secret123", transport=t).get_account() + assert "st_live_secret123" not in str(info.value) and info.value.detail == "bad key ***" + assert "st_live_secret123" not in repr(SupertextClient("st_live_secret123")) + + +def test_translate_texts_text_html_and_file() -> None: + t = Script( + lambda r: js({"translated_text": [f"T:{x}" for x in body(r)["text"]]}), + lambda r: js({"translated_text": [f"H:{x}" for x in body(r)["text"]]}), + js({"file_id": "f1"}, 202), + js({"status": "done"}), + HttpResponse( + 200, b'
LONG
\n', {"content-disposition": 'attachment; filename="c.html"'} + ), + js({"status": "deleted"}), + ) + out = SupertextClient("k", transport=t, sleep=lambda s: None).translate_texts( + {"a": "one", "b": v2.Segment("two", True), "c": " ", "d": "long text here"}, "de-CH", max_characters=10 + ) + assert out == {"a": "T:one", "b": "H:two", "c": " ", "d": "LONG"} + assert t.paths() == [ + "POST translate/ai/text", + "POST translate/ai/text", + "POST translate/ai/file", + "GET translate/ai/file/f1/status", + "GET translate/ai/file/f1/translation", + "DELETE translate/ai/file/f1", + ] + assert "tag_handling" not in body(t.requests[0]) and body(t.requests[1])["tag_handling"] == "html" + assert b"Content-Type: text/html\r\n" in (t.requests[2].body or b"") + + +def test_failed_file_deletes() -> None: + t = Script( + js({"file_id": "f1"}, 202), js({"status": "translating"}), js({"status": "error", "error": "Corrupt."}), js({}) + ) + with pytest.raises(SupertextError) as info: + SupertextClient("k", transport=t, sleep=lambda s: None).translate_file( + b"\x01\x02", "a.docx", "fr-CH", glossary={"a": "b"}, use_ocr=False + ) + assert (info.value.code, info.value.detail) == ("translation_error", "Corrupt.") + assert t.requests[-1].method == "DELETE" + upload = t.requests[0].body or b"" + assert ( + b"wordprocessingml.document" in upload + and b'name="glossary"\r\n\r\n{"a":"b"}' in upload + and b'name="use_ocr"\r\n\r\nfalse' in upload + ) + + +def test_not_ready_is_none() -> None: + t = Script( + js({"status": "in_progress"}, 202), js({"status": "in_progress"}, 202), js({"translated_text": "Geprüft"}) + ) + client = SupertextClient("k", transport=t) + assert ( + client.download_file("x") is None + and client.get_fused_text("t") is None + and client.get_fused_text("t") == "Geprüft" + ) + + +def test_fused_order() -> None: + t = Script( + js({"translation_id": "u-1", "briefing_applied": True, "service_label": "Optimisation", "request_id": "r"}, 202) + ) + order = SupertextClient("k", transport=t).order_fused_text( + "Hello", "en", "de-CH", briefing="Friendly", idempotency_key="idem-1" + ) + assert order == v2.FusedOrder("u-1", True, "Optimisation", "r") + assert t.requests[0].headers["Idempotency-Key"] == "idem-1" + assert body(t.requests[0]) == {"text": "Hello", "source_lang": "en", "target_lang": "de-CH", "briefing": "Friendly"} + + +def test_account_features_detection_quotes() -> None: + t = Script( + js( + { + "workspace_id": "w", + "workspace_name": "W", + "api_key_name": "CMS", + "api_key_prefix": "st", + "api_key_expires_at": "2027", + } + ), + js( + { + "supported_features": [ + {"source_lang": "en", "target_lang": "de-CH", "features": ["supports_politeness"]}, + {"bad": 1}, + ] + } + ), + js({"detected_languages": [{"lang_code": "en", "confidence": 0.9, "supports_translation": True}]}), + js({"character_count": 5, "prices": {"chf": 0.0001, "bad": "x"}}), + js( + { + "prices": {"chf": 12.5}, + "estimated_duration_in_seconds": 3600, + "word_count": 10, + "briefing_applied": False, + "service_label": "Verification", + } + ), + ) + c = SupertextClient("k", transport=t) + assert c.get_account().workspace_name == "W" + assert c.get_features("en", "de-CH") == [v2.FeatureSupport("en", "de-CH", ("supports_politeness",))] + assert t.requests[1].url.endswith("features?source_lang=en&target_lang=de-CH") + assert c.detect_language("Hello") == [v2.DetectedLanguage("en", 0.9, True)] + assert c.quote_text(["Hello"], "de-CH") == v2.Quote(5, {"chf": 0.0001}) + q = c.quote_fused_text("Hello", "en", "de-CH") + assert (q.prices, q.word_count, q.character_count, q.briefing_applied) == ({"chf": 12.5}, 10, None, False) + + +def test_webhooks_crud() -> None: + hook: dict[str, Any] = { + "id": "h1", + "url": "https://cms.example/hook", + "event_types": ["translation.ai_file.completed"], + "description": None, + "status": "active", + "disabled_reason": None, + "created_at": "2026", + "last_delivery_at": None, + "last_failure_at": None, + "last_failure_reason": None, + "consecutive_failures": 0, + } + t = Script( + js({**hook, "secret": "whsec_abc"}, 201), + js({"items": [hook]}), + js(hook), + HttpResponse(204), + js({"delivered": True, "status_code": 200, "error": None, "duration_ms": 42}), + ) + c = SupertextClient("k", transport=t) + created = c.create_webhook(hook["url"], hook["event_types"]) + assert created.secret == "whsec_abc" and "whsec_abc" not in repr(created) + assert body(t.requests[0]) == {"url": hook["url"], "event_types": hook["event_types"]} + assert len(c.list_webhooks()) == 1 and c.list_webhooks is not None + c.update_webhook("h1", enabled=True, description=None) + assert body(t.requests[2]) == {"description": None, "enabled": True} and t.requests[2].method == "PATCH" + c.delete_webhook("h1") + assert c.test_webhook("h1") == v2.WebhookTestResult(True, 200, None, 42) + + +def test_blank_target_or_key_sends_nothing() -> None: + def never(request: HttpRequest) -> HttpResponse: + raise AssertionError("no request expected") + + assert ( + code_of(lambda: SupertextClient("k", transport=never).translate_texts({"a": "x"}, " ")) + == "unsupported_language" + ) + assert code_of(lambda: SupertextClient(" ", transport=never).get_account()) == "missing_api_key" + + +def test_filename_from() -> None: + assert v2.filename_from('attachment; filename="a b.docx"') == "a b.docx" + assert v2.filename_from("attachment; filename=x.pdf; filename*=UTF-8''Z%C3%BCrich.docx") == "Zürich.docx" + assert v2.filename_from(None) is None diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index a9ef42a..61ba0b4 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -17,7 +17,7 @@ You need an API key. No Supertext account yet? Create one at https://www.superte ## Quick start -Everything that talks to the API is in the `v1` namespace, so a later API version can sit next to it: `import { SupertextClient } from 'supertext-sdk/v1'`, or `import { v1 } from 'supertext-sdk'` and `new v1.SupertextClient(…)`. `SDK_VERSION` is exported from both. +Everything that talks to the API v1 is in the `v1` namespace (API v2 is in `v2`, see [API v2](#api-v2)): `import { SupertextClient } from 'supertext-sdk/v1'`, or `import { v1 } from 'supertext-sdk'` and `new v1.SupertextClient(…)`. `SDK_VERSION` is exported from both. Translate texts and HTML fragments, keyed by your own ids: @@ -162,6 +162,27 @@ The client builds the multipart upload itself instead of using `FormData`: the A Also exported: `authHeader()`, `retryDelayMs()`, `HtmlDocument.build()/parse()` (the document format), `planBatches()`, `errorForStatus()`, `errorForFileStatus()`. +## API v2 + +Supertext's platform API (`https://api-platform.supertext.com/v1/`, `Authorization: Bearer st_live_…`) is in `supertext-sdk/v2` (or `import { v2 } from 'supertext-sdk'`), next to v1. `translateTexts` takes the same segments and returns the same keys; texts go in direct requests of up to 10,000 characters (HTML segments with `tagHandling: 'html'`), a longer segment through the file endpoint. No Supertext account yet? Create one at https://www.supertext.com/person/en/account/signin. Generate your API key at https://www.supertext.com/en/integrations/api (supertext.com → Integrations → API; requires the Admin role); API v2 takes the workspace keys (`st_live_…`) described in [Supertext's v2 documentation](https://www.supertext.com/en/neo/documentation/api). + +```ts +import { SupertextClient, SupertextError, verifyWebhook } from 'supertext-sdk/v2' + +const client = new SupertextClient(process.env.SUPERTEXT_API_KEY ?? '') +const german = await client.translateTexts( + { title: 'Hello & welcome', body: { text: '

Our new shop opens on Monday.

', html: true } }, + 'de-CH', + { sourceLang: 'en', politeness: 'more', glossary: { shop: 'Laden' } }, +) +const docx = await client.translateFile(await readFile('offer.docx'), 'offer.docx', 'fr-CH') // { content, filename } + +// In your webhook endpoint: the raw body, before parsing it +const event = await verifyWebhook(process.env.SUPERTEXT_WEBHOOK_SECRET ?? '', request.headers, rawBody) +``` + +What else is there: `translateText` (one request, with the detected source language and enforced glossary terms) and `quoteText`; documents with `translateFile` (upload, wait, download, always delete) or the single steps `submitFile`, `getFileStatus`, `waitForFile`, `downloadFile` (`null` while not ready), `deleteFile`, and `quoteFile`; `detectLanguage`, `detectFileLanguage` and their quotes; human review with `quoteFusedText`/`orderFusedText`, `getFusedTextStatus`, `getFusedText` (and the same for files: `orderFusedFile`, `getFusedFileStatus`, `downloadFusedFile`); `getAccount`, `getFeatures`, `validateApiKey`, `checkApiKey` (same `ApiKeyCheck` as v1, on `GET account`); webhooks (`createWebhook`, whose secret is returned only once, `listWebhooks`, `getWebhook`, `updateWebhook`, `deleteWebhook`, `testWebhook`). Errors are one type with the codes of `spec/v2/errors.json` (`insufficient_credit`, `invalid_request`, `authentication_failure`, …) and Supertext's `detail`, `apiErrorCode`, `errorId` and `reason`. More: [integration guide → API v2](../../docs/integration-guide.md#16-api-v2-the-supertext-platform-api). + ## Translation files `TranslationFiles` exports segments as an XLIFF 1.2 or HTML file, to be translated outside the API (a CAT tool, a translator, Supertext's web app), and imports the translated file again (test vectors: `spec/translation-file.json`). It doesn't call the API, so it comes from `supertext-sdk`, not `supertext-sdk/v1`. diff --git a/sdk/typescript/examples/conformance-v2.mjs b/sdk/typescript/examples/conformance-v2.mjs new file mode 100644 index 0000000..e7d8a54 --- /dev/null +++ b/sdk/typescript/examples/conformance-v2.mjs @@ -0,0 +1,29 @@ +#!/usr/bin/env node +// v2 conformance program for stand-in/conformance.mjs --v2 (see spec/v2/conformance.json). +// Needs the built package: `npm run build` first. +// +// node stand-in/conformance.mjs --v2 -- node sdk/typescript/examples/conformance-v2.mjs +import { SupertextClient, SupertextError } from '../dist/v2/index.js' + +let input = '' +for await (const chunk of process.stdin) input += chunk +const request = JSON.parse(input) + +const client = new SupertextClient(process.env.SUPERTEXT_API_KEY ?? '', { + baseUrl: process.env.SUPERTEXT_API_URL, + pollIntervalMs: 100, + userAgent: 'conformance', +}) +const segments = new Map(request.segments.map((s) => [s.key, { text: s.text, html: s.html }])) + +let output +try { + const options = { sourceLang: request.sourceLang, politeness: request.politeness } + if (request.maxCharacters !== undefined) options.maxCharacters = request.maxCharacters + const translations = await client.translateTexts(segments, request.targetLang, options) + output = { translations: Object.fromEntries(translations) } +} catch (error) { + if (!(error instanceof SupertextError)) throw error + output = { error: { code: error.code, status: error.status ?? null } } +} +process.stdout.write(`${JSON.stringify(output)}\n`) diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json index c2b158e..027f12c 100644 --- a/sdk/typescript/package.json +++ b/sdk/typescript/package.json @@ -30,6 +30,10 @@ "./v1": { "types": "./dist/v1/index.d.ts", "import": "./dist/v1/index.js" + }, + "./v2": { + "types": "./dist/v2/index.d.ts", + "import": "./dist/v2/index.js" } }, "files": [ @@ -44,7 +48,7 @@ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json", "typecheck": "tsc --noEmit", "test": "vitest run", - "conformance": "npm run build && cd ../.. && node stand-in/conformance.mjs -- node sdk/typescript/examples/conformance.mjs", + "conformance": "npm run build && cd ../.. && node stand-in/conformance.mjs -- node sdk/typescript/examples/conformance.mjs && node stand-in/conformance.mjs --v2 -- node sdk/typescript/examples/conformance-v2.mjs", "prepack": "npm run build" }, "devDependencies": { diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 4aaa13c..000c554 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -4,9 +4,10 @@ * import { v1 } from 'supertext-sdk' // or: import { SupertextClient } from 'supertext-sdk/v1' * const client = new v1.SupertextClient(apiKey) * - * A later API version gets `v2` next to `v1`. + * import { v2 } from 'supertext-sdk' // the platform API: import { SupertextClient } from 'supertext-sdk/v2' */ export * as v1 from './v1/index.js' +export * as v2 from './v2/index.js' export { SDK_VERSION } from './version.js' // Translation files (XLIFF 1.2 and HTML export/import) don't talk to the API, so they aren't versioned. export { TranslationFiles, TranslationFileError, MAX_FILE_CHARACTERS } from './translation-file.js' diff --git a/sdk/typescript/src/v1/api-key-check.ts b/sdk/typescript/src/v1/api-key-check.ts index ae9202c..910c632 100644 --- a/sdk/typescript/src/v1/api-key-check.ts +++ b/sdk/typescript/src/v1/api-key-check.ts @@ -56,7 +56,8 @@ const K = new Uint32Array([ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]) -function sha256Hex(text: string): string { +/** SHA-256 of a string (UTF-8), lower-case hex. */ +export function sha256Hex(text: string): string { const data = new TextEncoder().encode(text) const length = data.length const padded = new Uint8Array((((length + 9 + 63) >> 6) << 6)) diff --git a/sdk/typescript/src/v2/auth.ts b/sdk/typescript/src/v2/auth.ts new file mode 100644 index 0000000..57bf897 --- /dev/null +++ b/sdk/typescript/src/v2/auth.ts @@ -0,0 +1,17 @@ +import { SupertextError } from './errors.js' +import { isAsciiSpace, trimAscii } from './text.js' + +export { isAsciiSpace, trimAscii } from './text.js' + +export { retryDelayMs } from '../v1/auth.js' + +/** + * The `Authorization` header value for an API key as an administrator pasted it + * (spec/v2/auth-header.json): trimmed, a pasted `Bearer ` stripped, exactly one sent. + */ +export function authHeader(apiKey: string): string { + let key = trimAscii(apiKey ?? '') + if (key.slice(0, 6).toLowerCase() === 'bearer' && (key.length === 6 || isAsciiSpace(key.charCodeAt(6)))) key = trimAscii(key.slice(6)) + if (key === '') throw new SupertextError('missing_api_key') + return `Bearer ${key}` +} diff --git a/sdk/typescript/src/v2/batching.ts b/sdk/typescript/src/v2/batching.ts new file mode 100644 index 0000000..967ee34 --- /dev/null +++ b/sdk/typescript/src/v2/batching.ts @@ -0,0 +1,46 @@ +import { codePointLength, isBlank, planBatches, type KeyedSegment } from '../v1/batching.js' + +/** The API's limit per POST translate/ai/text. */ +export const DEFAULT_MAX_TEXT_CHARACTERS = 10_000 + +export type RequestKind = 'text' | 'html' | 'file' + +export interface PlannedRequest { + /** `text`: plain texts (tag_handling none); `html`: HTML (tag_handling html); `file`: an HTML document for translate/ai/file. */ + kind: RequestKind + segments: T[] +} + +/** + * Splits segments into requests (spec/v2/batching.json): plain-text requests, + * then HTML requests, each up to `maxCharacters` code points; a segment longer + * than that goes into HTML documents for the file endpoint (v1 packing rules). + */ +export function planRequests(segments: Iterable, maxCharacters: number = DEFAULT_MAX_TEXT_CHARACTERS): PlannedRequest[] { + const plain: T[] = [] + const html: T[] = [] + const oversized: T[] = [] + for (const s of segments) { + if (isBlank(s.text)) continue + if (codePointLength(s.text) > maxCharacters) oversized.push(s) + else (s.html ? html : plain).push(s) + } + const out: PlannedRequest[] = [] + for (const [kind, list] of [['text', plain], ['html', html]] as const) { + let current: T[] = [] + let size = 0 + for (const s of list) { + const length = codePointLength(s.text) + if (current.length > 0 && size + length > maxCharacters) { + out.push({ kind, segments: current }) + current = [] + size = 0 + } + current.push(s) + size += length + } + if (current.length > 0) out.push({ kind, segments: current }) + } + for (const batch of planBatches(oversized)) out.push({ kind: 'file', segments: batch }) + return out +} diff --git a/sdk/typescript/src/v2/client.ts b/sdk/typescript/src/v2/client.ts new file mode 100644 index 0000000..a3faa9f --- /dev/null +++ b/sdk/typescript/src/v2/client.ts @@ -0,0 +1,728 @@ +/** + * Client for the Supertext API v2 (api-platform.supertext.com/v1, Bearer keys): + * text translation in one request, AI file translation, language detection, + * human review ("fused"), quotes, the account and webhooks. + */ +import { sha256Hex, isoSeconds, KEY_CHECK_TIMEOUT_MS, type ApiKeyCheck, type ApiKeyCheckStatus } from '../v1/api-key-check.js' +import { isBlank, type KeyedSegment } from '../v1/batching.js' +import { build, parse, type Segment } from '../v1/html-document.js' +import { authHeader, retryDelayMs, trimAscii } from './auth.js' +import { DEFAULT_MAX_TEXT_CHARACTERS, planRequests } from './batching.js' +import { errorForStatus, errorForStatusValue, SupertextError } from './errors.js' +import { contentTypeFor, encodeMultipart, type MultipartBody } from './multipart.js' + +export const LIVE_BASE_URL = 'https://api-platform.supertext.com/v1/' + +/** `more`: formal address (Sie, vous, Lei). `less`: informal (du, tu). `default`: Supertext decides. */ +export type Politeness = 'default' | 'more' | 'less' +/** How inline markup in texts is handled: `none` (plain text), `xml` (strict), `html` (tolerant). */ +export type TagHandling = 'none' | 'xml' | 'html' +/** Source → target terms, at most 100 per request. */ +export type Glossary = Readonly> +/** A document: bytes, or a string (sent as UTF-8). */ +export type FileContent = string | Uint8Array +export type FetchLike = (input: string, init: RequestInit) => Promise + +export interface SupertextClientOptions { + /** Default: the live API. A trailing slash is added if missing. */ + baseUrl?: string + /** Wait between status polls. Default 2000 ms. */ + pollIntervalMs?: number + /** Give up waiting for an AI file translation after this long. Default 180000 ms. */ + timeoutMs?: number + /** Timeout of a single HTTP request. Default 30000 ms. */ + requestTimeoutMs?: number + /** Retries after HTTP 429. Default 4. */ + maxRetries?: number + /** Appended to the User-Agent, e.g. `Payload-Supertext-Translation/1.2.0`. */ + userAgent?: string + fetch?: FetchLike + sleep?: (ms: number) => Promise + now?: () => number +} + +export interface TranslateOptions { + /** Source language (BCP 47), sent as given. Omitted or empty: detected. */ + sourceLang?: string | null + politeness?: Politeness + glossary?: Glossary | null +} + +export interface TextOptions extends TranslateOptions { + tagHandling?: TagHandling +} + +export interface TranslateTextsOptions extends TranslateOptions { + /** Characters per text request. Default 10000, the API's limit. */ + maxCharacters?: number +} + +export interface FileOptions extends TranslateOptions { + /** Read a PDF's text with OCR (scans). Changes the price: send the same on the quote. */ + useOcr?: boolean +} + +export interface FusedOptions { + politeness?: Politeness + /** Instructions for the reviewer. Sending one orders Optimisation instead of Verification. */ + briefing?: string | null +} + +export interface FusedFileOptions extends FusedOptions { + useOcr?: boolean +} + +export interface FusedTextOptions extends FusedOptions { + /** Sent as `Idempotency-Key`: the same key never places a second order. */ + idempotencyKey?: string +} + +export interface TextTranslation { + /** One translation per input text, same order. */ + translations: string[] + detectedSourceLang: string | null + /** Glossary terms applied; null when no glossary was sent. */ + enforcedTerms: Record | null + requestId: string | null +} + +export interface Quote { + characterCount: number + /** Keyed by lower-case currency code; not rounded to the cent. */ + prices: Record +} + +export interface FileStatus { + /** `translating`, `done`, `error`, `deleted`. */ + status: string + error: string | null + estimatedSecondsLeft: number | null + detectedSourceLang: string | null +} + +export interface DownloadedFile { + content: Uint8Array + /** From `Content-Disposition`, when present. */ + filename: string | null +} + +export interface DetectedLanguage { + langCode: string + confidence: number | null + supportsTranslation: boolean +} + +export interface Account { + workspaceId: string + workspaceName: string + apiKeyName: string + apiKeyPrefix: string + apiKeyExpiresAt: string +} + +/** One language pair from `GET features`. */ +export interface FeatureSupport { + sourceLang: string + targetLang: string + /** `supports_politeness`, `supports_glossary`, `supports_fused_translation`. */ + features: string[] +} + +export interface FusedOrder { + translationId: string + /** True: Optimisation (with briefing); false: Verification. */ + briefingApplied: boolean + /** For display only. */ + serviceLabel: string + requestId: string | null +} + +export interface FusedStatus { + /** `in_progress`, `completed`, `failed`. */ + status: string + detectedSourceLang: string | null + /** Negative: the promised delivery time has passed. */ + estimatedSecondsLeft: number + error: string | null +} + +export interface FusedQuote { + prices: Record + estimatedDurationSeconds: number + wordCount: number + /** Files only. */ + characterCount: number | null + briefingApplied: boolean + serviceLabel: string +} + +export interface Webhook { + id: string + url: string + eventTypes: string[] + description: string | null + /** `active` or `disabled`. */ + status: string + /** `gone` or `failing` when disabled. */ + disabledReason: string | null + createdAt: string + lastDeliveryAt: string | null + lastFailureAt: string | null + lastFailureReason: string | null + consecutiveFailures: number +} + +export interface CreatedWebhook extends Webhook { + /** The signing secret (`whsec_…`), returned only once: store it. */ + secret: string +} + +export interface WebhookInput { + url: string + eventTypes: readonly string[] + description?: string | null +} + +export interface WebhookUpdate { + url?: string + eventTypes?: readonly string[] + /** null clears it. */ + description?: string | null + /** true switches a disabled webhook back on. */ + enabled?: boolean +} + +export interface WebhookTestResult { + delivered: boolean + statusCode: number | null + error: string | null + durationMs: number +} + +/** Segments for `translateTexts`: a Map or a plain object, key → segment (a string is plain text). */ +export type SegmentInput = Segment | string +export type Segments = ReadonlyMap | Readonly> + +interface Answer { + status: number + headers: Headers + bytes: Uint8Array +} + +const SDK_USER_AGENT = 'supertext-sdk-typescript' +const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) +const decoder = new TextDecoder() + +export class SupertextClient { + readonly #apiKey: string + readonly #fetch: FetchLike + readonly #userAgent: string + readonly baseUrl: string + readonly pollIntervalMs: number + readonly timeoutMs: number + readonly requestTimeoutMs: number + readonly maxRetries: number + readonly #sleep: (ms: number) => Promise + readonly #now: () => number + + /** A blank key doesn't throw here: the first request throws `missing_api_key` without sending anything. */ + constructor(apiKey: string, options: SupertextClientOptions = {}) { + this.#apiKey = apiKey ?? '' + const base = options.baseUrl ?? LIVE_BASE_URL + this.baseUrl = base.endsWith('/') ? base : `${base}/` + this.pollIntervalMs = options.pollIntervalMs ?? 2000 + this.timeoutMs = options.timeoutMs ?? 180_000 + this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000 + this.maxRetries = options.maxRetries ?? 4 + this.#userAgent = options.userAgent ? `${SDK_USER_AGENT} ${options.userAgent}` : SDK_USER_AGENT + this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init)) + this.#sleep = options.sleep ?? defaultSleep + this.#now = options.now ?? Date.now + } + + // ---- account and features + + /** The workspace and key behind the API key. Cost-free. */ + async getAccount(): Promise { + const o = await this.#json('GET', 'account') + return { + workspaceId: text(o.workspace_id), + workspaceName: text(o.workspace_name), + apiKeyName: text(o.api_key_name), + apiKeyPrefix: text(o.api_key_prefix), + apiKeyExpiresAt: text(o.api_key_expires_at), + } + } + + /** The language pairs and their features, optionally for one source and/or target. Cost-free. */ + async getFeatures(filter: { sourceLang?: string; targetLang?: string } = {}): Promise { + const query = new URLSearchParams() + if (filter.sourceLang) query.set('source_lang', filter.sourceLang) + if (filter.targetLang) query.set('target_lang', filter.targetLang) + const q = query.toString() + const list = (await this.#json('GET', q ? `features?${q}` : 'features')).supported_features + if (!Array.isArray(list)) return [] + return list.flatMap((item: unknown) => { + const o = object(item) + if (typeof o.source_lang !== 'string' || typeof o.target_lang !== 'string') return [] + return [{ sourceLang: o.source_lang, targetLang: o.target_lang, features: strings(o.features) }] + }) + } + + /** Throws a `SupertextError` unless the key is accepted (`GET account`). */ + async validateApiKey(): Promise { + await this.#request('GET', 'account') + } + + /** The automatic key check (spec/v2/api-key-check.json): never throws. */ + async checkApiKey(): Promise { + const checkedAt = isoSeconds(this.#now()) + const fingerprint = apiKeyFingerprint(this.#apiKey) + if (fingerprint === '') return { status: 'missing', checkedAt, httpStatus: null, errorCode: null, fingerprint } + try { + const answer = await this.#request('GET', 'account', undefined, Math.min(KEY_CHECK_TIMEOUT_MS, this.requestTimeoutMs)) + return { status: 'ok', checkedAt, httpStatus: answer.status, errorCode: null, fingerprint } + } catch (error) { + return { ...keyCheckFromError(error), checkedAt, fingerprint } + } + } + + // ---- text + + /** One request to POST translate/ai/text: the translations in input order. Codes are sent as given. */ + async translateText(texts: readonly string[], targetLang: string, options: TextOptions = {}): Promise { + const o = await this.#json('POST', 'translate/ai/text', jsonBody(textPayload(texts, targetLang, options))) + const translations = strings(o.translated_text) + if (!Array.isArray(o.translated_text) || translations.length !== texts.length) { + throw new SupertextError('incomplete_response', { detail: `expected ${texts.length} translations` }) + } + return { + translations, + detectedSourceLang: textOrNull(o.detected_source_lang), + enforcedTerms: stringMap(o.enforced_terms), + requestId: textOrNull(o.request_id), + } + } + + /** What `translateText` would cost (a free dry run). */ + async quoteText(texts: readonly string[], targetLang: string, options: TextOptions = {}): Promise { + return quote(await this.#json('POST', 'translate/ai/text/quote', jsonBody(textPayload(texts, targetLang, options)))) + } + + /** + * Translates texts and HTML fragments keyed by your own ids (spec/v2/batching.json): + * the same keys in the same order back, blank texts unchanged. Up to 10,000 + * characters per request; a longer segment goes through an HTML file. + */ + translateTexts(segments: ReadonlyMap, targetLang: string, options?: TranslateTextsOptions): Promise> + translateTexts(segments: Readonly>, targetLang: string, options?: TranslateTextsOptions): Promise> + async translateTexts(segments: Segments, targetLang: string, options: TranslateTextsOptions = {}): Promise | Record> { + if (trimAscii(targetLang ?? '') === '') throw new SupertextError('unsupported_language') + const isMap = segments instanceof Map + const entries: [string, SegmentInput][] = isMap ? [...(segments as ReadonlyMap)] : Object.entries(segments) + const keyed: KeyedSegment[] = entries.map(([key, s]) => (typeof s === 'string' ? { key, text: s, html: false } : { key, text: s.text, html: s.html ?? false })) + const translated = new Map() + for (const request of planRequests(keyed, options.maxCharacters ?? DEFAULT_MAX_TEXT_CHARACTERS)) { + if (request.kind === 'file') { + const html = await this.translateHtml(build(request.segments), targetLang, options) + const results = parse(html, request.segments) + const missing = request.segments.filter((_, i) => results[i] === null).map((s) => s.key) + if (missing.length > 0) throw new SupertextError('incomplete_response', { detail: `missing: ${missing.join(', ')}` }) + request.segments.forEach((s, i) => translated.set(s.key, results[i]!)) + } else { + const result = await this.translateText(request.segments.map((s) => s.text), targetLang, { ...options, tagHandling: request.kind === 'html' ? 'html' : 'none' }) + request.segments.forEach((s, i) => translated.set(s.key, result.translations[i]!)) + } + } + const out = keyed.map((s) => [s.key, isBlank(s.text) ? s.text : translated.get(s.key)!] as const) + return isMap ? new Map(out) : Object.fromEntries(out) + } + + // ---- AI file translation + + /** Uploads a document for AI translation; returns the file id. */ + async submitFile(content: FileContent, filename: string, targetLang: string, options: FileOptions = {}): Promise { + const o = await this.#json('POST', 'translate/ai/file', fileForm(content, filename, targetLang, options, true)) + const fileId = textOrNull(o.file_id) + if (fileId === null) throw new SupertextError('incomplete_response', { detail: 'no file_id' }) + return fileId + } + + async getFileStatus(fileId: string): Promise { + const o = await this.#json('GET', `translate/ai/file/${encodeURIComponent(fileId)}/status`) + return { + status: text(o.status), + error: textOrNull(o.error), + estimatedSecondsLeft: numberOrNull(o.estimated_duration_left_in_seconds), + detectedSourceLang: textOrNull(o.detected_source_lang), + } + } + + /** Polls until `done`; throws `translation_error`, `file_deleted` or `timeout`. */ + async waitForFile(fileId: string): Promise { + const started = this.#now() + for (;;) { + const status = await this.getFileStatus(fileId) + if (status.status === 'done') return status + const error = errorForStatusValue('file', status.status, status.error) + if (error) throw error + if (this.#now() - started + this.pollIntervalMs > this.timeoutMs) throw new SupertextError('timeout') + await this.#sleep(this.pollIntervalMs) + } + } + + /** The translated document, or null while it isn't ready (HTTP 202). Available for 24 hours. */ + async downloadFile(fileId: string): Promise { + return download(await this.#request('GET', `translate/ai/file/${encodeURIComponent(fileId)}/translation`)) + } + + /** Deletes the document and its translation. Never throws (best effort; charges stay). */ + async deleteFile(fileId: string): Promise { + try { + await this.#request('DELETE', `translate/ai/file/${encodeURIComponent(fileId)}`) + } catch { + // Best effort: files expire after 24 hours anyway. + } + } + + /** Full round trip for one document: upload, wait, download, and always delete. */ + async translateFile(content: FileContent, filename: string, targetLang: string, options: FileOptions = {}): Promise { + const fileId = await this.submitFile(content, filename, targetLang, options) + try { + await this.waitForFile(fileId) + const file = await this.downloadFile(fileId) + if (file === null || file.content.length === 0) throw new SupertextError('incomplete_response', { detail: 'empty document' }) + return file + } finally { + await this.deleteFile(fileId) + } + } + + /** One HTML document through the file endpoint (`translateFile` as `content.html`). */ + async translateHtml(html: string, targetLang: string, options: FileOptions = {}): Promise { + return decoder.decode((await this.translateFile(html, 'content.html', targetLang, options)).content) + } + + async quoteFile(content: FileContent, filename: string, targetLang: string, options: FileOptions = {}): Promise { + return quote(await this.#json('POST', 'translate/ai/file/quote', fileForm(content, filename, targetLang, options, true))) + } + + // ---- language detection + + /** The language of a text (the first 500 characters are read). Empty when none was found (free). */ + async detectLanguage(textToCheck: string): Promise { + return detected(await this.#json('POST', 'detect-languages/text', jsonBody({ text: textToCheck }))) + } + + async quoteDetection(textToCheck: string): Promise { + return quote(await this.#json('POST', 'detect-languages/text/quote', jsonBody({ text: textToCheck }))) + } + + async detectFileLanguage(content: FileContent, filename: string): Promise { + return detected(await this.#json('POST', 'detect-languages/file', encodeMultipart([], { filename, contentType: contentTypeFor(filename), content }))) + } + + async quoteFileDetection(content: FileContent, filename: string): Promise { + return quote(await this.#json('POST', 'detect-languages/file/quote', encodeMultipart([], { filename, contentType: contentTypeFor(filename), content }))) + } + + // ---- human review ("fused") + + /** Orders a reviewed translation of a text. The source language is required. Charged when accepted. */ + async orderFusedText(textToTranslate: string, sourceLang: string, targetLang: string, options: FusedTextOptions = {}): Promise { + const extra: Record = {} + if (options.idempotencyKey) extra['Idempotency-Key'] = options.idempotencyKey + return fusedOrder(await this.#json('POST', 'translate/fused/text', jsonBody(fusedPayload(textToTranslate, sourceLang, targetLang, options)), extra)) + } + + async getFusedTextStatus(translationId: string): Promise { + return fusedStatus(await this.#json('GET', `translate/fused/text/${encodeURIComponent(translationId)}/status`)) + } + + /** The reviewed text, or null while it isn't delivered yet (HTTP 202). */ + async getFusedText(translationId: string): Promise { + const answer = await this.#request('GET', `translate/fused/text/${encodeURIComponent(translationId)}/translation`) + if (answer.status === 202) return null + const value = parseObject(decoder.decode(answer.bytes)).translated_text + if (typeof value !== 'string') throw new SupertextError('incomplete_response', { detail: 'no translated_text' }) + return value + } + + async quoteFusedText(textToTranslate: string, sourceLang: string, targetLang: string, options: FusedOptions = {}): Promise { + return fusedQuote(await this.#json('POST', 'translate/fused/text/quote', jsonBody(fusedPayload(textToTranslate, sourceLang, targetLang, options)))) + } + + /** Orders a reviewed translation of a document (PDFs come back as DOCX). */ + async orderFusedFile(content: FileContent, filename: string, sourceLang: string, targetLang: string, options: FusedFileOptions = {}): Promise { + return fusedOrder(await this.#json('POST', 'translate/fused/file', fusedForm(content, filename, sourceLang, targetLang, options))) + } + + async getFusedFileStatus(translationId: string): Promise { + return fusedStatus(await this.#json('GET', `translate/fused/file/${encodeURIComponent(translationId)}/status`)) + } + + /** The reviewed document, or null until a reviewer delivers (HTTP 202). */ + async downloadFusedFile(translationId: string): Promise { + return download(await this.#request('GET', `translate/fused/file/${encodeURIComponent(translationId)}/translation`)) + } + + async quoteFusedFile(content: FileContent, filename: string, sourceLang: string, targetLang: string, options: FusedFileOptions = {}): Promise { + return fusedQuote(await this.#json('POST', 'translate/fused/file/quote', fusedForm(content, filename, sourceLang, targetLang, options))) + } + + // ---- webhooks + + /** This key's webhooks. */ + async listWebhooks(): Promise { + const items = (await this.#json('GET', 'webhooks')).items + return Array.isArray(items) ? items.map((i) => webhook(object(i))) : [] + } + + /** Registers a webhook; the result carries the signing secret, shown only once. */ + async createWebhook(input: WebhookInput): Promise { + const body: Record = { url: input.url, event_types: [...input.eventTypes] } + if (input.description !== undefined) body.description = input.description + const o = await this.#json('POST', 'webhooks', jsonBody(body)) + return { ...webhook(o), secret: text(o.secret) } + } + + async getWebhook(webhookId: string): Promise { + return webhook(await this.#json('GET', `webhooks/${encodeURIComponent(webhookId)}`)) + } + + /** Changes only the fields given. */ + async updateWebhook(webhookId: string, update: WebhookUpdate): Promise { + const body: Record = {} + if (update.url !== undefined) body.url = update.url + if (update.eventTypes !== undefined) body.event_types = [...update.eventTypes] + if (update.description !== undefined) body.description = update.description + if (update.enabled !== undefined) body.enabled = update.enabled + return webhook(await this.#json('PATCH', `webhooks/${encodeURIComponent(webhookId)}`, jsonBody(body))) + } + + async deleteWebhook(webhookId: string): Promise { + await this.#request('DELETE', `webhooks/${encodeURIComponent(webhookId)}`) + } + + /** Sends a test event (at most one per 5 seconds). */ + async testWebhook(webhookId: string): Promise { + const o = await this.#json('POST', `webhooks/${encodeURIComponent(webhookId)}/test`) + return { delivered: o.delivered === true, statusCode: numberOrNull(o.status_code), error: textOrNull(o.error), durationMs: numberOrNull(o.duration_ms) ?? 0 } + } + + // ---- HTTP + + async #json(method: string, path: string, body?: MultipartBody, extraHeaders: Record = {}): Promise> { + return parseObject(decoder.decode((await this.#request(method, path, body, this.requestTimeoutMs, extraHeaders)).bytes)) + } + + /** One HTTP request with auth, retries on 429 and error mapping. Returns any 2xx answer. */ + async #request(method: string, path: string, body?: MultipartBody, timeoutMs = this.requestTimeoutMs, extraHeaders: Record = {}): Promise { + const authorization = authHeader(this.#apiKey) // throws missing_api_key before anything is sent + const key = authorization.slice('Bearer '.length) + const scrub = (value: string) => value.split(key).join('***') + const headers: Record = { ...extraHeaders, Authorization: authorization, Accept: 'application/json, application/problem+json', 'User-Agent': this.#userAgent } + if (body) headers['Content-Type'] = body.contentType + for (let attempt = 0; ; attempt++) { + let response: Response + let bytes: Uint8Array + try { + const init: RequestInit = { method, headers, signal: AbortSignal.timeout(timeoutMs) } + if (body) init.body = body.body + response = await this.#fetch(this.baseUrl + path, init) + bytes = new Uint8Array(await response.arrayBuffer()) + } catch (error) { + throw new SupertextError('transport_error', { detail: scrub(errorMessage(error)), cause: error }) + } + if (response.status === 429 && attempt < this.maxRetries) { + await this.#sleep(retryDelayMs(attempt, response.headers.get('retry-after'))) + continue + } + if (!response.ok) throw errorForStatus(response.status, scrub(decoder.decode(bytes))) + return { status: response.status, headers: response.headers, bytes } + } + } +} + +/** SHA-256 (hex) of the key as the v2 `authHeader()` sends it; '' for a blank key. */ +export function apiKeyFingerprint(apiKey: string | null | undefined): string { + let header: string + try { + header = authHeader(apiKey ?? '') + } catch { + return '' + } + return sha256Hex(header.slice('Bearer '.length)) +} + +/** Status, HTTP status and error code of a failed key check. */ +export function keyCheckFromError(error: unknown): Pick { + if (!(error instanceof SupertextError)) return { status: 'error', httpStatus: null, errorCode: null } + const httpStatus = error.status ?? null + const errorCode = error.apiErrorCode ? error.apiErrorCode.slice(0, 100) : null + let status: ApiKeyCheckStatus + if (error.code === 'missing_api_key') status = 'missing' + else if (httpStatus === 401 || httpStatus === 403) status = 'invalid' + else if (httpStatus === null || httpStatus >= 500) status = 'unreachable' + else status = 'error' + return { status, httpStatus, errorCode } +} + +// ---- payloads + +function textPayload(texts: readonly string[], targetLang: string, options: TextOptions): Record { + const target = trimAscii(targetLang ?? '') + if (target === '') throw new SupertextError('unsupported_language') + const body: Record = { text: [...texts], target_lang: target } + const source = trimAscii(options.sourceLang ?? '') + if (source !== '') body.source_lang = source + if (options.politeness === 'more' || options.politeness === 'less') body.politeness = options.politeness + if (options.glossary && Object.keys(options.glossary).length > 0) body.glossary = { ...options.glossary } + if (options.tagHandling && options.tagHandling !== 'none') body.tag_handling = options.tagHandling + return body +} + +function fileForm(content: FileContent, filename: string, targetLang: string, options: FileOptions, withGlossary: boolean): MultipartBody { + const target = trimAscii(targetLang ?? '') + if (target === '') throw new SupertextError('unsupported_language') + const fields: [string, string][] = [['target_lang', target]] + const source = trimAscii(options.sourceLang ?? '') + if (source !== '') fields.push(['source_lang', source]) + if (options.politeness === 'more' || options.politeness === 'less') fields.push(['politeness', options.politeness]) + if (withGlossary && options.glossary && Object.keys(options.glossary).length > 0) fields.push(['glossary', JSON.stringify(options.glossary)]) + if (options.useOcr !== undefined) fields.push(['use_ocr', options.useOcr ? 'true' : 'false']) + return encodeMultipart(fields, { filename, contentType: contentTypeFor(filename), content }) +} + +function fusedPayload(textToTranslate: string, sourceLang: string, targetLang: string, options: FusedOptions): Record { + const source = trimAscii(sourceLang ?? '') + const target = trimAscii(targetLang ?? '') + if (source === '' || target === '') throw new SupertextError('unsupported_language') + const body: Record = { text: textToTranslate, source_lang: source, target_lang: target } + if (options.politeness === 'more' || options.politeness === 'less') body.politeness = options.politeness + if (options.briefing) body.briefing = options.briefing + return body +} + +function fusedForm(content: FileContent, filename: string, sourceLang: string, targetLang: string, options: FusedFileOptions): MultipartBody { + const source = trimAscii(sourceLang ?? '') + const target = trimAscii(targetLang ?? '') + if (source === '' || target === '') throw new SupertextError('unsupported_language') + const fields: [string, string][] = [['target_lang', target], ['source_lang', source]] + if (options.politeness === 'more' || options.politeness === 'less') fields.push(['politeness', options.politeness]) + if (options.briefing) fields.push(['briefing', options.briefing]) + if (options.useOcr !== undefined) fields.push(['use_ocr', options.useOcr ? 'true' : 'false']) + return encodeMultipart(fields, { filename, contentType: contentTypeFor(filename), content }) +} + +function jsonBody(value: unknown): MultipartBody { + const bytes = new TextEncoder().encode(JSON.stringify(value)) + return { body: bytes.buffer as ArrayBuffer, contentType: 'application/json' } +} + +// ---- answers (fields only count with the documented types) + +function parseObject(body: string): Record { + try { + return object(JSON.parse(body)) + } catch { + return {} + } +} + +function object(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {} +} + +const text = (value: unknown): string => (typeof value === 'string' ? value : '') +const textOrNull = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null) +const numberOrNull = (value: unknown): number | null => (typeof value === 'number' && Number.isFinite(value) ? value : null) +const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []) + +function stringMap(value: unknown): Record | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null + return Object.fromEntries(Object.entries(value).filter((e): e is [string, string] => typeof e[1] === 'string')) +} + +function prices(value: unknown): Record { + return Object.fromEntries(Object.entries(object(value)).filter((e): e is [string, number] => typeof e[1] === 'number')) +} + +function quote(o: Record): Quote { + return { characterCount: numberOrNull(o.character_count) ?? 0, prices: prices(o.prices) } +} + +function detected(o: Record): DetectedLanguage[] { + const list = o.detected_languages + if (!Array.isArray(list)) return [] + return list.flatMap((item: unknown) => { + const d = object(item) + if (typeof d.lang_code !== 'string') return [] + return [{ langCode: d.lang_code, confidence: numberOrNull(d.confidence), supportsTranslation: d.supports_translation === true }] + }) +} + +function fusedOrder(o: Record): FusedOrder { + const translationId = textOrNull(o.translation_id) + if (translationId === null) throw new SupertextError('incomplete_response', { detail: 'no translation_id' }) + return { translationId, briefingApplied: o.briefing_applied === true, serviceLabel: text(o.service_label), requestId: textOrNull(o.request_id) } +} + +function fusedStatus(o: Record): FusedStatus { + return { status: text(o.status), detectedSourceLang: textOrNull(o.detected_source_lang), estimatedSecondsLeft: numberOrNull(o.estimated_duration_left_in_seconds) ?? 0, error: textOrNull(o.error) } +} + +function fusedQuote(o: Record): FusedQuote { + return { + prices: prices(o.prices), + estimatedDurationSeconds: numberOrNull(o.estimated_duration_in_seconds) ?? 0, + wordCount: numberOrNull(o.word_count) ?? 0, + characterCount: numberOrNull(o.character_count), + briefingApplied: o.briefing_applied === true, + serviceLabel: text(o.service_label), + } +} + +function webhook(o: Record): Webhook { + return { + id: text(o.id), + url: text(o.url), + eventTypes: strings(o.event_types), + description: textOrNull(o.description), + status: text(o.status), + disabledReason: textOrNull(o.disabled_reason), + createdAt: text(o.created_at), + lastDeliveryAt: textOrNull(o.last_delivery_at), + lastFailureAt: textOrNull(o.last_failure_at), + lastFailureReason: textOrNull(o.last_failure_reason), + consecutiveFailures: numberOrNull(o.consecutive_failures) ?? 0, + } +} + +function download(answer: Answer): DownloadedFile | null { + if (answer.status === 202) return null + return { content: answer.bytes, filename: filenameFrom(answer.headers.get('content-disposition')) } +} + +/** The file name of a `Content-Disposition` header (`filename*=UTF-8''…` preferred). */ +export function filenameFrom(disposition: string | null): string | null { + if (!disposition) return null + const star = /filename\*\s*=\s*UTF-8''([^;]+)/i.exec(disposition) + if (star) { + try { + return decodeURIComponent(star[1]!.trim()) + } catch { + // fall through to the plain parameter + } + } + const plain = /filename\s*=\s*(?:"([^"]*)"|([^;\s]+))/i.exec(disposition) + return plain ? (plain[1] ?? plain[2] ?? null) : null +} + +function errorMessage(error: unknown): string { + if (error instanceof Error) { + const cause = (error as { cause?: unknown }).cause + return cause instanceof Error && cause.message ? `${error.message}: ${cause.message}` : error.message + } + return String(error) +} diff --git a/sdk/typescript/src/v2/errors.ts b/sdk/typescript/src/v2/errors.ts new file mode 100644 index 0000000..7f3ab8d --- /dev/null +++ b/sdk/typescript/src/v2/errors.ts @@ -0,0 +1,151 @@ +import { trimAscii } from './text.js' + +/** + * Errors of the v2 client. Every failure is a `SupertextError` with a stable + * `code` (spec/v2/errors.json); integrations translate the code for their users + * and may show `detail` (the API's own explanation, safe to display). + */ + +/** Stable error codes. The string values are shared by all Supertext SDKs. */ +export const ErrorCode = { + MissingApiKey: 'missing_api_key', + AuthenticationFailure: 'authentication_failure', + InsufficientCredit: 'insufficient_credit', + InvalidRequest: 'invalid_request', + UnsupportedLanguage: 'unsupported_language', + NotFound: 'not_found', + Conflict: 'conflict', + PayloadTooLarge: 'payload_too_large', + TooManyRequests: 'too_many_requests', + ServiceUnavailable: 'service_unavailable', + UnexpectedStatus: 'unexpected_status', + TransportError: 'transport_error', + IncompleteResponse: 'incomplete_response', + TranslationError: 'translation_error', + FileDeleted: 'file_deleted', + Timeout: 'timeout', + InvalidWebhook: 'invalid_webhook', +} as const + +export type SupertextErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode] + +const MESSAGES: Record = { + missing_api_key: 'No Supertext API key is configured.', + authentication_failure: 'Supertext rejected the API key. Please check it.', + insufficient_credit: 'The Supertext credit balance does not cover this request. Please top up.', + invalid_request: 'Supertext rejected the request.', + unsupported_language: 'This language has no Supertext language code. Map it to a Supertext language.', + not_found: 'Not found at Supertext (expired or already deleted).', + conflict: 'Supertext refused the change.', + payload_too_large: 'The document is too large for Supertext.', + too_many_requests: 'Too many requests to Supertext. Please try again shortly.', + service_unavailable: 'The Supertext service is unavailable.', + unexpected_status: 'Supertext sent an unexpected HTTP status.', + transport_error: 'Could not reach Supertext.', + incomplete_response: 'The Supertext answer is incomplete.', + translation_error: 'Supertext failed to translate.', + file_deleted: 'The Supertext file was deleted before it could be downloaded.', + timeout: 'Timed out waiting for the Supertext translation to finish.', + invalid_webhook: 'The webhook request is not a valid, signed Supertext event.', +} + +export interface SupertextErrorDetails { + /** HTTP status, when the error comes from an HTTP answer. */ + status?: number + /** The API's explanation (problem+json `detail`), at most 200 characters. */ + detail?: string + /** The problem's `code`, e.g. `validation_error`, `webhook_limit_reached`. */ + apiErrorCode?: string + /** The problem's `error_id`: quote it to Supertext support. */ + errorId?: string + /** The problem's `reason`, e.g. `insufficient_credit`. */ + reason?: string + cause?: unknown +} + +export class SupertextError extends Error { + readonly code: SupertextErrorCode + readonly status?: number + readonly detail?: string + readonly apiErrorCode?: string + readonly errorId?: string + readonly reason?: string + + constructor(code: SupertextErrorCode, details: SupertextErrorDetails = {}) { + let message = MESSAGES[code] + if (details.status !== undefined) message += ` HTTP ${details.status}.` + if (details.detail) message += ` Details: ${details.detail}` + if (details.errorId) message += ` (error id ${details.errorId})` + super(message, details.cause !== undefined ? { cause: details.cause } : undefined) + this.name = 'SupertextError' + this.code = code + if (details.status !== undefined) this.status = details.status + if (details.detail) this.detail = details.detail + if (details.apiErrorCode) this.apiErrorCode = details.apiErrorCode + if (details.errorId) this.errorId = details.errorId + if (details.reason) this.reason = details.reason + } +} + +const str = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined) +const cut = (text: string): string | undefined => trimAscii(text).slice(0, 200) || undefined + +/** The text without complete `<…>` tags (linear, no regular expression); an unclosed `<` stays. */ +function withoutTags(text: string): string { + let out = '' + let i = 0 + while (i < text.length) { + const open = text.indexOf('<', i) + if (open === -1) return out + text.slice(i) + const close = text.indexOf('>', open + 1) + if (close === -1) return out + text.slice(i) + out += text.slice(i, open) + i = close + 1 + } + return out +} + +/** Maps a non-2xx answer (problem+json) to a `SupertextError` (spec/v2/errors.json). */ +export function errorForStatus(status: number, body: string): SupertextError { + let json: Record | undefined + try { + const parsed: unknown = JSON.parse(body) + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) json = parsed as Record + } catch { + // Not JSON: an HTML error page from a proxy, or nothing. + } + const details: SupertextErrorDetails = { status } + const detail = cut(str(json?.detail) ?? withoutTags(body)) + if (detail !== undefined) details.detail = detail + const apiErrorCode = str(json?.code) + const errorId = str(json?.error_id) + const reason = str(json?.reason) + if (apiErrorCode !== undefined) details.apiErrorCode = apiErrorCode + if (errorId !== undefined) details.errorId = errorId + if (reason !== undefined) details.reason = reason + let code: SupertextErrorCode + if (status === 401 || status === 403) code = 'authentication_failure' + else if (status === 402) code = 'insufficient_credit' + else if (status === 404) code = 'not_found' + else if (status === 409) code = 'conflict' + else if (status === 413) code = 'payload_too_large' + else if (status === 422) code = 'invalid_request' + else if (status === 429) code = 'too_many_requests' + else if (status >= 500 && status <= 599) code = 'service_unavailable' + else code = 'unexpected_status' + return new SupertextError(code, details) +} + +/** + * The error for a polled status, or `null` when it isn't a failure: AI file + * (`file`) `error` and `deleted`, human review (`fused`) `failed`. + */ +export function errorForStatusValue(kind: 'file' | 'fused', status: string, error?: string | null): SupertextError | null { + const details: SupertextErrorDetails = {} + const detail = cut(error ?? '') + if (detail !== undefined) details.detail = detail + if (kind === 'file' && status === 'error') return new SupertextError('translation_error', details) + if (kind === 'file' && status === 'deleted') return new SupertextError('file_deleted') + if (kind === 'fused' && status === 'failed') return new SupertextError('translation_error', details) + return null +} diff --git a/sdk/typescript/src/v2/index.ts b/sdk/typescript/src/v2/index.ts new file mode 100644 index 0000000..5c3d3e9 --- /dev/null +++ b/sdk/typescript/src/v2/index.ts @@ -0,0 +1,53 @@ +/** + * Supertext API v2: the Supertext platform API (https://api-platform.supertext.com/v1, + * workspace keys sent as `Bearer st_live_…`). Text translation in one request, AI file + * translation, language detection, human review, quotes, the account and webhooks. + * Lives next to `supertext-sdk/v1` (the AI file translation API), so integrations + * move at their own pace. + * + * Keys: workspace admins create them in the Supertext workspace under API keys. + */ +export { SupertextClient, LIVE_BASE_URL, apiKeyFingerprint, filenameFrom, keyCheckFromError } from './client.js' +export type { + Account, + CreatedWebhook, + DetectedLanguage, + DownloadedFile, + FeatureSupport, + FetchLike, + FileContent, + FileOptions, + FileStatus, + FusedFileOptions, + FusedOptions, + FusedOrder, + FusedQuote, + FusedStatus, + FusedTextOptions, + Glossary, + Politeness, + Quote, + SegmentInput, + Segments, + SupertextClientOptions, + TagHandling, + TextOptions, + TextTranslation, + TranslateOptions, + TranslateTextsOptions, + Webhook, + WebhookInput, + WebhookTestResult, + WebhookUpdate, +} from './client.js' +export { authHeader, retryDelayMs } from './auth.js' +export { ErrorCode, SupertextError, errorForStatus, errorForStatusValue } from './errors.js' +export type { SupertextErrorCode, SupertextErrorDetails } from './errors.js' +export { DEFAULT_MAX_TEXT_CHARACTERS, planRequests } from './batching.js' +export type { PlannedRequest, RequestKind } from './batching.js' +export { WEBHOOK_TOLERANCE_SECONDS, verifyWebhook } from './webhooks.js' +export type { WebhookEvent, WebhookHeaders } from './webhooks.js' +export { HtmlDocument } from '../v1/html-document.js' +export type { Segment } from '../v1/html-document.js' +export { KEY_CHECK_TIMEOUT_MS } from '../v1/api-key-check.js' +export type { ApiKeyCheck, ApiKeyCheckStatus } from '../v1/api-key-check.js' diff --git a/sdk/typescript/src/v2/multipart.ts b/sdk/typescript/src/v2/multipart.ts new file mode 100644 index 0000000..9720565 --- /dev/null +++ b/sdk/typescript/src/v2/multipart.ts @@ -0,0 +1,51 @@ +/** multipart/form-data with exact control over the file part's Content-Type (see ../v1/multipart.ts). */ +export interface MultipartFile { + filename: string + contentType: string + content: string | Uint8Array +} + +export interface MultipartBody { + body: ArrayBuffer + contentType: string +} + +function randomBoundary(): string { + let hex = '' + for (let i = 0; i < 32; i++) hex += Math.floor(Math.random() * 16).toString(16) + return `----supertext-${hex}` +} + +/** Fields in order, then the file part `file`. A quote or line break in the file name is replaced by `_`. */ +export function encodeMultipart(fields: readonly (readonly [string, string])[], file: MultipartFile, boundary = randomBoundary()): MultipartBody { + const encoder = new TextEncoder() + let head = '' + for (const [name, value] of fields) head += `--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n` + const filename = file.filename.replace(/["\r\n\\]/g, '_') + head += `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${filename}"\r\nContent-Type: ${file.contentType}\r\n\r\n` + const parts = [encoder.encode(head), typeof file.content === 'string' ? encoder.encode(file.content) : file.content, encoder.encode(`\r\n--${boundary}--\r\n`)] + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)) + let offset = 0 + for (const p of parts) { + out.set(p, offset) + offset += p.length + } + return { body: out.buffer as ArrayBuffer, contentType: `multipart/form-data; boundary=${boundary}` } +} + +const TYPES: Record = { + html: 'text/html', + htm: 'text/html', + txt: 'text/plain', + srt: 'application/x-subrip', + pdf: 'application/pdf', + docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', +} + +/** The Content-Type for a file name's extension (the formats the API takes); else application/octet-stream. */ +export function contentTypeFor(filename: string): string { + const dot = filename.lastIndexOf('.') + return (dot >= 0 && Object.hasOwn(TYPES, filename.slice(dot + 1).toLowerCase()) ? TYPES[filename.slice(dot + 1).toLowerCase()] : undefined) ?? 'application/octet-stream' +} diff --git a/sdk/typescript/src/v2/text.ts b/sdk/typescript/src/v2/text.ts new file mode 100644 index 0000000..5289c8f --- /dev/null +++ b/sdk/typescript/src/v2/text.ts @@ -0,0 +1,11 @@ +/** Space, tab, line feed, carriage return, form feed. */ +export const isAsciiSpace = (c: number): boolean => c === 32 || c === 9 || c === 10 || c === 13 || c === 12 + +/** Trims ASCII whitespace (linear, no regular expression). */ +export function trimAscii(text: string): string { + let start = 0 + let end = text.length + while (start < end && isAsciiSpace(text.charCodeAt(start))) start++ + while (end > start && isAsciiSpace(text.charCodeAt(end - 1))) end-- + return text.slice(start, end) +} diff --git a/sdk/typescript/src/v2/webhooks.ts b/sdk/typescript/src/v2/webhooks.ts new file mode 100644 index 0000000..2657157 --- /dev/null +++ b/sdk/typescript/src/v2/webhooks.ts @@ -0,0 +1,83 @@ +import { SupertextError } from './errors.js' + +/** How far a webhook's timestamp may be from now, either way. */ +export const WEBHOOK_TOLERANCE_SECONDS = 300 + +/** A verified webhook event. `id` is the `webhook-id` header: de-duplicate on it (delivery is at least once). */ +export interface WebhookEvent { + id: string + type: string + timestamp: string + data: Record +} + +export type WebhookHeaders = Headers | Readonly> + +const invalid = () => new SupertextError('invalid_webhook') + +function header(headers: WebhookHeaders, name: string): string | undefined { + if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name) ?? undefined + for (const [key, value] of Object.entries(headers as Record)) { + if (key.toLowerCase() === name) return typeof value === 'string' ? value : value?.[0] + } + return undefined +} + +function base64Decode(text: string): Uint8Array { + if (!/^[A-Za-z0-9+/]*={0,2}$/.test(text) || text.length % 4 !== 0) throw invalid() + const binary = atob(text) + const out = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i) + return out +} + +function base64Encode(bytes: Uint8Array): string { + let binary = '' + for (const b of bytes) binary += String.fromCharCode(b) + return btoa(binary) +} + +function equalConstantTime(a: string, b: string): boolean { + if (a.length !== b.length) return false + let diff = 0 + for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i) + return diff === 0 +} + +/** + * Verifies a webhook request the Standard Webhooks way and returns its event + * (spec/v2/webhooks.json). Pass the raw body exactly as received, before any JSON + * parsing. Throws `invalid_webhook` if anything doesn't match. + */ +export async function verifyWebhook(secret: string, headers: WebhookHeaders, rawBody: string, nowSeconds: number = Math.floor(Date.now() / 1000)): Promise { + const key = base64Decode((secret ?? '').startsWith('whsec_') ? secret.slice('whsec_'.length) : secret ?? '') + if (key.length === 0) throw invalid() + const id = header(headers, 'webhook-id') + const timestamp = header(headers, 'webhook-timestamp') + const signatures = header(headers, 'webhook-signature') + if (!id || !timestamp || !signatures || !/^[0-9]+$/.test(timestamp)) throw invalid() + if (Math.abs(nowSeconds - Number(timestamp)) > WEBHOOK_TOLERANCE_SECONDS) throw invalid() + + const subtle = globalThis.crypto.subtle + const hmacKey = await subtle.importKey('raw', key as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']) + const signed = new TextEncoder().encode(`${id}.${timestamp}.${rawBody}`) + const expected = base64Encode(new Uint8Array(await subtle.sign('HMAC', hmacKey, signed))) + let matched = false + for (const entry of signatures.split(' ')) { + const comma = entry.indexOf(',') + if (comma > 0 && entry.slice(0, comma) === 'v1' && equalConstantTime(entry.slice(comma + 1), expected)) matched = true + } + if (!matched) throw invalid() + + let body: unknown + try { + body = JSON.parse(rawBody) + } catch { + throw invalid() + } + if (!body || typeof body !== 'object' || Array.isArray(body)) throw invalid() + const o = body as Record + if (typeof o.type !== 'string' || typeof o.timestamp !== 'string') throw invalid() + const data = o.data && typeof o.data === 'object' && !Array.isArray(o.data) ? (o.data as Record) : {} + return { id, type: o.type, timestamp: o.timestamp, data } +} diff --git a/sdk/typescript/test/v2.test.ts b/sdk/typescript/test/v2.test.ts new file mode 100644 index 0000000..bd83f2d --- /dev/null +++ b/sdk/typescript/test/v2.test.ts @@ -0,0 +1,274 @@ +// API v2: the shared vectors in spec/v2/ and the client against a fake fetch. +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { + SupertextClient, + SupertextError, + apiKeyFingerprint, + authHeader, + errorForStatus, + errorForStatusValue, + filenameFrom, + planRequests, + verifyWebhook, + type FetchLike, +} from '../src/v2/index.js' +import { v2 } from '../src/index.js' + +const spec = (name: string): any => JSON.parse(readFileSync(new URL(`../../../spec/v2/${name}`, import.meta.url), 'utf8')) + +const codeOf = async (fn: () => unknown): Promise => { + try { + await fn() + } catch (e) { + expect(e).toBeInstanceOf(SupertextError) + return (e as SupertextError).code + } + throw new Error('expected a SupertextError') +} + +describe('spec/v2/auth-header.json', () => { + for (const c of spec('auth-header.json').cases) { + it(JSON.stringify(c.apiKey), async () => { + if (c.error) expect(await codeOf(() => authHeader(c.apiKey))).toBe(c.error) + else expect(authHeader(c.apiKey)).toBe(c.header) + }) + } +}) + +describe('spec/v2/errors.json', () => { + const s = spec('errors.json') + for (const c of s.http) { + it(`HTTP ${c.status} ${c.body.slice(0, 40)}`, () => { + const e = errorForStatus(c.status, c.body) + expect(e.code).toBe(c.code) + expect(e.status).toBe(c.status) + expect(e.apiErrorCode ?? null).toBe(c.apiErrorCode) + expect(e.errorId ?? null).toBe(c.errorId) + expect(e.reason ?? null).toBe(c.reason) + expect(e.detail ?? null).toBe(c.detail) + }) + } + for (const c of s.fileStatus) { + it(`${c.kind} status ${c.status}`, () => { + const e = errorForStatusValue(c.kind, c.status, c.error) + expect(e?.code ?? null).toBe(c.code) + expect(e?.detail ?? null).toBe(c.detail) + }) + } +}) + +describe('spec/v2/batching.json', () => { + const s = spec('batching.json') + it('default', () => expect(s.defaultMaxCharacters).toBe(10_000)) + for (const c of s.cases) { + it(c.name, () => { + const plan = planRequests(c.segments, c.maxCharacters).map((r) => ({ kind: r.kind, keys: r.segments.map((x) => x.key) })) + expect(plan).toEqual(c.batches) + }) + } +}) + +describe('spec/v2/webhooks.json', () => { + const s = spec('webhooks.json') + for (const c of s.cases) { + it(c.name, async () => { + if (c.error) expect(await codeOf(() => verifyWebhook(c.secret, c.headers, c.body, c.now))).toBe(c.error) + else expect(await verifyWebhook(c.secret, c.headers, c.body, c.now)).toEqual(c.event) + }) + } + it('takes a Headers object', async () => { + const c = s.cases[0] + expect(await verifyWebhook(c.secret, new Headers(c.headers), c.body, c.now)).toEqual(c.event) + }) +}) + +describe('spec/v2/api-key-check.json', () => { + const s = spec('api-key-check.json') + for (const c of s.fingerprint) it(`fingerprint ${JSON.stringify(c.apiKey)}`, () => expect(apiKeyFingerprint(c.apiKey)).toBe(c.fingerprint)) + for (const c of s.apiKeyCheck) { + it(`check ${JSON.stringify(c.answer).slice(0, 60)}`, async () => { + const calls: string[] = [] + const fetch: FetchLike = async (url) => { + calls.push(url) + if (c.answer.transportError) throw new TypeError('fetch failed') + return new Response(c.answer.body, { status: c.answer.status }) + } + const check = await new SupertextClient('st_live_abc123', { fetch, now: () => Date.UTC(2026, 10, 1) }).checkApiKey() + expect(check).toEqual({ status: c.status, httpStatus: c.httpStatus, errorCode: c.errorCode, checkedAt: '2026-11-01T00:00:00Z', fingerprint: apiKeyFingerprint('st_live_abc123') }) + expect(calls).toEqual(['https://api-platform.supertext.com/v1/account']) + }) + } + it('a blank key is missing, nothing sent', async () => { + const check = await new SupertextClient('Bearer ', { fetch: async () => expect.unreachable() }).checkApiKey() + expect(check.status).toBe('missing') + }) +}) + +interface Call { + method: string + url: string + headers: Record + body: string +} + +function fake(answers: (Response | ((call: Call) => Response))[]) { + const calls: Call[] = [] + const fetch: FetchLike = async (url, init) => { + const body = init.body ? new TextDecoder().decode(init.body as ArrayBuffer) : '' + const call = { method: init.method ?? 'GET', url, headers: init.headers as Record, body } + calls.push(call) + const next = answers.shift() + if (!next) throw new Error(`unexpected ${call.method} ${url}`) + return typeof next === 'function' ? next(call) : next + } + return { calls, fetch } +} +const json = (value: unknown, status = 200, headers: Record = {}) => new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json', ...headers } }) +const noSleep = async () => {} + +describe('v2 client', () => { + it('is exported as v2 from the package root', () => expect(v2.SupertextClient).toBe(SupertextClient)) + + it('translateText sends the documented body and reads the answer', async () => { + const { calls, fetch } = fake([json({ request_id: 'r1', detected_source_lang: 'en', translated_text: ['Hallo', 'Welt'], enforced_terms: { shop: 'Laden' } })]) + const client = new SupertextClient(' Bearer st_live_k ', { fetch }) + const result = await client.translateText(['Hello', 'World'], 'de-CH', { sourceLang: 'en', politeness: 'more', glossary: { shop: 'Laden' }, tagHandling: 'html' }) + expect(result).toEqual({ translations: ['Hallo', 'Welt'], detectedSourceLang: 'en', enforcedTerms: { shop: 'Laden' }, requestId: 'r1' }) + expect(calls[0]!.url).toBe('https://api-platform.supertext.com/v1/translate/ai/text') + expect(calls[0]!.headers.Authorization).toBe('Bearer st_live_k') + expect(calls[0]!.headers['Content-Type']).toBe('application/json') + expect(JSON.parse(calls[0]!.body)).toEqual({ text: ['Hello', 'World'], target_lang: 'de-CH', source_lang: 'en', politeness: 'more', glossary: { shop: 'Laden' }, tag_handling: 'html' }) + }) + + it('a wrong number of translations is incomplete', async () => { + const { fetch } = fake([json({ translated_text: ['only one'] })]) + expect(await codeOf(() => new SupertextClient('k', { fetch }).translateText(['a', 'b'], 'de-CH'))).toBe('incomplete_response') + }) + + it('retries a 429 with Retry-After, then maps problem+json', async () => { + const waits: number[] = [] + const problem = { code: 'payment_required', detail: 'Top up.', error_id: 'e1', reason: 'insufficient_credit' } + const { calls, fetch } = fake([json({ code: 'rate_limited' }, 429, { 'Retry-After': '2' }), json(problem, 402)]) + const client = new SupertextClient('k', { fetch, sleep: async (ms) => void waits.push(ms) }) + try { + await client.translateText(['a'], 'de-CH') + expect.unreachable() + } catch (e) { + expect(e).toMatchObject({ code: 'insufficient_credit', status: 402, reason: 'insufficient_credit', errorId: 'e1', detail: 'Top up.' }) + } + expect(waits).toEqual([2000]) + expect(calls).toHaveLength(2) + }) + + it('never puts the key into a message', async () => { + const { fetch } = fake([new Response('bad key st_live_secret123', { status: 401 })]) + try { + await new SupertextClient('st_live_secret123', { fetch }).getAccount() + expect.unreachable() + } catch (e) { + expect(String((e as Error).message)).not.toContain('st_live_secret123') + expect((e as SupertextError).detail).toBe('bad key ***') + } + }) + + it('translateTexts: plain and HTML requests, a long segment as a file, blanks kept', async () => { + const { calls, fetch } = fake([ + (c) => json({ translated_text: JSON.parse(c.body).text.map((t: string) => `T:${t}`) }), + (c) => json({ translated_text: JSON.parse(c.body).text.map((t: string) => `H:${t}`) }), + json({ file_id: 'f1' }, 202), + json({ file_id: 'f1', status: 'done' }), + new Response('
LONG
\n', { status: 200, headers: { 'Content-Disposition': 'attachment; filename="content.de-CH.html"' } }), + json({ file_id: 'f1', status: 'deleted' }), + ]) + const client = new SupertextClient('k', { fetch, sleep: noSleep }) + const out = await client.translateTexts({ a: 'one', b: { text: 'two', html: true }, c: ' ', d: 'long text here' }, 'de-CH', { maxCharacters: 10 }) + expect(out).toEqual({ a: 'T:one', b: 'H:two', c: ' ', d: 'LONG' }) + expect(calls.map((c) => `${c.method} ${c.url.replace('https://api-platform.supertext.com/v1/', '')}`)).toEqual([ + 'POST translate/ai/text', + 'POST translate/ai/text', + 'POST translate/ai/file', + 'GET translate/ai/file/f1/status', + 'GET translate/ai/file/f1/translation', + 'DELETE translate/ai/file/f1', + ]) + expect(JSON.parse(calls[0]!.body).tag_handling).toBeUndefined() + expect(JSON.parse(calls[1]!.body).tag_handling).toBe('html') + expect(calls[2]!.body).toContain('Content-Type: text/html\r\n') + expect(calls[2]!.body).toContain('name="target_lang"\r\n\r\nde-CH') + }) + + it('a failed file translation throws translation_error and still deletes', async () => { + const { calls, fetch } = fake([json({ file_id: 'f1' }, 202), json({ status: 'translating' }), json({ status: 'error', error: 'Corrupt.' }), json({})]) + const client = new SupertextClient('k', { fetch, sleep: noSleep }) + try { + await client.translateFile(new Uint8Array([1, 2, 3]), 'a.docx', 'fr-CH', { useOcr: false, glossary: { a: 'b' } }) + expect.unreachable() + } catch (e) { + expect(e).toMatchObject({ code: 'translation_error', detail: 'Corrupt.' }) + } + expect(calls.at(-1)!.method).toBe('DELETE') + expect(calls[0]!.body).toContain('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document') + expect(calls[0]!.body).toContain('name="glossary"\r\n\r\n{"a":"b"}') + expect(calls[0]!.body).toContain('name="use_ocr"\r\n\r\nfalse') + }) + + it('downloads answer null while not ready', async () => { + const { fetch } = fake([json({ status: 'in_progress' }, 202), json({ status: 'in_progress' }, 202), json({ translated_text: 'Geprüft' })]) + const client = new SupertextClient('k', { fetch }) + expect(await client.downloadFile('x')).toBeNull() + expect(await client.getFusedText('t')).toBeNull() + expect(await client.getFusedText('t')).toBe('Geprüft') + }) + + it('fused text order with briefing and idempotency key', async () => { + const { calls, fetch } = fake([json({ translation_id: 'u-1', briefing_applied: true, service_label: 'Optimisation', request_id: 'r' }, 202)]) + const order = await new SupertextClient('k', { fetch }).orderFusedText('Hello', 'en', 'de-CH', { briefing: 'Friendly', idempotencyKey: 'idem-1' }) + expect(order).toEqual({ translationId: 'u-1', briefingApplied: true, serviceLabel: 'Optimisation', requestId: 'r' }) + expect(calls[0]!.headers['Idempotency-Key']).toBe('idem-1') + expect(JSON.parse(calls[0]!.body)).toEqual({ text: 'Hello', source_lang: 'en', target_lang: 'de-CH', briefing: 'Friendly' }) + }) + + it('account, features, detection, quotes', async () => { + const { calls, fetch } = fake([ + json({ workspace_id: 'w', workspace_name: 'W', api_key_name: 'CMS', api_key_prefix: 'st_live_ab', api_key_expires_at: '2027-01-01T00:00:00Z' }), + json({ supported_features: [{ source_lang: 'en', target_lang: 'de-CH', features: ['supports_politeness'] }, { bad: 1 }] }), + json({ detected_languages: [{ lang_code: 'en', confidence: 0.9, supports_translation: true }] }), + json({ character_count: 5, prices: { chf: 0.0001, bad: 'x' } }), + json({ prices: { chf: 12.5 }, estimated_duration_in_seconds: 3600, word_count: 10, briefing_applied: false, service_label: 'Verification' }), + ]) + const client = new SupertextClient('k', { fetch }) + expect((await client.getAccount()).workspaceName).toBe('W') + expect(await client.getFeatures({ sourceLang: 'en', targetLang: 'de-CH' })).toEqual([{ sourceLang: 'en', targetLang: 'de-CH', features: ['supports_politeness'] }]) + expect(calls[1]!.url).toBe('https://api-platform.supertext.com/v1/features?source_lang=en&target_lang=de-CH') + expect(await client.detectLanguage('Hello')).toEqual([{ langCode: 'en', confidence: 0.9, supportsTranslation: true }]) + expect(await client.quoteText(['Hello'], 'de-CH')).toEqual({ characterCount: 5, prices: { chf: 0.0001 } }) + expect(await client.quoteFusedText('Hello', 'en', 'de-CH')).toMatchObject({ prices: { chf: 12.5 }, wordCount: 10, characterCount: null, briefingApplied: false }) + }) + + it('webhooks', async () => { + const hook = { id: 'h1', url: 'https://cms.example/hook', event_types: ['translation.ai_file.completed'], description: null, status: 'active', disabled_reason: null, created_at: '2026-11-01T00:00:00Z', last_delivery_at: null, last_failure_at: null, last_failure_reason: null, consecutive_failures: 0 } + const { calls, fetch } = fake([json({ ...hook, secret: 'whsec_abc' }, 201), json({ items: [hook] }), json({ ...hook, status: 'active' }), new Response(null, { status: 204 }), json({ delivered: true, status_code: 200, error: null, duration_ms: 42 })]) + const client = new SupertextClient('k', { fetch }) + expect((await client.createWebhook({ url: hook.url, eventTypes: hook.event_types })).secret).toBe('whsec_abc') + expect(JSON.parse(calls[0]!.body)).toEqual({ url: hook.url, event_types: hook.event_types }) + expect(await client.listWebhooks()).toHaveLength(1) + await client.updateWebhook('h1', { enabled: true, description: null }) + expect(JSON.parse(calls[2]!.body)).toEqual({ description: null, enabled: true }) + expect(calls[2]!.method).toBe('PATCH') + await client.deleteWebhook('h1') + expect(await client.testWebhook('h1')).toEqual({ delivered: true, statusCode: 200, error: null, durationMs: 42 }) + }) + + it('a blank target or key sends nothing', async () => { + const client = new SupertextClient('k', { fetch: async () => expect.unreachable() }) + expect(await codeOf(() => client.translateTexts({ a: 'x' }, ' '))).toBe('unsupported_language') + expect(await codeOf(() => new SupertextClient(' ', { fetch: async () => expect.unreachable() }).getAccount())).toBe('missing_api_key') + }) + + it('reads file names from Content-Disposition', () => { + expect(filenameFrom('attachment; filename="a b.docx"')).toBe('a b.docx') + expect(filenameFrom("attachment; filename=x.pdf; filename*=UTF-8''Z%C3%BCrich.docx")).toBe('Zürich.docx') + expect(filenameFrom(null)).toBeNull() + }) +}) diff --git a/spec/README.md b/spec/README.md index 812d4e7..8a57356 100644 --- a/spec/README.md +++ b/spec/README.md @@ -15,4 +15,6 @@ Every SDK in this repository loads these files in its tests and must pass every | [`corrections.json`](corrections.json) | Corrections from reviewers (Supertext Localization Review's review service): the requests, paging, which items count, the acknowledge body and batches | | [`conformance.json`](conformance.json) | End-to-end scenarios against the [stand-in](../stand-in/stand-in.mjs) (`node stand-in/conformance.mjs -- `) | +**API v2** has its own folder, [`v2/`](v2/): `openapi.json` (Supertext's description of the API), `auth-header.json` (`Bearer` keys), `errors.json` (problem answers and file/review statuses → error codes), `batching.json` (segments → text, HTML and file requests), `webhooks.json` (signature checks), `api-key-check.json` (the key check on `GET account`) and `conformance.json` (scenarios against [`stand-in-v2.mjs`](../stand-in/stand-in-v2.mjs), `node stand-in/conformance.mjs --v2 -- `). + Changing a vector changes all six SDKs: update the SDKs and their tests in the same commit, and note the behaviour change in `CHANGELOG.md`. diff --git a/spec/v2/api-key-check.json b/spec/v2/api-key-check.json new file mode 100644 index 0000000..ade9eb8 --- /dev/null +++ b/spec/v2/api-key-check.json @@ -0,0 +1,77 @@ +{ + "description": "checkApiKey() of the v2 client: like ../api-key-check.json (same fields, same statuses, Plugin Health stores them), but the request is GET account (cost-free, timeout keyCheckTimeoutSeconds, the usual 429 retries), errorCode is the problem+json `code` (null if none, at most 100 characters) and the fingerprint is the SHA-256 (lower-case hex) of the key as the v2 authHeader() sends it (a pasted `Bearer ` removed); '' for a blank key, which gives missing without a request.", + "keyCheckTimeoutSeconds": 10, + "fingerprint": [ + { + "apiKey": "st_live_abc123", + "fingerprint": "aed3dc82623d07fe2d674bb842d792acef5c94ca837407731f89d3cf00dfde0c" + }, + { + "apiKey": " Bearer st_live_abc123 ", + "fingerprint": "aed3dc82623d07fe2d674bb842d792acef5c94ca837407731f89d3cf00dfde0c" + }, + { + "apiKey": "Bearer", + "fingerprint": "" + }, + { + "apiKey": "", + "fingerprint": "" + } + ], + "apiKeyCheck": [ + { + "answer": { + "status": 200, + "body": "{\"workspace_id\":\"ws_1\",\"workspace_name\":\"W\",\"api_key_name\":\"CMS\",\"api_key_prefix\":\"st_live_abc\",\"api_key_expires_at\":\"2027-01-01T00:00:00Z\"}" + }, + "status": "ok", + "httpStatus": 200, + "errorCode": null + }, + { + "answer": { + "status": 401, + "body": "{\"code\":\"unauthorized\",\"detail\":\"Missing or invalid API key.\",\"status\":401}" + }, + "status": "invalid", + "httpStatus": 401, + "errorCode": "unauthorized" + }, + { + "answer": { + "status": 403, + "body": "{\"code\":\"forbidden\",\"detail\":\"No.\"}" + }, + "status": "invalid", + "httpStatus": 403, + "errorCode": "forbidden" + }, + { + "answer": { + "status": 502, + "body": "Bad gateway" + }, + "status": "unreachable", + "httpStatus": 502, + "errorCode": null + }, + { + "answer": { + "transportError": true + }, + "status": "unreachable", + "httpStatus": null, + "errorCode": null + }, + { + "answer": { + "status": 418, + "body": "{\"code\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}" + }, + "status": "error", + "httpStatus": 418, + "errorCode": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + } + ] +} diff --git a/spec/v2/auth-header.json b/spec/v2/auth-header.json new file mode 100644 index 0000000..97853fb --- /dev/null +++ b/spec/v2/auth-header.json @@ -0,0 +1,49 @@ +{ + "description": "The Authorization header the v2 client sends for an API key as an administrator pasted it. The key is trimmed (ASCII whitespace); a leading `Bearer` (any case) followed by whitespace is stripped, then the rest is trimmed again; exactly one `Bearer ` is sent. An empty result is `missing_api_key`, thrown before anything is sent. Nothing else is changed: a v1 key (`Supertext-Auth-Key …`) is sent as it is and the API answers 401.", + "cases": [ + { + "apiKey": "st_live_abc123", + "header": "Bearer st_live_abc123" + }, + { + "apiKey": " st_live_abc123\n", + "header": "Bearer st_live_abc123" + }, + { + "apiKey": "Bearer st_live_abc123", + "header": "Bearer st_live_abc123" + }, + { + "apiKey": "bearer st_live_abc123", + "header": "Bearer st_live_abc123" + }, + { + "apiKey": "BEARER\tst_live_abc123 ", + "header": "Bearer st_live_abc123" + }, + { + "apiKey": "Bearerst_live_abc123", + "header": "Bearer Bearerst_live_abc123" + }, + { + "apiKey": "Supertext-Auth-Key abc", + "header": "Bearer Supertext-Auth-Key abc" + }, + { + "apiKey": "", + "error": "missing_api_key" + }, + { + "apiKey": " ", + "error": "missing_api_key" + }, + { + "apiKey": "Bearer", + "error": "missing_api_key" + }, + { + "apiKey": "Bearer ", + "error": "missing_api_key" + } + ] +} diff --git a/spec/v2/batching.json b/spec/v2/batching.json new file mode 100644 index 0000000..bdd277c --- /dev/null +++ b/spec/v2/batching.json @@ -0,0 +1,186 @@ +{ + "description": "How the v2 translateTexts splits segments into requests. A segment whose text is empty or only ASCII whitespace (space, tab, CR, LF, FF) is not sent and comes back unchanged. The others go to POST translate/ai/text, plain texts with tag_handling `none` and HTML with `html`, never mixed in one request: first the plain-text requests, then the HTML requests, segments in input order within each. A request takes segments while the sum of their lengths (Unicode code points) stays at or below maxCharacters (default 10000, the API's limit per request); then the next one starts. A segment longer than maxCharacters on its own can't go through the text endpoint: those segments are packed into HTML documents with the v1 rules (../batching.json, at most 900000 characters per document) and translated as files (POST translate/ai/file), after the text requests. Requests run one after the other.", + "defaultMaxCharacters": 10000, + "cases": [ + { + "name": "plain and HTML go into separate requests", + "maxCharacters": 100, + "segments": [ + { + "key": "a", + "text": "Hello", + "html": false + }, + { + "key": "b", + "text": "

World

", + "html": true + }, + { + "key": "c", + "text": "Again", + "html": false + } + ], + "batches": [ + { + "kind": "text", + "keys": [ + "a", + "c" + ] + }, + { + "kind": "html", + "keys": [ + "b" + ] + } + ] + }, + { + "name": "split at the limit; exactly the limit still fits", + "maxCharacters": 10, + "segments": [ + { + "key": "a", + "text": "12345", + "html": false + }, + { + "key": "b", + "text": "12345", + "html": false + }, + { + "key": "c", + "text": "1", + "html": false + } + ], + "batches": [ + { + "kind": "text", + "keys": [ + "a", + "b" + ] + }, + { + "kind": "text", + "keys": [ + "c" + ] + } + ] + }, + { + "name": "blank segments are not sent", + "maxCharacters": 100, + "segments": [ + { + "key": "a", + "text": "", + "html": false + }, + { + "key": "b", + "text": " \t\r\n\f", + "html": true + }, + { + "key": "c", + "text": "x", + "html": false + } + ], + "batches": [ + { + "kind": "text", + "keys": [ + "c" + ] + } + ] + }, + { + "name": "code points, not UTF-16 units", + "maxCharacters": 4, + "segments": [ + { + "key": "a", + "text": "😀😀", + "html": false + }, + { + "key": "b", + "text": "😀😀", + "html": false + } + ], + "batches": [ + { + "kind": "text", + "keys": [ + "a", + "b" + ] + } + ] + }, + { + "name": "a segment over the limit goes into a file, after the text requests", + "maxCharacters": 5, + "segments": [ + { + "key": "big", + "text": "123456", + "html": false + }, + { + "key": "a", + "text": "abc", + "html": false + }, + { + "key": "bightml", + "text": "

12345

", + "html": true + }, + { + "key": "h", + "text": "1", + "html": true + } + ], + "batches": [ + { + "kind": "text", + "keys": [ + "a" + ] + }, + { + "kind": "file", + "keys": [ + "big", + "bightml", + "h" + ] + } + ] + }, + { + "name": "nothing to send", + "maxCharacters": 100, + "segments": [ + { + "key": "a", + "text": " ", + "html": false + } + ], + "batches": [] + } + ] +} diff --git a/spec/v2/conformance.json b/spec/v2/conformance.json new file mode 100644 index 0000000..28021d7 --- /dev/null +++ b/spec/v2/conformance.json @@ -0,0 +1,215 @@ +{ + "description": "End-to-end scenarios every SDK's v2 client passes against the v2 stand-in (node stand-in/conformance.mjs --v2 -- ). Each SDK ships a v2 conformance program: it reads one request as JSON on stdin ({sourceLang, targetLang, politeness, maxCharacters, segments}), translates it with the v2 client's translateTexts (codes passed as given; maxCharacters only when present) using SUPERTEXT_API_URL and SUPERTEXT_API_KEY from the environment (poll interval 100 ms), and prints {\"translations\": {key: text}} or {\"error\": {\"code\": …, \"status\": …}} as JSON on stdout. Exit code 0 in both cases.", + "scenarios": [ + { + "name": "plain and HTML texts in two requests, retry a 429, Bearer header with a pasted prefix stripped, blank kept", + "apiKey": "Bearer st_live_conformance", + "rateLimit": true, + "request": { + "sourceLang": "en", + "targetLang": "de-CH", + "politeness": "more", + "segments": [ + { + "key": "title", + "text": "Hello & welcome", + "html": false + }, + { + "key": "body", + "text": "

Our new shop opens on Monday.

", + "html": true + }, + { + "key": "lines", + "text": "Line 1\nLine 2", + "html": false + }, + { + "key": "blank", + "text": " ", + "html": false + } + ] + }, + "expected": { + "translations": { + "title": "[de-CH] Hello & welcome", + "body": "

[de-CH] Our new shop opens on Monday.

", + "lines": "[de-CH] Line 1\nLine 2", + "blank": " " + } + }, + "expectedStats": { + "textRequests": 2, + "rateLimited": 1, + "submitted": 0, + "lastAuthorization": "Bearer st_live_conformance" + }, + "expectedText": { + "source_lang": "en", + "target_lang": "de-CH", + "politeness": "more", + "tag_handling": "html", + "count": 1 + } + }, + { + "name": "a segment over maxCharacters goes through an HTML file, which is deleted", + "apiKey": "st_live_conformance", + "rateLimit": false, + "request": { + "targetLang": "fr-CH", + "maxCharacters": 10, + "segments": [ + { + "key": "short", + "text": "Hi", + "html": false + }, + { + "key": "long", + "text": "A longer text & more", + "html": false + } + ] + }, + "expected": { + "translations": { + "short": "[fr-CH] Hi", + "long": "[fr-CH] A longer text & more" + } + }, + "expectedStats": { + "textRequests": 1, + "submitted": 1, + "downloads": 1, + "deleted": 1 + }, + "expectedUpload": { + "target_lang": "fr-CH", + "source_lang": null, + "content_type": "text/html" + } + }, + { + "name": "a rejected key", + "apiKey": "invalid", + "rateLimit": false, + "request": { + "targetLang": "de-CH", + "segments": [ + { + "key": "a", + "text": "Hello", + "html": false + } + ] + }, + "expected": { + "error": { + "code": "authentication_failure", + "status": 401 + } + } + }, + { + "name": "no credit left", + "apiKey": "no-credit", + "rateLimit": false, + "request": { + "targetLang": "de-CH", + "segments": [ + { + "key": "a", + "text": "Hello", + "html": false + } + ] + }, + "expected": { + "error": { + "code": "insufficient_credit", + "status": 402 + } + } + }, + { + "name": "a code Supertext doesn't offer is sent as given and rejected", + "apiKey": "st_live_conformance", + "rateLimit": false, + "request": { + "targetLang": "de", + "segments": [ + { + "key": "a", + "text": "Hello", + "html": false + } + ] + }, + "expected": { + "error": { + "code": "invalid_request", + "status": 422 + } + } + }, + { + "name": "a failed file translation", + "apiKey": "st_live_conformance", + "rateLimit": false, + "request": { + "targetLang": "de-CH", + "maxCharacters": 5, + "segments": [ + { + "key": "a", + "text": "STAND-IN:error", + "html": false + } + ] + }, + "expected": { + "error": { + "code": "translation_error", + "status": null + } + }, + "expectedStats": { + "submitted": 1, + "deleted": 1 + } + }, + { + "name": "only blank texts: nothing is sent", + "apiKey": "st_live_conformance", + "rateLimit": false, + "request": { + "targetLang": "de-CH", + "segments": [ + { + "key": "a", + "text": "", + "html": false + }, + { + "key": "b", + "text": " \n", + "html": true + } + ] + }, + "expected": { + "translations": { + "a": "", + "b": " \n" + } + }, + "expectedStats": { + "textRequests": 0, + "submitted": 0 + } + } + ] +} diff --git a/spec/v2/errors.json b/spec/v2/errors.json new file mode 100644 index 0000000..3f4e82b --- /dev/null +++ b/spec/v2/errors.json @@ -0,0 +1,198 @@ +{ + "description": "How v2 API answers map to SupertextError codes. Every v2 error is RFC 9457 problem+json: `apiErrorCode` is the body's `code`, `errorId` its `error_id`, `reason` its `reason` (402), each only when it is a non-empty string (else null). `detail` is the body's `detail` when that is a non-empty string; otherwise the whole body with tags (`<…>`) removed. Either way trimmed (ASCII whitespace) and cut to 200 characters; null when nothing is left. Status mapping: 401 and 403 authentication_failure, 402 insufficient_credit, 404 not_found, 409 conflict, 413 payload_too_large, 422 invalid_request, 429 too_many_requests (after the retries, see ../retry-delay.json, which v2 uses unchanged), every 5xx service_unavailable, anything else unexpected_status. `fileStatus` maps a status a poll returns: AI file `error` is translation_error (detail = the status body's `error`), `deleted` is file_deleted; human review (`fused`) `failed` is translation_error (detail = `error`). Other statuses are not errors (null).", + "http": [ + { + "status": 401, + "body": "{\"type\": \"urn:supertext:error:unauthorized\", \"title\": \"x\", \"status\": 401, \"detail\": \"Missing or invalid API key.\", \"code\": \"unauthorized\", \"error_id\": \"9f1c7a2e\"}", + "code": "authentication_failure", + "apiErrorCode": "unauthorized", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "Missing or invalid API key." + }, + { + "status": 403, + "body": "{\"type\": \"urn:supertext:error:forbidden\", \"title\": \"x\", \"status\": 403, \"detail\": \"This API key may not use human review.\", \"code\": \"forbidden\", \"error_id\": \"9f1c7a2e\"}", + "code": "authentication_failure", + "apiErrorCode": "forbidden", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "This API key may not use human review." + }, + { + "status": 402, + "body": "{\"type\": \"urn:supertext:error:payment_required\", \"title\": \"x\", \"status\": 402, \"detail\": \"The credit balance does not cover this request.\", \"code\": \"payment_required\", \"error_id\": \"9f1c7a2e\", \"reason\": \"insufficient_credit\"}", + "code": "insufficient_credit", + "apiErrorCode": "payment_required", + "errorId": "9f1c7a2e", + "reason": "insufficient_credit", + "detail": "The credit balance does not cover this request." + }, + { + "status": 404, + "body": "{\"type\": \"urn:supertext:error:not_found\", \"title\": \"x\", \"status\": 404, \"detail\": \"No such file.\", \"code\": \"not_found\", \"error_id\": \"9f1c7a2e\"}", + "code": "not_found", + "apiErrorCode": "not_found", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "No such file." + }, + { + "status": 409, + "body": "{\"type\": \"urn:supertext:error:webhook_limit_reached\", \"title\": \"x\", \"status\": 409, \"detail\": \"A workspace can have up to 10 webhooks.\", \"code\": \"webhook_limit_reached\", \"error_id\": \"9f1c7a2e\"}", + "code": "conflict", + "apiErrorCode": "webhook_limit_reached", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "A workspace can have up to 10 webhooks." + }, + { + "status": 413, + "body": "{\"type\": \"urn:supertext:error:payload_too_large\", \"title\": \"x\", \"status\": 413, \"detail\": \"The file is larger than 30 MiB.\", \"code\": \"payload_too_large\", \"error_id\": \"9f1c7a2e\"}", + "code": "payload_too_large", + "apiErrorCode": "payload_too_large", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "The file is larger than 30 MiB." + }, + { + "status": 422, + "body": "{\"type\": \"urn:supertext:error:validation_error\", \"title\": \"x\", \"status\": 422, \"detail\": \"body.target_lang: unsupported target language\", \"code\": \"validation_error\", \"error_id\": \"9f1c7a2e\"}", + "code": "invalid_request", + "apiErrorCode": "validation_error", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "body.target_lang: unsupported target language" + }, + { + "status": 422, + "body": "{\"detail\":[{\"loc\":[\"path\",\"file_id\"],\"msg\":\"bad\",\"type\":\"value_error\"}]}", + "code": "invalid_request", + "apiErrorCode": null, + "errorId": null, + "reason": null, + "detail": "{\"detail\":[{\"loc\":[\"path\",\"file_id\"],\"msg\":\"bad\",\"type\":\"value_error\"}]}" + }, + { + "status": 429, + "body": "{\"type\": \"urn:supertext:error:rate_limited\", \"title\": \"x\", \"status\": 429, \"detail\": \"Too many requests.\", \"code\": \"rate_limited\", \"error_id\": \"9f1c7a2e\"}", + "code": "too_many_requests", + "apiErrorCode": "rate_limited", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "Too many requests." + }, + { + "status": 500, + "body": "

Internal Server Error

", + "code": "service_unavailable", + "apiErrorCode": null, + "errorId": null, + "reason": null, + "detail": "Internal Server Error" + }, + { + "status": 502, + "body": "{\"type\": \"urn:supertext:error:upstream_error\", \"title\": \"x\", \"status\": 502, \"detail\": \" The translation engine did not answer. \", \"code\": \"upstream_error\", \"error_id\": \"9f1c7a2e\"}", + "code": "service_unavailable", + "apiErrorCode": "upstream_error", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "The translation engine did not answer." + }, + { + "status": 503, + "body": "", + "code": "service_unavailable", + "apiErrorCode": null, + "errorId": null, + "reason": null, + "detail": null + }, + { + "status": 400, + "body": "{\"type\": \"urn:supertext:error:bad_request\", \"title\": \"x\", \"status\": 400, \"detail\": \"\", \"code\": \"bad_request\", \"error_id\": \"9f1c7a2e\"}", + "code": "unexpected_status", + "apiErrorCode": "bad_request", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "{\"type\": \"urn:supertext:error:bad_request\", \"title\": \"x\", \"status\": 400, \"detail\": \"\", \"code\": \"bad_request\", \"error_id\": \"9f1c7a2e\"}" + }, + { + "status": 418, + "body": "{\"code\": 5, \"detail\": 7, \"error_id\": \"\"}", + "code": "unexpected_status", + "apiErrorCode": null, + "errorId": null, + "reason": null, + "detail": "{\"code\": 5, \"detail\": 7, \"error_id\": \"\"}" + }, + { + "status": 422, + "body": "{\"type\": \"urn:supertext:error:validation_error\", \"title\": \"x\", \"status\": 422, \"detail\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\", \"code\": \"validation_error\", \"error_id\": \"9f1c7a2e\"}", + "code": "invalid_request", + "apiErrorCode": "validation_error", + "errorId": "9f1c7a2e", + "reason": null, + "detail": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + } + ], + "fileStatus": [ + { + "kind": "file", + "status": "translating", + "error": null, + "code": null, + "detail": null + }, + { + "kind": "file", + "status": "done", + "error": null, + "code": null, + "detail": null + }, + { + "kind": "file", + "status": "error", + "error": "The document could not be read.", + "code": "translation_error", + "detail": "The document could not be read." + }, + { + "kind": "file", + "status": "error", + "error": null, + "code": "translation_error", + "detail": null + }, + { + "kind": "file", + "status": "deleted", + "error": null, + "code": "file_deleted", + "detail": null + }, + { + "kind": "fused", + "status": "in_progress", + "error": null, + "code": null, + "detail": null + }, + { + "kind": "fused", + "status": "completed", + "error": null, + "code": null, + "detail": null + }, + { + "kind": "fused", + "status": "failed", + "error": "The order was cancelled.", + "code": "translation_error", + "detail": "The order was cancelled." + } + ] +} diff --git a/spec/v2/openapi.json b/spec/v2/openapi.json new file mode 100644 index 0000000..8410fab --- /dev/null +++ b/spec/v2/openapi.json @@ -0,0 +1 @@ +{"openapi":"3.1.0","info":{"title":"Supertext API v1","description":"A RESTful API for translating text with AI, and for finding out what a\ntranslation will cost before you ask for it.\n\n### Use Cases\n\n`/translate/ai/text` translates plain text instantly with large language\nmodels. Use it to make a website or an application available in more\nlanguages.\n\n`/translate/ai/file` translates a whole document and gives it back in the\nsame format. It answers with a `file_id` rather than a translation, because\nextracting, translating and reassembling a document takes longer than a\nrequest should stay open; poll the id and download the result when it is\nready.\n\n`/translate/fused/text` translates text and has a human expert review the\nresult before you get it. Use it for the copy you cannot afford to get wrong —\nkey messages, legal or safety-critical wording, the pages most of your users\nsee. It answers with an id to poll rather than a translation, because a person\nhas to do the work; delivery is minutes during covered hours.\n\n`/translate/fused/file` is the same service for a whole document: it is\ntranslated and a reviewer works on the result, and what you download at the end\nis the reviewed document, not a machine translation of it.\n\nAdding a `briefing` to either request orders **Optimisation** instead of\nVerification: the reviewer works to your instructions — tone, audience, what\nthe text is for — rather than only checking that the translation is correct. It\nis the same endpoint and the same call sequence; the briefing changes the price,\nthe delivery time and how much text you may send.\n\n`/detect-languages/text` identifies the language a text is written in. If your\ngoal is to translate text whose language you do not know, you do not need this\nendpoint — omit `source_lang` from the translation request instead and the\nanswer comes back as `detected_source_lang`, at no extra cost.\n\nThe supported language pairs, and which features each pair supports, come from\n`/features`. Languages are [BCP 47 tags](https://en.wikipedia.org/wiki/IETF_language_tag).\n\n### Authentication\n\nEvery endpoint requires an API key. Workspace admins create and revoke keys in\nthe Supertext workspace under API keys; a key belongs to one workspace and\ninherits that workspace's plan, entitlements and billing.\n\nThe key goes in the `Authorization` header as a bearer token:\n\n Authorization: Bearer st_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\nA key is shown once, when it is created, and stored only as a hash — so it\ncannot be recovered afterwards, only replaced. Revoking a key takes effect\nimmediately.\n\n### Usage Costs\n\nThese endpoints incur usage costs:\n\n- `/translate/ai/text`\n- `/detect-languages/text`\n- `/translate/ai/file`\n- `/detect-languages/file`\n- `/translate/fused/text`\n- `/translate/fused/file`\n\nEach has a `/quote` sibling that takes **the same payload** and answers what\nthe real call would cost. Validation runs there too, so a quote doubles as a\ndry run: an unsupported language pair or an oversized request fails on the\nquote exactly as it would on the translation.\n\nA quote answers `prices`, keyed by lower-case currency code — one entry, your\nworkspace's own billing currency. It is deliberately not rounded to the cent,\nbecause nothing is charged per request: usage accrues in characters and is\npriced on the accumulated total, so a single request's share of the bill is a\nfraction of a cent and that fraction is what you are told.\n\nHuman review is charged differently from machine translation, because it is\ndifferent work. A `/translate/fused/text` order is priced per **word** of your\nsource text, with a minimum charge per order, and the amount is taken from your\ncredit balance the moment the order is accepted — the same price the same\nservice costs when ordered from the Supertext workspace. The machine\ntranslation that produces the reviewer's draft is **included in that price**;\nit is not metered separately, in the same way that detecting the language of a\ntranslation you did not label costs nothing extra.\n\n**API and MCP usage draws on your plan's quota first.** Each plan includes a\nquota of characters per month (per year on a yearly plan), shared by this API\nand the MCP server, and it resets with your billing period. Only the characters\npast it are charged. It is separate from the characters included for use of\nthe Supertext workspace itself, which API usage never draws on.\n\nCharacters past the quota are paid from the workspace's credit balance. A\nrequest whose slice past the quota the balance cannot cover is refused with\n**402** rather than queued, and the response's `reason`\nsays which case it is: `insufficient_credit` means top up (or switch automatic\ntop-up on, which is what an unattended integration wants). Usage accrues in\ncharacters and is priced periodically, so a 402 reflects what is already owed\nplus what you just asked for.\n\n### Limits\n\nSize limits cap one request; rate limits cap how many requests you may send\nper second, per key. Exceeding a rate limit returns **429** with a\n`Retry-After` header — read that header rather than hardcoding a backoff.\n\n| Endpoint | Size | Rate |\n|---|---|---|\n| `/translate/ai/text` | 10,000 characters, 100 terms | 5/s |\n| `/translate/ai/text/quote` | same | 10/s |\n| `/detect-languages/text` | first 500 characters read | 10/s |\n| `/detect-languages/text/quote` | same | 10/s |\n| `/translate/ai/file` | 30 MiB | 1/s |\n| `/translate/ai/file/quote` | same | 10/s |\n| `/detect-languages/file` | 30 MiB | 1/s |\n| `/detect-languages/file/quote` | same | 10/s |\n| `/translate/fused/text` | 3,000 characters, or 12,000 with a briefing | 1/s |\n| `/translate/fused/text/quote` | same | 10/s |\n| `/translate/fused/file` | 30 MiB | 1/s |\n| `/translate/fused/file/quote` | same | 10/s |\n| `/features` | — | 10/s |\n| `/webhooks` (every method) | 10 webhooks per workspace | 1/s |\n| `/webhooks/{webhook_id}/test` | — | 1 per 5 s |\n\nThis list is not exhaustive, and limits may change without a new API version.\n\n### Errors\n\nEvery error is `application/problem+json` ([RFC 9457](https://www.rfc-editor.org/rfc/rfc9457)):\n\n {\n \"type\": \"urn:supertext:error:validation_error\",\n \"title\": \"Unprocessable Entity\",\n \"status\": 422,\n \"detail\": \"body.target_lang: unsupported target language\",\n \"code\": \"validation_error\",\n \"error_id\": \"9f1c7a2e\"\n }\n\n`detail` is always a string and is safe to show to a person. `code` is the\nstable slug to branch on in code. Errors carry an `error_id`; quote it when\nreporting a problem.\n\n### Response headers\n\nEvery response carries an `X-Request-ID`, also returned as `request_id` in the\nbodies that have one; quote it with any support request. A **429** carries\n`Retry-After` (seconds) and a **401** carries `WWW-Authenticate`. A download\ncarries `Content-Disposition` with the file name. The rest — `Cache-Control`,\n`Strict-Transport-Security`, `Content-Security-Policy`,\n`X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`,\n`Permissions-Policy` — are standard security headers a client can ignore.\n\n### Webhooks\n\nInstead of polling, register a webhook: an HTTPS URL that we call when\nsomething happens — a translation finishes, or the workspace needs attention.\nPolling keeps working; a webhook tells you when to look.\n\nA webhook belongs to the API key that created it. A key lists, changes, tests\nand deletes only its own webhooks, and translation events go only to the\nwebhooks of the key that started the translation. Workspace events go to every\nwebhook in the workspace that subscribed to them. A webhook stops when its key\nis revoked or expires. A workspace can have up to 10 webhooks.\n\nA webhook subscribes to an explicit list of event types; there is no wildcard.\n\n| Event type | Sent when | Sample `data` |\n|---|---|---|\n| `translation.ai_file.completed` | An API-started AI file translation finishes successfully. | `{\"file_id\": \"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}` |\n| `translation.ai_file.failed` | An API-started AI file translation fails. | `{\"file_id\": \"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\", \"error\": \"The document could not be translated.\"}` |\n| `translation.fused_text.completed` | An API-ordered Fused text translation is delivered. | `{\"translation_id\": \"0e9b7c52-6a1d-4f3e-8b2a-9c4d5e6f7a81\"}` |\n| `translation.fused_file.completed` | An API-ordered Fused file translation is delivered. | `{\"translation_id\": \"7d3f9a12-4b6c-4e8d-a1f2-3c5b7d9e0f14\"}` |\n| `translation.fused_file.failed` | An API-ordered Fused file translation fails. | `{\"translation_id\": \"7d3f9a12-4b6c-4e8d-a1f2-3c5b7d9e0f14\", \"error\": \"The document could not be translated.\"}` |\n| `wallet.low_balance` | The wallet balance newly drops below its low-balance threshold. | `{\"currency\": \"CHF\", \"balance\": \"18.40\"}` |\n| `wallet.topped_up` | A wallet top-up is finalised, manual or automatic. | `{\"top_up_id\": \"c41a8e3d-2b7f-4d9a-8e1c-6f5b3a2d9e07\", \"currency\": \"CHF\", \"amount\": \"200.00\", \"balance\": \"218.40\"}` |\n| `invoice.issued` | An invoice PDF is issued. | `{\"invoice_id\": \"a9e2d7c4-1f3b-4a6e-9d8c-2b5f7e1a3c60\", \"issued_at\": \"2026-11-01T00:04:31Z\"}` |\n| `subscription.payment_failed` | The subscription goes past due after a failed payment. | `{\"plan_code\": \"growth\"}` |\n| `subscription.payment_recovered` | The subscription is restored after a payment succeeds. | `{\"plan_code\": \"growth\"}` |\n| `api_key.expiring` | An API key is 30 days, and again 7 days, from its expiry. | `{\"api_key_id\": \"3e7b1d9f-5c2a-4f8e-b6d1-8a4c2e9f7b35\", \"name\": \"CMS plugin\", \"expires_at\": \"2026-12-01T09:00:00Z\", \"days_left\": 30}` |\n| `api_key.revoked` | An API key is revoked. | `{\"api_key_id\": \"3e7b1d9f-5c2a-4f8e-b6d1-8a4c2e9f7b35\", \"name\": \"CMS plugin\", \"revoked_at\": \"2026-10-28T15:42:07Z\"}` |\n\n**Good to know about individual events.** Some events have conditions the table does not show:\n\n- `api_key.revoked` is never sent to the webhooks of the key that was revoked:\n they are deleted first. Only the workspace's other webhooks hear of it.\n- `wallet.low_balance` is sent at most once every 24 hours\n per wallet, not when a wallet is first seen, nor after its threshold is\n changed. It is sent only when the balance crosses below the threshold.\n- `invoice.issued` is sent only when the invoice is issued within\n 24 hours of its payment; an invoice that turns up later\n is not announced. `invoice.issued` `issued_at` is the invoice date, which\n is the payment time; for a top-up the `invoice_id` equals the `top_up_id`.\n- `wallet.topped_up` `amount` is the credits added, not the price paid. In\n every event, amounts are strings with 2 decimal places and the currency is\n upper-case, for example `\"18.40\"` and `\"CHF\"`.\n- `api_key.expiring` is sent at 30 days and again at 7 days before expiry, at most one\n warning per hourly run: a key first seen inside the 7-day window gets only\n that one.\n- `translation.fused_file.completed` can be held for up to\n 5 minutes, until the translated\n document is ready to download.\n\n**Payloads never contain content.** An event carries ids, statuses and\namounts — never text, documents or download links. Fetch the result with your\nAPI key, from the endpoint you would otherwise poll. The `error` of a `failed`\nevent is always the same generic message; call that endpoint's `/status` for\nthe detail.\n\nEvery event is a `POST` with a JSON body:\n\n POST https://cms.example.com/hooks/supertext\n content-type: application/json\n user-agent: Supertext-Webhooks/1\n webhook-id: 2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60\n webhook-timestamp: 1761656713\n webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=\n\n {\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}\n\n`timestamp` in the body is when the event happened, in UTC; `webhook-timestamp`\nis when this attempt was sent, in Unix seconds.\n\n**Verify every request.** Requests are signed the\n[Standard Webhooks](https://www.standardwebhooks.com) way: `webhook-signature`\nis `v1,` followed by the base64 HMAC-SHA256 of\n`{webhook-id}.{webhook-timestamp}.{body}`, keyed with your secret (the\nbase64 part after `whsec_`, decoded). Check it against the raw body, before\nany JSON parsing, and reject a request whose timestamp is more than a few\nminutes old.\nThe Standard Webhooks libraries do all of this. In Python, with the\n`standardwebhooks` package:\n\n from standardwebhooks.webhooks import Webhook\n\n webhook = Webhook(secret) # the whsec_... value from the create response\n event = webhook.verify(raw_body, headers) # raises unless the request is ours\n\nLibraries exist for JavaScript, PHP, Go, Java, Ruby, C#, Rust and more; see\n[standardwebhooks.com](https://www.standardwebhooks.com).\n\n**Source IPs are not fixed.** Requests can come from any address and the\naddresses change without notice, so verify the signature instead of\nallowlisting IPs.\n\n**Answer with a 2xx, quickly.** Any 2xx is a success. Anything else — another\nstatus, a redirect (never followed), or no answer within\n10 seconds — is a failed attempt. Answer first and do\nthe work afterwards.\n\n**Retries.** After each failed attempt the event is sent again, waiting\n5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h in turn. After the 8th failed attempt it is given up.\n\n**At least once, in any order.** An event can arrive more than once:\n`webhook-id` is the same on every retry, so deduplicate on it. Events are not\nguaranteed to arrive in the order they happened.\n\n**Disabled webhooks.** A webhook that answers `410 Gone` is disabled at once.\nOne that has failed 20 attempts in a row and not succeeded\nfor 5 days is disabled too; the 5\ndays run from the last success, or from when you created or re-enabled the\nwebhook, whichever is latest. A disabled webhook shows\n`status: disabled` with a `disabled_reason` (`gone` or `failing`), and the\nevents still waiting for it are cancelled. Once your endpoint is fixed,\nre-enable it with `PATCH /webhooks/{webhook_id}` and `{\"enabled\": true}`.\n\n**Testing.** `POST /webhooks/{webhook_id}/test` sends a `webhook.test`\nevent straight away, with `data` set to `{\"webhook_id\": \"5b0c1e7a-3d2f-4c8e-9a61-2f7d8e4b1c90\"}`, and answers with what\nyour endpoint replied. It is not retried and does not count as a failure. You cannot\nsubscribe to `webhook.test`.\n","version":"1.0.0"},"servers":[{"url":"https://api-platform.supertext.com/v1"}],"paths":{"/translate/ai/text":{"post":{"tags":["Text Translation"],"summary":"AI translation","description":"Translate plain text, with optional glossary terms, formality control and tag\nhandling.\n\n**This endpoint incurs usage costs.**\n\nSend one or several strings in `text`; each is translated independently and the\nresults come back in the same order. Omit `source_lang` to have it detected —\nthe detected language is reported as `detected_source_lang`, and detection\ncosts nothing extra because the translation pays for the text anyway.\n\nAsk `/features` whether the pair you want supports `politeness` or a\n`glossary`. Sending either for a pair that does not support it is refused\nrather than silently ignored.\n\n**Limits:** 10,000 characters per request (the total across\n`text`), 100 glossary terms, 5\nrequest(s) per second.","operationId":"translate_text_translate_ai_text_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TextTranslationIn"},"examples":{"plain":{"summary":"Plain translation","description":"One string, from a stated source language into one target variant.","value":{"text":["Your order has been shipped."],"source_lang":"en","target_lang":"de-CH"}},"unspecified-source-language":{"summary":"Unspecified source language","description":"Leave `source_lang` out and the language is identified on the way through, and reported as `detected_source_lang`. This is the cheap way to handle text of unknown origin: the translation pays for the characters anyway, so the detection adds nothing.","value":{"text":["This is the house where Gaudí spent almost 20 years of his life."],"target_lang":"de-CH"}},"several-strings":{"summary":"Several strings in one request","description":"Each string is translated independently and answered in the same order. The character limit applies to the total, not to each one.","value":{"text":["Sign in","Sign out","Your account"],"source_lang":"en","target_lang":"fr-CH"}},"glossary":{"summary":"With enforced glossary terms","description":"Source-to-target term pairs, enforced for this request only. The response's `enforced_terms` reports which ones were actually applied. Check `/features` first: not every target can enforce terms.","value":{"text":["The annual report was approved by the board of directors."],"source_lang":"en","target_lang":"de-CH","glossary":{"annual report":"Geschäftsbericht","board of directors":"Verwaltungsrat"}}},"politeness":{"summary":"With formality control","description":"`default`, `more` or `less`. Meaningless in some targets - English among them - so `/features` is where you check.","value":{"text":["Please read the manual."],"source_lang":"en","target_lang":"de-CH","politeness":"more"}},"tags":{"summary":"With inline markup","description":"`xml` or `html`: markup is preserved and repositioned to fit the translation rather than translated as text.","value":{"text":["The organisation published a new CSR report."],"source_lang":"en","target_lang":"de-CH","tag_handling":"html"}}}}},"required":true},"responses":{"200":{"description":"The translation, one entry per input string, in the order sent.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TextTranslationOut"},"example":{"request_id":"3feaf4c487b281fc144850525116797f","detected_source_lang":"en","translated_text":["Ihre Bestellung wurde versandt."]}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"402":{"description":"The part of the request past the plan's API & MCP quota is pay-as-you-go, and the workspace's credit balance cannot cover it, so `reason` is `insufficient_credit`. `included_chars` / `used_chars` are the quota and what the window has used of it.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:quota_exceeded","title":"Payment Required","status":402,"detail":"This workspace's credit balance can't cover this request. Top up the balance, or switch automatic top-up on.","code":"quota_exceeded","error_id":"9f1c7a2e","reason":"insufficient_credit","included_chars":1000000,"used_chars":1000000,"payg":true}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}}},"security":[{"Workspace API key":[]}]}},"/translate/ai/text/quote":{"post":{"tags":["Text Translation"],"summary":"AI translation quote","description":"What a translation would cost.\n\nTakes the same payload as `/translate/ai/text`, so you can price the exact call\nyou are about to make by re-sending it. Nothing is translated, nothing is\nmetered, and no usage is recorded. Validation still runs, which makes this a\ndry run as well as a price.\n\n`prices` gives what these characters cost, keyed by your workspace's billing\ncurrency in lower case (`{\"chf\": 0.00056}`). The price is what the request\nwould cost beyond your plan's API & MCP quota at the time of the quote, so it\nis `0.0` while the request fits inside the quota. It is not rounded to the\ncent, because usage is priced on an accumulated character total rather than\nper request.\n\nQuotes are not gated on your balance: the moment you most need to ask the price\nis the moment you have run out.\n\n**Limits:** 10 request(s) per second.","operationId":"quote_text_translate_ai_text_quote_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TextTranslationIn"},"examples":{"plain":{"summary":"Plain translation","description":"One string, from a stated source language into one target variant.","value":{"text":["Your order has been shipped."],"source_lang":"en","target_lang":"de-CH"}},"unspecified-source-language":{"summary":"Unspecified source language","description":"Leave `source_lang` out and the language is identified on the way through, and reported as `detected_source_lang`. This is the cheap way to handle text of unknown origin: the translation pays for the characters anyway, so the detection adds nothing.","value":{"text":["This is the house where Gaudí spent almost 20 years of his life."],"target_lang":"de-CH"}},"several-strings":{"summary":"Several strings in one request","description":"Each string is translated independently and answered in the same order. The character limit applies to the total, not to each one.","value":{"text":["Sign in","Sign out","Your account"],"source_lang":"en","target_lang":"fr-CH"}},"glossary":{"summary":"With enforced glossary terms","description":"Source-to-target term pairs, enforced for this request only. The response's `enforced_terms` reports which ones were actually applied. Check `/features` first: not every target can enforce terms.","value":{"text":["The annual report was approved by the board of directors."],"source_lang":"en","target_lang":"de-CH","glossary":{"annual report":"Geschäftsbericht","board of directors":"Verwaltungsrat"}}},"politeness":{"summary":"With formality control","description":"`default`, `more` or `less`. Meaningless in some targets - English among them - so `/features` is where you check.","value":{"text":["Please read the manual."],"source_lang":"en","target_lang":"de-CH","politeness":"more"}},"tags":{"summary":"With inline markup","description":"`xml` or `html`: markup is preserved and repositioned to fit the translation rather than translated as text.","value":{"text":["The organisation published a new CSR report."],"source_lang":"en","target_lang":"de-CH","tag_handling":"html"}}}}},"required":true},"responses":{"200":{"description":"What the same request would cost, in the workspace's own billing currency. Not rounded to the cent: usage is priced on an accumulated character total, so one request's share of the bill is a fraction of a cent.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TextQuoteOut"},"example":{"character_count":28,"prices":{"chf":0.00056}}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}}},"security":[{"Workspace API key":[]}]}},"/translate/fused/text":{"post":{"tags":["Text Translation"],"summary":"Fused translation","description":"Translate text and have a human expert review the result.\n\n**This endpoint incurs usage costs.**\n\nThis is an asynchronous operation: several HTTP requests are needed to get the\nfinished text.\n\n1. *(optional)* Ask `/translate/fused/text/quote` what it will cost and when it\n will be delivered. Same payload, nothing charged.\n2. `POST /translate/fused/text`. Keep the `translation_id` from the response.\n3. Poll `GET /translate/fused/text/{translation_id}/status` — once a minute is\n a sensible interval. `estimated_duration_left_in_seconds` tells you how long\n is left, and goes negative if the promised time has passed.\n4. When `status` is `completed`, fetch the text from\n `GET /translate/fused/text/{translation_id}/translation`.\n\nThe price covers the whole thing — the machine translation and the review.\n`/translate/fused/text/quote` reports it before you commit.\n\n**A `briefing` orders Optimisation instead of Verification.** Without one, a\nreviewer checks that the translation is correct. With one, the reviewer also\nworks the text to your instructions. You will get back `briefing_applied` so\nyou can tell which service you bought without parsing the name, and\n`service_label` for showing a person. Branch on the boolean, not the label —\nthe names may change.\n\n`source_lang` is required here, unlike on `/translate/ai/text`: the order is\npriced and routed to a linguist before anything is translated, and both need\nthe language pair up front.\n\nNot every language pair can be reviewed by a human — it depends on there being\na linguist for that direction. `/features` marks the ones that can with\n`supports_fused_translation`. Sending an unsupported pair is refused before\nanything is charged.\n\n**Limits:** 3,000 characters per request, or 12,000 with a\nbriefing; 1 request(s) per second.","operationId":"order_fused_translation_translate_fused_text_post","security":[{"Workspace API key":[]}],"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"schema":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"description":"Send the same key again and the order it placed is returned instead of a second one.","title":"Idempotency-Key"},"description":"Send the same key again and the order it placed is returned instead of a second one."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedTranslationIn"},"examples":{"verification":{"summary":"Verification (no briefing)","description":"A reviewer checks that the translation is correct. This is the default.","value":{"text":"Your order has been shipped and will arrive within three working days.","source_lang":"en","target_lang":"de-CH"}},"optimisation":{"summary":"Optimisation (with a briefing)","description":"Adding `briefing` orders Optimisation instead: the reviewer works the text to your instructions rather than only checking it. Costs more, takes longer, and allows a longer text.","value":{"text":"Our platform helps teams ship faster. Book a demo today and see how much time you could save.","source_lang":"en","target_lang":"fr-CH","politeness":"more","briefing":"Marketing copy for a landing page aimed at IT decision makers. Keep it concise and confident; address the reader formally."}},"politeness":{"summary":"Formality control","description":"Sets the formality of the machine translation the reviewer starts from.","value":{"text":"Please read the manual before using the device.","source_lang":"en","target_lang":"de-CH","politeness":"more"}}}}}},"responses":{"202":{"description":"The order was accepted and a reviewer will deliver it. Keep `translation_id` and poll the status endpoint. `briefing_applied` says which service was ordered.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedTranslationAcceptedOut"},"example":{"request_id":"3feaf4c487b281fc144850525116797f","translation_id":"8f1a5d3c-2b47-4e69-9c0a-7d5e1f2b3a44","briefing_applied":false,"service_label":"Verification"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"402":{"description":"The part of the request past the plan's API & MCP quota is pay-as-you-go, and the workspace's credit balance cannot cover it, so `reason` is `insufficient_credit`. `included_chars` / `used_chars` are the quota and what the window has used of it.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:quota_exceeded","title":"Payment Required","status":402,"detail":"This workspace's credit balance can't cover this request. Top up the balance, or switch automatic top-up on.","code":"quota_exceeded","error_id":"9f1c7a2e","reason":"insufficient_credit","included_chars":1000000,"used_chars":1000000,"payg":true}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"503":{"description":"Human review cannot be ordered right now: the fulfilment system is unreachable, or this service has no pricing or delivery configuration. None of it is caused by the request, and all of it clears without the caller doing anything.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:service_unavailable","title":"Service Unavailable","status":503,"detail":"Human review is not available right now. Please try again later.","code":"service_unavailable","error_id":"9f1c7a2e"}}}}}}},"/translate/fused/text/{translation_id}/status":{"get":{"tags":["Text Translation"],"summary":"Fused translation status","description":"Where a human-assisted translation has got to.\n\n`in_progress` covers everything before delivery, whether or not a reviewer has\nstarted. `completed` means the text is ready to fetch. `failed` means the order\nwas cancelled and no text is coming — check it rather than polling forever.\n\n`estimated_duration_left_in_seconds` counts down to the delivery time promised\nwhen the order was placed. A negative number means that time has passed; the\norder is still being worked on, and the number says by how much it is late.","operationId":"fused_translation_status_translate_fused_text__translation_id__status_get","security":[{"Workspace API key":[]}],"parameters":[{"name":"translation_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The `translation_id` from the order response.","title":"Translation Id"},"description":"The `translation_id` from the order response."}],"responses":{"200":{"description":"Where the order has got to. `estimated_duration_left_in_seconds` goes negative once the promised delivery time has passed.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedTranslationStatusOut"},"example":{"status":"in_progress","detected_source_lang":"en","estimated_duration_left_in_seconds":434}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No order with that id belongs to this workspace. An id from another workspace and an id that never existed give the same answer.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:not_found","title":"Not Found","status":404,"detail":"No such translation id.","code":"not_found","error_id":"9f1c7a2e"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/translate/fused/text/{translation_id}/translation":{"get":{"tags":["Text Translation"],"summary":"Fused translation download","description":"Download a human-assisted translation once a reviewer has delivered it.\n\n**202** with `\"status\": \"in_progress\"` while the order is still open —\nthe id is valid, the text just is not ready. Poll the status endpoint rather\nthan retrying this one on a tight loop.\n\nThe text stays available for as long as the order is kept in your workspace, so\nyou can fetch it more than once.","operationId":"fused_translation_result_translate_fused_text__translation_id__translation_get","security":[{"Workspace API key":[]}],"parameters":[{"name":"translation_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The `translation_id` from the order response.","title":"Translation Id"},"description":"The `translation_id` from the order response."}],"responses":{"200":{"description":"The reviewed translation.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedTranslationDownloadOut"},"example":{"translated_text":"Ihre Bestellung wurde versandt und kommt innerhalb von drei Werktagen an."}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No order with that id belongs to this workspace. An id from another workspace and an id that never existed give the same answer.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:not_found","title":"Not Found","status":404,"detail":"No such translation id.","code":"not_found","error_id":"9f1c7a2e"}}}},"202":{"description":"The order exists but no reviewer has delivered it yet. Poll the status endpoint rather than retrying this one.","content":{"application/json":{"example":{"status":"in_progress","detail":"This translation is not ready yet. Check the status endpoint."}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/translate/fused/text/quote":{"post":{"tags":["Text Translation"],"summary":"Fused translation quote","description":"What a human-assisted translation would cost, and when it would be delivered.\n\nTakes the same payload as `/translate/fused/text`, including the `briefing`,\nwhich is what decides both numbers. Nothing is translated, nothing is metered,\nno order is placed and no reviewer is engaged.\n\n`prices` is what the call costs, in your workspace's billing currency: the\nreview, priced per source word with a per-order minimum. The machine\ntranslation is included in it. `word_count` is the unit the price is computed\nfrom, so you can see where the number comes from.\n\n`estimated_duration_in_seconds` is measured from now and accounts for our\nreview hours, so a request sent at the end of a working day is quoted longer\nthan the same request sent at the start of one. It is an estimate, not a\nguarantee.\n\nValidation runs here too, so this doubles as a dry run: an unsupported pair, an\noversized text or a service we cannot currently deliver fails on the quote\nexactly as it would on the order.\n\nQuotes are not gated on your balance.\n\n**Limits:** 10 request(s) per second.","operationId":"quote_fused_translation_translate_fused_text_quote_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedTranslationIn"},"examples":{"verification":{"summary":"Verification (no briefing)","description":"A reviewer checks that the translation is correct. This is the default.","value":{"text":"Your order has been shipped and will arrive within three working days.","source_lang":"en","target_lang":"de-CH"}},"optimisation":{"summary":"Optimisation (with a briefing)","description":"Adding `briefing` orders Optimisation instead: the reviewer works the text to your instructions rather than only checking it. Costs more, takes longer, and allows a longer text.","value":{"text":"Our platform helps teams ship faster. Book a demo today and see how much time you could save.","source_lang":"en","target_lang":"fr-CH","politeness":"more","briefing":"Marketing copy for a landing page aimed at IT decision makers. Keep it concise and confident; address the reader formally."}},"politeness":{"summary":"Formality control","description":"Sets the formality of the machine translation the reviewer starts from.","value":{"text":"Please read the manual before using the device.","source_lang":"en","target_lang":"de-CH","politeness":"more"}}}}},"required":true},"responses":{"200":{"description":"What the same request costs and how long delivery is expected to take. `prices` is the whole price: the per-word review charge, with the machine translation included.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedTranslationQuoteOut"},"example":{"prices":{"chf":5.7},"estimated_duration_in_seconds":480,"word_count":12,"briefing_applied":false,"service_label":"Verification"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"503":{"description":"Human review cannot be ordered right now: the fulfilment system is unreachable, or this service has no pricing or delivery configuration. None of it is caused by the request, and all of it clears without the caller doing anything.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:service_unavailable","title":"Service Unavailable","status":503,"detail":"Human review is not available right now. Please try again later.","code":"service_unavailable","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/translate/ai/file":{"post":{"tags":["File Translation"],"summary":"AI file translation","description":"Translate a document and get it back in the same format.\n\n**This endpoint incurs usage costs.**\n\nSend the file as `multipart/form-data`. This is an asynchronous operation:\n\n1. *(optional)* Ask `/translate/ai/file/quote` what it will cost. Same form\n body, nothing charged.\n2. `POST /translate/ai/file`. Keep the `file_id` from the response.\n3. Poll `GET /translate/ai/file/{file_id}/status` — every few seconds is\n plenty.\n4. When `status` is `done`, download the translated document from\n `GET /translate/ai/file/{file_id}/translation`.\n\nSupported formats: `DOCX`, `PPTX`, `XLSX`, `PDF`, `HTML`, `TXT`, `SRT`. A PDF comes back as a DOCX, because a\ntranslated PDF has to be rebuilt as an editable document.\n\n`use_ocr` applies to PDFs only. Set it when the document is a scan, or when\nits text layer is unreliable — leaving it off on such a file yields an empty\nor garbled translation rather than an error.\n\n`glossary` is a JSON object of source → target terms, sent as a **string**\ninside the form field. At most 100 terms.\n\n**You are charged for the characters the document turns out to hold**, which\nis not knowable until it has been extracted. The upload checks that your\nbalance can be charged at all and refuses immediately if it cannot; the real\ncharge lands when the translation finishes.\n\n**Limits:** 30 MiB per file, 1 request(s)\nper second.","operationId":"translate_file_translate_ai_file_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_translate_file_translate_ai_file_post"}}},"required":true},"responses":{"202":{"description":"The document was accepted. Keep `file_id` and poll the status endpoint.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FileTranslationOut"},"example":{"request_id":"3feaf4c487b281fc144850525116797f","file_id":"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"402":{"description":"The part of the request past the plan's API & MCP quota is pay-as-you-go, and the workspace's credit balance cannot cover it, so `reason` is `insufficient_credit`. `included_chars` / `used_chars` are the quota and what the window has used of it.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:quota_exceeded","title":"Payment Required","status":402,"detail":"This workspace's credit balance can't cover this request. Top up the balance, or switch automatic top-up on.","code":"quota_exceeded","error_id":"9f1c7a2e","reason":"insufficient_credit","included_chars":1000000,"used_chars":1000000,"payg":true}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"413":{"description":"The uploaded document is larger than the per-file limit.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:request_entity_too_large","title":"Request Entity Too Large","status":413,"detail":"This file is 41 943 040 bytes; the limit is 31 457 280 (30 MiB).","code":"request_entity_too_large","error_id":"9f1c7a2e"}}}},"415":{"description":"file-translation-service cannot read this format. The message names the ones it can.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:unsupported_media_type","title":"Unsupported Media Type","status":415,"detail":"This file format can't be translated. Supported formats: DOCX, PPTX, XLSX, PDF, HTML, TXT, SRT.","code":"unsupported_media_type","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/translate/ai/file/{file_id}/status":{"get":{"tags":["File Translation"],"summary":"AI file translation status","description":"Where a file translation has got to.\n\n`translating` covers everything before the document is ready — extraction,\ntranslation and reassembly are our stages, not yours. Then `done`, or `error`\nwith a message, or `deleted` if you withdrew the document.\n\nPolling this is also what finalises the charge for the translation, so keep\npolling until you see a terminal status.","operationId":"file_status_translate_ai_file__file_id__status_get","security":[{"Workspace API key":[]}],"parameters":[{"name":"file_id","in":"path","required":true,"schema":{"type":"string","description":"The `file_id` from the upload response.","title":"File Id"},"description":"The `file_id` from the upload response."}],"responses":{"200":{"description":"Where the translation has got to. Keep polling until `done`, `error` or `deleted`.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FileTranslationStatusOut"},"example":{"file_id":"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30","status":"translating","detected_source_lang":"en"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No document with that id belongs to this workspace. An id from another workspace and an id that never existed give the same answer.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:not_found","title":"Not Found","status":404,"detail":"No such file id.","code":"not_found","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/translate/ai/file/{file_id}/translation":{"get":{"tags":["File Translation"],"summary":"AI file translation download","description":"Download the translated document once it is ready.\n\nThe response is the file itself, with a `Content-Disposition` header — not\nJSON. A PDF you uploaded comes back as a DOCX.\n\n**202** with `\"status\": \"in_progress\"` while the document is not ready\nyet: the id is valid, the translation just is not finished. Poll the status\nendpoint rather than retrying this one in a tight loop.\n\nTranslations stay available for 24 hours.","operationId":"download_file_translate_ai_file__file_id__translation_get","security":[{"Workspace API key":[]}],"parameters":[{"name":"file_id","in":"path","required":true,"schema":{"type":"string","description":"The `file_id` from the upload response.","title":"File Id"},"description":"The `file_id` from the upload response."}],"responses":{"200":{"description":"The translated document itself, with a `Content-Disposition` header. Not JSON.","content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No document with that id belongs to this workspace. An id from another workspace and an id that never existed give the same answer.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:not_found","title":"Not Found","status":404,"detail":"No such file id.","code":"not_found","error_id":"9f1c7a2e"}}}},"202":{"description":"The document exists but its translation is not finished. Poll the status endpoint rather than retrying this one.","content":{"application/json":{"example":{"status":"in_progress","detail":"This translation is not ready yet. Check the status endpoint."}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/translate/ai/file/{file_id}":{"delete":{"tags":["File Translation"],"summary":"AI file translation delete","description":"Delete an uploaded document before its retention window elapses.\n\nThe document is removed from storage, together with its translation and\neverything extracted from it. Use this when you have uploaded something\nconfidential and do not want to wait 24 hours for it to\nexpire.\n\nDeleting the same id twice answers the same both times. A translation already\nfinished has already been charged for; deleting the document does not undo\nthat.","operationId":"delete_file_translate_ai_file__file_id__delete","security":[{"Workspace API key":[]}],"parameters":[{"name":"file_id","in":"path","required":true,"schema":{"type":"string","description":"The `file_id` from the upload response.","title":"File Id"},"description":"The `file_id` from the upload response."}],"responses":{"200":{"description":"The document was removed from storage.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FileDeletedOut"},"example":{"file_id":"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30","status":"deleted"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No document with that id belongs to this workspace. An id from another workspace and an id that never existed give the same answer.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:not_found","title":"Not Found","status":404,"detail":"No such file id.","code":"not_found","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/translate/ai/file/quote":{"post":{"tags":["File Translation"],"summary":"AI file translation quote","description":"What translating a document would cost.\n\n**Send exactly the request you would send to `/translate/ai/file`.** Every\nfield that endpoint takes is accepted here, so pricing a call means re-sending\nit rather than rewriting it. Nothing is translated, nothing is metered and no\njob is created.\n\nMost of those fields cannot change the price — characters cost the same in\nevery language, and neither a glossary nor a politeness setting adds any — but\nthey are validated here anyway, so a request that would be refused by the\ntranslation is refused by its quote.\n\nThe price is what the request would cost beyond your plan's API & MCP quota at\nthe time of the quote.\n\n**`use_ocr` does change the price.** It decides how a PDF's text is read, and\ntherefore how many characters the document turns out to hold: quote a scan\nwithout it and you are pricing a document that appears to be empty, while the\nreal charge lands on everything OCR finds. Send the same value you will order\nwith.\n\nThe document does have to be read to count its characters, so this takes about\nas long as an extraction — it is a dry run for the price, not for the time. With\n`use_ocr`, it takes about as long as OCR: a large scan can take a while, and the\nanswer is worth the wait only because the alternative is a price for a document\nthat appears to be empty.\n\n**Limits:** 30 MiB per file, 10\nrequest(s) per second.","operationId":"quote_file_translate_ai_file_quote_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_quote_file_translate_ai_file_quote_post"}}},"required":true},"responses":{"200":{"description":"What translating this document would cost, and the characters it was priced on.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FileQuoteOut"},"example":{"character_count":12480,"prices":{"chf":0.2496}}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"413":{"description":"The uploaded document is larger than the per-file limit.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:request_entity_too_large","title":"Request Entity Too Large","status":413,"detail":"This file is 41 943 040 bytes; the limit is 31 457 280 (30 MiB).","code":"request_entity_too_large","error_id":"9f1c7a2e"}}}},"415":{"description":"file-translation-service cannot read this format. The message names the ones it can.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:unsupported_media_type","title":"Unsupported Media Type","status":415,"detail":"This file format can't be translated. Supported formats: DOCX, PPTX, XLSX, PDF, HTML, TXT, SRT.","code":"unsupported_media_type","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/translate/fused/file":{"post":{"tags":["File Translation"],"summary":"Fused file translation","description":"Translate a document and have a human expert review the result.\n\n**This endpoint incurs usage costs.**\n\nSend the file as `multipart/form-data`. One call places the whole order — the\ndocument is translated and a reviewer takes it from there:\n\n1. *(optional)* Ask `/translate/fused/file/quote` what it will cost and how\n long it will take. Same form body, nothing ordered.\n2. `POST /translate/fused/file`. Keep the `translation_id` from the response.\n3. Poll `GET /translate/fused/file/{translation_id}/status` — once a minute\n is plenty. It stays `in_progress` while the document is being translated and\n while it is being reviewed.\n4. When `status` is `completed`, download the reviewed document from\n `GET /translate/fused/file/{translation_id}/translation`.\n\nSupported formats: `DOCX`, `PPTX`, `XLSX`, `PDF`, `HTML`, `TXT`, `SRT`. A PDF comes back as a DOCX, because a\ntranslated document has to be rebuilt as an editable one.\n\n`source_lang` is required here, as it is for text: the review is priced and\nrouted to a linguist before anything is translated, and both need the pair up\nfront.\n\n**The price is the service's, per source word of your document, and the\nmachine translation is included in it.** It is not knowable until the document\nhas been extracted, so this call checks that your balance can be charged at all\nand the real debit lands when the order is placed. If your balance no longer\ncovers it by then, `status` answers `failed` with that as the reason.\n\n**Limits:** 30 MiB per file, 1\nrequest(s) per second. There is no character cap: a document too large to\npromise a delivery date for is refused with a 422 pointing at a manual quote.","operationId":"order_fused_file_translate_fused_file_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_order_fused_file_translate_fused_file_post"}}},"required":true},"responses":{"202":{"description":"The order was accepted. Keep `translation_id` and poll the status endpoint. `briefing_applied` says which service was ordered.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedFileAcceptedOut"},"example":{"request_id":"3feaf4c487b281fc144850525116797f","translation_id":"5c2e9a71-0d3b-4f86-a1e4-9b7c3d2f8e10","briefing_applied":false,"service_label":"Verification"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"402":{"description":"The part of the request past the plan's API & MCP quota is pay-as-you-go, and the workspace's credit balance cannot cover it, so `reason` is `insufficient_credit`. `included_chars` / `used_chars` are the quota and what the window has used of it.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:quota_exceeded","title":"Payment Required","status":402,"detail":"This workspace's credit balance can't cover this request. Top up the balance, or switch automatic top-up on.","code":"quota_exceeded","error_id":"9f1c7a2e","reason":"insufficient_credit","included_chars":1000000,"used_chars":1000000,"payg":true}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"503":{"description":"Human review cannot be ordered right now: the fulfilment system is unreachable, or this service has no pricing or delivery configuration. None of it is caused by the request, and all of it clears without the caller doing anything.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:service_unavailable","title":"Service Unavailable","status":503,"detail":"Human review is not available right now. Please try again later.","code":"service_unavailable","error_id":"9f1c7a2e"}}}},"413":{"description":"The uploaded document is larger than the per-file limit.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:request_entity_too_large","title":"Request Entity Too Large","status":413,"detail":"This file is 41 943 040 bytes; the limit is 31 457 280 (30 MiB).","code":"request_entity_too_large","error_id":"9f1c7a2e"}}}},"415":{"description":"file-translation-service cannot read this format. The message names the ones it can.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:unsupported_media_type","title":"Unsupported Media Type","status":415,"detail":"This file format can't be translated. Supported formats: DOCX, PPTX, XLSX, PDF, HTML, TXT, SRT.","code":"unsupported_media_type","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/translate/fused/file/{translation_id}/status":{"get":{"tags":["File Translation"],"summary":"Fused file translation status","description":"Where your order has got to.\n\n`in_progress` covers both phases — the machine translation and the human\nreview. `completed` means the reviewed document is ready to download.\n`failed` means the order will not be delivered, and `error` says why: the\ndocument could not be translated, it held no text to review, or your balance\ndid not cover the price when the order was placed.\n\n`estimated_duration_left_in_seconds` counts down to the promised delivery once\na reviewer has the document, and is 0 before that. A negative number means the\npromise has passed.","operationId":"fused_file_status_translate_fused_file__translation_id__status_get","security":[{"Workspace API key":[]}],"parameters":[{"name":"translation_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The `translation_id` from the order response.","title":"Translation Id"},"description":"The `translation_id` from the order response."}],"responses":{"200":{"description":"Where the order has got to. `in_progress` covers both the translation and the review; `error` is set only when the order has failed.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedFileStatusOut"},"example":{"status":"in_progress","detected_source_lang":"en","estimated_duration_left_in_seconds":4820}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No order with that id belongs to this workspace. An id from another workspace and an id that never existed give the same answer.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:not_found","title":"Not Found","status":404,"detail":"No such translation id.","code":"not_found","error_id":"9f1c7a2e"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/translate/fused/file/{translation_id}/translation":{"get":{"tags":["File Translation"],"summary":"Fused file translation download","description":"Download the reviewed document.\n\nAnswers the document itself, with the reviewer's changes patched back into it,\nunder a `Content-Disposition` filename — not JSON. It is a DOCX: a PDF is\nconverted on the way in, and what comes back is the document as it was\ntranslated.\n\n**202** with `\"status\": \"in_progress\"` until a reviewer has delivered.\nThe machine translation exists long before that, and handing it back here would\nsell you a draft as a reviewed document. Poll the status endpoint rather than\nretrying this one on a tight loop.","operationId":"fused_file_result_translate_fused_file__translation_id__translation_get","security":[{"Workspace API key":[]}],"parameters":[{"name":"translation_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The `translation_id` from the order response.","title":"Translation Id"},"description":"The `translation_id` from the order response."}],"responses":{"200":{"description":"The reviewed document itself, with a `Content-Disposition` header. Not JSON.","content":{"application/json":{"schema":{}},"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No order with that id belongs to this workspace. An id from another workspace and an id that never existed give the same answer.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:not_found","title":"Not Found","status":404,"detail":"No such translation id.","code":"not_found","error_id":"9f1c7a2e"}}}},"202":{"description":"The order exists but no reviewer has delivered it yet. Poll the status endpoint rather than retrying this one.","content":{"application/json":{"example":{"status":"in_progress","detail":"This translation is not ready yet. Check the status endpoint."}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/translate/fused/file/quote":{"post":{"tags":["File Translation"],"summary":"Fused file translation quote","description":"What a human review of this document would cost, and when it would arrive.\n\n**Send exactly the request you would send to `/translate/fused/file`.** Every\nfield that endpoint takes is accepted here, so pricing a call means re-sending\nit rather than rewriting it. Nothing is translated, nothing is metered, no\norder is placed and no reviewer is engaged.\n\nTwo of those fields change the answer. The `briefing` selects Optimisation\ninstead of Verification, which changes both the price and the delivery time.\nAnd **`use_ocr` decides how a PDF's text is read**, and therefore how many\nwords the document turns out to hold — quote a scan without it and you are\npricing a document that appears to be empty. `politeness` steers the draft the\nreviewer starts from, not how much there is to review, so it cannot change\neither number.\n\n`prices` is what the call costs, in your workspace's billing currency: the\nreview, priced per source word with a per-order minimum, with the machine\ntranslation included. `word_count` and `character_count` are what was found in\nthe document, so you can see where the number comes from — neither is a\nquantity you are charged for separately.\n\nThe document is read to answer this, so the same size and format rules apply as\nfor the order itself.\n\n**Limits:** 30 MiB per file, 10\nrequests per second.","operationId":"quote_fused_file_translate_fused_file_quote_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_quote_fused_file_translate_fused_file_quote_post"}}},"required":true},"responses":{"200":{"description":"What reviewing this document would cost and how long delivery is expected to take. `prices` is the whole price: the review, with the machine translation included.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FusedFileQuoteOut"},"example":{"prices":{"chf":24.5},"estimated_duration_in_seconds":5400,"word_count":490,"character_count":3180,"briefing_applied":false,"service_label":"Verification"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"503":{"description":"Human review cannot be ordered right now: the fulfilment system is unreachable, or this service has no pricing or delivery configuration. None of it is caused by the request, and all of it clears without the caller doing anything.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:service_unavailable","title":"Service Unavailable","status":503,"detail":"Human review is not available right now. Please try again later.","code":"service_unavailable","error_id":"9f1c7a2e"}}}},"413":{"description":"The uploaded document is larger than the per-file limit.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:request_entity_too_large","title":"Request Entity Too Large","status":413,"detail":"This file is 41 943 040 bytes; the limit is 31 457 280 (30 MiB).","code":"request_entity_too_large","error_id":"9f1c7a2e"}}}},"415":{"description":"file-translation-service cannot read this format. The message names the ones it can.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:unsupported_media_type","title":"Unsupported Media Type","status":415,"detail":"This file format can't be translated. Supported formats: DOCX, PPTX, XLSX, PDF, HTML, TXT, SRT.","code":"unsupported_media_type","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/features":{"get":{"tags":["Feature Scope"],"summary":"Language & feature support","description":"Every supported language pair, and the features supported for each.\n\nTranslation itself is a full matrix — every source language translates into\nevery target language. What has gaps is the features, and the gaps are per\nlanguage: formality is meaningless in some targets, and glossary terms cannot\nbe enforced in every target. So this endpoint answers one entry per pair with\nthe feature names that pair supports; a name that is absent is not supported.\n\nFilter with `source_lang` and/or `target_lang` to ask about one row rather than\nthe whole matrix. A filter naming a language we do not support narrows the\nanswer to nothing rather than failing — a language picker asking about an\nunknown language wants an empty list, not an error. A `target_lang` naming a\nbase language with several variants (`de`) keeps all of them.\n\n**Limits:** 10 request(s) per second.","operationId":"features_features_get","security":[{"Workspace API key":[]}],"parameters":[{"name":"source_lang","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Narrow the answer to this source language (BCP 47).","title":"Source Lang"},"description":"Narrow the answer to this source language (BCP 47)."},{"name":"target_lang","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Narrow the answer to this target language (BCP 47).","title":"Target Lang"},"description":"Narrow the answer to this target language (BCP 47)."}],"responses":{"200":{"description":"Every supported pair and the features it supports - truncated here; the real response carries one entry per (source, target) combination. A feature name that is absent is not supported for that pair.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeaturesOut"},"example":{"supported_features":[{"source_lang":"en","target_lang":"de-CH","features":["supports_politeness","supports_glossary"]},{"source_lang":"de","target_lang":"en-GB","features":["supports_glossary"]}]}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/detect-languages/text":{"post":{"tags":["Language Detection"],"summary":"Language detection","description":"Detect the language of the provided text.\n\n**This endpoint incurs usage costs**, charged like a translation of the\n500-character snippet actually read. An inconclusive\nanswer — an empty `detected_languages` — is free.\n\n**Limits:** 10 request(s) per second.","operationId":"detect_text_detect_languages_text_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TextDetectionIn"},"examples":{"plain":{"summary":"Detect the language of a text","description":"Only the first 500 characters are read, and only those are charged - a longer text is neither dearer nor better identified.","value":{"text":"Die Lieferung erfolgt innerhalb von zwei Werktagen."}}}}},"required":true},"responses":{"200":{"description":"The detected language. A language we cannot translate is still reported, with `supports_translation: false`, rather than substituted for the nearest one we can. An empty list means the text was too short or too mixed to identify, and is not charged.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LanguageDetectionOut"},"example":{"detected_languages":[{"lang_code":"de","confidence":0.98,"supports_translation":true}]}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"402":{"description":"The part of the request past the plan's API & MCP quota is pay-as-you-go, and the workspace's credit balance cannot cover it, so `reason` is `insufficient_credit`. `included_chars` / `used_chars` are the quota and what the window has used of it.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:quota_exceeded","title":"Payment Required","status":402,"detail":"This workspace's credit balance can't cover this request. Top up the balance, or switch automatic top-up on.","code":"quota_exceeded","error_id":"9f1c7a2e","reason":"insufficient_credit","included_chars":1000000,"used_chars":1000000,"payg":true}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}}},"security":[{"Workspace API key":[]}]}},"/detect-languages/text/quote":{"post":{"tags":["Language Detection"],"summary":"Language detection quote","description":"What a detection would cost.\n\nTakes the same payload as `/detect-languages/text`. Same fields as the\ntranslation quote, priced on the capped snippet. The price is what the request\nwould cost beyond your plan's API & MCP quota at the time of the quote.\n\n**Limits:** 10 request(s) per second.","operationId":"quote_detection_detect_languages_text_quote_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TextDetectionIn"},"examples":{"plain":{"summary":"Detect the language of a text","description":"Only the first 500 characters are read, and only those are charged - a longer text is neither dearer nor better identified.","value":{"text":"Die Lieferung erfolgt innerhalb von zwei Werktagen."}}}}},"required":true},"responses":{"200":{"description":"What the same detection would cost, on the capped snippet.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DetectionQuoteOut"},"example":{"character_count":51,"prices":{"chf":0.00102}}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}}},"security":[{"Workspace API key":[]}]}},"/detect-languages/file":{"post":{"tags":["Language Detection"],"summary":"File language detection","description":"Identify the language a document is written in.\n\n**This endpoint incurs usage costs.**\n\nSend the file as `multipart/form-data`. The answer comes back on the same\nrequest — no polling. The document is read while you wait, so a large file, or\na scan that needs OCR, can take a while and may time out; if that happens,\nextracting the text yourself and using `/detect-languages/text` is the\nreliable path.\n\nA document with no readable text answers with an empty `detected_languages`\nlist and costs nothing.\n\nCharged on the first 500 characters of the document,\nlike the text endpoint — identifying a language needs a sample, not the whole\nfile.\n\n**Limits:** 30 MiB per file, 1\nrequest(s) per second.","operationId":"detect_file_detect_languages_file_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_detect_file_detect_languages_file_post"}}},"required":true},"responses":{"200":{"description":"The language the document is written in. An empty list means there was no readable text, which costs nothing.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LanguageDetectionOut"},"example":{"detected_languages":[{"lang_code":"de","confidence":0.98,"supports_translation":true}]}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"402":{"description":"The part of the request past the plan's API & MCP quota is pay-as-you-go, and the workspace's credit balance cannot cover it, so `reason` is `insufficient_credit`. `included_chars` / `used_chars` are the quota and what the window has used of it.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:quota_exceeded","title":"Payment Required","status":402,"detail":"This workspace's credit balance can't cover this request. Top up the balance, or switch automatic top-up on.","code":"quota_exceeded","error_id":"9f1c7a2e","reason":"insufficient_credit","included_chars":1000000,"used_chars":1000000,"payg":true}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"413":{"description":"The uploaded document is larger than the per-file limit.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:request_entity_too_large","title":"Request Entity Too Large","status":413,"detail":"This file is 41 943 040 bytes; the limit is 31 457 280 (30 MiB).","code":"request_entity_too_large","error_id":"9f1c7a2e"}}}},"415":{"description":"file-translation-service cannot read this format. The message names the ones it can.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:unsupported_media_type","title":"Unsupported Media Type","status":415,"detail":"This file format can't be translated. Supported formats: DOCX, PPTX, XLSX, PDF, HTML, TXT, SRT.","code":"unsupported_media_type","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/detect-languages/file/quote":{"post":{"tags":["Language Detection"],"summary":"File language detection quote","description":"What detecting a document's language would cost.\n\nTakes the same file as `/detect-languages/file`. Nothing is identified and no\nusage is recorded, but the document is still read to see how much text it\nholds, so this is as slow as the detection itself. The price is what the request\nwould cost beyond your plan's API & MCP quota at the time of the quote.\n\n**Limits:** 10 request(s) per second.","operationId":"quote_file_detection_detect_languages_file_quote_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_quote_file_detection_detect_languages_file_quote_post"}}},"required":true},"responses":{"200":{"description":"What identifying this document's language would cost.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DetectionQuoteOut"},"example":{"character_count":500,"prices":{"chf":0.01}}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"422":{"description":"Well-formed JSON, but not a valid request.","content":{"application/problem+json":{"examples":{"validation_error":{"value":{"type":"urn:supertext:error:validation_error","title":"Unprocessable Entity","status":422,"detail":"body.text: request exceeds 10,000 characters","code":"validation_error","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}},"502":{"description":"Something we depend on did not deliver. Retryable, and not caused by the request.","content":{"application/problem+json":{"examples":{"upstream_error":{"value":{"type":"urn:supertext:error:upstream_error","title":"Bad Gateway","status":502,"detail":"The translation engine is unavailable.","code":"upstream_error","error_id":"9f1c7a2e"}},"plan_unresolved":{"value":{"type":"urn:supertext:error:plan_unresolved","title":"Bad Gateway","status":502,"detail":"Your plan could not be resolved just now. Please retry shortly.","code":"plan_unresolved","error_id":"9f1c7a2e"}},"plan_unpriced":{"value":{"type":"urn:supertext:error:plan_unpriced","title":"Bad Gateway","status":502,"detail":"This workspace's plan has no per-character price for its billing currency, so API usage cannot be priced. Please contact support.","code":"plan_unpriced","error_id":"9f1c7a2e"}}}}}},"413":{"description":"The uploaded document is larger than the per-file limit.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:request_entity_too_large","title":"Request Entity Too Large","status":413,"detail":"This file is 41 943 040 bytes; the limit is 31 457 280 (30 MiB).","code":"request_entity_too_large","error_id":"9f1c7a2e"}}}},"415":{"description":"file-translation-service cannot read this format. The message names the ones it can.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:unsupported_media_type","title":"Unsupported Media Type","status":415,"detail":"This file format can't be translated. Supported formats: DOCX, PPTX, XLSX, PDF, HTML, TXT, SRT.","code":"unsupported_media_type","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/account":{"get":{"tags":["account"],"summary":"Check a key and its workspace","description":"The workspace this API key belongs to, and the key's own name, prefix and\nexpiry date.\n\nFree, and it returns nothing you did not already hold — which is what makes it\nthe right way to confirm a new key works before wiring anything real.","operationId":"account_account_get","responses":{"200":{"description":"The workspace this key belongs to, and the key's own metadata.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountOut"},"example":{"workspace_id":"6f1b1e94-2f6a-4a5a-9a7e-0b1f2c3d4e5f","workspace_name":"Acme AG","api_key_name":"production","api_key_prefix":"st_live_7Fq2Vd","api_key_expires_at":"2028-09-16T09:12:00Z"}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/webhooks":{"get":{"tags":["Webhooks"],"summary":"List webhooks","description":"The webhooks this API key created. Another key's webhooks, even in the same\nworkspace, are not listed.\n\n**Limits:** 1 request(s) per second.","operationId":"list_webhooks_webhooks_get","responses":{"200":{"description":"This API key's webhooks, oldest first.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookListOut"},"example":{"items":[{"id":"5b0c1e7a-3d2f-4c8e-9a61-2f7d8e4b1c90","url":"https://cms.example.com/hooks/supertext","event_types":["translation.ai_file.completed","translation.ai_file.failed"],"description":"CMS plugin, production","status":"active","created_at":"2026-10-28T13:05:12Z","last_delivery_at":"2026-10-28T14:21:40Z","consecutive_failures":0}]}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]},"post":{"tags":["Webhooks"],"summary":"Create a webhook","description":"Register a URL to receive the events you list. See the Webhooks section for\nthe event types, the request we send and how to verify it.\n\n**The response carries the signing `secret`, and only this response does.**\nStore it now: it cannot be read again. To get a new one, delete the webhook\nand create it again.\n\nThe URL must be `https`, carry no credentials and resolve to a public address;\nit is checked now and again before every delivery. A workspace can have up to\n10 webhooks; the next one is refused with **409**\n`webhook_limit_reached`.\n\n**Limits:** 1 request(s) per second.","operationId":"create_webhook_webhooks_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookCreateIn"},"examples":{"translations":{"summary":"Hear when AI file translations finish","description":"The usual set for an integration that uploads documents and wants the result.","value":{"url":"https://cms.example.com/hooks/supertext","event_types":["translation.ai_file.completed","translation.ai_file.failed"],"description":"CMS plugin, production"}},"workspace-health":{"summary":"Hear when the workspace needs attention","description":"Balance, billing and key events, for whoever runs the integration.","value":{"url":"https://ops.example.com/supertext","event_types":["wallet.low_balance","subscription.payment_failed","api_key.expiring","api_key.revoked"]}}}}},"required":true},"responses":{"201":{"description":"The webhook, and its signing `secret`. The secret is in this response only: store it now.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookCreatedOut"},"example":{"id":"5b0c1e7a-3d2f-4c8e-9a61-2f7d8e4b1c90","url":"https://cms.example.com/hooks/supertext","event_types":["translation.ai_file.completed","translation.ai_file.failed"],"description":"CMS plugin, production","status":"active","created_at":"2026-10-28T13:05:12Z","consecutive_failures":0,"secret":"whsec_YJnbzH592OK0ptDLqC1jiewD6K9s2RHS6DYaHcQFl0c="}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"409":{"description":"The workspace already has the maximum number of webhooks.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:webhook_limit_reached","title":"Conflict","status":409,"detail":"This workspace already has 10 webhooks. Delete one to add another.","code":"webhook_limit_reached","error_id":"9f1c7a2e"}}}},"422":{"description":"The URL or the event types cannot be used.","content":{"application/problem+json":{"examples":{"webhook_url_invalid":{"value":{"type":"urn:supertext:error:webhook_url_invalid","title":"Unprocessable Entity","status":422,"detail":"The URL must be https, carry no credentials and be at most 2,048 characters.","code":"webhook_url_invalid","error_id":"9f1c7a2e"}},"webhook_url_unsafe":{"value":{"type":"urn:supertext:error:webhook_url_unsafe","title":"Unprocessable Entity","status":422,"detail":"The URL's host resolves to an address that is not on the public internet.","code":"webhook_url_unsafe","error_id":"9f1c7a2e"}},"webhook_url_unresolvable":{"value":{"type":"urn:supertext:error:webhook_url_unresolvable","title":"Unprocessable Entity","status":422,"detail":"The URL's host could not be resolved.","code":"webhook_url_unresolvable","error_id":"9f1c7a2e"}},"webhook_event_type_unknown":{"value":{"type":"urn:supertext:error:webhook_event_type_unknown","title":"Unprocessable Entity","status":422,"detail":"Not event types you can subscribe to: translation.done.","code":"webhook_event_type_unknown","error_id":"9f1c7a2e"}}}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}}}},"security":[{"Workspace API key":[]}]}},"/webhooks/{webhook_id}":{"get":{"tags":["Webhooks"],"summary":"Get a webhook","description":"One of this API key's webhooks, with its delivery health: when an event last\nreached it, the last failure and how many attempts in a row have failed.\n\n**Limits:** 1 request(s) per second.","operationId":"get_webhook_webhooks__webhook_id__get","security":[{"Workspace API key":[]}],"parameters":[{"name":"webhook_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The webhook's `id`.","title":"Webhook Id"},"description":"The webhook's `id`."}],"responses":{"200":{"description":"The webhook.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookOut"},"example":{"id":"5b0c1e7a-3d2f-4c8e-9a61-2f7d8e4b1c90","url":"https://cms.example.com/hooks/supertext","event_types":["translation.ai_file.completed","translation.ai_file.failed"],"description":"CMS plugin, production","status":"active","created_at":"2026-10-28T13:05:12Z","last_delivery_at":"2026-10-28T14:21:40Z","consecutive_failures":0}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No webhook with this id belongs to this API key. Another key's webhook answers the same.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:webhook_not_found","title":"Not Found","status":404,"detail":"No such webhook.","code":"webhook_not_found","error_id":"9f1c7a2e"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"patch":{"tags":["Webhooks"],"summary":"Update a webhook","description":"Change the URL, the event types or the description. Only the fields you send\nchange; `\"description\": null` clears the description.\n\n`\"enabled\": true` switches a disabled webhook back on and resets its failure\ncount. Events that were cancelled while it was disabled are not sent again.\n\n**Limits:** 1 request(s) per second.","operationId":"update_webhook_webhooks__webhook_id__patch","security":[{"Workspace API key":[]}],"parameters":[{"name":"webhook_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The webhook's `id`.","title":"Webhook Id"},"description":"The webhook's `id`."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookUpdateIn"},"examples":{"re-enable":{"summary":"Switch a disabled webhook back on","description":"Once your endpoint answers again. Resets the failure count.","value":{"enabled":true}},"change-events":{"summary":"Change the event types","description":"Only the fields sent change.","value":{"event_types":["translation.fused_text.completed","translation.fused_file.completed"]}}}}}},"responses":{"200":{"description":"The webhook as it now is.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookOut"},"example":{"id":"5b0c1e7a-3d2f-4c8e-9a61-2f7d8e4b1c90","url":"https://cms.example.com/hooks/supertext","event_types":["translation.ai_file.completed","translation.ai_file.failed"],"description":"CMS plugin, production","status":"active","created_at":"2026-10-28T13:05:12Z","last_delivery_at":"2026-10-28T14:21:40Z","consecutive_failures":0}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No webhook with this id belongs to this API key. Another key's webhook answers the same.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:webhook_not_found","title":"Not Found","status":404,"detail":"No such webhook.","code":"webhook_not_found","error_id":"9f1c7a2e"}}}},"422":{"description":"The URL or the event types cannot be used.","content":{"application/problem+json":{"examples":{"webhook_url_invalid":{"value":{"type":"urn:supertext:error:webhook_url_invalid","title":"Unprocessable Entity","status":422,"detail":"The URL must be https, carry no credentials and be at most 2,048 characters.","code":"webhook_url_invalid","error_id":"9f1c7a2e"}},"webhook_url_unsafe":{"value":{"type":"urn:supertext:error:webhook_url_unsafe","title":"Unprocessable Entity","status":422,"detail":"The URL's host resolves to an address that is not on the public internet.","code":"webhook_url_unsafe","error_id":"9f1c7a2e"}},"webhook_url_unresolvable":{"value":{"type":"urn:supertext:error:webhook_url_unresolvable","title":"Unprocessable Entity","status":422,"detail":"The URL's host could not be resolved.","code":"webhook_url_unresolvable","error_id":"9f1c7a2e"}},"webhook_event_type_unknown":{"value":{"type":"urn:supertext:error:webhook_event_type_unknown","title":"Unprocessable Entity","status":422,"detail":"Not event types you can subscribe to: translation.done.","code":"webhook_event_type_unknown","error_id":"9f1c7a2e"}}}}}}}},"delete":{"tags":["Webhooks"],"summary":"Delete a webhook","description":"Delete a webhook. Events not yet delivered to it are cancelled, and nothing new\nis sent to it; at most a request already in progress may still arrive.\n\n**Limits:** 1 request(s) per second.","operationId":"delete_webhook_webhooks__webhook_id__delete","security":[{"Workspace API key":[]}],"parameters":[{"name":"webhook_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The webhook's `id`.","title":"Webhook Id"},"description":"The webhook's `id`."}],"responses":{"204":{"description":"Deleted. Events not yet delivered to it are cancelled."},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No webhook with this id belongs to this API key. Another key's webhook answers the same.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:webhook_not_found","title":"Not Found","status":404,"detail":"No such webhook.","code":"webhook_not_found","error_id":"9f1c7a2e"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/webhooks/{webhook_id}/test":{"post":{"tags":["Webhooks"],"summary":"Send a test event","description":"Send a `webhook.test` event to the webhook now and report what came back.\nUse it to check an endpoint while you set it up.\n\nIt is signed and sent exactly like a real event, but it is not retried and\ndoes not count towards the webhook's failure record. A failed test is still a\n**200**: read `delivered`, `status_code` and `error`. A disabled webhook\nanswers **409** `webhook_disabled`; re-enable it first.\n\n**Limits:** 1 per 5 s.","operationId":"test_webhook_webhooks__webhook_id__test_post","security":[{"Workspace API key":[]}],"parameters":[{"name":"webhook_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"The webhook's `id`.","title":"Webhook Id"},"description":"The webhook's `id`."}],"responses":{"200":{"description":"What your endpoint answered. A failed test is still a 200: `delivered` and `status_code` say how it went.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookTestOut"},"examples":{"delivered":{"summary":"Your endpoint accepted it","value":{"delivered":true,"status_code":204,"duration_ms":182}},"rejected":{"summary":"Your endpoint answered with an error","value":{"delivered":false,"status_code":401,"duration_ms":95}},"unreachable":{"summary":"No answer in time","value":{"delivered":false,"error":"timeout","duration_ms":10003}}}}}},"401":{"description":"The key is missing, malformed, revoked or expired.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:invalid_api_key","title":"Unauthorized","status":401,"detail":"The API key is not valid.","code":"invalid_api_key","error_id":"9f1c7a2e"}}}},"403":{"description":"The workspace is not entitled to the API.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:api_access_not_enabled","title":"Forbidden","status":403,"detail":"API access is not enabled on this workspace's plan.","code":"api_access_not_enabled","error_id":"9f1c7a2e"}}}},"429":{"description":"Too many requests for this key. Honour the `Retry-After` header rather than hardcoding a backoff.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:rate_limited","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded. Retry after 1 second.","code":"rate_limited","error_id":"9f1c7a2e"}}},"headers":{"Retry-After":{"description":"Seconds to wait before retrying.","schema":{"type":"integer"}}}},"404":{"description":"No webhook with this id belongs to this API key. Another key's webhook answers the same.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:webhook_not_found","title":"Not Found","status":404,"detail":"No such webhook.","code":"webhook_not_found","error_id":"9f1c7a2e"}}}},"409":{"description":"The webhook is disabled. Re-enable it first.","content":{"application/problem+json":{"example":{"type":"urn:supertext:error:webhook_disabled","title":"Conflict","status":409,"detail":"This webhook is disabled. Re-enable it with `PATCH` and `enabled: true` first.","code":"webhook_disabled","error_id":"9f1c7a2e"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"AccountOut":{"properties":{"workspace_id":{"type":"string","format":"uuid","title":"Workspace Id"},"workspace_name":{"type":"string","title":"Workspace Name"},"api_key_name":{"type":"string","title":"Api Key Name"},"api_key_prefix":{"type":"string","title":"Api Key Prefix"},"api_key_expires_at":{"type":"string","format":"date-time","title":"Api Key Expires At"}},"type":"object","required":["workspace_id","workspace_name","api_key_name","api_key_prefix","api_key_expires_at"],"title":"AccountOut","description":"Identity of the calling credential. See app/api/public/meta.py."},"Body_detect_file_detect_languages_file_post":{"properties":{"file":{"type":"string","contentMediaType":"application/octet-stream","title":"File","description":"The document whose language should be detected."}},"type":"object","required":["file"],"title":"Body_detect_file_detect_languages_file_post"},"Body_order_fused_file_translate_fused_file_post":{"properties":{"file":{"type":"string","contentMediaType":"application/octet-stream","title":"File","description":"The document to translate and have reviewed."},"target_lang":{"type":"string","title":"Target Lang","description":"Target language (BCP 47)."},"source_lang":{"type":"string","title":"Source Lang","description":"Source language (BCP 47). Required, unlike on the AI endpoints."},"politeness":{"type":"string","title":"Politeness","description":"`default`, `more` or `less`.","default":"default"},"briefing":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Briefing","description":"Instructions for the reviewer. Sending one orders Optimisation instead of Verification."},"use_ocr":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Use Ocr","description":"Read a PDF's text with OCR. Required for a PDF, ignored for other formats."}},"type":"object","required":["file","target_lang","source_lang"],"title":"Body_order_fused_file_translate_fused_file_post"},"Body_quote_file_detection_detect_languages_file_quote_post":{"properties":{"file":{"type":"string","contentMediaType":"application/octet-stream","title":"File","description":"The document to price a detection for."}},"type":"object","required":["file"],"title":"Body_quote_file_detection_detect_languages_file_quote_post"},"Body_quote_file_translate_ai_file_quote_post":{"properties":{"file":{"type":"string","contentMediaType":"application/octet-stream","title":"File","description":"The document to price."},"target_lang":{"type":"string","title":"Target Lang","description":"Target language (BCP 47).","default":""},"source_lang":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Lang","description":"Source language (BCP 47). Detected when omitted."},"politeness":{"type":"string","title":"Politeness","description":"`default`, `more` or `less`.","default":"default"},"glossary":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Glossary","description":"A JSON object of source → target terms."},"use_ocr":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Use Ocr","description":"Read a PDF's text with OCR. Changes the character count, so send what you will order with."}},"type":"object","required":["file"],"title":"Body_quote_file_translate_ai_file_quote_post"},"Body_quote_fused_file_translate_fused_file_quote_post":{"properties":{"file":{"type":"string","contentMediaType":"application/octet-stream","title":"File","description":"The document to price."},"target_lang":{"type":"string","title":"Target Lang","description":"Target language (BCP 47)."},"source_lang":{"type":"string","title":"Source Lang","description":"Source language (BCP 47)."},"politeness":{"type":"string","title":"Politeness","description":"`default`, `more` or `less`.","default":"default"},"briefing":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Briefing","description":"Send the briefing you would order with: it changes the price and the delivery time."},"use_ocr":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Use Ocr","description":"Read a PDF's text with OCR. Changes the word count, so send what you will order with."}},"type":"object","required":["file","target_lang","source_lang"],"title":"Body_quote_fused_file_translate_fused_file_quote_post"},"Body_translate_file_translate_ai_file_post":{"properties":{"file":{"type":"string","contentMediaType":"application/octet-stream","title":"File","description":"The document to translate."},"target_lang":{"type":"string","title":"Target Lang","description":"Target language (BCP 47)."},"source_lang":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Lang","description":"Source language (BCP 47). Detected when omitted."},"politeness":{"type":"string","title":"Politeness","description":"`default`, `more` or `less`.","default":"default"},"glossary":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Glossary","description":"A JSON object of source → target terms."},"use_ocr":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Use Ocr","description":"Read a PDF's text with OCR. Ignored for other formats."}},"type":"object","required":["file","target_lang"],"title":"Body_translate_file_translate_ai_file_post"},"DetectedLanguageOut":{"properties":{"lang_code":{"type":"string","title":"Lang Code","description":"BCP 47 code of the detected language."},"confidence":{"anyOf":[{"type":"number","maximum":1.0,"minimum":0.0},{"type":"null"}],"title":"Confidence","description":"How sure the identifier is, 0–1. Null when upstream reported none."},"supports_translation":{"type":"boolean","title":"Supports Translation","description":"False when this deployment cannot translate the detected language."}},"type":"object","required":["lang_code","supports_translation"],"title":"DetectedLanguageOut"},"DetectionQuoteOut":{"properties":{"character_count":{"type":"integer","title":"Character Count","description":"Characters detection would read — the capped snippet, not the whole text."},"prices":{"additionalProperties":{"type":"number"},"type":"object","title":"Prices","description":"Cost of those characters, keyed by lower-case currency code. One entry: the workspace's own billing currency."}},"type":"object","required":["character_count","prices"],"title":"DetectionQuoteOut","description":"What detection would cost — the same shape as the translation quote,\nbecause it is charged the same way. See `TextQuoteOut` for why `prices`\ncarries a float rather than an integer number of cents.\n\nv1 metered detection too, and priced it like a translation of the cropped\ntext. v1 keeps it metered: a customer gets detection for free by omitting\n`source_lang` from a translation, which pays for the whole text anyway, but\na free standalone detection service is not on offer.\n\n`character_count` is one deliberate addition to v1's shape here — v1's\ndetection quote answered `prices` alone. It is the CAPPED count, and it is\nthe one figure a caller cannot work out for themselves, since the snippet\ncap is ours. An added field breaks no client that was reading v1's."},"FeaturedLanguagePair":{"properties":{"source_lang":{"type":"string","title":"Source Lang","description":"Source language code (BCP 47) to send as `source_lang`."},"target_lang":{"type":"string","title":"Target Lang","description":"Target language code (BCP 47) to send as `target_lang`."},"features":{"items":{"$ref":"#/components/schemas/PublicFeature"},"type":"array","title":"Features","description":"Feature names supported for this pair. Absent means unsupported."}},"type":"object","required":["source_lang","target_lang","features"],"title":"FeaturedLanguagePair"},"FeaturesOut":{"properties":{"supported_features":{"items":{"$ref":"#/components/schemas/FeaturedLanguagePair"},"type":"array","title":"Supported Features"}},"type":"object","required":["supported_features"],"title":"FeaturesOut"},"FileDeletedOut":{"properties":{"file_id":{"type":"string","title":"File Id","description":"Id of the document that was deleted."},"status":{"type":"string","const":"deleted","title":"Status","description":"Always `deleted`.","default":"deleted"}},"type":"object","required":["file_id"],"title":"FileDeletedOut","description":"What a DELETE answers.\n\nv1 documented `{\"file_id\", \"status\"}` here and actually returned its\ninternal `AsyncDocumentTranslationStatusResponse` -- `document_id`,\n`estimated_finishing_time`, `send_email`. This is the documented shape,\nwhich is the one a client was written against and the one that does not\nleak our field names."},"FileQuoteOut":{"properties":{"character_count":{"type":"integer","title":"Character Count","description":"Characters extracted from the document."},"prices":{"additionalProperties":{"type":"number"},"type":"object","title":"Prices","description":"What those characters cost, keyed by lower-case ISO 4217 code."}},"type":"object","required":["character_count","prices"],"title":"FileQuoteOut","description":"What translating this document would cost.\n\n`character_count` is the text file-translation-service extracts from the\ndocument, which is the quantity the translation is metered on -- not the\nfile's size in bytes, and not its word count.\n\nProducing it means extracting the document, so this endpoint does real work\nand can take as long as an extraction does. v1 had the same property and\ndocumented this as a dry run anyway; it is a dry run for the PRICE, not for\nthe latency."},"FileTranslationOut":{"properties":{"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Id of this request, also returned as the `X-Request-ID` header. Quote it to support."},"file_id":{"type":"string","title":"File Id","description":"Id of the uploaded document. Poll its status and fetch its translation with this."}},"type":"object","required":["file_id"],"title":"FileTranslationOut","description":"v1's 202 body, unchanged."},"FileTranslationStatusOut":{"properties":{"file_id":{"type":"string","title":"File Id","description":"Id of the uploaded document."},"status":{"type":"string","enum":["translating","done","error","deleted"],"title":"Status","description":"`translating` until the document is ready, then `done` -- or `error`, or `deleted`."},"error":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error","description":"What went wrong, when `status` is `error`."},"estimated_duration_left_in_seconds":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Estimated Duration Left In Seconds","description":"Time remaining, when we can estimate it. Null while file-translation-service has not reported progress; 0 once the document is ready."},"detected_source_lang":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Detected Source Lang","description":"The source language used -- detected when the upload omitted one."}},"type":"object","required":["file_id","status"],"title":"FileTranslationStatusOut","description":"v1's status body, minus `download_url` (see the module docstring).\n\n`status` collapses file-translation-service's six job states onto v1's\nvocabulary: `queued`, `extracting`, `translating` and `merging` are all\n`translating`, because which internal stage a document is in is our\noperational detail and a client can do nothing differently with it."},"FusedFileAcceptedOut":{"properties":{"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Id of this request, also returned as the `X-Request-ID` header. Quote it to support."},"translation_id":{"type":"string","title":"Translation Id","description":"Id of the human-review order, a UUID. Pass it to the status and download endpoints. It identifies the document you uploaded, and keeps identifying the order once a reviewer has it."},"briefing_applied":{"type":"boolean","title":"Briefing Applied","description":"Whether a briefing was applied, and therefore which service was ordered. This is the stable discriminator; `service_label` is for display."},"service_label":{"type":"string","title":"Service Label","description":"Human-readable name of the service ordered. Display only -- do not branch on it."}},"type":"object","required":["translation_id","briefing_applied","service_label"],"title":"FusedFileAcceptedOut","description":"The 202 body: the order is accepted, the work has not started."},"FusedFileQuoteOut":{"properties":{"prices":{"additionalProperties":{"type":"number"},"type":"object","title":"Prices","description":"What the same request costs, keyed by lower-case ISO 4217 code. The machine translation is included -- this is the whole price."},"estimated_duration_in_seconds":{"type":"integer","title":"Estimated Duration In Seconds","description":"How long delivery is expected to take, from now."},"word_count":{"type":"integer","title":"Word Count","description":"Source words the price is computed from."},"character_count":{"type":"integer","title":"Character Count","description":"Source characters found in the document."},"briefing_applied":{"type":"boolean","title":"Briefing Applied","description":"Whether this quote is for Optimisation (true) or Verification."},"service_label":{"type":"string","title":"Service Label","description":"Human-readable name of the service quoted. Display only."}},"type":"object","required":["prices","estimated_duration_in_seconds","word_count","character_count","briefing_applied","service_label"],"title":"FusedFileQuoteOut","description":"What reviewing this document would cost, and when it would arrive.\n\nThe text quote's body plus `character_count`, which is here for a reason\nthe text endpoint does not have: a customer cannot count the words in a\ndocument they have not extracted, so the two numbers together are what\nmakes the price checkable. Neither is a billing quantity for characters --\nthe price is per source word, and the machine translation is included in\nit, exactly as for text.\n\nA real dry run: the document is extracted to count its words, and nothing\nis translated, metered or ordered to answer this."},"FusedFileStatusOut":{"properties":{"status":{"type":"string","enum":["in_progress","completed","failed"],"title":"Status","description":"`in_progress` while the document is being translated and reviewed; then `completed`, or `failed` if the order could not be placed or was cancelled."},"detected_source_lang":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Detected Source Lang","description":"The source language the order was placed with."},"estimated_duration_left_in_seconds":{"type":"integer","title":"Estimated Duration Left In Seconds","description":"Time remaining until the promised delivery. Negative means the promise has passed. 0 until a reviewer has the document, since there is no promise to count down yet.","default":0},"error":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error","description":"Why the order failed. Null unless `status` is `failed`."}},"type":"object","required":["status"],"title":"FusedFileStatusOut","description":"Where the order has got to.\n\nThe text family's three states, unchanged in meaning: `in_progress` covers\nboth the machine translation and the review, because a client can do\nnothing differently with the distinction. `error` is the addition, and it\nis set only on `failed`."},"FusedTranslationAcceptedOut":{"properties":{"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Id of this request, also returned as the `X-Request-ID` header. Quote it to support."},"translation_id":{"type":"string","title":"Translation Id","description":"Id of the human-review order. Pass it to the status and download endpoints. A UUID -- v1 used an integer."},"briefing_applied":{"type":"boolean","title":"Briefing Applied","description":"Whether a briefing was applied, and therefore which service was ordered. This is the stable discriminator; `service_label` is for display."},"service_label":{"type":"string","title":"Service Label","description":"Human-readable name of the service ordered. Display only -- do not branch on it."}},"type":"object","required":["translation_id","briefing_applied","service_label"],"title":"FusedTranslationAcceptedOut","description":"v1's 202 body, plus the two fields that say which service was ordered."},"FusedTranslationDownloadOut":{"properties":{"translated_text":{"type":"string","title":"Translated Text","description":"The reviewed translation."}},"type":"object","required":["translated_text"],"title":"FusedTranslationDownloadOut","description":"v1's download body, unchanged."},"FusedTranslationIn":{"properties":{"text":{"type":"string","minLength":1,"title":"Text","description":"Text to translate and have reviewed by a human."},"source_lang":{"type":"string","maxLength":20,"minLength":2,"title":"Source Lang","description":"Source language (BCP 47). Required here, unlike on `/translate/ai/text`: the review is priced and routed to a linguist before anything is translated, and both need the pair up front."},"target_lang":{"type":"string","maxLength":20,"minLength":2,"title":"Target Lang","description":"Target language (BCP 47)."},"politeness":{"type":"string","enum":["default","more","less"],"title":"Politeness","description":"Politeness of the machine translation the reviewer starts from.","default":"default"},"briefing":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}],"title":"Briefing","description":"Instructions for the human reviewer -- tone, audience, what the text is for. **Sending a briefing orders Optimisation instead of Verification**: the reviewer works to your brief rather than only checking correctness, which changes the price and the delivery time. Omit it for Verification."}},"type":"object","required":["text","source_lang","target_lang"],"title":"FusedTranslationIn","description":"v1's `FusedTranslationRequest`, plus `briefing`.\n\n`text` is a bare string, not a list: that is v1's shape here, and unlike\nthe AI endpoint it is not an arbitrary choice -- one request becomes one\nhuman-review job over one continuous text, and a list would have to either\ninvent N jobs or silently concatenate."},"FusedTranslationQuoteOut":{"properties":{"prices":{"additionalProperties":{"type":"number"},"type":"object","title":"Prices","description":"What the same request costs, keyed by lower-case ISO 4217 code. The machine translation is included -- this is the whole price."},"estimated_duration_in_seconds":{"type":"integer","title":"Estimated Duration In Seconds","description":"How long delivery is expected to take, from now."},"word_count":{"type":"integer","title":"Word Count","description":"Source words the price is computed from."},"briefing_applied":{"type":"boolean","title":"Briefing Applied","description":"Whether this quote is for Optimisation (true) or Verification."},"service_label":{"type":"string","title":"Service Label","description":"Human-readable name of the service quoted. Display only."}},"type":"object","required":["prices","estimated_duration_in_seconds","word_count","briefing_applied","service_label"],"title":"FusedTranslationQuoteOut","description":"What a human-assisted translation would cost and how long it would take.\n\n`prices` is v1's shape -- a float per currency code, lower-cased -- with one\nentry, the workspace's own billing currency, which is known from the\ncredential.\n\n**It is the whole price of the call.** The machine translation that produces\nthe reviewer's draft is part of the service, not a second charge: the\ncustomer is buying Verification or Optimisation, and what they are quoted is\nwhat they pay. That is v1's behaviour (its usage row for a fused call\ncarried the ORDER price and counted the call as a \"profi check\", not as\ncharacters) and it is the same relationship language detection has to a\ntranslation that omits `source_lang` -- the work happens, and the quoted\nprice already covers it.\n\n`word_count` is here because words are the unit the price is computed in, so\na client can see why the number is what it is. There is deliberately no\n`character_count`: on the AI endpoints that field means \"what this request\nwill meter\", and nothing here meters characters.\n\n**Unlike v1, this quote is a real dry run.** v1 had to run the full AI\ntranslation before it could quote, because its upstream priced the target\ntext -- so asking the price of a fused translation cost the same compute as\nordering one, contradicting its own documentation's claim that quote\nendpoints are a dry-run utility. Neo prices the review on SOURCE words, so\nnothing is translated and nothing is metered to answer this."},"FusedTranslationStatusOut":{"properties":{"status":{"type":"string","enum":["in_progress","completed","failed"],"title":"Status","description":"`in_progress` until a reviewer delivers; then `completed`, or `failed` if the order was cancelled."},"detected_source_lang":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Detected Source Lang","description":"The source language the order was placed with."},"estimated_duration_left_in_seconds":{"type":"integer","title":"Estimated Duration Left In Seconds","description":"Time remaining until the promised delivery. Negative means the promise has passed.","default":0}},"type":"object","required":["status"],"title":"FusedTranslationStatusOut","description":"v1's status body, unchanged in shape.\n\nTwo behavioural corrections inside it. v1 declared a `failed` status and\nnever emitted one -- a cancelled order polled as `in_progress` forever --\nand it clamped a late delivery to exactly `-1`, discarding how late it\nactually was even though its own field description says a negative number\nsignifies a delay. v1 emits `failed` and reports the real number."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"LanguageDetectionOut":{"properties":{"detected_languages":{"items":{"$ref":"#/components/schemas/DetectedLanguageOut"},"type":"array","title":"Detected Languages","description":"The detected language. A list for compatibility with v1, which ranked candidates; Neo's identifier returns a single answer, so there is exactly one entry — or none when detection failed."}},"type":"object","required":["detected_languages"],"title":"LanguageDetectionOut"},"PublicFeature":{"type":"string","enum":["supports_politeness","supports_glossary","supports_fused_translation"],"title":"PublicFeature","description":"v1's feature vocabulary, unchanged — these strings are a wire contract.\n\nThey are named `supports_*` because that is what v1 emitted and what every\nexisting integration matches on, even though the enclosing field is already\ncalled `features`."},"TextDetectionIn":{"properties":{"text":{"type":"string","minLength":1,"title":"Text","description":"Text whose language should be detected."}},"type":"object","required":["text"],"title":"TextDetectionIn"},"TextQuoteOut":{"properties":{"character_count":{"type":"integer","title":"Character Count","description":"Source characters this request would meter."},"prices":{"additionalProperties":{"type":"number"},"type":"object","title":"Prices","description":"Cost of these characters, keyed by lower-case currency code. One entry: the workspace's own billing currency. Deliberately not rounded to the cent — usage is priced on an accumulated character total rather than per request, so this is the fraction this request contributes."}},"type":"object","required":["character_count","prices"],"title":"TextQuoteOut","description":"What a translation would cost, before committing to it.\n\n**The legacy shape, restored.** An earlier cut of v1 answered `character_count`,\n`currency` and an integer `price_cents`, reasoning that Neo bills one\nworkspace in one currency and holds money as integer cents. Both halves of\nthat are true and the conclusion was still wrong, because the cent is not\nthe unit this number lives in.\n\nNothing is charged per request. `record_usage` accrues CHARACTERS onto the\nperiod's counter and `settle_overage` prices the accumulated total once, at\nmost once a day — so one request's incremental cost is a fraction of a\ncent, and rounding it up to a whole cent does not make the quote an upper\nbound so much as an overstatement. A 28-character request at 2,000 cents\nper million costs 0.00056 in the workspace's currency; `price_cents: 1`\nreported that as roughly eighteen times its actual contribution to the\nbill, and a batch of small quotes compounded the error. The float carries\nthe information the integer threw away and is closer to what the customer\nis actually charged.\n\nSo: `prices`, keyed by lower-case currency code as in v1, to 6 decimal\nplaces (v1's `COST_N_DECIMALS`). One entry, because the workspace's billing\ncurrency is known from the credential, where v1 answered every currency its\ncustomers might be invoiced in. A client reading `prices[\"chf\"]` keeps\nworking; one enumerating the map keeps working too.\n\nThe price is marginal: what the request would cost beyond the plan's API &\nMCP quota at the time of the quote, so 0.0 while it fits inside the quota\nand the slice past it otherwise. There is no \"covered by your plan\" field to\nreport. A plan priced at 0 — API usage included by contract — answers 0.0,\nwhich is the truth rather than an absence.\n\nA quote is deliberately free of the quota gate: the moment a caller most\nneeds to ask the price is the moment they have run out."},"TextTranslationIn":{"properties":{"text":{"items":{"type":"string"},"type":"array","minItems":1,"title":"Text","description":"Text to translate. Each item is handled as a separate context and comes back at the same position in `translated_text`."},"source_lang":{"anyOf":[{"type":"string","maxLength":20},{"type":"null"}],"title":"Source Lang","description":"Source language (BCP 47). Detected from the text when omitted."},"target_lang":{"type":"string","maxLength":20,"minLength":2,"title":"Target Lang","description":"Target language (BCP 47). Required."},"politeness":{"type":"string","enum":["default","more","less"],"title":"Politeness","description":"Politeness of the translation. Not every language has a distinction.","default":"default"},"glossary":{"anyOf":[{"additionalProperties":{"type":"string"},"type":"object"},{"type":"null"}],"title":"Glossary","description":"Ad-hoc glossary as source → target term pairs, applied to this request only. At most 100 terms."},"tag_handling":{"type":"string","enum":["none","xml","html"],"title":"Tag Handling","description":"Carry inline markup through the translation instead of translating it: `xml` parses strictly, `html` tolerates malformed markup.","default":"none"}},"type":"object","required":["text","target_lang"],"title":"TextTranslationIn","description":"One translation request. `text` is a LIST because v1's is: each item is\ntranslated as its own context, and the response returns one translation per\nitem, in order."},"TextTranslationOut":{"properties":{"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Id of this request, also returned as the `X-Request-ID` header. Quote it to support."},"detected_source_lang":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Detected Source Lang","description":"The source language used — detected when the request omitted one."},"translated_text":{"items":{"type":"string"},"type":"array","title":"Translated Text","description":"One translation per item of `text`, in the same order."},"enforced_terms":{"anyOf":[{"additionalProperties":{"type":"string"},"type":"object"},{"type":"null"}],"title":"Enforced Terms","description":"Glossary terms the engine actually applied. Null when no glossary was sent."}},"type":"object","required":["translated_text"],"title":"TextTranslationOut","description":"v1's response shape, minus nothing and plus nothing."},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"},"input":{"title":"Input"},"ctx":{"type":"object","title":"Context"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"},"WebhookCreateIn":{"properties":{"url":{"type":"string","title":"Url","description":"Where we POST events. `https` only, no credentials in the URL, at most 2,048 characters."},"event_types":{"items":{"type":"string"},"type":"array","title":"Event Types","description":"The event types to receive. At least one; see the Webhooks section for the list."},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description","description":"A note for your own reference, at most 200 characters."}},"type":"object","required":["url","event_types"],"title":"WebhookCreateIn"},"WebhookCreatedOut":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"url":{"type":"string","title":"Url"},"event_types":{"items":{"type":"string"},"type":"array","title":"Event Types"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"status":{"type":"string","enum":["active","disabled"],"title":"Status"},"disabled_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Disabled Reason","description":"Why a disabled webhook was switched off: `gone` (it answered 410) or `failing`."},"created_at":{"type":"string","format":"date-time","title":"Created At"},"last_delivery_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Delivery At","description":"When an event last reached it."},"last_failure_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Failure At"},"last_failure_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Last Failure Reason","description":"A short code for the last failed attempt, such as `http_500`, `timeout` or `connect_error`."},"consecutive_failures":{"type":"integer","title":"Consecutive Failures"},"secret":{"type":"string","title":"Secret","description":"The signing secret, `whsec_…`. Shown only in this response: store it now."}},"type":"object","required":["id","url","event_types","description","status","disabled_reason","created_at","last_delivery_at","last_failure_at","last_failure_reason","consecutive_failures","secret"],"title":"WebhookCreatedOut"},"WebhookListOut":{"properties":{"items":{"items":{"$ref":"#/components/schemas/WebhookOut"},"type":"array","title":"Items"}},"type":"object","required":["items"],"title":"WebhookListOut"},"WebhookOut":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"url":{"type":"string","title":"Url"},"event_types":{"items":{"type":"string"},"type":"array","title":"Event Types"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"status":{"type":"string","enum":["active","disabled"],"title":"Status"},"disabled_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Disabled Reason","description":"Why a disabled webhook was switched off: `gone` (it answered 410) or `failing`."},"created_at":{"type":"string","format":"date-time","title":"Created At"},"last_delivery_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Delivery At","description":"When an event last reached it."},"last_failure_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Failure At"},"last_failure_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Last Failure Reason","description":"A short code for the last failed attempt, such as `http_500`, `timeout` or `connect_error`."},"consecutive_failures":{"type":"integer","title":"Consecutive Failures"}},"type":"object","required":["id","url","event_types","description","status","disabled_reason","created_at","last_delivery_at","last_failure_at","last_failure_reason","consecutive_failures"],"title":"WebhookOut"},"WebhookTestOut":{"properties":{"delivered":{"type":"boolean","title":"Delivered","description":"True when your endpoint answered with a 2xx status."},"status_code":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Status Code","description":"Your endpoint's HTTP status; null when no response arrived."},"error":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error","description":"Why no response arrived, or `redirect` for a 3xx."},"duration_ms":{"type":"integer","title":"Duration Ms"}},"type":"object","required":["delivered","status_code","error","duration_ms"],"title":"WebhookTestOut"},"WebhookUpdateIn":{"properties":{"url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Url","description":"Where we POST events. `https` only, no credentials in the URL, at most 2,048 characters."},"event_types":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Event Types","description":"The event types to receive. At least one; see the Webhooks section for the list."},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description","description":"A note for your own reference, at most 200 characters."},"enabled":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Enabled","description":"`true` switches a disabled webhook back on and resets its failure count."}},"type":"object","title":"WebhookUpdateIn","description":"Only the fields sent change. `description: null` clears the note."}},"securitySchemes":{"Workspace API key":{"type":"http","description":"A workspace API key, created by a workspace admin under Settings. Send it as `Authorization: Bearer st_live_...`.","scheme":"bearer"}}},"tags":[{"name":"Text Translation","description":"Translate plain text with AI or human assistance, or request a quote before ordering."},{"name":"File Translation","description":"Translate documents with AI or human review, follow progress, and download the result."},{"name":"Feature Scope","description":"Discover supported language pairs and their available features."},{"name":"Language Detection","description":"Identify the language of text or files, or quote detection."},{"name":"account","description":"Check your API key and workspace without incurring usage costs."},{"name":"Webhooks","description":"Register endpoints that we call when your translations finish or your workspace needs attention."}]} \ No newline at end of file diff --git a/spec/v2/webhooks.json b/spec/v2/webhooks.json new file mode 100644 index 0000000..02bc000 --- /dev/null +++ b/spec/v2/webhooks.json @@ -0,0 +1,258 @@ +{ + "description": "Verifying a webhook request (Standard Webhooks). Input: the secret from the create response (`whsec_` + base64; the prefix is optional), the request headers (names in any case), the raw body as received (a string; sign over its UTF-8 bytes) and the current Unix time. The signed content is `{webhook-id}.{webhook-timestamp}.{body}`; the expected signature is the base64 HMAC-SHA256 of it, keyed with the base64-decoded secret. `webhook-signature` holds one or more space-separated `,` entries: valid when a `v1` entry equals the expected signature (compare in constant time). The timestamp must be an integer within 300 seconds of now, either way. Then the body must be a JSON object with string `type` and `timestamp`; `data` is its `data` object (an empty object when absent or not an object). The result is the event: `id` (the webhook-id header, for de-duplication: delivery is at least once), `type`, `timestamp`, `data`. Any failure throws `invalid_webhook` (no detail that echoes the secret or the signature).", + "toleranceSeconds": 300, + "cases": [ + { + "name": "valid", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656723, + "event": { + "id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "type": "translation.ai_file.completed", + "timestamp": "2026-10-28T13:05:12Z", + "data": { + "file_id": "b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30" + } + } + }, + { + "name": "secret without the whsec_ prefix", + "secret": "c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "event": { + "id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "type": "translation.ai_file.completed", + "timestamp": "2026-10-28T13:05:12Z", + "data": { + "file_id": "b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30" + } + } + }, + { + "name": "header names in any case", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "Webhook-Id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "WEBHOOK-TIMESTAMP": "1761656713", + "Webhook-Signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "event": { + "id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "type": "translation.ai_file.completed", + "timestamp": "2026-10-28T13:05:12Z", + "data": { + "file_id": "b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30" + } + } + }, + { + "name": "several signatures, one matches (key rotation)", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= v2,whatever v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "event": { + "id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "type": "translation.ai_file.completed", + "timestamp": "2026-10-28T13:05:12Z", + "data": { + "file_id": "b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30" + } + } + }, + { + "name": "UTF-8 body", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,6xs9z8ZYHckI2Q8QiB5pdIrsslskJgzKxy2uc/VZKzw=" + }, + "body": "{\"type\":\"wallet.low_balance\",\"timestamp\":\"2026-11-01T00:00:00Z\",\"data\":{\"currency\":\"CHF\",\"balance\":\"18.40\",\"note\":\"Zürich 😀\"}}", + "now": 1761656713, + "event": { + "id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "type": "wallet.low_balance", + "timestamp": "2026-11-01T00:00:00Z", + "data": { + "currency": "CHF", + "balance": "18.40", + "note": "Zürich 😀" + } + } + }, + { + "name": "five minutes old still passes", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761657013, + "event": { + "id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "type": "translation.ai_file.completed", + "timestamp": "2026-10-28T13:05:12Z", + "data": { + "file_id": "b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30" + } + } + }, + { + "name": "older than five minutes", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761657014, + "error": "invalid_webhook" + }, + { + "name": "more than five minutes in the future", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656412, + "error": "invalid_webhook" + }, + { + "name": "body changed", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f4a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "error": "invalid_webhook" + }, + { + "name": "wrong secret", + "secret": "whsec_YW5vdGhlciBzZWNyZXQ=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "error": "invalid_webhook" + }, + { + "name": "id changed", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "other-id", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "error": "invalid_webhook" + }, + { + "name": "signature without v1, prefix", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "error": "invalid_webhook" + }, + { + "name": "signature missing", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "error": "invalid_webhook" + }, + { + "name": "timestamp not a number", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "soon", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "error": "invalid_webhook" + }, + { + "name": "signed but not a JSON event", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,nFqw+UGSdmtvOTIIojl83Sd/q51F7KjixwXW4QGAdDQ=" + }, + "body": "[1,2]", + "now": 1761656713, + "error": "invalid_webhook" + }, + { + "name": "signed event without data", + "secret": "whsec_c3VwZXJ0ZXh0LWNvbmZvcm1hbmNlLXdlYmhvb2stc2VjcmV0ISE=", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,FqtkIEKKW4qr9e2+16irmeel/RNR/7AlJGvafRLmqv4=" + }, + "body": "{\"type\":\"invoice.issued\",\"timestamp\":\"2026-11-01T00:00:00Z\"}", + "now": 1761656713, + "event": { + "id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "type": "invoice.issued", + "timestamp": "2026-11-01T00:00:00Z", + "data": {} + } + }, + { + "name": "empty secret", + "secret": "whsec_", + "headers": { + "webhook-id": "2f6c1b0e-9d4a-4e37-8c15-7a3b9e2d4f60", + "webhook-timestamp": "1761656713", + "webhook-signature": "v1,oalv6LA58QefCRGbdECoqRFfxpXkVAaLH0hiqZi4gP4=" + }, + "body": "{\"type\":\"translation.ai_file.completed\",\"timestamp\":\"2026-10-28T13:05:12Z\",\"data\":{\"file_id\":\"b0f3a1d84c6e4a7f9c2e5d1b8a7f6e30\"}}", + "now": 1761656713, + "error": "invalid_webhook" + } + ] +} diff --git a/stand-in/conformance.mjs b/stand-in/conformance.mjs index 41b0f78..c64d032 100644 --- a/stand-in/conformance.mjs +++ b/stand-in/conformance.mjs @@ -3,7 +3,8 @@ * Runs an SDK's conformance program against the stand-in for every scenario in * spec/conformance.json. * - * node stand-in/conformance.mjs -- [args…] + * node stand-in/conformance.mjs -- [args…] (API v1) + * node stand-in/conformance.mjs --v2 -- [args…] (API v2, spec/v2/conformance.json) * * The command is started once per scenario with SUPERTEXT_API_URL and * SUPERTEXT_API_KEY set and the scenario's request as JSON on stdin. It must @@ -13,14 +14,16 @@ import { spawn } from 'node:child_process'; import { readFileSync } from 'node:fs'; import { isDeepStrictEqual } from 'node:util'; import { createStandIn } from './stand-in.mjs'; +import { createStandInV2 } from './stand-in-v2.mjs'; +const v2 = process.argv.slice(2, process.argv.indexOf('--')).includes('--v2'); const separator = process.argv.indexOf('--'); const command = separator >= 0 ? process.argv.slice(separator + 1) : []; if (command.length === 0) { - console.error('usage: node stand-in/conformance.mjs -- [args…]'); + console.error('usage: node stand-in/conformance.mjs [--v2] -- [args…]'); process.exit(2); } -const spec = JSON.parse(readFileSync(new URL('../spec/conformance.json', import.meta.url), 'utf8')); +const spec = JSON.parse(readFileSync(new URL(v2 ? '../spec/v2/conformance.json' : '../spec/conformance.json', import.meta.url), 'utf8')); const run = (env, input) => new Promise((resolve, reject) => { @@ -36,7 +39,7 @@ const run = (env, input) => let failures = 0; for (const scenario of spec.scenarios) { - const server = createStandIn({ rateLimit: scenario.rateLimit }); + const server = (v2 ? createStandInV2 : createStandIn)({ rateLimit: scenario.rateLimit }); await new Promise((r) => server.listen(0, '127.0.0.1', r)); const base = `http://127.0.0.1:${server.address().port}/v1/`; const problems = []; @@ -61,6 +64,9 @@ for (const scenario of spec.scenarios) { for (const [name, value] of Object.entries(scenario.expectedStats ?? {})) { if (stats[name] !== value) problems.push(`stand-in ${name}: expected ${value}, got ${stats[name]}`); } + for (const [name, value] of Object.entries(scenario.expectedText ?? {})) { + if (stats.lastText?.[name] !== value) problems.push(`text request ${name}: expected ${JSON.stringify(value)}, got ${JSON.stringify(stats.lastText?.[name])}`); + } for (const [name, value] of Object.entries(scenario.expectedUpload ?? {})) { if (stats.lastUpload?.[name] !== value) problems.push(`upload ${name}: expected ${JSON.stringify(value)}, got ${JSON.stringify(stats.lastUpload?.[name])}`); } diff --git a/stand-in/stand-in-v2.mjs b/stand-in/stand-in-v2.mjs new file mode 100644 index 0000000..dde9d6f --- /dev/null +++ b/stand-in/stand-in-v2.mjs @@ -0,0 +1,239 @@ +#!/usr/bin/env node +/** + * Stand-in for the Supertext API v2 (api-platform.supertext.com/v1), for tests, + * CI and screenshots. Node 22+, no dependencies. It covers what the SDKs' v2 + * translateTexts, translateHtml, the key check and the conformance scenarios + * use: GET account, GET features, POST translate/ai/text (+ /quote), the AI + * file endpoints (+ /quote) and POST detect-languages/text. Human review + * (`fused`) and webhooks are not simulated. + * + * It behaves like the live API where integrations can go wrong: + * - Authorization must be exactly `Bearer `: otherwise 401. The key + * `invalid` is rejected with 401; the key `no-credit` gets 402 + * (reason `insufficient_credit`) on every billable endpoint. + * - Errors are problem+json with `code`, `detail` and `error_id`. + * - target_lang and source_lang must be codes of spec/languages.json: else 422 + * validation_error. More than 10,000 characters per text request, or more than + * 100 glossary terms: 422. + * - The first status poll of a file answers `translating`, the next the result; + * the download answers 202 until then. + * + * "Translations": each text, and each `
` of an HTML file, comes + * back with `[] ` in front of its text (after any leading tags). + * + * Test hooks: + * - rateLimit (STAND_IN_RATE_LIMIT=1): the first billable request gets 429 (Retry-After: 1). + * - A file containing `STAND-IN:error` / `STAND-IN:deleted` gets that status. + * - GET /__stand-in/stats: counters and the last request's fields. + * - POST /__stand-in/reset. + * + * CLI: `node stand-in/stand-in-v2.mjs` listens on PORT (default 8766) and prints + * the base URL, e.g. http://127.0.0.1:8766/v1/. + */ +import http from 'node:http'; +import { randomBytes } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const MAX_TEXT_CHARACTERS = 10_000; +const MAX_FILE_BYTES = 30 * 1024 * 1024; +const LANGUAGES = JSON.parse(readFileSync(fileURLToPath(new URL('../spec/languages.json', import.meta.url)), 'utf8')); +const SOURCES = new Set(LANGUAGES.sources.map((l) => l.code)); +const TARGETS = new Map(LANGUAGES.targets.map((l) => [l.code, l])); +const FEATURES = LANGUAGES.sources.flatMap((s) => + LANGUAGES.targets + .filter((t) => t.code.split('-')[0] !== s.code) + .map((t) => ({ source_lang: s.code, target_lang: t.code, features: t.politeness ? ['supports_politeness', 'supports_glossary'] : ['supports_glossary'] })), +); +const PRICE_PER_CHARACTER = 0.00002; + +const translate = (text, target) => text.replace(/^((?:\s*<[^>]+>)*)/, `$1[${target}] `); + +/** + * @param {{ rateLimit?: boolean, log?: (line: string) => void }} [options] + * @returns {http.Server} + */ +export function createStandInV2(options = {}) { + const log = options.log ?? (() => {}); + let files; + let stats; + const reset = () => { + files = new Map(); + stats = { textRequests: 0, quotes: 0, submitted: 0, deleted: 0, polls: 0, downloads: 0, detections: 0, rateLimited: 0, rejected: 0, lastText: null, lastUpload: null, lastAuthorization: null }; + }; + reset(); + + return http.createServer(async (req, res) => { + const url = new URL(req.url ?? '/', 'http://stand-in'); + const path = url.pathname.replace(/^\/v1(?=\/)/, ''); + const requestId = randomBytes(6).toString('hex'); + const send = (status, body, headers = {}) => { + res.writeHead(status, { 'Content-Type': 'application/json', 'X-Request-ID': requestId, ...headers }); + res.end(JSON.stringify(body)); + }; + const problem = (status, code, detail, extra = {}, headers = {}) => { + stats.rejected++; + log(`${req.method} ${path} -> ${status} ${code}: ${detail}`); + res.writeHead(status, { 'Content-Type': 'application/problem+json', 'X-Request-ID': requestId, ...headers }); + res.end(JSON.stringify({ type: `urn:supertext:error:${code}`, title: http.STATUS_CODES[status], status, detail, code, error_id: randomBytes(4).toString('hex'), ...extra })); + }; + const body = async () => { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + return Buffer.concat(chunks); + }; + + if (path === '/__stand-in/stats') return send(200, stats); + if (path === '/__stand-in/reset' && req.method === 'POST') { + reset(); + return send(200, {}); + } + + const auth = req.headers.authorization ?? ''; + stats.lastAuthorization = auth; + const key = auth.startsWith('Bearer ') ? auth.slice('Bearer '.length) : ''; + if (!/^\S+$/.test(key) || key === 'invalid') { + return problem(401, 'unauthorized', 'Missing or invalid API key.', {}, { 'WWW-Authenticate': 'Bearer' }); + } + // Billable endpoints: rate limit and credit checks. + const billable = req.method === 'POST' && /^\/(translate\/ai\/(text|file)|detect-languages\/text)$/.test(path); + if (billable && options.rateLimit && stats.rateLimited === 0) { + stats.rateLimited++; + await body(); + return problem(429, 'rate_limited', 'Too many requests.', {}, { 'Retry-After': '1' }); + } + if (billable && key === 'no-credit') { + await body(); + return problem(402, 'payment_required', 'The credit balance does not cover this request.', { reason: 'insufficient_credit' }); + } + + const checkLanguages = (target, source) => { + if (!TARGETS.has(target)) return 'body.target_lang: unsupported target language'; + if (source !== null && !SOURCES.has(source)) return 'body.source_lang: unsupported source language'; + return null; + }; + + if (req.method === 'GET' && path === '/account') { + return send(200, { workspace_id: 'ws_standin', workspace_name: 'Stand-in workspace', api_key_name: 'Conformance', api_key_prefix: key.slice(0, 12), api_key_expires_at: '2027-12-31T00:00:00Z' }); + } + if (req.method === 'GET' && path === '/features') { + const s = url.searchParams.get('source_lang'); + const t = url.searchParams.get('target_lang'); + return send(200, { supported_features: FEATURES.filter((p) => (!s || p.source_lang === s) && (!t || p.target_lang === t)) }); + } + + if (req.method === 'POST' && (path === '/translate/ai/text' || path === '/translate/ai/text/quote')) { + let input; + try { + input = JSON.parse((await body()).toString('utf8')); + } catch { + return problem(422, 'validation_error', 'body: invalid JSON'); + } + const texts = input?.text; + if (!Array.isArray(texts) || texts.some((t) => typeof t !== 'string')) return problem(422, 'validation_error', 'body.text: a list of strings is required'); + const target = typeof input.target_lang === 'string' ? input.target_lang : ''; + const source = typeof input.source_lang === 'string' ? input.source_lang : null; + const language = checkLanguages(target, source); + if (language) return problem(422, 'validation_error', language); + const politeness = input.politeness ?? 'default'; + if (!['default', 'more', 'less'].includes(politeness)) return problem(422, 'validation_error', 'body.politeness: invalid'); + const tagHandling = input.tag_handling ?? 'none'; + if (!['none', 'xml', 'html'].includes(tagHandling)) return problem(422, 'validation_error', 'body.tag_handling: invalid'); + const characters = texts.reduce((n, t) => n + [...t].length, 0); + if (characters > MAX_TEXT_CHARACTERS) return problem(422, 'validation_error', `body.text: at most ${MAX_TEXT_CHARACTERS} characters per request`); + const glossary = input.glossary ?? null; + if (glossary !== null && Object.keys(glossary).length > 100) return problem(422, 'validation_error', 'body.glossary: at most 100 terms'); + if (path.endsWith('/quote')) { + stats.quotes++; + return send(200, { character_count: characters, prices: { chf: characters * PRICE_PER_CHARACTER } }); + } + stats.textRequests++; + stats.lastText = { source_lang: source, target_lang: target, politeness, tag_handling: tagHandling, count: texts.length, characters, glossary }; + log(`POST text target_lang=${target} source_lang=${source ?? '-'} tag_handling=${tagHandling} texts=${texts.length}`); + return send(200, { + request_id: requestId, + detected_source_lang: source ?? 'en', + translated_text: texts.map((t) => (t.trim() === '' ? t : translate(t, target))), + enforced_terms: glossary, + }); + } + + if (req.method === 'POST' && path === '/detect-languages/text') { + await body(); + stats.detections++; + return send(200, { detected_languages: [{ lang_code: 'en', confidence: 0.99, supports_translation: true }] }); + } + + if (req.method === 'POST' && (path === '/translate/ai/file' || path === '/translate/ai/file/quote')) { + const raw = await body(); + if (raw.length > MAX_FILE_BYTES) return problem(413, 'payload_too_large', 'The file is larger than 30 MiB.'); + let form; + try { + form = await new Request('http://stand-in', { method: 'POST', headers: req.headers, body: raw }).formData(); + } catch (error) { + return problem(422, 'validation_error', `body: invalid multipart (${error.message})`); + } + const file = form.get('file'); + if (!file || typeof file === 'string') return problem(422, 'validation_error', 'body.file: required'); + const target = String(form.get('target_lang') ?? ''); + const source = form.has('source_lang') ? String(form.get('source_lang')) : null; + const language = checkLanguages(target, source); + if (language) return problem(422, 'validation_error', language); + const politeness = form.has('politeness') ? String(form.get('politeness')) : null; + const content = await file.text(); + if (path.endsWith('/quote')) { + stats.quotes++; + return send(200, { character_count: [...content].length, prices: { chf: [...content].length * PRICE_PER_CHARACTER } }); + } + const id = randomBytes(16).toString('hex'); + const status = content.includes('STAND-IN:error') ? 'error' : content.includes('STAND-IN:deleted') ? 'deleted' : 'done'; + files.set(id, { content, name: file.name, target, source, status, polls: 0 }); + stats.submitted++; + stats.lastUpload = { target_lang: target, source_lang: source, politeness, glossary: form.has('glossary') ? String(form.get('glossary')) : null, file_name: file.name, content_type: file.type }; + log(`POST file target_lang=${target} source_lang=${source ?? '-'} -> ${id}`); + return send(202, { request_id: requestId, file_id: id }); + } + + const match = path.match(/^\/translate\/ai\/file\/([a-f0-9]+)(\/status|\/translation)?$/); + if (!match || !files.has(match[1])) return problem(404, 'not_found', 'No such file.'); + const entry = files.get(match[1]); + const ready = entry.polls >= 2; + + if (req.method === 'DELETE' && !match[2]) { + files.delete(match[1]); + stats.deleted++; + return send(200, { file_id: match[1], status: 'deleted' }); + } + if (req.method === 'GET' && match[2] === '/status') { + stats.polls++; + entry.polls++; + const status = entry.polls === 1 ? 'translating' : entry.status; + return send(200, { + file_id: match[1], + status, + error: status === 'error' ? 'The document could not be translated.' : null, + estimated_duration_left_in_seconds: status === 'translating' ? 2 : 0, + detected_source_lang: entry.source ?? 'en', + }); + } + if (req.method === 'GET' && match[2] === '/translation') { + if (!ready || entry.status !== 'done') return send(202, { status: 'in_progress' }); + stats.downloads++; + const out = entry.content.replace(/(
)([\s\S]*?)(<\/div>\n)/g, (all, open, inner, close) => + inner.trim() === '' ? all : open + translate(inner, entry.target) + close, + ); + const dot = entry.name.lastIndexOf('.'); + const name = dot > 0 ? `${entry.name.slice(0, dot)}.${entry.target}${entry.name.slice(dot)}` : `${entry.name}.${entry.target}`; + res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Disposition': `attachment; filename="${name}"`, 'X-Request-ID': requestId }); + return res.end(out); + } + return problem(405, 'method_not_allowed', 'Method not allowed.'); + }); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const port = Number(process.env.PORT || 8766); + const server = createStandInV2({ rateLimit: process.env.STAND_IN_RATE_LIMIT === '1', log: (line) => console.log(line) }); + server.listen(port, '127.0.0.1', () => console.log(`Supertext v2 stand-in on http://127.0.0.1:${port}/v1/`)); +}