@waffo/pancake-cli 0.0.1-rc.2 → 0.0.1-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +32 -13
  3. package/SKILL.md +8 -4
  4. package/dist/adapters/browser-login.js +1 -13
  5. package/dist/adapters/config.js +1 -1
  6. package/dist/adapters/operations.js +60 -2
  7. package/dist/adapters/pancake/client.js +48 -22
  8. package/dist/adapters/pancake/listener-http-error.js +43 -0
  9. package/dist/adapters/pancake/retry-after.js +46 -0
  10. package/dist/application/api-reads.js +1 -1
  11. package/dist/application/diagnostics.js +2 -1
  12. package/dist/application/dispatch.js +6 -2
  13. package/dist/application/listen-history.js +41 -0
  14. package/dist/application/listen-resend.js +101 -0
  15. package/dist/application/listen.js +23 -18
  16. package/dist/application/listener-context.js +11 -0
  17. package/dist/application/listener-signature.js +24 -0
  18. package/dist/application/local.js +1 -1
  19. package/dist/application/read-operation.js +15 -7
  20. package/dist/cli/human-output.js +7 -0
  21. package/dist/cli/listen-history-output.js +29 -0
  22. package/dist/cli/listen-output.js +2 -2
  23. package/dist/cli/output.js +1 -1
  24. package/dist/cli/run.js +10 -0
  25. package/dist/commands/api-coverage.js +7 -0
  26. package/dist/commands/listen-definitions.js +14 -0
  27. package/dist/commands/listen-input.js +6 -2
  28. package/dist/commands/listen-response.js +47 -0
  29. package/dist/commands/read-definitions.js +9 -1
  30. package/dist/commands/registry.js +5 -3
  31. package/dist/contracts/action-routes.js +14 -0
  32. package/dist/contracts/listen-replay.js +20 -0
  33. package/dist/contracts/listener-protocol.js +12 -0
  34. package/dist/contracts/listener-routes.js +11 -0
  35. package/docs/api-coverage.md +7 -4
  36. package/docs/usage.md +49 -7
  37. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.1-rc.4
4
+
5
+ - Verify local deliveries and resends with a new RSA key for each listener session. The ready event includes the public PEM for the local receiver. The CLI requests protocol 2 at startup. Notify requires clients to declare support before creating a listener. The CLI reports older deployments before listening or submitting a replay.
6
+ - Add browser-session listener history, private payload export and confirmed resend to an active listener. Stream delivery records now include their history record ID and original event ID.
7
+
8
+ ## 0.0.1-rc.3
9
+
10
+ Release candidate for npm’s `next` channel. No stable release.
11
+
12
+ - Point the packaged CLI agent reference to the official Docs page while retaining the bundled offline `SKILL.md`.
13
+ - Add `graphql query --background` for recurring reads that skip local operation records while retaining authenticated context and private response export.
14
+ - Pass an explicit local archive path to the manual npm publishing command.
15
+
3
16
  ## 0.0.1-rc.2
4
17
 
5
18
  Release candidate for npm’s `next` channel. No stable release.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Developer CLI for Waffo Pancake, built with TypeScript, Node.js and Commander. The official TypeScript compiler builds the CLI.
4
4
 
5
- **Release candidate: 0.0.1-rc.2, using npm’s `next` channel. No stable release yet.** Implemented: 62 commands covering merchant authentication, resource queries, 33 supported merchant API-Key REST action routes within the scope below, read-only GraphQL, offline previews, operation records and redacted diagnostics. Manage stores, products, subscription groups, checkout sessions, subscription cancellation, refund tickets, customer session tokens, notification recipients, content-safety checks, coupons, promotion codes and test webhooks. Temporary local webhook listening is available for browser sessions; event triggering is not implemented. This is separate from the Pancake migration CLI.
5
+ **Release candidate 0.0.1-rc.4 uses npm’s `next` channel.** It adds local webhook delivery history, replay and per-listener signatures. The CLI provides 65 commands covering merchant authentication, resource queries, 33 supported merchant API-Key REST action routes within the scope below, read-only GraphQL, offline previews, operation records and redacted diagnostics. Manage stores, products, subscription groups, checkout sessions, subscription cancellation, refund tickets, customer session tokens, notification recipients, content-safety checks, coupons, promotion codes and test webhooks. Temporary local webhook listening is available for browser sessions; event triggering is not implemented. This is separate from the Pancake migration CLI.
6
6
 
7
7
  ## Try locally without publishing
8
8
 
@@ -20,9 +20,9 @@ JSON
20
20
  pnpm cli products create --type onetime --file product.json --dry-run --json
21
21
  ```
22
22
 
23
- See the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/docs/usage.md) for input examples and safe operations, and the [API coverage matrix](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/docs/api-coverage.md) for every command, endpoint and authentication boundary. `commands`, `schema` and supported `--dry-run` options work offline without credentials. Pipe output or use `--json` for one JSON envelope (`listen` streams NDJSON envelopes); debugging goes to stderr. Monetary amounts are decimal strings.
23
+ See the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/docs/usage.md) for input examples and safe operations, and the [API coverage matrix](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/docs/api-coverage.md) for every command, endpoint and authentication boundary. `commands`, `schema` and supported `--dry-run` options work offline without credentials. Pipe output or use `--json` for one JSON envelope (`listen` streams NDJSON envelopes); debugging goes to stderr. Monetary amounts are decimal strings.
24
24
 
25
- Documentation links serve the published npm package through jsDelivr; no GitHub access is needed. They are versioned snapshots, so later repository edits appear only in a new package release. The same Markdown guides ship in the package for offline reading. For a global npm installation, run `npm root -g` and open `@waffo/pancake-cli/docs/usage.md` under that directory. In a source checkout, open `docs/usage.md` directly.
25
+ The agent reference is hosted on official Docs and identifies the release it documents; use the bundled `SKILL.md` for your installed CLI. Other documentation links serve the published npm package through jsDelivr; no GitHub access is needed. They are versioned snapshots, so later repository edits appear only in a new package release. The same Markdown guides ship in the package for offline reading. For a global npm installation, run `npm root -g` and open `@waffo/pancake-cli/docs/usage.md` under that directory. In a source checkout, open `docs/usage.md` directly.
26
26
 
27
27
  CLI prompts and help use concise English. In a terminal, `pnpm cli` shows the first-use steps, `commands` prints a compact command list, and `whoami` explains how to log in when no credentials are present. Use `--json` (or pipe stdout) for the complete machine envelope. Local pnpm/npm script help uses the corresponding local command; installed CLI help uses `pancake`.
28
28
 
@@ -75,17 +75,19 @@ The expanded action commands use `--file input.json`, require `--yes`, and suppo
75
75
 
76
76
  Checkout and customer-session creation require `--output` to a new private file. Customer-session issuance requires RSA login; browser login is unsupported for this command. It is not CLI login. Arbitrary `graphql query` and `analytics query` also require private output for execution; their parser rejects mutations, subscriptions and multiple operations before credentials or network access. There is no raw REST passthrough. Customer-token-only order cancellation/reactivation is outside merchant coverage. Product create/update rejects `taxIncluded`; webhook writes remain test-only. No real merchant acceptance or release is implied by route coverage.
77
77
 
78
+ For recurring read-only queries, `pancake graphql query --background --file query.json --output ./query-result.json --json` skips the local operation record for that invocation. Use a fresh private output path for each call. The gateway must verify the environment before the response can be exported, and a browser session must match its selected environment. Authenticated results include the effective `meta.apiOrigin` and set `meta.operationId` to `null`.
79
+
78
80
  Configuration uses version 2. Legacy version 1 is not migrated: run `logout`, then `login` with your existing key. Unknown future versions are never overwritten, including by logout. Concurrent login, environment selection or logout returns `CONFIG_CHANGED` if another command replaced or cleared its saved configuration; the newer configuration is preserved. Inspect `whoami` before starting another login or environment change.
79
81
 
80
82
  ## Install the release candidate
81
83
 
82
- Version `0.0.1-rc.2` uses npm's `next` channel. Use the explicit channel or version while evaluating the candidate:
84
+ Version `0.0.1-rc.4` uses npm's `next` channel. Use the explicit channel or version while evaluating the candidate:
83
85
 
84
86
  ```sh
85
87
  npm install -g @waffo/pancake-cli@next
86
88
  pancake --version
87
89
  # Or run the exact candidate without a global installation:
88
- npx @waffo/pancake-cli@0.0.1-rc.2 --help
90
+ npx @waffo/pancake-cli@0.0.1-rc.4 --help
89
91
  ```
90
92
 
91
93
  For the hosted service, no URL overrides are needed:
@@ -106,7 +108,7 @@ pancake env test
106
108
  pancake stores list
107
109
  ```
108
110
 
109
- Check the merchant and environment before business operations. Default URLs target production; npm installation does not deploy the hosted services. Production browser login and listener startup, polling and cleanup have passed; real Production payment delivery remains pending. Automated Windows package checks pass; a real Windows console Ctrl+C listener walkthrough remains pending.
111
+ Check the merchant and environment before business operations. Default URLs target production; npm installation does not deploy the hosted services. An earlier candidate passed Production browser login and listener startup, polling and cleanup with its original listener signing scheme; real Production payment delivery remains pending. Automated Windows package checks pass; a real Windows console Ctrl+C listener walkthrough remains pending.
110
112
 
111
113
  To update within the candidate channel, run `npm install -g @waffo/pancake-cli@next`. Stable Homebrew does not install prereleases.
112
114
 
@@ -180,9 +182,9 @@ Package smoke tests install the actual tarball in isolated directories and exerc
180
182
  - Homebrew: CLI CI installs the tested package artifact on macOS/Linux using pinned public tap tooling, without publishing it. The [tap](https://github.com/waffo-com/homebrew-pancake) detects stable npm versions, verifies integrity and tests installation before updating.
181
183
  - Weekly Dependabot updates cover dependencies and pinned Actions.
182
184
 
183
- See the [agent reference](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/SKILL.md) and [changelog](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/CHANGELOG.md). Maintainer release instructions are in `docs/release/README.md` in the source repository and require repository access.
185
+ See the [agent reference](https://docs.waffo.ai/waffo-pancake-cli-skill) and [changelog](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/CHANGELOG.md). Maintainer release instructions are in `docs/release/README.md` in the source repository and require repository access.
184
186
 
185
- Internal planning documents are maintained outside the source repository. The published `0.0.1-rc.1` candidate passed npm/npx installation checks and selected business operations in Test and Production. Production login and logout revocation, Test sandbox-payment forwarding, signature verification, retry and cleanup were also verified. This is not blanket acceptance of every command: real Production payment delivery and actual Windows console Ctrl+C remain pending. Local tests use simulated API responses.
187
+ Internal planning documents are maintained outside the source repository. The published `0.0.1-rc.1` candidate passed npm/npx installation checks and selected business operations in Test and Production. Production login and logout revocation also passed. The original listener signing scheme passed Test sandbox-payment forwarding, signature verification, retry and cleanup. This is not blanket acceptance of every command: real Production payment delivery and actual Windows console Ctrl+C remain pending. Local tests use simulated API responses.
186
188
 
187
189
  Using or contributing to this open-source client does not require private service source code. Remote commands require credentials and access to a compatible hosted API; browser login also requires a compatible Dashboard. Offline discovery and previews need neither service source nor a running API.
188
190
 
@@ -211,9 +213,9 @@ Overrides accept HTTPS, or HTTP on `127.0.0.1` only. No URL credentials, paths,
211
213
 
212
214
  ## Contributing and security
213
215
 
214
- See [CONTRIBUTING.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/CONTRIBUTING.md) for development and validation, and [SECURITY.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/SECURITY.md) for handling credentials and reporting vulnerabilities. Licensed under [MIT](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/LICENSE).
216
+ See [CONTRIBUTING.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/CONTRIBUTING.md) for development and validation, and [SECURITY.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/SECURITY.md) for handling credentials and reporting vulnerabilities. Licensed under [MIT](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/LICENSE).
215
217
 
216
- Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). Offline previews show discount amounts or percentages, duration, product scope, redemption limits, coupon IDs and batch count/length. Customer email restrictions remain redacted, including inside nested promotion codes. See the Discounts section in the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/docs/usage.md). Gateway source permits browser sessions and RSA keys; merchant/store permissions still apply. Discount writes have response-only verification; the nine discount commands passed isolated Test-environment merchant acceptance, including final deactivation read-back. Selected coupon and promotion-code operations also passed Production acceptance; this does not establish coverage of every discount operation or full stable-release acceptance.
218
+ Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). Offline previews show discount amounts or percentages, duration, product scope, redemption limits, coupon IDs and batch count/length. Customer email restrictions remain redacted, including inside nested promotion codes. See the Discounts section in the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/docs/usage.md). Gateway source permits browser sessions and RSA keys; merchant/store permissions still apply. Discount writes have response-only verification; the nine discount commands passed isolated Test-environment merchant acceptance, including final deactivation read-back. Selected coupon and promotion-code operations also passed Production acceptance; this does not establish coverage of every discount operation or full stable-release acceptance.
217
219
 
218
220
  ## Listen to merchant events locally
219
221
 
@@ -224,8 +226,25 @@ pnpm cli listen --store-id STO_example --forward-to http://localhost:3000/webhoo
224
226
 
225
227
  Requires browser login and access to the store. Listening always starts in Test, even if your saved selection is Production. Use `--live` to explicitly listen in Production; this does not change your saved environment. Each API response must verify the requested environment. RSA credentials are unsupported. The receiver must use HTTP(S) on localhost, 127.0.0.1 or [::1]; redirects are not followed.
226
228
 
227
- The CLI preserves the exact event body and existing webhook signature, forwards only Content-Type, X-Waffo-Signature and X-Waffo-Event, and reports the actual HTTP response. Only 2xx succeeds; network failures are reported as null. Failed delivery can retry up to three times with the same event ID. Verify signatures with the existing webhook public key for the selected environment and handle duplicate event IDs. Payloads and signatures are never printed.
229
+ At startup the CLI prints an RSA public key for this listener session. Set your local receiver to verify each request with that key, including Production events received via `--live`. Update the receiver key every time you start a listener. Permanent webhook endpoints continue to use their configured platform keys. See the local verification example in `docs/usage.md`.
230
+
231
+ The CLI verifies the listener signature before forwarding the exact event body and the Content-Type, X-Waffo-Signature and X-Waffo-Event headers. Only 2xx succeeds. Network failures are reported as null. Delivery allows up to three attempts with the same event ID. Deduplicate by event ID. Event bodies and signatures stay out of CLI output.
232
+
233
+ With `--json` or piped stdout, `listen` emits one standard JSON envelope per line: `data.type` is `ready`, `delivery` or `stopped`, followed by an error envelope if listening fails. The ready event includes `data.listenerProtocol` (2) and `data.signingPublicKey` (PEM). Delivery metadata includes recordId, deliveryId, eventId, eventType, attempt and httpStatus. Ctrl+C and SIGTERM stop and clean up the session before exiting (130); cleanup failure exits nonzero and reports the 90-second expiry fallback. Abrupt process termination leaves only a temporary session that expires within 90 seconds of its last successful poll. No permanent webhook is changed. Listening requires separately deployed relay/gateway support.
234
+
235
+ During the upgrade to listener protocol 2, temporary listeners pause while permanent webhook endpoints continue delivering. If `pancake --version` shows `0.0.1-rc.2` or `0.0.1-rc.3`, starting a listener against the upgraded service returns HTTP 400 before creating a session. Those versions can display `INVALID_REQUEST` for that response. To upgrade to protocol 2, run `npm install -g @waffo/pancake-cli@next` and verify that `pancake --version` shows `0.0.1-rc.4`. Restart `pancake listen` and configure your local receiver with the new session’s public key.
236
+
237
+ The earlier published candidate passed Test sandbox-payment delivery and Production listener startup, polling, mode isolation and cleanup on the production deployment with its original signing scheme. Live Production payment delivery and production-deployment acceptance of protocol 2 are pending.
228
238
 
229
- With `--json` or piped stdout, `listen` emits one standard JSON envelope per line: `data.type` is `ready`, `delivery` or `stopped`, followed by an error envelope if listening fails. Delivery metadata includes deliveryId, eventId, eventType, attempt and httpStatus. Ctrl+C and SIGTERM stop and clean up the session before exiting (130); cleanup failure exits nonzero and reports the 90-second expiry fallback. Abrupt process termination leaves only a temporary session that expires within 90 seconds of its last successful poll. No permanent webhook is changed. Listening requires separately deployed relay/gateway support.
239
+ ### Inspect and resend a captured delivery
240
+
241
+ Listener history and resend are available in this source checkout and require a compatible API deployment. Browser login is required. All listener commands default to Test. Pass `--live` for Production. History keeps the latest 100 captured deliveries for up to 24 hours per account, store and environment. It also lists your active listener sessions.
242
+
243
+ ```sh
244
+ pancake listen history --store-id STO_example --limit 20
245
+ pancake listen show <recordId> --store-id STO_example
246
+ pancake listen show <recordId> --store-id STO_example --output ./delivery.json
247
+ pancake listen resend <recordId> --session <sessionId> --store-id STO_example --yes --idempotency-key <uuid>
248
+ ```
230
249
 
231
- Isolated Test acceptance verified a sandbox payment event reaching localhost, valid signatures on both attempts, retry after HTTP 500 followed by HTTP 200, and Ctrl+C cleanup. On the production deployment, Test sandbox-payment delivery passed, and Production listener startup, polling, mode isolation and cleanup passed. Real Production payment delivery remains pending.
250
+ Show prints metadata and attempts. A new private output file includes the original payload. Resend enqueues it for the selected active listener matching the event filter. The target listener signs the replay and preserves the original `eventId` for receiver deduplication. The receipt includes a fresh delivery ID and history record ID. It creates no payment and does not retry a permanent webhook. Production resend also requires `--confirm-production`. If admission is uncertain, repeat the exact command with the same UUID within 24 hours to recover the receipt.
package/SKILL.md CHANGED
@@ -5,7 +5,7 @@ description: Discover and use the Waffo Pancake CLI for merchant API operations,
5
5
 
6
6
  # Waffo Pancake CLI
7
7
 
8
- Release candidate: `0.0.1-rc.2`, using the `next` channel. Install with `npm install -g @waffo/pancake-cli@next`, or use `npx @waffo/pancake-cli@0.0.1-rc.2`. In a source checkout, use `pnpm cli` after `pnpm install --frozen-lockfile && pnpm run build`. Runtime and development require Node.js >=22.14; Node.js 24 LTS is recommended for development. Use the pinned pnpm 11.25.0.
8
+ Release candidate: `0.0.1-rc.4`, using the `next` channel. Install with `npm install -g @waffo/pancake-cli@next`, or use `npx @waffo/pancake-cli@0.0.1-rc.4`. In a source checkout, use `pnpm cli` after `pnpm install --frozen-lockfile && pnpm run build`. Runtime and development require Node.js >=22.14; Node.js 24 LTS is recommended for development. Use the pinned pnpm 11.25.0.
9
9
 
10
10
  For UAT, pass team-provided `--dashboard-url <origin>` and `--api-url <origin>` to login; default URLs target production. Check `whoami` and select `env test` before UAT business operations. Package installation does not deploy compatible hosted services or prove production readiness.
11
11
 
@@ -53,7 +53,7 @@ Read the command schema to construct JSON files. `--file -` reads one JSON objec
53
53
 
54
54
  ## Expanded merchant coverage
55
55
 
56
- There are 62 registered commands and 33 supported merchant API-Key REST action routes. Run discovery for exact flags and schemas; do not invent `orders get`, `subscriptions get`, or group read commands. Resource lists cover products, versions, orders, subscriptions, payments, refunds, refund tickets, notification recipients and merchants. Product/order variants require `--type onetime|subscription` where documented. Read one page at a time; a full page means `hasMore:"unknown"`.
56
+ There are 65 registered commands and 33 supported merchant API-Key REST action routes. Run discovery for exact flags and schemas; do not invent `orders get`, `subscriptions get`, or group read commands. Resource lists cover products, versions, orders, subscriptions, payments, refunds, refund tickets, notification recipients and merchants. Product/order variants require `--type onetime|subscription` where documented. Read one page at a time; a full page means `hasMore:"unknown"`.
57
57
 
58
58
  New actions manage stores, product updates/publication/status, subscription groups, checkout, merchant subscription cancellation, refund tickets, customer session tokens, notification recipients and content scans. Use `--file input.json`, `--dry-run`, explicit `--yes`, and preferably an explicit `--idempotency-key`. Without a key the CLI generates one and returns it. These actions use ID fields inside the input file, not invented positional arguments. Read each schema before constructing input.
59
59
 
@@ -65,6 +65,8 @@ Production writes require `--yes --confirm-production`. `products publish` and `
65
65
 
66
66
  `graphql query` and `analytics query` accept a JSON file containing `query` and optional `variables`. A real parser rejects mutations, subscriptions and multiple operations before credentials/network, including dry-run. Real execution requires private `--output` because arbitrary aliases/fragments can contain secrets. There is no raw REST passthrough. Group query fields must be confirmed using official documentation/introspection before use; do not invent a group root field. Customer-token-only onetime cancellation, customer subscription cancellation and reactivation are excluded from merchant scope.
67
67
 
68
+ For recurring reads, opt into `graphql query --background` to skip the local operation record for that call. Supply a fresh private `--output` for every execution. Responses are exported only after the gateway verifies the environment, which must match the selection for browser sessions. Authenticated responses include the effective `meta.apiOrigin` and a null `meta.operationId`. When a `RATE_LIMITED` error has `error.details.retryAfterMs`, wait at least that many milliseconds before the next request.
69
+
68
70
  ## Remote changes
69
71
 
70
72
  `products create --type onetime|subscription --file product.json --yes --idempotency-key KEY` creates a real product using the effective credential environment. Review the merchant, store, name and prices before confirming. The CLI requires verified environment evidence before writing and requires explicit production confirmation for Production. Subscription input requires `billingPeriod`; trial prices require positive `metadata.trialDays`. For product creation or updates, do not supply `taxIncluded`: the backend fixes tax-exclusive pricing and this CLI rejects that option. Results contain safe product fields; descriptions, metadata and URLs are omitted.
@@ -101,10 +103,12 @@ Use `coupons list|get|create|update|deactivate` and `promotion-codes list|create
101
103
 
102
104
  ## Temporary local listener
103
105
 
104
- Use `pancake listen --store-id STO_example --forward-to http://localhost:3000/webhook [--events event.name] [--live] [--json]` for actual merchant events. Browser session only; Test default even when saved mode is Production; only explicit `--live` enables Production. `listen` is a streaming exception to one-result output: standard NDJSON envelopes with data.type ready/delivery/stopped, plus terminal failure when needed. Never expect event bodies or signatures in output. Forwarding is loopback-only, redirects fail, only 2xx is success. Stable eventId identifies duplicates/retries. SIGINT/SIGTERM stop the session; abrupt termination uses the 90-second TTL. No permanent endpoint mutation or synthetic trigger.
106
+ Use `pancake listen --store-id STO_example --forward-to http://localhost:3000/webhook [--events event.name] [--live] [--json]` for actual merchant events. Browser session only; Test default even when saved mode is Production; only explicit `--live` enables Production. `listen` is a streaming exception to one-result output: standard NDJSON envelopes with data.type ready/delivery/stopped, plus terminal failure when needed. Read `data.signingPublicKey` (PEM) from the protocol 2 ready event. Use that key only for this session's local receiver, including `--live` and resends. Refresh it whenever the listener restarts. Never expect event bodies or signatures in output. Forwarding is loopback-only, redirects fail, only 2xx is success. Stable eventId identifies duplicates/retries. SIGINT/SIGTERM stop the session; abrupt termination uses the 90-second TTL. No permanent endpoint mutation or synthetic trigger.
105
107
 
106
108
  ## Service and verification boundaries
107
109
 
108
- Private service source is not required to use or develop the open-source client. Remote commands require credentials and a reachable compatible hosted API; browser authorization also needs a compatible Dashboard. Browser login, environment headers and listener relay support must be deployed separately from the CLI. The published candidate passed npm/npx installation, production browser login and logout revocation, selected business operations in Test and Production, and Test sandbox-payment forwarding. Production listener startup, polling, isolation and cleanup passed; real Production payment delivery and actual Windows console Ctrl+C remain pending. These checks do not establish acceptance of every command.
110
+ Private service source is not required to use or develop the open-source client. Remote commands require credentials and a reachable compatible hosted API; browser authorization also needs a compatible Dashboard. For listener protocol 2, shift all listener traffic to upgraded Notify first, then deploy Resource, Auth, Dashboard and finally the npm CLI. The published candidate passed npm/npx installation, production browser login and logout revocation, selected business operations in Test and Production, and Test sandbox-payment forwarding. The original signing scheme passed Production listener startup, polling, isolation and cleanup; real Production payment delivery and actual Windows console Ctrl+C remain pending. These checks do not establish acceptance of every command.
109
111
 
110
112
  Browser login grants supported business operations in Test and Production within existing merchant/store permissions. Server policy denies account, API Key, payout/bank, other-device, further authorization and API credential, Webhook `secret` and identity-document access. No `--scope` option is needed. Use `logout` only for the current CLI session. RSA permissions are unchanged. Webhook addresses remain readable. Browser secret writes use server acknowledgement (`verification: response_only`); do not claim the secret was read back.
113
+
114
+ Use `listen history --store-id <store>` for captured metadata and active sessions. `listen show <recordId> --store-id <store>` prints attempts. Add `--output <new-file>` only when the original payload is needed. To enqueue the event for an active listener, use `listen resend <recordId> --store-id <store> --session <uuid> --yes --idempotency-key <uuid>`. Production requires `--live --confirm-production`. The CLI checks protocol 2 support using a read-only history request before enqueueing a replay. If an upgrade is required, update the listener services. Explicit recovery repeats the same command and UUID within 24 hours. Resend preserves eventId for receiver deduplication.
@@ -3,20 +3,8 @@ import { execFile } from 'node:child_process';
3
3
  import { promisify } from 'node:util';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
5
  import pkg from '../../package.json' with { type: 'json' };
6
+ import { serviceOrigin } from "../contracts/action-routes.js";
6
7
  import { CliError } from "../contracts/errors.js";
7
- export function serviceOrigin(value) {
8
- let url;
9
- try {
10
- url = new URL(value);
11
- }
12
- catch {
13
- throw new CliError('INVALID_ARGUMENT', 'Provide a valid API or Dashboard origin.', { exitCode: 2 });
14
- }
15
- if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === '127.0.0.1'))) {
16
- throw new CliError('INVALID_ARGUMENT', 'Service URLs must be HTTPS origins, or explicit http://127.0.0.1:<port> origins for local testing.', { exitCode: 2 });
17
- }
18
- return url.origin;
19
- }
20
8
  async function openBrowser(url) {
21
9
  const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? windowsSystemTool('browser') : 'xdg-open';
22
10
  const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
@@ -3,7 +3,7 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
3
  import { atomicJson, readJson, protectDirectory, withDirectoryLock, exportPrivateFile, hasCode } from "./files.js";
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { lstat, unlink } from 'node:fs/promises';
6
- import { serviceOrigin } from "./browser-login.js";
6
+ import { serviceOrigin } from "../contracts/action-routes.js";
7
7
  import { CliError } from "../contracts/errors.js";
8
8
  export function configDirectory(env = process.env) {
9
9
  if (env.WAFFO_CONFIG_DIR)
@@ -2,6 +2,7 @@ import { randomUUID, createHash } from 'node:crypto';
2
2
  import { readdir, unlink } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { atomicJson, hasCode, readJson, protectDirectory, privateDirectory, withDirectoryLock } from "./files.js";
5
+ import { requireReplayWindow, sameReplayIntent } from "../contracts/listen-replay.js";
5
6
  import { argumentError, CliError } from "../contracts/errors.js";
6
7
  export function inputFingerprint(input) {
7
8
  const canonical = (value) => {
@@ -53,11 +54,23 @@ export class OperationStore {
53
54
  }
54
55
  async list(limit = 20) { return (await this.all()).slice(0, limit); }
55
56
  async begin(input) {
57
+ return this.reserve(input);
58
+ }
59
+ async beginListenReplay(input) {
60
+ return this.reserve(input, true);
61
+ }
62
+ async reserve(input, recoverReplay = false) {
56
63
  await privateDirectory(this.root);
57
64
  return withDirectoryLock(this.directory, async () => {
58
65
  const records = await this.all();
59
66
  if (input.idempotencyKey) {
60
- const existing = records.find(record => record.idempotencyKey === input.idempotencyKey);
67
+ const key = input.idempotencyKey;
68
+ const existing = records.find(record => record.idempotencyKey === key
69
+ || ((recoverReplay || record.command === 'listen.resend') && record.idempotencyKey?.toLowerCase() === key.toLowerCase()));
70
+ if (existing && recoverReplay && sameReplayIntent(existing, input)) {
71
+ requireReplayWindow(existing);
72
+ return existing;
73
+ }
61
74
  if (existing)
62
75
  throw new CliError('OPERATION_EXISTS', 'This idempotency key already has a local operation. It will not be replayed.', { details: { operationId: existing.operationId }, recovery: 'Inspect operations show, then query the remote resource. Do not create a new key to retry an unknown result.' });
63
76
  }
@@ -72,15 +85,60 @@ export class OperationStore {
72
85
  await unlink(join(this.directory, `${record.operationId}.json`));
73
86
  if (retained.length - rotated.length >= 1000)
74
87
  throw new CliError('OPERATION_STORAGE_FULL', 'Operation storage reached 1000 records; unresolved records are retained.', { recovery: 'Export needed diagnostics and resolve pending operations before explicitly archiving local records.' });
75
- const record = { operationRecordVersion: 1, operationId: randomUUID(), ...input, startedAt: new Date().toISOString(), outcome: 'unknown', attempts: [] };
88
+ const record = { operationRecordVersion: 1, operationId: randomUUID(), ...input, startedAt: new Date().toISOString(), outcome: 'unknown', attempts: [], ...(recoverReplay ? { unconfirmedReplaySubmissions: 0 } : {}) };
76
89
  await atomicJson(join(this.directory, `${record.operationId}.json`), record);
77
90
  return record;
78
91
  });
79
92
  }
93
+ async updateListenReplay(id, event) {
94
+ await protectDirectory(this.root);
95
+ return withDirectoryLock(this.directory, async () => {
96
+ const record = await this.readRecord(id);
97
+ if (record.command !== 'listen.resend')
98
+ throw argumentError('A listener replay operation is required.');
99
+ if (event.kind === 'submitting')
100
+ requireReplayWindow(record);
101
+ if (record.outcome === 'completed')
102
+ return record;
103
+ // A retained unknown operation without a counter may already have reached the server.
104
+ const pending = record.unconfirmedReplaySubmissions ?? (record.outcome === 'unknown' ? 1 : 0);
105
+ if (event.kind === 'submitting') {
106
+ record.unconfirmedReplaySubmissions = pending + 1;
107
+ record.outcome = 'unknown';
108
+ delete record.finishedAt;
109
+ if (pending === 0)
110
+ delete record.errorCode;
111
+ }
112
+ else if (event.kind === 'accepted') {
113
+ record.unconfirmedReplaySubmissions = 0;
114
+ record.outcome = 'completed';
115
+ record.resourceId = event.resourceId;
116
+ record.attempts = event.attempts;
117
+ record.finishedAt = new Date().toISOString();
118
+ delete record.errorCode;
119
+ }
120
+ else {
121
+ const outstanding = event.kind === 'rejected' ? pending - 1 : pending;
122
+ if (outstanding < 0)
123
+ throw new CliError('INVALID_CONFIG', 'The replay has no matching local submission.');
124
+ record.unconfirmedReplaySubmissions = outstanding;
125
+ record.outcome = outstanding > 0 ? 'unknown' : 'rejected';
126
+ if (outstanding === 0 || event.kind === 'uncertain') {
127
+ record.attempts = event.attempts;
128
+ record.errorCode = event.errorCode;
129
+ record.finishedAt = new Date().toISOString();
130
+ }
131
+ }
132
+ await atomicJson(join(this.directory, `${id}.json`), record);
133
+ return record;
134
+ });
135
+ }
80
136
  async finish(id, patch) {
81
137
  await protectDirectory(this.root);
82
138
  return withDirectoryLock(this.directory, async () => {
83
139
  const previous = await this.readRecord(id);
140
+ if (previous.command === 'listen.resend')
141
+ throw argumentError('Use the listener replay journal for this operation.');
84
142
  const record = { ...previous, outcome: patch.outcome, finishedAt: new Date().toISOString(), ...(patch.resourceId ? { resourceId: patch.resourceId } : {}), ...(patch.errorCode ? { errorCode: patch.errorCode } : {}), attempts: patch.attempts ?? previous.attempts };
85
143
  await atomicJson(join(this.directory, `${id}.json`), record);
86
144
  return record;
@@ -1,13 +1,15 @@
1
1
  import { createHash, createPrivateKey, randomUUID, sign } from 'node:crypto';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
- import { DEFAULT_API_ORIGIN, productCreateEndpoint, webhookEndpoint } from "../../contracts/action-routes.js";
3
+ import { DEFAULT_API_ORIGIN, productCreateEndpoint, serviceOrigin, webhookEndpoint } from "../../contracts/action-routes.js";
4
4
  import { CliError } from "../../contracts/errors.js";
5
- import { serviceOrigin } from "../browser-login.js";
5
+ import { listenerEndpoint } from "../../contracts/listener-routes.js";
6
6
  import { readPrivateKey } from "../files.js";
7
7
  import { ME_QUERY, PRODUCT_QUERIES, STORES_QUERY, WEBHOOKS_QUERY, WEBHOOK_SECRETS_QUERY } from "./queries.js";
8
8
  import { graphqlValidationError } from "./graphql-errors.js";
9
9
  import { conflictError } from "./conflict-error.js";
10
10
  import { httpErrorReason } from "./http-error-reason.js";
11
+ import { listenerHttpError } from "./listener-http-error.js";
12
+ import { parseRetryAfter } from "./retry-after.js";
11
13
  export function parsePrivateKey(raw) {
12
14
  let value = raw.trim().replace(/\\n/g, '\n');
13
15
  if (!value.startsWith('-----BEGIN'))
@@ -22,12 +24,12 @@ export function parsePrivateKey(raw) {
22
24
  throw new CliError('INVALID_KEY', 'A valid RSA private key in PKCS#8 or PKCS#1 format is required.', { exitCode: 2, stage: 'credentials' });
23
25
  }
24
26
  }
25
- function apiError(status, write, reason, requestId, session = false) {
27
+ function apiError(status, write, reason, requestId, session = false, retryAfterMs) {
26
28
  const codes = { 400: 'INVALID_REQUEST', 401: 'AUTH_FAILED', 403: 'PERMISSION_DENIED', 404: 'NOT_FOUND', 429: 'RATE_LIMITED' };
27
29
  const unknown = write && (status >= 500 || status === 409 || (status >= 200 && status < 300));
28
30
  const message = unknown ? 'The write result is unknown; do not create a new operation to retry it.' : status === 401 && session ? 'Your login was not accepted. Run login again.' : 'The API rejected or could not complete the request.';
29
31
  return new CliError(unknown ? 'OUTCOME_UNKNOWN' : codes[status] ?? 'REMOTE_ERROR', reason ? `${message} Server reason: ${reason}` : message, {
30
- stage: 'api', outcome: unknown ? 'unknown' : 'rejected', details: { status, ...(requestId ? { requestId } : {}) },
32
+ stage: 'api', outcome: unknown ? 'unknown' : 'rejected', details: { status, ...(requestId ? { requestId } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) },
31
33
  recovery: unknown ? 'Inspect the operation record and query the affected resource before taking further action.' : 'Check credentials, store access and command input. Run doctor for connection checks.',
32
34
  });
33
35
  }
@@ -56,8 +58,8 @@ async function responseJson(response, maximumBytes = 2 * 1024 * 1024) {
56
58
  throw new Error('Invalid response');
57
59
  return parsed;
58
60
  }
59
- function requestId(response) {
60
- const value = response.headers.get('x-request-id') ?? response.headers.get('x-context-request-id');
61
+ function requestId(response, listener = false) {
62
+ const value = response.headers.get('x-request-id') ?? (listener ? null : response.headers.get('x-context-request-id'));
61
63
  return value && /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : undefined;
62
64
  }
63
65
  export async function createGateway(credentials, observer, fetchImpl = fetch) {
@@ -68,9 +70,11 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
68
70
  throw new CliError('INVALID_CONFIG', 'Select a valid session environment.', { exitCode: 2 });
69
71
  const raw = credentials.privateKey ?? (credentials.privateKeyFile ? await readPrivateKey(credentials.privateKeyFile) : '');
70
72
  const key = credentials.sessionToken ? undefined : parsePrivateKey(raw);
71
- async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal, singleAttempt = false) {
73
+ async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal, options = {}) {
72
74
  const serialized = JSON.stringify(body);
73
- const write = idempotencyKey !== undefined || singleAttempt;
75
+ const write = idempotencyKey !== undefined || options.singleAttempt === true || (options.listenerAction !== undefined && !['history', 'detail'].includes(options.listenerAction));
76
+ const listenerRequest = options.listenerAction !== undefined || options.listenerIdentity === true;
77
+ const retryRead = !write && !listenerRequest;
74
78
  const deadline = Date.now() + 20000;
75
79
  for (let index = 0;; index++) {
76
80
  const started = Date.now(), timestamp = Math.floor(started / 1000).toString();
@@ -84,7 +88,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
84
88
  try {
85
89
  response = await fetchImpl(`${apiUrl}${path}`, { method: 'POST', headers, body: serialized, redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15000)]) : AbortSignal.timeout(Math.max(1, Math.min(15000, deadline - Date.now()))) });
86
90
  attempt.status = response.status;
87
- attempt.requestId = requestId(response);
91
+ attempt.requestId = requestId(response, listenerRequest);
88
92
  const environment = response.headers.get('x-waffo-environment');
89
93
  if (environment === 'test' || environment === 'prod')
90
94
  attempt.environment = environment;
@@ -98,7 +102,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
98
102
  catch {
99
103
  attempt.durationMs = Date.now() - started;
100
104
  observer(attempt);
101
- if (!signal?.aborted && !write && index < 2 && Date.now() + 100 < deadline) {
105
+ if (!signal?.aborted && retryRead && index < 2 && Date.now() + 100 < deadline) {
102
106
  await delay(50 * (index + 1));
103
107
  continue;
104
108
  }
@@ -111,21 +115,33 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
111
115
  if (!response.ok) {
112
116
  const retryable = response.status === 429 || response.status >= 500;
113
117
  const retryHeader = response.headers.get('retry-after');
114
- const retryMs = retryHeader ? (/^\d+$/.test(retryHeader) ? Number(retryHeader) * 1000 : Math.max(0, Date.parse(retryHeader) - Date.now())) : 100 * (index + 1);
115
- if (!signal?.aborted && !write && retryable && index < 2 && Number.isFinite(retryMs) && Date.now() + retryMs < deadline) {
118
+ const retryAfterMs = retryHeader ? parseRetryAfter(retryHeader) : undefined;
119
+ const retryMs = retryHeader ? retryAfterMs : 100 * (index + 1);
120
+ if (!signal?.aborted && retryRead && retryable && index < 2 && retryMs !== undefined && Date.now() + retryMs < deadline) {
116
121
  await delay(retryMs);
117
122
  continue;
118
123
  }
124
+ if (listenerRequest) {
125
+ const conflict = response.status === 409 && envelope.data === null && Array.isArray(envelope.errors)
126
+ && envelope.errors.some(error => error?.layer === 'notification' && typeof error.message === 'string');
127
+ const failure = conflict
128
+ ? new CliError('CONFLICT', 'The listener request conflicts with the current session or replay ID.', { stage: 'listen', details: { status: 409 } })
129
+ : apiError(response.status, write, undefined, attempt.requestId, Boolean(credentials.sessionToken));
130
+ if (options.listenerAction)
131
+ throw listenerHttpError(options.listenerAction, response, envelope, credentials.environment, failure);
132
+ throw failure;
133
+ }
119
134
  if (response.status === 409) {
120
135
  const conflict = conflictError(envelope, [credentials.sessionToken ?? '', raw, headers['X-Signature'] ?? '']);
121
136
  if (conflict)
122
137
  throw conflict;
123
138
  }
124
139
  const reason = httpErrorReason(response.status, envelope, [credentials.sessionToken ?? '', raw, headers['X-Signature'] ?? '']);
125
- throw apiError(response.status, write, reason, attempt.requestId, Boolean(credentials.sessionToken));
140
+ const retryHint = options.includeRetryAfter && response.status === 429 ? retryAfterMs : undefined;
141
+ throw apiError(response.status, write, reason, attempt.requestId, Boolean(credentials.sessionToken), retryHint);
126
142
  }
127
143
  if (Array.isArray(envelope.errors) && envelope.errors.length > 0) {
128
- if (!write && path === '/v1/graphql' && response.status === 200 && 'query' in body && typeof body.query === 'string') {
144
+ if (!listenerRequest && !write && path === '/v1/graphql' && response.status === 200 && 'query' in body && typeof body.query === 'string') {
129
145
  throw graphqlValidationError(envelope.errors, body.query) ?? apiError(response.status, write);
130
146
  }
131
147
  throw apiError(response.status, write);
@@ -143,7 +159,19 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
143
159
  return { data: envelope.data, environment: attempt.environment };
144
160
  }
145
161
  }
146
- async function query(query, variables = {}) { return (await post('/v1/graphql', { query, variables })).data; }
162
+ const query = async (query, variables = {}, options) => {
163
+ const { data, environment } = await post('/v1/graphql', { query, variables }, undefined, false, undefined, { includeRetryAfter: options?.background });
164
+ if (options?.background) {
165
+ if (!environment)
166
+ throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the credential environment. No result was exported.', { stage: 'api' });
167
+ if (credentials.sessionToken && environment !== credentials.environment) {
168
+ throw new CliError('ENVIRONMENT_MISMATCH', 'The gateway did not confirm the selected environment. No result was exported.', {
169
+ stage: 'api', details: { selectedEnvironment: credentials.environment },
170
+ });
171
+ }
172
+ }
173
+ return data;
174
+ };
147
175
  return {
148
176
  query,
149
177
  async revokeSession() {
@@ -159,7 +187,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
159
187
  if (typeof payload.jti !== 'string' || !/^mer_[A-Za-z0-9_-]{16}$/.test(payload.jti))
160
188
  throw new CliError('INVALID_CONFIG', 'Saved session ID is invalid. Revoke it in Dashboard Security.');
161
189
  try {
162
- const result = await post('/v1/actions/merchant/sign-out-session', { jti: payload.jti }, undefined, false, undefined, true);
190
+ const result = await post('/v1/actions/merchant/sign-out-session', { jti: payload.jti }, undefined, false, undefined, { singleAttempt: true });
163
191
  if (result.data.success !== true)
164
192
  throw new Error('Revocation not confirmed');
165
193
  return true;
@@ -171,13 +199,11 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
171
199
  }
172
200
  },
173
201
  async listen(action, body, signal) {
174
- if (!['start', 'poll', 'ack', 'stop'].includes(action))
175
- throw new CliError('INVALID_ARGUMENT', 'Invalid listener action.', { exitCode: 2 });
176
202
  try {
177
- return (await post(`/v1/actions/notification/cli-listen-${action}`, body, undefined, false, signal, true)).data;
203
+ return (await post(listenerEndpoint(action), body, undefined, false, signal, { listenerAction: action })).data;
178
204
  }
179
205
  catch (error) {
180
- if (error instanceof CliError && error.code === 'OUTCOME_UNKNOWN')
206
+ if (action !== 'replay' && error instanceof CliError && error.code === 'OUTCOME_UNKNOWN')
181
207
  throw new CliError('OUTCOME_UNKNOWN', 'The temporary listener request result is unknown.', { stage: 'listen', outcome: 'unknown', recovery: 'The CLI attempts session cleanup when the session ID is known. Otherwise the session expires within 90 seconds without polling.' });
182
208
  throw error;
183
209
  }
@@ -187,8 +213,8 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
187
213
  throw new CliError('INVALID_ARGUMENT', 'Invalid action endpoint.', { exitCode: 2 });
188
214
  return (await post(path, body, key, acknowledgementOnly)).data;
189
215
  },
190
- async me(signal) {
191
- const { data, environment } = await post('/v1/graphql', { query: ME_QUERY, variables: {} }, undefined, false, signal);
216
+ async me(signal, options) {
217
+ const { data, environment } = await post('/v1/graphql', { query: ME_QUERY, variables: {} }, undefined, false, signal, { listenerIdentity: options?.listener });
192
218
  const me = data.me;
193
219
  if (!me || me.id !== credentials.merchantId)
194
220
  throw new CliError('AUTH_FAILED', 'The authenticated merchant could not be verified.', { stage: 'identity' });
@@ -0,0 +1,43 @@
1
+ import { CliError } from "../../contracts/errors.js";
2
+ import { listenerUpgradeCode, listenerUpgradeRequired } from "../../contracts/listener-protocol.js";
3
+ import { ConfirmedReplayRejection } from "../../contracts/listen-replay.js";
4
+ const gatewayDenials = new Map([
5
+ [401, 'The gateway did not accept your login. Run pancake login again.'],
6
+ [403, 'The gateway denied access to this listener. Check your store permissions.'],
7
+ [429, 'The gateway rate limit was reached. Wait before resending.'],
8
+ ]);
9
+ function listenerDenial(envelope) {
10
+ if (envelope.data !== null || !Array.isArray(envelope.errors) || envelope.errors.length !== 1)
11
+ return;
12
+ const [error] = envelope.errors;
13
+ if (!error || typeof error.message !== 'string' || !error.message.trim())
14
+ return;
15
+ if (error.layer === 'gateway' || error.layer === 'notification')
16
+ return { layer: error.layer, message: error.message, code: error.code };
17
+ }
18
+ export function listenerHttpError(action, response, envelope, selectedEnvironment, failure) {
19
+ const contentType = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
20
+ const denial = contentType === 'application/json' ? listenerDenial(envelope) : undefined;
21
+ const layer = denial?.layer;
22
+ const responseEnvironment = response.headers.get('x-waffo-environment');
23
+ const verified = selectedEnvironment !== undefined && responseEnvironment === selectedEnvironment;
24
+ // The gateway emits this exact envelope before selecting an environment or proxying a missing route.
25
+ if (response.status === 404 && responseEnvironment === null && denial?.layer === 'gateway' && denial.message === 'Route not found') {
26
+ const upgrade = listenerUpgradeRequired();
27
+ return action === 'replay' ? new ConfirmedReplayRejection(upgrade.code, upgrade.message, upgrade) : upgrade;
28
+ }
29
+ if (verified && response.status === 503 && denial?.layer === 'notification' && denial.code === listenerUpgradeCode) {
30
+ // A mixed deployment can discover an incompatible reply after forwarding a write.
31
+ return listenerUpgradeRequired();
32
+ }
33
+ if (action !== 'replay')
34
+ return failure;
35
+ // Authentication, store authorization and rate limiting can deny a request before routing to its environment.
36
+ const gatewayMessage = layer === 'gateway' ? gatewayDenials.get(response.status) : undefined;
37
+ const preProxyDenial = responseEnvironment === null && gatewayMessage !== undefined;
38
+ const supportedStatus = [400, 401, 403, 409, 413, 429].includes(response.status) || (response.status === 404 && layer === 'notification');
39
+ if (supportedStatus && layer && (verified || preProxyDenial) && failure.outcome === 'rejected') {
40
+ return new ConfirmedReplayRejection(failure.code, gatewayMessage ?? failure.message, failure);
41
+ }
42
+ return new CliError('OUTCOME_UNKNOWN', 'Listener replay admission could not be confirmed.', { stage: 'listen', outcome: 'unknown' });
43
+ }
@@ -0,0 +1,46 @@
1
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
2
+ const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
3
+ const imfFixdate = /^(?<weekday>[A-Z][a-z]{2}), (?<day>\d{2}) (?<month>[A-Z][a-z]{2}) (?<year>\d{4}) (?<time>\d{2}:\d{2}:\d{2}) GMT$/;
4
+ const rfc850Date = /^(?<weekday>[A-Z][a-z]{5,8}), (?<day>\d{2})-(?<month>[A-Z][a-z]{2})-(?<year>\d{2}) (?<time>\d{2}:\d{2}:\d{2}) GMT$/;
5
+ const asctimeDate = /^(?<weekday>[A-Z][a-z]{2}) (?<month>[A-Z][a-z]{2}) (?<day>\d{2}| \d) (?<time>\d{2}:\d{2}:\d{2}) (?<year>\d{4})$/;
6
+ function httpDate(value, now) {
7
+ const parts = imfFixdate.exec(value)?.groups ?? rfc850Date.exec(value)?.groups ?? asctimeDate.exec(value)?.groups;
8
+ if (!parts)
9
+ return;
10
+ const month = months.indexOf(parts.month) + 1;
11
+ if (!month)
12
+ return;
13
+ const leapSecond = parts.time === '23:59:60';
14
+ const time = leapSecond ? '23:59:59' : parts.time;
15
+ const dateAndTime = `${String(month).padStart(2, '0')}-${parts.day.trimStart().padStart(2, '0')}T${time}`;
16
+ const shortYear = parts.year.length === 2;
17
+ let year = Number(parts.year);
18
+ if (shortYear) {
19
+ // Resolve the latest matching year no more than 50 years in the future.
20
+ const limit = new Date(now);
21
+ limit.setUTCFullYear(limit.getUTCFullYear() + 50);
22
+ year += Math.floor(limit.getUTCFullYear() / 100) * 100;
23
+ const candidate = new Date(`${year}-${dateAndTime}Z`).getTime();
24
+ if (candidate + (leapSecond ? 1000 : 0) > limit.getTime())
25
+ year -= 100;
26
+ }
27
+ if (year < 1900)
28
+ return;
29
+ const normalized = `${String(year).padStart(4, '0')}-${dateAndTime}`;
30
+ const date = new Date(`${normalized}Z`);
31
+ if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 19) !== normalized)
32
+ return;
33
+ const weekday = weekdays[date.getUTCDay()];
34
+ if (parts.weekday !== (shortYear ? weekday : weekday.slice(0, 3)))
35
+ return;
36
+ return date.getTime() + (leapSecond ? 1000 : 0);
37
+ }
38
+ /** Parse RFC 9110 delay-seconds and HTTP-date without permissive date coercion. */
39
+ export function parseRetryAfter(value, now = Date.now()) {
40
+ if (/^\d+$/.test(value)) {
41
+ const milliseconds = Number(value) * 1000;
42
+ return Number.isSafeInteger(milliseconds) ? milliseconds : undefined;
43
+ }
44
+ const timestamp = httpDate(value, now);
45
+ return timestamp === undefined ? undefined : Math.max(0, timestamp - now);
46
+ }
@@ -28,7 +28,7 @@ export async function executeApiRead(spec, request, options, services) {
28
28
  const output = options.output ? await services.prepareOutput(options.output) : undefined;
29
29
  try {
30
30
  return await readOperation(spec.definition.id, options, services, async (gateway) => {
31
- const response = await gateway.query(request.query, request.variables);
31
+ const response = await gateway.query(request.query, request.variables, spec.definition.id === 'graphql.query' && options.background ? { background: true } : undefined);
32
32
  if (output) {
33
33
  await output.commit(`${JSON.stringify(response, null, 2)}\n`);
34
34
  return { output: options.output, exported: true };
@@ -6,7 +6,8 @@ export function diagnosticRecord(record) {
6
6
  command: record.command, impact: record.impact, cliVersion: record.cliVersion, startedAt: record.startedAt,
7
7
  finishedAt: record.finishedAt, outcome: record.outcome, merchantId: record.merchantId,
8
8
  storeId: record.storeId, inputHash: record.inputHash, idempotencyKey: record.idempotencyKey,
9
- targetResourceId: record.targetResourceId, endpoint: record.endpoint, apiOrigin: record.apiOrigin, selectedEnvironment: record.selectedEnvironment,
9
+ targetResourceId: record.targetResourceId, targetSessionId: record.targetSessionId, endpoint: record.endpoint, apiOrigin: record.apiOrigin, selectedEnvironment: record.selectedEnvironment,
10
+ ...(record.unconfirmedReplaySubmissions === undefined ? {} : { unconfirmedReplaySubmissions: record.unconfirmedReplaySubmissions }),
10
11
  resourceId: record.resourceId, errorCode: record.errorCode,
11
12
  attempts: record.attempts.map(attempt => ({ attemptId: attempt.attemptId, endpoint: attempt.endpoint, durationMs: attempt.durationMs, status: attempt.status, requestId: attempt.requestId, environment: attempt.environment })),
12
13
  };