diff --git a/CHANGELOG.md b/CHANGELOG.md index b15adcb03..60ae9b997 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Breaking: Test number phone and event methods use the Number-scoped routes + in API contract revision `f180dc1ee2`. `testing.getPhone`, `sendPhoneMessage` + and `unlinkPhoneDevice` take a Number ID and no project argument, and + `testing.triggerEvent(numberId, body)` omits body `session` and accepts + `fromNumber`. `listEventFixtures()` has no project argument. History fixtures + keep their project argument and use + `/messaging/projects/{projectId}/test-history-fixtures`. Real Numbers return + `404 resource_not_found`. Scope names remain `sandbox:read` / `sandbox:write`. + Applies to all six SDKs. Source-only and unpublished. + - UI Kit: give `CallNumberPicker` built-in themes, appearance variables and styling slots. It supports `classNames` and unstyled mode without a host stylesheet. @@ -48,16 +58,16 @@ Contract snapshots, coverage fingerprints, the machine-credential fixture and the documentation snippet catalog are re-pinned to that revision. The revision also carries later API dev changes. The coverage ledger now holds 671 - operations: 451 covered, 2 partial, 58 missing and 160 excluded in TypeScript. + operations: 457 covered, 2 partial, 52 missing and 160 excluded in TypeScript. The TypeScript error-code list adds the new `billing_credit_required`, `safe_mode_not_entitled`, `warmup_plan_not_entitled`, `team_deletion_scheduled`, `terms_acceptance_required`, `terms_activation_blocked` and `idempotency_replay_unavailable` codes, and the campaign recipient sent and - failed webhook payloads type the optional `messageIndex`. The Test number - routes (`/messaging/testing/...`), `/platform/keys` and `/platform/tokens` left - the specification, so `projectTokens.list`, `apiKeys.list` and - `apiKeys.deactivate` and the older Test-event helpers target retired paths - until a removal or update decision lands. Publish + failed webhook payloads type the optional `messageIndex`. The + `/platform/keys` and `/platform/tokens` routes left the specification, so + `projectTokens.list`, `apiKeys.list` and `apiKeys.deactivate` target retired + paths until a removal or update decision lands. The Test number helpers use + the Number-scoped routes (see the entry above). Publish these SDKs only after the API change is deployed: a build from this source cannot call an API that still uses the old names. Source-only and unpublished. diff --git a/contracts/README.md b/contracts/README.md index dd0e92b4b..9ac0a9704 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -1,5 +1,16 @@ # Contract coverage +## Number-scoped Test phone and events + +The full Messaging snapshot at API `f180dc1ee2bd45dbecf01702f73bdd75c664634b` +contains the six Number-scoped Test operations (`getTestingPhone`, +`sendTestingPhoneMessage`, `unlinkTestingPhoneDevice`, `triggerTestEvent`, +`listTestEventFixtures` and `createTestingHistoryFixture`), so the ledger +covers them from the global baseline with no per-operation source override. +`testing-phone.json` and `testing-events.json` are focused extracts of those +operations and their schemas from the same snapshot. This is a breaking SDK +change: the earlier project-scoped `/messaging/testing/...` methods are gone. + ## Idempotency response replay `idempotency-replay.json` is produced by @@ -117,9 +128,8 @@ published SDK package before updating their pinned dependency. `testing-phone.json` records the three Test number phone operations (`getTestingPhone`, `sendTestingPhoneMessage`, `unlinkTestingPhoneDevice`) and -their schemas from API `dev` merge commit -`2f1510f901aca1d68398a6dc9dbf243348c672c0` (polymorfa/polymorfa#526), with the -source path and file hash. `MessagingClient.testing.getPhone`, +their schemas from API commit `f180dc1ee2bd45dbecf01702f73bdd75c664634b`, with +the source path and file hash. `MessagingClient.testing.getPhone`, `sendPhoneMessage` and `unlinkPhoneDevice` use this revision; a contract test compares their paths and fields. The full snapshots are not repinned here. diff --git a/contracts/coverage.json b/contracts/coverage.json index 07b4c49d7..bcbb5ad2a 100644 --- a/contracts/coverage.json +++ b/contracts/coverage.json @@ -18655,34 +18655,28 @@ "operationId": "getTestingPhone", "fingerprint": "3857280d47e6fdfea20616d423160d1eacf357b37609cc71b1d408ebb25e80fe", "typescript": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.getPhone" }, "go": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.GetPhone" }, "python": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "AsyncMessagingClient.testing.get_phone" }, "php": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient::testing.getPhone" }, "dotnet": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.GetPhoneAsync" }, "rust": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.get_phone" } }, { @@ -18840,34 +18834,28 @@ "operationId": "listTestEventFixtures", "fingerprint": "04fbd25cb26404b99eeee32dc3861e9fd89daff9cd273fa859787e7fe9cf13c1", "typescript": { - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient.testing.listEventFixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.listEventFixtures" }, "go": { - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient.Testing.ListEventFixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.ListEventFixtures" }, "python": { - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (AsyncMessagingClient.testing.list_event_fixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "AsyncMessagingClient.testing.list_event_fixtures" }, "php": { - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient::testing.listEventFixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient::testing.listEventFixtures" }, "dotnet": { - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient.Testing.ListEventFixturesAsync) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.ListEventFixturesAsync" }, "rust": { - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient.testing.list_event_fixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.list_event_fixtures" } }, { @@ -19167,34 +19155,28 @@ "operationId": "unlinkTestingPhoneDevice", "fingerprint": "c02e328d3ae2555873d9abcc37f40a25a95d4ed7d004a8d3bb147dd81fd9d628", "typescript": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.unlinkPhoneDevice" }, "go": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.UnlinkPhoneDevice" }, "python": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "AsyncMessagingClient.testing.unlink_phone_device" }, "php": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient::testing.unlinkPhoneDevice" }, "dotnet": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.UnlinkPhoneDeviceAsync" }, "rust": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.unlink_phone_device" } }, { @@ -19204,34 +19186,28 @@ "operationId": "sendTestingPhoneMessage", "fingerprint": "28d48aa209a0fb6dd2779d1103d2a0ca98f0f3407f3c1c806890076b0cf6e5d9", "typescript": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.sendPhoneMessage" }, "go": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.SendPhoneMessage" }, "python": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "AsyncMessagingClient.testing.send_phone_message" }, "php": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient::testing.sendPhoneMessage" }, "dotnet": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.SendPhoneMessageAsync" }, "rust": { - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.send_phone_message" } }, { @@ -19352,34 +19328,28 @@ "operationId": "triggerTestEvent", "fingerprint": "7bd451a4dad642aa1b260fbe735e0a31da10d88c9294f29983a6d13cff4cfe86", "typescript": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient.testing.triggerEvent) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.triggerEvent" }, "go": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient.Testing.TriggerEvent) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.TriggerEvent" }, "python": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (AsyncMessagingClient.testing.trigger_event) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "AsyncMessagingClient.testing.trigger_event" }, "php": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient::testing.triggerEvent) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient::testing.triggerEvent" }, "dotnet": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient.Testing.TriggerEventAsync) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.TriggerEventAsync" }, "rust": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient.testing.trigger_event) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.trigger_event" } }, { @@ -19426,34 +19396,28 @@ "operationId": "createTestingHistoryFixture", "fingerprint": "90836ddb657f5021281794ce5d3c24e6acc9a0a59fee2a23fb235fc418179abf", "typescript": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient.testing.createHistoryFixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.createHistoryFixture" }, "go": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient.Testing.CreateHistoryFixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.CreateHistoryFixture" }, "python": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (AsyncMessagingClient.testing.create_history_fixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "AsyncMessagingClient.testing.create_history_fixture" }, "php": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient::testing.createHistoryFixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient::testing.createHistoryFixture" }, "dotnet": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient.Testing.CreateHistoryFixtureAsync) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.Testing.CreateHistoryFixtureAsync" }, "rust": { - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient.testing.create_history_fixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "method": "MessagingClient.testing.create_history_fixture" } }, { @@ -21921,51 +21885,6 @@ } }, "retiredOperations": [ - { - "family": "messaging", - "method": "GET", - "path": "/messaging/testing/{projectId}/events/fixtures", - "operationId": "listTestEventFixtures", - "reason": "No longer in the API specification at contract revision f180dc1ee2 of polymorfa/polymorfa#887 under this path or operation. The SDK methods named below still target it and are pending a removal or update decision.", - "sdkMethods": { - "typescript": "MessagingClient.testing.listEventFixtures", - "go": "MessagingClient.Testing.ListEventFixtures", - "python": "AsyncMessagingClient.testing.list_event_fixtures", - "php": "MessagingClient::testing.listEventFixtures", - "dotnet": "MessagingClient.Testing.ListEventFixturesAsync", - "rust": "MessagingClient.testing.list_event_fixtures" - } - }, - { - "family": "messaging", - "method": "POST", - "path": "/messaging/testing/{projectId}/events", - "operationId": "triggerTestEvent", - "reason": "No longer in the API specification at contract revision f180dc1ee2 of polymorfa/polymorfa#887 under this path or operation. The SDK methods named below still target it and are pending a removal or update decision.", - "sdkMethods": { - "typescript": "MessagingClient.testing.triggerEvent", - "go": "MessagingClient.Testing.TriggerEvent", - "python": "AsyncMessagingClient.testing.trigger_event", - "php": "MessagingClient::testing.triggerEvent", - "dotnet": "MessagingClient.Testing.TriggerEventAsync", - "rust": "MessagingClient.testing.trigger_event" - } - }, - { - "family": "messaging", - "method": "POST", - "path": "/messaging/testing/{projectId}/history-fixtures", - "operationId": "createTestingHistoryFixture", - "reason": "No longer in the API specification at contract revision f180dc1ee2 of polymorfa/polymorfa#887 under this path or operation. The SDK methods named below still target it and are pending a removal or update decision.", - "sdkMethods": { - "typescript": "MessagingClient.testing.createHistoryFixture", - "go": "MessagingClient.Testing.CreateHistoryFixture", - "python": "AsyncMessagingClient.testing.create_history_fixture", - "php": "MessagingClient::testing.createHistoryFixture", - "dotnet": "MessagingClient.Testing.CreateHistoryFixtureAsync", - "rust": "MessagingClient.testing.create_history_fixture" - } - }, { "family": "platform", "method": "DELETE", diff --git a/contracts/doc-snippets.json b/contracts/doc-snippets.json index eb78bf338..bc6b23f11 100644 --- a/contracts/doc-snippets.json +++ b/contracts/doc-snippets.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "sourceCommit": "4b6ce43985ab6e3d6b0427858da5792c06dbb520", - "sourceFilesSha256": "3efbdccb5efd4cf7ed8165b5eb25a37bd79a53a7860196250f8c3d36bbc4a282", + "sourceCommit": "1e6fd9952e8183497a28f43c3987d960d9bf52eb", + "sourceFilesSha256": "536a8c44342cf6a09e6a47d37f6f3239b8a083471a33743a2b8b0cfa32a73792", "apiVersion": "2026-09-22", "apiSourceCommit": "f180dc1ee2bd45dbecf01702f73bdd75c664634b", "specs": { diff --git a/contracts/doc-snippets.md b/contracts/doc-snippets.md index f75814a71..a9841688b 100644 --- a/contracts/doc-snippets.md +++ b/contracts/doc-snippets.md @@ -42,8 +42,8 @@ recipe. Its schemas and union branches are validated against the pinned OpenAPI. No optional request fields are included in this initial catalog. There are **31 operations per language**, 186 complete programs. The TypeScript -coverage ledger contains 451 covered operations (**420 omitted**) and each -native ledger 445 (**414 omitted**). The initial recipes cover text sends, message actions, session +coverage ledger contains 457 covered operations (**426 omitted**) and each +native ledger 451 (**420 omitted**). The initial recipes cover text sends, message actions, session lifecycle, business profiles/catalogs/collections and project event listing. The remaining operations have no verified recipe in this catalog and retain cURL fallback. Coverage of a method does not imply a verified documentation diff --git a/contracts/testing-events.json b/contracts/testing-events.json index 270ee3d03..a6ea5793b 100644 --- a/contracts/testing-events.json +++ b/contracts/testing-events.json @@ -1,56 +1,324 @@ { "repository": "polymorfa/polymorfa", - "commit": "6839976e7ad54e044c4d789fd296edc44772a907", + "commit": "f180dc1ee2bd45dbecf01702f73bdd75c664634b", "sourcePath": "apps/api/docs/openapi.json", - "sourceSha256": "79543bf719017598c3e2497004d761056e919b3200abdaae1560893542816cc7", - "schemas": { - "TestEventFixtureList": { - "type": "object", - "properties": { - "fixtures": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "enum": [ - "message.received", - "message.ack", - "message.failed", - "call.received", - "call.missed", - "call.ended", - "session.status", - "session.restriction_updated", - "template.status" - ] + "sourceSha256": "0c66f1ee93923cf57425ac29c01a84c5c140b703ace2160e1b899ee6dad0b071", + "operations": { + "triggerTestEvent": { + "method": "POST", + "path": "/messaging/{session}/test-events", + "operation": { + "operationId": "triggerTestEvent", + "tags": ["Testing"], + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "Trigger a test event for a Test number", + "x-required-scope": "sandbox:write", + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Test Number ID." + }, + "required": true, + "name": "session", + "in": "path" + }, + { + "schema": { + "type": "string", + "pattern": "^[\\x21-\\x7e]{1,255}$", + "description": "Optional. Repeating a request with the same key and body reuses the same event ID, so a retry after a failed or uncertain response never creates a second event or duplicate webhook deliveries." + }, + "required": false, + "name": "idempotency-key", + "in": "header" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/TriggerTestEventRequest" + } + } + } + }, + "responses": { + "202": { + "description": "Test event accepted for delivery", + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/TriggerTestEventResponse" + } + } + }, + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" }, - "description": { - "type": "string" + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" }, - "overrides": { - "type": "array", - "items": { - "type": "string" + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "400": { + "description": "Invalid fixture or override", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/PublicError" + }, + "example": { + "error": { + "type": "invalid_request_error", + "code": "invalid_parameter", + "message": "Correct the invalid request field.", + "param": null, + "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" + }, + "data": null, + "docs": "https://docs.polymorfa.com/api/errors#invalid-parameter" } } + } + }, + "403": { + "description": "Test numbers access required, or a client token was used", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } }, - "required": ["name", "description", "overrides"] + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/PublicError" + }, + "example": { + "error": { + "type": "permission_error", + "code": "permission_denied", + "message": "The credential does not have access to this resource.", + "param": null, + "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" + }, + "data": null, + "docs": "https://docs.polymorfa.com/api/errors#permission-denied" + } + } + } + }, + "404": { + "description": "Resource not found", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/PublicError" + }, + "example": { + "error": { + "type": "invalid_request_error", + "code": "resource_not_found", + "message": "The resource is unavailable to this caller.", + "param": null, + "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" + }, + "data": null, + "docs": "https://docs.polymorfa.com/api/errors#resource-not-found" + } + } + } + }, + "429": { + "description": "Test event rate limit reached", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/PublicError" + }, + "example": { + "error": { + "type": "rate_limit_error", + "code": "rate_limit_exceeded", + "message": "The request limit was reached. Follow Retry-After when supplied.", + "param": null, + "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" + }, + "data": null, + "docs": "https://docs.polymorfa.com/api/errors#rate-limit-exceeded" + } + } + } + }, + "502": { + "description": "Test event delivery unavailable. Retry with the same Idempotency-Key to avoid a second event.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/PublicError" + }, + "example": { + "error": { + "type": "upstream_error", + "code": "upstream_failure", + "message": "The messaging provider could not complete the request.", + "param": null, + "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" + }, + "data": null, + "docs": "https://docs.polymorfa.com/api/errors#upstream-failure" + } + } + } } - } - }, - "required": ["fixtures"] + }, + "x-mint": { + "content": "Linked Device API sandbox:write" + }, + "x-protocols": ["Linked Device API"], + "description": "**Protocols:** Linked Device API\n\n**Required scope:** `sandbox:write`" + } }, + "listTestEventFixtures": { + "method": "GET", + "path": "/messaging/test-events/fixtures", + "operation": { + "operationId": "listTestEventFixtures", + "tags": ["Testing"], + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "List test event fixtures", + "x-required-scope": "sandbox:read", + "responses": { + "200": { + "description": "Available fixtures and the overrides each accepts", + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/TestEventFixtureList" + } + } + }, + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "403": { + "description": "Read scope required; client tokens are not permitted", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/schemas/PublicError" + }, + "example": { + "error": { + "type": "permission_error", + "code": "permission_denied", + "message": "The credential does not have access to this resource.", + "param": null, + "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" + }, + "data": null, + "docs": "https://docs.polymorfa.com/api/errors#permission-denied" + } + } + } + } + }, + "x-mint": { + "content": "sandbox:read" + }, + "description": "**Required scope:** `sandbox:read`" + } + } + }, + "schemas": { "TriggerTestEventRequest": { "type": "object", "properties": { - "session": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Test number session name in the project." - }, "event": { "type": "string", "enum": [ @@ -69,52 +337,16 @@ "overrides": { "$ref": "#/schemas/TestEventOverrides" }, - "fromSession": { + "fromNumber": { "type": "string", "minLength": 1, "maxLength": 128, "description": "message.received only. Send a simulated text message from this other connected Test number in the same project instead of generating an event." } }, - "required": ["session", "event"], + "required": ["event"], "additionalProperties": false }, - "TriggerTestEventResponse": { - "type": "object", - "properties": { - "event": { - "type": "string", - "enum": [ - "message.received", - "message.ack", - "message.failed", - "call.received", - "call.missed", - "call.ended", - "session.status", - "session.restriction_updated", - "template.status" - ] - }, - "session": { - "type": "string" - }, - "delivery": { - "type": "string", - "enum": ["generated", "simulated"] - }, - "eventId": { - "type": "string", - "nullable": true, - "format": "uuid" - }, - "source": { - "type": "string", - "enum": ["test", "runtime"] - } - }, - "required": ["event", "session", "delivery", "eventId", "source"] - }, "TestEventOverrides": { "type": "object", "properties": { @@ -212,6 +444,264 @@ } }, "additionalProperties": false + }, + "TriggerTestEventResponse": { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "message.received", + "message.ack", + "message.failed", + "call.received", + "call.missed", + "call.ended", + "session.status", + "session.restriction_updated", + "template.status" + ] + }, + "session": { + "type": "string" + }, + "delivery": { + "type": "string", + "enum": ["generated", "simulated"] + }, + "eventId": { + "type": "string", + "nullable": true, + "format": "uuid" + }, + "source": { + "type": "string", + "enum": ["test", "runtime"] + } + }, + "required": ["event", "session", "delivery", "eventId", "source"] + }, + "PublicError": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "invalid_request_error", + "authentication_error", + "permission_error", + "billing_error", + "conflict_error", + "rate_limit_error", + "api_error", + "upstream_error" + ] + }, + "code": { + "type": "string", + "enum": [ + "zero_knowledge_session", + "invalid_parameter", + "invalid_credential", + "entitlement_required", + "cloud_template_authority_restricted", + "gate_limit_reached", + "billing_credit_required", + "addon_required", + "safe_mode_not_entitled", + "warmup_plan_not_entitled", + "method_not_allowed", + "permission_denied", + "missing_scope", + "resource_not_found", + "hms_not_enabled", + "media_fetch_failed", + "resource_gone", + "feature_unavailable", + "stream_cursor_invalid", + "stream_cursor_expired", + "stream_connection_limit_reached", + "state_conflict", + "team_deletion_scheduled", + "hybrid_routing_paused", + "hybrid_choice_required", + "hybrid_transition_ineligible", + "hybrid_automation_unavailable", + "hybrid_group_linked_devices_unavailable", + "hybrid_transport_unavailable", + "hybrid_target_reference_unavailable", + "send_outcome_unknown", + "terms_acceptance_required", + "terms_activation_blocked", + "idempotency_conflict", + "idempotency_in_progress", + "idempotency_outcome_unknown", + "idempotency_replay_unavailable", + "call_claimed", + "call_not_ringing", + "connection_limit", + "unsupported_for_connection", + "call_permission_required", + "invalid_sip_trunk", + "calls_disabled", + "call_recipient_opted_out", + "call_destination_blocked", + "call_permission_request_limited", + "call_permission_granted", + "order_status_transition_invalid", + "order_cancellation_failed", + "call_opt_out_limit", + "number_restricted", + "sip_trunk_in_use", + "sip_trunk_revision_conflict", + "sip_trunk_limit", + "sip_unavailable", + "voice_not_enabled", + "provider_credential_invalid", + "provider_unavailable", + "asset_not_ready", + "voice_asset_in_use", + "voice_asset_revision_conflict", + "voice_unavailable", + "rate_limit_exceeded", + "internal_error", + "operation_not_supported", + "upstream_failure", + "service_unavailable", + "credential_verification_unavailable", + "session_not_ready", + "command_dispatch_failed", + "result_unknown", + "parent_bsuid_not_supported", + "recipient_not_on_whatsapp", + "conversation_window_closed", + "template_not_approved", + "media_too_large", + "whatsapp_rate_limited", + "new_chat_limit_reached", + "marketing_disabled_on_cloud_api", + "whatsapp_account_restricted", + "whatsapp_authorization_required", + "whatsapp_payment_method_required", + "whatsapp_number_not_registered", + "whatsapp_groups_ineligible", + "whatsapp_group_creation_paused", + "whatsapp_group_limit_reached", + "whatsapp_group_full", + "whatsapp_group_suspended", + "whatsapp_group_has_no_participants", + "bansafe_suspended", + "bansafe_team_suspended", + "bansafe_cold_blocked", + "bansafe_cold_held", + "bansafe_throttled", + "bansafe_daily_allowance_reached", + "bansafe_accounting_unavailable", + "bansafe_send_outcome_unknown", + "campaigns_not_entitled", + "campaign_throughput_capped", + "campaign_approval_required", + "campaign_approval_stale", + "campaign_variables_missing" + ] + }, + "message": { + "type": "string" + }, + "param": { + "type": "string", + "nullable": true + }, + "request_id": { + "type": "string", + "description": "Matches the X-Request-Id response header. Include it when you contact support." + }, + "request_log_url": { + "type": "string", + "format": "uri", + "description": "Console page that shows this request. Returned only to team and project credentials whose request was logged." + } + }, + "required": ["type", "code", "message", "param", "request_id"] + }, + "data": { + "type": "string", + "nullable": true, + "enum": [null], + "description": "Always null for a failed request." + }, + "docs": { + "type": "string", + "format": "uri" + } + }, + "required": ["error", "data", "docs"] + }, + "TestEventFixtureList": { + "type": "object", + "properties": { + "fixtures": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "message.received", + "message.ack", + "message.failed", + "call.received", + "call.missed", + "call.ended", + "session.status", + "session.restriction_updated", + "template.status" + ] + }, + "description": { + "type": "string" + }, + "overrides": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["name", "description", "overrides"] + } + } + }, + "required": ["fixtures"] + } + }, + "components": { + "headers": { + "X-RateLimit-Limit": { + "description": "Team request quota per rolling minute, when the per-team request limiter applies.", + "schema": { + "type": "integer", + "minimum": 1 + } + }, + "X-RateLimit-Remaining": { + "description": "Requests left in the per-team quota; zero when this limiter rejects the request.", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + "X-RateLimit-Reset": { + "description": "Unix timestamp in seconds when the oldest counted request leaves the rolling window, when the per-team request limiter applies. Follow Retry-After on a rejected request.", + "schema": { + "type": "integer", + "minimum": 0 + } + } } } } diff --git a/contracts/testing-phone.json b/contracts/testing-phone.json index 08b6dabb1..61e7001a5 100644 --- a/contracts/testing-phone.json +++ b/contracts/testing-phone.json @@ -1,12 +1,12 @@ { "repository": "polymorfa/polymorfa", - "commit": "2f1510f901aca1d68398a6dc9dbf243348c672c0", + "commit": "f180dc1ee2bd45dbecf01702f73bdd75c664634b", "sourcePath": "apps/api/docs/openapi.json", - "sourceSha256": "ea165cf5da67985a8f3c944d4771c6e30a77bb3d081396895454db22b66d9221", + "sourceSha256": "0c66f1ee93923cf57425ac29c01a84c5c140b703ace2160e1b899ee6dad0b071", "operations": { "getTestingPhone": { "method": "GET", - "path": "/messaging/testing/{projectId}/numbers/{session}/phone", + "path": "/messaging/{session}/phone", "operation": { "operationId": "getTestingPhone", "tags": ["Testing"], @@ -18,15 +18,6 @@ "summary": "Get a Test number's phone", "x-required-scope": "sandbox:read", "parameters": [ - { - "schema": { - "type": "string", - "format": "uuid" - }, - "required": true, - "name": "projectId", - "in": "path" - }, { "schema": { "type": "string", @@ -45,7 +36,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TestingPhoneState" + "$ref": "#/schemas/TestingPhoneState" } } }, @@ -61,38 +52,6 @@ } } }, - "400": { - "description": "The session is not a Test number in the project", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PublicError" - }, - "example": { - "error": { - "type": "invalid_request_error", - "code": "invalid_parameter", - "message": "Correct the invalid request field.", - "param": null, - "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" - }, - "data": null, - "docs": "https://docs.polymorfa.com/api/errors#invalid-parameter" - } - } - } - }, "403": { "description": "Test numbers access required, or a client token was used", "headers": { @@ -109,7 +68,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -126,7 +85,7 @@ } }, "404": { - "description": "Project not found", + "description": "Resource not found", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -141,7 +100,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -173,7 +132,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -191,14 +150,15 @@ } }, "x-mint": { - "content": "sandbox:read" + "content": "Linked Device API sandbox:read" }, - "description": "**Required scope:** `sandbox:read`" + "x-protocols": ["Linked Device API"], + "description": "**Protocols:** Linked Device API\n\n**Required scope:** `sandbox:read`" } }, "sendTestingPhoneMessage": { "method": "POST", - "path": "/messaging/testing/{projectId}/numbers/{session}/phone/messages", + "path": "/messaging/{session}/phone/messages", "operation": { "operationId": "sendTestingPhoneMessage", "tags": ["Testing"], @@ -210,15 +170,6 @@ "summary": "Send a message from a Test number's phone", "x-required-scope": "sandbox:write", "parameters": [ - { - "schema": { - "type": "string", - "format": "uuid" - }, - "required": true, - "name": "projectId", - "in": "path" - }, { "schema": { "type": "string", @@ -236,7 +187,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TestingPhoneMessageRequest" + "$ref": "#/schemas/TestingPhoneMessageRequest" } } } @@ -247,7 +198,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TestingPhoneMessage" + "$ref": "#/schemas/TestingPhoneMessage" } } }, @@ -264,7 +215,7 @@ } }, "400": { - "description": "The session or recipient is not a Test number in the project, or the phone is offline", + "description": "Invalid recipient, or the phone is offline", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -279,7 +230,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -311,7 +262,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -328,7 +279,7 @@ } }, "404": { - "description": "Project not found", + "description": "Resource not found", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -343,7 +294,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -375,7 +326,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -407,7 +358,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -425,14 +376,15 @@ } }, "x-mint": { - "content": "sandbox:write" + "content": "Linked Device API sandbox:write" }, - "description": "**Required scope:** `sandbox:write`" + "x-protocols": ["Linked Device API"], + "description": "**Protocols:** Linked Device API\n\n**Required scope:** `sandbox:write`" } }, "unlinkTestingPhoneDevice": { "method": "POST", - "path": "/messaging/testing/{projectId}/numbers/{session}/phone/devices/{deviceId}/unlink", + "path": "/messaging/{session}/phone/devices/{deviceId}/unlink", "operation": { "operationId": "unlinkTestingPhoneDevice", "tags": ["Testing"], @@ -444,15 +396,6 @@ "summary": "Unlink a companion from a Test number's phone", "x-required-scope": "sandbox:write", "parameters": [ - { - "schema": { - "type": "string", - "format": "uuid" - }, - "required": true, - "name": "projectId", - "in": "path" - }, { "schema": { "type": "string", @@ -482,7 +425,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TestingPhoneUnlink" + "$ref": "#/schemas/TestingPhoneUnlink" } } }, @@ -499,7 +442,7 @@ } }, "400": { - "description": "The session is not a Test number in the project, or the phone is offline", + "description": "The phone is offline", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -514,7 +457,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -546,7 +489,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -578,7 +521,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -610,7 +553,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PublicError" + "$ref": "#/schemas/PublicError" }, "example": { "error": { @@ -628,9 +571,10 @@ } }, "x-mint": { - "content": "sandbox:write" + "content": "Linked Device API sandbox:write" }, - "description": "**Required scope:** `sandbox:write`" + "x-protocols": ["Linked Device API"], + "description": "**Protocols:** Linked Device API\n\n**Required scope:** `sandbox:write`" } } }, @@ -677,6 +621,7 @@ "invalid_request_error", "authentication_error", "permission_error", + "billing_error", "conflict_error", "rate_limit_error", "api_error", @@ -686,11 +631,16 @@ "code": { "type": "string", "enum": [ + "zero_knowledge_session", "invalid_parameter", "invalid_credential", "entitlement_required", "cloud_template_authority_restricted", "gate_limit_reached", + "billing_credit_required", + "addon_required", + "safe_mode_not_entitled", + "warmup_plan_not_entitled", "method_not_allowed", "permission_denied", "missing_scope", @@ -703,17 +653,21 @@ "stream_cursor_expired", "stream_connection_limit_reached", "state_conflict", + "team_deletion_scheduled", "hybrid_routing_paused", "hybrid_choice_required", "hybrid_transition_ineligible", "hybrid_automation_unavailable", + "hybrid_group_linked_devices_unavailable", "hybrid_transport_unavailable", "hybrid_target_reference_unavailable", "send_outcome_unknown", + "terms_acceptance_required", + "terms_activation_blocked", "idempotency_conflict", "idempotency_in_progress", - "idempotency_completed", "idempotency_outcome_unknown", + "idempotency_replay_unavailable", "call_claimed", "call_not_ringing", "connection_limit", @@ -749,13 +703,18 @@ "session_not_ready", "command_dispatch_failed", "result_unknown", + "parent_bsuid_not_supported", "recipient_not_on_whatsapp", "conversation_window_closed", "template_not_approved", "media_too_large", "whatsapp_rate_limited", "new_chat_limit_reached", + "marketing_disabled_on_cloud_api", "whatsapp_account_restricted", + "whatsapp_authorization_required", + "whatsapp_payment_method_required", + "whatsapp_number_not_registered", "whatsapp_groups_ineligible", "whatsapp_group_creation_paused", "whatsapp_group_limit_reached", @@ -858,5 +817,30 @@ }, "required": ["session", "deviceId", "unlinked"] } + }, + "components": { + "headers": { + "X-RateLimit-Limit": { + "description": "Team request quota per rolling minute, when the per-team request limiter applies.", + "schema": { + "type": "integer", + "minimum": 1 + } + }, + "X-RateLimit-Remaining": { + "description": "Requests left in the per-team quota; zero when this limiter rejects the request.", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + "X-RateLimit-Reset": { + "description": "Unix timestamp in seconds when the oldest counted request leaves the rolling window, when the per-team request limiter applies. Follow Retry-After on a rejected request.", + "schema": { + "type": "integer", + "minimum": 0 + } + } + } } } diff --git a/packages/dotnet/README.md b/packages/dotnet/README.md index 0cae7e072..5f9d48931 100644 --- a/packages/dotnet/README.md +++ b/packages/dotnet/README.md @@ -39,7 +39,7 @@ Known webhooks have typed payloads for all 84 names in the pinned TypeScript con `Events.LiveSource` and `EventStreamSource` feed decoded webhook bodies to an application-owned store. Each subscription resumes from its saved cursor and skips events whose body was not retained. Dispose the subscription to stop delivery; await `DisposeAsync` or `Completion` to wait for stream cleanup. `OnError` receives terminal stream or listener failures. -The existing coverage ledger records 442 covered operations. The separate campaign/custody supplement adds 30 source implementations with TCP fixtures; its ledger adoption is pending. Graph and testing-phone supplements retain their separate fixtures. This is source-level contract coverage, not a registry release or hosted acceptance result. +The existing coverage ledger records 445 covered operations. The separate campaign/custody supplement adds 30 source implementations with TCP fixtures; its ledger adoption is pending. Graph and testing-phone supplements retain their separate fixtures. This is source-level contract coverage, not a registry release or hosted acceptance result. `CallsClient` tracks incoming and outgoing calls. `Call` provides answer, join, reject, leave, end, participant controls and typed media frames. Connections authenticate in the first WebSocket frame, refresh expiring credentials, detect missed heartbeats and reconnect within a bounded attempt budget. Media reconnect preserves connection identity and acknowledged preferences. `CallsTokenSource` shares concurrent provider requests while preserving each caller's cancellation. PCM uses the rate announced in `Call.SampleRate`; H.264 frames retain timestamps. Outgoing H.264 uses the protocol's reserved source zero; received source ownership is exposed separately. @@ -1114,6 +1114,16 @@ Task>> ConfirmExplicitly() => client.Passkeys.ConfirmAsync(session, suppliedConfirmation); ``` +## Number-scoped Test operations + +The Test phone methods take a Number ID, without a project argument: +~~~csharp +var phone = await client.Testing.GetPhoneAsync("support"); +var testEvent = await client.Testing.TriggerEventAsync("support", new("call.missed", FromNumber: "sales")); +var fixtures = await client.Testing.ListEventFixturesAsync(); +~~~ + +Send-phone-message and unlink-device helpers use the same Number scope. The trigger body contains event, optional overrides and optional fromNumber; it does not contain session or fromSession. The static fixture catalog has no project argument. History-fixture creation remains project-scoped. These operations require a server credential and the API’s Test-number access checks; a helper does not grant access or make a real Number a Test number. ## Guest participants and waiting rooms (unreleased) diff --git a/packages/dotnet/coverage.json b/packages/dotnet/coverage.json index 96cf089ee..52e856f5a 100644 --- a/packages/dotnet/coverage.json +++ b/packages/dotnet/coverage.json @@ -4517,9 +4517,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/{session}/phone", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.GetPhoneAsync", + "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "family": "messaging", @@ -4557,9 +4557,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/test-events/fixtures", - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient.Testing.ListEventFixturesAsync) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.ListEventFixturesAsync", + "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "family": "messaging", @@ -4629,17 +4629,17 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/devices/{deviceId}/unlink", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.UnlinkPhoneDeviceAsync", + "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/messages", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.SendPhoneMessageAsync", + "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "family": "messaging", @@ -4669,9 +4669,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/test-events", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient.Testing.TriggerEventAsync) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.TriggerEventAsync", + "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "family": "messaging", @@ -4685,9 +4685,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/projects/{projectId}/test-history-fixtures", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient.Testing.CreateHistoryFixtureAsync) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.CreateHistoryFixtureAsync", + "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "family": "messaging", diff --git a/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs b/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs index 9df71f883..936a74f09 100644 --- a/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs +++ b/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs @@ -12,7 +12,7 @@ public sealed record TestingHistoryMessage(string Id, string SenderPhone, string public sealed record CreateTestingHistoryFixtureRequest(IReadOnlyList Messages); public sealed record TestingHistoryFixtureCreated(string FixtureId); public sealed record TestEventOverrides(string? Text = null, string? From = null, string? PushName = null, string? MediaType = null, string? Caption = null, string? AckStatus = null, string? MessageId = null, string? FailureReason = null, bool? Video = null, decimal? DurationSeconds = null, string? CallEndReason = null, bool? RestrictionActive = null, string? Status = null, string? StatusReason = null, string? TemplateName = null, string? TemplateStatus = null, string? Reason = null); -public sealed record TriggerTestEventRequest(string Session, string Event, TestEventOverrides? Overrides = null, string? FromSession = null); +public sealed record TriggerTestEventRequest(string Event, TestEventOverrides? Overrides = null, string? FromNumber = null); public sealed record TriggerTestEventResponse(string Event, string Session, string Delivery, string? EventId, string Source); public sealed record TestEventFixtureInfo(string Name, string Description, IReadOnlyList Overrides); public sealed record TestEventFixtures(IReadOnlyList Fixtures); @@ -24,15 +24,15 @@ public sealed record UnlinkTestingPhoneDeviceResponse(string Session, int Device public sealed class Testing : Resource { internal Testing(HttpTransport http) : base(http) { } - private static string Path(string projectId) => "/messaging/testing/" + E(projectId); - private static string PhonePath(string projectId, string session) => Path(projectId) + "/numbers/" + E(session) + "/phone"; + private static string Path(string projectId) => "/messaging/projects/" + E(projectId); + private static string PhonePath(string session) => "/messaging/" + E(session) + "/phone"; private Task> Request(HttpMethod method, string path, object? body, RequestOptions? options) { Http.Credential.RequireServer(); return Http.RequestAsync(method, path, body, options); } - public Task> CreateHistoryFixtureAsync(string projectId, CreateTestingHistoryFixtureRequest input, RequestOptions? options = null) => Request(HttpMethod.Post, Path(projectId) + "/history-fixtures", input, options); - public Task> TriggerEventAsync(string projectId, TriggerTestEventRequest input, RequestOptions? options = null) => Request(HttpMethod.Post, Path(projectId) + "/events", input, options); - public Task> ListEventFixturesAsync(string projectId, RequestOptions? options = null) => Request(HttpMethod.Get, Path(projectId) + "/events/fixtures", null, options); - public Task> GetPhoneAsync(string projectId, string session, RequestOptions? options = null) { Http.Credential.RequireServer(); return ExistingContractCodec.Request(Http, HttpMethod.Get, PhonePath(projectId, session), options: options); } - public Task> SendPhoneMessageAsync(string projectId, string session, SendTestingPhoneMessageRequest input, RequestOptions? options = null) { Http.Credential.RequireServer(); return ExistingContractCodec.Request(Http, HttpMethod.Post, PhonePath(projectId, session) + "/messages", ExistingContractCodec.Capture(input), options, status: 202); } - public Task> UnlinkPhoneDeviceAsync(string projectId, string session, int deviceId, RequestOptions? options = null) { if (deviceId is < 1 or > 99) throw new PolymorfaValidationException("deviceId must be a companion ID from 1 to 99.", "invalid_parameter"); Http.Credential.RequireServer(); return ExistingContractCodec.Request(Http, HttpMethod.Post, PhonePath(projectId, session) + "/devices/" + deviceId + "/unlink", options: options); } + public Task> CreateHistoryFixtureAsync(string projectId, CreateTestingHistoryFixtureRequest input, RequestOptions? options = null) => Request(HttpMethod.Post, Path(projectId) + "/test-history-fixtures", input, options); + public Task> TriggerEventAsync(string session, TriggerTestEventRequest input, RequestOptions? options = null) => Request(HttpMethod.Post, "/messaging/" + E(session) + "/test-events", input, options); + public Task> ListEventFixturesAsync(RequestOptions? options = null) => Request(HttpMethod.Get, "/messaging/test-events/fixtures", null, options); + public Task> GetPhoneAsync(string session, RequestOptions? options = null) { Http.Credential.RequireServer(); return ExistingContractCodec.Request(Http, HttpMethod.Get, PhonePath(session), options: options); } + public Task> SendPhoneMessageAsync(string session, SendTestingPhoneMessageRequest input, RequestOptions? options = null) { Http.Credential.RequireServer(); return ExistingContractCodec.Request(Http, HttpMethod.Post, PhonePath(session) + "/messages", ExistingContractCodec.Capture(input), options, status: 202); } + public Task> UnlinkPhoneDeviceAsync(string session, int deviceId, RequestOptions? options = null) { if (deviceId is < 1 or > 99) throw new PolymorfaValidationException("deviceId must be a companion ID from 1 to 99.", "invalid_parameter"); Http.Credential.RequireServer(); return ExistingContractCodec.Request(Http, HttpMethod.Post, PhonePath(session) + "/devices/" + deviceId + "/unlink", options: options); } } public sealed record ProjectObservationPolicy(string ProjectId, string PresenceMode, string TypingMode, string LabelMode, string? QuickReplyMode = null); public sealed record SessionObservationPolicyValues(string PresenceMode, string TypingMode, string LabelMode, string? QuickReplyMode = null); diff --git a/packages/dotnet/supplements.json b/packages/dotnet/supplements.json index c7f995e3c..5ed02a560 100644 --- a/packages/dotnet/supplements.json +++ b/packages/dotnet/supplements.json @@ -40,21 +40,21 @@ { "sdkMethod": "MessagingClient.Testing.GetPhoneAsync", "method": "GET", - "fixturePath": "/messaging/testing/p1/numbers/support/phone", + "fixturePath": "/messaging/support/phone", "status": "covered", "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "sdkMethod": "MessagingClient.Testing.SendPhoneMessageAsync", "method": "POST", - "fixturePath": "/messaging/testing/p1/numbers/support/phone/messages", + "fixturePath": "/messaging/support/phone/messages", "status": "covered", "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, { "sdkMethod": "MessagingClient.Testing.UnlinkPhoneDeviceAsync", "method": "POST", - "fixturePath": "/messaging/testing/p1/numbers/support/phone/devices/1/unlink", + "fixturePath": "/messaging/support/phone/devices/1/unlink", "status": "covered", "testFile": "tests/Polymorfa.Sdk.Tests/OnboardingTests.cs" }, diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineBoundary41Tests.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineBoundary41Tests.cs index 2da846fc0..f080b5687 100644 --- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineBoundary41Tests.cs +++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineBoundary41Tests.cs @@ -11,9 +11,9 @@ internal static async Task RunAsync() var boundaries = new Boundary[] { new("group", "GET", "/messaging/s/groups/g/capabilities", null, "{\"success\":true,\"data\":{\"status\":\"synced\",\"syncedAt\":null,\"checkedAt\":null,\"capabilities\":[]}}", 200, "2026-09-22", async (c, _, o) => { await c.Groups.GetCapabilitiesAsync("s", "g", o); }), - new("phone", "GET", "/messaging/testing/p/numbers/s/phone", null, "{\"session\":\"s\",\"phone\":\"+15550001111\",\"online\":false,\"devices\":[]}", 200, "2026-09-22", async (c, _, o) => { await c.Testing.GetPhoneAsync("p", "s", o); }), - new("send-phone", "POST", "/messaging/testing/p/numbers/s/phone/messages", "{\"to\":\"to\",\"text\":\"text\"}", "{\"session\":\"s\",\"to\":\"to\",\"messageId\":null}", 202, "2026-09-22", async (c, _, o) => { await c.Testing.SendPhoneMessageAsync("p", "s", new("to", "text"), o); }), - new("unlink", "POST", "/messaging/testing/p/numbers/s/phone/devices/1/unlink", null, "{\"session\":\"s\",\"deviceId\":1,\"unlinked\":true}", 200, "2026-09-22", async (c, _, o) => { await c.Testing.UnlinkPhoneDeviceAsync("p", "s", 1, o); }), + new("phone", "GET", "/messaging/s/phone", null, "{\"session\":\"s\",\"phone\":\"+15550001111\",\"online\":false,\"devices\":[]}", 200, "2026-09-22", async (c, _, o) => { await c.Testing.GetPhoneAsync("s", o); }), + new("send-phone", "POST", "/messaging/s/phone/messages", "{\"to\":\"to\",\"text\":\"text\"}", "{\"session\":\"s\",\"to\":\"to\",\"messageId\":null}", 202, "2026-09-22", async (c, _, o) => { await c.Testing.SendPhoneMessageAsync("s", new("to", "text"), o); }), + new("unlink", "POST", "/messaging/s/phone/devices/1/unlink", null, "{\"session\":\"s\",\"deviceId\":1,\"unlinked\":true}", 200, "2026-09-22", async (c, _, o) => { await c.Testing.UnlinkPhoneDeviceAsync("s", 1, o); }), new("logs", "GET", "/platform/projects/p/request-logs", null, "{\"data\":[],\"page\":{\"hasMore\":false,\"nextCursor\":null,\"followCursor\":\"f\"}}", 200, "2026-09-22", async (_, c, o) => { await c.RequestLogs.ListAsync(new("p"), o); }), new("grant", "POST", "/messaging/s/media/upload-grants", "{\"type\":\"image\",\"fileEncSha256\":\"" + encoded + "\"}", "{\"success\":true,\"data\":{\"host\":\"mmg.whatsapp.net\",\"uploadUrl\":\"https://mmg.whatsapp.net/mms/image/" + encoded + "?auth=synthetic\",\"expiresAt\":2000000000}}", 200, "2026-10-14", async (c, _, o) => { var grant = await c.WhatsAppMedia.CreateUploadGrantAsync("s", WhatsAppUploadMediaType.Image, new byte[32], o); Check(grant.ExpiresAt.ToUnixTimeSeconds() == 2000000000, "Expiry units"); }), new("relay", "POST", "/messaging/s/media/uploads?type=image&fileEncSha256=" + encoded, "bytes:AQ==", "{\"success\":true,\"data\":{\"directPath\":\"/x\",\"url\":\"https://mmg.whatsapp.net/x\"}}", 200, "2026-10-14", async (c, _, o) => { using var bytes = new MemoryStream(new byte[] { 1 }); await c.WhatsAppMedia.RelayUploadAsync("s", WhatsAppUploadMediaType.Image, new byte[32], bytes, 1, o); Check(bytes.CanRead, "Borrowed relay input"); }), diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineSeams41Tests.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineSeams41Tests.cs index b942c0952..2f9b7de54 100644 --- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineSeams41Tests.cs +++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/NineSeams41Tests.cs @@ -11,14 +11,14 @@ internal static async Task RunAsync() await Messaging("GET", "/messaging/s%2Fone/groups/g%40group/capabilities", null, caps, async c => { var v = (await c.Groups.GetCapabilitiesAsync("s/one", "g@group")).Data.Data; Check(v.Capabilities[0].Value is null && v.Capabilities[1].Value == false && v.CheckedAt is null, "Nullable group facts"); }); await Messaging("GET", "/messaging/s/groups/g/capabilities", null, caps.Replace("\"unit\":null,", ""), c => InvalidResponse(async () => { await c.Groups.GetCapabilitiesAsync("s", "g"); })); const string phone = "{\"session\":\"s\",\"phone\":\"+15550001111\",\"online\":false,\"devices\":[{\"deviceId\":99}]}"; - await Messaging("GET", "/messaging/testing/p/numbers/s/phone", null, phone, async c => Check(!(await c.Testing.GetPhoneAsync("p", "s")).Data.Online, "Phone offline")); - await Messaging("POST", "/messaging/testing/p/numbers/s/phone/messages", "{\"to\":\"+15550001111\",\"text\":\"Hello\"}", "{\"session\":\"s\",\"to\":\"+15550001111\",\"messageId\":null}", async c => Check((await c.Testing.SendPhoneMessageAsync("p", "s", new("+15550001111", "Hello"))).Data.MessageId is null, "Accepted nullable messageId"), 202); - await Messaging("POST", "/messaging/testing/p/numbers/s/phone/messages", "{\"to\":\"+15550001111\",\"text\":\"Hello\"}", "{\"session\":\"s\",\"to\":\"+15550001111\"}", c => InvalidResponse(async () => { await c.Testing.SendPhoneMessageAsync("p", "s", new("+15550001111", "Hello")); }), 202); - await Messaging("POST", "/messaging/testing/p/numbers/s/phone/devices/99/unlink", null, "{\"session\":\"s\",\"deviceId\":99,\"unlinked\":true}", async c => Check((await c.Testing.UnlinkPhoneDeviceAsync("p", "s", 99)).Data.Unlinked, "Unlink99")); - await Messaging("POST", "/messaging/testing/p/numbers/s/phone/devices/1/unlink", null, "{\"session\":\"s\",\"deviceId\":1,\"unlinked\":false}", c => InvalidResponse(async () => { await c.Testing.UnlinkPhoneDeviceAsync("p", "s", 1); })); + await Messaging("GET", "/messaging/s/phone", null, phone, async c => Check(!(await c.Testing.GetPhoneAsync("s")).Data.Online, "Phone offline")); + await Messaging("POST", "/messaging/s/phone/messages", "{\"to\":\"+15550001111\",\"text\":\"Hello\"}", "{\"session\":\"s\",\"to\":\"+15550001111\",\"messageId\":null}", async c => Check((await c.Testing.SendPhoneMessageAsync("s", new("+15550001111", "Hello"))).Data.MessageId is null, "Accepted nullable messageId"), 202); + await Messaging("POST", "/messaging/s/phone/messages", "{\"to\":\"+15550001111\",\"text\":\"Hello\"}", "{\"session\":\"s\",\"to\":\"+15550001111\"}", c => InvalidResponse(async () => { await c.Testing.SendPhoneMessageAsync("s", new("+15550001111", "Hello")); }), 202); + await Messaging("POST", "/messaging/s/phone/devices/99/unlink", null, "{\"session\":\"s\",\"deviceId\":99,\"unlinked\":true}", async c => Check((await c.Testing.UnlinkPhoneDeviceAsync("s", 99)).Data.Unlinked, "Unlink99")); + await Messaging("POST", "/messaging/s/phone/devices/1/unlink", null, "{\"session\":\"s\",\"deviceId\":1,\"unlinked\":false}", c => InvalidResponse(async () => { await c.Testing.UnlinkPhoneDeviceAsync("s", 1); })); foreach (var id in new[] { 0, 100 }) { - using var c = new MessagingClient(Key); try { await c.Testing.UnlinkPhoneDeviceAsync("p", "s", id); throw new Exception("Invalid unlink accepted"); } catch (PolymorfaValidationException) { Check(true, "Unlink bounds"); } + using var c = new MessagingClient(Key); try { await c.Testing.UnlinkPhoneDeviceAsync("s", id); throw new Exception("Invalid unlink accepted"); } catch (PolymorfaValidationException) { Check(true, "Unlink bounds"); } } const string log = "{\"id\":\"9007199254740993123\",\"projectId\":\"p\",\"createdAt\":\"2026-10-14T00:00:00Z\",\"method\":\"GET\",\"route\":\"/messaging/:session\",\"status\":200,\"durationMs\":0,\"result\":\"success\",\"source\":\"api\",\"requestId\":null,\"traceId\":null,\"errorCode\":null,\"mcpTool\":null,\"credential\":null}"; foreach (var selected in new[] { Project, "22222222-2222-4222-8222-222222222222", Project }) @@ -41,9 +41,9 @@ internal static async Task RunAsync() await ClientGuardsAsync(c => c.HistorySync.RequestChunkRetryAsync("s", new(HistorySyncType.FULL, 0))); await ClientGuardsAsync(c => c.HistorySync.DeleteChunkAsync("s", new("/x", hash))); await ClientGuardsAsync(c => c.WhatsAppMedia.CreateUploadGrantAsync("s", WhatsAppUploadMediaType.Image, new byte[32])); - await ClientGuardsAsync(c => c.Testing.GetPhoneAsync("p", "s")); - await ClientGuardsAsync(c => c.Testing.SendPhoneMessageAsync("p", "s", new("to", "text"))); - await ClientGuardsAsync(c => c.Testing.UnlinkPhoneDeviceAsync("p", "s", 1)); + await ClientGuardsAsync(c => c.Testing.GetPhoneAsync("s")); + await ClientGuardsAsync(c => c.Testing.SendPhoneMessageAsync("s", new("to", "text"))); + await ClientGuardsAsync(c => c.Testing.UnlinkPhoneDeviceAsync("s", 1)); using (var wire = new WireFixture()) using (var c = new MessagingClient(Credential.ClientToken("pmfa_ct_Zml4dHVyZQ"), Options(wire))) { diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/OnboardingTests.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/OnboardingTests.cs index eb697f65a..f829c56b0 100644 --- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/OnboardingTests.cs +++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/OnboardingTests.cs @@ -5,20 +5,20 @@ internal static class OnboardingTests public static async Task RunAsync() { await Messaging("POST", "/messaging/cloud-api/embedded-signup", """{"quicklinkId":"q1","projectId":"p1","result":{"code":"fixture-code","wabaId":"waba1","phoneNumberId":"pn1","coexistence":false,"historySync":false}}""", """{"success":true,"data":{"stage":"connected"}}""", async c => ResourceTests.Equal((await c.CloudOnboarding.AdvanceAsync(new("q1", "p1", new("fixture-code", "waba1", "pn1", false, false)))).Data.Data.Stage, "connected")); - await Messaging("POST", "/messaging/testing/p1/history-fixtures", """{"messages":[{"id":"m1","senderPhone":"+15550001111","text":"Hello","timestamp":9007199254740993,"fromMe":false}]}""", """{"fixtureId":"fixture1"}""", async c => ResourceTests.Equal((await c.Testing.CreateHistoryFixtureAsync("p1", new([new("m1", "+15550001111", "Hello", 9007199254740993L, false)]))).Data.FixtureId, "fixture1")); - await Messaging("POST", "/messaging/testing/p1/events", """{"session":"support","event":"message.received","overrides":{"text":"Hello","video":false,"restrictionActive":false},"fromSession":"other"}""", """{"event":"message.received","session":"support","delivery":"simulated","eventId":null,"source":"runtime"}""", async c => ResourceTests.Equal((await c.Testing.TriggerEventAsync("p1", new("support", "message.received", new(Text: "Hello", Video: false, RestrictionActive: false), "other"))).Data.EventId, null)); - await Messaging("GET", "/messaging/testing/p1/events/fixtures", null, """{"fixtures":[{"name":"message.received","description":"Inbound","overrides":["text","from"]}]}""", async c => ResourceTests.Equal((await c.Testing.ListEventFixturesAsync("p1")).Data.Fixtures[0].Overrides[0], "text")); - await Messaging("GET", "/messaging/testing/p1/numbers/support/phone", null, """{"session":"support","phone":"+15550001111","online":false,"devices":[{"deviceId":1}]}""", async c => ResourceTests.True(!(await c.Testing.GetPhoneAsync("p1", "support")).Data.Online)); - await CampaignExistingTests.Messaging("POST", "/messaging/testing/p1/numbers/support/phone/messages", """{"to":"+15550002222","text":"Hello"}""", """{"session":"support","to":"+15550002222","messageId":null}""", async c => ResourceTests.Equal((await c.Testing.SendPhoneMessageAsync("p1", "support", new("+15550002222", "Hello"))).Data.MessageId, null), status: 202); - await Messaging("POST", "/messaging/testing/p1/numbers/support/phone/devices/1/unlink", null, """{"session":"support","deviceId":1,"unlinked":true}""", async c => ResourceTests.True((await c.Testing.UnlinkPhoneDeviceAsync("p1", "support", 1)).Data.Unlinked)); + await Messaging("POST", "/messaging/projects/p1/test-history-fixtures", """{"messages":[{"id":"m1","senderPhone":"+15550001111","text":"Hello","timestamp":9007199254740993,"fromMe":false}]}""", """{"fixtureId":"fixture1"}""", async c => ResourceTests.Equal((await c.Testing.CreateHistoryFixtureAsync("p1", new([new("m1", "+15550001111", "Hello", 9007199254740993L, false)]))).Data.FixtureId, "fixture1")); + await Messaging("POST", "/messaging/support/test-events", """{"event":"message.received","overrides":{"text":"Hello","video":false,"restrictionActive":false},"fromNumber":"other"}""", """{"event":"message.received","session":"support","delivery":"simulated","eventId":null,"source":"runtime"}""", async c => ResourceTests.Equal((await c.Testing.TriggerEventAsync("support", new("message.received", new(Text: "Hello", Video: false, RestrictionActive: false), "other"))).Data.EventId, null)); + await Messaging("GET", "/messaging/test-events/fixtures", null, """{"fixtures":[{"name":"message.received","description":"Inbound","overrides":["text","from"]}]}""", async c => ResourceTests.Equal((await c.Testing.ListEventFixturesAsync()).Data.Fixtures[0].Overrides[0], "text")); + await Messaging("GET", "/messaging/support/phone", null, """{"session":"support","phone":"+15550001111","online":false,"devices":[{"deviceId":1}]}""", async c => ResourceTests.True(!(await c.Testing.GetPhoneAsync("support")).Data.Online)); + await CampaignExistingTests.Messaging("POST", "/messaging/support/phone/messages", """{"to":"+15550002222","text":"Hello"}""", """{"session":"support","to":"+15550002222","messageId":null}""", async c => ResourceTests.Equal((await c.Testing.SendPhoneMessageAsync("support", new("+15550002222", "Hello"))).Data.MessageId, null), status: 202); + await Messaging("POST", "/messaging/support/phone/devices/1/unlink", null, """{"session":"support","deviceId":1,"unlinked":true}""", async c => ResourceTests.True((await c.Testing.UnlinkPhoneDeviceAsync("support", 1)).Data.Unlinked)); await Messaging("GET", "/messaging/projects/p1/observation-policy", null, """{"success":true,"data":{"projectId":"p1","presenceMode":"follow","typingMode":"off","labelMode":"off","quickReplyMode":"follow"}}""", async c => ResourceTests.Equal((await c.ObservationPolicies.RetrieveForProjectAsync("p1")).Data.Data.LabelMode, "off")); await Messaging("GET", "/messaging/support/observation-policy", null, """{"success":true,"data":{"sessionName":"support","projectId":"p1","project":{"presenceMode":"follow","typingMode":"off","labelMode":"off","quickReplyMode":"follow"},"override":{"presenceMode":"inherit","typingMode":"inherit","labelMode":"inherit","quickReplyMode":"off"},"effective":{"presenceMode":"follow","typingMode":"off","labelMode":"off","quickReplyMode":"off"}}}""", async c => ResourceTests.Equal((await c.ObservationPolicies.RetrieveForSessionAsync("support")).Data.Data.Effective.QuickReplyMode, "off")); await Messaging("GET", "/messaging/routing/hybrid?scope=project&projectId=p1", null, """{"success":true,"data":{"scope":"project","revision":"rev1","prefer":null,"allowedTransports":["official_api","linked_devices"]}}""", async c => ResourceTests.Equal((await c.HybridLink.GetPolicyAsync(HybridRoutingPolicyScope.Project("p1"))).Data.Data.Prefer, null)); await Messaging("PUT", "/messaging/routing/hybrid?scope=session&projectId=p1&session=support", """{"expectedRevision":"rev1","prefer":null,"allowedTransports":[]}""", """{"success":true,"data":{"scope":"session","revision":"rev2","prefer":null,"allowedTransports":[]}}""", async c => ResourceTests.Equal((await c.HybridLink.SetPolicyAsync(HybridRoutingPolicyScope.Number("p1", "support"), new("rev1", null, []))).Data.Data.Revision, "rev2")); await Messaging("GET", "/messaging/support/hybrid-link", null, """{"success":true,"data":{"revision":"rev1","paused":false,"connections":[{"kind":"official_api","status":"connected","enabled":true}]}}""", async c => ResourceTests.True(!(await c.HybridLink.StateAsync("support")).Data.Data.Paused)); await Messaging("PUT", "/messaging/support/hybrid-link", """{"expectedRevision":"rev1","paused":false}""", """{"success":true,"data":{"revision":"rev2","paused":false}}""", async c => ResourceTests.Equal((await c.HybridLink.SetPausedAsync("support", new("rev1", false))).Data.Data.Revision, "rev2")); - using var token = new MessagingClient(Credential.ClientToken("pmfa_ct_Zml4dHVyZQ")); try { await token.Testing.GetPhoneAsync("p1", "support"); throw new Exception("Client operated phone"); } catch (PolymorfaConfigurationException) { } - using var server = new MessagingClient(Credential.TeamApiKey("pmfa_AAECAwQFBgcICQoLDA0ODxAREhM73f-k")); try { await server.Testing.UnlinkPhoneDeviceAsync("p1", "support", 0); throw new Exception("Primary device unlink accepted"); } catch (PolymorfaValidationException) { } + using var token = new MessagingClient(Credential.ClientToken("pmfa_ct_Zml4dHVyZQ")); try { await token.Testing.GetPhoneAsync("support"); throw new Exception("Client operated phone"); } catch (PolymorfaConfigurationException) { } + using var server = new MessagingClient(Credential.TeamApiKey("pmfa_AAECAwQFBgcICQoLDA0ODxAREhM73f-k")); try { await server.Testing.UnlinkPhoneDeviceAsync("support", 0); throw new Exception("Primary device unlink accepted"); } catch (PolymorfaValidationException) { } ResourceTests.Equal(HybridLink.GraphTransportHeaders("official_api")["X-Polymorfa-Transport"], "official_api"); ResourceTests.True(!new EmbeddedSignupResult("fixture-code", "waba1", "pn1").ToString().Contains("fixture-code")); Console.WriteLine("PASS trusted onboarding, testing events/history/phone, resolved observation and Hybrid routing policies"); } diff --git a/packages/go/README.md b/packages/go/README.md index 1a49fb10a..7b672bd26 100644 --- a/packages/go/README.md +++ b/packages/go/README.md @@ -1,6 +1,6 @@ # Polymorfa Go SDK -Handwritten server SDK for Go 1.24 or newer. This source checkout is under development and has not been published. The checked coverage manifest records native request/response evidence for all 439 primary operations supported by TypeScript SDK commit `e24cb176fc1124f5fe852ff6c77902648fd13b4a`, plus three campaign supplements in the ledger. Eight additional Graph and testing-phone routes and the eleven frequency-cap, audience-segment and drip operations in `contracts/native-campaign-supplements.json` have typed wire tests. This evidence describes SDK contracts, not deployed feature availability. +Handwritten server SDK for Go 1.24 or newer. This source checkout is under development and has not been published. The primary ledger records 445 covered operations; mapping, native execution, package verification and deployed availability are separate evidence. The module import is `github.com/polymorfa/sdks/packages/go`. This corrects the proposed `github.com/polymorfa/sdks/go` name to match the actual repository subdirectory. A release from this layout needs a `packages/go/vX.Y.Z` tag. Do not advertise an installation version until that version exists. For local work, use the `replace` directive in `examples/go/send-message/go.mod`. @@ -921,6 +921,18 @@ confirmExplicitly := func() error { _ = confirmExplicitly ``` +## Number-scoped Test operations + +The Test phone methods take a Number ID, without a project argument: +~~~go +phone, err := client.Testing().GetPhone(ctx, "support") +event, err := client.Testing().TriggerEvent(ctx, "support", polymorfa.TriggerTestEventRequest{ + Event: "call.missed", FromNumber: "sales", +}) +fixtures, err := client.Testing().ListEventFixtures(ctx) +~~~ + +Send-phone-message and unlink-device helpers use the same Number scope. The trigger body contains event, optional overrides and optional fromNumber; it does not contain session or fromSession. The static fixture catalog has no project argument. History-fixture creation remains project-scoped. These operations require a server credential and the API’s Test-number access checks; a helper does not grant access or make a real Number a Test number. ## Guest participants and waiting rooms (unreleased) diff --git a/packages/go/cloud_audiences_test.go b/packages/go/cloud_audiences_test.go index 38a20ad02..e9a273576 100644 --- a/packages/go/cloud_audiences_test.go +++ b/packages/go/cloud_audiences_test.go @@ -23,14 +23,14 @@ var cloudAudienceFixtures = []operationFixture{ v := false return wireData(m.CloudOnboarding().Advance(ctx, EmbeddedSignupRequest{QuickLinkID: "link", ProjectID: "p", Result: &EmbeddedSignupResult{Code: "fixture-code", WABAID: "waba", PhoneNumberID: "phone", Coexistence: &v}})) }}, - {"MessagingClient.Testing.CreateHistoryFixture", "POST", "/messaging/testing/p/history-fixtures", "", `{"messages":[{"id":"message","senderPhone":"+15551234567","text":"Hello","timestamp":123,"fromMe":false}]}`, `{"fixtureId":"fixture"}`, "fixtureId", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { + {"MessagingClient.Testing.CreateHistoryFixture", "POST", "/messaging/projects/p/test-history-fixtures", "", `{"messages":[{"id":"message","senderPhone":"+15551234567","text":"Hello","timestamp":123,"fromMe":false}]}`, `{"fixtureId":"fixture"}`, "fixtureId", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { return wireData(m.Testing().CreateHistoryFixture(ctx, "p", []TestingHistoryMessage{{ID: "message", SenderPhone: "+15551234567", Text: "Hello", Timestamp: 123}})) }}, - {"MessagingClient.Testing.TriggerEvent", "POST", "/messaging/testing/p/events", "", `{"session":"s","event":"message.received","overrides":{"text":"Hello"}}`, `{"event":"message.received","session":"s","delivery":"queued","eventId":"event","source":"test"}`, "eventId", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { - return wireData(m.Testing().TriggerEvent(ctx, "p", TriggerTestEventRequest{Session: "s", Event: "message.received", Overrides: &TestEventOverrides{Text: "Hello"}})) + {"MessagingClient.Testing.TriggerEvent", "POST", "/messaging/s/test-events", "", `{"event":"message.received","overrides":{"text":"Hello"}}`, `{"event":"message.received","session":"s","delivery":"queued","eventId":"event","source":"test"}`, "eventId", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { + return wireData(m.Testing().TriggerEvent(ctx, "s", TriggerTestEventRequest{Event: "message.received", Overrides: &TestEventOverrides{Text: "Hello"}})) }}, - {"MessagingClient.Testing.ListEventFixtures", "GET", "/messaging/testing/p/events/fixtures", "", "", `{"fixtures":[{"name":"message.received","description":"Incoming","overrides":["text"]}]}`, "fixtures.0.description", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { - return wireData(m.Testing().ListEventFixtures(ctx, "p")) + {"MessagingClient.Testing.ListEventFixtures", "GET", "/messaging/test-events/fixtures", "", "", `{"fixtures":[{"name":"message.received","description":"Incoming","overrides":["text"]}]}`, "fixtures.0.description", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { + return wireData(m.Testing().ListEventFixtures(ctx)) }}, {"TeamClient.Audiences.List", "GET", "/platform/audiences", "", "", `{"data":{"audiences":[{"id":"audience"}]}}`, "data.audiences.0.id", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { return wireData(o.Audiences().List(ctx)) diff --git a/packages/go/coverage.json b/packages/go/coverage.json index 8494c9919..7f18c0c45 100644 --- a/packages/go/coverage.json +++ b/packages/go/coverage.json @@ -4517,9 +4517,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/{session}/phone", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.GetPhone", + "testFile": "supplements_test.go" }, { "family": "messaging", @@ -4557,9 +4557,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/test-events/fixtures", - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient.Testing.ListEventFixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.ListEventFixtures", + "testFile": "cloud_audiences_test.go" }, { "family": "messaging", @@ -4629,17 +4629,17 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/devices/{deviceId}/unlink", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.UnlinkPhoneDevice", + "testFile": "supplements_test.go" }, { "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/messages", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.SendPhoneMessage", + "testFile": "supplements_test.go" }, { "family": "messaging", @@ -4669,9 +4669,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/test-events", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient.Testing.TriggerEvent) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.TriggerEvent", + "testFile": "cloud_audiences_test.go" }, { "family": "messaging", @@ -4685,9 +4685,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/projects/{projectId}/test-history-fixtures", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient.Testing.CreateHistoryFixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.Testing.CreateHistoryFixture", + "testFile": "cloud_audiences_test.go" }, { "family": "messaging", diff --git a/packages/go/go41_nine_test.go b/packages/go/go41_nine_test.go index ac5028623..1419548e1 100644 --- a/packages/go/go41_nine_test.go +++ b/packages/go/go41_nine_test.go @@ -38,14 +38,14 @@ func go41Routes() []go41Route { {"getGroupCapabilities", "GET", "/messaging/session%20%2Fx/groups/group%20%2Fx/capabilities", "", go41Group, 200, false, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { return m.Groups().GetCapabilities(c, "session /x", "group /x", p) }}, - {"getTestingPhone", "GET", "/messaging/testing/project%20%2Fx/numbers/session%20%2Fx/phone", "", go41Phone, 200, true, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { - return m.Testing().GetPhone(c, "project /x", "session /x", p) + {"getTestingPhone", "GET", "/messaging/session%20%2Fx/phone", "", go41Phone, 200, true, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { + return m.Testing().GetPhone(c, "session /x", p) }}, - {"sendTestingPhoneMessage", "POST", "/messaging/testing/project%20%2Fx/numbers/session%20%2Fx/phone/messages", `{"to":"+15550000002","text":"hello"}`, go41PhoneSend, 202, true, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { - return m.Testing().SendPhoneMessage(c, "project /x", "session /x", sdk.SendTestingPhoneMessageRequest{To: "+15550000002", Text: "hello"}, p) + {"sendTestingPhoneMessage", "POST", "/messaging/session%20%2Fx/phone/messages", `{"to":"+15550000002","text":"hello"}`, go41PhoneSend, 202, true, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { + return m.Testing().SendPhoneMessage(c, "session /x", sdk.SendTestingPhoneMessageRequest{To: "+15550000002", Text: "hello"}, p) }}, - {"unlinkTestingPhoneDevice", "POST", "/messaging/testing/project%20%2Fx/numbers/session%20%2Fx/phone/devices/99/unlink", "", go41Unlink, 200, true, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { - return m.Testing().UnlinkPhoneDevice(c, "project /x", "session /x", 99, p) + {"unlinkTestingPhoneDevice", "POST", "/messaging/session%20%2Fx/phone/devices/99/unlink", "", go41Unlink, 200, true, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { + return m.Testing().UnlinkPhoneDevice(c, "session /x", 99, p) }}, {"listProjectRequestLogs", "GET", "/platform/projects/project%20%2Fx/request-logs", "", go41Logs, 200, true, func(c context.Context, m *sdk.MessagingClient, o *sdk.TeamClient, p sdk.RequestOptions) (any, error) { return o.RequestLogs().List(c, sdk.ListRequestLogsParams{ProjectID: "project /x"}, p) diff --git a/packages/go/supplements.json b/packages/go/supplements.json index 8ba572a6c..59e35a13c 100644 --- a/packages/go/supplements.json +++ b/packages/go/supplements.json @@ -40,21 +40,21 @@ { "sdkMethod": "MessagingClient.Testing.GetPhone", "method": "GET", - "fixturePath": "/messaging/testing/project/numbers/support/phone", + "fixturePath": "/messaging/support/phone", "status": "covered", "testFile": "supplements_test.go" }, { "sdkMethod": "MessagingClient.Testing.SendPhoneMessage", "method": "POST", - "fixturePath": "/messaging/testing/project/numbers/support/phone/messages", + "fixturePath": "/messaging/support/phone/messages", "status": "covered", "testFile": "supplements_test.go" }, { "sdkMethod": "MessagingClient.Testing.UnlinkPhoneDevice", "method": "POST", - "fixturePath": "/messaging/testing/project/numbers/support/phone/devices/1/unlink", + "fixturePath": "/messaging/support/phone/devices/1/unlink", "status": "covered", "testFile": "supplements_test.go" }, diff --git a/packages/go/supplements_test.go b/packages/go/supplements_test.go index 2afcd971e..57644203b 100644 --- a/packages/go/supplements_test.go +++ b/packages/go/supplements_test.go @@ -24,14 +24,14 @@ var supplementFixtures = []operationFixture{ {"MessagingClient.FlowEncryption.Register", "POST", "/graph/whatsapp/v26.0/phone/whatsapp_business_encryption", "", `{"business_public_key":"public-key"}`, `{"success":true}`, "success", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { return wireData(m.FlowEncryption().Register(ctx, "phone", RegisterFlowEncryptionKeyRequest{BusinessPublicKey: "public-key"}, CloudGraphVersion{Version: "v26.0"})) }}, - {"MessagingClient.Testing.GetPhone", "GET", "/messaging/testing/project/numbers/support/phone", "", "", `{"session":"support","phone":"+15551234567","online":false,"devices":[{"deviceId":1}]}`, "devices.0.deviceId", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { - return wireData(m.Testing().GetPhone(ctx, "project", "support")) + {"MessagingClient.Testing.GetPhone", "GET", "/messaging/support/phone", "", "", `{"session":"support","phone":"+15551234567","online":false,"devices":[{"deviceId":1}]}`, "devices.0.deviceId", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { + return wireData(m.Testing().GetPhone(ctx, "support")) }}, - {"MessagingClient.Testing.SendPhoneMessage", "POST", "/messaging/testing/project/numbers/support/phone/messages", "", `{"to":"+15551234567","text":"Hello"}`, `{"session":"support","to":"+15551234567","messageId":null}`, "to", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { - return wireData(m.Testing().SendPhoneMessage(ctx, "project", "support", SendTestingPhoneMessageRequest{To: "+15551234567", Text: "Hello"})) + {"MessagingClient.Testing.SendPhoneMessage", "POST", "/messaging/support/phone/messages", "", `{"to":"+15551234567","text":"Hello"}`, `{"session":"support","to":"+15551234567","messageId":null}`, "to", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { + return wireData(m.Testing().SendPhoneMessage(ctx, "support", SendTestingPhoneMessageRequest{To: "+15551234567", Text: "Hello"})) }}, - {"MessagingClient.Testing.UnlinkPhoneDevice", "POST", "/messaging/testing/project/numbers/support/phone/devices/1/unlink", "", "", `{"session":"support","deviceId":1,"unlinked":true}`, "unlinked", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { - return wireData(m.Testing().UnlinkPhoneDevice(ctx, "project", "support", 1)) + {"MessagingClient.Testing.UnlinkPhoneDevice", "POST", "/messaging/support/phone/devices/1/unlink", "", "", `{"session":"support","deviceId":1,"unlinked":true}`, "unlinked", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { + return wireData(m.Testing().UnlinkPhoneDevice(ctx, "support", 1)) }}, {"MessagingClient.Campaigns.Update", "PATCH", "/messaging/projects/project/campaigns/campaign", "", `{"name":"New","scheduledAt":null,"sendWindow":null}`, campaignFixture, "data.name", func(ctx context.Context, m *MessagingClient, o *TeamClient, p *ProjectClient) (any, error) { name := "New" diff --git a/packages/go/testing.go b/packages/go/testing.go index 81c1c2bfb..a71690692 100644 --- a/packages/go/testing.go +++ b/packages/go/testing.go @@ -42,10 +42,9 @@ type TestEventOverrides struct { Reason string `json:"reason,omitempty"` } type TriggerTestEventRequest struct { - Session string `json:"session"` - Event string `json:"event"` - Overrides *TestEventOverrides `json:"overrides,omitempty"` - FromSession string `json:"fromSession,omitempty"` + Event string `json:"event"` + Overrides *TestEventOverrides `json:"overrides,omitempty"` + FromNumber string `json:"fromNumber,omitempty"` } type TriggerTestEventResult struct { Event string `json:"event"` @@ -94,17 +93,17 @@ func (r *Testing) CreateHistoryFixture(ctx context.Context, project string, mess } return request[struct { FixtureID string `json:"fixtureId"` - }](ctx, r.t, "POST", "/messaging/testing/"+escaped(project)+"/history-fixtures", nil, struct { + }](ctx, r.t, "POST", "/messaging/projects/"+escaped(project)+"/test-history-fixtures", nil, struct { Messages []TestingHistoryMessage `json:"messages"` }{messages}, options(o)) } -func (r *Testing) TriggerEvent(ctx context.Context, project string, b TriggerTestEventRequest, o ...RequestOptions) (Response[TriggerTestEventResult], error) { +func (r *Testing) TriggerEvent(ctx context.Context, session string, b TriggerTestEventRequest, o ...RequestOptions) (Response[TriggerTestEventResult], error) { if err := serverOnly(r.t); err != nil { return Response[TriggerTestEventResult]{}, err } - return request[TriggerTestEventResult](ctx, r.t, "POST", "/messaging/testing/"+escaped(project)+"/events", nil, b, options(o)) + return request[TriggerTestEventResult](ctx, r.t, "POST", "/messaging/"+escaped(session)+"/test-events", nil, b, options(o)) } -func (r *Testing) ListEventFixtures(ctx context.Context, project string, o ...RequestOptions) (Response[struct { +func (r *Testing) ListEventFixtures(ctx context.Context, o ...RequestOptions) (Response[struct { Fixtures []TestEventFixtureInfo `json:"fixtures"` }], error) { if err := serverOnly(r.t); err != nil { @@ -114,31 +113,31 @@ func (r *Testing) ListEventFixtures(ctx context.Context, project string, o ...Re } return request[struct { Fixtures []TestEventFixtureInfo `json:"fixtures"` - }](ctx, r.t, "GET", "/messaging/testing/"+escaped(project)+"/events/fixtures", nil, nil, options(o)) + }](ctx, r.t, "GET", "/messaging/test-events/fixtures", nil, nil, options(o)) } -func phonePath(project, session string) string { - return "/messaging/testing/" + escaped(project) + "/numbers/" + escaped(session) + "/phone" +func phonePath(session string) string { + return "/messaging/" + escaped(session) + "/phone" } -func (r *Testing) GetPhone(ctx context.Context, project, session string, o ...RequestOptions) (Response[TestingPhone], error) { +func (r *Testing) GetPhone(ctx context.Context, session string, o ...RequestOptions) (Response[TestingPhone], error) { if err := serverOnly(r.t); err != nil { return Response[TestingPhone]{}, err } - return endpointBare[TestingPhone](ctx, r.t, "GET", phonePath(project, session), nil, nil, options(o), 200) + return endpointBare[TestingPhone](ctx, r.t, "GET", phonePath(session), nil, nil, options(o), 200) } -func (r *Testing) SendPhoneMessage(ctx context.Context, project, session string, b SendTestingPhoneMessageRequest, o ...RequestOptions) (Response[SendTestingPhoneMessageResult], error) { +func (r *Testing) SendPhoneMessage(ctx context.Context, session string, b SendTestingPhoneMessageRequest, o ...RequestOptions) (Response[SendTestingPhoneMessageResult], error) { if err := serverOnly(r.t); err != nil { return Response[SendTestingPhoneMessageResult]{}, err } - return endpointBare[SendTestingPhoneMessageResult](ctx, r.t, "POST", phonePath(project, session)+"/messages", nil, b, appendOnce(options(o)), 202) + return endpointBare[SendTestingPhoneMessageResult](ctx, r.t, "POST", phonePath(session)+"/messages", nil, b, appendOnce(options(o)), 202) } -func (r *Testing) UnlinkPhoneDevice(ctx context.Context, project, session string, id int, o ...RequestOptions) (Response[UnlinkTestingPhoneDeviceResult], error) { +func (r *Testing) UnlinkPhoneDevice(ctx context.Context, session string, id int, o ...RequestOptions) (Response[UnlinkTestingPhoneDeviceResult], error) { if err := serverOnly(r.t); err != nil { return Response[UnlinkTestingPhoneDeviceResult]{}, err } if id < 1 || id > 99 { return Response[UnlinkTestingPhoneDeviceResult]{}, validation("deviceId must be between 1 and 99.") } - return endpointBare[UnlinkTestingPhoneDeviceResult](ctx, r.t, "POST", phonePath(project, session)+"/devices/"+strconv.Itoa(id)+"/unlink", nil, nil, options(o), 200) + return endpointBare[UnlinkTestingPhoneDeviceResult](ctx, r.t, "POST", phonePath(session)+"/devices/"+strconv.Itoa(id)+"/unlink", nil, nil, options(o), 200) } type EmbeddedSignupResult struct { diff --git a/packages/php/README.md b/packages/php/README.md index 9d7415bf3..126511d0f 100644 --- a/packages/php/README.md +++ b/packages/php/README.md @@ -1059,6 +1059,16 @@ $state = $client->passkeys->getConfirmation($session); $confirmExplicitly = fn () => $client->passkeys->confirm($session, $suppliedConfirmation); ``` +## Number-scoped Test operations + +The Test phone methods take a Number ID, without a project argument: +~~~php +$phone = $client->testing->getPhone('support'); +$event = $client->testing->triggerEvent('support', ['event' => 'call.missed', 'fromNumber' => 'sales']); +$fixtures = $client->testing->listEventFixtures(); +~~~ + +Send-phone-message and unlink-device helpers use the same Number scope. The trigger body contains event, optional overrides and optional fromNumber; it does not contain session or fromSession. The static fixture catalog has no project argument. History-fixture creation remains project-scoped. These operations require a server credential and the API’s Test-number access checks; a helper does not grant access or make a real Number a Test number. ## Guest participants and waiting rooms (unreleased) diff --git a/packages/php/coverage.json b/packages/php/coverage.json index 168765acb..8040d515a 100644 --- a/packages/php/coverage.json +++ b/packages/php/coverage.json @@ -4654,9 +4654,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/{session}/phone", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient::testing.getPhone", + "testFile": "tests/onboarding.php" }, { "family": "messaging", @@ -4694,9 +4694,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/test-events/fixtures", - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient::testing.listEventFixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient::testing.listEventFixtures", + "testFile": "tests/onboarding.php" }, { "family": "messaging", @@ -4766,17 +4766,17 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/devices/{deviceId}/unlink", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient::testing.unlinkPhoneDevice", + "testFile": "tests/onboarding.php" }, { "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/messages", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient::testing.sendPhoneMessage", + "testFile": "tests/onboarding.php" }, { "family": "messaging", @@ -4806,9 +4806,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/test-events", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient::testing.triggerEvent) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient::testing.triggerEvent", + "testFile": "tests/onboarding.php" }, { "family": "messaging", @@ -4822,9 +4822,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/projects/{projectId}/test-history-fixtures", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient::testing.createHistoryFixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient::testing.createHistoryFixture", + "testFile": "tests/onboarding.php" }, { "family": "messaging", diff --git a/packages/php/src/OnboardingModels.php b/packages/php/src/OnboardingModels.php index 88827338d..0a6690d59 100644 --- a/packages/php/src/OnboardingModels.php +++ b/packages/php/src/OnboardingModels.php @@ -17,7 +17,7 @@ * @phpstan-type HistoryMessage array{id:string,senderPhone:string,text:string,timestamp:int|float,fromMe:bool} * @phpstan-type Fixture 'message.received'|'message.ack'|'message.failed'|'call.received'|'call.missed'|'call.ended'|'session.status'|'session.restriction_updated'|'template.status' * @phpstan-type Overrides array{text?:string,from?:string,pushName?:string,mediaType?:'image'|'video'|'audio'|'document'|'sticker',caption?:string,ackStatus?:'delivered'|'read'|'played'|'error',messageId?:string,failureReason?:'invalid_recipient'|'session_not_connected'|'ack_timeout'|'send_failed'|'blocked_by_safety',video?:bool,durationSeconds?:int|float,callEndReason?:'user_hangup'|'timeout'|'lost_connection'|'rejected'|'call_restricted',restrictionActive?:bool,status?:'CONNECTING'|'CONNECTED'|'DISCONNECTED',statusReason?:'SCAN_QR'|'AUTO_RECONNECT'|'FAILED'|'MANUAL_STOP'|'QR_TIMEOUT'|'LOGGED_OUT'|'TEMPORARY_BAN'|'STREAM_ERROR',templateName?:string,templateStatus?:'APPROVED'|'REJECTED',reason?:string} - * @phpstan-type Trigger array{session:string,event:Fixture,overrides?:Overrides,fromSession?:string} + * @phpstan-type Trigger array{event:Fixture,overrides?:Overrides,fromNumber?:string} * @phpstan-type TriggerResult array{event:Fixture,session:string,delivery:'generated'|'simulated',eventId:?string,source:'test'|'runtime'} * @phpstan-type Phone array{session:string,phone:string,online:bool,devices:list} */ diff --git a/packages/php/src/Resources/Testing.php b/packages/php/src/Resources/Testing.php index bd1dd1718..764f68fa4 100644 --- a/packages/php/src/Resources/Testing.php +++ b/packages/php/src/Resources/Testing.php @@ -20,48 +20,44 @@ final class Testing extends Resource public function createHistoryFixture(string $projectId, array $input, ?RequestOptions $options = null): ApiResponse { $this->server(); - /** @var ApiResponse */ return $this->request('POST', $this->base($projectId).'/history-fixtures', $input, options:$options); + /** @var ApiResponse */ return $this->request('POST', '/messaging/projects/'.self::segment($projectId).'/test-history-fixtures', $input, options:$options); } /** @param Trigger $input * @return ApiResponse */ - public function triggerEvent(string $projectId, array $input, ?RequestOptions $options = null): ApiResponse + public function triggerEvent(string $session, array $input, ?RequestOptions $options = null): ApiResponse { $this->server(); - /** @var ApiResponse */ return $this->request('POST', $this->base($projectId).'/events', $input, options:$options); + /** @var ApiResponse */ return $this->request('POST', '/messaging/'.self::segment($session).'/test-events', $input, options:$options); } /** @return ApiResponse}>}> */ - public function listEventFixtures(string $projectId, ?RequestOptions $options = null): ApiResponse + public function listEventFixtures(?RequestOptions $options = null): ApiResponse { $this->server(); - /** @var ApiResponse}>}> */ return $this->request('GET', $this->base($projectId).'/events/fixtures', options:$options); + /** @var ApiResponse}>}> */ return $this->request('GET', '/messaging/test-events/fixtures', options:$options); } /** @return ApiResponse */ - public function getPhone(string $projectId, string $session, ?RequestOptions $options = null): ApiResponse + public function getPhone(string $session, ?RequestOptions $options = null): ApiResponse { $this->server(); - /** @var ApiResponse */ return \Polymorfa\ExistingContract::bare($this->transport, 'GET', $this->phone($projectId, $session), null, $options, 'testingPhone'); + /** @var ApiResponse */ return \Polymorfa\ExistingContract::bare($this->transport, 'GET', $this->phone($session), null, $options, 'testingPhone'); } /** @param array{to:string,text:string} $input * @return ApiResponse */ - public function sendPhoneMessage(string $projectId, string $session, array $input, ?RequestOptions $options = null): ApiResponse + public function sendPhoneMessage(string $session, array $input, ?RequestOptions $options = null): ApiResponse { $this->server(); - /** @var ApiResponse */ return \Polymorfa\ExistingContract::bare($this->transport, 'POST', $this->phone($projectId, $session).'/messages', $input, $options, 'testingSend', 202); + /** @var ApiResponse */ return \Polymorfa\ExistingContract::bare($this->transport, 'POST', $this->phone($session).'/messages', $input, $options, 'testingSend', 202); } /** @return ApiResponse */ - public function unlinkPhoneDevice(string $projectId, string $session, int $deviceId, ?RequestOptions $options = null): ApiResponse + public function unlinkPhoneDevice(string $session, int $deviceId, ?RequestOptions $options = null): ApiResponse { $this->server(); if ($deviceId < 1 || $deviceId > 99) { throw new ValidationException('deviceId must be a companion device ID from 1 to 99.'); - } /** @var ApiResponse */ return \Polymorfa\ExistingContract::bare($this->transport, 'POST', $this->phone($projectId, $session).'/devices/'.$deviceId.'/unlink', null, $options, 'testingUnlink'); + } /** @var ApiResponse */ return \Polymorfa\ExistingContract::bare($this->transport, 'POST', $this->phone($session).'/devices/'.$deviceId.'/unlink', null, $options, 'testingUnlink'); } - private function base(string $projectId): string + private function phone(string $session): string { - return '/messaging/testing/'.self::segment($projectId); - } - private function phone(string $projectId, string $session): string - { - return $this->base($projectId).'/numbers/'.self::segment($session).'/phone'; + return '/messaging/'.self::segment($session).'/phone'; } } diff --git a/packages/php/supplements.json b/packages/php/supplements.json index 6f7ddc62e..ff23b0c19 100644 --- a/packages/php/supplements.json +++ b/packages/php/supplements.json @@ -25,21 +25,21 @@ }, { "method": "GET", - "fixturePath": "/messaging/testing/project/numbers/session/phone", + "fixturePath": "/messaging/session/phone", "sdkMethod": "MessagingClient::testing.getPhone", "status": "covered", "testFile": "tests/onboarding.php" }, { "method": "POST", - "fixturePath": "/messaging/testing/project/numbers/session/phone/messages", + "fixturePath": "/messaging/session/phone/messages", "sdkMethod": "MessagingClient::testing.sendPhoneMessage", "status": "covered", "testFile": "tests/onboarding.php" }, { "method": "POST", - "fixturePath": "/messaging/testing/project/numbers/session/phone/devices/1/unlink", + "fixturePath": "/messaging/session/phone/devices/1/unlink", "sdkMethod": "MessagingClient::testing.unlinkPhoneDevice", "status": "covered", "testFile": "tests/onboarding.php" diff --git a/packages/php/tests/existing_contract_edges.php b/packages/php/tests/existing_contract_edges.php index 5d4aba4e9..06b05a6cf 100644 --- a/packages/php/tests/existing_contract_edges.php +++ b/packages/php/tests/existing_contract_edges.php @@ -47,13 +47,13 @@ $ecNoIO(fn () => $ecMessaging->historySync->requestChunkRetry('s', $bad)); } foreach ([0,100] as $device) { - $ecNoIO(fn () => $ecMessaging->testing->unlinkPhoneDevice($ecProject, 's', $device), Polymorfa\ValidationException::class); + $ecNoIO(fn () => $ecMessaging->testing->unlinkPhoneDevice('s', $device), Polymorfa\ValidationException::class); } $ecNoIO(fn () => $ecTeam->requestLogs->list()); $ecNoIO(fn () => $ecA->requestLogs->list(['projectId' => $ecBProject]), Polymorfa\ValidationException::class); $ecNoIO(fn () => $ecA->requestLogs->list(['cursor' => 'next','traceId' => 'trace']), Polymorfa\ValidationException::class); $ecBrowser = new Polymorfa\MessagingClient($ecPrincipals[2], baseUrl:$ecUrl); -foreach ([fn () => $ecBrowser->testing->getPhone($ecProject, 's'),fn () => $ecBrowser->testing->sendPhoneMessage($ecProject, 's', ['to' => 'x','text' => 'y']),fn () => $ecBrowser->testing->unlinkPhoneDevice($ecProject, 's', 1),fn () => $ecBrowser->historySync->requestChunkRetry('s', ['syncType' => 'FULL','chunkOrder' => 0]),fn () => $ecBrowser->historySync->deleteChunk('s', '/file', str_repeat('h', 32)),fn () => $ecBrowser->whatsappMedia->createUploadGrant('s', 'image', str_repeat('h', 32)),fn () => $ecBrowser->whatsappMedia->uploadTransport('direct', new Polymorfa\UploadWhatsAppMediaOptions('image'))] as $invoke) { +foreach ([fn () => $ecBrowser->testing->getPhone('s'),fn () => $ecBrowser->testing->sendPhoneMessage('s', ['to' => 'x','text' => 'y']),fn () => $ecBrowser->testing->unlinkPhoneDevice('s', 1),fn () => $ecBrowser->historySync->requestChunkRetry('s', ['syncType' => 'FULL','chunkOrder' => 0]),fn () => $ecBrowser->historySync->deleteChunk('s', '/file', str_repeat('h', 32)),fn () => $ecBrowser->whatsappMedia->createUploadGrant('s', 'image', str_repeat('h', 32)),fn () => $ecBrowser->whatsappMedia->uploadTransport('direct', new Polymorfa\UploadWhatsAppMediaOptions('image'))] as $invoke) { $ecNoIO($invoke); } $opens = 0; diff --git a/packages/php/tests/existing_contract_nine.php b/packages/php/tests/existing_contract_nine.php index 8468cae14..389d66ec8 100644 --- a/packages/php/tests/existing_contract_nine.php +++ b/packages/php/tests/existing_contract_nine.php @@ -14,12 +14,12 @@ ecCheck($r->data['data']['capabilities'][0]['value'] === null && $r->data['data']['capabilities'][1]['value'] === false, 'Group nullable capability and Client support'); } $ecPhone = ['session' => 's','phone' => '+15555555555','online' => false,'devices' => [['deviceId' => 1],['deviceId' => 99]]]; -$ecTestingPath = '/messaging/testing/'.$ecProject.'/numbers/s/phone'; +$ecTestingPath = '/messaging/s/phone'; $ecNine = [ ['getGroupCapabilities','GET','/messaging/s/groups/g/capabilities',null,['success' => true,'data' => $ecCapabilities],fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->groups->getCapabilities('s', 'g', $o),200,'2026-09-22'], - ['getTestingPhone','GET',$ecTestingPath,null,$ecPhone,fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->testing->getPhone($ecProject, 's', $o),200,'2026-09-22'], - ['sendTestingPhoneMessage','POST',$ecTestingPath.'/messages',['to' => '+15555555555','text' => 'hello'],['session' => 's','to' => '+15555555555','messageId' => null],fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->testing->sendPhoneMessage($ecProject, 's', ['to' => '+15555555555','text' => 'hello'], $o),202,'2026-09-22'], - ['unlinkTestingPhoneDevice','POST',$ecTestingPath.'/devices/99/unlink',null,['session' => 's','deviceId' => 99,'unlinked' => true],fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->testing->unlinkPhoneDevice($ecProject, 's', 99, $o),200,'2026-09-22'], + ['getTestingPhone','GET',$ecTestingPath,null,$ecPhone,fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->testing->getPhone('s', $o),200,'2026-09-22'], + ['sendTestingPhoneMessage','POST',$ecTestingPath.'/messages',['to' => '+15555555555','text' => 'hello'],['session' => 's','to' => '+15555555555','messageId' => null],fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->testing->sendPhoneMessage('s', ['to' => '+15555555555','text' => 'hello'], $o),202,'2026-09-22'], + ['unlinkTestingPhoneDevice','POST',$ecTestingPath.'/devices/99/unlink',null,['session' => 's','deviceId' => 99,'unlinked' => true],fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->testing->unlinkPhoneDevice('s', 99, $o),200,'2026-09-22'], ['retryHistoryChunk','POST','/messaging/s/history/chunks/retry',['syncType' => 'FULL','chunkOrder' => 0,'regenerate' => false],['success' => true,'data' => ['requestId' => 'native-retry','status' => 'requested']],fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->historySync->requestChunkRetry('s', ['syncType' => 'FULL','chunkOrder' => 0,'regenerate' => false], $o),200,'2026-10-14'], ['deleteHistoryMedia','POST','/messaging/s/history/media/delete',['directPath' => '/mms/history/file','fileEncSha256' => '//////////////////////////////////////////8=','encHandle' => 'handle','companionMetaNonce' => 'nonce'],['success' => true,'data' => ['status' => 'deleted']],fn (?Polymorfa\RequestOptions $o = null) => $ecMessaging->historySync->deleteChunk('s', '/mms/history/file', str_repeat("\xff", 32), 'handle', 'nonce', $o),200,'2026-10-14'], ]; diff --git a/packages/php/tests/existing_contract_types.php b/packages/php/tests/existing_contract_types.php index 18d1009da..974168dac 100644 --- a/packages/php/tests/existing_contract_types.php +++ b/packages/php/tests/existing_contract_types.php @@ -39,9 +39,9 @@ public static function publicInputs(Polymorfa\Client $team, Polymorfa\MessagingC self::delivery($config['effective']['historySync']['delivery']); } $messages->groups->getCapabilities('s', 'g')->data['data']['capabilities']; - $messages->testing->getPhone($project, 's')->data['online']; - $messages->testing->sendPhoneMessage($project, 's', ['to' => '+15555555555','text' => 'hello'])->data['messageId']; - $messages->testing->unlinkPhoneDevice($project, 's', 1)->data['unlinked']; + $messages->testing->getPhone('s')->data['online']; + $messages->testing->sendPhoneMessage('s', ['to' => '+15555555555','text' => 'hello'])->data['messageId']; + $messages->testing->unlinkPhoneDevice('s', 1)->data['unlinked']; $team->project($project)->requestLogs->list()->items; $messages->whatsappMedia->relayUpload('s', new Polymorfa\EncryptedMediaInfo('image', str_repeat('k', 32), str_repeat('h', 32), str_repeat('e', 32), 1, 26), static fn (?Polymorfa\CancellationToken $c): Psr\Http\Message\StreamInterface => GuzzleHttp\Psr7\Utils::streamFor('cipher')); $messages->whatsappMedia->createUploadGrant('s', 'sticker', str_repeat('h', 32)); diff --git a/packages/php/tests/onboarding.php b/packages/php/tests/onboarding.php index 1aef0c578..42bea22e0 100644 --- a/packages/php/tests/onboarding.php +++ b/packages/php/tests/onboarding.php @@ -17,14 +17,14 @@ ['GET','/messaging/projects/project/observation-policy',null,$envelope($projectPolicy),fn ($c) => $c->observationPolicies->retrieveForProject('project')], ['GET','/messaging/session/observation-policy',null,$envelope($sessionPolicy),fn ($c) => $c->observationPolicies->retrieveForSession('session')], ['POST','/messaging/cloud-api/embedded-signup',['quicklinkId' => 'link','result' => ['code' => 'synthetic_fixture','wabaId' => 'waba','phoneNumberId' => 'phone','coexistence' => false]],$envelope(['stage' => 'complete']),fn ($c) => $c->cloudOnboarding->advance(['quicklinkId' => 'link','result' => ['code' => 'synthetic_fixture','wabaId' => 'waba','phoneNumberId' => 'phone','coexistence' => false]])], - ['POST','/messaging/testing/project/history-fixtures',['messages' => [['id' => 'message','senderPhone' => '+15555555555','text' => 'Fixture','timestamp' => 1,'fromMe' => false]]],['fixtureId' => 'fixture'],fn ($c) => $c->testing->createHistoryFixture('project', ['messages' => [['id' => 'message','senderPhone' => '+15555555555','text' => 'Fixture','timestamp' => 1,'fromMe' => false]]])], - ['POST','/messaging/testing/project/events',['session' => 'session','event' => 'message.received','fromSession' => 'sender','overrides' => ['text' => 'Fixture']],$trigger,fn ($c) => $c->testing->triggerEvent('project', ['session' => 'session','event' => 'message.received','fromSession' => 'sender','overrides' => ['text' => 'Fixture']])], - ['GET','/messaging/testing/project/events/fixtures',null,$fixtures,fn ($c) => $c->testing->listEventFixtures('project')], - ['GET','/messaging/testing/project/numbers/session/phone',null,['session' => 'session','phone' => '+15555555555','online' => false,'devices' => [['deviceId' => 1]]],fn ($c) => $c->testing->getPhone('project', 'session')], - ['POST','/messaging/testing/project/numbers/session/phone/messages',['to' => '+15555555555','text' => 'Fixture'],['session' => 'session','to' => '+15555555555','messageId' => null],fn ($c) => $c->testing->sendPhoneMessage('project', 'session', ['to' => '+15555555555','text' => 'Fixture']),null,['status' => 202]], - ['POST','/messaging/testing/project/numbers/session/phone/devices/1/unlink',null,['session' => 'session','deviceId' => 1,'unlinked' => true],fn ($c) => $c->testing->unlinkPhoneDevice('project', 'session', 1)], + ['POST','/messaging/projects/project/test-history-fixtures',['messages' => [['id' => 'message','senderPhone' => '+15555555555','text' => 'Fixture','timestamp' => 1,'fromMe' => false]]],['fixtureId' => 'fixture'],fn ($c) => $c->testing->createHistoryFixture('project', ['messages' => [['id' => 'message','senderPhone' => '+15555555555','text' => 'Fixture','timestamp' => 1,'fromMe' => false]]])], + ['POST','/messaging/session/test-events',['event' => 'message.received','fromNumber' => 'sender','overrides' => ['text' => 'Fixture']],$trigger,fn ($c) => $c->testing->triggerEvent('session', ['event' => 'message.received','fromNumber' => 'sender','overrides' => ['text' => 'Fixture']])], + ['GET','/messaging/test-events/fixtures',null,$fixtures,fn ($c) => $c->testing->listEventFixtures()], + ['GET','/messaging/session/phone',null,['session' => 'session','phone' => '+15555555555','online' => false,'devices' => [['deviceId' => 1]]],fn ($c) => $c->testing->getPhone('session')], + ['POST','/messaging/session/phone/messages',['to' => '+15555555555','text' => 'Fixture'],['session' => 'session','to' => '+15555555555','messageId' => null],fn ($c) => $c->testing->sendPhoneMessage('session', ['to' => '+15555555555','text' => 'Fixture']),null,['status' => 202]], + ['POST','/messaging/session/phone/devices/1/unlink',null,['session' => 'session','deviceId' => 1,'unlinked' => true],fn ($c) => $c->testing->unlinkPhoneDevice('session', 1)], ], fn ($credential, $url) => new Polymorfa\MessagingClient($credential, baseUrl:$url)); -raises(fn () => (new Polymorfa\MessagingClient($credential))->testing->unlinkPhoneDevice('project', 'session', 0), Polymorfa\ValidationException::class); +raises(fn () => (new Polymorfa\MessagingClient($credential))->testing->unlinkPhoneDevice('session', 0), Polymorfa\ValidationException::class); $history = []; new Polymorfa\SystemClient(baseUrl:'http://api.fixture.invalid', http:mocked([], $history)); nativeCases([ diff --git a/packages/php/tools/native-coverage.py b/packages/php/tools/native-coverage.py index d38e1975c..39699b6d2 100644 --- a/packages/php/tools/native-coverage.py +++ b/packages/php/tools/native-coverage.py @@ -143,9 +143,12 @@ ('GET','/messaging/projects/{projectId}/observation-policy','observationPolicies.retrieveForProject','onboarding'), ('GET','/messaging/{session}/observation-policy','observationPolicies.retrieveForSession','onboarding'), ('POST','/messaging/cloud-api/embedded-signup','cloudOnboarding.advance','onboarding'), - ('POST','/messaging/testing/{projectId}/history-fixtures','testing.createHistoryFixture','onboarding'), - ('POST','/messaging/testing/{projectId}/events','testing.triggerEvent','onboarding'), - ('GET','/messaging/testing/{projectId}/events/fixtures','testing.listEventFixtures','onboarding'), + ('POST','/messaging/projects/{projectId}/test-history-fixtures','testing.createHistoryFixture','onboarding'), + ('POST','/messaging/{session}/test-events','testing.triggerEvent','onboarding'), + ('GET','/messaging/test-events/fixtures','testing.listEventFixtures','onboarding'), + ('GET','/messaging/{session}/phone','testing.getPhone','onboarding'), + ('POST','/messaging/{session}/phone/messages','testing.sendPhoneMessage','onboarding'), + ('POST','/messaging/{session}/phone/devices/{deviceId}/unlink','testing.unlinkPhoneDevice','onboarding'), ('GET','/messaging/info/status','SystemClient.status','onboarding'), ('GET','/messaging/info/version','SystemClient.version','onboarding'), ('GET','/health','SystemClient.health','onboarding'), diff --git a/packages/python/README.md b/packages/python/README.md index cf954debb..340122497 100644 --- a/packages/python/README.md +++ b/packages/python/README.md @@ -929,6 +929,18 @@ async def confirm_explicitly(): return await client.passkeys.confirm(session, supplied_confirmation) ``` +## Number-scoped Test operations + +The Test phone methods take a Number ID, without a project argument: +~~~python +phone = await client.testing.get_phone("support") +event = await client.testing.trigger_event( + "support", {"event": "call.missed", "fromNumber": "sales"} +) +fixtures = await client.testing.list_event_fixtures() +~~~ + +Send-phone-message and unlink-device helpers use the same Number scope. The trigger body contains event, optional overrides and optional fromNumber; it does not contain session or fromSession. The static fixture catalog has no project argument. History-fixture creation remains project-scoped. These operations require a server credential and the API’s Test-number access checks; a helper does not grant access or make a real Number a Test number. ## Guest participants and waiting rooms (unreleased) diff --git a/packages/python/coverage.json b/packages/python/coverage.json index 840cd54c6..e41b61eeb 100644 --- a/packages/python/coverage.json +++ b/packages/python/coverage.json @@ -4654,9 +4654,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/{session}/phone", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "AsyncMessagingClient.testing.get_phone", + "testFile": "tests/test_onboarding.py" }, { "family": "messaging", @@ -4694,9 +4694,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/test-events/fixtures", - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (AsyncMessagingClient.testing.list_event_fixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "AsyncMessagingClient.testing.list_event_fixtures", + "testFile": "tests/test_onboarding.py" }, { "family": "messaging", @@ -4766,17 +4766,17 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/devices/{deviceId}/unlink", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "AsyncMessagingClient.testing.unlink_phone_device", + "testFile": "tests/test_onboarding.py" }, { "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/messages", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "AsyncMessagingClient.testing.send_phone_message", + "testFile": "tests/test_onboarding.py" }, { "family": "messaging", @@ -4806,9 +4806,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/test-events", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (AsyncMessagingClient.testing.trigger_event) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "AsyncMessagingClient.testing.trigger_event", + "testFile": "tests/test_onboarding.py" }, { "family": "messaging", @@ -4822,9 +4822,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/projects/{projectId}/test-history-fixtures", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (AsyncMessagingClient.testing.create_history_fixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "AsyncMessagingClient.testing.create_history_fixture", + "testFile": "tests/test_onboarding.py" }, { "family": "messaging", diff --git a/packages/python/src/polymorfa/onboarding.py b/packages/python/src/polymorfa/onboarding.py index b690a555b..fd6ecc2d5 100644 --- a/packages/python/src/polymorfa/onboarding.py +++ b/packages/python/src/polymorfa/onboarding.py @@ -120,10 +120,9 @@ class EventOverrides(TypedDict, total=False): class TriggerEvent(TypedDict): - session: str event: TestEvent overrides: NotRequired[EventOverrides] - fromSession: NotRequired[str] + fromNumber: NotRequired[str] class TriggeredEvent(TypedDict): @@ -200,13 +199,13 @@ async def create_history_fixture( self._server() return await self._request( "POST", - f"/messaging/testing/{segment(project_id)}/history-fixtures", + f"/messaging/projects/{segment(project_id)}/test-history-fixtures", body=body, options=options, ) async def trigger_event( - self, project_id: str, body: TriggerEvent, *, options: RequestOptions = O + self, session: str, body: TriggerEvent, *, options: RequestOptions = O ) -> ApiResponse[TriggeredEvent]: self._server() wire: dict[str, object] = dict(body) @@ -216,31 +215,29 @@ async def trigger_event( overrides["from"] = overrides.pop("from_") wire["overrides"] = overrides return await self._request( - "POST", f"/messaging/testing/{segment(project_id)}/events", body=wire, options=options + "POST", f"/messaging/{segment(session)}/test-events", body=wire, options=options ) async def list_event_fixtures( - self, project_id: str, *, options: RequestOptions = O + self, *, options: RequestOptions = O ) -> ApiResponse[EventFixtures]: self._server() - return await self._request( - "GET", f"/messaging/testing/{segment(project_id)}/events/fixtures", options=options - ) + return await self._request("GET", "/messaging/test-events/fixtures", options=options) @acknowledged() async def get_phone( - self, project_id: str, session: str, *, options: RequestOptions = O + self, session: str, *, options: RequestOptions = O ) -> ApiResponse[TestingPhone]: self._server() return await self._request( "GET", - f"/messaging/testing/{segment(project_id)}/numbers/{segment(session)}/phone", + f"/messaging/{segment(session)}/phone", options=options, ) @acknowledged(202) async def send_phone_message( - self, project_id: str, session: str, body: PhoneMessage, *, options: RequestOptions = O + self, session: str, body: PhoneMessage, *, options: RequestOptions = O ) -> ApiResponse[PhoneMessageResult]: self._server() data = V.fields(body, ["to", "text"], ["to", "text"]) @@ -248,14 +245,14 @@ async def send_phone_message( V.text(data["text"], "text") return await self._request( "POST", - f"/messaging/testing/{segment(project_id)}/numbers/{segment(session)}/phone/messages", + f"/messaging/{segment(session)}/phone/messages", body=V.capture(body), options=options, ) @acknowledged() async def unlink_phone_device( - self, project_id: str, session: str, device_id: int, *, options: RequestOptions = O + self, session: str, device_id: int, *, options: RequestOptions = O ) -> ApiResponse[UnlinkedDevice]: self._server() if ( @@ -266,6 +263,6 @@ async def unlink_phone_device( raise ValidationError("device_id must be a companion device ID from 1 to 99.") return await self._request( "POST", - f"/messaging/testing/{segment(project_id)}/numbers/{segment(session)}/phone/devices/{device_id}/unlink", + f"/messaging/{segment(session)}/phone/devices/{device_id}/unlink", options=options, ) diff --git a/packages/python/supplements.json b/packages/python/supplements.json index 9b6a0e103..1595d23d8 100644 --- a/packages/python/supplements.json +++ b/packages/python/supplements.json @@ -40,21 +40,21 @@ { "sdkMethod": "AsyncMessagingClient.testing.get_phone", "method": "GET", - "fixturePath": "/messaging/testing/project_1/numbers/support/phone", + "fixturePath": "/messaging/support/phone", "status": "covered", "testFile": "tests/test_onboarding.py" }, { "sdkMethod": "AsyncMessagingClient.testing.send_phone_message", "method": "POST", - "fixturePath": "/messaging/testing/project_1/numbers/support/phone/messages", + "fixturePath": "/messaging/support/phone/messages", "status": "covered", "testFile": "tests/test_onboarding.py" }, { "sdkMethod": "AsyncMessagingClient.testing.unlink_phone_device", "method": "POST", - "fixturePath": "/messaging/testing/project_1/numbers/support/phone/devices/2/unlink", + "fixturePath": "/messaging/support/phone/devices/2/unlink", "status": "covered", "testFile": "tests/test_onboarding.py" }, diff --git a/packages/python/tests/test_existing_contract_41.py b/packages/python/tests/test_existing_contract_41.py index 8991e57f0..00dc1bd8b 100644 --- a/packages/python/tests/test_existing_contract_41.py +++ b/packages/python/tests/test_existing_contract_41.py @@ -523,16 +523,14 @@ def respond(request, raw, count): ): o = RequestOptions(api_version=version) assert (await scoped.groups.get_capabilities("a/b", "g/1", options=o)).data["data"] == caps - assert (await c.testing.get_phone("p/1", "a/b", options=o)).data["online"] is False + assert (await c.testing.get_phone("a/b", options=o)).data["online"] is False assert ( await c.testing.send_phone_message( - "p/1", "a/b", {"to": "+15557654321", "text": "test"}, options=o + "a/b", {"to": "+15557654321", "text": "test"}, options=o ) ).data["messageId"] is None for device in (1, 99): - assert (await c.testing.unlink_phone_device("p/1", "a/b", device, options=o)).data[ - "unlinked" - ] + assert (await c.testing.unlink_phone_device("a/b", device, options=o)).data["unlinked"] for sync in ( "INITIAL_BOOTSTRAP", "INITIAL_STATUS_V3", @@ -560,7 +558,7 @@ def respond(request, raw, count): is None ) assert calls[0][1] == "/messaging/a%2Fb/groups/g%2F1/capabilities" - assert calls[1][1] == "/messaging/testing/p%2F1/numbers/a%2Fb/phone" + assert calls[1][1] == "/messaging/a%2Fb/phone" assert calls[1][3] == calls[3][3] == calls[4][3] == b"" assert json.loads(calls[2][3]) == {"to": "+15557654321", "text": "test"} assert [x[2]["polymorfa-version"] for x in calls[:5]] == [version or "2026-09-22"] * 5 @@ -568,7 +566,7 @@ def respond(request, raw, count): before = len(calls) for device in (0, 100, True): with pytest.raises(ValidationError): - await c.testing.unlink_phone_device("p", "s", device) + await c.testing.unlink_phone_device("s", device) for bad in ( {"chunkMessageId": None}, {"regenerate": None}, @@ -580,7 +578,7 @@ def respond(request, raw, count): "s", {"syncType": "RECENT", "chunkOrder": 0} | bad ) for action in ( - lambda: scoped.testing.get_phone("p", "s"), + lambda: scoped.testing.get_phone("s"), lambda: scoped.history_sync.request_chunk_retry( "s", {"syncType": "RECENT", "chunkOrder": 0} ), @@ -605,11 +603,11 @@ async def test_nine_malformed_success_is_safe(operation, bad): await ( c.groups.get_capabilities("s", "g") if operation == "group" - else c.testing.get_phone("p", "s") + else c.testing.get_phone("s") if operation == "phone" - else c.testing.send_phone_message("p", "s", {"to": "t", "text": "x"}) + else c.testing.send_phone_message("s", {"to": "t", "text": "x"}) if operation == "send" - else c.testing.unlink_phone_device("p", "s", 1) + else c.testing.unlink_phone_device("s", 1) if operation == "unlink" else c.history_sync.request_chunk_retry( "s", {"syncType": "RECENT", "chunkOrder": 0} @@ -933,7 +931,7 @@ async def test_no_key_uncertain_writes_are_once(operation): if operation == "audience" else c.audiences.add_members(ID, {"members": []}) if operation == "members" - else m.testing.send_phone_message("p", "s", {"to": "t", "text": "x"}) + else m.testing.send_phone_message("s", {"to": "t", "text": "x"}) ) assert len(calls) == 1 and "idempotency-key" not in calls[0][2] @@ -1009,11 +1007,11 @@ async def hold(request): action = ( m.groups.get_capabilities("s", "g") if operation == "group" - else m.testing.get_phone("p", "s") + else m.testing.get_phone("s") if operation == "phone" - else m.testing.send_phone_message("p", "s", {"to": "t", "text": "x"}) + else m.testing.send_phone_message("s", {"to": "t", "text": "x"}) if operation == "send" - else m.testing.unlink_phone_device("p", "s", 1) + else m.testing.unlink_phone_device("s", 1) if operation == "unlink" else c.request_logs.list(project_id=PROJECT) if operation == "logs" diff --git a/packages/python/tests/test_onboarding.py b/packages/python/tests/test_onboarding.py index bd4e03101..a64108f59 100644 --- a/packages/python/tests/test_onboarding.py +++ b/packages/python/tests/test_onboarding.py @@ -44,16 +44,15 @@ ), ( "POST", - "/messaging/testing/project_1/history-fixtures", + "/messaging/projects/project_1/test-history-fixtures", HISTORY, {"fixtureId": "fixture_1"}, lambda c: c.testing.create_history_fixture("project_1", HISTORY), ), ( "POST", - "/messaging/testing/project_1/events", + "/messaging/support/test-events", { - "session": "support", "event": "message.received", "overrides": { "text": "Hello", @@ -71,9 +70,8 @@ "source": "test", }, lambda c: c.testing.trigger_event( - "project_1", + "support", { - "session": "support", "event": "message.received", "overrides": { "text": "Hello", @@ -87,8 +85,8 @@ ), ( "POST", - "/messaging/testing/project_1/events", - {"session": "support", "event": "message.received", "fromSession": "sales"}, + "/messaging/support/test-events", + {"event": "message.received", "fromNumber": "sales"}, { "event": "message.received", "session": "support", @@ -97,12 +95,12 @@ "source": "runtime", }, lambda c: c.testing.trigger_event( - "project_1", {"session": "support", "event": "message.received", "fromSession": "sales"} + "support", {"event": "message.received", "fromNumber": "sales"} ), ), ( "GET", - "/messaging/testing/project_1/events/fixtures", + "/messaging/test-events/fixtures", None, { "fixtures": [ @@ -114,11 +112,11 @@ for name in TEST_EVENT_FIXTURES ] }, - lambda c: c.testing.list_event_fixtures("project_1"), + lambda c: c.testing.list_event_fixtures(), ), ( "GET", - "/messaging/testing/project_1/numbers/support/phone", + "/messaging/support/phone", None, { "session": "support", @@ -126,23 +124,21 @@ "online": True, "devices": [{"deviceId": 1}, {"deviceId": 2}], }, - lambda c: c.testing.get_phone("project_1", "support"), + lambda c: c.testing.get_phone("support"), ), ( "POST", - "/messaging/testing/project_1/numbers/support/phone/messages", + "/messaging/support/phone/messages", {"to": "+15551234568", "text": "Hello"}, {"session": "support", "to": "+15551234568", "messageId": None}, - lambda c: c.testing.send_phone_message( - "project_1", "support", {"to": "+15551234568", "text": "Hello"} - ), + lambda c: c.testing.send_phone_message("support", {"to": "+15551234568", "text": "Hello"}), ), ( "POST", - "/messaging/testing/project_1/numbers/support/phone/devices/2/unlink", + "/messaging/support/phone/devices/2/unlink", None, {"session": "support", "deviceId": 2, "unlinked": True}, - lambda c: c.testing.unlink_phone_device("project_1", "support", 2), + lambda c: c.testing.unlink_phone_device("support", 2), ), ] @@ -183,7 +179,7 @@ async def test_unlink_companion_bounds_and_keyed_fixture_retry(): ) as client: for device_id in [0, 100, True, 1.5]: with pytest.raises(ValidationError): - await client.testing.unlink_phone_device("project_1", "support", device_id) + await client.testing.unlink_phone_device("support", device_id) requests = [] def handler(request): @@ -214,8 +210,8 @@ def handler(request): http_transport=httpx.MockTransport(handler), ) as client: result = await client.testing.trigger_event( - "project_1", - {"session": "support", "event": "call.missed"}, + "support", + {"event": "call.missed"}, options=RequestOptions(idempotency_key="event-retry", max_network_retries=1), ) assert result.data["eventId"] == "event_2" and result.metadata.attempts == 2 diff --git a/packages/rust/README.md b/packages/rust/README.md index 4640826eb..dd840cfee 100644 --- a/packages/rust/README.md +++ b/packages/rust/README.md @@ -1032,6 +1032,27 @@ async fn confirm_explicitly(client: &polymorfa_sdk::MessagingClient, session: &s # } ``` +## Number-scoped Test operations + +The Test phone methods take a Number ID, without a project argument: +```rust,no_run +# async fn run(client: &polymorfa_sdk::MessagingClient) -> polymorfa_sdk::Result<()> { +use polymorfa_sdk::onboarding::{TestEventFixture, TriggerTestEventRequest}; +use polymorfa_sdk::RequestOptions; + +let phone = client.testing().get_phone("support", RequestOptions::default()).await?; +let event = client.testing().trigger_event("support", &TriggerTestEventRequest { + event: TestEventFixture::CallMissed, + overrides: None, + from_number: Some("sales".into()), +}, RequestOptions::default()).await?; +let fixtures = client.testing().list_event_fixtures(RequestOptions::default()).await?; +# let _ = (phone, event, fixtures); +# Ok(()) +# } +``` + +Send-phone-message and unlink-device helpers use the same Number scope. The trigger body contains event, optional overrides and optional fromNumber; it does not contain session or fromSession. The static fixture catalog has no project argument. History-fixture creation remains project-scoped. These operations require a server credential and the API’s Test-number access checks; a helper does not grant access or make a real Number a Test number. ## Guest participants and waiting rooms (unreleased) diff --git a/packages/rust/coverage.json b/packages/rust/coverage.json index 6e745485d..16bbadce3 100644 --- a/packages/rust/coverage.json +++ b/packages/rust/coverage.json @@ -4654,9 +4654,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/{session}/phone", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.testing.get_phone", + "testFile": "tests/onboarding.rs" }, { "family": "messaging", @@ -4694,9 +4694,9 @@ "family": "messaging", "method": "GET", "path": "/messaging/test-events/fixtures", - "status": "missing", - "reason": "The API moved this operation from GET /messaging/testing/{projectId}/events/fixtures to GET /messaging/test-events/fixtures; the SDK method for the old path (MessagingClient.testing.list_event_fixtures) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.testing.list_event_fixtures", + "testFile": "tests/onboarding.rs" }, { "family": "messaging", @@ -4766,17 +4766,17 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/devices/{deviceId}/unlink", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.testing.unlink_phone_device", + "testFile": "tests/onboarding.rs" }, { "family": "messaging", "method": "POST", "path": "/messaging/{session}/phone/messages", - "status": "missing", - "reason": "Added by contract revision f180dc1ee2 of polymorfa/polymorfa#887 and not yet attributed to a native SDK method in this ledger.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.testing.send_phone_message", + "testFile": "tests/onboarding.rs" }, { "family": "messaging", @@ -4806,9 +4806,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/{session}/test-events", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/events to POST /messaging/{session}/test-events; the SDK method for the old path (MessagingClient.testing.trigger_event) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.testing.trigger_event", + "testFile": "tests/onboarding.rs" }, { "family": "messaging", @@ -4822,9 +4822,9 @@ "family": "messaging", "method": "POST", "path": "/messaging/projects/{projectId}/test-history-fixtures", - "status": "missing", - "reason": "The API moved this operation from POST /messaging/testing/{projectId}/history-fixtures to POST /messaging/projects/{projectId}/test-history-fixtures; the SDK method for the old path (MessagingClient.testing.create_history_fixture) is not yet updated.", - "milestone": "contract-f180dc1ee2-sync" + "status": "covered", + "sdkMethod": "MessagingClient.testing.create_history_fixture", + "testFile": "tests/onboarding.rs" }, { "family": "messaging", diff --git a/packages/rust/src/onboarding.rs b/packages/rust/src/onboarding.rs index 685e521de..f6e1f4ce2 100644 --- a/packages/rust/src/onboarding.rs +++ b/packages/rust/src/onboarding.rs @@ -69,12 +69,11 @@ overrides!(text:String,from:String,push_name:String,media_type:TestMediaType,cap #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TriggerTestEventRequest { - pub session: String, pub event: TestEventFixture, #[serde(skip_serializing_if = "Option::is_none")] pub overrides: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub from_session: Option, + pub from_number: Option, } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -159,14 +158,10 @@ impl CloudOnboarding<'_> { } } fn project_path(project: &str) -> String { - format!("/messaging/testing/{}", encode(project)) + format!("/messaging/projects/{}", encode(project)) } -fn phone_path(project: &str, session: &str) -> String { - format!( - "{}/numbers/{}/phone", - project_path(project), - encode(session) - ) +fn phone_path(session: &str) -> String { + format!("/messaging/{}/phone", encode(session)) } impl Testing<'_> { pub async fn create_history_fixture( @@ -179,7 +174,7 @@ impl Testing<'_> { self.0 .request( Method::POST, - &format!("{}/history-fixtures", project_path(project)), + &format!("{}/test-history-fixtures", project_path(project)), &[], Some(body), options, @@ -188,7 +183,7 @@ impl Testing<'_> { } pub async fn trigger_event( &self, - project: &str, + session: &str, body: &TriggerTestEventRequest, options: RequestOptions, ) -> Result> { @@ -196,7 +191,7 @@ impl Testing<'_> { self.0 .request( Method::POST, - &format!("{}/events", project_path(project)), + &format!("/messaging/{}/test-events", encode(session)), &[], Some(body), options, @@ -205,30 +200,22 @@ impl Testing<'_> { } pub async fn list_event_fixtures( &self, - project: &str, options: RequestOptions, ) -> Result> { self.0.server()?; - self.0 - .get( - &format!("{}/events/fixtures", project_path(project)), - options, - ) - .await + self.0.get("/messaging/test-events/fixtures", options).await } pub async fn get_phone( &self, - project: &str, session: &str, options: RequestOptions, ) -> Result> { self.0.server()?; - let response = self.0.get(&phone_path(project, session), options).await?; + let response = self.0.get(&phone_path(session), options).await?; phone_response(response, 200, true) } pub async fn send_phone_message( &self, - project: &str, session: &str, body: &SendTestingPhoneMessageRequest, options: RequestOptions, @@ -238,7 +225,7 @@ impl Testing<'_> { .0 .request( Method::POST, - &format!("{}/messages", phone_path(project, session)), + &format!("{}/messages", phone_path(session)), &[], Some(body), options, @@ -248,7 +235,6 @@ impl Testing<'_> { } pub async fn unlink_phone_device( &self, - project: &str, session: &str, device: u8, options: RequestOptions, @@ -265,7 +251,7 @@ impl Testing<'_> { .0 .request::<_, ()>( Method::POST, - &format!("{}/devices/{device}/unlink", phone_path(project, session)), + &format!("{}/devices/{device}/unlink", phone_path(session)), &[], None, options, diff --git a/packages/rust/supplements.json b/packages/rust/supplements.json index 21d82a732..11b7b475d 100644 --- a/packages/rust/supplements.json +++ b/packages/rust/supplements.json @@ -40,21 +40,21 @@ { "sdkMethod": "MessagingClient.testing().get_phone", "method": "GET", - "fixturePath": "/messaging/testing/project/numbers/support/phone", + "fixturePath": "/messaging/support/phone", "status": "covered", "testFile": "tests/onboarding.rs" }, { "sdkMethod": "MessagingClient.testing().send_phone_message", "method": "POST", - "fixturePath": "/messaging/testing/project/numbers/support/phone/messages", + "fixturePath": "/messaging/support/phone/messages", "status": "covered", "testFile": "tests/onboarding.rs" }, { "sdkMethod": "MessagingClient.testing().unlink_phone_device", "method": "POST", - "fixturePath": "/messaging/testing/project/numbers/support/phone/devices/2/unlink", + "fixturePath": "/messaging/support/phone/devices/2/unlink", "status": "covered", "testFile": "tests/onboarding.rs" }, diff --git a/packages/rust/tests/adoption41.rs b/packages/rust/tests/adoption41.rs index 6945e767d..b9bcab978 100644 --- a/packages/rust/tests/adoption41.rs +++ b/packages/rust/tests/adoption41.rs @@ -1287,7 +1287,7 @@ async fn group_testing_and_request_log_actual_public_seams_keep_principals_and_e let m = support::messaging(wire.base.clone()); let phone = m .testing() - .get_phone("p /", "s /", Default::default()) + .get_phone("s /", Default::default()) .await .unwrap(); assert!(!phone.data.online); @@ -1295,7 +1295,6 @@ async fn group_testing_and_request_log_actual_public_seams_keep_principals_and_e let sent = m .testing() .send_phone_message( - "p /", "s /", &SendTestingPhoneMessageRequest { to: "+15550002222".into(), @@ -1313,7 +1312,7 @@ async fn group_testing_and_request_log_actual_public_seams_keep_principals_and_e for device in [1, 99] { assert!( m.testing() - .unlink_phone_device("p /", "s /", device, Default::default()) + .unlink_phone_device("s /", device, Default::default()) .await .unwrap() .data @@ -1330,27 +1329,26 @@ async fn group_testing_and_request_log_actual_public_seams_keep_principals_and_e wire.check( 1, "GET", - "/messaging/testing/p%20%2F/numbers/s%20%2F/phone", + "/messaging/s%20%2F/phone", json!(null), "2026-09-22", ); wire.check( 2, "POST", - "/messaging/testing/p%20%2F/numbers/s%20%2F/phone/messages", + "/messaging/s%20%2F/phone/messages", json!({"to":"+15550002222","text":"Synthetic test"}), "2026-10-14", ); assert!(!wire.captured()[2].headers.contains_key("idempotency-key")); assert!(scoped .testing() - .get_phone("p", "s", Default::default()) + .get_phone("s", Default::default()) .await .is_err()); assert!(scoped .testing() .send_phone_message( - "p", "s", &SendTestingPhoneMessageRequest { to: "x".into(), @@ -1362,14 +1360,14 @@ async fn group_testing_and_request_log_actual_public_seams_keep_principals_and_e .is_err()); assert!(scoped .testing() - .unlink_phone_device("p", "s", 1, Default::default()) + .unlink_phone_device("s", 1, Default::default()) .await .is_err()); assert_eq!(wire.captured().len(), 5); for device in [0, 100] { assert_eq!( m.testing() - .unlink_phone_device("p", "s", device, Default::default()) + .unlink_phone_device("s", device, Default::default()) .await .unwrap_err() .kind, @@ -1448,7 +1446,7 @@ async fn public_seam_malformed_errors_and_cancel_are_not_successes() { let w = Wire::raw(vec![(200, "fixture".into(), vec![])]).await; let e = support::messaging(w.base.clone()) .testing() - .get_phone("p", "s", Default::default()) + .get_phone("s", Default::default()) .await .unwrap_err(); assert_eq!(e.code.as_deref(), Some("invalid_response")); @@ -1462,13 +1460,12 @@ async fn public_seam_malformed_errors_and_cancel_are_not_successes() { let error = match kind { 0 => m .testing() - .get_phone("p", "s", Default::default()) + .get_phone("s", Default::default()) .await .unwrap_err(), 1 => m .testing() .send_phone_message( - "p", "s", &SendTestingPhoneMessageRequest { to: "x".into(), @@ -1480,7 +1477,7 @@ async fn public_seam_malformed_errors_and_cancel_are_not_successes() { .unwrap_err(), _ => m .testing() - .unlink_phone_device("p", "s", 1, Default::default()) + .unlink_phone_device("s", 1, Default::default()) .await .unwrap_err(), }; @@ -1507,7 +1504,7 @@ async fn public_seam_malformed_errors_and_cancel_are_not_successes() { ); assert_eq!( m.testing() - .get_phone("p", "s", options.clone()) + .get_phone("s", options.clone()) .await .unwrap_err() .kind, @@ -1516,7 +1513,6 @@ async fn public_seam_malformed_errors_and_cancel_are_not_successes() { assert_eq!( m.testing() .send_phone_message( - "p", "s", &SendTestingPhoneMessageRequest { to: "x".into(), @@ -1531,7 +1527,7 @@ async fn public_seam_malformed_errors_and_cancel_are_not_successes() { ); assert_eq!( m.testing() - .unlink_phone_device("p", "s", 1, options.clone()) + .unlink_phone_device("s", 1, options.clone()) .await .unwrap_err() .kind, @@ -1799,7 +1795,6 @@ async fn regression41_testing_message_requires_its_nullable_id() { assert!(support::messaging(w.base.clone()) .testing() .send_phone_message( - "p", "s", &polymorfa_sdk::onboarding::SendTestingPhoneMessageRequest { to: "phone".into(), @@ -1819,7 +1814,7 @@ async fn regression41_unlink_requires_the_acknowledged_true_outcome() { .await; assert!(support::messaging(w.base.clone()) .testing() - .unlink_phone_device("p", "s", 1, Default::default()) + .unlink_phone_device("s", 1, Default::default()) .await .is_err()); } diff --git a/packages/rust/tests/onboarding.rs b/packages/rust/tests/onboarding.rs index c98f748a2..09d995d17 100644 --- a/packages/rust/tests/onboarding.rs +++ b/packages/rust/tests/onboarding.rs @@ -30,7 +30,7 @@ async fn embedded_signup_and_simulated_event_history_resources_native_wire() { wire_messaging!( client, "POST", - "/messaging/testing/project/history-fixtures", + "/messaging/projects/project/test-history-fixtures", Some( json!({"messages":[{"id":"message","senderPhone":"+15551234567","text":"History","timestamp":1000,"fromMe":false}]}) ), @@ -52,15 +52,14 @@ async fn embedded_signup_and_simulated_event_history_resources_native_wire() { wire_messaging!( client, "POST", - "/messaging/testing/project/events", + "/messaging/support/test-events", Some( - json!({"session":"support","event":"message.received","overrides":{"text":"Hello","mediaType":"image","caption":"Caption"},"fromSession":"other"}) + json!({"event":"message.received","overrides":{"text":"Hello","mediaType":"image","caption":"Caption"},"fromNumber":"other"}) ), json!({"event":"message.received","session":"support","delivery":"simulated","eventId":null,"source":"runtime"}), client.testing().trigger_event( - "project", + "support", &TriggerTestEventRequest { - session: "support".into(), event: TestEventFixture::MessageReceived, overrides: Some(TestEventOverrides { text: Some("Hello".into()), @@ -68,7 +67,7 @@ async fn embedded_signup_and_simulated_event_history_resources_native_wire() { caption: Some("Caption".into()), ..Default::default() }), - from_session: Some("other".into()) + from_number: Some("other".into()) }, RequestOptions::default() ) @@ -76,12 +75,12 @@ async fn embedded_signup_and_simulated_event_history_resources_native_wire() { wire_messaging!( client, "GET", - "/messaging/testing/project/events/fixtures", + "/messaging/test-events/fixtures", None, json!({"fixtures":[{"name":"message.received","description":"Inbound message","overrides":["text","from","mediaType","caption"]},{"name":"session.status","description":"Status","overrides":["status","statusReason"]}]}), client .testing() - .list_event_fixtures("project", RequestOptions::default()) + .list_event_fixtures(RequestOptions::default()) ); } #[tokio::test] @@ -89,22 +88,21 @@ async fn simulated_phone_supplemental_native_wire_and_invalid_device_guard() { wire_messaging!( client, "GET", - "/messaging/testing/project/numbers/support/phone", + "/messaging/support/phone", None, json!({"session":"support","phone":"+15551234567","online":true,"devices":[{"deviceId":1},{"deviceId":2}]}), client .testing() - .get_phone("project", "support", RequestOptions::default()) + .get_phone("support", RequestOptions::default()) ); wire_messaging_status!( 202, client, "POST", - "/messaging/testing/project/numbers/support/phone/messages", + "/messaging/support/phone/messages", Some(json!({"to":"+15551234568","text":"Hello"})), json!({"session":"support","to":"+15551234568","messageId":"wamessage"}), client.testing().send_phone_message( - "project", "support", &SendTestingPhoneMessageRequest { to: "+15551234568".into(), @@ -116,19 +114,19 @@ async fn simulated_phone_supplemental_native_wire_and_invalid_device_guard() { wire_messaging!( client, "POST", - "/messaging/testing/project/numbers/support/phone/devices/2/unlink", + "/messaging/support/phone/devices/2/unlink", None, json!({"session":"support","deviceId":2,"unlinked":true}), client .testing() - .unlink_phone_device("project", "support", 2, RequestOptions::default()) + .unlink_phone_device("support", 2, RequestOptions::default()) ); let client = support::messaging("http://127.0.0.1:1".into()); for device in [0, 100] { assert_eq!( client .testing() - .unlink_phone_device("project", "support", device, RequestOptions::default()) + .unlink_phone_device("support", device, RequestOptions::default()) .await .unwrap_err() .kind, diff --git a/packages/typescript/README.md b/packages/typescript/README.md index 387c55d37..2ed09b0eb 100644 --- a/packages/typescript/README.md +++ b/packages/typescript/README.md @@ -3038,30 +3038,28 @@ hosted message storage. Fire a named, signed test event for a Test number. The event reaches your webhooks and event history with `source: "test"` and does not change the Test -number. Real numbers are refused with a `PolymorfaValidationError`, and each +number. Real Numbers return `404 resource_not_found` (`PolymorfaNotFoundError`), and each project can trigger 30 test events per minute (`PolymorfaRateLimitError`). ```ts import { TEST_EVENT_FIXTURES } from "@polymorfa/sdk"; -const result = await messaging.testing.triggerEvent(projectId, { - session: "my-test-number", +const result = await messaging.testing.triggerEvent("my-test-number", { event: "message.received", // one of TEST_EVENT_FIXTURES overrides: { text: "hi", from: "+15550100001" }, }); console.log(result.data.eventId); // Rare events: failed delivery, ban warning, incoming call, template rejection. -await messaging.testing.triggerEvent(projectId, { - session: "my-test-number", +await messaging.testing.triggerEvent("my-test-number", { event: "template.status", overrides: { templateStatus: "REJECTED", reason: "INVALID_FORMAT" }, }); -const { data } = await messaging.testing.listEventFixtures(projectId); +const { data } = await messaging.testing.listEventFixtures(); ``` -Set `fromSession` on a `message.received` request to send a simulated text +Set `fromNumber` on a `message.received` request to send a simulated text from another connected Test number in the same project instead; the response has `delivery: "simulated"` and the event arrives as ordinary Test number activity. Both methods require a team key or project token with @@ -3084,26 +3082,25 @@ to see which companions are linked, to send a message as the phone, or to unlink a companion as a person would from Linked devices. ```ts -const { data: phone } = await messaging.testing.getPhone( - projectId, - "my-test-number", -); +const { data: phone } = await messaging.testing.getPhone("my-test-number"); console.log(phone.online, phone.devices); // [{ deviceId: 33 }, ...] // Sent over the simulated network to another connected Test number in the // same project. The sender's companions receive the sent copy. -await messaging.testing.sendPhoneMessage(projectId, "my-test-number", { +await messaging.testing.sendPhoneMessage("my-test-number", { to: "+15550100002", text: "hello from the phone", }); -await messaging.testing.unlinkPhoneDevice(projectId, "my-test-number", 74); +await messaging.testing.unlinkPhoneDevice("my-test-number", 74); ``` `getPhone` needs `sandbox:read`; `sendPhoneMessage` and `unlinkPhoneDevice` need `sandbox:write`. All three need a team key or project token -and Test numbers access. Real numbers, an offline phone and recipients outside -the project are refused with a `PolymorfaValidationError`. Phone messages share +and Test numbers access. Real Numbers return `404 resource_not_found` +(`PolymorfaNotFoundError`). An offline phone and invalid recipients return +`400` (`PolymorfaValidationError`); a Test key hides unknown, real, and +other-project recipients with `404 resource_not_found`. Phone messages share the 30-per-minute project limit with test events. Device 0 is the phone and cannot be unlinked. diff --git a/packages/typescript/src/messaging/onboarding.ts b/packages/typescript/src/messaging/onboarding.ts index 5cd9c5535..93cec178c 100644 --- a/packages/typescript/src/messaging/onboarding.ts +++ b/packages/typescript/src/messaging/onboarding.ts @@ -67,7 +67,7 @@ export class TestingResource { assertServerCredential(this.credentialType); return this.transport.request({ method: "POST", - path: `/messaging/testing/${encodeURIComponent(projectId)}/history-fixtures`, + path: `/messaging/projects/${encodeURIComponent(projectId)}/test-history-fixtures`, body: input, ...options, }); @@ -75,22 +75,22 @@ export class TestingResource { /** * Fire a named, signed test event for a Test number. Generated events reach - * webhooks and event history with `source: "test"`. With `fromSession`, a + * webhooks and event history with `source: "test"`. With `fromNumber`, a * `message.received` request sends a simulated message from another Test - * number instead. Real numbers are refused with a 400 error. Pass + * number instead. Real numbers are refused with a 404 resource_not_found error. Pass * `options.idempotencyKey` to make retries safe: repeating the request with * the same key and body reuses the same event ID, and the SDK then retries * network and 5xx failures. */ triggerEvent( - projectId: string, + session: string, input: TriggerTestEventRequest, options: RequestOptions = {}, ): Promise> { assertServerCredential(this.credentialType); return this.transport.request({ method: "POST", - path: `/messaging/testing/${encodeURIComponent(projectId)}/events`, + path: `/messaging/${encodeURIComponent(session)}/test-events`, body: input, ...options, }); @@ -98,23 +98,21 @@ export class TestingResource { /** List test-event fixtures and the overrides each accepts. */ listEventFixtures( - projectId: string, options: RequestOptions = {}, ): Promise> { assertServerCredential(this.credentialType); return this.transport.request({ method: "GET", - path: `/messaging/testing/${encodeURIComponent(projectId)}/events/fixtures`, + path: `/messaging/test-events/fixtures`, ...options, }); } /** * Read a Test number's simulated phone: whether it is online and which - * companions are linked to it. Real numbers are refused with a 400 error. + * companions are linked to it. Real numbers are refused with a 404 resource_not_found error. */ getPhone( - projectId: string, session: string, options: RequestOptions = {}, ): Promise> { @@ -123,7 +121,7 @@ export class TestingResource { this.transport, { method: "GET", - path: phonePath(projectId, session), + path: phonePath(session), ...existingOptions(options), }, "phone", @@ -138,7 +136,6 @@ export class TestingResource { * normal inbound message. Counts toward the Testing rate limit. */ sendPhoneMessage( - projectId: string, session: string, input: SendTestingPhoneMessageRequest, options: RequestOptions = {}, @@ -148,7 +145,7 @@ export class TestingResource { this.transport, { method: "POST", - path: `${phonePath(projectId, session)}/messages`, + path: `${phonePath(session)}/messages`, body: input, ...existingOptions(options), }, @@ -163,7 +160,6 @@ export class TestingResource { * cannot be unlinked. */ unlinkPhoneDevice( - projectId: string, session: string, deviceId: number, options: RequestOptions = {}, @@ -177,7 +173,7 @@ export class TestingResource { this.transport, { method: "POST", - path: `${phonePath(projectId, session)}/devices/${deviceId}/unlink`, + path: `${phonePath(session)}/devices/${deviceId}/unlink`, ...existingOptions(options), }, "unlink", @@ -185,8 +181,8 @@ export class TestingResource { ); } } -function phonePath(projectId: string, session: string): string { - return `/messaging/testing/${encodeURIComponent(projectId)}/numbers/${encodeURIComponent(session)}/phone`; +function phonePath(session: string): string { + return `/messaging/${encodeURIComponent(session)}/phone`; } function assertServerCredential(type: MessagingCredential["type"]): void { if (type === "clientToken") diff --git a/packages/typescript/src/messaging/testing-configuration.ts b/packages/typescript/src/messaging/testing-configuration.ts index 167da4bf9..9234ef825 100644 --- a/packages/typescript/src/messaging/testing-configuration.ts +++ b/packages/typescript/src/messaging/testing-configuration.ts @@ -95,15 +95,13 @@ export interface TestEventOverrides { } export interface TriggerTestEventRequest { - /** Test number session name in the project. */ - session: string; event: TestEventFixture; overrides?: TestEventOverrides; /** * message.received only: deliver a real simulated message from this other * Test number in the same project instead of a generated event. */ - fromSession?: string; + fromNumber?: string; } export interface TriggerTestEventResponse { diff --git a/packages/typescript/test/coverage-reconciliation.test.ts b/packages/typescript/test/coverage-reconciliation.test.ts index fd0fb4bac..dc59c80c3 100644 --- a/packages/typescript/test/coverage-reconciliation.test.ts +++ b/packages/typescript/test/coverage-reconciliation.test.ts @@ -211,6 +211,35 @@ describe("reconciled coverage evidence", () => { } }); + it("covers the six Number-scoped Test routes from the global baseline", () => { + const ids = [ + "createTestingHistoryFixture", + "getTestingPhone", + "listTestEventFixtures", + "sendTestingPhoneMessage", + "triggerTestEvent", + "unlinkTestingPhoneDevice", + ]; + const operations = ledger.operations.filter((operation) => + ids.includes(operation.operationId), + ); + expect(operations.map((operation) => operation.operationId).sort()).toEqual( + ids, + ); + for (const operation of operations) { + expect(operation.typescript.status, operation.operationId).toBe( + "covered", + ); + expect(operation.path, operation.operationId).not.toContain( + "/messaging/testing/", + ); + expect( + (operation as LedgerEntry & { sourceCommit?: string }).sourceCommit, + operation.operationId, + ).toBeUndefined(); + } + }); + it("pins Analytics to the same full Platform source and snapshot hash", () => { const source = JSON.parse( readFileSync(repositoryFile("contracts/source.json"), "utf8"), diff --git a/packages/typescript/test/coverage.test.ts b/packages/typescript/test/coverage.test.ts index 4db4cf91b..d7fd11c64 100644 --- a/packages/typescript/test/coverage.test.ts +++ b/packages/typescript/test/coverage.test.ts @@ -175,9 +175,9 @@ describe("coverage checker", () => { expect(result.report).toMatchObject({ sourceCommit: "f180dc1ee2bd45dbecf01702f73bdd75c664634b", total: 671, - covered: 451, + covered: 457, partial: 2, - missing: 58, + missing: 52, excluded: 160, changed: 0, }); @@ -718,12 +718,9 @@ describe("coverage checker", () => { ({ operationId }) => operationId, ); expect(retired.sort()).toEqual([ - "createTestingHistoryFixture", "deactivateApiKey", "listApiKeys", "listPolymorfaTokens", - "listTestEventFixtures", - "triggerTestEvent", ]); expect( ledger.operations.some( diff --git a/packages/typescript/test/nine-41-public.test.ts b/packages/typescript/test/nine-41-public.test.ts index 60049584d..db75ac168 100644 --- a/packages/typescript/test/nine-41-public.test.ts +++ b/packages/typescript/test/nine-41-public.test.ts @@ -43,34 +43,28 @@ it("checks bare testing-phone results and actual202 through native HTTP", async credential: { type: "projectToken", value: PROJECT_TOKEN }, baseUrl: server.url, }); - expect((await m.testing.getPhone(projectId, "s/a")).data).toEqual( - fixtures[0], - ); + expect((await m.testing.getPhone("s/a")).data).toEqual(fixtures[0]); expect( ( - await m.testing.sendPhoneMessage(projectId, "s/a", { + await m.testing.sendPhoneMessage("s/a", { to: "+15551234568", text: "x", }) ).metadata.status, ).toBe(202); - expect( - (await m.testing.unlinkPhoneDevice(projectId, "s/a", 99)).data, - ).toEqual(fixtures[2]); + expect((await m.testing.unlinkPhoneDevice("s/a", 99)).data).toEqual( + fixtures[2], + ); expect(server.requests.map((r) => [r.method, r.path, r.body])).toEqual([ - ["GET", `/messaging/testing/${projectId}/numbers/s%2Fa/phone`, ""], + ["GET", `/messaging/s%2Fa/phone`, ""], [ "POST", - `/messaging/testing/${projectId}/numbers/s%2Fa/phone/messages`, + `/messaging/s%2Fa/phone/messages`, '{"to":"+15551234568","text":"x"}', ], - [ - "POST", - `/messaging/testing/${projectId}/numbers/s%2Fa/phone/devices/99/unlink`, - "", - ], + ["POST", `/messaging/s%2Fa/phone/devices/99/unlink`, ""], ]); - await expect(m.testing.getPhone(projectId, "s/a")).rejects.toMatchObject({ + await expect(m.testing.getPhone("s/a")).rejects.toMatchObject({ code: "invalid_response", metadata: { headers: { "x-trace-id": "a".repeat(32) } }, }); diff --git a/packages/typescript/test/onboarding.test.ts b/packages/typescript/test/onboarding.test.ts index 80a7f2793..743f39499 100644 --- a/packages/typescript/test/onboarding.test.ts +++ b/packages/typescript/test/onboarding.test.ts @@ -39,7 +39,7 @@ it("uploads fixture content separately and advances an existing QuickLink withou expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual(input); expect(JSON.parse(String(fetcher.mock.calls[1]?.[1]?.body))).toEqual(signup); expect(String(fetcher.mock.calls[0]?.[0])).toContain( - "/messaging/testing/project-a/history-fixtures", + "/messaging/projects/project-a/test-history-fixtures", ); expect(String(fetcher.mock.calls[1]?.[0])).toContain( "/messaging/cloud-api/embedded-signup", diff --git a/packages/typescript/test/testing-events.test.ts b/packages/typescript/test/testing-events.test.ts index 62042939a..b48876d5f 100644 --- a/packages/typescript/test/testing-events.test.ts +++ b/packages/typescript/test/testing-events.test.ts @@ -3,7 +3,7 @@ import { afterEach, expect, it, vi } from "vitest"; import { MessagingClient, PolymorfaRateLimitError, - PolymorfaValidationError, + PolymorfaNotFoundError, TEST_EVENT_FIXTURES, type TriggerTestEventRequest, } from "../src/index.js"; @@ -50,16 +50,13 @@ it("triggers a typed test event with overrides", async () => { }; const { client: messaging, fetcher } = client(json(accepted, 202)); const input: TriggerTestEventRequest = { - session: "test-a", event: "message.received", overrides: { text: "hi", from: "+15550100001" }, }; - const result = await messaging.testing.triggerEvent("project a", input); + const result = await messaging.testing.triggerEvent("test-a", input); expect(result.data).toEqual(accepted); const [url, init] = fetcher.mock.calls[0]!; - expect(String(url)).toBe( - "https://api.example/messaging/testing/project%20a/events", - ); + expect(String(url)).toBe("https://api.example/messaging/test-a/test-events"); expect(init?.method).toBe("POST"); expect(JSON.parse(String(init?.body))).toEqual(input); }); @@ -71,12 +68,12 @@ it("lists fixtures", async () => { overrides: [], })); const { client: messaging, fetcher } = client(json({ fixtures })); - const result = await messaging.testing.listEventFixtures("project-a"); + const result = await messaging.testing.listEventFixtures(); expect(result.data.fixtures.map((f) => f.name)).toEqual([ ...TEST_EVENT_FIXTURES, ]); expect(String(fetcher.mock.calls[0]![0])).toBe( - "https://api.example/messaging/testing/project-a/events/fixtures", + "https://api.example/messaging/test-events/fixtures", ); expect(fetcher.mock.calls[0]![1]?.method).toBe("GET"); }); @@ -121,12 +118,11 @@ it.each([true, false])( }; const { client: messaging, fetcher } = client(json(accepted, 202)); const input: TriggerTestEventRequest = { - session: "test-a", event: "session.restriction_updated", overrides: { restrictionActive }, }; expect( - (await messaging.testing.triggerEvent("project-a", input)).data, + (await messaging.testing.triggerEvent("test-a", input)).data, ).toEqual(accepted); expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual(input); }, @@ -137,11 +133,10 @@ it("sends a call restriction outcome supported by the API fixture", async () => json({ event: "call.ended" }, 202), ); const input: TriggerTestEventRequest = { - session: "test-a", event: "call.ended", overrides: { callEndReason: "call_restricted" }, }; - await messaging.testing.triggerEvent("project-a", input); + await messaging.testing.triggerEvent("test-a", input); expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual(input); }); @@ -151,22 +146,20 @@ it("surfaces a real-session refusal as an invalid request", async () => { { error: { type: "invalid_request_error", - code: "invalid_parameter", - message: - "Test events are available only for Test numbers. This session is not a Test number in the project, or it does not exist.", + code: "resource_not_found", + message: "Resource not found", param: null, }, data: null, }, - 400, + 404, ), ); await expect( - messaging.testing.triggerEvent("project-a", { - session: "real", + messaging.testing.triggerEvent("real", { event: "call.received", }), - ).rejects.toBeInstanceOf(PolymorfaValidationError); + ).rejects.toBeInstanceOf(PolymorfaNotFoundError); }); it("rejects client tokens before transport", () => { @@ -177,12 +170,11 @@ it("rejects client tokens before transport", () => { fetch: fetcher, }); expect(() => - messaging.testing.triggerEvent("project-a", { - session: "test-a", + messaging.testing.triggerEvent("test-a", { event: "session.status", }), ).toThrow("requires a team key or project token"); - expect(() => messaging.testing.listEventFixtures("project-a")).toThrow( + expect(() => messaging.testing.listEventFixtures()).toThrow( "requires a team key or project token", ); expect(fetcher).not.toHaveBeenCalled(); @@ -203,8 +195,8 @@ it("surfaces the per-project rate limit", async () => { ); await expect( messaging.testing.triggerEvent( - "project-a", - { session: "test-a", event: "call.missed" }, + "test-a", + { event: "call.missed" }, { maxNetworkRetries: 0 }, ), ).rejects.toBeInstanceOf(PolymorfaRateLimitError); @@ -231,8 +223,8 @@ it("sends an optional Idempotency-Key and retries safely with it", async () => { fetch: fetcher, }); const result = await messaging.testing.triggerEvent( - "project-a", - { session: "test-a", event: "message.received" }, + "test-a", + { event: "message.received" }, { idempotencyKey: "trigger-1", maxNetworkRetries: 1 }, ); expect(result.data).toEqual(accepted); @@ -255,8 +247,7 @@ it("omits Idempotency-Key when none is given", async () => { 202, ), ); - await messaging.testing.triggerEvent("project-a", { - session: "test-a", + await messaging.testing.triggerEvent("test-a", { event: "session.status", }); const init = fetcher.mock.calls[0]![1]; @@ -266,12 +257,10 @@ it("omits Idempotency-Key when none is given", async () => { it("serializes restriction fixtures and restricted call endings", async () => { for (const input of [ { - session: "test-a", event: "session.restriction_updated", overrides: { restrictionActive: true }, }, { - session: "test-a", event: "call.ended", overrides: { callEndReason: "call_restricted" }, }, @@ -280,7 +269,7 @@ it("serializes restriction fixtures and restricted call endings", async () => { json( { event: input.event, - session: input.session, + session: "test-a", delivery: "generated", eventId: null, source: "test", @@ -288,7 +277,7 @@ it("serializes restriction fixtures and restricted call endings", async () => { 202, ), ); - await messaging.testing.triggerEvent("project-a", input); + await messaging.testing.triggerEvent("test-a", input); expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual(input); } }); diff --git a/packages/typescript/test/testing-phone.test.ts b/packages/typescript/test/testing-phone.test.ts index 0e389d6fa..6f2174def 100644 --- a/packages/typescript/test/testing-phone.test.ts +++ b/packages/typescript/test/testing-phone.test.ts @@ -4,6 +4,7 @@ import { MessagingClient, PolymorfaConfigurationError, PolymorfaValidationError, + PolymorfaNotFoundError, type TestingPhone, } from "../src/index.js"; import { TEAM_API_KEY } from "./support/credentials.js"; @@ -39,12 +40,10 @@ it("reads a Test number's phone", async () => { devices: [{ deviceId: 33 }, { deviceId: 74 }], }; const { client: messaging, fetcher } = client(json(phone)); - const result = await messaging.testing.getPhone("project-a", "test a"); + const result = await messaging.testing.getPhone("test a"); expect(result.data).toEqual(phone); const [url, init] = fetcher.mock.calls[0]!; - expect(String(url)).toBe( - "https://api.example/messaging/testing/project-a/numbers/test%20a/phone", - ); + expect(String(url)).toBe("https://api.example/messaging/test%20a/phone"); expect(init?.method).toBe("GET"); }); @@ -52,15 +51,11 @@ it("sends a message from the phone", async () => { const sent = { session: "test-a", to: "+15550100002", messageId: "3EB0AA" }; const { client: messaging, fetcher } = client(json(sent, 202)); const input = { to: "+15550100002", text: "hello" }; - const result = await messaging.testing.sendPhoneMessage( - "project-a", - "test-a", - input, - ); + const result = await messaging.testing.sendPhoneMessage("test-a", input); expect(result.data).toEqual(sent); const [url, init] = fetcher.mock.calls[0]!; expect(String(url)).toBe( - "https://api.example/messaging/testing/project-a/numbers/test-a/phone/messages", + "https://api.example/messaging/test-a/phone/messages", ); expect(init?.method).toBe("POST"); expect(JSON.parse(String(init?.body))).toEqual(input); @@ -69,30 +64,26 @@ it("sends a message from the phone", async () => { it("unlinks a companion", async () => { const unlinked = { session: "test-a", deviceId: 74, unlinked: true }; const { client: messaging, fetcher } = client(json(unlinked)); - const result = await messaging.testing.unlinkPhoneDevice( - "project-a", - "test-a", - 74, - ); + const result = await messaging.testing.unlinkPhoneDevice("test-a", 74); expect(result.data).toEqual(unlinked); const [url, init] = fetcher.mock.calls[0]!; expect(String(url)).toBe( - "https://api.example/messaging/testing/project-a/numbers/test-a/phone/devices/74/unlink", + "https://api.example/messaging/test-a/phone/devices/74/unlink", ); expect(init?.method).toBe("POST"); }); it.each([0, 100, 1.5])("refuses device ID %s before sending", (deviceId) => { const { client: messaging, fetcher } = client(json({})); - expect(() => - messaging.testing.unlinkPhoneDevice("project-a", "test-a", deviceId), - ).toThrow(PolymorfaValidationError); + expect(() => messaging.testing.unlinkPhoneDevice("test-a", deviceId)).toThrow( + PolymorfaValidationError, + ); expect(fetcher).not.toHaveBeenCalled(); }); it("refuses client tokens", () => { const { client: messaging, fetcher } = client(json({}), "clientToken"); - expect(() => messaging.testing.getPhone("project-a", "test-a")).toThrow( + expect(() => messaging.testing.getPhone("test-a")).toThrow( PolymorfaConfigurationError, ); expect(fetcher).not.toHaveBeenCalled(); @@ -110,7 +101,7 @@ it("surfaces an offline phone as a validation error", async () => { ), ); await expect( - messaging.testing.sendPhoneMessage("project-a", "test-a", { + messaging.testing.sendPhoneMessage("test-a", { to: "+15550100002", text: "hi", }), @@ -134,15 +125,15 @@ it("matches the pinned Testing phone contract", () => { const route = (operationId: string) => contract.operations[operationId]!; expect(route("getTestingPhone")).toMatchObject({ method: "GET", - path: "/messaging/testing/{projectId}/numbers/{session}/phone", + path: "/messaging/{session}/phone", }); expect(route("sendTestingPhoneMessage")).toMatchObject({ method: "POST", - path: "/messaging/testing/{projectId}/numbers/{session}/phone/messages", + path: "/messaging/{session}/phone/messages", }); expect(route("unlinkTestingPhoneDevice")).toMatchObject({ method: "POST", - path: "/messaging/testing/{projectId}/numbers/{session}/phone/devices/{deviceId}/unlink", + path: "/messaging/{session}/phone/devices/{deviceId}/unlink", }); const fields = (name: string) => Object.keys(contract.schemas[name]!.properties).sort(); @@ -161,3 +152,15 @@ it("matches the pinned Testing phone contract", () => { "unlinked", ]); }); + +it("hides a real Number with resource_not_found", async () => { + const { client: messaging } = client( + json( + { error: { code: "resource_not_found", message: "Resource not found" } }, + 404, + ), + ); + await expect( + messaging.testing.getPhone("real-number"), + ).rejects.toBeInstanceOf(PolymorfaNotFoundError); +}); diff --git a/scripts/doc-snippets/recipes.mjs b/scripts/doc-snippets/recipes.mjs index 8a64abb33..37f240bd2 100644 --- a/scripts/doc-snippets/recipes.mjs +++ b/scripts/doc-snippets/recipes.mjs @@ -1,7 +1,7 @@ // Requests come from the pinned OpenAPI and existing native wire fixtures. // Calls are handwritten in the language modules. Never derive arguments from // contracts/coverage.json's display-only method names. -export const sourceCommit = "4b6ce43985ab6e3d6b0427858da5792c06dbb520"; +export const sourceCommit = "1e6fd9952e8183497a28f43c3987d960d9bf52eb"; export const apiVersion = "2026-09-22"; export const languages = [ "typescript", diff --git a/scripts/native-supplements.mjs b/scripts/native-supplements.mjs index 85f5b167d..0945c88e1 100644 --- a/scripts/native-supplements.mjs +++ b/scripts/native-supplements.mjs @@ -166,6 +166,43 @@ export function checkNativeSupplements(root, inventory) { ); } } + // The Number-scoped Test phone operations live in the ledger, not this + // inventory; each language's supplements.json must still record all three + // on the current routes, with the path present in its wire test. + for (const language of NATIVE_SUPPLEMENT_LANGUAGES) { + if (language === "typescript") continue; + const packageRoot = resolve(root, "packages", language); + const manifest = JSON.parse( + readFileSync(resolve(packageRoot, "supplements.json")), + ); + const phone = manifest.operations.filter((entry) => + /^\/messaging\/[^/]+\/phone(\/|$)/.test(entry.fixturePath ?? ""), + ); + assert.deepEqual( + phone + .map( + (entry) => + `${entry.method} ${entry.fixturePath + .replace(/^\/messaging\/[^/]+/, "/messaging/{session}") + .replace(/\/devices\/\d+\//, "/devices/{deviceId}/")}`, + ) + .sort(), + [ + "GET /messaging/{session}/phone", + "POST /messaging/{session}/phone/devices/{deviceId}/unlink", + "POST /messaging/{session}/phone/messages", + ], + `${language} supplements.json must record the three Number-scoped phone routes`, + ); + for (const entry of phone) { + assert.ok( + readFileSync(resolve(packageRoot, entry.testFile), "utf8").includes( + entry.fixturePath, + ), + `${language} wire test lacks ${entry.fixturePath}`, + ); + } + } for (const field of inventory.fields) { const source = supplements.get(field.supplement)?.sources?.[field.family]; assert.ok(