Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sdk): JavaScript, Python, and PHP client libraries (#463)
Yudhi Armyndharis55ad38808f1d
diff --git a/sdk/README.md b/sdk/README.mdindex 97219813d..025ed7e8b 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -1,15 +1,50 @@# OpenWA SDKs-Official client libraries for the OpenWA WhatsApp API Gateway.+Official client libraries for the [OpenWA](https://github.com/rmyndharis/OpenWA)+WhatsApp API Gateway.-> **Note:** These SDKs are scaffolds and will be auto-generated from the OpenAPI spec in the future. They provide a working starting point for community contributions.+All three SDKs are **hand-written** against the exact API surface (paths, DTOs,+response shapes) and **unit-tested with mocked HTTP transports** that assert on+the precise request URL, method, and body — so drift is caught at test time.+The wire types live in a dedicated module (`types.ts` / `types.py`) so they can+later be regenerated by an OpenAPI codegen pass without touching the+hand-written resource methods.++| Language | Package | Notes |+| ----------------------- | ---------------------------- | --------------------------- |+| JavaScript / TypeScript | [`@openwa/sdk`](javascript/) | dual ESM/CJS, bundled types |+| Python | [`openwa-sdk`](python/) | sync (httpx), PEP 561 typed |+| PHP | [`openwa/sdk`](php/) | sync (Guzzle, PHP 8.1+) |++## Coverage++Both SDKs expose the same fluent resource surface:++| Resource | Methods |+| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `sessions` | list, get, create, delete, start, stop, forceKill, getQrCode, requestPairingCode, stats |+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, reply, forward, react, delete, history, reactions, sendBulk, batchStatus, cancelBatch |+| `contacts` | list, get, check, profilePicture, phone, block, unblock |+| `groups` | list, get, create, add/remove/promote/demoteParticipants, setSubject, setDescription, leave, inviteCode, revokeInviteCode |+| `webhooks` | list, get, create, update, delete, test |+| `chats` | list, markRead, markUnread, delete, sendState |+| `labels` | list, get, forChat, addToChat, removeFromChat _(WhatsApp Business)_ |+| `channels` | list, get, messages, subscribe, unsubscribe _(Newsletters)_ |+| `catalog` | info, products, product, sendProduct, sendCatalog _(WhatsApp Business)_ |+| `status` | list, fromContact, sendText, sendImage, sendVideo, delete _(Stories)_ |+| `templates`| list, get, create, update, delete |+| `health` | check, live, ready |++> ⚠️ Endpoints requiring an `OPERATOR`-level API key are noted in the inline+> docs. Operator-only modules (`docker`, `metrics`, `infra`, `plugins`, `mcp`)+> are intentionally **not** exposed in the SDK; all user-facing resources are.## JavaScript / TypeScript```bashcd sdk/javascriptnpm install-npm run build+npm run build # dual ESM + CJS output in dist/``````typescript@@ -17,32 +52,112 @@ import { OpenWAClient } from '@openwa/sdk';const client = new OpenWAClient({baseUrl: 'http://localhost:2785',- apiKey: 'your-api-key',+ apiKey: 'owa_k1_…',});-const result = await client.messages.sendText('session-1', {+await client.sessions.start('my-session');+const result = await client.messages.sendText('my-session', {chatId: '[email protected]',- text: 'Hello from OpenWA SDK!',+ text: 'Hello from the OpenWA SDK!',});+console.log(result.messageId);+```++Errors are typed — branch with `instanceof`:++```typescript+import { OpenWANotFoundError, OpenWAConflictError } from '@openwa/sdk';+try {+ await client.messages.sendText(/* … */);+} catch (e) {+ if (e instanceof OpenWAConflictError) {+ /* engine not ready (409) */+ }+}```+> Requires Node 18+ (uses the global `fetch`). Pass a custom `fetch` to the+> client constructor to intercept or observability-wrap requests.+## Python```bashcd sdk/python-pip install -e .+pip install -e ".[dev]"``````python-from openwa import OpenWAClient+from openwa import OpenWAClient, OpenWANotFoundErrorclient = OpenWAClient(base_url="http://localhost:2785",- api_key="your-api-key",+ api_key="owa_k1_…",)-result = client.messages.send_text("session-1", {+client.sessions.start("my-session")+result = client.messages.send_text("my-session", {"chatId": "[email protected]",- "text": "Hello from OpenWA Python SDK!",+ "text": "Hello from the OpenWA Python SDK!",})+print(result["messageId"])```++Pass `transport=httpx.MockTransport(handler)` for testing — no global+monkey-patching required.++## PHP++```bash+cd sdk/php+composer install+```++```php+<?php+use OpenWA\Client;++$client = new Client([+ 'baseUrl' => 'http://localhost:2785',+ 'apiKey' => 'owa_k1_…',+]);++$client->sessions->start('my-session');+$result = $client->messages->sendText('my-session', [+ 'chatId' => '[email protected]',+ 'text' => 'Hello from the OpenWA PHP SDK!',+]);+echo $result['messageId'];+```++Requires PHP 8.1+ and Guzzle 7. For testing, inject a Guzzle client whose+handler is a `MockHandler` — no global state, no network.++## Reliability & security++- **Use HTTPS in production.** The API key is sent as `X-API-Key` on every+ request and is bearer-equivalent — never send it over plaintext `http://`+ outside local development.+- **No automatic retries.** A failed request raises/throws immediately; wrap+ calls in your own backoff if you need retries (especially for `429`). The+ injectable transport (`fetch` / `transport` / `httpClient`) is the extension+ point for retry or observability middleware.+- **Redirects are never followed.** A `3xx` surfaces to the caller rather than+ being followed, so the API key is never re-sent to a redirect target.+- **Default per-request timeout** is 30s (configurable). Path segments (chat /+ message ids) are percent-encoded; a base-URL path prefix (e.g. behind a proxy+ at `/v1`) is preserved.++## Development++```bash+# JavaScript+cd sdk/javascript && npm test && npm run build && npm run smoke+# Python+cd sdk/python && python -m pytest -q+# PHP+cd sdk/php && composer install && ./vendor/bin/phpunit+```++Each test suite mocks the HTTP layer and asserts on the exact path, so the+regression that originally shipped a broken `messages/text` path (the real path+is `messages/send-text`) can never recur silently.diff --git a/sdk/javascript/README.md b/sdk/javascript/README.mdnew file mode 100644index 000000000..1ae8639dd--- /dev/null+++ b/sdk/javascript/README.md@@ -0,0 +1,47 @@+# @openwa/sdk++Official JavaScript/TypeScript SDK for the [OpenWA](https://github.com/rmyndharis/OpenWA) WhatsApp API Gateway.++Ships dual CJS + ESM builds with bundled type declarations.++## Install++```bash+npm install @openwa/sdk+```++Requires Node.js >= 18 (relies on the global `fetch`).++## Usage++```typescript+import { OpenWAClient } from '@openwa/sdk';++const client = new OpenWAClient({+ baseUrl: 'https://your-gateway.example.com',+ apiKey: 'owa_k1_…',+});++await client.sessions.start('my-session');++const result = await client.messages.sendText('my-session', {+ chatId: '[email protected]',+ text: 'Hello from the OpenWA SDK!',+});+console.log(result.messageId);+```++CommonJS consumers use `require('@openwa/sdk')` identically.++## Errors++Non-2xx responses throw a typed `OpenWAApiError` subclass+(`OpenWAAuthError`, `OpenWAForbiddenError`, `OpenWANotFoundError`,+`OpenWAConflictError`, `OpenWARateLimitError`, `OpenWANotImplementedError`),+each carrying `.status` and the parsed `.body`. Timeouts throw+`OpenWATimeoutError`. The SDK does **not** retry — wrap calls with your own+backoff if needed.++## License++MITdiff --git a/sdk/javascript/package-lock.json b/sdk/javascript/package-lock.jsonnew file mode 100644index 000000000..9e89c2eab--- /dev/null+++ b/sdk/javascript/package-lock.json@@ -0,0 +1,1440 @@+{+ "name": "@openwa/sdk",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@openwa/sdk",+ "version": "0.1.0",+ "license": "MIT",+ "devDependencies": {+ "typescript": "^5.7.3",+ "vitest": "^2.1.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz",+ "integrity": "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz",+ "integrity": "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.2.tgz",+ "integrity": "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.2.tgz",+ "integrity": "sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.2.tgz",+ "integrity": "sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.2.tgz",+ "integrity": "sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.2.tgz",+ "integrity": "sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.2.tgz",+ "integrity": "sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.2.tgz",+ "integrity": "sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.2.tgz",+ "integrity": "sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.2.tgz",+ "integrity": "sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz",+ "integrity": "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz",+ "integrity": "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz",+ "integrity": "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz",+ "integrity": "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz",+ "integrity": "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz",+ "integrity": "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz",+ "integrity": "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz",+ "integrity": "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-openbsd-x64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz",+ "integrity": "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ]+ },+ "node_modules/@rollup/rollup-openharmony-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz",+ "integrity": "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz",+ "integrity": "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz",+ "integrity": "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz",+ "integrity": "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz",+ "integrity": "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@vitest/expect": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",+ "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "2.1.9",+ "@vitest/utils": "2.1.9",+ "chai": "^5.1.2",+ "tinyrainbow": "^1.2.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/mocker": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",+ "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "2.1.9",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.12"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^5.0.0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/pretty-format": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",+ "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^1.2.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/runner": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",+ "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "2.1.9",+ "pathe": "^1.1.2"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/snapshot": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",+ "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "2.1.9",+ "magic-string": "^0.30.12",+ "pathe": "^1.1.2"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/spy": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",+ "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyspy": "^3.0.2"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/utils": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",+ "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "2.1.9",+ "loupe": "^3.1.2",+ "tinyrainbow": "^1.2.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/assertion-error": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/cac": {+ "version": "6.7.14",+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/chai": {+ "version": "5.3.3",+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "assertion-error": "^2.0.1",+ "check-error": "^2.1.1",+ "deep-eql": "^5.0.1",+ "loupe": "^3.1.0",+ "pathval": "^2.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/check-error": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",+ "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/deep-eql": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/esbuild": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=12"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.21.5",+ "@esbuild/android-arm": "0.21.5",+ "@esbuild/android-arm64": "0.21.5",+ "@esbuild/android-x64": "0.21.5",+ "@esbuild/darwin-arm64": "0.21.5",+ "@esbuild/darwin-x64": "0.21.5",+ "@esbuild/freebsd-arm64": "0.21.5",+ "@esbuild/freebsd-x64": "0.21.5",+ "@esbuild/linux-arm": "0.21.5",+ "@esbuild/linux-arm64": "0.21.5",+ "@esbuild/linux-ia32": "0.21.5",+ "@esbuild/linux-loong64": "0.21.5",+ "@esbuild/linux-mips64el": "0.21.5",+ "@esbuild/linux-ppc64": "0.21.5",+ "@esbuild/linux-riscv64": "0.21.5",+ "@esbuild/linux-s390x": "0.21.5",+ "@esbuild/linux-x64": "0.21.5",+ "@esbuild/netbsd-x64": "0.21.5",+ "@esbuild/openbsd-x64": "0.21.5",+ "@esbuild/sunos-x64": "0.21.5",+ "@esbuild/win32-arm64": "0.21.5",+ "@esbuild/win32-ia32": "0.21.5",+ "@esbuild/win32-x64": "0.21.5"+ }+ },+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/expect-type": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",+ "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/loupe": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.15",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",+ "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/pathe": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathval": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14.16"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/postcss": {+ "version": "8.5.15",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",+ "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.12",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/rollup": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",+ "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "1.0.9"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@rollup/rollup-android-arm-eabi": "4.62.2",+ "@rollup/rollup-android-arm64": "4.62.2",+ "@rollup/rollup-darwin-arm64": "4.62.2",+ "@rollup/rollup-darwin-x64": "4.62.2",+ "@rollup/rollup-freebsd-arm64": "4.62.2",+ "@rollup/rollup-freebsd-x64": "4.62.2",+ "@rollup/rollup-linux-arm-gnueabihf": "4.62.2",+ "@rollup/rollup-linux-arm-musleabihf": "4.62.2",+ "@rollup/rollup-linux-arm64-gnu": "4.62.2",+ "@rollup/rollup-linux-arm64-musl": "4.62.2",+ "@rollup/rollup-linux-loong64-gnu": "4.62.2",+ "@rollup/rollup-linux-loong64-musl": "4.62.2",+ "@rollup/rollup-linux-ppc64-gnu": "4.62.2",+ "@rollup/rollup-linux-ppc64-musl": "4.62.2",+ "@rollup/rollup-linux-riscv64-gnu": "4.62.2",+ "@rollup/rollup-linux-riscv64-musl": "4.62.2",+ "@rollup/rollup-linux-s390x-gnu": "4.62.2",+ "@rollup/rollup-linux-x64-gnu": "4.62.2",+ "@rollup/rollup-linux-x64-musl": "4.62.2",+ "@rollup/rollup-openbsd-x64": "4.62.2",+ "@rollup/rollup-openharmony-arm64": "4.62.2",+ "@rollup/rollup-win32-arm64-msvc": "4.62.2",+ "@rollup/rollup-win32-ia32-msvc": "4.62.2",+ "@rollup/rollup-win32-x64-gnu": "4.62.2",+ "@rollup/rollup-win32-x64-msvc": "4.62.2",+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/siginfo": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/stackback": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/std-env": {+ "version": "3.10.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinybench": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinyexec": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinypool": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ }+ },+ "node_modules/tinyrainbow": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",+ "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tinyspy": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",+ "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/vite": {+ "version": "5.4.21",+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "^0.21.3",+ "postcss": "^8.4.43",+ "rollup": "^4.20.0"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^18.0.0 || >=20.0.0",+ "less": "*",+ "lightningcss": "^1.21.0",+ "sass": "*",+ "sass-embedded": "*",+ "stylus": "*",+ "sugarss": "*",+ "terser": "^5.4.0"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ }+ }+ },+ "node_modules/vite-node": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",+ "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cac": "^6.7.14",+ "debug": "^4.3.7",+ "es-module-lexer": "^1.5.4",+ "pathe": "^1.1.2",+ "vite": "^5.0.0"+ },+ "bin": {+ "vite-node": "vite-node.mjs"+ },+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/vitest": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",+ "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/expect": "2.1.9",+ "@vitest/mocker": "2.1.9",+ "@vitest/pretty-format": "^2.1.9",+ "@vitest/runner": "2.1.9",+ "@vitest/snapshot": "2.1.9",+ "@vitest/spy": "2.1.9",+ "@vitest/utils": "2.1.9",+ "chai": "^5.1.2",+ "debug": "^4.3.7",+ "expect-type": "^1.1.0",+ "magic-string": "^0.30.12",+ "pathe": "^1.1.2",+ "std-env": "^3.8.0",+ "tinybench": "^2.9.0",+ "tinyexec": "^0.3.1",+ "tinypool": "^1.0.1",+ "tinyrainbow": "^1.2.0",+ "vite": "^5.0.0",+ "vite-node": "2.1.9",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@types/node": "^18.0.0 || >=20.0.0",+ "@vitest/browser": "2.1.9",+ "@vitest/ui": "2.1.9",+ "happy-dom": "*",+ "jsdom": "*"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ }+ }+ },+ "node_modules/why-is-node-running": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "siginfo": "^2.0.0",+ "stackback": "0.0.2"+ },+ "bin": {+ "why-is-node-running": "cli.js"+ },+ "engines": {+ "node": ">=8"+ }+ }+ }+}diff --git a/sdk/javascript/package.json b/sdk/javascript/package.jsonindex 377412e69..8a627e5f1 100644--- a/sdk/javascript/package.json+++ b/sdk/javascript/package.json@@ -1,14 +1,31 @@{"name": "@openwa/sdk",- "version": "0.0.1",+ "version": "0.1.0","description": "Official JavaScript/TypeScript SDK for OpenWA WhatsApp API Gateway",- "main": "dist/index.js",- "types": "dist/index.d.ts",+ "type": "module",+ "main": "./dist/cjs/index.js",+ "module": "./dist/esm/index.js",+ "types": "./dist/esm/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/esm/index.d.ts",+ "import": "./dist/esm/index.js",+ "require": "./dist/cjs/index.js",+ "default": "./dist/esm/index.js"+ }+ },+ "files": [+ "dist",+ "README.md"+ ],"scripts": {- "build": "tsc",- "dev": "tsc --watch",- "test": "jest",- "lint": "eslint src/"+ "build": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json',JSON.stringify({type:'commonjs'}))\"",+ "prepublishOnly": "npm run build",+ "dev": "tsc -p tsconfig.esm.json --watch",+ "test": "vitest run",+ "test:watch": "vitest",+ "smoke": "node scripts/smoke.mjs",+ "typecheck": "tsc --noEmit"},"keywords": ["whatsapp",@@ -21,14 +38,16 @@"license": "MIT","repository": {"type": "git",- "url": "https://github.com/openwa/openwa",+ "url": "https://github.com/rmyndharis/OpenWA","directory": "sdk/javascript"},"engines": {"node": ">=18"},+ "sideEffects": false,"peerDependencies": {},"devDependencies": {- "typescript": "^5.3.0"+ "typescript": "^5.7.3",+ "vitest": "^2.1.0"}}\ No newline at end of filediff --git a/sdk/javascript/scripts/smoke.mjs b/sdk/javascript/scripts/smoke.mjsnew file mode 100644index 000000000..d7b9b094f--- /dev/null+++ b/sdk/javascript/scripts/smoke.mjs@@ -0,0 +1,17 @@+/**+ * Packaging smoke test: load the BUILT dist/ through Node's real CJS and ESM+ * loaders. Unit tests run under vitest's bundler-like resolver and cannot catch+ * a dual-format misconfig (CJS parsed as ESM, or extensionless ESM specifiers),+ * so this guards `npm publish` against shipping an unconsumable package.+ * Run after `npm run build`.+ */+import { createRequire } from 'node:module';++const require = createRequire(import.meta.url);+const cjs = require('../dist/cjs/index.js');+if (typeof cjs.OpenWAClient !== 'function') throw new Error('CJS: OpenWAClient missing');++const esm = await import(new URL('../dist/esm/index.js', import.meta.url).href);+if (typeof esm.OpenWAClient !== 'function') throw new Error('ESM: OpenWAClient missing');++console.log('smoke OK: require() + import() both resolve OpenWAClient');diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.tsnew file mode 100644index 000000000..ecd464bc6--- /dev/null+++ b/sdk/javascript/src/client.ts@@ -0,0 +1,113 @@+/**+ * OpenWA JavaScript/TypeScript SDK — client core.+ *+ * The {@link OpenWAClient} is the single entry point. It holds configuration+ * (base URL, API key, timeout, injectable transport) and exposes domain+ * resources as properties:+ *+ * ```typescript+ * import { OpenWAClient } from '@openwa/sdk';+ *+ * const client = new OpenWAClient({+ * baseUrl: 'http://localhost:2785',+ * apiKey: 'owa_k1_…',+ * });+ *+ * await client.sessions.start('my-session');+ * await client.messages.sendText('my-session', {+ * chatId: '[email protected]',+ * text: 'Hello from the OpenWA SDK!',+ * });+ * ```+ *+ * @packageDocumentation+ */++import { request, encodeSegment, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';+import { CatalogResource } from './resources/catalog.js';+import { ChannelsResource } from './resources/channels.js';+import { ChatsResource } from './resources/chats.js';+import { ContactsResource } from './resources/contacts.js';+import { GroupsResource } from './resources/groups.js';+import { HealthResource } from './resources/health.js';+import { LabelsResource } from './resources/labels.js';+import { MessagesResource } from './resources/messages.js';+import { SessionsResource } from './resources/sessions.js';+import { StatusResource } from './resources/status.js';+import { TemplatesResource } from './resources/templates.js';+import { WebhooksResource } from './resources/webhooks.js';+import type { AuthValidateResponse, MessageResponse, SendMediaRequest } from './types.js';++export interface OpenWAClientOptions {+ /** Base URL of the OpenWA API, e.g. `http://localhost:2785`. */+ baseUrl: string;+ /** API key sent as `X-API-Key`. */+ apiKey: string;+ /** Per-request timeout in milliseconds (default 30000). */+ timeoutMs?: number;+ /** Default headers applied to every request. */+ defaultHeaders?: Record<string, string>;+ /** Injectable transport; defaults to the global `fetch`. */+ fetch?: FetchLike;+}++export class OpenWAClient {+ private readonly config: Required<Omit<ClientConfig, 'fetch'>> & { fetch: FetchLike };++ constructor(options: OpenWAClientOptions) {+ if (!options.baseUrl) throw new Error('OpenWAClient: baseUrl is required');+ if (!options.apiKey) throw new Error('OpenWAClient: apiKey is required');++ this.config = {+ baseUrl: options.baseUrl,+ apiKey: options.apiKey,+ timeoutMs: options.timeoutMs ?? 30000,+ defaultHeaders: options.defaultHeaders ?? {},+ fetch: options.fetch ?? globalThis.fetch,+ };+ }++ // ── Resources ────────────────────────────────────────────────────++ readonly sessions = new SessionsResource(this);+ readonly messages = new MessagesResource(this);+ readonly contacts = new ContactsResource(this);+ readonly groups = new GroupsResource(this);+ readonly webhooks = new WebhooksResource(this);+ readonly chats = new ChatsResource(this);+ readonly status = new StatusResource(this);+ readonly health = new HealthResource(this);+ readonly labels = new LabelsResource(this);+ readonly channels = new ChannelsResource(this);+ readonly catalog = new CatalogResource(this);+ readonly templates = new TemplatesResource(this);++ // ── Auth ─────────────────────────────────────────────────────────++ /** Validate the configured API key and resolve its role. */+ auth(): Promise<AuthValidateResponse> {+ return this.request<AuthValidateResponse>({ method: 'POST', path: '/api/auth/validate' });+ }++ // ── Internal API ─────────────────────────────────────────────────++ /** Issue a raw request against the API. (Public for advanced use.) */+ request<T>(options: RequestOptions): Promise<T> {+ return request<T>(this.config, options);+ }++ /**+ * Shared media-send helper used by the image/video/audio/document/sticker+ * methods, which all share the {@link SendMediaRequest} shape and only differ+ * by their path segment.+ */+ sendMedia(sessionId: string, segment: string, body: SendMediaRequest): Promise<MessageResponse> {+ return this.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/${segment}`,+ body,+ });+ }+}++export default OpenWAClient;diff --git a/sdk/javascript/src/errors.ts b/sdk/javascript/src/errors.tsnew file mode 100644index 000000000..30649b83a--- /dev/null+++ b/sdk/javascript/src/errors.ts@@ -0,0 +1,119 @@+/**+ * Typed error hierarchy for the OpenWA SDK.+ *+ * The OpenWA API returns NestJS-default errors of the shape:+ * `{ statusCode: number, message: string | string[], error: string }`+ * This module maps that to a typed, ergonomic error tree so callers can+ * `instanceof`-check or branch on `.status`.+ *+ * @packageDocumentation+ */++/** Base class for every error thrown by the SDK. */+export class OpenWAError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'OpenWAError';+ }+}++/**+ * Thrown when the API responds with a non-2xx status. Carries the HTTP status+ * code and the parsed error body (or the raw text if the body was not JSON).+ *+ * Use the static {@link OpenWAApiError.fromResponse} factory in most cases.+ */+export class OpenWAApiError extends OpenWAError {+ /** HTTP status code (e.g. 400, 404, 409, 429, 501). */+ readonly status: number;+ /** Parsed JSON body if available, otherwise the raw response text. */+ readonly body: unknown;+ /** Value of the `error` field in the NestJS error envelope, if present. */+ readonly errorKind?: string;++ constructor(message: string, status: number, body: unknown, errorKind?: string) {+ super(message);+ this.name = 'OpenWAApiError';+ this.status = status;+ this.body = body;+ this.errorKind = errorKind;+ }++ /** Build an {@link OpenWAApiError} from a fetch Response, awaiting its body. */+ static async fromResponse(res: Response, context: string): Promise<OpenWAApiError> {+ let body: unknown = undefined;+ const text = await res.text().catch(() => '');+ if (text) {+ try {+ body = JSON.parse(text);+ } catch {+ body = text;+ }+ }+ const env = isNestEnvelope(body) ? body : undefined;+ const messageText = describeMessage(env?.message ?? body ?? res.statusText);+ const message = `OpenWA API ${res.status} ${res.statusText} — ${context}: ${messageText}`;+ return new OpenWAApiError(message, res.status, body, env?.error);+ }+}++/** 401 Unauthorized — missing or invalid API key. */+export class OpenWAAuthError extends OpenWAApiError {}+/** 403 Forbidden — the API key's role is insufficient for this endpoint. */+export class OpenWAForbiddenError extends OpenWAApiError {}+/** 404 Not Found. */+export class OpenWANotFoundError extends OpenWAApiError {}+/** 409 Conflict — typically an {@link EngineNotReadyError} from the backend. */+export class OpenWAConflictError extends OpenWAApiError {}+/** 429 Too Many Requests — rate limited. */+export class OpenWARateLimitError extends OpenWAApiError {}+/** 501 Not Implemented — the active engine does not support this operation. */+export class OpenWANotImplementedError extends OpenWAApiError {}++/** Thrown when a request exceeds the configured timeout. */+export class OpenWATimeoutError extends OpenWAError {+ constructor(timeoutMs: number) {+ super(`Request timed out after ${timeoutMs}ms`);+ this.name = 'OpenWATimeoutError';+ }+}++/**+ * Construct the most specific {@link OpenWAApiError} subclass for a status code.+ * Falls back to the generic {@link OpenWAApiError} for unmapped statuses.+ */+export function classifyApiError(status: number, message: string, body: unknown, errorKind?: string): OpenWAApiError {+ switch (status) {+ case 401:+ return new OpenWAAuthError(message, status, body, errorKind);+ case 403:+ return new OpenWAForbiddenError(message, status, body, errorKind);+ case 404:+ return new OpenWANotFoundError(message, status, body, errorKind);+ case 409:+ return new OpenWAConflictError(message, status, body, errorKind);+ case 429:+ return new OpenWARateLimitError(message, status, body, errorKind);+ case 501:+ return new OpenWANotImplementedError(message, status, body, errorKind);+ default:+ return new OpenWAApiError(message, status, body, errorKind);+ }+}++/** Narrow the NestJS error envelope shape: `{ statusCode, message, error }`. */+interface NestErrorEnvelope {+ statusCode: number;+ message: string | string[];+ error: string;+}++function isNestEnvelope(body: unknown): body is NestErrorEnvelope {+ return typeof body === 'object' && body !== null && 'statusCode' in body && 'message' in body && 'error' in body;+}++function describeMessage(message: string | string[] | unknown): string {+ if (Array.isArray(message)) return message.join(', ');+ if (typeof message === 'string') return message;+ return String(message);+}diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsnew file mode 100644index 000000000..7bdd530cc--- /dev/null+++ b/sdk/javascript/src/http.ts@@ -0,0 +1,129 @@+/**+ * Injectable HTTP transport for the OpenWA SDK.+ *+ * The client never calls `globalThis.fetch` directly. Instead it accepts a+ * `FetchLike` implementation (defaulting to the global `fetch`). This makes the+ * SDK trivially testable — a test passes a recorder as `fetch` instead of+ * monkey-patching globals — and lets consumers intercept/observability-wrap+ * outbound calls.+ *+ * @packageDocumentation+ */++import { classifyApiError, OpenWAApiError, OpenWATimeoutError } from './errors.js';++/** Subset of the WHATWG `fetch` signature the SDK relies on. */+export type FetchLike = typeof globalThis.fetch;++export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';++export interface RequestOptions {+ method: HttpMethod;+ /** Full path beginning with `/`, e.g. `/api/sessions`. */+ path: string;+ /** Query parameters, serialized into the URL. */+ query?: object;+ /** JSON-serializable request body. */+ body?: unknown;+ /** Override the per-client timeout (ms) for this single request. */+ timeoutMs?: number;+ /** Extra headers merged on top of the client defaults (auth/JSON win). */+ headers?: Record<string, string>;+}++export interface ClientConfig {+ /** Base URL of the OpenWA API, e.g. `http://localhost:2785`. */+ baseUrl: string;+ /** API key sent as `X-API-Key`. */+ apiKey: string;+ /** Per-request timeout in milliseconds (default 30000). */+ timeoutMs?: number;+ /** Default headers applied to every request. */+ defaultHeaders?: Record<string, string>;+ /** Injectable transport; defaults to the global `fetch`. */+ fetch?: FetchLike;+}++/**+ * Percent-encode a single path segment (e.g. a chat/message id) so a value+ * containing `/`, `#`, `?` or whitespace can't break out of its path position.+ * WhatsApp-id characters that are already path-safe (`@`, `:`, `+`) are kept+ * readable.+ */+export function encodeSegment(segment: string | number): string {+ return encodeURIComponent(String(segment)).replace(/%40/g, '@').replace(/%3A/g, ':').replace(/%2B/g, '+');+}++/** Build a URL with serialized query params, omitting `undefined`/`null` values. */+export function buildUrl(baseUrl: string, path: string, query?: object): string {+ const url = `${baseUrl.replace(/\/$/, '')}${path}`;+ if (!query) return url;+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(query)) {+ if (value === undefined || value === null) continue;+ params.append(key, String(value));+ }+ const qs = params.toString();+ return qs ? `${url}?${qs}` : url;+}++/**+ * Perform a single request against the OpenWA API and return the parsed JSON+ * body (or `null` for 204). Throws a typed {@link OpenWAApiError} subclass on+ * non-2xx, or {@link OpenWATimeoutError} on timeout.+ */+export async function request<T>(+ config: Required<Omit<ClientConfig, 'fetch'>> & { fetch: FetchLike },+ options: RequestOptions,+): Promise<T> {+ const url = buildUrl(config.baseUrl, options.path, options.query);+ const timeoutMs = options.timeoutMs ?? config.timeoutMs;++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);++ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ ...config.defaultHeaders,+ ...options.headers,+ 'X-API-Key': config.apiKey,+ };++ let res: Response;+ try {+ res = await config.fetch(url, {+ method: options.method,+ headers,+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,+ signal: controller.signal,+ // Never auto-follow redirects: doing so would re-send the X-API-Key header+ // to the redirect target (potentially a different origin). A 3xx surfaces+ // as a non-2xx error instead.+ redirect: 'manual',+ });+ } catch (err) {+ clearTimeout(timer);+ if (err instanceof Error && err.name === 'AbortError') {+ throw new OpenWATimeoutError(timeoutMs);+ }+ throw err;+ }+ clearTimeout(timer);++ if (!res.ok) {+ const context = `${options.method} ${options.path}`;+ const apiError = await OpenWAApiError.fromResponse(res, context);+ throw classifyApiError(apiError.status, apiError.message, apiError.body, apiError.errorKind);+ }++ if (res.status === 204) {+ return null as T;+ }+ const text = await res.text();+ if (!text) return null as T;+ try {+ return JSON.parse(text) as T;+ } catch {+ return text as unknown as T;+ }+}diff --git a/sdk/javascript/src/index.ts b/sdk/javascript/src/index.tsindex ae56714c0..d58046747 100644--- a/sdk/javascript/src/index.ts+++ b/sdk/javascript/src/index.ts@@ -1,112 +1,32 @@/**- * OpenWA JavaScript/TypeScript SDK+ * OpenWA JavaScript/TypeScript SDK.** Official client library for the OpenWA WhatsApp API Gateway.** @example* ```typescript- * import { OpenWAClient } from '@openwa/sdk';+ * import { OpenWAClient, OpenWAApiError } from '@openwa/sdk';** const client = new OpenWAClient({* baseUrl: 'http://localhost:2785',- * apiKey: 'your-api-key',+ * apiKey: 'owa_k1_…',* });*- * // Send a text message- * const result = await client.messages.sendText('session-1', {+ * await client.sessions.start('my-session');+ * const result = await client.messages.sendText('my-session', {* chatId: '[email protected]',- * text: 'Hello from OpenWA SDK!',+ * text: 'Hello from the OpenWA SDK!',* });+ * console.log(result.messageId);* ```** @packageDocumentation*/-// ── Client Configuration ──────────────────────────────────────────--export interface OpenWAClientConfig {- /** Base URL of the OpenWA API (e.g., 'http://localhost:2785') */- baseUrl: string;-- /** API key for authentication */- apiKey: string;-- /** Request timeout in milliseconds (default: 30000) */- timeout?: number;-}--// ── Response Types ────────────────────────────────────────────────--export interface MessageResponse {- messageId: string;- timestamp: number;-}--export interface Session {- id: string;- name: string;- status: string;- phone: string | null;- pushName: string | null;-}--// ── Client Class ──────────────────────────────────────────────────--export class OpenWAClient {- private readonly config: Required<OpenWAClientConfig>;-- constructor(config: OpenWAClientConfig) {- this.config = {- timeout: 30000,- ...config,- };- }-- // Placeholder — will be auto-generated from OpenAPI spec- get sessions() {- return {- list: () => this.request<Session[]>('GET', '/api/sessions'),- get: (id: string) => this.request<Session>('GET', `/api/sessions/${id}`),- create: (data: { name: string }) => this.request<Session>('POST', '/api/sessions', data),- start: (id: string) => this.request<Session>('POST', `/api/sessions/${id}/start`),- stop: (id: string) => this.request<Session>('POST', `/api/sessions/${id}/stop`),- delete: (id: string) => this.request<void>('DELETE', `/api/sessions/${id}`),- };- }-- get messages() {- return {- sendText: (sessionId: string, data: { chatId: string; text: string }) =>- this.request<MessageResponse>('POST', `/api/sessions/${sessionId}/messages/text`, data),- };- }-- // ── Internal HTTP client ──────────────────────────────────────────-- private async request<T>(method: string, path: string, body?: unknown): Promise<T> {- const url = `${this.config.baseUrl}${path}`;- const response = await fetch(url, {- method,- headers: {- 'Content-Type': 'application/json',- 'X-API-Key': this.config.apiKey,- },- body: body ? JSON.stringify(body) : undefined,- signal: AbortSignal.timeout(this.config.timeout),- });-- if (!response.ok) {- const error = await response.json().catch(() => ({ message: response.statusText }));- throw new Error(`OpenWA API Error (${response.status}): ${(error as { message: string }).message}`);- }-- // Handle empty responses (204 No Content)- if (response.status === 204) {- return undefined as T;- }-- return response.json() as Promise<T>;- }-}--export default OpenWAClient;+export { OpenWAClient } from './client.js';+export { default } from './client.js';+export type { OpenWAClientOptions } from './client.js';+export * from './errors.js';+export type * from './types.js';+export type { ClientConfig, FetchLike, HttpMethod, RequestOptions } from './http.js';+export { buildUrl } from './http.js';diff --git a/sdk/javascript/src/resources/catalog.ts b/sdk/javascript/src/resources/catalog.tsnew file mode 100644index 000000000..c4c24f246--- /dev/null+++ b/sdk/javascript/src/resources/catalog.ts@@ -0,0 +1,69 @@+/**+ * Catalog resource — WhatsApp Business catalog, products, and product/catalog sends.+ *+ * Backed by `src/modules/catalog/catalog.controller.ts` (`@Controller('sessions/:sessionId')`).+ * NOTE: the catalog controller is mounted under the session root, so catalog+ * reads are `/catalog...` while product/catalog SENDS share the messages+ * namespace (`/messages/send-product`, `/messages/send-catalog`). All require+ * an OPERATOR-level key for write operations.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type {+ CatalogInfo,+ CatalogProduct,+ CatalogProductsQuery,+ MessageResponse,+ PaginatedProducts,+ SendCatalogRequest,+ SendProductRequest,+} from '../types.js';++export class CatalogResource {+ constructor(private readonly client: OpenWAClient) {}++ /** Get the business catalog info. */+ info(sessionId: string): Promise<CatalogInfo> {+ return this.client.request<CatalogInfo>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/catalog`,+ });+ }++ /** List catalog products. Returns a `{ products, pagination }` page. */+ products(sessionId: string, query?: CatalogProductsQuery): Promise<PaginatedProducts> {+ return this.client.request<PaginatedProducts>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/catalog/products`,+ query,+ });+ }++ /** Get a single product by id. */+ product(sessionId: string, productId: string): Promise<CatalogProduct> {+ return this.client.request<CatalogProduct>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/catalog/products/${encodeSegment(productId)}`,+ });+ }++ /** Send a product message. Requires an OPERATOR-level key. Shares the messages path. */+ sendProduct(sessionId: string, body: SendProductRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-product`,+ body,+ });+ }++ /** Send a catalog link message. Requires an OPERATOR-level key. Shares the messages path. */+ sendCatalog(sessionId: string, body: SendCatalogRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-catalog`,+ body,+ });+ }+}diff --git a/sdk/javascript/src/resources/channels.ts b/sdk/javascript/src/resources/channels.tsnew file mode 100644index 000000000..7c23202a0--- /dev/null+++ b/sdk/javascript/src/resources/channels.ts@@ -0,0 +1,62 @@+/**+ * Channels resource — WhatsApp Channels / Newsletters.+ *+ * Backed by `src/modules/channel/channel.controller.ts` (`@Controller('sessions/:sessionId/channels')`).+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type {+ ChannelMessageQuery,+ ChannelRecord,+ MessageRecord,+ SubscribeChannelRequest,+ SuccessResult,+} from '../types.js';++export class ChannelsResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List all channels/newsletters the session is subscribed to. */+ list(sessionId: string): Promise<ChannelRecord[]> {+ return this.client.request<ChannelRecord[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/channels`,+ });+ }++ /** Get a single channel by id. */+ get(sessionId: string, channelId: string): Promise<ChannelRecord> {+ return this.client.request<ChannelRecord>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/channels/${encodeSegment(channelId)}`,+ });+ }++ /** Get recent messages from a channel. */+ messages(sessionId: string, channelId: string, query?: ChannelMessageQuery): Promise<MessageRecord[]> {+ return this.client.request<MessageRecord[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/channels/${encodeSegment(channelId)}/messages`,+ query,+ });+ }++ /** Subscribe to a channel using its invite code. Requires an OPERATOR-level key. */+ subscribe(sessionId: string, body: SubscribeChannelRequest): Promise<ChannelRecord> {+ return this.client.request<ChannelRecord>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/channels/subscribe`,+ body,+ });+ }++ /** Unsubscribe from a channel. Requires an OPERATOR-level key. */+ unsubscribe(sessionId: string, channelId: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/channels/${encodeSegment(channelId)}`,+ });+ }+}diff --git a/sdk/javascript/src/resources/chats.ts b/sdk/javascript/src/resources/chats.tsnew file mode 100644index 000000000..49f7ba1f1--- /dev/null+++ b/sdk/javascript/src/resources/chats.ts@@ -0,0 +1,67 @@+/**+ * Chats resource — chat-list operations (read/unread/delete/typing state).+ *+ * NOTE: these endpoints live under the session controller+ * (`/api/sessions/:id/chats/*`), but are surfaced here as a dedicated resource+ * for clarity.+ *+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { ChatSummary, DeleteChatRequest, MarkChatRequest, SendChatStateRequest, SuccessResult } from '../types.js';++export interface ListChatsQuery {+ limit?: number;+ offset?: number;+}++export class ChatsResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List active chats, most recent first. */+ list(sessionId: string, query?: ListChatsQuery): Promise<ChatSummary[]> {+ return this.client.request<ChatSummary[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/chats`,+ query,+ });+ }++ /** Mark a chat as read/seen. */+ markRead(sessionId: string, body: MarkChatRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/chats/read`,+ body,+ });+ }++ /** Mark a chat as unread. */+ markUnread(sessionId: string, body: MarkChatRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/chats/unread`,+ body,+ });+ }++ /** Delete a chat from the chat list. */+ delete(sessionId: string, body: DeleteChatRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/chats/delete`,+ body,+ });+ }++ /** Send a chat presence state (typing/recording/paused). */+ sendState(sessionId: string, body: SendChatStateRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/chats/typing`,+ body,+ });+ }+}diff --git a/sdk/javascript/src/resources/contacts.ts b/sdk/javascript/src/resources/contacts.tsnew file mode 100644index 000000000..def86c3b2--- /dev/null+++ b/sdk/javascript/src/resources/contacts.ts@@ -0,0 +1,82 @@+/**+ * Contacts resource — contact lookup and management.+ *+ * Backed by `src/modules/contact/contact.controller.ts`.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type {+ CheckNumberResponse,+ ContactPhoneResponse,+ ContactRecord,+ ProfilePictureResponse,+ SuccessResult,+} from '../types.js';++export interface ListContactsQuery {+ limit?: number;+ offset?: number;+}++export class ContactsResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List contacts known to the session. */+ list(sessionId: string, query?: ListContactsQuery): Promise<ContactRecord[]> {+ return this.client.request<ContactRecord[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts`,+ query,+ });+ }++ /** Get details for a single contact by id (JID). */+ get(sessionId: string, contactId: string): Promise<ContactRecord> {+ return this.client.request<ContactRecord>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/${encodeSegment(contactId)}`,+ });+ }++ /** Check whether a phone number is registered on WhatsApp. */+ check(sessionId: string, number: string): Promise<CheckNumberResponse> {+ return this.client.request<CheckNumberResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/check/${encodeSegment(number)}`,+ });+ }++ /** Get the contact's profile picture URL (or null). */+ profilePicture(sessionId: string, contactId: string): Promise<ProfilePictureResponse> {+ return this.client.request<ProfilePictureResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/${encodeSegment(contactId)}/profile-picture`,+ });+ }++ /** Resolve a contact id (e.g. a `@lid`) to a phone number. */+ phone(sessionId: string, contactId: string): Promise<ContactPhoneResponse> {+ return this.client.request<ContactPhoneResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/${encodeSegment(contactId)}/phone`,+ });+ }++ /** Block a contact. Requires an OPERATOR-level key. */+ block(sessionId: string, contactId: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/${encodeSegment(contactId)}/block`,+ });+ }++ /** Unblock a contact. Requires an OPERATOR-level key. */+ unblock(sessionId: string, contactId: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/${encodeSegment(contactId)}/block`,+ });+ }+}diff --git a/sdk/javascript/src/resources/groups.ts b/sdk/javascript/src/resources/groups.tsnew file mode 100644index 000000000..a43422bc6--- /dev/null+++ b/sdk/javascript/src/resources/groups.ts@@ -0,0 +1,123 @@+/**+ * Groups resource — WhatsApp group management.+ *+ * Backed by `src/modules/group/group.controller.ts`.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { CreateGroupRequest, GroupInfo, GroupSummary, InviteCodeResponse, SuccessResult } from '../types.js';++export interface ListGroupsQuery {+ limit?: number;+ offset?: number;+}++export class GroupsResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List all groups for the session. */+ list(sessionId: string, query?: ListGroupsQuery): Promise<GroupSummary[]> {+ return this.client.request<GroupSummary[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups`,+ query,+ });+ }++ /** Get detailed group info including the participant list. */+ get(sessionId: string, groupId: string): Promise<GroupInfo> {+ return this.client.request<GroupInfo>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}`,+ });+ }++ /** Create a new group. */+ create(sessionId: string, body: CreateGroupRequest): Promise<GroupInfo> {+ return this.client.request<GroupInfo>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups`,+ body,+ });+ }++ /** Add participants to a group. */+ addParticipants(sessionId: string, groupId: string, participants: string[]): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/participants`,+ body: { participants },+ });+ }++ /** Remove participants from a group. */+ removeParticipants(sessionId: string, groupId: string, participants: string[]): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/participants`,+ body: { participants },+ });+ }++ /** Promote participants to group admin. */+ promoteParticipants(sessionId: string, groupId: string, participants: string[]): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/participants/promote`,+ body: { participants },+ });+ }++ /** Demote participants from group admin. */+ demoteParticipants(sessionId: string, groupId: string, participants: string[]): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/participants/demote`,+ body: { participants },+ });+ }++ /** Update the group subject (name). */+ setSubject(sessionId: string, groupId: string, subject: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/subject`,+ body: { subject },+ });+ }++ /** Update the group description (empty string clears it). */+ setDescription(sessionId: string, groupId: string, description: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/description`,+ body: { description },+ });+ }++ /** Leave a group. */+ leave(sessionId: string, groupId: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/leave`,+ });+ }++ /** Get the group invite code and link. */+ inviteCode(sessionId: string, groupId: string): Promise<InviteCodeResponse> {+ return this.client.request<InviteCodeResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/invite-code`,+ });+ }++ /** Revoke the current invite code and generate a new one. */+ revokeInviteCode(sessionId: string, groupId: string): Promise<InviteCodeResponse> {+ return this.client.request<InviteCodeResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/invite-code/revoke`,+ });+ }+}diff --git a/sdk/javascript/src/resources/health.ts b/sdk/javascript/src/resources/health.tsnew file mode 100644index 000000000..458ddbd50--- /dev/null+++ b/sdk/javascript/src/resources/health.ts@@ -0,0 +1,29 @@+/**+ * Health resource — connectivity and readiness probes.+ *+ * Backed by `src/modules/health/health.controller.ts`.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { HealthReadyResponse, HealthResponse } from '../types.js';++export class HealthResource {+ constructor(private readonly client: OpenWAClient) {}++ /** General health (also returns the running version). */+ check(): Promise<HealthResponse> {+ return this.client.request<HealthResponse>({ method: 'GET', path: '/api/health' });+ }++ /** Kubernetes liveness probe. */+ live(): Promise<{ status: string }> {+ return this.client.request<{ status: string }>({ method: 'GET', path: '/api/health/live' });+ }++ /** Kubernetes readiness probe — checks both DB connections. */+ ready(): Promise<HealthReadyResponse> {+ return this.client.request<HealthReadyResponse>({ method: 'GET', path: '/api/health/ready' });+ }+}diff --git a/sdk/javascript/src/resources/labels.ts b/sdk/javascript/src/resources/labels.tsnew file mode 100644index 000000000..229d858ac--- /dev/null+++ b/sdk/javascript/src/resources/labels.ts@@ -0,0 +1,56 @@+/**+ * Labels resource — WhatsApp Business chat labels.+ *+ * Backed by `src/modules/label/label.controller.ts` (`@Controller('sessions/:sessionId/labels')`).+ * Labels are a WhatsApp Business feature; the session must be a business account.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { AddLabelRequest, LabelRecord, SuccessResult } from '../types.js';++export class LabelsResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List all labels available in the business account. */+ list(sessionId: string): Promise<LabelRecord[]> {+ return this.client.request<LabelRecord[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels`,+ });+ }++ /** Get a single label by id. */+ get(sessionId: string, labelId: string): Promise<LabelRecord> {+ return this.client.request<LabelRecord>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels/${encodeSegment(labelId)}`,+ });+ }++ /** Get the labels currently applied to a chat. */+ forChat(sessionId: string, chatId: string): Promise<LabelRecord[]> {+ return this.client.request<LabelRecord[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels/chat/${encodeSegment(chatId)}`,+ });+ }++ /** Add a label to a chat. Requires an OPERATOR-level key. */+ addToChat(sessionId: string, chatId: string, body: AddLabelRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels/chat/${encodeSegment(chatId)}`,+ body,+ });+ }++ /** Remove a label from a chat. Requires an OPERATOR-level key. */+ removeFromChat(sessionId: string, chatId: string, labelId: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels/chat/${encodeSegment(chatId)}/${encodeSegment(labelId)}`,+ });+ }+}diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.tsnew file mode 100644index 000000000..4818a43a4--- /dev/null+++ b/sdk/javascript/src/resources/messages.ts@@ -0,0 +1,186 @@+/**+ * Messages resource — sending and querying messages.+ *+ * Backed by `src/modules/message/message.controller.ts`.+ * NOTE: the real paths use the `/send-` prefix, e.g. `/messages/send-text`.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type {+ BatchStatusResponse,+ BulkMessageResponse,+ ChatHistoryMessage,+ DeleteMessageRequest,+ ForwardMessageRequest,+ ListMessagesQuery,+ MessageHistoryQuery,+ MessageListResponse,+ MessageResponse,+ ReactionRecord,+ ReactMessageRequest,+ ReplyMessageRequest,+ SendBulkRequest,+ SendContactRequest,+ SendLocationRequest,+ SendMediaRequest,+ SendTemplateRequest,+ SendTextRequest,+ SuccessResult,+} from '../types.js';++export class MessagesResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List messages, optionally filtered by chat or sender. Returns a `{ messages, total }` page. */+ list(sessionId: string, query?: ListMessagesQuery): Promise<MessageListResponse> {+ return this.client.request<MessageListResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages`,+ query,+ });+ }++ /** Send a text message. */+ sendText(sessionId: string, body: SendTextRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-text`,+ body,+ });+ }++ /** Send an image (url or base64). */+ sendImage(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-image', body);+ }++ /** Send a video (url or base64). */+ sendVideo(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-video', body);+ }++ /** Send an audio file (url or base64). */+ sendAudio(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-audio', body);+ }++ /** Send a document (url or base64; `filename` required). */+ sendDocument(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-document', body);+ }++ /** Send a sticker (url or base64). */+ sendSticker(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-sticker', body);+ }++ /** Send a location. */+ sendLocation(sessionId: string, body: SendLocationRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-location`,+ body,+ });+ }++ /** Send a contact card. */+ sendContact(sessionId: string, body: SendContactRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-contact`,+ body,+ });+ }++ /** Render and send a stored message template. */+ sendTemplate(sessionId: string, body: SendTemplateRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-template`,+ body,+ });+ }++ /** Reply to a specific message. */+ reply(sessionId: string, body: ReplyMessageRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/reply`,+ body,+ });+ }++ /** Forward a message to another chat. */+ forward(sessionId: string, body: ForwardMessageRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/forward`,+ body,+ });+ }++ /** React to a message (empty `emoji` removes the reaction). */+ react(sessionId: string, body: ReactMessageRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/react`,+ body,+ });+ }++ /** Delete a message. */+ delete(sessionId: string, body: DeleteMessageRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/delete`,+ body,+ });+ }++ /** Get the message history for a chat (read live from WhatsApp). */+ history(sessionId: string, chatId: string, query?: MessageHistoryQuery): Promise<ChatHistoryMessage[]> {+ return this.client.request<ChatHistoryMessage[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/${encodeSegment(chatId)}/history`,+ query,+ });+ }++ /** Get reactions for a specific message. */+ reactions(sessionId: string, chatId: string, messageId: string): Promise<ReactionRecord[]> {+ return this.client.request<ReactionRecord[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/${encodeSegment(chatId)}/${encodeSegment(messageId)}/reactions`,+ });+ }++ /**+ * Send a batch of messages asynchronously. Returns HTTP 202 with a batch id;+ * poll the status via {@link batchStatus}.+ */+ sendBulk(sessionId: string, body: SendBulkRequest): Promise<BulkMessageResponse> {+ return this.client.request<BulkMessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-bulk`,+ body,+ });+ }++ /** Poll the status/progress of a bulk send batch. */+ batchStatus(sessionId: string, batchId: string): Promise<BatchStatusResponse> {+ return this.client.request<BatchStatusResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/batch/${encodeSegment(batchId)}`,+ });+ }++ /** Cancel a running batch. Requires an OPERATOR-level key. */+ cancelBatch(sessionId: string, batchId: string): Promise<BatchStatusResponse> {+ return this.client.request<BatchStatusResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/batch/${encodeSegment(batchId)}/cancel`,+ });+ }+}diff --git a/sdk/javascript/src/resources/sessions.ts b/sdk/javascript/src/resources/sessions.tsnew file mode 100644index 000000000..2a0bdac4c--- /dev/null+++ b/sdk/javascript/src/resources/sessions.ts@@ -0,0 +1,78 @@+/**+ * Sessions resource — lifecycle management for WhatsApp sessions.+ *+ * Backed by `src/modules/session/session.controller.ts`.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type {+ CreateSessionRequest,+ PairingCodeResponse,+ QrCodeResponse,+ RequestPairingCodeRequest,+ SessionResponse,+ SessionStatsOverview,+} from '../types.js';++export class SessionsResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List all sessions (scoped to the API key's `allowedSessions`). */+ list(): Promise<SessionResponse[]> {+ return this.client.request<SessionResponse[]>({ method: 'GET', path: '/api/sessions' });+ }++ /** Get a single session by id. */+ get(id: string): Promise<SessionResponse> {+ return this.client.request<SessionResponse>({ method: 'GET', path: `/api/sessions/${encodeSegment(id)}` });+ }++ /** Create a new session. Requires an OPERATOR-level key. */+ create(body: CreateSessionRequest): Promise<SessionResponse> {+ return this.client.request<SessionResponse>({ method: 'POST', path: '/api/sessions', body });+ }++ /** Delete a session. Requires an OPERATOR-level key. */+ delete(id: string): Promise<void> {+ return this.client.request<void>({ method: 'DELETE', path: `/api/sessions/${encodeSegment(id)}` });+ }++ /** Start a session and initialize the WhatsApp connection. */+ start(id: string): Promise<SessionResponse> {+ return this.client.request<SessionResponse>({ method: 'POST', path: `/api/sessions/${encodeSegment(id)}/start` });+ }++ /** Stop a session and disconnect gracefully. */+ stop(id: string): Promise<SessionResponse> {+ return this.client.request<SessionResponse>({ method: 'POST', path: `/api/sessions/${encodeSegment(id)}/stop` });+ }++ /** Force-kill a stuck session (SIGKILL + teardown). */+ forceKill(id: string): Promise<SessionResponse> {+ return this.client.request<SessionResponse>({ method: 'POST', path: `/api/sessions/${encodeSegment(id)}/force-kill` });+ }++ /** Get the current QR code for authentication (live from the engine, not the DB). */+ getQrCode(id: string): Promise<QrCodeResponse> {+ return this.client.request<QrCodeResponse>({ method: 'GET', path: `/api/sessions/${encodeSegment(id)}/qr` });+ }++ /** Request an 8-character pairing code for phone-based login. */+ requestPairingCode(id: string, body: RequestPairingCodeRequest): Promise<PairingCodeResponse> {+ return this.client.request<PairingCodeResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(id)}/pairing-code`,+ body,+ });+ }++ /** Aggregate statistics across the API key's sessions. */+ stats(): Promise<SessionStatsOverview> {+ return this.client.request<SessionStatsOverview>({+ method: 'GET',+ path: '/api/sessions/stats/overview',+ });+ }+}diff --git a/sdk/javascript/src/resources/status.ts b/sdk/javascript/src/resources/status.tsnew file mode 100644index 000000000..03d60b11d--- /dev/null+++ b/sdk/javascript/src/resources/status.ts@@ -0,0 +1,66 @@+/**+ * Status (Stories) resource — WhatsApp status updates.+ *+ * Backed by `src/modules/status/status.controller.ts`.+ * NOTE: this is WhatsApp "Status/Stories", distinct from session lifecycle status.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { SendImageStatusRequest, SendTextStatusRequest, SendVideoStatusRequest, StatusRecord } from '../types.js';++export class StatusResource {+ constructor(private readonly client: OpenWAClient) {}++ /** Get all status updates. */+ list(sessionId: string): Promise<{ statuses: StatusRecord[] }> {+ return this.client.request<{ statuses: StatusRecord[] }>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/status`,+ });+ }++ /** Get status updates from a specific contact. */+ fromContact(sessionId: string, contactId: string): Promise<{ statuses: StatusRecord[] }> {+ return this.client.request<{ statuses: StatusRecord[] }>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/status/${encodeSegment(contactId)}`,+ });+ }++ /** Post a text status update. */+ sendText(sessionId: string, body: SendTextStatusRequest): Promise<StatusRecord> {+ return this.client.request<StatusRecord>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/status/send-text`,+ body,+ });+ }++ /** Post an image status update. */+ sendImage(sessionId: string, body: SendImageStatusRequest): Promise<StatusRecord> {+ return this.client.request<StatusRecord>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/status/send-image`,+ body,+ });+ }++ /** Post a video status update. */+ sendVideo(sessionId: string, body: SendVideoStatusRequest): Promise<StatusRecord> {+ return this.client.request<StatusRecord>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/status/send-video`,+ body,+ });+ }++ /** Delete a status update by id. */+ delete(sessionId: string, statusId: string): Promise<void> {+ return this.client.request<void>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/status/${encodeSegment(statusId)}`,+ });+ }+}diff --git a/sdk/javascript/src/resources/templates.ts b/sdk/javascript/src/resources/templates.tsnew file mode 100644index 000000000..6f0294b77--- /dev/null+++ b/sdk/javascript/src/resources/templates.ts@@ -0,0 +1,56 @@+/**+ * Templates resource — stored message templates with `{{variable}}` placeholders.+ *+ * Backed by `src/modules/template/template.controller.ts`.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { CreateTemplateRequest, TemplateRecord, UpdateTemplateRequest } from '../types.js';++export class TemplatesResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List all templates for a session. */+ list(sessionId: string): Promise<TemplateRecord[]> {+ return this.client.request<TemplateRecord[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/templates`,+ });+ }++ /** Get a single template by id. */+ get(sessionId: string, id: string): Promise<TemplateRecord> {+ return this.client.request<TemplateRecord>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/templates/${encodeSegment(id)}`,+ });+ }++ /** Create a new template. */+ create(sessionId: string, body: CreateTemplateRequest): Promise<TemplateRecord> {+ return this.client.request<TemplateRecord>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/templates`,+ body,+ });+ }++ /** Update a template. */+ update(sessionId: string, id: string, body: UpdateTemplateRequest): Promise<TemplateRecord> {+ return this.client.request<TemplateRecord>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/templates/${encodeSegment(id)}`,+ body,+ });+ }++ /** Delete a template. */+ delete(sessionId: string, id: string): Promise<void> {+ return this.client.request<void>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/templates/${encodeSegment(id)}`,+ });+ }+}diff --git a/sdk/javascript/src/resources/webhooks.ts b/sdk/javascript/src/resources/webhooks.tsnew file mode 100644index 000000000..d300d712c--- /dev/null+++ b/sdk/javascript/src/resources/webhooks.ts@@ -0,0 +1,64 @@+/**+ * Webhooks resource — configure event delivery to external HTTP endpoints.+ *+ * Backed by `src/modules/webhook/webhook.controller.ts`.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { CreateWebhookRequest, UpdateWebhookRequest, WebhookResponse, WebhookTestResult } from '../types.js';++export class WebhooksResource {+ constructor(private readonly client: OpenWAClient) {}++ /** List all webhooks for a session. */+ list(sessionId: string): Promise<WebhookResponse[]> {+ return this.client.request<WebhookResponse[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/webhooks`,+ });+ }++ /** Get a single webhook by id. */+ get(sessionId: string, id: string): Promise<WebhookResponse> {+ return this.client.request<WebhookResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/webhooks/${encodeSegment(id)}`,+ });+ }++ /** Create a new webhook. */+ create(sessionId: string, body: CreateWebhookRequest): Promise<WebhookResponse> {+ return this.client.request<WebhookResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/webhooks`,+ body,+ });+ }++ /** Update a webhook. */+ update(sessionId: string, id: string, body: UpdateWebhookRequest): Promise<WebhookResponse> {+ return this.client.request<WebhookResponse>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/webhooks/${encodeSegment(id)}`,+ body,+ });+ }++ /** Delete a webhook. */+ delete(sessionId: string, id: string): Promise<void> {+ return this.client.request<void>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/webhooks/${encodeSegment(id)}`,+ });+ }++ /** Trigger a test dispatch to the webhook URL and report the result. */+ test(sessionId: string, id: string): Promise<WebhookTestResult> {+ return this.client.request<WebhookTestResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/webhooks/${encodeSegment(id)}/test`,+ });+ }+}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsnew file mode 100644index 000000000..228c318ac--- /dev/null+++ b/sdk/javascript/src/types.ts@@ -0,0 +1,667 @@+/**+ * Request and response type definitions for the OpenWA API.+ *+ * IMPORTANT (hybrid codegen strategy): this module is the single source of truth+ * for wire types. It is the part most prone to drift with the backend, and is+ * structured so that it can be regenerated by an OpenAPI codegen pass later+ * without touching the hand-written resource methods (paths + DX live elsewhere).+ *+ * Field names mirror the backend DTOs exactly (camelCase JSON).+ *+ * @packageDocumentation+ */++// ── Common ────────────────────────────────────────────────────────++/** A WhatsApp JID, e.g. `[email protected]` (user) or `120363…@g.us` (group). */+export type Jid = string;++/** Session lifecycle status. */+export type SessionStatus =+ | 'created'+ | 'initializing'+ | 'qr_ready'+ | 'authenticating'+ | 'ready'+ | 'disconnected'+ | 'failed';++/** Minimal success envelope returned by some state-changing endpoints. */+export interface SuccessResult {+ success: boolean;+ message?: string;+}++// ── Session ───────────────────────────────────────────────────────++export interface SessionResponse {+ id: string;+ name: string;+ status: SessionStatus;+ phone?: string | null;+ pushName?: string | null;+ connectedAt?: string | null;+ lastActive?: string | null;+ createdAt: string;+ updatedAt: string;+ /** Only present when `status === 'failed'`. */+ lastError?: string | null;+}++export interface CreateSessionRequest {+ /** Alphanumeric + hyphens, 3–50 chars. */+ name: string;+ config?: Record<string, unknown>;+ proxyUrl?: string;+ proxyType?: 'http' | 'https' | 'socks4' | 'socks5';+}++export interface QrCodeResponse {+ /** Data URL, e.g. `data:image/png;base64,…`. */+ qrCode: string;+ status: SessionStatus;+}++export interface PairingCodeResponse {+ /** 8-character code, e.g. `ABCD1234`. */+ pairingCode: string;+ status: string;+}++export interface RequestPairingCodeRequest {+ /** Digits only, international format, e.g. `628123456789`. */+ phoneNumber: string;+}++export interface SessionStatsOverview {+ total: number;+ active: number;+ ready: number;+ disconnected: number;+ byStatus: Record<string, number>;+ memoryUsage?: { heapUsed: number; heapTotal: number; rss: number };+}++// ── Message ───────────────────────────────────────────────────────++/** Returned by every send operation. */+export interface MessageResponse {+ messageId: string;+ /** Unix timestamp in milliseconds. */+ timestamp: number;+}++export interface SendTextRequest {+ chatId: Jid;+ /** Max 4096 chars. */+ text: string;+}++export interface SendMediaRequest {+ chatId: Jid;+ /** Mutually exclusive with `base64`. */+ url?: string;+ /** Requires `mimetype`. */+ base64?: string;+ mimetype?: string;+ /** Required for documents; max 255 chars. */+ filename?: string;+ /** Max 1024 chars. */+ caption?: string;+}++export interface SendLocationRequest {+ chatId: Jid;+ latitude: number;+ longitude: number;+ description?: string;+ address?: string;+}++export interface SendContactRequest {+ chatId: Jid;+ contactName: string;+ contactNumber: string;+}++export interface ReplyMessageRequest {+ chatId: Jid;+ quotedMessageId: string;+ text: string;+}++export interface ForwardMessageRequest {+ fromChatId: Jid;+ toChatId: Jid;+ messageId: string;+}++export interface ReactMessageRequest {+ chatId: Jid;+ messageId: string;+ /** Empty string removes the reaction. */+ emoji: string;+}++export interface DeleteMessageRequest {+ chatId: Jid;+ messageId: string;+ /** Delete for everyone (default true). */+ forEveryone?: boolean;+}++export interface SendTemplateRequest {+ chatId: Jid;+ /** Provide exactly one of `templateId` or `templateName`. */+ templateId?: string;+ /** Provide exactly one of `templateId` or `templateName`. */+ templateName?: string;+ /** Template variables (server DTO field is `vars`). */+ vars?: Record<string, string>;+}++export interface ListMessagesQuery {+ chatId?: Jid;+ from?: Jid;+ limit?: number;+ offset?: number;+}++export interface MessageHistoryQuery {+ limit?: number;+ includeMedia?: boolean;+ deep?: boolean;+}++/** Message direction. */+export type MessageDirection = 'incoming' | 'outgoing';++/** Delivery status for a message. */+export type DeliveryStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'failed';++/** A persisted message row, as returned by `GET /sessions/:id/messages`. */+export interface MessageRecord {+ id: string;+ sessionId: string;+ /** Engine/WhatsApp message id; may be null until a send is acked. */+ waMessageId?: string | null;+ chatId: Jid;+ from: Jid;+ to: Jid;+ body?: string | null;+ type: string;+ direction: MessageDirection;+ /** Unix timestamp in milliseconds. */+ timestamp?: number | null;+ metadata?: Record<string, unknown> | null;+ status: DeliveryStatus;+ createdAt: string;+}++/**+ * A message read live from WhatsApp by `messages.history()`. This is the engine+ * payload (richer and differently shaped than the persisted {@link MessageRecord}).+ */+export interface ChatHistoryMessage {+ id: string;+ from: Jid;+ to: Jid;+ chatId: Jid;+ body: string;+ type: string;+ /** Unix timestamp in seconds. */+ timestamp: number;+ fromMe: boolean;+ isGroup: boolean;+ isStatusBroadcast?: boolean;+ /** For group messages, the participant who sent it (`from` is the group JID). */+ author?: Jid;+ mentionedIds?: Jid[];+ isLidSender?: boolean;+ senderPhone?: string | null;+ media?: {+ mimetype: string;+ filename?: string;+ /** base64; absent when the payload was omitted (too large). */+ data?: string;+ omitted?: boolean;+ sizeBytes?: number;+ };+ quotedMessage?: { id: string; body: string };+ location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };+}++/** Paginated payload returned by `GET /sessions/:id/messages`. */+export interface MessageListResponse {+ messages: MessageRecord[];+ total: number;+}++export interface ReactionSender {+ senderId: Jid;+ emoji: string;+ /** Unix timestamp in seconds. */+ timestamp: number;+}++/** One emoji and everyone who reacted with it (server returns `MessageReaction[]`). */+export interface ReactionRecord {+ emoji: string;+ senders: ReactionSender[];+}++// ── Bulk ──────────────────────────────────────────────────────────++export type BulkMessageType = 'text' | 'image' | 'video' | 'audio' | 'document';++export interface BulkMessageContent {+ text?: string;+ image?: SendMediaRequest;+ video?: SendMediaRequest;+ audio?: SendMediaRequest;+ document?: SendMediaRequest;+ caption?: string;+}++export interface BulkMessageItem {+ chatId: Jid;+ type: BulkMessageType;+ content: BulkMessageContent;+ variables?: Record<string, string>;+}++export interface SendBulkRequest {+ messages: BulkMessageItem[];+ /** Optional caller-supplied idempotency/batch id. */+ batchId?: string;+ options?: {+ /** Minimum 1000 ms; default 3000. */+ delayBetweenMessages?: number;+ /** Randomize the delay between messages to look less automated. */+ randomizeDelay?: boolean;+ stopOnError?: boolean;+ };+}++export interface BulkMessageResponse {+ batchId: string;+ status: string;+ totalMessages: number;+ estimatedCompletionTime: string;+ statusUrl: string;+}++/** Progress counters for a bulk-send batch. */+export interface BatchProgress {+ total: number;+ sent: number;+ failed: number;+ pending: number;+ cancelled: number;+}++/** Per-message outcome within a batch result list. */+export interface BatchMessageResult {+ chatId?: Jid;+ status?: string;+ messageId?: string;+ sentAt?: string;+ error?: { code: string; message: string };+}++/**+ * Response from `GET /messages/batch/:batchId` (batch status polling) and+ * `POST /messages/batch/:batchId/cancel`. Distinct from+ * {@link BulkMessageResponse} (the send-bulk acknowledgement).+ */+export interface BatchStatusResponse {+ batchId: string;+ status: string;+ progress?: BatchProgress;+ results?: BatchMessageResult[];+ startedAt?: string;+ completedAt?: string;+}++// ── Contact ───────────────────────────────────────────────────────++export interface ContactRecord {+ id: Jid;+ name?: string | null;+ number?: string | null;+ pushname?: string | null;+ isBusiness?: boolean;+ isMyContact?: boolean;+}++export interface CheckNumberResponse {+ number: string;+ exists: boolean;+ whatsappId?: string | null;+}++export interface ProfilePictureResponse {+ url: string | null;+}++export interface ContactPhoneResponse {+ contactId: Jid;+ phone: string | null;+}++// ── Group ─────────────────────────────────────────────────────────++export interface GroupParticipant {+ id: Jid;+ number: string;+ name?: string;+ isAdmin: boolean;+ isSuperAdmin: boolean;+}++/** Item returned by `GET /sessions/:id/groups` (the slim list shape). */+export interface GroupSummary {+ id: Jid;+ name: string;+ participantsCount?: number;+ isAdmin?: boolean;+ /** JID of the parent community, or null if standalone. */+ linkedParentJID?: string | null;+}++/** Full detail returned by `GET /sessions/:id/groups/:groupId`. */+export interface GroupInfo {+ id: Jid;+ name: string;+ description?: string | null;+ owner?: Jid | null;+ /** Unix timestamp in seconds. */+ createdAt?: number;+ participants: GroupParticipant[];+ isReadOnly?: boolean;+ isAnnounce?: boolean;+ linkedParentJID?: string | null;+}++export interface CreateGroupRequest {+ name: string;+ participants: Jid[];+}++export interface ParticipantsRequest {+ participants: Jid[];+}++export interface GroupSubjectRequest {+ subject: string;+}++export interface GroupDescriptionRequest {+ /** May be empty to clear. */+ description: string;+}++export interface InviteCodeResponse {+ inviteCode: string;+ inviteLink: string;+ message?: string;+}++// ── Webhook ───────────────────────────────────────────────────────++/** Events a webhook may subscribe to. Use `*` to receive all. */+export type WebhookEvent =+ | 'message.received'+ | 'message.sent'+ | 'message.ack'+ | 'message.failed'+ | 'message.revoked'+ | 'message.reaction'+ | 'session.status'+ | 'session.qr'+ | 'session.authenticated'+ | 'session.disconnected'+ // Reserved: accepted on subscribe but not dispatched yet.+ | 'group.join'+ | 'group.leave'+ | 'group.update'+ | '*';++export interface WebhookFilterCondition {+ field: string;+ operator: string;+ value: string[];+}++export interface WebhookFilters {+ conditions: WebhookFilterCondition[];+}++export interface CreateWebhookRequest {+ url: string;+ events?: WebhookEvent[];+ /** HMAC secret; signed as `X-OpenWA-Signature: sha256=…`. */+ secret?: string;+ headers?: Record<string, string>;+ filters?: WebhookFilters | null;+ /** 0–5; default 3. Server DTO field is `retryCount`. */+ retryCount?: number;+}++export type UpdateWebhookRequest = Partial<CreateWebhookRequest> & { active?: boolean };++export interface WebhookResponse {+ id: string;+ sessionId: string;+ url: string;+ events: WebhookEvent[];+ active: boolean;+ filters?: WebhookFilters | null;+ retryCount: number;+ /** ISO timestamp of the last delivery attempt, or null if never triggered. */+ lastTriggeredAt: string | null;+ createdAt: string;+ updatedAt: string;+ // NOTE: the server deliberately omits `secret` and `headers` from read responses.+}++export interface WebhookTestResult {+ success: boolean;+ statusCode?: number;+ error?: string;+}++// ── Chat (session-scoped chat operations) ─────────────────────────++export interface ChatSummary {+ id: Jid;+ name?: string | null;+ isGroup?: boolean;+ unreadCount?: number;+ /** Preview text of the last message (the server returns a plain string, not an object). */+ lastMessage?: string;+ timestamp?: string | number;+}++export interface MarkChatRequest {+ chatId: Jid;+}++export type ChatState = 'typing' | 'recording' | 'paused';++export interface SendChatStateRequest {+ chatId: Jid;+ state: ChatState;+}++export interface DeleteChatRequest {+ chatId: Jid;+}++// ── Status / Stories ──────────────────────────────────────────────++export interface StatusRecord {+ id?: string;+ statusId?: string;+ type?: string;+ body?: string | null;+ timestamp?: string | number;+}++export interface SendTextStatusRequest {+ text: string;+ /** Hex background color, e.g. `#25D366`. */+ backgroundColor?: string;+ /** Font index supported by WhatsApp status. */+ font?: number;+}++/** Media payload for a status post: provide `url` OR `base64`. */+export interface StatusMediaInput {+ url?: string;+ base64?: string;+}++/** Server expects a nested `{ image: { url|base64 } }` body, not flat media fields. */+export interface SendImageStatusRequest {+ image: StatusMediaInput;+ caption?: string;+}++/** Server expects a nested `{ video: { url|base64 } }` body, not flat media fields. */+export interface SendVideoStatusRequest {+ video: StatusMediaInput;+ caption?: string;+}++// ── Health ────────────────────────────────────────────────────────++export interface HealthResponse {+ status: string;+ timestamp?: string;+ version?: string;+}++export interface HealthReadyDetails {+ mainDatabase?: string;+ dataDatabase?: string;+}++export interface HealthReadyResponse {+ status: string;+ details?: HealthReadyDetails;+}++// ── Auth ──────────────────────────────────────────────────────────++export interface AuthValidateResponse {+ valid: boolean;+ role?: string;+}++// ── Template ──────────────────────────────────────────────────────++export interface TemplateRecord {+ id: string;+ sessionId: string;+ name: string;+ /** Template body with `{{variable}}` placeholders. */+ body: string;+ header?: string | null;+ footer?: string | null;+ createdAt: string;+ updatedAt: string;+}++export interface CreateTemplateRequest {+ /** Unique template name within the session. */+ name: string;+ body: string;+ header?: string;+ footer?: string;+}++export type UpdateTemplateRequest = Partial<CreateTemplateRequest>;++// ── Label (WhatsApp Business) ─────────────────────────────────────++export interface LabelRecord {+ id: string;+ name: string;+ color?: string;+ colorHex?: string;+}++export interface AddLabelRequest {+ labelId: string;+}++// ── Channel / Newsletter ──────────────────────────────────────────++export interface ChannelRecord {+ id: Jid;+ name?: string;+ description?: string | null;+ subscriberCount?: number;+ pictureUrl?: string | null;+ role?: string;+}++export interface ChannelMessageQuery {+ /** Max messages to return (default 50). */+ limit?: number;+}++export interface SubscribeChannelRequest {+ /** Channel invite code (from a channel link). */+ inviteCode: string;+}++// ── Catalog (Business) ────────────────────────────────────────────++export interface CatalogInfo {+ id: string;+ name: string;+ description?: string | null;+ productCount: number;+ url: string;+}++export interface CatalogProductsQuery {+ /** Page number (min 1, default 1). */+ page?: number;+ /** Page size (min 1, default 20). */+ limit?: number;+}++export interface CatalogProduct {+ id: string;+ name: string;+ description?: string | null;+ price: number;+ currency: string;+ priceFormatted: string;+ imageUrl?: string | null;+ url: string;+ isAvailable: boolean;+ retailerId?: string;+}++/** Paginated payload returned by `GET /sessions/:id/catalog/products`. */+export interface PaginatedProducts {+ products: CatalogProduct[];+ pagination: { page: number; limit: number; total: number; totalPages: number };+}++export interface SendProductRequest {+ chatId: Jid;+ productId: string;+ /** Optional body/caption text. */+ body?: string;+}++export interface SendCatalogRequest {+ chatId: Jid;+ /** Optional body/caption text. */+ body?: string;+}diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsnew file mode 100644index 000000000..1a04fd5e2--- /dev/null+++ b/sdk/javascript/test/client.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it } from 'vitest';+import {+ OpenWAClient,+ OpenWAApiError,+ OpenWAAuthError,+ OpenWAForbiddenError,+ OpenWANotFoundError,+ OpenWAConflictError,+ OpenWARateLimitError,+ OpenWANotImplementedError,+ OpenWATimeoutError,+} from '../src';+import type { FetchLike } from '../src';+import { MockTransport } from './helpers';++function client(transport: MockTransport): OpenWAClient {+ return new OpenWAClient({+ baseUrl: 'http://localhost:2785',+ apiKey: 'owa_k1_test',+ fetch: transport.asFetch(),+ });+}++describe('OpenWAClient', () => {+ it('requires baseUrl and apiKey', () => {+ expect(() => new OpenWAClient({ baseUrl: '', apiKey: 'x' })).toThrow();+ expect(() => new OpenWAClient({ baseUrl: 'http://x', apiKey: '' })).toThrow();+ });++ it('sends the API key as X-API-Key and JSON content type', async () => {+ const t = new MockTransport().on('GET', '/api/sessions', { body: [] });+ await client(t).sessions.list();+ expect(t.lastCall!.headers['x-api-key']).toBe('owa_k1_test');+ expect(t.lastCall!.headers['content-type']).toBe('application/json');+ });++ it('strips a trailing slash from baseUrl', async () => {+ const t = new MockTransport().on('GET', '/api/sessions', { body: [] });+ const c = new OpenWAClient({ baseUrl: 'http://localhost:2785/', apiKey: 'k', fetch: t.asFetch() });+ await c.sessions.list();+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions');+ });++ it('does not auto-follow redirects (passes redirect: manual to fetch)', async () => {+ // Auto-following a redirect would re-send X-API-Key to the redirect target,+ // potentially a different origin. The SDK must not follow silently.+ let seenInit: RequestInit | undefined;+ const recordingFetch: FetchLike = async (_url, init) => {+ seenInit = init as RequestInit;+ return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });+ };+ const c = new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: recordingFetch });+ await c.health.check();+ expect(seenInit?.redirect).toBe('manual');+ });++ it('percent-encodes path segments but keeps @ in JIDs readable', async () => {+ const t = new MockTransport().on('GET', /\/history$/, { body: [] });+ await client(t).messages.history('s', '[email protected]');+ expect(t.lastCall!.url).toContain('/messages/[email protected]/history'); // @ preserved+ const t2 = new MockTransport().on('GET', /\/history$/, { body: [] });+ await client(t2).messages.history('s', 'weird/id#x');+ expect(t2.lastCall!.url).toContain('weird%2Fid%23x'); // path-breaking chars encoded+ });++ it('serializes query params and skips null/undefined', async () => {+ const t = new MockTransport().on('GET', /\/messages/, { body: [] });+ await client(t).messages.list('s1', { chatId: '[email protected]', from: undefined, limit: 10 });+ expect(t.lastCall!.url).toContain('chatId=a%40c.us');+ expect(t.lastCall!.url).toContain('limit=10');+ expect(t.lastCall!.url).not.toContain('from=');+ });++ it('maps a 404 to OpenWANotFoundError with parsed body', async () => {+ const t = new MockTransport().on('GET', '/api/sessions/missing', {+ status: 404,+ body: { statusCode: 404, message: 'Session not found', error: 'Not Found' },+ });+ await expect(client(t).sessions.get('missing')).rejects.toBeInstanceOf(OpenWANotFoundError);+ await expect(client(t).sessions.get('missing')).rejects.toMatchObject({ status: 404 });+ });++ it('exposes all expected resource properties', () => {+ const c = client(new MockTransport());+ for (const r of ['sessions', 'messages', 'contacts', 'groups', 'webhooks', 'chats', 'status', 'health']) {+ expect(c).toHaveProperty(r);+ }+ });++ it('treats 204 as a null result', async () => {+ const t = new MockTransport().on('DELETE', '/api/sessions/x', { status: 204 });+ await expect(client(t).sessions.delete('x')).resolves.toBeNull();+ });++ it('OpenWAApiError.fromResponse parses the NestJS envelope', async () => {+ const t = new MockTransport().on('POST', /send-text/, {+ status: 409,+ body: { statusCode: 409, message: 'Engine not ready', error: 'Conflict' },+ });+ await expect(client(t).messages.sendText('s', { chatId: '[email protected]', text: 'hi' })).rejects.toBeInstanceOf(+ OpenWAApiError,+ );+ });++ it('maps each status code to its typed error subclass', async () => {+ const cases: Array<[number, new (...a: never[]) => OpenWAApiError]> = [+ [401, OpenWAAuthError],+ [403, OpenWAForbiddenError],+ [404, OpenWANotFoundError],+ [409, OpenWAConflictError],+ [429, OpenWARateLimitError],+ [501, OpenWANotImplementedError],+ ];+ for (const [status, cls] of cases) {+ const t = new MockTransport().on('GET', '/api/sessions', {+ status,+ body: { statusCode: status, message: 'x', error: 'E' },+ });+ await expect(client(t).sessions.list()).rejects.toBeInstanceOf(cls);+ }+ });++ it('falls back to the generic OpenWAApiError (with .status) for an unmapped status', async () => {+ const t = new MockTransport().on('GET', '/api/sessions', {+ status: 418,+ body: { statusCode: 418, message: 'teapot', error: 'Teapot' },+ });+ await expect(client(t).sessions.list()).rejects.toMatchObject({ status: 418 });+ await expect(client(t).sessions.list()).rejects.toBeInstanceOf(OpenWAApiError);+ });++ it('throws OpenWATimeoutError when the request aborts', async () => {+ const abortingFetch: FetchLike = async () => {+ const e = new Error('aborted');+ e.name = 'AbortError';+ throw e;+ };+ const c = new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: abortingFetch });+ await expect(c.sessions.list()).rejects.toBeInstanceOf(OpenWATimeoutError);+ });++ it('keeps X-API-Key winning over defaultHeaders', async () => {+ const t = new MockTransport().on('GET', '/api/sessions', { body: [] });+ const c = new OpenWAClient({+ baseUrl: 'http://x',+ apiKey: 'REAL',+ defaultHeaders: { 'X-API-Key': 'EVIL', 'X-Trace': 'keep' },+ fetch: t.asFetch(),+ });+ await c.sessions.list();+ expect(t.lastCall!.headers['x-api-key']).toBe('REAL');+ expect(t.lastCall!.headers['x-trace']).toBe('keep');+ });+});diff --git a/sdk/javascript/test/helpers.ts b/sdk/javascript/test/helpers.tsnew file mode 100644index 000000000..938ff3e42--- /dev/null+++ b/sdk/javascript/test/helpers.ts@@ -0,0 +1,108 @@+/**+ * Test helpers — a mock fetch transport that records calls and returns+ * canned responses, so tests assert on exact method/url/body/headers without+ * any real network or global monkey-patching.+ */+import type { FetchLike } from '../src';++export interface RecordedCall {+ url: string;+ method: string;+ headers: Record<string, string>;+ body: unknown;+}++export interface MockResponseSpec {+ status?: number;+ body?: unknown;+ text?: string;+}++/** A scripted mock transport. Throws if a call doesn't match a route. */+export class MockTransport {+ readonly calls: RecordedCall[] = [];+ private readonly routes: { method: string; matcher: RegExp; respond: (call: RecordedCall) => MockResponseSpec }[] =+ [];+ private fallback: ((call: RecordedCall) => MockResponseSpec) | null = null;++ /** Register a response for the first call matching `method` + `matcher`. */+ on(+ method: string,+ matcher: string | RegExp,+ respond: MockResponseSpec | ((call: RecordedCall) => MockResponseSpec),+ ): this {+ const regex = typeof matcher === 'string' ? new RegExp(matcher) : matcher;+ this.routes.push({+ method,+ matcher: regex,+ respond: typeof respond === 'function' ? respond : () => respond,+ });+ return this;+ }++ /** Catch-all for any unmatched call. */+ passthrough(respond: MockResponseSpec | ((call: RecordedCall) => MockResponseSpec)): this {+ this.fallback = typeof respond === 'function' ? respond : () => respond;+ return this;+ }++ /** @internal build the FetchLike impl consumed by the client. */+ asFetch(): FetchLike {+ return (async (input: RequestInfo | URL, init?: RequestInit) => {+ const fullUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;+ const method = (init?.method ?? 'GET').toUpperCase();+ const rawHeaders = init?.headers;+ const headers: Record<string, string> = {};+ if (rawHeaders) {+ const collect = (k: string, v: string): void => {+ headers[String(k).toLowerCase()] = String(v);+ };+ if (rawHeaders instanceof Headers) {+ rawHeaders.forEach((v, k) => collect(k, v));+ } else if (Array.isArray(rawHeaders)) {+ for (const [k, v] of rawHeaders) collect(k, String(v));+ } else {+ for (const [k, v] of Object.entries(rawHeaders as Record<string, string>)) collect(k, v);+ }+ }+ let body: unknown = undefined;+ if (init?.body) {+ try {+ body = JSON.parse(String(init.body));+ } catch {+ body = String(init.body);+ }+ }+ const call: RecordedCall = { url: fullUrl, method, headers, body };+ this.calls.push(call);++ // Route matching uses the pathname only (query stripped) so regexes+ // like `/contacts$` still match `…/contacts?limit=10`.+ const matchUrl = fullUrl.split('?')[0];++ let spec: MockResponseSpec;+ const route = this.routes.find(r => r.method === method && r.matcher.test(matchUrl));+ if (route) {+ spec = route.respond(call);+ } else if (this.fallback) {+ spec = this.fallback(call);+ } else {+ throw new Error(`MockTransport: no route for ${method} ${fullUrl}`);+ }++ const status = spec.status ?? 200;+ // 204/100/304 may not carry a body. Node's undici Response rejects+ // an empty-string body with these statuses, so pass `null`.+ const noBody = status === 204 || status === 100 || status === 304;+ const responseBody: BodyInit | null = noBody+ ? null+ : (spec.text ?? (spec.body === undefined ? '' : JSON.stringify(spec.body)));+ const resHeaders: Record<string, string> = noBody ? {} : { 'content-type': 'application/json' };+ return new Response(responseBody, { status, headers: resHeaders });+ }) as FetchLike;+ }++ get lastCall(): RecordedCall | undefined {+ return this.calls[this.calls.length - 1];+ }+}diff --git a/sdk/javascript/test/labels-channels-catalog.test.ts b/sdk/javascript/test/labels-channels-catalog.test.tsnew file mode 100644index 000000000..226249ac7--- /dev/null+++ b/sdk/javascript/test/labels-channels-catalog.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from 'vitest';+import { OpenWAClient } from '../src';+import { MockTransport } from './helpers';++function client(t: MockTransport): OpenWAClient {+ return new OpenWAClient({ baseUrl: 'http://localhost:2785', apiKey: 'k', fetch: t.asFetch() });+}++describe('LabelsResource — exact paths', () => {+ it('list / get / forChat / addToChat / removeFromChat', async () => {+ const t = new MockTransport()+ .on('GET', /\/labels$/, { body: [{ id: 'l1', name: 'VIP' }] })+ .on('GET', /\/labels\/l1$/, { body: { id: 'l1', name: 'VIP' } })+ .on('GET', /\/labels\/chat\/a@c\.us$/, { body: [{ id: 'l1', name: 'VIP' }] })+ .on('POST', /\/labels\/chat\/a@c\.us$/, { body: { success: true } })+ .on('DELETE', /\/labels\/chat\/a@c\.us\/l1$/, { body: { success: true } });+ const c = client(t);+ await c.labels.list('s');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/labels');+ await c.labels.get('s', 'l1');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/labels/l1');+ await c.labels.forChat('s', '[email protected]');+ expect(t.lastCall!.url).toContain('/labels/chat/[email protected]');+ await c.labels.addToChat('s', '[email protected]', { labelId: 'l1' });+ expect(t.lastCall!.method).toBe('POST');+ expect(t.lastCall!.body).toEqual({ labelId: 'l1' });+ await c.labels.removeFromChat('s', '[email protected]', 'l1');+ expect(t.lastCall!.method).toBe('DELETE');+ expect(t.lastCall!.url).toContain('/labels/chat/[email protected]/l1');+ });+});++describe('ChannelsResource — exact paths', () => {+ it('list / get / messages / subscribe / unsubscribe', async () => {+ const t = new MockTransport()+ .on('GET', /\/channels$/, { body: [{ id: '123@newsletter', name: 'News' }] })+ .on('GET', /\/channels\/123@newsletter$/, { body: { id: '123@newsletter', name: 'News' } })+ .on('GET', /\/channels\/123@newsletter\/messages$/, { body: [] })+ .on('POST', /\/channels\/subscribe$/, { body: { id: '123@newsletter', name: 'News' } })+ .on('DELETE', /\/channels\/123@newsletter$/, { body: { success: true } });+ const c = client(t);+ await c.channels.list('s');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/channels');+ await c.channels.get('s', '123@newsletter');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/channels/123@newsletter');+ await c.channels.messages('s', '123@newsletter', { limit: 10 });+ expect(t.lastCall!.url).toContain('/channels/123@newsletter/messages');+ expect(t.lastCall!.url).toContain('limit=10');+ await c.channels.subscribe('s', { inviteCode: 'ABCxyz' });+ expect(t.lastCall!.method).toBe('POST');+ expect(t.lastCall!.body).toEqual({ inviteCode: 'ABCxyz' });+ expect(t.lastCall!.url).toContain('/channels/subscribe');+ await c.channels.unsubscribe('s', '123@newsletter');+ expect(t.lastCall!.method).toBe('DELETE');+ });+});++describe('CatalogResource — exact paths (note: catalog controller is session-rooted)', () => {+ it('info / products / product', async () => {+ const t = new MockTransport()+ .on('GET', /\/catalog$/, { body: { id: 'c1', name: 'My Shop', productCount: 5, url: 'http://shop' } })+ .on('GET', /\/catalog\/products$/, {+ body: { products: [{ id: 'p1', name: 'Widget' }], pagination: { page: 1, limit: 20, total: 1, totalPages: 1 } },+ })+ .on('GET', /\/catalog\/products\/p1$/, { body: { id: 'p1', name: 'Widget' } });+ const c = client(t);+ await c.catalog.info('s');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/catalog');+ const page = await c.catalog.products('s', { page: 1, limit: 20 });+ expect(page.products).toHaveLength(1);+ expect(page.pagination.total).toBe(1);+ expect(t.lastCall!.url).toContain('/catalog/products');+ expect(t.lastCall!.url).toContain('page=1');+ expect(t.lastCall!.url).toContain('limit=20');+ await c.catalog.product('s', 'p1');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/catalog/products/p1');+ });++ it('sendProduct / sendCatalog share the messages path', async () => {+ const t = new MockTransport()+ .on('POST', /\/messages\/send-product$/, { body: { messageId: 'm', timestamp: 1 } })+ .on('POST', /\/messages\/send-catalog$/, { body: { messageId: 'm', timestamp: 1 } });+ const c = client(t);+ await c.catalog.sendProduct('s', { chatId: '[email protected]', productId: 'p1', body: 'see this' });+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/messages/send-product');+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', productId: 'p1', body: 'see this' });+ await c.catalog.sendCatalog('s', { chatId: '[email protected]', body: 'our catalog' });+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/messages/send-catalog');+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', body: 'our catalog' });+ });+});++describe('TemplatesResource — exact paths and bodies', () => {+ it('list / get / create / update / delete', async () => {+ const tpl = { id: 't1', sessionId: 's', name: 'welcome', body: 'Hi {{name}}', createdAt: '', updatedAt: '' };+ const t = new MockTransport()+ .on('GET', /\/templates$/, { body: [tpl] })+ .on('GET', /\/templates\/t1$/, { body: tpl })+ .on('POST', /\/templates$/, { body: tpl })+ .on('PUT', /\/templates\/t1$/, { body: { ...tpl, body: 'Hello {{name}}' } })+ .on('DELETE', /\/templates\/t1$/, { status: 204 });+ const c = client(t);+ await c.templates.list('s');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/templates');+ await c.templates.get('s', 't1');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s/templates/t1');+ await c.templates.create('s', { name: 'welcome', body: 'Hi {{name}}' });+ expect(t.lastCall!.method).toBe('POST');+ expect(t.lastCall!.body).toEqual({ name: 'welcome', body: 'Hi {{name}}' });+ await c.templates.update('s', 't1', { body: 'Hello {{name}}' });+ expect(t.lastCall!.method).toBe('PUT');+ expect(t.lastCall!.body).toEqual({ body: 'Hello {{name}}' });+ await c.templates.delete('s', 't1');+ expect(t.lastCall!.method).toBe('DELETE');+ });+});++describe('Client exposes all resources', () => {+ it('has labels, channels, catalog, templates on the client', () => {+ const c = client(new MockTransport());+ for (const r of [+ 'sessions',+ 'messages',+ 'contacts',+ 'groups',+ 'webhooks',+ 'chats',+ 'status',+ 'health',+ 'labels',+ 'channels',+ 'catalog',+ 'templates',+ ]) {+ expect(c).toHaveProperty(r);+ }+ });+});diff --git a/sdk/javascript/test/messages.test.ts b/sdk/javascript/test/messages.test.tsnew file mode 100644index 000000000..4221d440a--- /dev/null+++ b/sdk/javascript/test/messages.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from 'vitest';+import { OpenWAClient } from '../src';+import { MockTransport } from './helpers';++function client(t: MockTransport): OpenWAClient {+ return new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: t.asFetch() });+}++describe('MessagesResource — exact paths', () => {+ it('sendText posts to /messages/send-text (NOT /messages/text)', async () => {+ const t = new MockTransport().on('POST', /send-text$/, { body: { messageId: 'm1', timestamp: 1 } });+ await client(t).messages.sendText('s1', { chatId: '[email protected]', text: 'hi' });+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s1/messages/send-text');+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', text: 'hi' });+ });++ it('sendImage posts to /messages/send-image', async () => {+ const t = new MockTransport().on('POST', /send-image$/, { body: { messageId: 'm', timestamp: 2 } });+ await client(t).messages.sendImage('s', { chatId: '[email protected]', url: 'http://img' });+ expect(t.lastCall!.url).toContain('/messages/send-image');+ });++ it('sendVideo / sendAudio / sendDocument / sendSticker use correct segments', async () => {+ const cases: Array<[string, (c: OpenWAClient) => Promise<unknown>]> = [+ ['send-video', c => c.messages.sendVideo('s', { chatId: '[email protected]', url: 'u' })],+ ['send-audio', c => c.messages.sendAudio('s', { chatId: '[email protected]', url: 'u' })],+ ['send-document', c => c.messages.sendDocument('s', { chatId: '[email protected]', filename: 'f.pdf' })],+ ['send-sticker', c => c.messages.sendSticker('s', { chatId: '[email protected]', url: 'u' })],+ ];+ for (const [segment, fn] of cases) {+ const t = new MockTransport().on('POST', new RegExp(`${segment}$`), { body: { messageId: 'm', timestamp: 3 } });+ await fn(client(t));+ expect(t.lastCall!.url).toContain(`/messages/${segment}`);+ }+ });++ it('sendLocation / sendContact / sendTemplate', async () => {+ const t = new MockTransport()+ .on('POST', /send-location/, { body: { messageId: 'm', timestamp: 1 } })+ .on('POST', /send-contact/, { body: { messageId: 'm', timestamp: 1 } })+ .on('POST', /send-template/, { body: { messageId: 'm', timestamp: 1 } });+ const c = client(t);+ await c.messages.sendLocation('s', { chatId: '[email protected]', latitude: -6.2, longitude: 106.8 });+ expect(t.lastCall!.url).toContain('/messages/send-location');+ await c.messages.sendContact('s', { chatId: '[email protected]', contactName: 'A', contactNumber: '628' });+ expect(t.lastCall!.url).toContain('/messages/send-contact');+ await c.messages.sendTemplate('s', { chatId: '[email protected]', templateId: 't1', vars: { name: 'Sam' } });+ expect(t.lastCall!.url).toContain('/messages/send-template');+ // Server DTO field is `vars` (NOT `variables`) — body must forward verbatim.+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', templateId: 't1', vars: { name: 'Sam' } });+ });++ it('sendTemplate accepts templateName as the alternative to templateId', async () => {+ const t = new MockTransport().on('POST', /send-template/, { body: { messageId: 'm', timestamp: 1 } });+ await client(t).messages.sendTemplate('s', { chatId: '[email protected]', templateName: 'welcome', vars: { x: '1' } });+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', templateName: 'welcome', vars: { x: '1' } });+ });++ it('list returns the {messages,total} wrapper the server actually sends', async () => {+ const t = new MockTransport().on('GET', /\/messages$/, {+ body: {+ messages: [+ { id: '1', sessionId: 's', chatId: '[email protected]', from: '[email protected]', to: 's', type: 'text', direction: 'incoming', status: 'delivered', createdAt: '' },+ ],+ total: 1,+ },+ });+ const res = await client(t).messages.list('s', { chatId: '[email protected]' });+ expect(res.total).toBe(1);+ expect(res.messages).toHaveLength(1);+ });++ it('reply / forward / react / delete', async () => {+ const t = new MockTransport()+ .on('POST', /\/messages\/reply$/, { body: { messageId: 'm', timestamp: 1 } })+ .on('POST', /\/messages\/forward$/, { body: { messageId: 'm', timestamp: 1 } })+ .on('POST', /\/messages\/react$/, { body: { success: true } })+ .on('POST', /\/messages\/delete$/, { body: { success: true } });+ const c = client(t);+ await c.messages.reply('s', { chatId: '[email protected]', quotedMessageId: 'q', text: 'r' });+ expect(t.lastCall!.url).toContain('/messages/reply');+ await c.messages.forward('s', { fromChatId: '[email protected]', toChatId: '[email protected]', messageId: 'm' });+ expect(t.lastCall!.url).toContain('/messages/forward');+ await c.messages.react('s', { chatId: '[email protected]', messageId: 'm', emoji: '👍' });+ expect(t.lastCall!.url).toContain('/messages/react');+ await c.messages.delete('s', { chatId: '[email protected]', messageId: 'm' });+ expect(t.lastCall!.url).toContain('/messages/delete');+ });++ it('history puts chatId in the path', async () => {+ const t = new MockTransport().on('GET', /\/messages\/[^/]+\/history$/, { body: [] });+ await client(t).messages.history('s', '[email protected]', { limit: 5 });+ expect(t.lastCall!.url).toContain('/messages/[email protected]/history');+ expect(t.lastCall!.url).toContain('limit=5');+ });++ it('reactions puts chatId and messageId in the path', async () => {+ const t = new MockTransport().on('GET', /\/reactions$/, { body: [] });+ await client(t).messages.reactions('s', '[email protected]', 'm1');+ expect(t.lastCall!.url).toContain('/[email protected]/m1/reactions');+ });++ it('sendBulk + batchStatus + cancelBatch', async () => {+ const t = new MockTransport()+ .on('POST', /send-bulk$/, {+ body: { batchId: 'b', status: 'queued', totalMessages: 1, estimatedCompletionTime: 't', statusUrl: '/u' },+ })+ .on('GET', /\/batch\/b$/, {+ body: {+ batchId: 'b',+ status: 'done',+ progress: { total: 1, sent: 1, failed: 0, pending: 0, cancelled: 0 },+ results: [],+ startedAt: 's',+ completedAt: 'c',+ },+ })+ .on('POST', /\/batch\/b\/cancel$/, {+ body: { batchId: 'b', status: 'cancelled', progress: { total: 1, sent: 0, failed: 0, pending: 0, cancelled: 1 } },+ });+ const c = client(t);+ await c.messages.sendBulk('s', { messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'x' } }] });+ expect(t.lastCall!.url).toContain('/messages/send-bulk');+ const status = await c.messages.batchStatus('s', 'b');+ expect(status.progress?.sent).toBe(1);+ expect(t.lastCall!.url).toContain('/messages/batch/b');+ const cancelled = await c.messages.cancelBatch('s', 'b');+ expect(cancelled.status).toBe('cancelled');+ expect(t.lastCall!.url).toContain('/messages/batch/b/cancel');+ expect(t.lastCall!.method).toBe('POST');+ });+});diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.tsnew file mode 100644index 000000000..c483131ff--- /dev/null+++ b/sdk/javascript/test/resources.test.ts@@ -0,0 +1,172 @@+import { describe, expect, it } from 'vitest';+import { OpenWAClient } from '../src';+import { MockTransport } from './helpers';++function client(t: MockTransport): OpenWAClient {+ return new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: t.asFetch() });+}++describe('GroupsResource — exact paths and bodies', () => {+ it('list / get / create', async () => {+ const t = new MockTransport()+ .on('GET', /\/groups$/, { body: [] })+ .on('GET', /\/groups\/g1@g\.us$/, { body: { id: '[email protected]', name: 'G', participants: [] } })+ .on('POST', /\/groups$/, { body: { id: '[email protected]', name: 'G', participants: [] } });+ const c = client(t);+ await c.groups.list('s');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/groups');+ await c.groups.get('s', '[email protected]');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/groups/[email protected]');+ await c.groups.create('s', { name: 'G', participants: ['[email protected]'] });+ expect(t.lastCall!.body).toEqual({ name: 'G', participants: ['[email protected]'] });+ });++ it('participant ops wrap participants in a body', async () => {+ const t = new MockTransport()+ .on('POST', /\/participants$/, { body: { success: true, message: 'added' } })+ .on('DELETE', /\/participants$/, { body: { success: true } })+ .on('POST', /\/participants\/promote$/, { body: { success: true } })+ .on('POST', /\/participants\/demote$/, { body: { success: true } });+ const c = client(t);+ await c.groups.addParticipants('s', '[email protected]', ['[email protected]', '[email protected]']);+ expect(t.lastCall!.body).toEqual({ participants: ['[email protected]', '[email protected]'] });+ expect(t.lastCall!.method).toBe('POST');+ await c.groups.removeParticipants('s', '[email protected]', ['[email protected]']);+ expect(t.lastCall!.method).toBe('DELETE');+ await c.groups.promoteParticipants('s', '[email protected]', ['[email protected]']);+ expect(t.lastCall!.url).toContain('/participants/promote');+ await c.groups.demoteParticipants('s', '[email protected]', ['[email protected]']);+ expect(t.lastCall!.url).toContain('/participants/demote');+ });++ it('subject / description / leave / inviteCode / revoke', async () => {+ const t = new MockTransport()+ .on('PUT', /\/subject$/, { body: { success: true } })+ .on('PUT', /\/description$/, { body: { success: true } })+ .on('POST', /\/leave$/, { body: { success: true } })+ .on('GET', /\/invite-code$/, { body: { inviteCode: 'c', inviteLink: 'l' } })+ .on('POST', /\/invite-code\/revoke$/, { body: { inviteCode: 'c2', inviteLink: 'l2' } });+ const c = client(t);+ await c.groups.setSubject('s', 'g', 'New');+ expect(t.lastCall!.method).toBe('PUT');+ expect(t.lastCall!.body).toEqual({ subject: 'New' });+ await c.groups.setDescription('s', 'g', 'desc');+ expect(t.lastCall!.body).toEqual({ description: 'desc' });+ await c.groups.leave('s', 'g');+ await c.groups.inviteCode('s', 'g');+ await c.groups.revokeInviteCode('s', 'g');+ expect(t.lastCall!.url).toContain('/invite-code/revoke');+ });+});++describe('ContactsResource — exact paths', () => {+ it('list / get / check / profilePicture / phone', async () => {+ const t = new MockTransport()+ .on('GET', /\/contacts$/, { body: [] })+ .on('GET', /\/contacts\/[^/]+$/, { body: { id: '[email protected]' } })+ .on('GET', /\/check\/628123$/, { body: { number: '628123', exists: true, whatsappId: '[email protected]' } })+ .on('GET', /\/profile-picture$/, { body: { url: 'http://p' } })+ .on('GET', /\/phone$/, { body: { contactId: 'x@lid', phone: '628123' } });+ const c = client(t);+ await c.contacts.list('s', { limit: 10 });+ expect(t.lastCall!.url).toContain('limit=10');+ await c.contacts.get('s', '[email protected]');+ await c.contacts.check('s', '628123');+ expect(t.lastCall!.url).toContain('/check/628123');+ await c.contacts.profilePicture('s', '[email protected]');+ await c.contacts.phone('s', 'x@lid');+ });++ it('block (POST) / unblock (DELETE)', async () => {+ const t = new MockTransport()+ .on('POST', /\/block$/, { body: { success: true } })+ .on('DELETE', /\/block$/, { body: { success: true } });+ const c = client(t);+ await c.contacts.block('s', '[email protected]');+ expect(t.lastCall!.method).toBe('POST');+ await c.contacts.unblock('s', '[email protected]');+ expect(t.lastCall!.method).toBe('DELETE');+ });+});++describe('WebhooksResource — exact paths', () => {+ it('list/get/create/update/delete/test', async () => {+ const t = new MockTransport()+ .on('GET', /\/webhooks$/, { body: [] })+ .on('GET', /\/webhooks\/w1$/, {+ body: { id: 'w1', sessionId: 's', url: 'u', events: ['*'], active: true, createdAt: '', updatedAt: '' },+ })+ .on('POST', /\/webhooks$/, {+ body: { id: 'w1', sessionId: 's', url: 'u', events: ['*'], active: true, retryCount: 5, lastTriggeredAt: null, createdAt: '', updatedAt: '' },+ })+ .on('PUT', /\/webhooks\/w1$/, {+ body: { id: 'w1', sessionId: 's', url: 'u', events: ['*'], active: false, createdAt: '', updatedAt: '' },+ })+ .on('DELETE', /\/webhooks\/w1$/, { status: 204 })+ .on('POST', /\/webhooks\/w1\/test$/, { body: { success: true } });+ const c = client(t);+ await c.webhooks.list('s');+ await c.webhooks.get('s', 'w1');+ // Server DTO field is `retryCount` (NOT `retries`) — body must forward verbatim.+ const created = await c.webhooks.create('s', { url: 'u', events: ['*'], retryCount: 5 });+ expect(t.lastCall!.body).toEqual({ url: 'u', events: ['*'], retryCount: 5 });+ // Response exposes retryCount and lastTriggeredAt; secret/headers are stripped server-side.+ expect(created.retryCount).toBe(5);+ expect(created.lastTriggeredAt).toBeNull();+ await c.webhooks.update('s', 'w1', { active: false });+ expect(t.lastCall!.method).toBe('PUT');+ await c.webhooks.delete('s', 'w1');+ await c.webhooks.test('s', 'w1');+ expect(t.lastCall!.url).toContain('/webhooks/w1/test');+ });+});++describe('StatusResource — nested media bodies', () => {+ it('sendImage/sendVideo forward the server-required nested {image|video:{...}} shape', async () => {+ const t = new MockTransport()+ .on('POST', /\/status\/send-image$/, { body: { statusId: 's1' } })+ .on('POST', /\/status\/send-video$/, { body: { statusId: 's2' } });+ const c = client(t);+ await c.status.sendImage('s', { image: { url: 'http://img' }, caption: 'hi' });+ expect(t.lastCall!.body).toEqual({ image: { url: 'http://img' }, caption: 'hi' });+ await c.status.sendVideo('s', { video: { url: 'http://vid' } });+ expect(t.lastCall!.body).toEqual({ video: { url: 'http://vid' } });+ });+});++describe('ChatsResource — exact paths', () => {+ it('list / markRead / markUnread / delete / sendState', async () => {+ const t = new MockTransport()+ .on('GET', /\/chats$/, { body: [] })+ .on('POST', /\/chats\/read$/, { body: { success: true } })+ .on('POST', /\/chats\/unread$/, { body: { success: true } })+ .on('POST', /\/chats\/delete$/, { body: { success: true } })+ .on('POST', /\/chats\/typing$/, { body: { success: true } });+ const c = client(t);+ await c.chats.list('s');+ await c.chats.markRead('s', { chatId: '[email protected]' });+ expect(t.lastCall!.url).toContain('/chats/read');+ await c.chats.markUnread('s', { chatId: '[email protected]' });+ await c.chats.delete('s', { chatId: '[email protected]' });+ await c.chats.sendState('s', { chatId: '[email protected]', state: 'typing' });+ expect(t.lastCall!.url).toContain('/chats/typing');+ });+});++describe('HealthResource + auth — exact paths', () => {+ it('health/live/ready and auth validate', async () => {+ const t = new MockTransport()+ .on('GET', /\/health$/, { body: { status: 'ok', version: '0.7.2' } })+ .on('GET', /\/health\/live$/, { body: { status: 'ok' } })+ .on('GET', /\/health\/ready$/, { body: { status: 'ok', details: {} } })+ .on('POST', /\/auth\/validate$/, { body: { valid: true, role: 'admin' } });+ const c = client(t);+ await c.health.check();+ expect(t.lastCall!.url).toBe('http://x/api/health');+ await c.health.live();+ await c.health.ready();+ await c.auth();+ expect(t.lastCall!.method).toBe('POST');+ expect(t.lastCall!.url).toBe('http://x/api/auth/validate');+ });+});diff --git a/sdk/javascript/test/sessions.test.ts b/sdk/javascript/test/sessions.test.tsnew file mode 100644index 000000000..0f042053c--- /dev/null+++ b/sdk/javascript/test/sessions.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';+import { OpenWAClient } from '../src';+import { MockTransport } from './helpers';++function client(t: MockTransport): OpenWAClient {+ return new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: t.asFetch() });+}++describe('SessionsResource — exact paths', () => {+ it('list/get/create/delete/start/stop/forceKill', async () => {+ const t = new MockTransport()+ .on('GET', /\/sessions$/, { body: [] })+ .on('GET', /\/sessions\/s1$/, { body: { id: 's1', name: 'n', status: 'ready' } })+ .on('POST', /\/sessions$/, { body: { id: 's1', name: 'n', status: 'created' } })+ .on('DELETE', /\/sessions\/s1$/, { status: 204 })+ .on('POST', /\/sessions\/s1\/start$/, { body: { id: 's1', name: 'n', status: 'initializing' } })+ .on('POST', /\/sessions\/s1\/stop$/, { body: { id: 's1', name: 'n', status: 'disconnected' } })+ .on('POST', /\/sessions\/s1\/force-kill$/, { body: { id: 's1', name: 'n', status: 'disconnected' } });+ const c = client(t);+ await c.sessions.list();+ expect(t.lastCall!.url).toBe('http://x/api/sessions');+ await c.sessions.get('s1');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s1');+ await c.sessions.create({ name: 'n' });+ expect(t.lastCall!.body).toEqual({ name: 'n' });+ await c.sessions.start('s1');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s1/start');+ await c.sessions.stop('s1');+ await c.sessions.forceKill('s1');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s1/force-kill');+ await c.sessions.delete('s1');+ expect(t.lastCall!.method).toBe('DELETE');+ });++ it('getQrCode / requestPairingCode / stats', async () => {+ const t = new MockTransport()+ .on('GET', /\/qr$/, { body: { qrCode: 'data:image/png;base64,xxx', status: 'qr_ready' } })+ .on('POST', /\/pairing-code$/, { body: { pairingCode: 'ABCD1234', status: 'qr_ready' } })+ .on('GET', /\/stats\/overview$/, {+ body: { total: 1, active: 1, ready: 1, disconnected: 0, byStatus: { ready: 1 } },+ });+ const c = client(t);+ await c.sessions.getQrCode('s1');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s1/qr');+ await c.sessions.requestPairingCode('s1', { phoneNumber: '628123456789' });+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s1/pairing-code');+ expect(t.lastCall!.body).toEqual({ phoneNumber: '628123456789' });+ await c.sessions.stats();+ expect(t.lastCall!.url).toBe('http://x/api/sessions/stats/overview');+ });+});diff --git a/sdk/javascript/tsconfig.cjs.json b/sdk/javascript/tsconfig.cjs.jsonnew file mode 100644index 000000000..cbd709199--- /dev/null+++ b/sdk/javascript/tsconfig.cjs.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "CommonJS",+ "moduleResolution": "Node",+ "lib": ["ES2022", "DOM"],+ "declaration": true,+ "strict": true,+ "esModuleInterop": true,+ "isolatedModules": true,+ "outDir": "./dist/cjs",+ "rootDir": "./src",+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules", "dist", "test"]+}diff --git a/sdk/javascript/tsconfig.esm.json b/sdk/javascript/tsconfig.esm.jsonnew file mode 100644index 000000000..301e508da--- /dev/null+++ b/sdk/javascript/tsconfig.esm.json@@ -0,0 +1,21 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022", "DOM"],+ "declaration": true,+ "declarationMap": true,+ "strict": true,+ "esModuleInterop": true,+ "verbatimModuleSyntax": false,+ "isolatedModules": true,+ "outDir": "./dist/esm",+ "rootDir": "./src",+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules", "dist", "test"]+}diff --git a/sdk/javascript/tsconfig.json b/sdk/javascript/tsconfig.jsonindex fd1c1e812..c5a900071 100644--- a/sdk/javascript/tsconfig.json+++ b/sdk/javascript/tsconfig.json@@ -1,17 +1,20 @@{"compilerOptions": {"target": "ES2022",- "module": "commonjs",- "lib": ["ES2022"],+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "lib": ["ES2022", "DOM"],"declaration": true,+ "declarationMap": true,"strict": true,"esModuleInterop": true,- "outDir": "./dist",- "rootDir": "./src",+ "isolatedModules": true,+ "noEmit": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["vitest/globals"]},- "include": ["src/**/*"],+ "include": ["src/**/*.ts", "test/**/*.ts"],"exclude": ["node_modules", "dist"]}diff --git a/sdk/javascript/vitest.config.ts b/sdk/javascript/vitest.config.tsnew file mode 100644index 000000000..3353345c4--- /dev/null+++ b/sdk/javascript/vitest.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ include: ['test/**/*.test.ts'],+ globals: false,+ },+});diff --git a/sdk/php/.gitignore b/sdk/php/.gitignorenew file mode 100644index 000000000..da24412f1--- /dev/null+++ b/sdk/php/.gitignore@@ -0,0 +1,4 @@+/vendor/+/composer.phar+/.phpunit.cache/+.phpunit.result.cachediff --git a/sdk/php/composer.json b/sdk/php/composer.jsonnew file mode 100644index 000000000..64e7ab16a--- /dev/null+++ b/sdk/php/composer.json@@ -0,0 +1,43 @@+{+ "name": "openwa/sdk",+ "description": "Official PHP SDK for OpenWA WhatsApp API Gateway",+ "type": "library",+ "license": "MIT",+ "keywords": [+ "whatsapp",+ "api",+ "sdk",+ "openwa",+ "gateway"+ ],+ "authors": [+ {+ "name": "OpenWA Contributors"+ }+ ],+ "require": {+ "php": ">=8.1",+ "guzzlehttp/guzzle": "^7.9"+ },+ "require-dev": {+ "phpunit/phpunit": "^10.0 || ^11.0"+ },+ "autoload": {+ "psr-4": {+ "OpenWA\\": "src/"+ }+ },+ "autoload-dev": {+ "psr-4": {+ "OpenWA\\Tests\\": "tests/"+ }+ },+ "config": {+ "sort-packages": true+ },+ "extra": {+ "branch-alias": {+ "dev-main": "0.1.x-dev"+ }+ }+}\ No newline at end of filediff --git a/sdk/php/composer.lock b/sdk/php/composer.locknew file mode 100644index 000000000..eea65f35a--- /dev/null+++ b/sdk/php/composer.lock@@ -0,0 +1,2493 @@+{+ "_readme": [+ "This file locks the dependencies of your project to a known state",+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",+ "This file is @generated automatically"+ ],+ "content-hash": "98c18578ce6bc58c383aa8f25462b8d2",+ "packages": [+ {+ "name": "guzzlehttp/guzzle",+ "version": "7.12.3",+ "source": {+ "type": "git",+ "url": "https://github.com/guzzle/guzzle.git",+ "reference": "9aa17bcdd777ee31df9fc83c337ca4ca2340def3"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/guzzle/guzzle/zipball/9aa17bcdd777ee31df9fc83c337ca4ca2340def3",+ "reference": "9aa17bcdd777ee31df9fc83c337ca4ca2340def3",+ "shasum": ""+ },+ "require": {+ "ext-json": "*",+ "guzzlehttp/promises": "^2.5",+ "guzzlehttp/psr7": "^2.12.3",+ "php": "^7.2.5 || ^8.0",+ "psr/http-client": "^1.0",+ "symfony/deprecation-contracts": "^2.5 || ^3.0",+ "symfony/polyfill-php80": "^1.25"+ },+ "provide": {+ "psr/http-client-implementation": "1.0"+ },+ "require-dev": {+ "bamarni/composer-bin-plugin": "^1.8.2",+ "ext-curl": "*",+ "guzzle/client-integration-tests": "3.0.2",+ "guzzlehttp/test-server": "^0.5.1",+ "php-http/message-factory": "^1.1",+ "phpunit/phpunit": "^8.5.52 || ^9.6.34",+ "psr/log": "^1.1 || ^2.0 || ^3.0"+ },+ "suggest": {+ "ext-curl": "Required for CURL handler support",+ "ext-intl": "Required for Internationalized Domain Name (IDN) support",+ "psr/log": "Required for using the Log middleware"+ },+ "type": "library",+ "extra": {+ "bamarni-bin": {+ "bin-links": true,+ "forward-command": false+ }+ },+ "autoload": {+ "files": [+ "src/functions_include.php"+ ],+ "psr-4": {+ "GuzzleHttp\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Graham Campbell",+ "email": "[email protected]",+ "homepage": "https://github.com/GrahamCampbell"+ },+ {+ "name": "Michael Dowling",+ "email": "[email protected]",+ "homepage": "https://github.com/mtdowling"+ },+ {+ "name": "Jeremy Lindblom",+ "email": "[email protected]",+ "homepage": "https://github.com/jeremeamia"+ },+ {+ "name": "George Mponos",+ "email": "[email protected]",+ "homepage": "https://github.com/gmponos"+ },+ {+ "name": "Tobias Nyholm",+ "email": "[email protected]",+ "homepage": "https://github.com/Nyholm"+ },+ {+ "name": "Márk Sági-Kazár",+ "email": "[email protected]",+ "homepage": "https://github.com/sagikazarmark"+ },+ {+ "name": "Tobias Schultze",+ "email": "[email protected]",+ "homepage": "https://github.com/Tobion"+ }+ ],+ "description": "Guzzle is a PHP HTTP client library",+ "keywords": [+ "client",+ "curl",+ "framework",+ "http",+ "http client",+ "psr-18",+ "psr-7",+ "rest",+ "web service"+ ],+ "support": {+ "issues": "https://github.com/guzzle/guzzle/issues",+ "source": "https://github.com/guzzle/guzzle/tree/7.12.3"+ },+ "funding": [+ {+ "url": "https://github.com/GrahamCampbell",+ "type": "github"+ },+ {+ "url": "https://github.com/Nyholm",+ "type": "github"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle",+ "type": "tidelift"+ }+ ],+ "time": "2026-06-23T15:29:02+00:00"+ },+ {+ "name": "guzzlehttp/promises",+ "version": "2.5.0",+ "source": {+ "type": "git",+ "url": "https://github.com/guzzle/promises.git",+ "reference": "4360e982f87f5f258bf872d094647791db2f4c8e"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/guzzle/promises/zipball/4360e982f87f5f258bf872d094647791db2f4c8e",+ "reference": "4360e982f87f5f258bf872d094647791db2f4c8e",+ "shasum": ""+ },+ "require": {+ "php": "^7.2.5 || ^8.0",+ "symfony/deprecation-contracts": "^2.5 || ^3.0"+ },+ "require-dev": {+ "bamarni/composer-bin-plugin": "^1.8.2",+ "phpunit/phpunit": "^8.5.52 || ^9.6.34"+ },+ "type": "library",+ "extra": {+ "bamarni-bin": {+ "bin-links": true,+ "forward-command": false+ }+ },+ "autoload": {+ "psr-4": {+ "GuzzleHttp\\Promise\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Graham Campbell",+ "email": "[email protected]",+ "homepage": "https://github.com/GrahamCampbell"+ },+ {+ "name": "Michael Dowling",+ "email": "[email protected]",+ "homepage": "https://github.com/mtdowling"+ },+ {+ "name": "Tobias Nyholm",+ "email": "[email protected]",+ "homepage": "https://github.com/Nyholm"+ },+ {+ "name": "Tobias Schultze",+ "email": "[email protected]",+ "homepage": "https://github.com/Tobion"+ }+ ],+ "description": "Guzzle promises library",+ "keywords": [+ "promise"+ ],+ "support": {+ "issues": "https://github.com/guzzle/promises/issues",+ "source": "https://github.com/guzzle/promises/tree/2.5.0"+ },+ "funding": [+ {+ "url": "https://github.com/GrahamCampbell",+ "type": "github"+ },+ {+ "url": "https://github.com/Nyholm",+ "type": "github"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises",+ "type": "tidelift"+ }+ ],+ "time": "2026-06-02T12:23:43+00:00"+ },+ {+ "name": "guzzlehttp/psr7",+ "version": "2.12.3",+ "source": {+ "type": "git",+ "url": "https://github.com/guzzle/psr7.git",+ "reference": "7ec62dc3f44aa218487dbed81a9bf9bc647be55d"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/guzzle/psr7/zipball/7ec62dc3f44aa218487dbed81a9bf9bc647be55d",+ "reference": "7ec62dc3f44aa218487dbed81a9bf9bc647be55d",+ "shasum": ""+ },+ "require": {+ "php": "^7.2.5 || ^8.0",+ "psr/http-factory": "^1.0",+ "psr/http-message": "^1.1 || ^2.0",+ "ralouphie/getallheaders": "^3.0",+ "symfony/deprecation-contracts": "^2.5 || ^3.0",+ "symfony/polyfill-php80": "^1.25"+ },+ "provide": {+ "psr/http-factory-implementation": "1.0",+ "psr/http-message-implementation": "1.0"+ },+ "require-dev": {+ "bamarni/composer-bin-plugin": "^1.8.2",+ "http-interop/http-factory-tests": "1.1.0",+ "jshttp/mime-db": "1.54.0.1",+ "phpunit/phpunit": "^8.5.52 || ^9.6.34"+ },+ "suggest": {+ "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"+ },+ "type": "library",+ "extra": {+ "bamarni-bin": {+ "bin-links": true,+ "forward-command": false+ }+ },+ "autoload": {+ "psr-4": {+ "GuzzleHttp\\Psr7\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Graham Campbell",+ "email": "[email protected]",+ "homepage": "https://github.com/GrahamCampbell"+ },+ {+ "name": "Michael Dowling",+ "email": "[email protected]",+ "homepage": "https://github.com/mtdowling"+ },+ {+ "name": "George Mponos",+ "email": "[email protected]",+ "homepage": "https://github.com/gmponos"+ },+ {+ "name": "Tobias Nyholm",+ "email": "[email protected]",+ "homepage": "https://github.com/Nyholm"+ },+ {+ "name": "Márk Sági-Kazár",+ "email": "[email protected]",+ "homepage": "https://github.com/sagikazarmark"+ },+ {+ "name": "Tobias Schultze",+ "email": "[email protected]",+ "homepage": "https://github.com/Tobion"+ },+ {+ "name": "Márk Sági-Kazár",+ "email": "[email protected]",+ "homepage": "https://sagikazarmark.hu"+ }+ ],+ "description": "PSR-7 message implementation that also provides common utility methods",+ "keywords": [+ "http",+ "message",+ "psr-7",+ "request",+ "response",+ "stream",+ "uri",+ "url"+ ],+ "support": {+ "issues": "https://github.com/guzzle/psr7/issues",+ "source": "https://github.com/guzzle/psr7/tree/2.12.3"+ },+ "funding": [+ {+ "url": "https://github.com/GrahamCampbell",+ "type": "github"+ },+ {+ "url": "https://github.com/Nyholm",+ "type": "github"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7",+ "type": "tidelift"+ }+ ],+ "time": "2026-06-23T15:21:08+00:00"+ },+ {+ "name": "psr/http-client",+ "version": "1.0.3",+ "source": {+ "type": "git",+ "url": "https://github.com/php-fig/http-client.git",+ "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90",+ "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90",+ "shasum": ""+ },+ "require": {+ "php": "^7.0 || ^8.0",+ "psr/http-message": "^1.0 || ^2.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "1.0.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "Psr\\Http\\Client\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "PHP-FIG",+ "homepage": "https://www.php-fig.org/"+ }+ ],+ "description": "Common interface for HTTP clients",+ "homepage": "https://github.com/php-fig/http-client",+ "keywords": [+ "http",+ "http-client",+ "psr",+ "psr-18"+ ],+ "support": {+ "source": "https://github.com/php-fig/http-client"+ },+ "time": "2023-09-23T14:17:50+00:00"+ },+ {+ "name": "psr/http-factory",+ "version": "1.1.0",+ "source": {+ "type": "git",+ "url": "https://github.com/php-fig/http-factory.git",+ "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",+ "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",+ "shasum": ""+ },+ "require": {+ "php": ">=7.1",+ "psr/http-message": "^1.0 || ^2.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "1.0.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "Psr\\Http\\Message\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "PHP-FIG",+ "homepage": "https://www.php-fig.org/"+ }+ ],+ "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",+ "keywords": [+ "factory",+ "http",+ "message",+ "psr",+ "psr-17",+ "psr-7",+ "request",+ "response"+ ],+ "support": {+ "source": "https://github.com/php-fig/http-factory"+ },+ "time": "2024-04-15T12:06:14+00:00"+ },+ {+ "name": "psr/http-message",+ "version": "2.0",+ "source": {+ "type": "git",+ "url": "https://github.com/php-fig/http-message.git",+ "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",+ "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71",+ "shasum": ""+ },+ "require": {+ "php": "^7.2 || ^8.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "2.0.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "Psr\\Http\\Message\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "PHP-FIG",+ "homepage": "https://www.php-fig.org/"+ }+ ],+ "description": "Common interface for HTTP messages",+ "homepage": "https://github.com/php-fig/http-message",+ "keywords": [+ "http",+ "http-message",+ "psr",+ "psr-7",+ "request",+ "response"+ ],+ "support": {+ "source": "https://github.com/php-fig/http-message/tree/2.0"+ },+ "time": "2023-04-04T09:54:51+00:00"+ },+ {+ "name": "ralouphie/getallheaders",+ "version": "3.0.3",+ "source": {+ "type": "git",+ "url": "https://github.com/ralouphie/getallheaders.git",+ "reference": "120b605dfeb996808c31b6477290a714d356e822"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822",+ "reference": "120b605dfeb996808c31b6477290a714d356e822",+ "shasum": ""+ },+ "require": {+ "php": ">=5.6"+ },+ "require-dev": {+ "php-coveralls/php-coveralls": "^2.1",+ "phpunit/phpunit": "^5 || ^6.5"+ },+ "type": "library",+ "autoload": {+ "files": [+ "src/getallheaders.php"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Ralph Khattar",+ "email": "[email protected]"+ }+ ],+ "description": "A polyfill for getallheaders.",+ "support": {+ "issues": "https://github.com/ralouphie/getallheaders/issues",+ "source": "https://github.com/ralouphie/getallheaders/tree/develop"+ },+ "time": "2019-03-08T08:55:37+00:00"+ },+ {+ "name": "symfony/deprecation-contracts",+ "version": "v3.7.0",+ "source": {+ "type": "git",+ "url": "https://github.com/symfony/deprecation-contracts.git",+ "reference": "50f59d1f3ca46d41ac911f97a78626b6756af35b"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/50f59d1f3ca46d41ac911f97a78626b6756af35b",+ "reference": "50f59d1f3ca46d41ac911f97a78626b6756af35b",+ "shasum": ""+ },+ "require": {+ "php": ">=8.1"+ },+ "type": "library",+ "extra": {+ "thanks": {+ "url": "https://github.com/symfony/contracts",+ "name": "symfony/contracts"+ },+ "branch-alias": {+ "dev-main": "3.7-dev"+ }+ },+ "autoload": {+ "files": [+ "function.php"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Nicolas Grekas",+ "email": "[email protected]"+ },+ {+ "name": "Symfony Community",+ "homepage": "https://symfony.com/contributors"+ }+ ],+ "description": "A generic function and convention to trigger deprecation notices",+ "homepage": "https://symfony.com",+ "support": {+ "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.0"+ },+ "funding": [+ {+ "url": "https://symfony.com/sponsor",+ "type": "custom"+ },+ {+ "url": "https://github.com/fabpot",+ "type": "github"+ },+ {+ "url": "https://github.com/nicolas-grekas",+ "type": "github"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",+ "type": "tidelift"+ }+ ],+ "time": "2026-04-13T15:52:40+00:00"+ },+ {+ "name": "symfony/polyfill-php80",+ "version": "v1.37.0",+ "source": {+ "type": "git",+ "url": "https://github.com/symfony/polyfill-php80.git",+ "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411",+ "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411",+ "shasum": ""+ },+ "require": {+ "php": ">=7.2"+ },+ "type": "library",+ "extra": {+ "thanks": {+ "url": "https://github.com/symfony/polyfill",+ "name": "symfony/polyfill"+ }+ },+ "autoload": {+ "files": [+ "bootstrap.php"+ ],+ "psr-4": {+ "Symfony\\Polyfill\\Php80\\": ""+ },+ "classmap": [+ "Resources/stubs"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Ion Bazan",+ "email": "[email protected]"+ },+ {+ "name": "Nicolas Grekas",+ "email": "[email protected]"+ },+ {+ "name": "Symfony Community",+ "homepage": "https://symfony.com/contributors"+ }+ ],+ "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions",+ "homepage": "https://symfony.com",+ "keywords": [+ "compatibility",+ "polyfill",+ "portable",+ "shim"+ ],+ "support": {+ "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0"+ },+ "funding": [+ {+ "url": "https://symfony.com/sponsor",+ "type": "custom"+ },+ {+ "url": "https://github.com/fabpot",+ "type": "github"+ },+ {+ "url": "https://github.com/nicolas-grekas",+ "type": "github"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",+ "type": "tidelift"+ }+ ],+ "time": "2026-04-10T16:19:22+00:00"+ }+ ],+ "packages-dev": [+ {+ "name": "myclabs/deep-copy",+ "version": "1.13.4",+ "source": {+ "type": "git",+ "url": "https://github.com/myclabs/DeepCopy.git",+ "reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/07d290f0c47959fd5eed98c95ee5602db07e0b6a",+ "reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a",+ "shasum": ""+ },+ "require": {+ "php": "^7.1 || ^8.0"+ },+ "conflict": {+ "doctrine/collections": "<1.6.8",+ "doctrine/common": "<2.13.3 || >=3 <3.2.2"+ },+ "require-dev": {+ "doctrine/collections": "^1.6.8",+ "doctrine/common": "^2.13.3 || ^3.2.2",+ "phpspec/prophecy": "^1.10",+ "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"+ },+ "type": "library",+ "autoload": {+ "files": [+ "src/DeepCopy/deep_copy.php"+ ],+ "psr-4": {+ "DeepCopy\\": "src/DeepCopy/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "description": "Create deep copies (clones) of your objects",+ "keywords": [+ "clone",+ "copy",+ "duplicate",+ "object",+ "object graph"+ ],+ "support": {+ "issues": "https://github.com/myclabs/DeepCopy/issues",+ "source": "https://github.com/myclabs/DeepCopy/tree/1.13.4"+ },+ "funding": [+ {+ "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy",+ "type": "tidelift"+ }+ ],+ "time": "2025-08-01T08:46:24+00:00"+ },+ {+ "name": "nikic/php-parser",+ "version": "v5.7.0",+ "source": {+ "type": "git",+ "url": "https://github.com/nikic/PHP-Parser.git",+ "reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/dca41cd15c2ac9d055ad70dbfd011130757d1f82",+ "reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82",+ "shasum": ""+ },+ "require": {+ "ext-ctype": "*",+ "ext-json": "*",+ "ext-tokenizer": "*",+ "php": ">=7.4"+ },+ "require-dev": {+ "ircmaxell/php-yacc": "^0.0.7",+ "phpunit/phpunit": "^9.0"+ },+ "bin": [+ "bin/php-parse"+ ],+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "5.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "PhpParser\\": "lib/PhpParser"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Nikita Popov"+ }+ ],+ "description": "A PHP parser written in PHP",+ "keywords": [+ "parser",+ "php"+ ],+ "support": {+ "issues": "https://github.com/nikic/PHP-Parser/issues",+ "source": "https://github.com/nikic/PHP-Parser/tree/v5.7.0"+ },+ "time": "2025-12-06T11:56:16+00:00"+ },+ {+ "name": "phar-io/manifest",+ "version": "2.0.4",+ "source": {+ "type": "git",+ "url": "https://github.com/phar-io/manifest.git",+ "reference": "54750ef60c58e43759730615a392c31c80e23176"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/phar-io/manifest/zipball/54750ef60c58e43759730615a392c31c80e23176",+ "reference": "54750ef60c58e43759730615a392c31c80e23176",+ "shasum": ""+ },+ "require": {+ "ext-dom": "*",+ "ext-libxml": "*",+ "ext-phar": "*",+ "ext-xmlwriter": "*",+ "phar-io/version": "^3.0.1",+ "php": "^7.2 || ^8.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "2.0.x-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Arne Blankerts",+ "email": "[email protected]",+ "role": "Developer"+ },+ {+ "name": "Sebastian Heuer",+ "email": "[email protected]",+ "role": "Developer"+ },+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "Developer"+ }+ ],+ "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)",+ "support": {+ "issues": "https://github.com/phar-io/manifest/issues",+ "source": "https://github.com/phar-io/manifest/tree/2.0.4"+ },+ "funding": [+ {+ "url": "https://github.com/theseer",+ "type": "github"+ }+ ],+ "time": "2024-03-03T12:33:53+00:00"+ },+ {+ "name": "phar-io/version",+ "version": "3.2.1",+ "source": {+ "type": "git",+ "url": "https://github.com/phar-io/version.git",+ "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74",+ "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74",+ "shasum": ""+ },+ "require": {+ "php": "^7.2 || ^8.0"+ },+ "type": "library",+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Arne Blankerts",+ "email": "[email protected]",+ "role": "Developer"+ },+ {+ "name": "Sebastian Heuer",+ "email": "[email protected]",+ "role": "Developer"+ },+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "Developer"+ }+ ],+ "description": "Library for handling version information and constraints",+ "support": {+ "issues": "https://github.com/phar-io/version/issues",+ "source": "https://github.com/phar-io/version/tree/3.2.1"+ },+ "time": "2022-02-21T01:04:05+00:00"+ },+ {+ "name": "phpunit/php-code-coverage",+ "version": "11.0.12",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/php-code-coverage.git",+ "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2c1ed04922802c15e1de5d7447b4856de949cf56",+ "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56",+ "shasum": ""+ },+ "require": {+ "ext-dom": "*",+ "ext-libxml": "*",+ "ext-xmlwriter": "*",+ "nikic/php-parser": "^5.7.0",+ "php": ">=8.2",+ "phpunit/php-file-iterator": "^5.1.0",+ "phpunit/php-text-template": "^4.0.1",+ "sebastian/code-unit-reverse-lookup": "^4.0.1",+ "sebastian/complexity": "^4.0.1",+ "sebastian/environment": "^7.2.1",+ "sebastian/lines-of-code": "^3.0.1",+ "sebastian/version": "^5.0.2",+ "theseer/tokenizer": "^1.3.1"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.5.46"+ },+ "suggest": {+ "ext-pcov": "PHP extension that provides line coverage",+ "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "11.0.x-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.",+ "homepage": "https://github.com/sebastianbergmann/php-code-coverage",+ "keywords": [+ "coverage",+ "testing",+ "xunit"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",+ "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/11.0.12"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/phpunit/php-code-coverage",+ "type": "tidelift"+ }+ ],+ "time": "2025-12-24T07:01:01+00:00"+ },+ {+ "name": "phpunit/php-file-iterator",+ "version": "5.1.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/php-file-iterator.git",+ "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/2f3a64888c814fc235386b7387dd5b5ed92ad903",+ "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.3"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "5.1-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "FilterIterator implementation that filters files based on a list of suffixes.",+ "homepage": "https://github.com/sebastianbergmann/php-file-iterator/",+ "keywords": [+ "filesystem",+ "iterator"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues",+ "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy",+ "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/5.1.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/phpunit/php-file-iterator",+ "type": "tidelift"+ }+ ],+ "time": "2026-02-02T13:52:54+00:00"+ },+ {+ "name": "phpunit/php-invoker",+ "version": "5.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/php-invoker.git",+ "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/c1ca3814734c07492b3d4c5f794f4b0995333da2",+ "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "ext-pcntl": "*",+ "phpunit/phpunit": "^11.0"+ },+ "suggest": {+ "ext-pcntl": "*"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "5.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Invoke callables with a timeout",+ "homepage": "https://github.com/sebastianbergmann/php-invoker/",+ "keywords": [+ "process"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/php-invoker/issues",+ "security": "https://github.com/sebastianbergmann/php-invoker/security/policy",+ "source": "https://github.com/sebastianbergmann/php-invoker/tree/5.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T05:07:44+00:00"+ },+ {+ "name": "phpunit/php-text-template",+ "version": "4.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/php-text-template.git",+ "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/3e0404dc6b300e6bf56415467ebcb3fe4f33e964",+ "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "4.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Simple template engine.",+ "homepage": "https://github.com/sebastianbergmann/php-text-template/",+ "keywords": [+ "template"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/php-text-template/issues",+ "security": "https://github.com/sebastianbergmann/php-text-template/security/policy",+ "source": "https://github.com/sebastianbergmann/php-text-template/tree/4.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T05:08:43+00:00"+ },+ {+ "name": "phpunit/php-timer",+ "version": "7.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/php-timer.git",+ "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3b415def83fbcb41f991d9ebf16ae4ad8b7837b3",+ "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "7.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Utility class for timing",+ "homepage": "https://github.com/sebastianbergmann/php-timer/",+ "keywords": [+ "timer"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/php-timer/issues",+ "security": "https://github.com/sebastianbergmann/php-timer/security/policy",+ "source": "https://github.com/sebastianbergmann/php-timer/tree/7.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T05:09:35+00:00"+ },+ {+ "name": "phpunit/phpunit",+ "version": "11.5.55",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/phpunit.git",+ "reference": "adc7262fccc12de2b30f12a8aa0b33775d814f00"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/adc7262fccc12de2b30f12a8aa0b33775d814f00",+ "reference": "adc7262fccc12de2b30f12a8aa0b33775d814f00",+ "shasum": ""+ },+ "require": {+ "ext-dom": "*",+ "ext-json": "*",+ "ext-libxml": "*",+ "ext-mbstring": "*",+ "ext-xml": "*",+ "ext-xmlwriter": "*",+ "myclabs/deep-copy": "^1.13.4",+ "phar-io/manifest": "^2.0.4",+ "phar-io/version": "^3.2.1",+ "php": ">=8.2",+ "phpunit/php-code-coverage": "^11.0.12",+ "phpunit/php-file-iterator": "^5.1.1",+ "phpunit/php-invoker": "^5.0.1",+ "phpunit/php-text-template": "^4.0.1",+ "phpunit/php-timer": "^7.0.1",+ "sebastian/cli-parser": "^3.0.2",+ "sebastian/code-unit": "^3.0.3",+ "sebastian/comparator": "^6.3.3",+ "sebastian/diff": "^6.0.2",+ "sebastian/environment": "^7.2.1",+ "sebastian/exporter": "^6.3.2",+ "sebastian/global-state": "^7.0.2",+ "sebastian/object-enumerator": "^6.0.1",+ "sebastian/recursion-context": "^6.0.3",+ "sebastian/type": "^5.1.3",+ "sebastian/version": "^5.0.2",+ "staabm/side-effects-detector": "^1.0.5"+ },+ "suggest": {+ "ext-soap": "To be able to generate mocks based on WSDL files"+ },+ "bin": [+ "phpunit"+ ],+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "11.5-dev"+ }+ },+ "autoload": {+ "files": [+ "src/Framework/Assert/Functions.php"+ ],+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "The PHP Unit Testing framework.",+ "homepage": "https://phpunit.de/",+ "keywords": [+ "phpunit",+ "testing",+ "xunit"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/phpunit/issues",+ "security": "https://github.com/sebastianbergmann/phpunit/security/policy",+ "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.55"+ },+ "funding": [+ {+ "url": "https://phpunit.de/sponsors.html",+ "type": "custom"+ },+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit",+ "type": "tidelift"+ }+ ],+ "time": "2026-02-18T12:37:06+00:00"+ },+ {+ "name": "sebastian/cli-parser",+ "version": "3.0.2",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/cli-parser.git",+ "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/15c5dd40dc4f38794d383bb95465193f5e0ae180",+ "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "3.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Library for parsing CLI options",+ "homepage": "https://github.com/sebastianbergmann/cli-parser",+ "support": {+ "issues": "https://github.com/sebastianbergmann/cli-parser/issues",+ "security": "https://github.com/sebastianbergmann/cli-parser/security/policy",+ "source": "https://github.com/sebastianbergmann/cli-parser/tree/3.0.2"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T04:41:36+00:00"+ },+ {+ "name": "sebastian/code-unit",+ "version": "3.0.3",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/code-unit.git",+ "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/54391c61e4af8078e5b276ab082b6d3c54c9ad64",+ "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.5"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "3.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Collection of value objects that represent the PHP code units",+ "homepage": "https://github.com/sebastianbergmann/code-unit",+ "support": {+ "issues": "https://github.com/sebastianbergmann/code-unit/issues",+ "security": "https://github.com/sebastianbergmann/code-unit/security/policy",+ "source": "https://github.com/sebastianbergmann/code-unit/tree/3.0.3"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2025-03-19T07:56:08+00:00"+ },+ {+ "name": "sebastian/code-unit-reverse-lookup",+ "version": "4.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git",+ "reference": "183a9b2632194febd219bb9246eee421dad8d45e"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/183a9b2632194febd219bb9246eee421dad8d45e",+ "reference": "183a9b2632194febd219bb9246eee421dad8d45e",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "4.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ }+ ],+ "description": "Looks up which function or method a line of code belongs to",+ "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",+ "support": {+ "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues",+ "security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy",+ "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/4.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T04:45:54+00:00"+ },+ {+ "name": "sebastian/comparator",+ "version": "6.3.3",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/comparator.git",+ "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/2c95e1e86cb8dd41beb8d502057d1081ccc8eca9",+ "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9",+ "shasum": ""+ },+ "require": {+ "ext-dom": "*",+ "ext-mbstring": "*",+ "php": ">=8.2",+ "sebastian/diff": "^6.0",+ "sebastian/exporter": "^6.0"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.4"+ },+ "suggest": {+ "ext-bcmath": "For comparing BcMath\\Number objects"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "6.3-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ },+ {+ "name": "Jeff Welch",+ "email": "[email protected]"+ },+ {+ "name": "Volker Dusch",+ "email": "[email protected]"+ },+ {+ "name": "Bernhard Schussek",+ "email": "[email protected]"+ }+ ],+ "description": "Provides the functionality to compare PHP values for equality",+ "homepage": "https://github.com/sebastianbergmann/comparator",+ "keywords": [+ "comparator",+ "compare",+ "equality"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/comparator/issues",+ "security": "https://github.com/sebastianbergmann/comparator/security/policy",+ "source": "https://github.com/sebastianbergmann/comparator/tree/6.3.3"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/sebastian/comparator",+ "type": "tidelift"+ }+ ],+ "time": "2026-01-24T09:26:40+00:00"+ },+ {+ "name": "sebastian/complexity",+ "version": "4.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/complexity.git",+ "reference": "ee41d384ab1906c68852636b6de493846e13e5a0"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/ee41d384ab1906c68852636b6de493846e13e5a0",+ "reference": "ee41d384ab1906c68852636b6de493846e13e5a0",+ "shasum": ""+ },+ "require": {+ "nikic/php-parser": "^5.0",+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "4.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Library for calculating the complexity of PHP code units",+ "homepage": "https://github.com/sebastianbergmann/complexity",+ "support": {+ "issues": "https://github.com/sebastianbergmann/complexity/issues",+ "security": "https://github.com/sebastianbergmann/complexity/security/policy",+ "source": "https://github.com/sebastianbergmann/complexity/tree/4.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T04:49:50+00:00"+ },+ {+ "name": "sebastian/diff",+ "version": "6.0.2",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/diff.git",+ "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/b4ccd857127db5d41a5b676f24b51371d76d8544",+ "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0",+ "symfony/process": "^4.2 || ^5"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "6.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ },+ {+ "name": "Kore Nordmann",+ "email": "[email protected]"+ }+ ],+ "description": "Diff implementation",+ "homepage": "https://github.com/sebastianbergmann/diff",+ "keywords": [+ "diff",+ "udiff",+ "unidiff",+ "unified diff"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/diff/issues",+ "security": "https://github.com/sebastianbergmann/diff/security/policy",+ "source": "https://github.com/sebastianbergmann/diff/tree/6.0.2"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T04:53:05+00:00"+ },+ {+ "name": "sebastian/environment",+ "version": "7.2.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/environment.git",+ "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/a5c75038693ad2e8d4b6c15ba2403532647830c4",+ "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.3"+ },+ "suggest": {+ "ext-posix": "*"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "7.2-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ }+ ],+ "description": "Provides functionality to handle HHVM/PHP environments",+ "homepage": "https://github.com/sebastianbergmann/environment",+ "keywords": [+ "Xdebug",+ "environment",+ "hhvm"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/environment/issues",+ "security": "https://github.com/sebastianbergmann/environment/security/policy",+ "source": "https://github.com/sebastianbergmann/environment/tree/7.2.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/sebastian/environment",+ "type": "tidelift"+ }+ ],+ "time": "2025-05-21T11:55:47+00:00"+ },+ {+ "name": "sebastian/exporter",+ "version": "6.3.2",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/exporter.git",+ "reference": "70a298763b40b213ec087c51c739efcaa90bcd74"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/70a298763b40b213ec087c51c739efcaa90bcd74",+ "reference": "70a298763b40b213ec087c51c739efcaa90bcd74",+ "shasum": ""+ },+ "require": {+ "ext-mbstring": "*",+ "php": ">=8.2",+ "sebastian/recursion-context": "^6.0"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.3"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "6.3-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ },+ {+ "name": "Jeff Welch",+ "email": "[email protected]"+ },+ {+ "name": "Volker Dusch",+ "email": "[email protected]"+ },+ {+ "name": "Adam Harvey",+ "email": "[email protected]"+ },+ {+ "name": "Bernhard Schussek",+ "email": "[email protected]"+ }+ ],+ "description": "Provides the functionality to export PHP variables for visualization",+ "homepage": "https://www.github.com/sebastianbergmann/exporter",+ "keywords": [+ "export",+ "exporter"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/exporter/issues",+ "security": "https://github.com/sebastianbergmann/exporter/security/policy",+ "source": "https://github.com/sebastianbergmann/exporter/tree/6.3.2"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/sebastian/exporter",+ "type": "tidelift"+ }+ ],+ "time": "2025-09-24T06:12:51+00:00"+ },+ {+ "name": "sebastian/global-state",+ "version": "7.0.2",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/global-state.git",+ "reference": "3be331570a721f9a4b5917f4209773de17f747d7"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/3be331570a721f9a4b5917f4209773de17f747d7",+ "reference": "3be331570a721f9a4b5917f4209773de17f747d7",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2",+ "sebastian/object-reflector": "^4.0",+ "sebastian/recursion-context": "^6.0"+ },+ "require-dev": {+ "ext-dom": "*",+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "7.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ }+ ],+ "description": "Snapshotting of global state",+ "homepage": "https://www.github.com/sebastianbergmann/global-state",+ "keywords": [+ "global state"+ ],+ "support": {+ "issues": "https://github.com/sebastianbergmann/global-state/issues",+ "security": "https://github.com/sebastianbergmann/global-state/security/policy",+ "source": "https://github.com/sebastianbergmann/global-state/tree/7.0.2"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T04:57:36+00:00"+ },+ {+ "name": "sebastian/lines-of-code",+ "version": "3.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/lines-of-code.git",+ "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d36ad0d782e5756913e42ad87cb2890f4ffe467a",+ "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a",+ "shasum": ""+ },+ "require": {+ "nikic/php-parser": "^5.0",+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "3.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Library for counting the lines of code in PHP source code",+ "homepage": "https://github.com/sebastianbergmann/lines-of-code",+ "support": {+ "issues": "https://github.com/sebastianbergmann/lines-of-code/issues",+ "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy",+ "source": "https://github.com/sebastianbergmann/lines-of-code/tree/3.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T04:58:38+00:00"+ },+ {+ "name": "sebastian/object-enumerator",+ "version": "6.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/object-enumerator.git",+ "reference": "f5b498e631a74204185071eb41f33f38d64608aa"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/f5b498e631a74204185071eb41f33f38d64608aa",+ "reference": "f5b498e631a74204185071eb41f33f38d64608aa",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2",+ "sebastian/object-reflector": "^4.0",+ "sebastian/recursion-context": "^6.0"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "6.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ }+ ],+ "description": "Traverses array structures and object graphs to enumerate all referenced objects",+ "homepage": "https://github.com/sebastianbergmann/object-enumerator/",+ "support": {+ "issues": "https://github.com/sebastianbergmann/object-enumerator/issues",+ "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy",+ "source": "https://github.com/sebastianbergmann/object-enumerator/tree/6.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T05:00:13+00:00"+ },+ {+ "name": "sebastian/object-reflector",+ "version": "4.0.1",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/object-reflector.git",+ "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/6e1a43b411b2ad34146dee7524cb13a068bb35f9",+ "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.0"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "4.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ }+ ],+ "description": "Allows reflection of object attributes, including inherited and non-public ones",+ "homepage": "https://github.com/sebastianbergmann/object-reflector/",+ "support": {+ "issues": "https://github.com/sebastianbergmann/object-reflector/issues",+ "security": "https://github.com/sebastianbergmann/object-reflector/security/policy",+ "source": "https://github.com/sebastianbergmann/object-reflector/tree/4.0.1"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-07-03T05:01:32+00:00"+ },+ {+ "name": "sebastian/recursion-context",+ "version": "6.0.3",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/recursion-context.git",+ "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/f6458abbf32a6c8174f8f26261475dc133b3d9dc",+ "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.3"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "6.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]"+ },+ {+ "name": "Jeff Welch",+ "email": "[email protected]"+ },+ {+ "name": "Adam Harvey",+ "email": "[email protected]"+ }+ ],+ "description": "Provides functionality to recursively process PHP variables",+ "homepage": "https://github.com/sebastianbergmann/recursion-context",+ "support": {+ "issues": "https://github.com/sebastianbergmann/recursion-context/issues",+ "security": "https://github.com/sebastianbergmann/recursion-context/security/policy",+ "source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.3"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/sebastian/recursion-context",+ "type": "tidelift"+ }+ ],+ "time": "2025-08-13T04:42:22+00:00"+ },+ {+ "name": "sebastian/type",+ "version": "5.1.3",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/type.git",+ "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/f77d2d4e78738c98d9a68d2596fe5e8fa380f449",+ "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "require-dev": {+ "phpunit/phpunit": "^11.3"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "5.1-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Collection of value objects that represent the types of the PHP type system",+ "homepage": "https://github.com/sebastianbergmann/type",+ "support": {+ "issues": "https://github.com/sebastianbergmann/type/issues",+ "security": "https://github.com/sebastianbergmann/type/security/policy",+ "source": "https://github.com/sebastianbergmann/type/tree/5.1.3"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ },+ {+ "url": "https://liberapay.com/sebastianbergmann",+ "type": "liberapay"+ },+ {+ "url": "https://thanks.dev/u/gh/sebastianbergmann",+ "type": "thanks_dev"+ },+ {+ "url": "https://tidelift.com/funding/github/packagist/sebastian/type",+ "type": "tidelift"+ }+ ],+ "time": "2025-08-09T06:55:48+00:00"+ },+ {+ "name": "sebastian/version",+ "version": "5.0.2",+ "source": {+ "type": "git",+ "url": "https://github.com/sebastianbergmann/version.git",+ "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c687e3387b99f5b03b6caa64c74b63e2936ff874",+ "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874",+ "shasum": ""+ },+ "require": {+ "php": ">=8.2"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "5.0-dev"+ }+ },+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Sebastian Bergmann",+ "email": "[email protected]",+ "role": "lead"+ }+ ],+ "description": "Library that helps with managing the version number of Git-hosted PHP projects",+ "homepage": "https://github.com/sebastianbergmann/version",+ "support": {+ "issues": "https://github.com/sebastianbergmann/version/issues",+ "security": "https://github.com/sebastianbergmann/version/security/policy",+ "source": "https://github.com/sebastianbergmann/version/tree/5.0.2"+ },+ "funding": [+ {+ "url": "https://github.com/sebastianbergmann",+ "type": "github"+ }+ ],+ "time": "2024-10-09T05:16:32+00:00"+ },+ {+ "name": "staabm/side-effects-detector",+ "version": "1.0.5",+ "source": {+ "type": "git",+ "url": "https://github.com/staabm/side-effects-detector.git",+ "reference": "d8334211a140ce329c13726d4a715adbddd0a163"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/staabm/side-effects-detector/zipball/d8334211a140ce329c13726d4a715adbddd0a163",+ "reference": "d8334211a140ce329c13726d4a715adbddd0a163",+ "shasum": ""+ },+ "require": {+ "ext-tokenizer": "*",+ "php": "^7.4 || ^8.0"+ },+ "require-dev": {+ "phpstan/extension-installer": "^1.4.3",+ "phpstan/phpstan": "^1.12.6",+ "phpunit/phpunit": "^9.6.21",+ "symfony/var-dumper": "^5.4.43",+ "tomasvotruba/type-coverage": "1.0.0",+ "tomasvotruba/unused-public": "1.0.0"+ },+ "type": "library",+ "autoload": {+ "classmap": [+ "lib/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "description": "A static analysis tool to detect side effects in PHP code",+ "keywords": [+ "static analysis"+ ],+ "support": {+ "issues": "https://github.com/staabm/side-effects-detector/issues",+ "source": "https://github.com/staabm/side-effects-detector/tree/1.0.5"+ },+ "funding": [+ {+ "url": "https://github.com/staabm",+ "type": "github"+ }+ ],+ "time": "2024-10-20T05:08:20+00:00"+ },+ {+ "name": "theseer/tokenizer",+ "version": "1.3.1",+ "source": {+ "type": "git",+ "url": "https://github.com/theseer/tokenizer.git",+ "reference": "b7489ce515e168639d17feec34b8847c326b0b3c"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b7489ce515e168639d17feec34b8847c326b0b3c",+ "reference": "b7489ce515e168639d17feec34b8847c326b0b3c",+ "shasum": ""+ },+ "require": {+ "ext-dom": "*",+ "ext-tokenizer": "*",+ "ext-xmlwriter": "*",+ "php": "^7.2 || ^8.0"+ },+ "type": "library",+ "autoload": {+ "classmap": [+ "src/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Arne Blankerts",+ "email": "[email protected]",+ "role": "Developer"+ }+ ],+ "description": "A small library for converting tokenized PHP source code into XML and potentially other formats",+ "support": {+ "issues": "https://github.com/theseer/tokenizer/issues",+ "source": "https://github.com/theseer/tokenizer/tree/1.3.1"+ },+ "funding": [+ {+ "url": "https://github.com/theseer",+ "type": "github"+ }+ ],+ "time": "2025-11-17T20:03:58+00:00"+ }+ ],+ "aliases": [],+ "minimum-stability": "stable",+ "stability-flags": {},+ "prefer-stable": false,+ "prefer-lowest": false,+ "platform": {+ "php": ">=8.1"+ },+ "platform-dev": {},+ "plugin-api-version": "2.9.0"+}diff --git a/sdk/php/phpunit.xml b/sdk/php/phpunit.xmlnew file mode 100644index 000000000..abb90f73c--- /dev/null+++ b/sdk/php/phpunit.xml@@ -0,0 +1,23 @@+<?xml version="1.0" encoding="UTF-8"?>+<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"+ xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"+ colors="true"+ cacheDirectory=".phpunit.cache"+ executionOrder="depends,defects"+ requireCoverageMetadata="false"+ beStrictAboutCoverageMetadata="false"+ beStrictAboutOutputDuringTests="true"+ displayDetailsOnTestsThatTriggerWarnings="true"+ failOnRisky="true"+ failOnWarning="true">+ <testsuites>+ <testsuite name="OpenWA PHP SDK">+ <directory>tests</directory>+ </testsuite>+ </testsuites>+ <source>+ <include>+ <directory>src</directory>+ </include>+ </source>+</phpunit>diff --git a/sdk/php/src/Client.php b/sdk/php/src/Client.phpnew file mode 100644index 000000000..0a37628dc--- /dev/null+++ b/sdk/php/src/Client.php@@ -0,0 +1,125 @@+<?php++declare(strict_types=1);++namespace OpenWA;++use GuzzleHttp\ClientInterface;+use OpenWA\Exceptions\OpenWAException;+use OpenWA\Http\HttpExecutor;+use OpenWA\Resources\CatalogResource;+use OpenWA\Resources\ChannelsResource;+use OpenWA\Resources\ChatsResource;+use OpenWA\Resources\ContactsResource;+use OpenWA\Resources\GroupsResource;+use OpenWA\Resources\HealthResource;+use OpenWA\Resources\LabelsResource;+use OpenWA\Resources\MessagesResource;+use OpenWA\Resources\SessionsResource;+use OpenWA\Resources\StatusResource;+use OpenWA\Resources\TemplatesResource;+use OpenWA\Resources\WebhooksResource;++/**+ * OpenWA PHP SDK — client core.+ *+ * The single entry point. It owns an {@see HttpExecutor} (which wraps a Guzzle+ * client with an injectable handler) and exposes domain resources as+ * properties:+ *+ * ```php+ * use OpenWA\Client;+ *+ * $client = new Client([+ * 'baseUrl' => 'http://localhost:2785',+ * 'apiKey' => 'owa_k1_…',+ * ]);+ *+ * $client->sessions->start('my-session');+ * $result = $client->messages->sendText('my-session', [+ * 'chatId' => '[email protected]',+ * 'text' => 'Hello from the OpenWA PHP SDK!',+ * ]);+ * echo $result['messageId'];+ * ```+ *+ * For testing, inject a Guzzle client whose handler is a MockHandler.+ */+class Client+{+ private HttpExecutor $http;++ public SessionsResource $sessions;+ public MessagesResource $messages;+ public ContactsResource $contacts;+ public GroupsResource $groups;+ public WebhooksResource $webhooks;+ public ChatsResource $chats;+ public StatusResource $status;+ public HealthResource $health;+ public LabelsResource $labels;+ public ChannelsResource $channels;+ public CatalogResource $catalog;+ public TemplatesResource $templates;++ /**+ * @param array{+ * baseUrl:string,+ * apiKey:string,+ * timeout?:float,+ * httpClient?:?\GuzzleHttp\ClientInterface|null,+ * defaultHeaders?:array<string,string>+ * } $config+ *+ * @throws OpenWAException If baseUrl or apiKey is missing.+ */+ public function __construct(array $config)+ {+ if (empty($config['baseUrl'])) {+ throw new OpenWAException('OpenWA Client: baseUrl is required');+ }+ if (empty($config['apiKey'])) {+ throw new OpenWAException('OpenWA Client: apiKey is required');+ }++ $this->http = new HttpExecutor(+ $config['baseUrl'],+ $config['apiKey'],+ $config['timeout'] ?? 30.0,+ $config['httpClient'] ?? null,+ $config['defaultHeaders'] ?? [],+ );++ $this->sessions = new SessionsResource($this->http);+ $this->messages = new MessagesResource($this->http);+ $this->contacts = new ContactsResource($this->http);+ $this->groups = new GroupsResource($this->http);+ $this->webhooks = new WebhooksResource($this->http);+ $this->chats = new ChatsResource($this->http);+ $this->status = new StatusResource($this->http);+ $this->health = new HealthResource($this->http);+ $this->labels = new LabelsResource($this->http);+ $this->channels = new ChannelsResource($this->http);+ $this->catalog = new CatalogResource($this->http);+ $this->templates = new TemplatesResource($this->http);+ }++ /** Validate the configured API key and resolve its role. */+ public function auth(): array+ {+ return $this->http->request('POST', '/api/auth/validate') ?? [];+ }++ /**+ * Issue a raw request against the API (advanced use).+ *+ * @param string $path Path beginning with /, e.g. /api/sessions.+ * @param array<string,mixed> $query Query parameters (null values skipped).+ * @param mixed|null $body JSON-serializable request body.+ * @return mixed Decoded JSON, or null for empty/204 responses.+ */+ public function request(string $method, string $path, array $query = [], $body = null)+ {+ return $this->http->request($method, $path, $query, $body);+ }+}diff --git a/sdk/php/src/Exceptions/OpenWAApiException.php b/sdk/php/src/Exceptions/OpenWAApiException.phpnew file mode 100644index 000000000..7fd0edb1d--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWAApiException.php@@ -0,0 +1,64 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/**+ * Raised when the API responds with a non-2xx status.+ *+ * Carries the HTTP status code and the parsed error body. Use the named+ * subclass for common statuses, or branch on getStatus().+ */+class OpenWAApiException extends OpenWAException+{+ private int $status;+ /** @var mixed */+ private $body;+ private ?string $errorKind;++ /**+ * @param mixed $body+ */+ public function __construct(string $message, int $status, $body = null, ?string $errorKind = null)+ {+ parent::__construct($message);+ $this->status = $status;+ $this->body = $body;+ $this->errorKind = $errorKind;+ }++ public function getStatus(): int+ {+ return $this->status;+ }++ /** @return mixed */+ public function getBody()+ {+ return $this->body;+ }++ public function getErrorKind(): ?string+ {+ return $this->errorKind;+ }++ /**+ * Build the most specific OpenWAApiException subclass for a status code.+ *+ * @param mixed $body+ */+ public static function classify(int $status, string $message, $body, ?string $errorKind): OpenWAApiException+ {+ return match ($status) {+ 401 => new OpenWAAuthException($message, $status, $body, $errorKind),+ 403 => new OpenWAForbiddenException($message, $status, $body, $errorKind),+ 404 => new OpenWANotFoundException($message, $status, $body, $errorKind),+ 409 => new OpenWAConflictException($message, $status, $body, $errorKind),+ 429 => new OpenWARateLimitException($message, $status, $body, $errorKind),+ 501 => new OpenWANotImplementedException($message, $status, $body, $errorKind),+ default => new OpenWAApiException($message, $status, $body, $errorKind),+ };+ }+}diff --git a/sdk/php/src/Exceptions/OpenWAAuthException.php b/sdk/php/src/Exceptions/OpenWAAuthException.phpnew file mode 100644index 000000000..b2d1b550e--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWAAuthException.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/** 401 Unauthorized — missing or invalid API key. */+class OpenWAAuthException extends OpenWAApiException+{+}diff --git a/sdk/php/src/Exceptions/OpenWAConflictException.php b/sdk/php/src/Exceptions/OpenWAConflictException.phpnew file mode 100644index 000000000..968534a93--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWAConflictException.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/** 409 Conflict — typically an engine-not-ready condition. */+class OpenWAConflictException extends OpenWAApiException+{+}diff --git a/sdk/php/src/Exceptions/OpenWAException.php b/sdk/php/src/Exceptions/OpenWAException.phpnew file mode 100644index 000000000..6e542fc25--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWAException.php@@ -0,0 +1,12 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/**+ * Base class for every error thrown by the OpenWA SDK.+ */+class OpenWAException extends \Exception+{+}diff --git a/sdk/php/src/Exceptions/OpenWAForbiddenException.php b/sdk/php/src/Exceptions/OpenWAForbiddenException.phpnew file mode 100644index 000000000..074f6f34e--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWAForbiddenException.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/** 403 Forbidden — the API key's role is insufficient. */+class OpenWAForbiddenException extends OpenWAApiException+{+}diff --git a/sdk/php/src/Exceptions/OpenWANotFoundException.php b/sdk/php/src/Exceptions/OpenWANotFoundException.phpnew file mode 100644index 000000000..78fb5a580--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWANotFoundException.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/** 404 Not Found. */+class OpenWANotFoundException extends OpenWAApiException+{+}diff --git a/sdk/php/src/Exceptions/OpenWANotImplementedException.php b/sdk/php/src/Exceptions/OpenWANotImplementedException.phpnew file mode 100644index 000000000..20264397d--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWANotImplementedException.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/** 501 Not Implemented — the active engine does not support this operation. */+class OpenWANotImplementedException extends OpenWAApiException+{+}diff --git a/sdk/php/src/Exceptions/OpenWARateLimitException.php b/sdk/php/src/Exceptions/OpenWARateLimitException.phpnew file mode 100644index 000000000..e4aa0e32e--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWARateLimitException.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/** 429 Too Many Requests — rate limited. */+class OpenWARateLimitException extends OpenWAApiException+{+}diff --git a/sdk/php/src/Exceptions/OpenWATimeoutException.php b/sdk/php/src/Exceptions/OpenWATimeoutException.phpnew file mode 100644index 000000000..6227ddba8--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWATimeoutException.php@@ -0,0 +1,22 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/** Raised when a request exceeds the configured timeout. */+class OpenWATimeoutException extends OpenWAException+{+ private float $timeout;++ public function __construct(float $timeout)+ {+ parent::__construct("Request timed out after {$timeout}s");+ $this->timeout = $timeout;+ }++ public function getTimeout(): float+ {+ return $this->timeout;+ }+}diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.phpnew file mode 100644index 000000000..0de83aa30--- /dev/null+++ b/sdk/php/src/Http/HttpExecutor.php@@ -0,0 +1,158 @@+<?php++declare(strict_types=1);++namespace OpenWA\Http;++use GuzzleHttp\ClientInterface;+use GuzzleHttp\Exception\ConnectException;+use OpenWA\Exceptions\OpenWAApiException;+use OpenWA\Exceptions\OpenWATimeoutException;+use Psr\Http\Message\ResponseInterface;++/**+ * Injectable HTTP transport for the OpenWA SDK.+ *+ * The client never builds a bare Guzzle client with a hard-coded handler.+ * Instead it accepts an optional Guzzle {@see ClientInterface} (defaulting to a+ * new Guzzle client), and for testing a Guzzle {@see \GuzzleHttp\Handler\MockHandler}+ * is injected via the ``httpClient`` option — no global monkey-patching.+ */+class HttpExecutor+{+ private ClientInterface $http;+ private float $timeout;+ private string $apiKey;+ private string $baseUrl;+ /** @var array<string,string> */+ private array $defaultHeaders;++ /**+ * @param array<string,string> $defaultHeaders Applied UNDER the auth/JSON headers+ * (which always win), on every request.+ */+ public function __construct(+ string $baseUrl,+ string $apiKey,+ float $timeout = 30.0,+ ?ClientInterface $httpClient = null,+ array $defaultHeaders = []+ ) {+ $this->timeout = $timeout;+ $this->apiKey = $apiKey;+ $this->baseUrl = rtrim($baseUrl, '/');+ $this->defaultHeaders = $defaultHeaders;+ // Auth/JSON headers are applied per-request (in request()). Request URLs+ // are built absolute (baseUrl . path) so a base path prefix (e.g. /v1+ // behind a reverse proxy) is preserved; base_uri is intentionally unset,+ // because an absolute request path would otherwise replace it.+ $this->http = $httpClient ?? new \GuzzleHttp\Client([+ 'timeout' => $timeout,+ ]);+ }++ /**+ * Percent-encode a single path segment (e.g. a chat/message id) so a value+ * containing /, # or ? can't break out of its path position. WhatsApp-id+ * characters that are already path-safe (@, :, +) are kept readable.+ */+ public function encodeSegment(string $segment): string+ {+ return str_replace(['%40', '%3A', '%2B'], ['@', ':', '+'], rawurlencode($segment));+ }++ /**+ * Perform one request and return the decoded JSON body (or null for 204).+ *+ * @param string $method HTTP method.+ * @param string $path Path beginning with /, e.g. /api/sessions.+ * @param array<string,mixed> $query Query parameters (null values skipped).+ * @param mixed|null $body JSON-serializable request body.+ *+ * @return mixed Decoded JSON, or null for empty/204 responses.+ *+ * @throws OpenWAApiException On any non-2xx response (typed subclass).+ * @throws OpenWATimeoutException On timeout.+ */+ public function request(string $method, string $path, array $query = [], $body = null)+ {+ // Auth/JSON headers are applied per-request so they are correct whether+ // a default or injected client is used (and never leak Guzzle exceptions:+ // http_errors disabled so we translate status into typed SDK exceptions).+ $options = [+ 'http_errors' => false,+ // Never auto-follow redirects: doing so would re-send the X-API-Key+ // header to the redirect target (potentially a different origin).+ 'allow_redirects' => false,+ // Caller default headers first; auth/JSON win so they can't be clobbered.+ 'headers' => array_merge($this->defaultHeaders, [+ 'X-API-Key' => $this->apiKey,+ 'Content-Type' => 'application/json',+ 'Accept' => 'application/json',+ ]),+ ];+ // Build query string, skipping null values (so absent optionals aren't sent).+ $query = array_filter($query, fn ($v) => $v !== null);+ if ($query !== []) {+ $options['query'] = $query;+ }+ if ($body !== null) {+ $options['json'] = $body;+ }++ try {+ $response = $this->http->request($method, $this->baseUrl . $path, $options);+ } catch (ConnectException $e) {+ // cURL error 28 (CURLE_OPERATION_TIMEDOUT) is the canonical timeout+ // signal, surfaced via the handler context. We check errno first+ // (locale- and version-independent) and fall back to message matching+ // for transports that don't populate the context (e.g. stream handler).+ $errno = $e->getHandlerContext()['errno'] ?? null;+ $isTimeout = $errno === 28 || str_contains($e->getMessage(), 'timed out');+ if ($isTimeout) {+ throw new OpenWATimeoutException($this->timeout);+ }+ throw $e;+ }++ $status = $response->getStatusCode();+ if ($status >= 400) {+ throw $this->buildApiException($response, $method, $path);+ }++ $text = (string) $response->getBody();+ if ($status === 204 || $text === '') {+ return null;+ }++ $decoded = json_decode($text, true);+ return $decoded === null && json_last_error() !== JSON_ERROR_NONE ? $text : $decoded;+ }++ private function buildApiException(ResponseInterface $response, string $method, string $path): OpenWAApiException+ {+ $status = $response->getStatusCode();+ $text = (string) $response->getBody();+ $data = null;+ if ($text !== '') {+ $decoded = json_decode($text, true);+ $data = ($decoded === null && json_last_error() !== JSON_ERROR_NONE) ? $text : $decoded;+ }++ // NestJS envelope: {statusCode, message, error}. `error` is sometimes absent+ // (e.g. some 500s), so detect on statusCode + message and treat error as optional.+ $envelope = is_array($data) && isset($data['statusCode'], $data['message']) ? $data : null;+ $rawMessage = $envelope['message'] ?? $data;+ if (is_array($rawMessage)) {+ $messageText = implode(', ', array_map('strval', $rawMessage));+ } elseif (is_string($rawMessage)) {+ $messageText = $rawMessage;+ } else {+ $messageText = $rawMessage === null ? $response->getReasonPhrase() : (string) $rawMessage;+ }+ $reason = $response->getReasonPhrase();+ $message = "OpenWA API {$status} {$reason} — {$method} {$path}: {$messageText}";++ return OpenWAApiException::classify($status, $message, $data, $envelope['error'] ?? null);+ }+}diff --git a/sdk/php/src/Resources/CatalogResource.php b/sdk/php/src/Resources/CatalogResource.phpnew file mode 100644index 000000000..58f26a025--- /dev/null+++ b/sdk/php/src/Resources/CatalogResource.php@@ -0,0 +1,70 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Catalog resource — WhatsApp Business catalog, products, and product/catalog sends.+ *+ * Backed by src/modules/catalog/catalog.controller.ts (@Controller('sessions/:sessionId')).+ * NOTE: the catalog controller is mounted under the session root, so catalog+ * reads are /catalog... while product/catalog SENDS share the messages namespace+ * (/messages/send-product, /messages/send-catalog).+ */+class CatalogResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<string,mixed> */+ public function info(string $sessionId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/catalog");+ }++ /**+ * List catalog products (paginated).+ *+ * @param array<string,mixed> $query e.g. ['page' => 1, 'limit' => 20].+ * @return array<int,array<string,mixed>>+ */+ public function products(string $sessionId, array $query = []): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/catalog/products", $query) ?? [];+ }++ /** @return array<string,mixed> */+ public function product(string $sessionId, string $productId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/catalog/products/{$this->http->encodeSegment($productId)}");+ }++ /**+ * Send a product message. Requires an OPERATOR-level key. Shares the messages path.+ *+ * @param array<string,mixed> $body chatId + productId required; body optional.+ * @return array<string,mixed>+ */+ public function sendProduct(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-product", [], $body);+ }++ /**+ * Send a catalog link message. Requires an OPERATOR-level key. Shares the messages path.+ *+ * @param array<string,mixed> $body chatId required; body optional.+ * @return array<string,mixed>+ */+ public function sendCatalog(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-catalog", [], $body);+ }+}diff --git a/sdk/php/src/Resources/ChannelsResource.php b/sdk/php/src/Resources/ChannelsResource.phpnew file mode 100644index 000000000..3cae6543d--- /dev/null+++ b/sdk/php/src/Resources/ChannelsResource.php@@ -0,0 +1,62 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Channels resource — WhatsApp Channels / Newsletters.+ *+ * Backed by src/modules/channel/channel.controller.ts (@Controller('sessions/:sessionId/channels')).+ */+class ChannelsResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<int,array<string,mixed>> */+ public function list(string $sessionId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/channels") ?? [];+ }++ /** @return array<string,mixed> */+ public function get(string $sessionId, string $channelId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/channels/{$this->http->encodeSegment($channelId)}");+ }++ /**+ * Get recent messages from a channel.+ *+ * @param array<string,mixed> $query e.g. ['limit' => 50].+ * @return array<int,array<string,mixed>>+ */+ public function messages(string $sessionId, string $channelId, array $query = []): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/channels/{$this->http->encodeSegment($channelId)}/messages", $query) ?? [];+ }++ /**+ * Subscribe to a channel using its invite code. Requires an OPERATOR-level key.+ *+ * @param array<string,mixed> $body Must contain 'inviteCode'.+ * @return array<string,mixed>+ */+ public function subscribe(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/channels/subscribe", [], $body);+ }++ /** Unsubscribe from a channel. Requires an OPERATOR-level key. */+ public function unsubscribe(string $sessionId, string $channelId): array+ {+ return $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/channels/{$this->http->encodeSegment($channelId)}");+ }+}diff --git a/sdk/php/src/Resources/ChatsResource.php b/sdk/php/src/Resources/ChatsResource.phpnew file mode 100644index 000000000..343d6f8a3--- /dev/null+++ b/sdk/php/src/Resources/ChatsResource.php@@ -0,0 +1,59 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Chats resource — chat-list operations (read/unread/delete/typing state).+ *+ * These endpoints live under the session controller (/api/sessions/:id/chats/*)+ * but are surfaced here as a dedicated resource for clarity.+ */+class ChatsResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /**+ * @param array<string,mixed> $query+ * @return array<int,array<string,mixed>>+ */+ public function list(string $sessionId, array $query = []): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats", $query) ?? [];+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function markRead(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/read", [], $body);+ }++ /** @return array<string,mixed> */+ public function markUnread(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/unread", [], $body);+ }++ /** @return array<string,mixed> */+ public function delete(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/delete", [], $body);+ }++ /** @return array<string,mixed> */+ public function sendState(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/typing", [], $body);+ }+}diff --git a/sdk/php/src/Resources/ContactsResource.php b/sdk/php/src/Resources/ContactsResource.phpnew file mode 100644index 000000000..03d2f235a--- /dev/null+++ b/sdk/php/src/Resources/ContactsResource.php@@ -0,0 +1,67 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Contacts resource — contact lookup and management.+ *+ * Backed by src/modules/contact/contact.controller.ts.+ */+class ContactsResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /**+ * @param array<string,mixed> $query+ * @return array<int,array<string,mixed>>+ */+ public function list(string $sessionId, array $query = []): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts", $query) ?? [];+ }++ /** @return array<string,mixed> */+ public function get(string $sessionId, string $contactId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}");+ }++ /** @return array<string,mixed> */+ public function check(string $sessionId, string $number): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/check/{$this->http->encodeSegment($number)}");+ }++ /** @return array<string,mixed> */+ public function profilePicture(string $sessionId, string $contactId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}/profile-picture");+ }++ /** @return array<string,mixed> */+ public function phone(string $sessionId, string $contactId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}/phone");+ }++ /** @return array<string,mixed> */+ public function block(string $sessionId, string $contactId): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}/block");+ }++ /** @return array<string,mixed> */+ public function unblock(string $sessionId, string $contactId): array+ {+ return $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}/block");+ }+}diff --git a/sdk/php/src/Resources/GroupsResource.php b/sdk/php/src/Resources/GroupsResource.phpnew file mode 100644index 000000000..07ba115f0--- /dev/null+++ b/sdk/php/src/Resources/GroupsResource.php@@ -0,0 +1,100 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Groups resource — WhatsApp group management.+ *+ * Backed by src/modules/group/group.controller.ts.+ */+class GroupsResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /**+ * @param array<string,mixed> $query+ * @return array<int,array<string,mixed>>+ */+ public function list(string $sessionId, array $query = []): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups", $query) ?? [];+ }++ /** @return array<string,mixed> */+ public function get(string $sessionId, string $groupId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}");+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function create(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups", [], $body);+ }++ /** @return array<string,mixed> */+ public function addParticipants(string $sessionId, string $groupId, array $participants): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/participants", [], ['participants' => $participants]);+ }++ /** @return array<string,mixed> */+ public function removeParticipants(string $sessionId, string $groupId, array $participants): array+ {+ return $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/participants", [], ['participants' => $participants]);+ }++ /** @return array<string,mixed> */+ public function promoteParticipants(string $sessionId, string $groupId, array $participants): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/participants/promote", [], ['participants' => $participants]);+ }++ /** @return array<string,mixed> */+ public function demoteParticipants(string $sessionId, string $groupId, array $participants): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/participants/demote", [], ['participants' => $participants]);+ }++ /** @return array<string,mixed> */+ public function setSubject(string $sessionId, string $groupId, string $subject): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/subject", [], ['subject' => $subject]);+ }++ /** @return array<string,mixed> */+ public function setDescription(string $sessionId, string $groupId, string $description): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/description", [], ['description' => $description]);+ }++ /** @return array<string,mixed> */+ public function leave(string $sessionId, string $groupId): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/leave");+ }++ /** @return array<string,mixed> */+ public function inviteCode(string $sessionId, string $groupId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/invite-code");+ }++ /** @return array<string,mixed> */+ public function revokeInviteCode(string $sessionId, string $groupId): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/invite-code/revoke");+ }+}diff --git a/sdk/php/src/Resources/HealthResource.php b/sdk/php/src/Resources/HealthResource.phpnew file mode 100644index 000000000..cfc943214--- /dev/null+++ b/sdk/php/src/Resources/HealthResource.php@@ -0,0 +1,40 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Health resource — connectivity and readiness probes.+ *+ * Backed by src/modules/health/health.controller.ts.+ */+class HealthResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<string,mixed> */+ public function check(): array+ {+ return $this->http->request('GET', '/api/health') ?? [];+ }++ /** @return array<string,mixed> */+ public function live(): array+ {+ return $this->http->request('GET', '/api/health/live') ?? [];+ }++ /** @return array<string,mixed> */+ public function ready(): array+ {+ return $this->http->request('GET', '/api/health/ready') ?? [];+ }+}diff --git a/sdk/php/src/Resources/LabelsResource.php b/sdk/php/src/Resources/LabelsResource.phpnew file mode 100644index 000000000..639113f14--- /dev/null+++ b/sdk/php/src/Resources/LabelsResource.php@@ -0,0 +1,58 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Labels resource — WhatsApp Business chat labels.+ *+ * Backed by src/modules/label/label.controller.ts (@Controller('sessions/:sessionId/labels')).+ * Labels are a WhatsApp Business feature; the session must be a business account.+ */+class LabelsResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<int,array<string,mixed>> */+ public function list(string $sessionId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels") ?? [];+ }++ /** @return array<string,mixed> */+ public function get(string $sessionId, string $labelId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/{$this->http->encodeSegment($labelId)}");+ }++ /** @return array<int,array<string,mixed>> */+ public function forChat(string $sessionId, string $chatId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/chat/{$this->http->encodeSegment($chatId)}") ?? [];+ }++ /**+ * Add a label to a chat. Requires an OPERATOR-level key.+ *+ * @param array<string,mixed> $body Must contain 'labelId'.+ * @return array<string,mixed>+ */+ public function addToChat(string $sessionId, string $chatId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/chat/{$this->http->encodeSegment($chatId)}", [], $body);+ }++ /** Remove a label from a chat. Requires an OPERATOR-level key. */+ public function removeFromChat(string $sessionId, string $chatId, string $labelId): array+ {+ return $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/chat/{$this->http->encodeSegment($chatId)}/{$this->http->encodeSegment($labelId)}");+ }+}diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.phpnew file mode 100644index 000000000..764f1bb1d--- /dev/null+++ b/sdk/php/src/Resources/MessagesResource.php@@ -0,0 +1,155 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Messages resource — sending and querying messages.+ *+ * Backed by src/modules/message/message.controller.ts.+ * NOTE: the real paths use the /send- prefix, e.g. /messages/send-text.+ */+class MessagesResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /**+ * @param array<string,mixed> $query+ * @return array<int,array<string,mixed>>+ */+ public function list(string $sessionId, array $query = []): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages", $query) ?? [];+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function sendText(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-text", [], $body);+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function sendImage(string $sessionId, array $body): array+ {+ return $this->sendMedia($sessionId, 'send-image', $body);+ }++ /** @return array<string,mixed> */+ public function sendVideo(string $sessionId, array $body): array+ {+ return $this->sendMedia($sessionId, 'send-video', $body);+ }++ /** @return array<string,mixed> */+ public function sendAudio(string $sessionId, array $body): array+ {+ return $this->sendMedia($sessionId, 'send-audio', $body);+ }++ /** @return array<string,mixed> */+ public function sendDocument(string $sessionId, array $body): array+ {+ return $this->sendMedia($sessionId, 'send-document', $body);+ }++ /** @return array<string,mixed> */+ public function sendSticker(string $sessionId, array $body): array+ {+ return $this->sendMedia($sessionId, 'send-sticker', $body);+ }++ /** @return array<string,mixed> */+ private function sendMedia(string $sessionId, string $segment, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($segment)}", [], $body);+ }++ /** @return array<string,mixed> */+ public function sendLocation(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-location", [], $body);+ }++ /** @return array<string,mixed> */+ public function sendContact(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-contact", [], $body);+ }++ /** @return array<string,mixed> */+ public function sendTemplate(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-template", [], $body);+ }++ /** @return array<string,mixed> */+ public function reply(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/reply", [], $body);+ }++ /** @return array<string,mixed> */+ public function forward(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/forward", [], $body);+ }++ /** @return array<string,mixed> */+ public function react(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/react", [], $body);+ }++ /** @return array<string,mixed> */+ public function delete(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/delete", [], $body);+ }++ /**+ * @param array<string,mixed> $query+ * @return array<int,array<string,mixed>>+ */+ public function history(string $sessionId, string $chatId, array $query = []): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($chatId)}/history", $query) ?? [];+ }++ /** @return array<int,array<string,mixed>> */+ public function reactions(string $sessionId, string $chatId, string $messageId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($chatId)}/{$this->http->encodeSegment($messageId)}/reactions") ?? [];+ }++ /** @return array<string,mixed> */+ public function sendBulk(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-bulk", [], $body);+ }++ /** @return array<string,mixed> */+ public function batchStatus(string $sessionId, string $batchId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/batch/{$this->http->encodeSegment($batchId)}");+ }++ /** @return array<string,mixed> */+ public function cancelBatch(string $sessionId, string $batchId): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/batch/{$this->http->encodeSegment($batchId)}/cancel");+ }+}diff --git a/sdk/php/src/Resources/SessionsResource.php b/sdk/php/src/Resources/SessionsResource.phpnew file mode 100644index 000000000..4c997de33--- /dev/null+++ b/sdk/php/src/Resources/SessionsResource.php@@ -0,0 +1,87 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Sessions resource — lifecycle management for WhatsApp sessions.+ *+ * Backed by src/modules/session/session.controller.ts.+ */+class SessionsResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<int,array<string,mixed>> */+ public function list(): array+ {+ return $this->http->request('GET', '/api/sessions') ?? [];+ }++ /** @return array<string,mixed> */+ public function get(string $id): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($id)}");+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function create(array $body): array+ {+ return $this->http->request('POST', '/api/sessions', [], $body);+ }++ public function delete(string $id): void+ {+ $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($id)}");+ }++ /** @return array<string,mixed> */+ public function start(string $id): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($id)}/start");+ }++ /** @return array<string,mixed> */+ public function stop(string $id): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($id)}/stop");+ }++ /** @return array<string,mixed> */+ public function forceKill(string $id): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($id)}/force-kill");+ }++ /** @return array<string,mixed> */+ public function getQrCode(string $id): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($id)}/qr");+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function requestPairingCode(string $id, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($id)}/pairing-code", [], $body);+ }++ /** @return array<string,mixed> */+ public function stats(): array+ {+ return $this->http->request('GET', '/api/sessions/stats/overview');+ }+}diff --git a/sdk/php/src/Resources/StatusResource.php b/sdk/php/src/Resources/StatusResource.phpnew file mode 100644index 000000000..38702393f--- /dev/null+++ b/sdk/php/src/Resources/StatusResource.php@@ -0,0 +1,61 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Status (Stories) resource — WhatsApp status updates.+ *+ * Backed by src/modules/status/status.controller.ts.+ * NOTE: this is WhatsApp "Status/Stories", distinct from session lifecycle status.+ */+class StatusResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<string,mixed> */+ public function list(string $sessionId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status") ?? [];+ }++ /** @return array<string,mixed> */+ public function fromContact(string $sessionId, string $contactId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status/{$this->http->encodeSegment($contactId)}") ?? [];+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function sendText(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status/send-text", [], $body);+ }++ /** @return array<string,mixed> */+ public function sendImage(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status/send-image", [], $body);+ }++ /** @return array<string,mixed> */+ public function sendVideo(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status/send-video", [], $body);+ }++ public function delete(string $sessionId, string $statusId): void+ {+ $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status/{$this->http->encodeSegment($statusId)}");+ }+}diff --git a/sdk/php/src/Resources/TemplatesResource.php b/sdk/php/src/Resources/TemplatesResource.phpnew file mode 100644index 000000000..429b4d6b0--- /dev/null+++ b/sdk/php/src/Resources/TemplatesResource.php@@ -0,0 +1,63 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Templates resource — stored message templates with {{variable}} placeholders.+ *+ * Backed by src/modules/template/template.controller.ts+ * (@Controller('sessions/:sessionId/templates')).+ */+class TemplatesResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<int,array<string,mixed>> */+ public function list(string $sessionId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/templates") ?? [];+ }++ /** @return array<string,mixed> */+ public function get(string $sessionId, string $templateId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/templates/{$this->http->encodeSegment($templateId)}");+ }++ /**+ * Create a template. Requires an OPERATOR-level key.+ *+ * @param array<string,mixed> $body Must contain 'name' and 'body'; 'header'/'footer' optional.+ * @return array<string,mixed>+ */+ public function create(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/templates", [], $body);+ }++ /**+ * Update a template. Requires an OPERATOR-level key.+ *+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function update(string $sessionId, string $templateId, array $body): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/templates/{$this->http->encodeSegment($templateId)}", [], $body);+ }++ /** Delete a template. Requires an OPERATOR-level key. */+ public function delete(string $sessionId, string $templateId): void+ {+ $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/templates/{$this->http->encodeSegment($templateId)}");+ }+}diff --git a/sdk/php/src/Resources/WebhooksResource.php b/sdk/php/src/Resources/WebhooksResource.phpnew file mode 100644index 000000000..9aae594c9--- /dev/null+++ b/sdk/php/src/Resources/WebhooksResource.php@@ -0,0 +1,63 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Webhooks resource — configure event delivery to external HTTP endpoints.+ *+ * Backed by src/modules/webhook/webhook.controller.ts.+ */+class WebhooksResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /** @return array<int,array<string,mixed>> */+ public function list(string $sessionId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/webhooks") ?? [];+ }++ /** @return array<string,mixed> */+ public function get(string $sessionId, string $id): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/webhooks/{$this->http->encodeSegment($id)}");+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function create(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/webhooks", [], $body);+ }++ /**+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function update(string $sessionId, string $id, array $body): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/webhooks/{$this->http->encodeSegment($id)}", [], $body);+ }++ public function delete(string $sessionId, string $id): void+ {+ $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/webhooks/{$this->http->encodeSegment($id)}");+ }++ /** @return array<string,mixed> */+ public function test(string $sessionId, string $id): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/webhooks/{$this->http->encodeSegment($id)}/test");+ }+}diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.phpnew file mode 100644index 000000000..c8576086c--- /dev/null+++ b/sdk/php/tests/ClientTest.php@@ -0,0 +1,189 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use OpenWA\Exceptions\OpenWAAuthException;+use OpenWA\Exceptions\OpenWANotFoundException;+use OpenWA\Exceptions\OpenWATimeoutException;+use PHPUnit\Framework\TestCase;++class ClientTest extends TestCase+{+ public function testRequiresBaseUrlAndApiKey(): void+ {+ $this->expectException(\OpenWA\Exceptions\OpenWAException::class);+ new \OpenWA\Client(['baseUrl' => '', 'apiKey' => 'k']);+ }++ public function testRequiresApiKey(): void+ {+ $this->expectException(\OpenWA\Exceptions\OpenWAException::class);+ new \OpenWA\Client(['baseUrl' => 'http://x', 'apiKey' => '']);+ }++ public function testSendsApiKeyHeader(): void+ {+ $backend = (new MockBackend())->on(200, []);+ $client = $backend->makeClient();+ $client->sessions->list();+ $call = $backend->lastCall();+ $this->assertSame('owa_k1_test', $call['headers']['x-api-key'] ?? '');+ $this->assertSame('application/json', $call['headers']['content-type'] ?? '');+ }++ public function testDefaultHeadersApplledUnderAuth(): void+ {+ $backend = (new MockBackend())->on(200, []);+ $client = new \OpenWA\Client([+ 'baseUrl' => 'http://x',+ 'apiKey' => 'REAL_KEY',+ 'httpClient' => $backend->httpClient(),+ 'defaultHeaders' => ['X-Trace' => 'keep', 'X-API-Key' => 'EVIL'],+ ]);+ $client->sessions->list();+ $headers = $backend->lastCall()['headers'];+ $this->assertSame('keep', $headers['x-trace'] ?? ''); // custom header forwarded+ $this->assertSame('REAL_KEY', $headers['x-api-key'] ?? ''); // auth still wins+ }++ public function testPathSegmentsAreEncoded(): void+ {+ $backend = (new MockBackend())->on(200, ['id' => 'x']);+ $backend->makeClient()->labels->get('s', 'weird/id#x');+ $this->assertStringContainsString('/labels/weird%2Fid%23x', $backend->lastCall()['path']);++ $backend2 = (new MockBackend())->on(200, ['id' => 'x']);+ $backend2->makeClient()->labels->get('s', '[email protected]');+ $this->assertStringContainsString('/labels/[email protected]', $backend2->lastCall()['path']); // @ preserved+ }++ public function testRawRequestEscapeHatch(): void+ {+ $backend = (new MockBackend())->on(200, ['ok' => true]);+ $result = $backend->makeClient()->request('GET', '/api/anything', ['a' => 1]);+ $this->assertSame(['ok' => true], $result);+ $this->assertSame('/api/anything', $backend->lastCall()['path']);+ $this->assertStringContainsString('a=1', $backend->lastCall()['query']);+ }++ public function testBaseUrlPathPrefixIsPreserved(): void+ {+ // A base URL with a path prefix (e.g. behind a reverse proxy at /v1) must+ // be kept; absolute request paths must not drop it.+ $backend = (new MockBackend())->on(200, []);+ $backend->makeClient('http://localhost:2785/v1')->sessions->list();+ $this->assertStringContainsString('/v1/api/sessions', $backend->lastCall()['path']);+ }++ public function testDoesNotFollowRedirects(): void+ {+ // A redirect must not be followed (which would re-send X-API-Key to the+ // target origin). The 3xx body is returned and only one request is made.+ $backend = new MockBackend();+ $backend->on(302, ['redirected' => true], ['Location' => 'http://evil.example/x']);+ $backend->on(200, ['followed' => true]); // only reached if a redirect were followed+ $result = $backend->makeClient()->sessions->list();+ $this->assertCount(1, $backend->calls());+ $this->assertSame(['redirected' => true], $result);+ }++ public function test204DeleteSucceedsWithNoBody(): void+ {+ $backend = (new MockBackend())->on(204);+ $backend->makeClient()->sessions->delete('x');+ $this->assertSame('DELETE', $backend->lastCall()['method']);+ }++ public function test404MapsToNotFoundException(): void+ {+ $backend = (new MockBackend())->on(404, [+ 'statusCode' => 404,+ 'message' => 'Session not found',+ 'error' => 'Not Found',+ ]);+ $this->expectException(OpenWANotFoundException::class);+ $backend->makeClient()->sessions->get('missing');+ }++ public function test401MapsToAuthException(): void+ {+ $backend = (new MockBackend())->on(401, [+ 'statusCode' => 401,+ 'message' => 'Unauthorized',+ 'error' => 'Unauthorized',+ ]);+ $this->expectException(OpenWAAuthException::class);+ $backend->makeClient()->sessions->list();+ }++ public function testExposesAllResources(): void+ {+ $client = (new MockBackend())->makeClient();+ foreach (['sessions', 'messages', 'contacts', 'groups', 'webhooks', 'chats', 'status', 'health'] as $r) {+ $this->assertTrue(property_exists($client, $r), "Client should expose resource: {$r}");+ }+ }++ public function testErrorCarriesStatusAndBody(): void+ {+ $backend = (new MockBackend())->on(404, [+ 'statusCode' => 404,+ 'message' => 'Session not found',+ 'error' => 'Not Found',+ ]);+ try {+ $backend->makeClient()->sessions->get('x');+ $this->fail('Expected exception');+ } catch (OpenWANotFoundException $e) {+ $this->assertSame(404, $e->getStatus());+ $this->assertSame('Not Found', $e->getErrorKind());+ $this->assertIsArray($e->getBody());+ }+ }++ public function testTimeoutWithErrno28MapsToTimeoutException(): void+ {+ // Regression guard: cURL error 28 (CURLE_OPERATION_TIMEDOUT) must map to+ // OpenWATimeoutException, regardless of the message wording.+ $timeoutRequest = new \GuzzleHttp\Exception\ConnectException(+ 'cURL error 28: Operation timed out',+ new \GuzzleHttp\Psr7\Request('GET', '/api/sessions'),+ null,+ ['errno' => 28],+ );+ $mock = new \GuzzleHttp\Handler\MockHandler([$timeoutRequest]);+ $httpClient = new \GuzzleHttp\Client(['handler' => \GuzzleHttp\HandlerStack::create($mock)]);+ $client = new \OpenWA\Client([+ 'baseUrl' => 'http://localhost:2785',+ 'apiKey' => 'k',+ 'httpClient' => $httpClient,+ ]);++ $this->expectException(OpenWATimeoutException::class);+ $client->sessions->list();+ }++ public function testConnectionRefusedDoesNotMapToTimeoutException(): void+ {+ // Regression guard: a non-timeout ConnectException (errno 7) must NOT be+ // misclassified as a timeout — it must propagate as ConnectException.+ $refused = new \GuzzleHttp\Exception\ConnectException(+ 'cURL error 7: connection refused',+ new \GuzzleHttp\Psr7\Request('GET', '/api/sessions'),+ null,+ ['errno' => 7],+ );+ $mock = new \GuzzleHttp\Handler\MockHandler([$refused]);+ $httpClient = new \GuzzleHttp\Client(['handler' => \GuzzleHttp\HandlerStack::create($mock)]);+ $client = new \OpenWA\Client([+ 'baseUrl' => 'http://localhost:2785',+ 'apiKey' => 'k',+ 'httpClient' => $httpClient,+ ]);++ $this->expectException(\GuzzleHttp\Exception\ConnectException::class);+ $client->sessions->list();+ }+}diff --git a/sdk/php/tests/LabelsChannelsCatalogTest.php b/sdk/php/tests/LabelsChannelsCatalogTest.phpnew file mode 100644index 000000000..68f157075--- /dev/null+++ b/sdk/php/tests/LabelsChannelsCatalogTest.php@@ -0,0 +1,81 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use PHPUnit\Framework\TestCase;++class LabelsChannelsCatalogTest extends TestCase+{+ public function testLabels(): void+ {+ $backend = new MockBackend();+ $backend->on(200, [['id' => 'l1', 'name' => 'VIP']]);+ $backend->on(200, ['id' => 'l1', 'name' => 'VIP']);+ $backend->on(200, [['id' => 'l1', 'name' => 'VIP']]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->labels->list('s');+ $this->assertStringContainsString('/sessions/s/labels', $backend->calls()[0]['path']);+ $client->labels->get('s', 'l1');+ $this->assertStringContainsString('/labels/l1', $backend->calls()[1]['path']);+ $client->labels->forChat('s', '[email protected]');+ $client->labels->addToChat('s', '[email protected]', ['labelId' => 'l1']);+ $this->assertSame('POST', $backend->calls()[3]['method']);+ $this->assertSame(['labelId' => 'l1'], $backend->calls()[3]['body']);+ $client->labels->removeFromChat('s', '[email protected]', 'l1');+ $this->assertSame('DELETE', $backend->calls()[4]['method']);+ }++ public function testChannels(): void+ {+ $backend = new MockBackend();+ $backend->on(200, [['id' => '123@newsletter', 'name' => 'News']]);+ $backend->on(200, ['id' => '123@newsletter', 'name' => 'News']);+ $backend->on(200, []);+ $backend->on(201, ['id' => '123@newsletter', 'name' => 'News']);+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->channels->list('s');+ $this->assertStringContainsString('/sessions/s/channels', $backend->calls()[0]['path']);+ $client->channels->get('s', '123@newsletter');+ $client->channels->messages('s', '123@newsletter', ['limit' => 10]);+ $this->assertStringContainsString('limit=10', $backend->calls()[2]['query']);+ $client->channels->subscribe('s', ['inviteCode' => 'ABCxyz']);+ $this->assertSame('POST', $backend->calls()[3]['method']);+ $this->assertSame(['inviteCode' => 'ABCxyz'], $backend->calls()[3]['body']);+ $client->channels->unsubscribe('s', '123@newsletter');+ $this->assertSame('DELETE', $backend->calls()[4]['method']);+ }++ public function testCatalog(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['name' => 'My Shop', 'productsCount' => 5]);+ $backend->on(200, [['id' => 'p1', 'name' => 'Widget']]);+ $backend->on(200, ['id' => 'p1', 'name' => 'Widget']);+ $backend->on(201, ['messageId' => 'm', 'timestamp' => 1]);+ $backend->on(201, ['messageId' => 'm', 'timestamp' => 1]);+ $client = $backend->makeClient();+ $client->catalog->info('s');+ $this->assertStringContainsString('/sessions/s/catalog', $backend->calls()[0]['path']);+ $client->catalog->products('s', ['page' => 1, 'limit' => 20]);+ $this->assertStringContainsString('page=1', $backend->calls()[1]['query']);+ $client->catalog->product('s', 'p1');+ $client->catalog->sendProduct('s', ['chatId' => '[email protected]', 'productId' => 'p1', 'body' => 'x']);+ $this->assertStringContainsString('/messages/send-product', $backend->calls()[3]['path']);+ $this->assertSame(['chatId' => '[email protected]', 'productId' => 'p1', 'body' => 'x'], $backend->calls()[3]['body']);+ $client->catalog->sendCatalog('s', ['chatId' => '[email protected]', 'body' => 'cat']);+ $this->assertStringContainsString('/messages/send-catalog', $backend->calls()[4]['path']);+ }++ public function testClientExposesAll11Resources(): void+ {+ $client = (new MockBackend())->makeClient();+ foreach (['sessions', 'messages', 'contacts', 'groups', 'webhooks', 'chats', 'status', 'health', 'labels', 'channels', 'catalog'] as $r) {+ $this->assertTrue(property_exists($client, $r), "Client should expose resource: {$r}");+ }+ }+}diff --git a/sdk/php/tests/MessagesTest.php b/sdk/php/tests/MessagesTest.phpnew file mode 100644index 000000000..ed9fe9677--- /dev/null+++ b/sdk/php/tests/MessagesTest.php@@ -0,0 +1,93 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use PHPUnit\Framework\TestCase;++class MessagesTest extends TestCase+{+ public function testSendTextUsesSendTextPath(): void+ {+ $backend = (new MockBackend())->on(201, ['messageId' => 'm1', 'timestamp' => 1]);+ $client = $backend->makeClient();+ $client->messages->sendText('s1', ['chatId' => '[email protected]', 'text' => 'hi']);+ $call = $backend->lastCall();+ // Guzzle exposes the relative path at the handler layer; the host is+ // statically configured via base_uri, so we assert on path + body.+ $this->assertSame('/api/sessions/s1/messages/send-text', $call['path']);+ $this->assertSame(['chatId' => '[email protected]', 'text' => 'hi'], $call['body']);+ }++ public static function mediaSegments(): array+ {+ return [+ 'sendImage' => ['sendImage', 'send-image'],+ 'sendVideo' => ['sendVideo', 'send-video'],+ 'sendAudio' => ['sendAudio', 'send-audio'],+ 'sendDocument' => ['sendDocument', 'send-document'],+ 'sendSticker' => ['sendSticker', 'send-sticker'],+ ];+ }++ /**+ * @dataProvider mediaSegments+ */+ public function testMediaSegmentsUseCorrectPaths(string $method, string $segment): void+ {+ $backend = (new MockBackend())->on(201, ['messageId' => 'm', 'timestamp' => 2]);+ $client = $backend->makeClient();+ $client->messages->$method('s', ['chatId' => '[email protected]', 'url' => 'u']);+ $this->assertStringContainsString("/messages/{$segment}", $backend->lastCall()['path']);+ }++ public function testReplyForwardReactDelete(): void+ {+ $backend = new MockBackend();+ $backend->on(201, ['messageId' => 'm', 'timestamp' => 1]);+ $backend->on(201, ['messageId' => 'm', 'timestamp' => 1]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->messages->reply('s', ['chatId' => '[email protected]', 'quotedMessageId' => 'q', 'text' => 'r']);+ $this->assertStringContainsString('/messages/reply', $backend->calls()[0]['url']);+ $client->messages->forward('s', ['fromChatId' => '[email protected]', 'toChatId' => '[email protected]', 'messageId' => 'm']);+ $this->assertStringContainsString('/messages/forward', $backend->calls()[1]['url']);+ $client->messages->react('s', ['chatId' => '[email protected]', 'messageId' => 'm', 'emoji' => '👍']);+ $this->assertStringContainsString('/messages/react', $backend->calls()[2]['url']);+ $client->messages->delete('s', ['chatId' => '[email protected]', 'messageId' => 'm']);+ $this->assertStringContainsString('/messages/delete', $backend->calls()[3]['url']);+ }++ public function testHistoryAndReactionsPath(): void+ {+ $backend = new MockBackend();+ $backend->on(200, []);+ $backend->on(200, []);+ $client = $backend->makeClient();+ $client->messages->history('s', '[email protected]', ['limit' => 5]);+ $this->assertStringContainsString('/messages/[email protected]/history', $backend->calls()[0]['url']);+ $this->assertStringContainsString('limit=5', $backend->calls()[0]['url']);+ $client->messages->reactions('s', '[email protected]', 'm1');+ $this->assertStringContainsString('/messages/[email protected]/m1/reactions', $backend->calls()[1]['url']);+ }++ public function testSendBulkBatchStatusCancelBatch(): void+ {+ $backend = new MockBackend();+ $backend->on(202, ['batchId' => 'b', 'status' => 'queued', 'totalMessages' => 1, 'estimatedCompletionTime' => 't', 'statusUrl' => '/u']);+ $backend->on(200, ['batchId' => 'b', 'status' => 'done', 'progress' => 100, 'results' => [], 'startedAt' => 's', 'completedAt' => 'c']);+ $backend->on(200, ['batchId' => 'b', 'status' => 'cancelled', 'progress' => 50]);+ $client = $backend->makeClient();+ $client->messages->sendBulk('s', ['messages' => [['chatId' => '[email protected]', 'type' => 'text', 'content' => ['text' => 'x']]]]);+ $this->assertStringContainsString('/messages/send-bulk', $backend->calls()[0]['url']);+ $status = $client->messages->batchStatus('s', 'b');+ $this->assertSame(100, $status['progress']);+ $this->assertStringContainsString('/messages/batch/b', $backend->calls()[1]['url']);+ $cancelled = $client->messages->cancelBatch('s', 'b');+ $this->assertSame('cancelled', $cancelled['status']);+ $this->assertSame('POST', $backend->calls()[2]['method']);+ $this->assertStringContainsString('/messages/batch/b/cancel', $backend->calls()[2]['url']);+ }+}diff --git a/sdk/php/tests/MockBackend.php b/sdk/php/tests/MockBackend.phpnew file mode 100644index 000000000..719c6ca45--- /dev/null+++ b/sdk/php/tests/MockBackend.php@@ -0,0 +1,128 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use GuzzleHttp\Client as GuzzleClient;+use GuzzleHttp\Handler\MockHandler;+use GuzzleHttp\HandlerStack;+use GuzzleHttp\Middleware;+use GuzzleHttp\Psr7\Response;+use OpenWA\Client as OpenWAClient;+use Psr\Http\Message\RequestInterface;++/**+ * A scripted backend for SDK tests.+ *+ * Uses Guzzle's MockHandler + a history middleware to record every request so+ * tests can assert on the exact method, URL, query string, and body — without+ * any real network or global state.+ */+class MockBackend+{+ private MockHandler $mock;+ /** @var array<int,RequestInterface> */+ private array $recorded = [];++ public function __construct()+ {+ $this->mock = new MockHandler();+ }++ /**+ * Queue a response for the next matching call.+ *+ * @param mixed $body JSON-encodable body (omit/null for empty/204).+ */+ public function on(int $status = 200, $body = null, array $headers = []): self+ {+ if ($status === 204 || $body === null) {+ $this->mock->append(new Response($status, $headers, ''));+ } else {+ $headers['Content-Type'] = 'application/json';+ $this->mock->append(new Response($status, $headers, json_encode($body) ?: ''));+ }+ return $this;+ }++ public function httpClient(): GuzzleClient+ {+ // Record at the handler layer (innermost). The handler always sees the+ // fully-prepared request — host merged from base_uri, JSON body+ // serialized, headers applied — unlike history middleware which can run+ // before prepare-body. This is the most reliable capture point.+ $mock = $this->mock;+ $recorded = &$this->recorded;+ $recorder = static function (RequestInterface $request, array $options) use ($mock, &$recorded) {+ $recorded[] = $request;+ return $mock($request, $options);+ };++ return new GuzzleClient(['handler' => HandlerStack::create($recorder)]);+ }++ public function makeClient(string $baseUrl = 'http://localhost:2785', string $apiKey = 'owa_k1_test'): OpenWAClient+ {+ return new OpenWAClient([+ 'baseUrl' => $baseUrl,+ 'apiKey' => $apiKey,+ 'httpClient' => $this->httpClient(),+ ]);+ }++ /** @return array<string,mixed> */+ public function lastCall(): array+ {+ return $this->callAt(count($this->recorded) - 1);+ }++ /**+ * @param int $index Zero-based call index.+ * @return array<string,mixed>+ */+ public function callAt(int $index): array+ {+ if (!isset($this->recorded[$index])) {+ return [];+ }+ $req = $this->recorded[$index];+ $uri = $req->getUri();+ $body = (string) $req->getBody();+ $decoded = null;+ if ($body !== '') {+ $tmp = json_decode($body, true);+ $decoded = ($tmp === null && json_last_error() !== JSON_ERROR_NONE) ? $body : $tmp;+ }+ $headerMap = [];+ foreach ($req->getHeaders() as $k => $vs) {+ $headerMap[strtolower((string) $k)] = $vs[0] ?? '';+ }+ return [+ 'method' => $req->getMethod(),+ 'url' => (string) $uri,+ 'host' => $uri->getHost(),+ 'path' => $uri->getPath(),+ 'query' => $uri->getQuery(),+ 'body' => $decoded,+ 'headers' => $headerMap,+ ];+ }++ /** @return array<int,array<string,mixed>> */+ public function calls(): array+ {+ $out = [];+ for ($i = 0, $n = count($this->recorded); $i < $n; $i++) {+ $c = $this->callAt($i);+ $out[] = [+ 'method' => $c['method'],+ 'url' => $c['url'],+ 'path' => $c['path'],+ 'query' => $c['query'],+ 'body' => $c['body'],+ ];+ }+ return $out;+ }+}diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.phpnew file mode 100644index 000000000..8e5181814--- /dev/null+++ b/sdk/php/tests/ResourcesTest.php@@ -0,0 +1,201 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use PHPUnit\Framework\TestCase;++class ResourcesTest extends TestCase+{+ // ── Sessions ──────────────────────────────────────────────────────++ public function testSessionLifecyclePaths(): void+ {+ $backend = new MockBackend();+ // Queue responses in CALL order: list, get, create, start, stop, forceKill, delete.+ $backend->on(200, []);+ $backend->on(200, ['id' => 's1', 'name' => 'n', 'status' => 'ready']);+ $backend->on(201, ['id' => 's1', 'name' => 'n', 'status' => 'created']);+ $backend->on(200, ['id' => 's1', 'status' => 'initializing']);+ $backend->on(200, ['id' => 's1', 'status' => 'disconnected']);+ $backend->on(200, ['id' => 's1', 'status' => 'disconnected']);+ $backend->on(204);+ $client = $backend->makeClient();+ $client->sessions->list();+ $this->assertSame('/api/sessions', $backend->calls()[0]['path']);+ $client->sessions->get('s1');+ $client->sessions->create(['name' => 'n']);+ $this->assertSame(['name' => 'n'], $backend->lastCall()['body']);+ $client->sessions->start('s1');+ $this->assertStringContainsString('/sessions/s1/start', $backend->lastCall()['path']);+ $client->sessions->stop('s1');+ $client->sessions->forceKill('s1');+ $this->assertStringContainsString('/sessions/s1/force-kill', $backend->lastCall()['path']);+ $client->sessions->delete('s1');+ $this->assertSame('DELETE', $backend->lastCall()['method']);+ }++ public function testQrPairingStats(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['qrCode' => 'data:image/png;base64,xxx', 'status' => 'qr_ready']);+ $backend->on(200, ['pairingCode' => 'ABCD1234', 'status' => 'qr_ready']);+ $backend->on(200, ['total' => 1, 'active' => 1, 'ready' => 1, 'disconnected' => 0, 'byStatus' => ['ready' => 1]]);+ $client = $backend->makeClient();+ $client->sessions->getQrCode('s1');+ $this->assertStringContainsString('/sessions/s1/qr', $backend->calls()[0]['url']);+ $client->sessions->requestPairingCode('s1', ['phoneNumber' => '628123456789']);+ $this->assertSame(['phoneNumber' => '628123456789'], $backend->lastCall()['body']);+ $client->sessions->stats();+ $this->assertStringContainsString('/sessions/stats/overview', $backend->lastCall()['url']);+ }++ // ── Groups ────────────────────────────────────────────────────────++ public function testGroupListGetCreate(): void+ {+ $backend = new MockBackend();+ $backend->on(200, []);+ $backend->on(200, ['id' => '[email protected]', 'subject' => 'G', 'participants' => []]);+ $backend->on(201, ['id' => '[email protected]', 'subject' => 'G', 'participants' => []]);+ $client = $backend->makeClient();+ $client->groups->list('s');+ $client->groups->get('s', '[email protected]');+ $this->assertStringContainsString('/groups/[email protected]', $backend->calls()[1]['url']);+ $client->groups->create('s', ['name' => 'G', 'participants' => ['[email protected]']]);+ $this->assertSame(['name' => 'G', 'participants' => ['[email protected]']], $backend->lastCall()['body']);+ }++ public function testGroupParticipantOps(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->groups->addParticipants('s', 'g', ['[email protected]', '[email protected]']);+ $this->assertSame(['participants' => ['[email protected]', '[email protected]']], $backend->calls()[0]['body']);+ $this->assertSame('POST', $backend->calls()[0]['method']);+ $client->groups->removeParticipants('s', 'g', ['[email protected]']);+ $this->assertSame('DELETE', $backend->calls()[1]['method']);+ $client->groups->promoteParticipants('s', 'g', ['[email protected]']);+ $this->assertStringContainsString('/promote', $backend->calls()[2]['url']);+ $client->groups->demoteParticipants('s', 'g', ['[email protected]']);+ $this->assertStringContainsString('/demote', $backend->calls()[3]['url']);+ }++ public function testGroupSubjectDescriptionInvite(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['inviteCode' => 'c', 'inviteLink' => 'l']);+ $backend->on(200, ['inviteCode' => 'c2', 'inviteLink' => 'l2']);+ $client = $backend->makeClient();+ $client->groups->setSubject('s', 'g', 'New');+ $this->assertSame(['subject' => 'New'], $backend->calls()[0]['body']);+ $this->assertSame('PUT', $backend->calls()[0]['method']);+ $client->groups->setDescription('s', 'g', 'desc');+ $this->assertSame(['description' => 'desc'], $backend->calls()[1]['body']);+ $client->groups->leave('s', 'g');+ $client->groups->inviteCode('s', 'g');+ $client->groups->revokeInviteCode('s', 'g');+ $this->assertStringContainsString('/revoke', $backend->calls()[4]['url']);+ }++ // ── Contacts ──────────────────────────────────────────────────────++ public function testContactPaths(): void+ {+ $backend = new MockBackend();+ $backend->on(200, []);+ $backend->on(200, ['id' => '[email protected]']);+ $backend->on(200, ['number' => '628123', 'exists' => true, 'whatsappId' => '[email protected]']);+ $backend->on(200, ['url' => 'http://p']);+ $backend->on(200, ['contactId' => 'x@lid', 'phone' => '628123']);+ $client = $backend->makeClient();+ $client->contacts->list('s', ['limit' => 10]);+ $this->assertStringContainsString('limit=10', $backend->calls()[0]['url']);+ $client->contacts->get('s', '[email protected]');+ $client->contacts->check('s', '628123');+ $this->assertStringContainsString('/check/628123', $backend->calls()[2]['url']);+ $client->contacts->profilePicture('s', '[email protected]');+ $client->contacts->phone('s', 'x@lid');+ }++ public function testBlockUnblock(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->contacts->block('s', '[email protected]');+ $this->assertSame('POST', $backend->calls()[0]['method']);+ $client->contacts->unblock('s', '[email protected]');+ $this->assertSame('DELETE', $backend->calls()[1]['method']);+ }++ // ── Webhooks ──────────────────────────────────────────────────────++ public function testWebhookCrudTest(): void+ {+ $wh = ['id' => 'w1', 'sessionId' => 's', 'url' => 'u', 'events' => ['*'], 'active' => true, 'createdAt' => '', 'updatedAt' => ''];+ $backend = new MockBackend();+ $backend->on(200, [$wh]);+ $backend->on(200, $wh);+ $backend->on(201, $wh);+ $backend->on(200, array_merge($wh, ['active' => false]));+ $backend->on(204);+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->webhooks->list('s');+ $client->webhooks->get('s', 'w1');+ $client->webhooks->create('s', ['url' => 'u', 'events' => ['*']]);+ $this->assertSame(['url' => 'u', 'events' => ['*']], $backend->calls()[2]['body']);+ $client->webhooks->update('s', 'w1', ['active' => false]);+ $this->assertSame('PUT', $backend->calls()[3]['method']);+ $client->webhooks->delete('s', 'w1');+ $client->webhooks->test('s', 'w1');+ $this->assertStringContainsString('/webhooks/w1/test', $backend->calls()[5]['url']);+ }++ // ── Chats & Health ────────────────────────────────────────────────++ public function testChats(): void+ {+ $backend = new MockBackend();+ $backend->on(200, []);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->chats->list('s');+ $client->chats->markRead('s', ['chatId' => '[email protected]']);+ $this->assertStringContainsString('/chats/read', $backend->calls()[1]['url']);+ $client->chats->markUnread('s', ['chatId' => '[email protected]']);+ $client->chats->delete('s', ['chatId' => '[email protected]']);+ $client->chats->sendState('s', ['chatId' => '[email protected]', 'state' => 'typing']);+ $this->assertStringContainsString('/chats/typing', $backend->calls()[4]['url']);+ }++ public function testHealthAndAuth(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['status' => 'ok', 'version' => '0.7.2']);+ $backend->on(200, ['status' => 'ok']);+ $backend->on(200, ['status' => 'ok', 'details' => []]);+ $backend->on(200, ['valid' => true, 'role' => 'admin']);+ $client = $backend->makeClient();+ $client->health->check();+ $this->assertSame('/api/health', $backend->calls()[0]['path']);+ $client->health->live();+ $client->health->ready();+ $client->auth();+ $this->assertSame('POST', $backend->calls()[3]['method']);+ $this->assertStringContainsString('/auth/validate', $backend->calls()[3]['url']);+ }+}diff --git a/sdk/php/tests/TemplatesTest.php b/sdk/php/tests/TemplatesTest.phpnew file mode 100644index 000000000..a06f85fdb--- /dev/null+++ b/sdk/php/tests/TemplatesTest.php@@ -0,0 +1,39 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use PHPUnit\Framework\TestCase;++class TemplatesTest extends TestCase+{+ public function testCrudPaths(): void+ {+ $tpl = ['id' => 't1', 'sessionId' => 's', 'name' => 'welcome', 'body' => 'Hi {{name}}'];+ $backend = new MockBackend();+ $backend->on(200, [$tpl]); // list+ $backend->on(200, $tpl); // get+ $backend->on(201, $tpl); // create+ $backend->on(200, ['...' => 1] + $tpl); // update+ $backend->on(204); // delete+ $client = $backend->makeClient();++ $client->templates->list('s');+ $this->assertSame('/api/sessions/s/templates', $backend->calls()[0]['path']);++ $client->templates->get('s', 't1');+ $this->assertSame('/api/sessions/s/templates/t1', $backend->calls()[1]['path']);++ $client->templates->create('s', ['name' => 'welcome', 'body' => 'Hi {{name}}']);+ $this->assertSame('POST', $backend->calls()[2]['method']);+ $this->assertSame(['name' => 'welcome', 'body' => 'Hi {{name}}'], $backend->calls()[2]['body']);++ $client->templates->update('s', 't1', ['body' => 'Hello {{name}}']);+ $this->assertSame('PUT', $backend->calls()[3]['method']);+ $this->assertSame(['body' => 'Hello {{name}}'], $backend->calls()[3]['body']);++ $client->templates->delete('s', 't1');+ $this->assertSame('DELETE', $backend->lastCall()['method']);+ }+}diff --git a/sdk/python/.gitignore b/sdk/python/.gitignorenew file mode 100644index 000000000..a73de677f--- /dev/null+++ b/sdk/python/.gitignore@@ -0,0 +1,8 @@+__pycache__/+*.py[cod]+*.egg+*.egg-info/+.pytest_cache/+build/+dist/+.venv/diff --git a/sdk/python/openwa/__init__.py b/sdk/python/openwa/__init__.pyindex 2164a1f36..511c60afa 100644--- a/sdk/python/openwa/__init__.py+++ b/sdk/python/openwa/__init__.py@@ -1,5 +1,5 @@"""-OpenWA Python SDK+OpenWA Python SDK.Official client library for the OpenWA WhatsApp API Gateway.@@ -9,123 +9,41 @@ Example usage::client = OpenWAClient(base_url="http://localhost:2785",- api_key="your-api-key",+ api_key="owa_k1_…",)- # Send a text message- result = client.messages.send_text("session-1", {+ client.sessions.start("my-session")+ result = client.messages.send_text("my-session", {"chatId": "[email protected]",- "text": "Hello from OpenWA Python SDK!",+ "text": "Hello from the OpenWA Python SDK!",})+ print(result["messageId"])"""from __future__ import annotations-from dataclasses import dataclass, field-from typing import Any---@dataclass-class OpenWAClientConfig:- """Configuration for the OpenWA client."""-- base_url: str- api_key: str- timeout: float = 30.0---@dataclass-class MessageResponse:- """Response from sending a message."""-- message_id: str- timestamp: int---class OpenWAClient:- """OpenWA API client.-- This is a scaffold — methods will be auto-generated from the OpenAPI spec.- """-- def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:- self.config = OpenWAClientConfig(- base_url=base_url.rstrip("/"),- api_key=api_key,- timeout=timeout,- )-- # Placeholder — will be auto-generated from OpenAPI spec- @property- def sessions(self) -> "_SessionsResource":- return _SessionsResource(self)-- @property- def messages(self) -> "_MessagesResource":- return _MessagesResource(self)-- def _request(self, method: str, path: str, json: Any = None) -> Any:- """Internal HTTP request helper. Requires httpx."""- try:- import httpx- except ImportError:- raise ImportError(- "httpx is required for the OpenWA SDK. "- "Install it with: pip install openwa-sdk"- )-- with httpx.Client(timeout=self.config.timeout) as client:- response = client.request(- method,- f"{self.config.base_url}{path}",- headers={- "Content-Type": "application/json",- "X-API-Key": self.config.api_key,- },- json=json,- )- response.raise_for_status()-- if response.status_code == 204:- return None-- return response.json()---class _SessionsResource:- def __init__(self, client: OpenWAClient) -> None:- self._client = client-- def list(self) -> list[dict]:- return self._client._request("GET", "/api/sessions")-- def get(self, session_id: str) -> dict:- return self._client._request("GET", f"/api/sessions/{session_id}")-- def create(self, name: str) -> dict:- return self._client._request("POST", "/api/sessions", {"name": name})-- def start(self, session_id: str) -> dict:- return self._client._request("POST", f"/api/sessions/{session_id}/start")-- def stop(self, session_id: str) -> dict:- return self._client._request("POST", f"/api/sessions/{session_id}/stop")-- def delete(self, session_id: str) -> None:- self._client._request("DELETE", f"/api/sessions/{session_id}")---class _MessagesResource:- def __init__(self, client: OpenWAClient) -> None:- self._client = client-- def send_text(- self, session_id: str, data: dict[str, str]- ) -> MessageResponse:- result = self._client._request(- "POST", f"/api/sessions/{session_id}/messages/text", data- )- return MessageResponse(- message_id=result["messageId"],- timestamp=result["timestamp"],- )+from .client import OpenWAClient+from .errors import (+ OpenWAApiError,+ OpenWAAuthError,+ OpenWAConflictError,+ OpenWAError,+ OpenWAForbiddenError,+ OpenWANotFoundError,+ OpenWANotImplementedError,+ OpenWARateLimitError,+ OpenWATimeoutError,+)++__all__ = [+ "OpenWAClient",+ "OpenWAError",+ "OpenWAApiError",+ "OpenWAAuthError",+ "OpenWAForbiddenError",+ "OpenWANotFoundError",+ "OpenWAConflictError",+ "OpenWARateLimitError",+ "OpenWANotImplementedError",+ "OpenWATimeoutError",+]diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.pynew file mode 100644index 000000000..d8582b28a--- /dev/null+++ b/sdk/python/openwa/_http.py@@ -0,0 +1,115 @@+"""HTTP transport wrapper for the OpenWA Python SDK.++The client never builds a bare :class:`httpx.Client` with a hard-coded+transport. Instead it accepts an optional ``transport`` (an ``httpx.BaseTransport``)+that overrides the default. This makes the SDK trivially testable — a test+passes ``httpx.MockTransport(handler)`` instead of monkey-patching — and lets+consumers intercept/observability-wrap outbound calls.+"""++from __future__ import annotations++from typing import Any, Mapping+from urllib.parse import quote++import httpx++from .errors import OpenWAApiError, OpenWATimeoutError, classify++HttpMethod = str # "GET" | "POST" | "PUT" | "PATCH" | "DELETE"+++def quote_segment(segment: Any) -> str:+ """Percent-encode a single path segment so a value containing ``/``, ``#`` or+ ``?`` can't break out of its path position. WhatsApp-id characters that are+ already path-safe (``@``, ``:``, ``+``) are kept readable.+ """+ return quote(str(segment), safe="@:+")+++def build_url(base_url: str, path: str, query: Mapping[str, Any] | None = None) -> str:+ """Build a URL, serializing query params and skipping ``None`` values."""+ url = f"{base_url.rstrip('/')}{path}"+ if not query:+ return url++ def _serialize(v: Any) -> str:+ # Booleans must be lowercase: the backend reads query flags as `=== 'true'`,+ # so Python's default str(True) == 'True' would be silently ignored.+ if v is True:+ return "true"+ if v is False:+ return "false"+ return str(v)++ params = {k: _serialize(v) for k, v in query.items() if v is not None}+ if not params:+ return url+ req = httpx.Request("GET", url, params=params)+ # httpx.Request already encoded params into the URL string.+ return str(req.url)+++class HttpExecutor:+ """Owns the :class:`httpx.Client` and performs JSON requests.++ Constructed once per :class:`OpenWAClient`; the transport is taken from+ the client config so all requests share one connection pool.+ """++ def __init__(+ self,+ base_url: str,+ api_key: str,+ timeout: float = 30.0,+ default_headers: Mapping[str, str] | None = None,+ transport: httpx.BaseTransport | None = None,+ ) -> None:+ # Caller-supplied default headers are applied FIRST so the auth/JSON+ # headers below always win and can never be clobbered (mirrors the JS SDK).+ headers: dict[str, str] = {}+ if default_headers:+ headers.update(default_headers)+ headers["Content-Type"] = "application/json"+ headers["X-API-Key"] = api_key+ client_kwargs: dict[str, Any] = {+ "base_url": base_url.rstrip("/"),+ "headers": headers,+ "timeout": timeout,+ # Never auto-follow redirects: doing so would re-send the X-API-Key+ # header to the redirect target (potentially a different origin).+ # (This is also httpx's default; set explicitly so it can't regress.)+ "follow_redirects": False,+ }+ if transport is not None:+ client_kwargs["transport"] = transport+ self._client = httpx.Client(**client_kwargs)+ self._timeout = timeout++ def close(self) -> None:+ self._client.close()++ def __enter__(self) -> "HttpExecutor":+ return self++ def __exit__(self, *exc: Any) -> None:+ self.close()++ def request(self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None = None, body: Any = None) -> Any:+ """Perform one request and return the parsed JSON (or ``None`` for 204)."""+ url = build_url("", path, query)+ try:+ res = self._client.request(method, url, json=body if body is not None else None)+ except httpx.TimeoutException as e:+ raise OpenWATimeoutError(self._timeout) from e+ if res.status_code >= 400:+ context = f"{method} {path}"+ raise OpenWAApiError.from_response(res.status_code, res.text, context)+ if res.status_code == 204 or not res.content:+ return None+ try:+ return res.json()+ except ValueError:+ # A 2xx body that isn't JSON surfaces as text rather than a raw+ # JSONDecodeError (mirrors the JS and PHP transports).+ return res.textdiff --git a/sdk/python/openwa/client.py b/sdk/python/openwa/client.pynew file mode 100644index 000000000..504ce566a--- /dev/null+++ b/sdk/python/openwa/client.py@@ -0,0 +1,148 @@+"""OpenWA Python SDK — client core.++The :class:`OpenWAClient` is the single entry point. It owns an+:class:`HttpExecutor` (which wraps :class:`httpx.Client` with an injectable+transport) and exposes domain resources as properties::++ from openwa import OpenWAClient++ client = OpenWAClient(+ base_url="http://localhost:2785",+ api_key="owa_k1_…",+ )++ client.sessions.start("my-session")+ client.messages.send_text("my-session", {+ "chatId": "[email protected]",+ "text": "Hello from the OpenWA SDK!",+ })++Pass ``transport=httpx.MockTransport(handler)`` for testability — no global+monkey-patching required.+"""++from __future__ import annotations++from types import TracebackType+from typing import Any, Mapping++import httpx++from ._http import HttpExecutor, HttpMethod+from .resources import (+ CatalogResource,+ ChannelsResource,+ ChatsResource,+ ContactsResource,+ GroupsResource,+ HealthResource,+ LabelsResource,+ MessagesResource,+ SessionsResource,+ StatusResource,+ TemplatesResource,+ WebhooksResource,+)+from .types import AuthValidateResponse+++class OpenWAClient:+ def __init__(+ self,+ base_url: str,+ api_key: str,+ *,+ timeout: float = 30.0,+ default_headers: Mapping[str, str] | None = None,+ transport: httpx.BaseTransport | None = None,+ ) -> None:+ if not base_url:+ raise ValueError("OpenWAClient: base_url is required")+ if not api_key:+ raise ValueError("OpenWAClient: api_key is required")+ self._http = HttpExecutor(+ base_url=base_url,+ api_key=api_key,+ timeout=timeout,+ default_headers=default_headers,+ transport=transport,+ )++ # ── Resources ────────────────────────────────────────────────────++ @property+ def sessions(self) -> SessionsResource:+ return SessionsResource(self._http)++ @property+ def messages(self) -> MessagesResource:+ return MessagesResource(self._http)++ @property+ def contacts(self) -> ContactsResource:+ return ContactsResource(self._http)++ @property+ def groups(self) -> GroupsResource:+ return GroupsResource(self._http)++ @property+ def webhooks(self) -> WebhooksResource:+ return WebhooksResource(self._http)++ @property+ def chats(self) -> ChatsResource:+ return ChatsResource(self._http)++ @property+ def status(self) -> StatusResource:+ return StatusResource(self._http)++ @property+ def health(self) -> HealthResource:+ return HealthResource(self._http)++ @property+ def labels(self) -> LabelsResource:+ return LabelsResource(self._http)++ @property+ def channels(self) -> ChannelsResource:+ return ChannelsResource(self._http)++ @property+ def catalog(self) -> CatalogResource:+ return CatalogResource(self._http)++ @property+ def templates(self) -> TemplatesResource:+ return TemplatesResource(self._http)++ # ── Auth ─────────────────────────────────────────────────────────++ def auth(self) -> AuthValidateResponse:+ return self._http.request("POST", "/api/auth/validate")++ # ── Raw request escape hatch ─────────────────────────────────────++ def request(+ self,+ method: str,+ path: str,+ *,+ query: Mapping[str, Any] | None = None,+ body: Any = None,+ ) -> Any:+ """Issue a raw request against the API (advanced use). ``path`` begins with ``/``."""+ return self._http.request(method, path, query=query, body=body)++ # ── Lifecycle ────────────────────────────────────────────────────++ def close(self) -> None:+ self._http.close()++ def __enter__(self) -> "OpenWAClient":+ return self++ def __exit__(self, *exc: Any) -> None:+ self.close()diff --git a/sdk/python/openwa/errors.py b/sdk/python/openwa/errors.pynew file mode 100644index 000000000..9b3dfc8d2--- /dev/null+++ b/sdk/python/openwa/errors.py@@ -0,0 +1,99 @@+"""Typed error hierarchy for the OpenWA Python SDK.++The OpenWA API returns NestJS-default errors of the shape::++ {"statusCode": int, "message": str | list[str], "error": str}++This module maps that to a typed, ergonomic error tree so callers can+``isinstance``-check or branch on ``.status``.+"""++from __future__ import annotations++from typing import Any+++class OpenWAError(Exception):+ """Base class for every error raised by the SDK."""+++class OpenWAApiError(OpenWAError):+ """Raised when the API responds with a non-2xx status.++ Attributes:+ status: HTTP status code.+ body: Parsed JSON body if available, otherwise the raw text.+ error_kind: Value of the ``error`` field in the NestJS envelope.+ """++ def __init__(self, message: str, status: int, body: Any = None, error_kind: str | None = None) -> None:+ super().__init__(message)+ self.status = status+ self.body = body+ self.error_kind = error_kind++ @classmethod+ def from_response(cls, status_code: int, text: str, context: str) -> "OpenWAApiError":+ import json++ body: Any = None+ if text:+ try:+ body = json.loads(text)+ except ValueError:+ body = text+ envelope = body if isinstance(body, dict) and "statusCode" in body else None+ raw_message = envelope.get("message") if envelope else body+ if isinstance(raw_message, list):+ message_text = ", ".join(str(m) for m in raw_message)+ elif isinstance(raw_message, str):+ message_text = raw_message+ else:+ message_text = str(raw_message)+ message = f"OpenWA API {status_code} — {context}: {message_text}"+ return classify(status_code, message, body, envelope.get("error") if envelope else None)+++class OpenWAAuthError(OpenWAApiError):+ """401 Unauthorized — missing or invalid API key."""+++class OpenWAForbiddenError(OpenWAApiError):+ """403 Forbidden — insufficient role."""+++class OpenWANotFoundError(OpenWAApiError):+ """404 Not Found."""+++class OpenWAConflictError(OpenWAApiError):+ """409 Conflict — typically an engine-not-ready condition."""+++class OpenWARateLimitError(OpenWAApiError):+ """429 Too Many Requests."""+++class OpenWANotImplementedError(OpenWAApiError):+ """501 Not Implemented — the active engine does not support this operation."""+++class OpenWATimeoutError(OpenWAError):+ """Raised when a request exceeds the configured timeout."""++ def __init__(self, timeout: float) -> None:+ super().__init__(f"Request timed out after {timeout}s")+ self.timeout = timeout+++def classify(status: int, message: str, body: Any, error_kind: str | None) -> OpenWAApiError:+ """Pick the most specific :class:`OpenWAApiError` subclass for a status."""+ cls = {+ 401: OpenWAAuthError,+ 403: OpenWAForbiddenError,+ 404: OpenWANotFoundError,+ 409: OpenWAConflictError,+ 429: OpenWARateLimitError,+ 501: OpenWANotImplementedError,+ }.get(status, OpenWAApiError)+ return cls(message, status, body, error_kind)diff --git a/sdk/python/openwa/py.typed b/sdk/python/openwa/py.typednew file mode 100644index 000000000..e69de29bbdiff --git a/sdk/python/openwa/resources/__init__.py b/sdk/python/openwa/resources/__init__.pynew file mode 100644index 000000000..917b37fe6--- /dev/null+++ b/sdk/python/openwa/resources/__init__.py@@ -0,0 +1,35 @@+"""Resource modules for the OpenWA Python SDK.++Each module defines a small ``_*Resource`` class whose methods map 1:1 to an+API path group. They are constructed by :class:`openwa.client.OpenWAClient`.+"""++from __future__ import annotations++from .catalog import CatalogResource+from .channels import ChannelsResource+from .chats import ChatsResource+from .contacts import ContactsResource+from .groups import GroupsResource+from .health import HealthResource+from .labels import LabelsResource+from .messages import MessagesResource+from .sessions import SessionsResource+from .status import StatusResource+from .templates import TemplatesResource+from .webhooks import WebhooksResource++__all__ = [+ "CatalogResource",+ "ChannelsResource",+ "ChatsResource",+ "ContactsResource",+ "GroupsResource",+ "HealthResource",+ "LabelsResource",+ "MessagesResource",+ "SessionsResource",+ "StatusResource",+ "TemplatesResource",+ "WebhooksResource",+]diff --git a/sdk/python/openwa/resources/catalog.py b/sdk/python/openwa/resources/catalog.pynew file mode 100644index 000000000..3de8ba5d1--- /dev/null+++ b/sdk/python/openwa/resources/catalog.py@@ -0,0 +1,58 @@+"""Catalog resource — WhatsApp Business catalog, products, and product/catalog sends.++Backed by ``src/modules/catalog/catalog.controller.ts``+(``@Controller('sessions/:sessionId')``). NOTE: the catalog controller is+mounted under the session root, so catalog reads are ``/catalog...`` while+product/catalog SENDS share the messages namespace+(``/messages/send-product``, ``/messages/send-catalog``).+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import (+ CatalogInfo,+ CatalogProduct,+ CatalogProductsQuery,+ MessageResponse,+ PaginatedProducts,+ SendCatalogRequest,+ SendProductRequest,+)++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class CatalogResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def info(self, session_id: str) -> CatalogInfo:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/catalog")++ def products(+ self, session_id: str, query: CatalogProductsQuery | None = None+ ) -> PaginatedProducts:+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/catalog/products", query=query+ )++ def product(self, session_id: str, product_id: str) -> CatalogProduct:+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/catalog/products/{quote_segment(product_id)}"+ )++ def send_product(self, session_id: str, body: SendProductRequest) -> MessageResponse:+ """Send a product message. Requires an OPERATOR-level key. Shares the messages path."""+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-product", body=body+ )++ def send_catalog(self, session_id: str, body: SendCatalogRequest) -> MessageResponse:+ """Send a catalog link message. Requires an OPERATOR-level key. Shares the messages path."""+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-catalog", body=body+ )diff --git a/sdk/python/openwa/resources/channels.py b/sdk/python/openwa/resources/channels.pynew file mode 100644index 000000000..a0d440424--- /dev/null+++ b/sdk/python/openwa/resources/channels.py@@ -0,0 +1,41 @@+"""Channels resource — WhatsApp Channels / Newsletters.++Backed by ``src/modules/channel/channel.controller.ts``+(``@Controller('sessions/:sessionId/channels')``).+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import ChannelMessageQuery, ChannelRecord, MessageRecord, SubscribeChannelRequest, SuccessResult++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class ChannelsResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str) -> list[ChannelRecord]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/channels")++ def get(self, session_id: str, channel_id: str) -> ChannelRecord:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/channels/{quote_segment(channel_id)}")++ def messages(+ self, session_id: str, channel_id: str, query: ChannelMessageQuery | None = None+ ) -> list[MessageRecord]:+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/channels/{quote_segment(channel_id)}/messages", query=query+ )++ def subscribe(self, session_id: str, body: SubscribeChannelRequest) -> ChannelRecord:+ """Subscribe to a channel using its invite code. Requires an OPERATOR-level key."""+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/channels/subscribe", body=body)++ def unsubscribe(self, session_id: str, channel_id: str) -> SuccessResult:+ """Unsubscribe from a channel. Requires an OPERATOR-level key."""+ return self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}/channels/{quote_segment(channel_id)}")diff --git a/sdk/python/openwa/resources/chats.py b/sdk/python/openwa/resources/chats.pynew file mode 100644index 000000000..8aa5c1bae--- /dev/null+++ b/sdk/python/openwa/resources/chats.py@@ -0,0 +1,46 @@+"""Chats resource — chat-list operations (read/unread/delete/typing state).++These endpoints live under the session controller (``/api/sessions/:id/chats/*``)+but are surfaced here as a dedicated resource for clarity.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, TypedDict++from .._http import quote_segment+from ..types import (+ ChatSummary,+ DeleteChatRequest,+ MarkChatRequest,+ SendChatStateRequest,+ SuccessResult,+)++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class ListChatsQuery(TypedDict, total=False):+ limit: int+ offset: int+++class ChatsResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str, query: ListChatsQuery | None = None) -> list[ChatSummary]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/chats", query=query)++ def mark_read(self, session_id: str, body: MarkChatRequest) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/read", body=body)++ def mark_unread(self, session_id: str, body: MarkChatRequest) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/unread", body=body)++ def delete(self, session_id: str, body: DeleteChatRequest) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/delete", body=body)++ def send_state(self, session_id: str, body: SendChatStateRequest) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/typing", body=body)diff --git a/sdk/python/openwa/resources/contacts.py b/sdk/python/openwa/resources/contacts.pynew file mode 100644index 000000000..02acac8a3--- /dev/null+++ b/sdk/python/openwa/resources/contacts.py@@ -0,0 +1,53 @@+"""Contacts resource — contact lookup and management.++Backed by ``src/modules/contact/contact.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, TypedDict++from .._http import quote_segment+from ..types import (+ CheckNumberResponse,+ ContactPhoneResponse,+ ContactRecord,+ ProfilePictureResponse,+ SuccessResult,+)++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class ListContactsQuery(TypedDict, total=False):+ limit: int+ offset: int+++class ContactsResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str, query: ListContactsQuery | None = None) -> list[ContactRecord]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/contacts", query=query)++ def get(self, session_id: str, contact_id: str) -> ContactRecord:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}")++ def check(self, session_id: str, number: str) -> CheckNumberResponse:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/contacts/check/{quote_segment(number)}")++ def profile_picture(self, session_id: str, contact_id: str) -> ProfilePictureResponse:+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/profile-picture"+ )++ def phone(self, session_id: str, contact_id: str) -> ContactPhoneResponse:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/phone")++ def block(self, session_id: str, contact_id: str) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/block")++ def unblock(self, session_id: str, contact_id: str) -> SuccessResult:+ return self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/block")diff --git a/sdk/python/openwa/resources/groups.py b/sdk/python/openwa/resources/groups.pynew file mode 100644index 000000000..5494cab8a--- /dev/null+++ b/sdk/python/openwa/resources/groups.py@@ -0,0 +1,87 @@+"""Groups resource — WhatsApp group management.++Backed by ``src/modules/group/group.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, TypedDict++from .._http import quote_segment+from ..types import (+ CreateGroupRequest,+ GroupInfo,+ GroupSummary,+ InviteCodeResponse,+ SuccessResult,+)++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class ListGroupsQuery(TypedDict, total=False):+ limit: int+ offset: int+++class GroupsResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str, query: ListGroupsQuery | None = None) -> list[GroupSummary]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/groups", query=query)++ def get(self, session_id: str, group_id: str) -> GroupInfo:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}")++ def create(self, session_id: str, body: CreateGroupRequest) -> GroupInfo:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/groups", body=body)++ def add_participants(self, session_id: str, group_id: str, participants: list[str]) -> SuccessResult:+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/participants",+ body={"participants": participants},+ )++ def remove_participants(self, session_id: str, group_id: str, participants: list[str]) -> SuccessResult:+ return self._http.request(+ "DELETE", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/participants",+ body={"participants": participants},+ )++ def promote_participants(self, session_id: str, group_id: str, participants: list[str]) -> SuccessResult:+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/participants/promote",+ body={"participants": participants},+ )++ def demote_participants(self, session_id: str, group_id: str, participants: list[str]) -> SuccessResult:+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/participants/demote",+ body={"participants": participants},+ )++ def set_subject(self, session_id: str, group_id: str, subject: str) -> SuccessResult:+ return self._http.request(+ "PUT", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/subject", body={"subject": subject}+ )++ def set_description(self, session_id: str, group_id: str, description: str) -> SuccessResult:+ return self._http.request(+ "PUT", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/description",+ body={"description": description},+ )++ def leave(self, session_id: str, group_id: str) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/leave")++ def invite_code(self, session_id: str, group_id: str) -> InviteCodeResponse:+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/invite-code"+ )++ def revoke_invite_code(self, session_id: str, group_id: str) -> InviteCodeResponse:+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/invite-code/revoke"+ )diff --git a/sdk/python/openwa/resources/health.py b/sdk/python/openwa/resources/health.pynew file mode 100644index 000000000..77b4a63e7--- /dev/null+++ b/sdk/python/openwa/resources/health.py@@ -0,0 +1,27 @@+"""Health resource — connectivity and readiness probes.++Backed by ``src/modules/health/health.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from ..types import HealthReadyResponse, HealthResponse++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class HealthResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def check(self) -> HealthResponse:+ return self._http.request("GET", "/api/health")++ def live(self) -> dict[str, str]:+ return self._http.request("GET", "/api/health/live")++ def ready(self) -> HealthReadyResponse:+ return self._http.request("GET", "/api/health/ready")diff --git a/sdk/python/openwa/resources/labels.py b/sdk/python/openwa/resources/labels.pynew file mode 100644index 000000000..f59efbe88--- /dev/null+++ b/sdk/python/openwa/resources/labels.py@@ -0,0 +1,40 @@+"""Labels resource — WhatsApp Business chat labels.++Backed by ``src/modules/label/label.controller.ts``+(``@Controller('sessions/:sessionId/labels')``). Labels are a WhatsApp Business+feature; the session must be a business account.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import AddLabelRequest, LabelRecord, SuccessResult++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class LabelsResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str) -> list[LabelRecord]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/labels")++ def get(self, session_id: str, label_id: str) -> LabelRecord:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/labels/{quote_segment(label_id)}")++ def for_chat(self, session_id: str, chat_id: str) -> list[LabelRecord]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/labels/chat/{quote_segment(chat_id)}")++ def add_to_chat(self, session_id: str, chat_id: str, body: AddLabelRequest) -> SuccessResult:+ """Add a label to a chat. Requires an OPERATOR-level key."""+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/labels/chat/{quote_segment(chat_id)}", body=body)++ def remove_from_chat(self, session_id: str, chat_id: str, label_id: str) -> SuccessResult:+ """Remove a label from a chat. Requires an OPERATOR-level key."""+ return self._http.request(+ "DELETE", f"/api/sessions/{quote_segment(session_id)}/labels/chat/{quote_segment(chat_id)}/{quote_segment(label_id)}"+ )diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.pynew file mode 100644index 000000000..b04070de9--- /dev/null+++ b/sdk/python/openwa/resources/messages.py@@ -0,0 +1,109 @@+"""Messages resource — sending and querying messages.++Backed by ``src/modules/message/message.controller.ts``.+NOTE: the real paths use the ``/send-`` prefix, e.g. ``/messages/send-text``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import (+ BatchStatusResponse,+ BulkMessageResponse,+ ChatHistoryMessage,+ DeleteMessageRequest,+ ForwardMessageRequest,+ ListMessagesQuery,+ MessageHistoryQuery,+ MessageListResponse,+ MessageResponse,+ ReactionRecord,+ ReactMessageRequest,+ ReplyMessageRequest,+ SendBulkRequest,+ SendContactRequest,+ SendLocationRequest,+ SendMediaRequest,+ SendTemplateRequest,+ SendTextRequest,+ SuccessResult,+)++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class MessagesResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str, query: ListMessagesQuery | None = None) -> MessageListResponse:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/messages", query=query)++ def send_text(self, session_id: str, body: SendTextRequest) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-text", body=body)++ def send_image(self, session_id: str, body: SendMediaRequest) -> MessageResponse:+ return self._send_media(session_id, "send-image", body)++ def send_video(self, session_id: str, body: SendMediaRequest) -> MessageResponse:+ return self._send_media(session_id, "send-video", body)++ def send_audio(self, session_id: str, body: SendMediaRequest) -> MessageResponse:+ return self._send_media(session_id, "send-audio", body)++ def send_document(self, session_id: str, body: SendMediaRequest) -> MessageResponse:+ return self._send_media(session_id, "send-document", body)++ def send_sticker(self, session_id: str, body: SendMediaRequest) -> MessageResponse:+ return self._send_media(session_id, "send-sticker", body)++ def _send_media(self, session_id: str, segment: str, body: SendMediaRequest) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(segment)}", body=body)++ def send_location(self, session_id: str, body: SendLocationRequest) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-location", body=body)++ def send_contact(self, session_id: str, body: SendContactRequest) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-contact", body=body)++ def send_template(self, session_id: str, body: SendTemplateRequest) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-template", body=body)++ def reply(self, session_id: str, body: ReplyMessageRequest) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/reply", body=body)++ def forward(self, session_id: str, body: ForwardMessageRequest) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/forward", body=body)++ def react(self, session_id: str, body: ReactMessageRequest) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/react", body=body)++ def delete(self, session_id: str, body: DeleteMessageRequest) -> SuccessResult:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/delete", body=body)++ def history(+ self, session_id: str, chat_id: str, query: MessageHistoryQuery | None = None+ ) -> list[ChatHistoryMessage]:+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(chat_id)}/history", query=query+ )++ def reactions(self, session_id: str, chat_id: str, message_id: str) -> list[ReactionRecord]:+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(chat_id)}/{quote_segment(message_id)}/reactions"+ )++ def send_bulk(self, session_id: str, body: SendBulkRequest) -> BulkMessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-bulk", body=body)++ def batch_status(self, session_id: str, batch_id: str) -> BatchStatusResponse:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/messages/batch/{quote_segment(batch_id)}")++ def cancel_batch(self, session_id: str, batch_id: str) -> BatchStatusResponse:+ """Cancel a running batch. Requires an OPERATOR-level key."""+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/messages/batch/{quote_segment(batch_id)}/cancel"+ )diff --git a/sdk/python/openwa/resources/py.typed b/sdk/python/openwa/resources/py.typednew file mode 100644index 000000000..e69de29bbdiff --git a/sdk/python/openwa/resources/sessions.py b/sdk/python/openwa/resources/sessions.pynew file mode 100644index 000000000..025c175e1--- /dev/null+++ b/sdk/python/openwa/resources/sessions.py@@ -0,0 +1,56 @@+"""Sessions resource — lifecycle management for WhatsApp sessions.++Backed by ``src/modules/session/session.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import (+ CreateSessionRequest,+ PairingCodeResponse,+ QrCodeResponse,+ RequestPairingCodeRequest,+ SessionResponse,+ SessionStatsOverview,+)++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class SessionsResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self) -> list[SessionResponse]:+ return self._http.request("GET", "/api/sessions")++ def get(self, session_id: str) -> SessionResponse:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}")++ def create(self, body: CreateSessionRequest) -> SessionResponse:+ return self._http.request("POST", "/api/sessions", body=body)++ def delete(self, session_id: str) -> None:+ self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}")++ def start(self, session_id: str) -> SessionResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/start")++ def stop(self, session_id: str) -> SessionResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/stop")++ def force_kill(self, session_id: str) -> SessionResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/force-kill")++ def get_qr_code(self, session_id: str) -> QrCodeResponse:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/qr")++ def request_pairing_code(self, session_id: str, body: RequestPairingCodeRequest) -> PairingCodeResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/pairing-code", body=body)++ def stats(self) -> SessionStatsOverview:+ return self._http.request("GET", "/api/sessions/stats/overview")diff --git a/sdk/python/openwa/resources/status.py b/sdk/python/openwa/resources/status.pynew file mode 100644index 000000000..0ded81b24--- /dev/null+++ b/sdk/python/openwa/resources/status.py@@ -0,0 +1,38 @@+"""Status (Stories) resource — WhatsApp status updates.++Backed by ``src/modules/status/status.controller.ts``.+NOTE: this is WhatsApp "Status/Stories", distinct from session lifecycle status.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import SendImageStatusRequest, SendTextStatusRequest, SendVideoStatusRequest, StatusRecord++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class StatusResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str) -> dict[str, list[StatusRecord]]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/status")++ def from_contact(self, session_id: str, contact_id: str) -> dict[str, list[StatusRecord]]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/status/{quote_segment(contact_id)}")++ def send_text(self, session_id: str, body: SendTextStatusRequest) -> StatusRecord:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/status/send-text", body=body)++ def send_image(self, session_id: str, body: SendImageStatusRequest) -> StatusRecord:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/status/send-image", body=body)++ def send_video(self, session_id: str, body: SendVideoStatusRequest) -> StatusRecord:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/status/send-video", body=body)++ def delete(self, session_id: str, status_id: str) -> None:+ self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}/status/{quote_segment(status_id)}")diff --git a/sdk/python/openwa/resources/templates.py b/sdk/python/openwa/resources/templates.pynew file mode 100644index 000000000..2b5f69c1c--- /dev/null+++ b/sdk/python/openwa/resources/templates.py@@ -0,0 +1,34 @@+"""Templates resource — stored message templates with ``{{variable}}`` placeholders.++Backed by ``src/modules/template/template.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import CreateTemplateRequest, TemplateRecord, UpdateTemplateRequest++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class TemplatesResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str) -> list[TemplateRecord]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/templates")++ def get(self, session_id: str, template_id: str) -> TemplateRecord:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/templates/{quote_segment(template_id)}")++ def create(self, session_id: str, body: CreateTemplateRequest) -> TemplateRecord:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/templates", body=body)++ def update(self, session_id: str, template_id: str, body: UpdateTemplateRequest) -> TemplateRecord:+ return self._http.request("PUT", f"/api/sessions/{quote_segment(session_id)}/templates/{quote_segment(template_id)}", body=body)++ def delete(self, session_id: str, template_id: str) -> None:+ self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}/templates/{quote_segment(template_id)}")diff --git a/sdk/python/openwa/resources/webhooks.py b/sdk/python/openwa/resources/webhooks.pynew file mode 100644index 000000000..8783a3d21--- /dev/null+++ b/sdk/python/openwa/resources/webhooks.py@@ -0,0 +1,41 @@+"""Webhooks resource — configure event delivery to external HTTP endpoints.++Backed by ``src/modules/webhook/webhook.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import CreateWebhookRequest, UpdateWebhookRequest, WebhookResponse, WebhookTestResult++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class WebhooksResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def list(self, session_id: str) -> list[WebhookResponse]:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/webhooks")++ def get(self, session_id: str, webhook_id: str) -> WebhookResponse:+ return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/webhooks/{quote_segment(webhook_id)}")++ def create(self, session_id: str, body: CreateWebhookRequest) -> WebhookResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/webhooks", body=body)++ def update(self, session_id: str, webhook_id: str, body: UpdateWebhookRequest) -> WebhookResponse:+ return self._http.request(+ "PUT", f"/api/sessions/{quote_segment(session_id)}/webhooks/{quote_segment(webhook_id)}", body=body+ )++ def delete(self, session_id: str, webhook_id: str) -> None:+ self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}/webhooks/{quote_segment(webhook_id)}")++ def test(self, session_id: str, webhook_id: str) -> WebhookTestResult:+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/webhooks/{quote_segment(webhook_id)}/test"+ )diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pynew file mode 100644index 000000000..55c68a9dc--- /dev/null+++ b/sdk/python/openwa/types.py@@ -0,0 +1,673 @@+"""Wire type definitions for the OpenWA API.++Hybrid codegen strategy: this module is the single source of truth for wire+types — the part most prone to drift with the backend. It is structured so it+can be regenerated by an OpenAPI codegen pass later without touching the+hand-written resource methods (paths + DX live elsewhere).++Field names mirror the backend DTOs exactly (camelCase JSON).+"""++from __future__ import annotations++from typing import Any, Literal, Optional, TypedDict++Jid = str+SessionStatus = Literal[+ "created", "initializing", "qr_ready", "authenticating", "ready", "disconnected", "failed"+]+ChatState = Literal["typing", "recording", "paused"]+MessageDirection = Literal["incoming", "outgoing"]+DeliveryStatus = Literal["pending", "sent", "delivered", "read", "failed"]+BulkMessageType = Literal["text", "image", "video", "audio", "document"]+WebhookEvent = Literal[+ "message.received", "message.sent", "message.ack", "message.failed", "message.revoked",+ "message.reaction", "session.status", "session.qr", "session.authenticated",+ "session.disconnected",+ # Reserved: accepted on subscribe but not dispatched yet.+ "group.join", "group.leave", "group.update",+ "*",+]+++class SuccessResult(TypedDict, total=False):+ success: bool+ message: str+++# ── Session ───────────────────────────────────────────────────────+++class SessionResponse(TypedDict, total=False):+ id: str+ name: str+ status: SessionStatus+ phone: str | None+ pushName: str | None+ connectedAt: str | None+ lastActive: str | None+ createdAt: str+ updatedAt: str+ lastError: str | None+++class CreateSessionRequest(TypedDict, total=False):+ name: str+ config: dict[str, Any]+ proxyUrl: str+ proxyType: Literal["http", "https", "socks4", "socks5"]+++class QrCodeResponse(TypedDict):+ qrCode: str+ status: SessionStatus+++class PairingCodeResponse(TypedDict):+ pairingCode: str+ status: str+++class RequestPairingCodeRequest(TypedDict):+ phoneNumber: str+++class MemoryUsage(TypedDict):+ heapUsed: int+ heapTotal: int+ rss: int+++class SessionStatsOverview(TypedDict, total=False):+ total: int+ active: int+ ready: int+ disconnected: int+ byStatus: dict[str, int]+ memoryUsage: MemoryUsage+++# ── Message ───────────────────────────────────────────────────────+++class MessageResponse(TypedDict):+ messageId: str+ timestamp: int+++class SendTextRequest(TypedDict):+ chatId: Jid+ text: str+++class SendMediaRequest(TypedDict, total=False):+ chatId: Jid+ url: str+ base64: str+ mimetype: str+ filename: str+ caption: str+++class SendLocationRequest(TypedDict, total=False):+ # chatId/latitude/longitude required; description/address optional.+ chatId: Jid+ latitude: float+ longitude: float+ description: str+ address: str+++class SendContactRequest(TypedDict):+ chatId: Jid+ contactName: str+ contactNumber: str+++class ReplyMessageRequest(TypedDict):+ chatId: Jid+ quotedMessageId: str+ text: str+++class ForwardMessageRequest(TypedDict):+ fromChatId: Jid+ toChatId: Jid+ messageId: str+++class ReactMessageRequest(TypedDict):+ chatId: Jid+ messageId: str+ emoji: str+++class DeleteMessageRequest(TypedDict, total=False):+ # chatId/messageId required; forEveryone optional (default true).+ chatId: Jid+ messageId: str+ forEveryone: bool+++class SendTemplateRequest(TypedDict, total=False):+ # chatId required; provide exactly one of templateId / templateName.+ # Modeled total=False (callers pass plain dicts); the backend validates.+ chatId: Jid+ templateId: str+ templateName: str+ vars: dict[str, str]+++# ``from`` is a Python keyword, so use the functional TypedDict form.+ListMessagesQuery = TypedDict(+ "ListMessagesQuery",+ {"chatId": Jid, "from": Jid, "limit": int, "offset": int},+ total=False,+)+++class MessageHistoryQuery(TypedDict, total=False):+ limit: int+ includeMedia: bool+ deep: bool+++# ``from`` is a Python keyword, so use the functional TypedDict form (and+# Optional[...] rather than ``X | None`` so the runtime values stay 3.9-safe).+MessageRecord = TypedDict(+ "MessageRecord",+ {+ "id": str,+ "sessionId": str,+ "waMessageId": Optional[str],+ "chatId": Jid,+ "from": Jid,+ "to": Jid,+ "body": Optional[str],+ "type": str,+ "direction": MessageDirection,+ "timestamp": Optional[int],+ "metadata": dict,+ "status": DeliveryStatus,+ "createdAt": str,+ },+ total=False,+)+++class ChatHistoryMedia(TypedDict, total=False):+ mimetype: str+ filename: str+ data: str # base64; absent when the payload was omitted (too large)+ omitted: bool+ sizeBytes: int+++class QuotedMessage(TypedDict, total=False):+ id: str+ body: str+++class MessageLocation(TypedDict, total=False):+ latitude: float+ longitude: float+ description: str+ address: str+ url: str+++# A message read live from WhatsApp by ``messages.history()`` — the engine+# payload, richer and differently shaped than the persisted MessageRecord.+ChatHistoryMessage = TypedDict(+ "ChatHistoryMessage",+ {+ "id": str,+ "from": Jid,+ "to": Jid,+ "chatId": Jid,+ "body": str,+ "type": str,+ "timestamp": int,+ "fromMe": bool,+ "isGroup": bool,+ "isStatusBroadcast": bool,+ "author": Jid,+ "mentionedIds": list,+ "isLidSender": bool,+ "senderPhone": Optional[str],+ "media": ChatHistoryMedia,+ "quotedMessage": QuotedMessage,+ "location": MessageLocation,+ },+ total=False,+)+++class MessageListResponse(TypedDict):+ """Paginated payload returned by ``GET /sessions/:id/messages``."""++ messages: list[MessageRecord]+ total: int+++class ReactionSender(TypedDict, total=False):+ senderId: Jid+ emoji: str+ timestamp: int+++class ReactionRecord(TypedDict, total=False):+ """One emoji and everyone who reacted with it (server returns MessageReaction[])."""++ emoji: str+ senders: list[ReactionSender]+++# ── Bulk ──────────────────────────────────────────────────────────+++class BulkMessageContent(TypedDict, total=False):+ text: str+ image: SendMediaRequest+ video: SendMediaRequest+ audio: SendMediaRequest+ document: SendMediaRequest+ caption: str+++class BulkMessageItem(TypedDict, total=False):+ # chatId/type/content required; variables optional.+ chatId: Jid+ type: BulkMessageType+ content: BulkMessageContent+ variables: dict[str, str]+++class BulkOptions(TypedDict, total=False):+ delayBetweenMessages: int+ randomizeDelay: bool+ stopOnError: bool+++class _SendBulkRequired(TypedDict):+ messages: list[BulkMessageItem]+++class SendBulkRequest(_SendBulkRequired, total=False):+ # `options` and `batchId` are optional; the backend applies defaults.+ options: BulkOptions+ batchId: str+++class BulkMessageResponse(TypedDict):+ batchId: str+ status: str+ totalMessages: int+ estimatedCompletionTime: str+ statusUrl: str+++class BatchError(TypedDict, total=False):+ code: str+ message: str+++class BatchMessageResult(TypedDict, total=False):+ chatId: Jid+ status: str+ messageId: str+ sentAt: str+ error: BatchError+++class BatchProgress(TypedDict, total=False):+ total: int+ sent: int+ failed: int+ pending: int+ cancelled: int+++class BatchStatusResponse(TypedDict, total=False):+ """Response from ``GET /messages/batch/:batchId`` and the cancel endpoint.++ Distinct from :class:`BulkMessageResponse` (the send-bulk acknowledgement).+ """++ batchId: str+ status: str+ progress: BatchProgress+ results: list[BatchMessageResult]+ startedAt: str+ completedAt: str+++# ── Contact ───────────────────────────────────────────────────────+++class ContactRecord(TypedDict, total=False):+ id: Jid+ name: str | None+ number: str | None+ pushname: str | None+ isBusiness: bool+ isMyContact: bool+++class CheckNumberResponse(TypedDict):+ number: str+ exists: bool+ whatsappId: str | None+++class ProfilePictureResponse(TypedDict):+ url: str | None+++class ContactPhoneResponse(TypedDict):+ contactId: Jid+ phone: str | None+++# ── Group ─────────────────────────────────────────────────────────+++class GroupParticipant(TypedDict, total=False):+ id: Jid+ number: str+ name: str+ isAdmin: bool+ isSuperAdmin: bool+++class GroupSummary(TypedDict, total=False):+ """Item returned by ``GET /sessions/:id/groups`` (the slim list shape)."""++ id: Jid+ name: str+ participantsCount: int+ isAdmin: bool+ linkedParentJID: str | None+++class GroupInfo(TypedDict, total=False):+ """Full detail returned by ``GET /sessions/:id/groups/:groupId``."""++ id: Jid+ name: str+ description: str | None+ owner: Jid | None+ createdAt: int+ participants: list[GroupParticipant]+ isReadOnly: bool+ isAnnounce: bool+ linkedParentJID: str | None+++class CreateGroupRequest(TypedDict):+ name: str+ participants: list[Jid]+++class InviteCodeResponse(TypedDict, total=False):+ inviteCode: str+ inviteLink: str+ message: str+++# ── Webhook ───────────────────────────────────────────────────────+++class WebhookFilterCondition(TypedDict):+ field: str+ operator: str+ value: list[str]+++class WebhookFilters(TypedDict):+ conditions: list[WebhookFilterCondition]+++class CreateWebhookRequest(TypedDict, total=False):+ url: str+ events: list[WebhookEvent]+ secret: str+ headers: dict[str, str]+ filters: WebhookFilters | None+ # Server DTO field is ``retryCount`` (0–5; default 3).+ retryCount: int+++class UpdateWebhookRequest(CreateWebhookRequest, total=False):+ active: bool+++class WebhookResponse(TypedDict, total=False):+ id: str+ sessionId: str+ url: str+ events: list[WebhookEvent]+ active: bool+ filters: WebhookFilters | None+ retryCount: int+ # ISO timestamp of the last delivery attempt, or None if never triggered.+ lastTriggeredAt: str | None+ createdAt: str+ updatedAt: str+ # NOTE: the server deliberately omits ``secret`` and ``headers`` from reads.+++class WebhookTestResult(TypedDict, total=False):+ success: bool+ statusCode: int+ error: str+++# ── Chat ──────────────────────────────────────────────────────────+++class ChatSummary(TypedDict, total=False):+ id: Jid+ name: str | None+ isGroup: bool+ unreadCount: int+ # Server returns a plain preview string, not a message object.+ lastMessage: str+ timestamp: str | int+++class MarkChatRequest(TypedDict):+ chatId: Jid+++class SendChatStateRequest(TypedDict):+ chatId: Jid+ state: ChatState+++class DeleteChatRequest(TypedDict):+ chatId: Jid+++# ── Status / Stories ──────────────────────────────────────────────+++class StatusRecord(TypedDict, total=False):+ id: str+ statusId: str+ type: str+ body: str | None+ timestamp: str | int+++class SendTextStatusRequest(TypedDict, total=False):+ # text required; backgroundColor (hex, e.g. #25D366) and font optional.+ text: str+ backgroundColor: str+ font: int+++class StatusMediaInput(TypedDict, total=False):+ """Media payload for a status post: provide ``url`` OR ``base64``."""++ url: str+ base64: str+++class SendImageStatusRequest(TypedDict, total=False):+ """Server expects a nested ``{ image: { url|base64 } }`` body."""++ image: StatusMediaInput+ caption: str+++class SendVideoStatusRequest(TypedDict, total=False):+ """Server expects a nested ``{ video: { url|base64 } }`` body."""++ video: StatusMediaInput+ caption: str+++# ── Health ────────────────────────────────────────────────────────+++class HealthResponse(TypedDict, total=False):+ status: str+ timestamp: str+ version: str+++class HealthReadyResponse(TypedDict, total=False):+ status: str+ details: dict[str, str]+++# ── Auth ──────────────────────────────────────────────────────────+++class AuthValidateResponse(TypedDict, total=False):+ valid: bool+ role: str+++# ── Template ──────────────────────────────────────────────────────+++class TemplateRecord(TypedDict, total=False):+ id: str+ sessionId: str+ name: str+ body: str # template body with {{variable}} placeholders+ header: str | None+ footer: str | None+ createdAt: str+ updatedAt: str+++class CreateTemplateRequest(TypedDict, total=False):+ # name + body required; header/footer optional. Modeled total=False+ # (callers pass plain dicts); the backend validates the required fields.+ name: str+ body: str+ header: str+ footer: str+++class UpdateTemplateRequest(TypedDict, total=False):+ name: str+ body: str+ header: str+ footer: str+++# ── Label (WhatsApp Business) ─────────────────────────────────────+++class LabelRecord(TypedDict, total=False):+ id: str+ name: str+ color: str+ colorHex: str+++class AddLabelRequest(TypedDict):+ labelId: str+++# ── Channel / Newsletter ──────────────────────────────────────────+++class ChannelRecord(TypedDict, total=False):+ id: Jid+ name: str+ description: str | None+ subscriberCount: int+ pictureUrl: str | None+ role: str+++class ChannelMessageQuery(TypedDict, total=False):+ """Max messages to return (default 50)."""++ limit: int+++class SubscribeChannelRequest(TypedDict):+ inviteCode: str+++# ── Catalog (Business) ────────────────────────────────────────────+++class CatalogInfo(TypedDict, total=False):+ id: str+ name: str+ description: str | None+ productCount: int+ url: str+++class CatalogProductsQuery(TypedDict, total=False):+ page: int+ limit: int+++class CatalogProduct(TypedDict, total=False):+ id: str+ name: str+ description: str | None+ price: float+ currency: str+ priceFormatted: str+ imageUrl: str | None+ url: str+ isAvailable: bool+ retailerId: str+++class ProductPagination(TypedDict):+ page: int+ limit: int+ total: int+ totalPages: int+++class PaginatedProducts(TypedDict):+ """Paginated payload returned by ``GET /sessions/:id/catalog/products``."""++ products: list[CatalogProduct]+ pagination: ProductPagination+++# chatId + productId required; body optional. Modeled total=False for 3.9 compat+# (callers pass plain dicts); the backend validates the required fields.+class SendProductRequest(TypedDict, total=False):+ chatId: Jid+ productId: str+ body: str+++# chatId required; body optional. See SendProductRequest note.+class SendCatalogRequest(TypedDict, total=False):+ chatId: Jid+ body: strdiff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex aab160daa..0afa16af0 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "openwa-sdk"-version = "0.0.1"+version = "0.1.0"description = "Official Python SDK for OpenWA WhatsApp API Gateway"readme = "README.md"license = { text = "MIT" }@@ -15,7 +15,7 @@ authors = [keywords = ["whatsapp", "api", "sdk", "openwa", "gateway"]dependencies = [- "httpx>=0.25.0",+ "httpx>=0.25.0,<1.0",][project.optional-dependencies]@@ -23,3 +23,18 @@ dev = ["pytest>=7.0","pytest-asyncio>=0.23",]++[project.urls]+Homepage = "https://github.com/rmyndharis/OpenWA"+Repository = "https://github.com/rmyndharis/OpenWA"++[tool.setuptools.packages.find]+include = ["openwa*"]++# Ship type information (PEP 561) so consumers get the bundled type hints.+[tool.setuptools.package-data]+openwa = ["py.typed"]+"openwa.resources" = ["py.typed"]++[tool.pytest.ini_options]+testpaths = ["tests"]diff --git a/sdk/python/tests/conftest.py b/sdk/python/tests/conftest.pynew file mode 100644index 000000000..7f4198eb3--- /dev/null+++ b/sdk/python/tests/conftest.py@@ -0,0 +1,81 @@+"""Test helpers — an httpx.MockTransport-based recorder.++Tests assert on exact method/url/body/headers without any real network or+global monkey-patching. ``httpx.MockTransport`` is the idiomatic, native way+to test an httpx-based client.+"""++from __future__ import annotations++import json+from dataclasses import dataclass, field+from typing import Any, Callable++import httpx+++@dataclass+class RecordedCall:+ method: str+ url: str+ headers: dict[str, str]+ body: Any+++@dataclass+class MockBackend:+ """A scripted backend. Raises if a call doesn't match a route."""+ calls: list[RecordedCall] = field(default_factory=list)+ routes: list[tuple[str, str, Callable[[RecordedCall], httpx.Response]]] = field(default_factory=list)+ fallback: Callable[[RecordedCall], httpx.Response] | None = None++ def on(+ self,+ method: str,+ path_prefix: str,+ status: int = 200,+ body: Any = None,+ ) -> "MockBackend":+ def responder(_: RecordedCall) -> httpx.Response:+ if status in (204, 100, 304) or body is None:+ return httpx.Response(status, content=b"")+ return httpx.Response(status, content=json.dumps(body).encode(), headers={"content-type": "application/json"})++ self.routes.append((method.upper(), path_prefix, responder))+ return self++ def as_transport(self) -> httpx.MockTransport:+ def handler(request: httpx.Request) -> httpx.Response:+ method = request.method.upper()+ url = str(request.url)+ body: Any = None+ if request.content:+ try:+ body = json.loads(request.content)+ except ValueError:+ body = request.content.decode(errors="replace")+ call = RecordedCall(method=method, url=url, headers=dict(request.headers), body=body)+ self.calls.append(call)++ # Most-specific (longest) matching prefix wins, so a nested route like+ # "/catalog/products" is preferred over "/catalog" regardless of+ # registration order.+ matches = [(pp, resp) for m, pp, resp in self.routes if m == method and pp in url]+ if matches:+ _, responder = max(matches, key=lambda pair: len(pair[0]))+ return responder(call)+ if self.fallback is not None:+ return self.fallback(call)+ raise AssertionError(f"MockBackend: no route for {method} {url}")++ return httpx.MockTransport(handler)++ @property+ def last_call(self) -> RecordedCall:+ return self.calls[-1]+++def make_client(backend: MockBackend, base_url: str = "http://localhost:2785", api_key: str = "owa_k1_test"):+ from openwa import OpenWAClient++ return OpenWAClient(base_url=base_url, api_key=api_key, transport=backend.as_transport())diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pynew file mode 100644index 000000000..ce9de92d1--- /dev/null+++ b/sdk/python/tests/test_sdk.py@@ -0,0 +1,499 @@+"""Unit tests for the OpenWA Python SDK — assert exact paths and bodies."""++from __future__ import annotations++import pytest++from openwa import OpenWAClient, OpenWAApiError, OpenWANotFoundError++from conftest import MockBackend, make_client+++# ── Client core ────────────────────────────────────────────────────+++class TestClientCore:+ def test_requires_base_url_and_api_key(self):+ with pytest.raises(ValueError):+ OpenWAClient(base_url="", api_key="k")+ with pytest.raises(ValueError):+ OpenWAClient(base_url="http://x", api_key="")++ def test_sends_api_key_header(self):+ backend = MockBackend().on("GET", "/api/sessions", body=[])+ client = make_client(backend)+ client.sessions.list()+ assert backend.last_call.headers["x-api-key"] == "owa_k1_test"+ assert backend.last_call.headers["content-type"] == "application/json"++ def test_default_headers_cannot_override_api_key(self):+ # A caller-supplied default header must NEVER clobber the auth/JSON headers.+ backend = MockBackend().on("GET", "/api/sessions", body=[])+ client = OpenWAClient(+ base_url="http://x",+ api_key="REAL_KEY",+ default_headers={"X-API-Key": "EVIL", "Content-Type": "text/plain", "X-Trace": "keep"},+ transport=backend.as_transport(),+ )+ client.sessions.list()+ assert backend.last_call.headers["x-api-key"] == "REAL_KEY"+ assert backend.last_call.headers["content-type"] == "application/json"+ assert backend.last_call.headers["x-trace"] == "keep" # benign custom headers still pass through++ def test_non_json_2xx_body_returns_text(self):+ import httpx++ def handler(_req: httpx.Request) -> httpx.Response:+ return httpx.Response(200, content=b"plain text", headers={"content-type": "text/plain"})++ client = OpenWAClient(base_url="http://x", api_key="k", transport=httpx.MockTransport(handler))+ # A non-JSON 2xx body must surface as text, not raise a raw JSONDecodeError.+ assert client.sessions.list() == "plain text"++ def test_path_segments_are_encoded(self):+ backend = MockBackend().on("GET", "/history", body=[])+ make_client(backend).messages.history("s", "weird/id#x")+ assert "weird%2Fid%23x" in backend.last_call.url+ backend2 = MockBackend().on("GET", "/history", body=[])+ make_client(backend2).messages.history("s", "[email protected]")+ assert "/messages/[email protected]/history" in backend2.last_call.url # @ preserved++ def test_raw_request_escape_hatch(self):+ backend = MockBackend().on("GET", "/api/anything", body={"ok": True})+ result = make_client(backend).request("GET", "/api/anything", query={"a": 1})+ assert result == {"ok": True}+ assert "a=1" in backend.last_call.url++ def test_does_not_follow_redirects(self):+ import httpx++ def handler(_req: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 302,+ headers={"location": "http://evil.example/x", "content-type": "application/json"},+ content=b'{"redirected": true}',+ )++ client = OpenWAClient(base_url="http://x", api_key="k", transport=httpx.MockTransport(handler))+ # A redirect is NOT followed (which would re-send X-API-Key); the 3xx body is returned.+ assert client.sessions.list() == {"redirected": True}++ def test_strips_trailing_slash(self):+ backend = MockBackend().on("GET", "/api/sessions", body=[])+ client = OpenWAClient(base_url="http://localhost:2785/", api_key="k", transport=backend.as_transport())+ client.sessions.list()+ assert backend.last_call.url == "http://localhost:2785/api/sessions"++ def test_query_params_skip_none(self):+ backend = MockBackend().on("GET", "/messages", body=[])+ make_client(backend).messages.list("s1", {"chatId": "[email protected]", "limit": 10})+ url = backend.last_call.url+ assert "chatId=a%40c.us" in url+ assert "limit=10" in url++ def test_204_is_none(self):+ backend = MockBackend().on("DELETE", "/api/sessions", status=204)+ assert make_client(backend).sessions.delete("x") is None++ def test_404_maps_to_not_found_error(self):+ backend = MockBackend().on("GET", "/api/sessions/missing", status=404, body={+ "statusCode": 404, "message": "Session not found", "error": "Not Found"+ })+ with pytest.raises(OpenWANotFoundError):+ make_client(backend).sessions.get("missing")++ def test_exposes_all_resources(self):+ client = make_client(MockBackend())+ for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health"]:+ assert hasattr(client, r)+++# ── Messages (the critical send-text fix) ──────────────────────────+++class TestMessages:+ def test_send_text_uses_send_text_path(self):+ backend = MockBackend().on("POST", "/send-text", body={"messageId": "m1", "timestamp": 1})+ make_client(backend).messages.send_text("s1", {"chatId": "[email protected]", "text": "hi"})+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s1/messages/send-text"+ assert backend.last_call.body == {"chatId": "[email protected]", "text": "hi"}++ @pytest.mark.parametrize("method,segment", [+ ("send_image", "send-image"),+ ("send_video", "send-video"),+ ("send_audio", "send-audio"),+ ("send_document", "send-document"),+ ("send_sticker", "send-sticker"),+ ])+ def test_media_segments(self, method, segment):+ backend = MockBackend().on("POST", f"/{segment}", body={"messageId": "m", "timestamp": 2})+ fn = getattr(make_client(backend).messages, method)+ fn("s", {"chatId": "[email protected]", "url": "u"})+ assert f"/messages/{segment}" in backend.last_call.url++ def test_send_location_contact_template(self):+ backend = MockBackend()+ backend.on("POST", "/send-location", body={"messageId": "m", "timestamp": 1})+ backend.on("POST", "/send-contact", body={"messageId": "m", "timestamp": 1})+ backend.on("POST", "/send-template", body={"messageId": "m", "timestamp": 1})+ client = make_client(backend)+ client.messages.send_location("s", {"chatId": "[email protected]", "latitude": -6.2, "longitude": 106.8})+ assert "/messages/send-location" in backend.last_call.url+ client.messages.send_contact("s", {"chatId": "[email protected]", "contactName": "A", "contactNumber": "628"})+ assert "/messages/send-contact" in backend.last_call.url+ # Server DTO field is `vars` (NOT `variables`); body forwarded verbatim.+ client.messages.send_template("s", {"chatId": "[email protected]", "templateId": "t", "vars": {"name": "Sam"}})+ assert "/messages/send-template" in backend.last_call.url+ assert backend.last_call.body == {"chatId": "[email protected]", "templateId": "t", "vars": {"name": "Sam"}}++ def test_send_template_accepts_template_name(self):+ backend = MockBackend().on("POST", "/send-template", body={"messageId": "m", "timestamp": 1})+ make_client(backend).messages.send_template("s", {"chatId": "[email protected]", "templateName": "welcome"})+ assert backend.last_call.body == {"chatId": "[email protected]", "templateName": "welcome"}++ def test_list_returns_messages_total_wrapper(self):+ backend = MockBackend().on("GET", "/messages", body={"messages": [{"id": "1"}], "total": 1})+ res = make_client(backend).messages.list("s")+ assert res["total"] == 1+ assert len(res["messages"]) == 1++ def test_reply_forwardReactDelete(self):+ backend = MockBackend()+ backend.on("POST", "/reply", body={"messageId": "m", "timestamp": 1})+ backend.on("POST", "/forward", body={"messageId": "m", "timestamp": 1})+ backend.on("POST", "/react", body={"success": True})+ backend.on("POST", "/delete", body={"success": True})+ client = make_client(backend)+ client.messages.reply("s", {"chatId": "[email protected]", "quotedMessageId": "q", "text": "r"})+ client.messages.forward("s", {"fromChatId": "[email protected]", "toChatId": "[email protected]", "messageId": "m"})+ client.messages.react("s", {"chatId": "[email protected]", "messageId": "m", "emoji": "👍"})+ client.messages.delete("s", {"chatId": "[email protected]", "messageId": "m"})+ assert "/messages/reply" in backend.calls[-4].url+ assert "/messages/forward" in backend.calls[-3].url+ assert "/messages/react" in backend.calls[-2].url+ assert "/messages/delete" in backend.calls[-1].url++ def test_history_and_reactions_path(self):+ backend = MockBackend()+ backend.on("GET", "/history", body=[])+ backend.on("GET", "/reactions", body=[])+ client = make_client(backend)+ client.messages.history("s", "[email protected]", {"limit": 5})+ assert "/messages/[email protected]/history" in backend.calls[-1].url+ assert "limit=5" in backend.calls[-1].url+ client.messages.reactions("s", "[email protected]", "m1")+ assert "/messages/[email protected]/m1/reactions" in backend.calls[-1].url++ def test_history_boolean_query_serializes_lowercase(self):+ # Server reads `includeMedia === 'true'`; Python str(True) == 'True' would be ignored.+ backend = MockBackend().on("GET", "/history", body=[])+ make_client(backend).messages.history("s", "[email protected]", {"limit": 5, "includeMedia": True, "deep": False})+ url = backend.last_call.url+ assert "includeMedia=true" in url+ assert "deep=false" in url++ def test_bulk_and_batch_status(self):+ backend = MockBackend()+ backend.on("POST", "/send-bulk", body={+ "batchId": "b", "status": "queued", "totalMessages": 1,+ "estimatedCompletionTime": "t", "statusUrl": "/u",+ })+ backend.on("GET", "/batch/b", body={+ "batchId": "b", "status": "done",+ "progress": {"total": 1, "sent": 1, "failed": 0, "pending": 0, "cancelled": 0},+ "results": [], "startedAt": "s", "completedAt": "c",+ })+ backend.on("POST", "/cancel", body={+ "batchId": "b", "status": "cancelled",+ "progress": {"total": 1, "sent": 0, "failed": 0, "pending": 0, "cancelled": 1},+ })+ client = make_client(backend)+ client.messages.send_bulk("s", {"messages": [{"chatId": "[email protected]", "type": "text", "content": {"text": "x"}}]})+ assert "/messages/send-bulk" in backend.calls[-1].url+ status = client.messages.batch_status("s", "b")+ assert status["progress"]["sent"] == 1+ assert "/messages/batch/b" in backend.calls[-1].url+ cancelled = client.messages.cancel_batch("s", "b")+ assert cancelled["status"] == "cancelled"+ assert "/messages/batch/b/cancel" in backend.calls[-1].url+ assert backend.calls[-1].method == "POST"+++# ── Sessions ───────────────────────────────────────────────────────+++class TestSessions:+ def test_lifecycle_paths(self):+ backend = MockBackend()+ backend.on("GET", "/api/sessions", body=[])+ backend.on("GET", "/sessions/s1", body={"id": "s1", "name": "n", "status": "ready"})+ backend.on("POST", "/api/sessions", body={"id": "s1", "name": "n", "status": "created"})+ backend.on("DELETE", "/sessions/s1", status=204)+ backend.on("POST", "/start", body={"id": "s1", "status": "initializing"})+ backend.on("POST", "/stop", body={"id": "s1", "status": "disconnected"})+ backend.on("POST", "/force-kill", body={"id": "s1", "status": "disconnected"})+ client = make_client(backend)+ client.sessions.list()+ assert backend.calls[-1].url == "http://localhost:2785/api/sessions"+ client.sessions.get("s1")+ assert "/sessions/s1" in backend.calls[-1].url+ client.sessions.create({"name": "n"})+ assert backend.calls[-1].body == {"name": "n"}+ client.sessions.start("s1")+ assert "/sessions/s1/start" in backend.calls[-1].url+ client.sessions.stop("s1")+ client.sessions.force_kill("s1")+ assert "/sessions/s1/force-kill" in backend.calls[-1].url+ client.sessions.delete("s1")+ assert backend.calls[-1].method == "DELETE"++ def test_qr_pairing_stats(self):+ backend = MockBackend()+ backend.on("GET", "/qr", body={"qrCode": "data:image/png;base64,xxx", "status": "qr_ready"})+ backend.on("POST", "/pairing-code", body={"pairingCode": "ABCD1234", "status": "qr_ready"})+ backend.on("GET", "/stats/overview", body={"total": 1, "active": 1, "ready": 1, "disconnected": 0, "byStatus": {"ready": 1}})+ client = make_client(backend)+ client.sessions.get_qr_code("s1")+ assert "/sessions/s1/qr" in backend.calls[-1].url+ client.sessions.request_pairing_code("s1", {"phoneNumber": "628123456789"})+ assert backend.calls[-1].body == {"phoneNumber": "628123456789"}+ client.sessions.stats()+ assert "/sessions/stats/overview" in backend.calls[-1].url+++# ── Groups, Contacts, Webhooks, Chats, Health ──────────────────────+++class TestGroups:+ def test_list_get_create(self):+ backend = MockBackend()+ backend.on("GET", "/groups", body=[])+ backend.on("GET", "/groups/[email protected]", body={"id": "[email protected]", "subject": "G", "participants": []})+ backend.on("POST", "/groups", body={"id": "[email protected]", "subject": "G", "participants": []})+ client = make_client(backend)+ client.groups.list("s")+ client.groups.get("s", "[email protected]")+ assert "/groups/[email protected]" in backend.calls[-1].url+ client.groups.create("s", {"name": "G", "participants": ["[email protected]"]})+ assert backend.calls[-1].body == {"name": "G", "participants": ["[email protected]"]}++ def test_participant_ops(self):+ backend = MockBackend()+ backend.on("POST", "/participants", body={"success": True})+ backend.on("DELETE", "/participants", body={"success": True})+ backend.on("POST", "/promote", body={"success": True})+ backend.on("POST", "/demote", body={"success": True})+ client = make_client(backend)+ client.groups.add_participants("s", "g", ["[email protected]", "[email protected]"])+ assert backend.calls[-1].body == {"participants": ["[email protected]", "[email protected]"]}+ assert backend.calls[-1].method == "POST"+ client.groups.remove_participants("s", "g", ["[email protected]"])+ assert backend.calls[-1].method == "DELETE"+ client.groups.promote_participants("s", "g", ["[email protected]"])+ assert "/promote" in backend.calls[-1].url+ client.groups.demote_participants("s", "g", ["[email protected]"])+ assert "/demote" in backend.calls[-1].url++ def test_subject_description_invite(self):+ backend = MockBackend()+ backend.on("PUT", "/subject", body={"success": True})+ backend.on("PUT", "/description", body={"success": True})+ backend.on("POST", "/leave", body={"success": True})+ backend.on("GET", "/invite-code", body={"inviteCode": "c", "inviteLink": "l"})+ backend.on("POST", "/revoke", body={"inviteCode": "c2", "inviteLink": "l2"})+ client = make_client(backend)+ client.groups.set_subject("s", "g", "New")+ assert backend.calls[-1].body == {"subject": "New"}+ assert backend.calls[-1].method == "PUT"+ client.groups.set_description("s", "g", "desc")+ assert backend.calls[-1].body == {"description": "desc"}+ client.groups.leave("s", "g")+ client.groups.invite_code("s", "g")+ client.groups.revoke_invite_code("s", "g")+ assert "/revoke" in backend.calls[-1].url+++class TestContacts:+ def test_paths(self):+ backend = MockBackend()+ backend.on("GET", "/contacts", body=[])+ backend.on("GET", "/contacts/[email protected]", body={"id": "[email protected]"})+ backend.on("GET", "/check/628123", body={"number": "628123", "exists": True, "whatsappId": "[email protected]"})+ backend.on("GET", "/profile-picture", body={"url": "http://p"})+ backend.on("GET", "/phone", body={"contactId": "x@lid", "phone": "628123"})+ client = make_client(backend)+ client.contacts.list("s", {"limit": 10})+ assert "limit=10" in backend.calls[-1].url+ client.contacts.get("s", "[email protected]")+ client.contacts.check("s", "628123")+ assert "/check/628123" in backend.calls[-1].url+ client.contacts.profile_picture("s", "[email protected]")+ client.contacts.phone("s", "x@lid")++ def test_block_unblock(self):+ backend = MockBackend()+ backend.on("POST", "/block", body={"success": True})+ backend.on("DELETE", "/block", body={"success": True})+ client = make_client(backend)+ client.contacts.block("s", "[email protected]")+ assert backend.calls[-1].method == "POST"+ client.contacts.unblock("s", "[email protected]")+ assert backend.calls[-1].method == "DELETE"+++class TestWebhooks:+ def test_crud_test(self):+ wh = {"id": "w1", "sessionId": "s", "url": "u", "events": ["*"], "active": True, "createdAt": "", "updatedAt": ""}+ backend = MockBackend()+ backend.on("GET", "/webhooks", body=[wh])+ backend.on("GET", "/webhooks/w1", body=wh)+ backend.on("POST", "/webhooks", body=wh)+ backend.on("PUT", "/webhooks/w1", body={**wh, "active": False})+ backend.on("DELETE", "/webhooks/w1", status=204)+ backend.on("POST", "/test", body={"success": True})+ client = make_client(backend)+ client.webhooks.list("s")+ client.webhooks.get("s", "w1")+ # Server DTO field is `retryCount` (NOT `retries`); body forwarded verbatim.+ client.webhooks.create("s", {"url": "u", "events": ["*"], "retryCount": 5})+ assert backend.calls[-1].body == {"url": "u", "events": ["*"], "retryCount": 5}+ client.webhooks.update("s", "w1", {"active": False})+ assert backend.calls[-1].method == "PUT"+ client.webhooks.delete("s", "w1")+ client.webhooks.test("s", "w1")+ assert "/webhooks/w1/test" in backend.calls[-1].url+++class TestStatus:+ def test_send_image_video_forward_nested_media_body(self):+ backend = MockBackend()+ backend.on("POST", "/status/send-image", body={"statusId": "s1"})+ backend.on("POST", "/status/send-video", body={"statusId": "s2"})+ client = make_client(backend)+ # Server requires a nested {image|video:{...}} body, not flat media fields.+ client.status.send_image("s", {"image": {"url": "http://img"}, "caption": "hi"})+ assert backend.calls[-1].body == {"image": {"url": "http://img"}, "caption": "hi"}+ client.status.send_video("s", {"video": {"url": "http://vid"}})+ assert backend.calls[-1].body == {"video": {"url": "http://vid"}}+++class TestChatsAndHealth:+ def test_chats(self):+ backend = MockBackend()+ backend.on("GET", "/chats", body=[])+ backend.on("POST", "/read", body={"success": True})+ backend.on("POST", "/unread", body={"success": True})+ backend.on("POST", "/delete", body={"success": True})+ backend.on("POST", "/typing", body={"success": True})+ client = make_client(backend)+ client.chats.list("s")+ client.chats.mark_read("s", {"chatId": "[email protected]"})+ assert "/chats/read" in backend.calls[-1].url+ client.chats.mark_unread("s", {"chatId": "[email protected]"})+ client.chats.delete("s", {"chatId": "[email protected]"})+ client.chats.send_state("s", {"chatId": "[email protected]", "state": "typing"})+ assert "/chats/typing" in backend.calls[-1].url++ def test_health_and_auth(self):+ backend = MockBackend()+ backend.on("GET", "/api/health", body={"status": "ok", "version": "0.7.2"})+ backend.on("GET", "/live", body={"status": "ok"})+ backend.on("GET", "/ready", body={"status": "ok", "details": {}})+ backend.on("POST", "/validate", body={"valid": True, "role": "admin"})+ client = make_client(backend)+ client.health.check()+ assert backend.calls[-1].url == "http://localhost:2785/api/health"+ client.health.live()+ client.health.ready()+ client.auth()+ assert backend.calls[-1].method == "POST"+ assert "/auth/validate" in backend.calls[-1].url+++class TestLabelsChannelsCatalog:+ def test_labels(self):+ backend = MockBackend()+ backend.on("GET", "/labels", body=[{"id": "l1", "name": "VIP"}])+ backend.on("GET", "/labels/l1", body={"id": "l1", "name": "VIP"})+ backend.on("GET", "/labels/chat/[email protected]", body=[{"id": "l1", "name": "VIP"}])+ backend.on("POST", "/labels/chat/[email protected]", body={"success": True})+ backend.on("DELETE", "/labels/chat/[email protected]/l1", body={"success": True})+ client = make_client(backend)+ client.labels.list("s")+ assert "/sessions/s/labels" in backend.calls[-1].url+ client.labels.get("s", "l1")+ client.labels.for_chat("s", "[email protected]")+ client.labels.add_to_chat("s", "[email protected]", {"labelId": "l1"})+ assert backend.calls[-1].method == "POST"+ assert backend.calls[-1].body == {"labelId": "l1"}+ client.labels.remove_from_chat("s", "[email protected]", "l1")+ assert backend.calls[-1].method == "DELETE"++ def test_channels(self):+ backend = MockBackend()+ backend.on("GET", "/channels", body=[{"id": "123@newsletter", "name": "News"}])+ backend.on("GET", "/channels/123@newsletter", body={"id": "123@newsletter", "name": "News"})+ backend.on("GET", "/channels/123@newsletter/messages", body=[])+ backend.on("POST", "/channels/subscribe", body={"id": "123@newsletter", "name": "News"})+ backend.on("DELETE", "/channels/123@newsletter", body={"success": True})+ client = make_client(backend)+ client.channels.list("s")+ assert "/sessions/s/channels" in backend.calls[-1].url+ client.channels.get("s", "123@newsletter")+ client.channels.messages("s", "123@newsletter", {"limit": 10})+ assert "limit=10" in backend.calls[-1].url+ client.channels.subscribe("s", {"inviteCode": "ABCxyz"})+ assert backend.calls[-1].method == "POST"+ assert backend.calls[-1].body == {"inviteCode": "ABCxyz"}+ client.channels.unsubscribe("s", "123@newsletter")+ assert backend.calls[-1].method == "DELETE"++ def test_catalog(self):+ backend = MockBackend()+ backend.on("GET", "/catalog", body={"id": "c1", "name": "My Shop", "productCount": 5, "url": "http://shop"})+ backend.on("GET", "/catalog/products", body={+ "products": [{"id": "p1", "name": "Widget"}],+ "pagination": {"page": 1, "limit": 20, "total": 1, "totalPages": 1},+ })+ backend.on("GET", "/catalog/products/p1", body={"id": "p1", "name": "Widget"})+ backend.on("POST", "/messages/send-product", body={"messageId": "m", "timestamp": 1})+ backend.on("POST", "/messages/send-catalog", body={"messageId": "m", "timestamp": 1})+ client = make_client(backend)+ client.catalog.info("s")+ assert "/sessions/s/catalog" in backend.calls[-1].url+ page = client.catalog.products("s", {"page": 1, "limit": 20})+ assert page["pagination"]["total"] == 1+ assert "page=1" in backend.calls[-1].url+ client.catalog.product("s", "p1")+ client.catalog.send_product("s", {"chatId": "[email protected]", "productId": "p1", "body": "x"})+ assert "/messages/send-product" in backend.calls[-1].url+ assert backend.calls[-1].body == {"chatId": "[email protected]", "productId": "p1", "body": "x"}+ client.catalog.send_catalog("s", {"chatId": "[email protected]", "body": "cat"})+ assert "/messages/send-catalog" in backend.calls[-1].url++ def test_templates_crud(self):+ tpl = {"id": "t1", "sessionId": "s", "name": "welcome", "body": "Hi {{name}}", "createdAt": "", "updatedAt": ""}+ backend = MockBackend()+ backend.on("GET", "/templates/t1", body=tpl)+ backend.on("GET", "/templates", body=[tpl])+ backend.on("POST", "/templates", body=tpl)+ backend.on("PUT", "/templates/t1", body={**tpl, "body": "Hello {{name}}"})+ backend.on("DELETE", "/templates/t1", status=204)+ client = make_client(backend)+ client.templates.list("s")+ assert "/api/sessions/s/templates" in backend.last_call.url+ client.templates.get("s", "t1")+ assert backend.last_call.url.endswith("/api/sessions/s/templates/t1")+ client.templates.create("s", {"name": "welcome", "body": "Hi {{name}}"})+ assert backend.last_call.method == "POST"+ assert backend.last_call.body == {"name": "welcome", "body": "Hi {{name}}"}+ client.templates.update("s", "t1", {"body": "Hello {{name}}"})+ assert backend.last_call.method == "PUT"+ assert backend.last_call.body == {"body": "Hello {{name}}"}+ client.templates.delete("s", "t1")+ assert backend.last_call.method == "DELETE"++ def test_client_exposes_all_resources(self):+ client = make_client(MockBackend())+ for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "labels", "channels", "catalog", "templates"]:+ assert hasattr(client, r)