diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0477999..6969ddf 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.3.2" + ".": "0.3.3" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e5973e..13b6bd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## [0.3.3](https://github.com/xapi-labs/xapi-cli/compare/v0.3.2...v0.3.3) (2026-11-27) + + +### Features + +* **cli:** accept PREVIEW revision state and add --preview flag ([8dfc574](https://github.com/xapi-labs/xapi-cli/commit/8dfc5742449f5580b18a2cf4dc5c436a49a50155)) +* **cli:** add --preview to get, get-batch and categories ([b2b4f85](https://github.com/xapi-labs/xapi-cli/commit/b2b4f8558c2f18231e6aa389cd6b7d80a4bb09e0)) +* **cli:** promote the PREVIEW lifecycle state and --preview to staging ([e968136](https://github.com/xapi-labs/xapi-cli/commit/e9681365d310ef4c745696b2158cd531dbfef7fc)) +* **cli:** support preview services in discovery and action calls ([ad476ba](https://github.com/xapi-labs/xapi-cli/commit/ad476ba385d1343aff2dae5a760f7f4cb53cf850)) +* **provider:** explain default-major takedown conflicts and document endpoint delisting ([8766527](https://github.com/xapi-labs/xapi-cli/commit/8766527c66af09cf55780b86703f30ecda67cf54)) +* **skill:** explain service-limited keys and permission errors ([42aad1b](https://github.com/xapi-labs/xapi-cli/commit/42aad1b4f45843eb40408bf79b132eda85ba56c3)) + + +### Bug Fixes + +* **cli:** carry --preview into --code snippets and explain old-backend 400s ([2db03b2](https://github.com/xapi-labs/xapi-cli/commit/2db03b252b6dce9df3f10151abfcdd3f22285167)) +* **cli:** promote the call --preview old-backend hint to staging ([7d4f3ba](https://github.com/xapi-labs/xapi-cli/commit/7d4f3ba31ad97bd5ff2b9333b9516ca67a82485c)) +* **cli:** show the old-backend hint when call --preview gets a 400 ([2a68a15](https://github.com/xapi-labs/xapi-cli/commit/2a68a1589756f9290cb418e1aa25a27910398fde)) + ## [0.3.2](https://github.com/xapi-labs/xapi-cli/compare/v0.3.1...v0.3.2) (2026-11-19) diff --git a/README.md b/README.md index 064d1ef..c6b6750 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ xapi-to search "token price" --source api # search APIs only xapi-to search "token price" --sort relevance # strongest text match xapi-to search "token price" --sort price # lowest comparable price xapi-to search "twitter" --include-all-versions # include active non-default majors +xapi-to search "weather" --preview # also include your own PREVIEW services xapi-to categories # list all categories xapi-to categories --source capability # categories for capabilities only @@ -209,7 +210,7 @@ xapi-to provider import --file openapi.json > imported.json PROVIDER_SERVICE_ID=$(jq -er '.serviceId' imported.json) PROVIDER_REVISION_ID=$(jq -er '.revisionId' imported.json) -# Imports with endpoints start in SANDBOX on updated backends. +# Imports with endpoints start in PREVIEW on updated backends. # Inspect configuration and prices before submission. xapi-to provider get "$PROVIDER_SERVICE_ID" --format pretty @@ -233,7 +234,15 @@ nonzero; its structured validation errors are preserved. Registration creates a new service each time. If a response is lost, inspect `provider list` before retrying to avoid duplicate services. An older deployed backend may still return `DRAFT` for an import with endpoints; only then save its configuration once with -`provider update --revision --file config.json` to enter `SANDBOX`. +`provider update --revision --file config.json` to enter `PREVIEW`. +Older backends report this state as `SANDBOX`; the CLI accepts both. + +While a revision is in `PREVIEW`, you can call it for free to self-test. Pass +`--preview` to `list`, `search`, `categories`, `services`, `get`, `get-batch` +or `call` (API field `include_preview`) to include your own preview services; they are no longer +exposed through an API key permission, and any of your keys works. Preview +responses carry `X-XAPI-Billing: preview` and usage records mark them with +`isPreviewCall: true`. For an authenticated upstream, store credentials in a local JSON object such as `{"Authorization":"Bearer YOUR_UPSTREAM_KEY"}` and pass @@ -247,11 +256,12 @@ and structured validation errors rather than changing a version label. Missing per-call prices stop import before a write. Choose an explicit default with `--default-price 0.001`, or use `--default-price 0` when free access is -intended. The default fills only missing `PER_CALL` prices (including hidden +intended. The default fills only missing `PER_CALL` prices (including delisted operations) and preserves authored prices and billing types. Resource, token and dynamic operations need their own pricing configuration in the spec; a -per-call default cannot fill those. Hidden endpoints remain callable, so they -also need an explicit pricing choice. +per-call default cannot fill those. Delisted (`x-xapi-delisted: true`) endpoints are not +callable (the gateway returns 410), but they keep their pricing so they can be +restored, so they also need an explicit pricing choice. `provider update --revision ` reads a version configuration object, using the backend fields `description`, `baseUrl`, `baseUrls`, `authType`, `privateHeaders`, @@ -296,7 +306,7 @@ does not guarantee publication, but a passing review can automatically publish and switch live traffic. `wait` checks the requested revision, succeeds only for `PUBLISHED`, and outputs the review report with `success` and `reason`. `--changelog` is limited to 2,000 characters by both the CLI and backend. -Rejection, a draft/sandbox/suspended revision, or a legacy manual-review hold +Rejection, a draft/preview/suspended revision, or a legacy manual-review hold exit nonzero. Pending review continues until publication, the timeout (default 10 minutes), or optional `--max-attempts`. Timeout and attempt-limit results include the last received report; polling can be resumed with the same IDs. diff --git a/package.json b/package.json index 6a769a8..719b66a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "xapi-to", - "version": "0.3.2", + "version": "0.3.3", "description": "Agent-friendly CLI for xapi - discover and call capabilities and APIs", "type": "module", "bin": { diff --git a/skills/xapi-provider/SKILL.md b/skills/xapi-provider/SKILL.md index 6895502..cac1454 100644 --- a/skills/xapi-provider/SKILL.md +++ b/skills/xapi-provider/SKILL.md @@ -114,6 +114,29 @@ npx xapi-to provider revision start npx xapi-to provider major create ``` +To delist one endpoint, set `delisted: true` on it in a working revision and +publish. `x-xapi-delisted: true` in OpenAPI only applies to endpoints an import +creates; re-importing keeps an existing endpoint's state, so use the patch below. +If delisting is the revision's only change, it skips the upstream review test; +other pending edits in the same working revision are still reviewed. Callers +then get `410 EndpointDelisted` (host calls and Actions), and the endpoint +leaves docs, Marketplace and Tools. Set it back to `false` and +publish to restore it; delete the endpoint instead only to remove it for good. +For TIME_RENTAL, delist only the CREATE endpoint: submission rejects a delisted +TERMINATE or STATUS endpoint because open rentals could no longer be stopped. +SANDBOX endpoints cannot be delisted one by one (submission returns +`SANDBOX_ENDPOINT_DELISTED`); remove a size from `sandboxConfig.offerings` instead. +With merge mode, the patch carries only the endpoint ID from the working +revision (`currentVersion.endpoints` after `provider get`): + +```bash +echo '{"endpoints":[{"id":"ENDPOINT_ID","delisted":true}]}' > delist.json +npx xapi-to provider update --revision --file delist.json +``` + +The old names `hidden` / `x-xapi-hidden` are rejected with HTTP 400; use +`delisted` / `x-xapi-delisted`. + ## Marketplace content and usage Skill Update service-card content separately from the version contract: @@ -194,6 +217,11 @@ npx xapi-to provider deprecate npx xapi-to provider restore ``` +`deprecate` on the default major is refused with `409 +DEFAULT_MAJOR_HAS_LIVE_MAJORS` while another major is live: run `default-major` +to a live major first. Deprecating the only live major pauses the whole service. +A deprecated major answers `410 MajorVersionDelisted` to `X-Xapi-Version` calls. + Do not automatically retry an ambiguous rollback response. Read `versions` and `review` first. Deletion requires both `service:delete` and the explicit service name or ID: @@ -236,3 +264,15 @@ or prove upstream health. Dedicated CLI readiness support is still pending. Scope and ownership are independent. A key with a scope cannot manage another provider's service or Skill. + +An owner can also limit a key to selected services. That key lists only those +services, gets `404 API service not found` for any other service, and adds each +service it creates to its own selection. + +A missing permission returns `403` with `code: API_KEY_SCOPE_MISSING`, +`requiredPermission`, and `grantedBy` (the console permission groups that +include it). Report `requiredPermission` to the user. Only the owner, logged in +to the xAPI console with a full account login, can change a key's permissions, +service selection, IP allowlist, or limit; a session obtained by logging in +with an API Key cannot. The console's Developer template covers the operations +above except rollback and deletion. diff --git a/skills/xapi-provider/reference/lifecycle-management.md b/skills/xapi-provider/reference/lifecycle-management.md index f0cb301..33fad9f 100644 --- a/skills/xapi-provider/reference/lifecycle-management.md +++ b/skills/xapi-provider/reference/lifecycle-management.md @@ -6,13 +6,15 @@ Use the commands here instead of constructing management requests yourself. ## Service and revision states Creating a service with a non-empty `endpoints` list starts its v1 revision in -`SANDBOX`, including `provider import` and `provider create --file`. An empty -service starts in `DRAFT`; saving a valid contract moves it to `SANDBOX`. +`PREVIEW`, including `provider import` and `provider create --file`. An empty +service starts in `DRAFT`; saving a valid contract moves it to `PREVIEW`. +Older backends report `PREVIEW` as `SANDBOX` and revision labels as `sandbox`; +treat them as the same state. Read the returned state: older deployed backends may still create `DRAFT` even with endpoints, in which case save the contract once before submitting. Publishing moves it to `IN_REVIEW`. A passing review produces an immutable `PUBLISHED` revision. A failed review returns the -revision to `SANDBOX`; an uncertain review may wait for human review. A service +revision to `PREVIEW`; an uncertain review may wait for human review. A service can also become `SUSPENDED` after publication. Use these reads to determine current state and IDs: @@ -35,7 +37,31 @@ published revision is not necessarily serving. The legacy revision `status` field is not the routing truth. `revision start` may return an existing working revision, including one already -in review. Only `DRAFT` and `SANDBOX` are editable; inspect state before writing. +in review. Only `DRAFT` and `PREVIEW` are editable; inspect state before writing. + +## Self-test a preview service + +The owner can call their own `PREVIEW` service for free, rate-limited, before +submitting it. Preview services are hidden from Action discovery and execution +by default; pass `--preview` to opt in: + +```bash +npx xapi-to search "" --preview +npx xapi-to list --service-id --preview +npx xapi-to get --preview +npx xapi-to call --preview --input '{"key":"value"}' +``` + +The flag sends the query `include_preview=true` on `list`, `search`, +`categories` and `services`, and the body field `include_preview: true` on +`get`/`get-batch` (`POST /v1/actions/batch`) and `call` (`POST +/v1/actions/execute`). Without the flag the field is not sent. Direct Gateway calls to a +preview service need no flag. Any of the owner's API keys works; the former +key-level `allowSandbox` permission no longer exists and is ignored if sent. +Other users receive 404 (platform admins excepted). Preview responses carry `X-XAPI-Billing: preview` +(older backends: `sandbox`), and their usage records have `isPreviewCall: true` +(older field `isSandboxCall`). A free preview call still spends real upstream +supplier credits. Use the major and working `revision` number from the overview to read its contract, for example v1.4 for major 1, revision 4: @@ -313,6 +339,26 @@ npx xapi-to provider deprecate npx xapi-to provider restore ``` +Deprecating a non-default major takes only that major offline; the service stays +active. Deprecating the default major pauses the whole service, so it is allowed +only when no other major is live. Otherwise the API returns `409 +DEFAULT_MAJOR_HAS_LIVE_MAJORS` with `liveMajors`; switch the default to one of +them first, then deprecate. Calls that pin a deprecated major with +`X-Xapi-Version` get `410 MajorVersionDelisted`. + +To delist a single endpoint without touching the major, set `delisted: true` on +it in a working revision and publish (`x-xapi-delisted: true` in OpenAPI only +applies to endpoints an import creates). A delist-only revision skips the +upstream review test, and callers get `410 EndpointDelisted`; publishing +`delisted: false` restores it. TIME_RENTAL +groups may delist CREATE only. A revision with a delisted TERMINATE or STATUS +endpoint fails submission readiness with `RENTAL_LIFECYCLE_DELISTED`. If a revision +already in review has this configuration, it cannot take traffic. Automatic +review returns it for edits. A manual approval is rejected and the reviewer can +send it back. Restore the affected routes in the editable revision and submit +again. A rollback that would activate that revision also returns +`400 RENTAL_LIFECYCLE_DELISTED`. + Read `versions` after an ambiguous write. Delete only when the user intends to remove the service and has identified it by name or ID: diff --git a/skills/xapi-provider/reference/submission-readiness-and-review-recovery.md b/skills/xapi-provider/reference/submission-readiness-and-review-recovery.md index cf54b88..0d3d9e0 100644 --- a/skills/xapi-provider/reference/submission-readiness-and-review-recovery.md +++ b/skills/xapi-provider/reference/submission-readiness-and-review-recovery.md @@ -35,7 +35,8 @@ Normal Agent audit logging still applies. Its result contains: | `changes.reviewTestReason/reviewTestNote` | Why that review-test decision applies | | `selfTest` | Advisory availability, reason, observation boundary (`since`), endpoint observations and untested count; `blocking` is `false` | -Issue codes include `SERVICE_BLOCKED`, `REVISION_NOT_IN_SANDBOX`, `NO_ENDPOINTS`, +Issue codes include `SERVICE_BLOCKED`, `REVISION_NOT_IN_PREVIEW` (formerly +`REVISION_NOT_IN_SANDBOX`), `NO_ENDPOINTS`, `PROVIDER_SCHEMA_INVALID`, `ENDPOINT_PATH_INVALID`, `MISSING_BASE_URL`, `WS_MISSING_UPSTREAM`, `SANDBOX_CONFIG_INCOMPLETE`, and `PER_TOKEN_USAGE_UNREADABLE`. Correct the reported issues, then read readiness @@ -56,7 +57,7 @@ submission flow described in [lifecycle management](lifecycle-management.md). `REVIEW_INTERRUPTED` is a provider inbox notification for platform failure during automatic review. Its title identifies the service/revision; its body says the -revision returned to Sandbox without content changes and can be submitted again. +revision returned to Preview without content changes and can be submitted again. It does not carry the internal exception text, and it is not an author-content rejection or an approval. Notification data includes `apiVersionId`, `majorVersion` and the affected `reviewId`. @@ -64,11 +65,11 @@ rejection or an approval. Notification data includes `apiVersionId`, Recovery is tied to that review attempt and revision. A stale worker must not roll back a newer attempt, a completed decision or an unrelated revision, and must not emit a misleading recovery notification for them. The serving revision -continues serving while the working revision returns to `SANDBOX`. +continues serving while the working revision returns to `PREVIEW`. On receiving a notification, read `provider versions` and `provider review` for the referenced IDs. Confirm the current working revision is still the intended -`SANDBOX` revision, inspect readiness if supported, then explicitly submit it +`PREVIEW` revision, inspect readiness if supported, then explicitly submit it again when appropriate. A notification can be stale; never blindly resubmit a revision that is already `IN_REVIEW`, has a newer attempt, or has been published. Do not automatically replay an ambiguous submit response; read current state diff --git a/skills/xapi-provider/reference/tripo-async.md b/skills/xapi-provider/reference/tripo-async.md index a366264..5fab83f 100644 --- a/skills/xapi-provider/reference/tripo-async.md +++ b/skills/xapi-provider/reference/tripo-async.md @@ -62,7 +62,7 @@ long-term asset retention require separate verification. ## Acceptance boundary -Private draft/sandbox calls still spend real supplier credits while xAPI wallet +Private draft/preview calls still spend real supplier credits while xAPI wallet billing can be disabled. Supplier success and usage reconciliation do not prove nonzero caller-wallet settlement. Before paid public access, verify the final deployed candidate's ownership checks, result query/download, reservation diff --git a/skills/xapi-provider/reference/validation-checklist.md b/skills/xapi-provider/reference/validation-checklist.md index 7074db0..5d70185 100644 --- a/skills/xapi-provider/reference/validation-checklist.md +++ b/skills/xapi-provider/reference/validation-checklist.md @@ -38,7 +38,10 @@ before `provider version update --replace`, and again before publication. `id` does not always mean new. Preserve the stored `endpointKey` across revisions and use the working ID when changing a path; inspect the diff for unintended additions or removals. -- Path parameters use `:name` and have matching `pathParams` descriptions. +- Use `:name` at the end of a path segment, or `{name}` before a literal + suffix (for example, `/files/{id}.json`). In OpenAPI, use `{name}`. Add a + matching `pathParams` description and use each parameter name once when + creating an endpoint or changing its path. - Billing fields match the chosen `billingType`; pre-charge estimates are realistic. No price is negative. - A `PER_TOKEN` HTTP endpoint keeps usage readable: its protocol supplies usage @@ -78,9 +81,10 @@ Every imported operation needs an explicit price or billing configuration. For missing `PER_CALL` prices (including operations with no billing extension), choose the price with the user and pass `--default-price `, or add `x-xapi-billing.costPerCall` to the spec. `--default-price 0` explicitly chooses -free access. The default fills only missing per-call prices, including hidden +free access. The default fills only missing per-call prices, including delisted operations; it preserves explicit prices, including zero, and never changes a -billing type. Hidden operations remain callable and still need pricing. +billing type. Delisted (`x-xapi-delisted: true`) operations are not callable (the gateway +returns 410) but still need pricing, because they can be restored. `PER_RESOURCE` needs `costPerResource`, `PER_TOKEN` needs non-empty `tokenPricing` with a rate for each listed model, and `DYNAMIC` needs `dynamicRules`; configure those in the spec rather than using the per-call diff --git a/skills/xapi/SKILL.md b/skills/xapi/SKILL.md index 228d915..5f12c57 100644 --- a/skills/xapi/SKILL.md +++ b/skills/xapi/SKILL.md @@ -86,7 +86,7 @@ npx xapi-to search "token price" --sort relevance # strongest text match npx xapi-to search "token price" --sort price # lowest comparable price npx xapi-to search "twitter" --include-all-versions # include active non-default majors -# List all APIs (supports --source, --category, --service-id, --page, --page-size) +# List all APIs (supports --source, --category, --service-id, --page, --page-size; --preview, on every discovery/get/call command, adds your own unpublished PREVIEW services) npx xapi-to list npx xapi-to list --source capability npx xapi-to list --category Social --page-size 10 diff --git a/skills/xapi/guides/blockpi.md b/skills/xapi/guides/blockpi.md index 494b5d9..41446bf 100644 --- a/skills/xapi/guides/blockpi.md +++ b/skills/xapi/guides/blockpi.md @@ -135,10 +135,9 @@ or on-chain confirmation. Use a deliberately invalid, format-complete fixture for a forwarding check; do not construct a valid signed transaction to obtain 2xx. The maintained public Aptos contract has 27 operations. Raw table -`POST /v1/tables/{handle}/raw_item` is hidden pending upstream compatibility. -`hidden` controls public discovery/export and does not disable an existing -runtime route. Do not infer availability from its omission or advertise it as -supported. Its binary response type `application/x-bcs` is different from the +`POST /v1/tables/{handle}/raw_item` is delisted (`x-xapi-delisted: true`) pending +upstream compatibility: it is not listed or exported and the gateway returns +410 for it. Do not advertise it as supported. Its binary response type `application/x-bcs` is different from the signed-transaction **request** media type above. ## Generic JSON-RPC diff --git a/skills/xapi/guides/choosing.md b/skills/xapi/guides/choosing.md index 44233b0..9fa8a61 100644 --- a/skills/xapi/guides/choosing.md +++ b/skills/xapi/guides/choosing.md @@ -131,7 +131,7 @@ review status matters to the user's choice. Action execution envelopes may include `rate_limit` with `limit`, `remaining`, `reset_at` and optional `retry_after_seconds`. Service quota errors carry -`error.retry_after_seconds`; a quota rejection for free API sandbox calls uses +`error.retry_after_seconds`; a quota rejection for free API preview calls uses flat `retry_after_seconds` plus `rate_limit_buckets` (`creator_minute`, `creator_daily`, `api_key_daily`). Inspect the actual error body, including any outer Action envelope, instead of assuming one field location for all routes. diff --git a/skills/xapi/guides/provider.md b/skills/xapi/guides/provider.md index 6095aad..e6ecbba 100644 --- a/skills/xapi/guides/provider.md +++ b/skills/xapi/guides/provider.md @@ -27,6 +27,12 @@ manage another provider's service or Skill. These commands validate the owner path; they do not prove a separate administrator can view or review a working revision. +A key limited to selected services lists only those services and gets +`404 API service not found` for the others; services it creates join its +selection. A missing permission returns `403 API_KEY_SCOPE_MISSING` with +`requiredPermission` and `grantedBy`. Key permissions, service selection, IP +allowlist, and limit change only in the console after a full account login. + ## Create and describe a service Create uses the backend service DTO as JSON so credentials and endpoint diff --git a/src/commands/provider-onboarding.ts b/src/commands/provider-onboarding.ts index 63ed213..faf39d5 100644 --- a/src/commands/provider-onboarding.ts +++ b/src/commands/provider-onboarding.ts @@ -4,7 +4,7 @@ import { getConfig, requireApiKey } from '../config.ts'; import { HttpError, isRetryableRequestError } from '../client.ts'; import { output, err, type OutputFormat } from '../format.ts'; import { waitForPoll } from '../poll-wait.ts'; -import { providerRequest, object, redactProvider, collectProviderSecrets, type ProviderObject } from '../provider-client.ts'; +import { providerRequest, object, redactProvider, collectProviderSecrets, legacyFieldNotice, type ProviderObject } from '../provider-client.ts'; export const PROVIDER_ONBOARDING_HELP = `xapi-to provider - Import and publish your API services @@ -33,7 +33,7 @@ COMMON FLAGS configuration and credential files remain JSON. Swagger 2.0 conversion and OpenAPI validation happen on the server. Missing prices require an explicit choice; --default-price affects only unpriced PER_CALL operations, including -hidden ones, and preserves existing prices and other billing types. +delisted ones, and preserves existing prices and other billing types. Merge updates to existing endpoints require their IDs. Use --mode replace to replace the endpoint list, or --allow-new-endpoints to intentionally add. Creation with endpoints starts in PREVIEW (formerly SANDBOX); empty services @@ -289,7 +289,8 @@ export async function providerOnboarding(args: string[], flags: Record) { // Provider error bodies can echo submitted configuration or credentials. // Preserve local errors, but never print an HTTP response body verbatim. const message = error instanceof HttpError - ? `HTTP ${error.status}` + ? defaultMajorConflict(error) ?? legacyFieldNotice(error) ?? `HTTP ${error.status}` : String(redactProvider(error instanceof Error ? error.message : 'Unknown error', [apiKey])); err('provider request failed', message); } } + +// Deprecating the default major while another major is live is refused (409). +// The body is a fixed server message plus major labels, so it is safe to show. +function defaultMajorConflict(error: HttpError): string | undefined { + const body = error.responseBody as { code?: unknown; liveMajors?: unknown } | undefined; + if (error.status !== 409 || body?.code !== 'DEFAULT_MAJOR_HAS_LIVE_MAJORS') return undefined; + const live = Array.isArray(body.liveMajors) + ? body.liveMajors.filter((v): v is string => typeof v === 'string' && /^v\d+$/.test(v)) + : []; + const target = live[0] ?? ''; + return `HTTP 409: other majors are still live (${live.join(', ') || 'unknown'}). ` + + `Switch the default first: xapi-to provider default-major ${target.replace(/^v/, '')}, then deprecate.`; +} diff --git a/src/provider-client.ts b/src/provider-client.ts index 4133a8d..8db9a61 100644 --- a/src/provider-client.ts +++ b/src/provider-client.ts @@ -78,3 +78,16 @@ export function redactProvider(value: unknown, knownSecrets: string[] = []): unk } return visit(value); } + +// The backend rejects the old endpoint field names (`hidden`, `x-xapi-hidden`) with a fixed +// rename notice. It names only the field and the spec location, never request values, so it is +// safe to print; every other 400 body stays hidden because it may echo submitted configuration. +const LEGACY_FIELD_NOTICE = /no longer supported: it was renamed to `(x-xapi-)?delisted`/; + +export function legacyFieldNotice(error: { status: number; responseBody?: unknown }): string | undefined { + if (error.status !== 400) return undefined; + const body = error.responseBody as { message?: unknown } | undefined; + const messages = Array.isArray(body?.message) ? body.message : [body?.message]; + const notice = messages.find((m): m is string => typeof m === 'string' && LEGACY_FIELD_NOTICE.test(m)); + return notice ? `HTTP 400: ${notice}` : undefined; +} diff --git a/src/tests/provider-onboarding.test.ts b/src/tests/provider-onboarding.test.ts index 62105c0..1b4b63c 100644 --- a/src/tests/provider-onboarding.test.ts +++ b/src/tests/provider-onboarding.test.ts @@ -138,13 +138,13 @@ paths: expect(calls[1].body.openApiSpec).toEqual(swagger); }); - it('requires explicit missing-price choices and preserves authored billing, including hidden operations', async () => { + it('requires explicit missing-price choices and preserves authored billing, including delisted operations', async () => { respond = () => json({ success: true, apiService: { id: 'svc', activeVersionId: 'rev' } }); const spec = { openapi: '3.0.3', paths: { '/missing': { get: { summary: 'Missing' } }, '/typed': { post: { 'x-xapi-billing': { type: 'PER_CALL' } } }, '/empty-type': { GET: { 'x-xapi-billing': { type: '' } } }, - '/hidden': { get: { 'x-xapi-hidden': true } }, + '/delisted': { get: { 'x-xapi-delisted': true } }, '/priced': { get: { 'x-xapi-billing': { costPerCall: 0.25 } } }, '/free': { get: { 'x-xapi-billing': { type: 'PER_CALL', costPerCall: 0 } } }, '/resource': { get: { 'x-xapi-billing': { type: 'PER_RESOURCE', costPerResource: 0.03 } } }, @@ -157,10 +157,10 @@ paths: for (const price of ['0', '0.002']) { await provider(['import'], { file: path, 'default-price': price }); const paths = calls.at(-1)!.body.openApiSpec.paths; - for (const [route, method] of [['/missing', 'get'], ['/typed', 'post'], ['/hidden', 'get'], ['/empty-type', 'GET']]) { + for (const [route, method] of [['/missing', 'get'], ['/typed', 'post'], ['/delisted', 'get'], ['/empty-type', 'GET']]) { expect(paths[route!][method!]['x-xapi-billing'].costPerCall).toBe(Number(price)); } - expect(paths['/hidden'].get['x-xapi-hidden']).toBe(true); + expect(paths['/delisted'].get['x-xapi-delisted']).toBe(true); for (const route of ['/priced', '/free', '/resource', '/token']) { expect(paths[route]).toEqual(spec.paths[route as keyof typeof spec.paths]); } diff --git a/src/tests/provider.test.ts b/src/tests/provider.test.ts index c3afd47..e1b4c91 100644 --- a/src/tests/provider.test.ts +++ b/src/tests/provider.test.ts @@ -229,6 +229,36 @@ describe('provider command', () => { ); }); + it('explains the default-major 409 without echoing other response bodies', async () => { + requestSpy.mockRejectedValueOnce(new client.HttpError(409, 'conflict', undefined, { + code: 'DEFAULT_MAJOR_HAS_LIVE_MAJORS', + message: '默认版本是 v2,请先切换默认版本到 v1,再弃用 v2', + liveMajors: ['v1'], + })); + await expect(provider(['deprecate', 'service-1', '2'], {})).rejects.toThrow('err called'); + expect(errSpy).toHaveBeenCalledWith( + 'provider request failed', + 'HTTP 409: other majors are still live (v1). Switch the default first: xapi-to provider default-major 1, then deprecate.', + ); + + requestSpy.mockRejectedValueOnce(new client.HttpError(409, 'conflict', undefined, { code: 'OTHER', secret: 'x' })); + await expect(provider(['deprecate', 'service-1', '2'], {})).rejects.toThrow('err called'); + expect(errSpy).toHaveBeenLastCalledWith('provider request failed', 'HTTP 409'); + }); + + it('shows the backend rename notice for legacy delist field names only', async () => { + const notice = 'Field `hidden` is no longer supported: it was renamed to `delisted` (delisted = not listed, the gateway returns 410; set false to restore). Send `delisted` instead.'; + requestSpy.mockRejectedValueOnce(new client.HttpError(400, 'bad', undefined, { + statusCode: 400, error: 'Bad Request', message: ['endpoints.0.' + notice, 'name should not be empty'], + })); + await expect(provider(['deprecate', 'service-1', '2'], {})).rejects.toThrow('err called'); + expect(errSpy).toHaveBeenLastCalledWith('provider request failed', `HTTP 400: endpoints.0.${notice}`); + + requestSpy.mockRejectedValueOnce(new client.HttpError(400, 'bad', undefined, { message: ['secret-value is invalid'] })); + await expect(provider(['deprecate', 'service-1', '2'], {})).rejects.toThrow('err called'); + expect(errSpy).toHaveBeenLastCalledWith('provider request failed', 'HTTP 400'); + }); + it('links a primary skill using service:update', async () => { await provider(['skill', 'link', 'service-1', 'skill-1'], {});