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

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.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.1-rc.2
4
+
5
+ Release candidate for npm’s `next` channel. No stable release.
6
+
7
+ - Record full write intent, including product-create endpoint and API origin, before sending a business request; retain known result IDs when verification, private export or record completion fails. Unknown writes are never replayed.
8
+ - Preserve confirmed-rejection exit codes across product, webhook and API actions; unknown outcomes remain `OUTCOME_UNKNOWN` with exit 1.
9
+ - Correct action target/result identities, including checkout sessions and promotion-code batches; exclude tokens and content request IDs from resource IDs.
10
+ - Show discount terms, scope, limits and batch settings in offline previews while keeping nested customer email restrictions redacted.
11
+ - Return `CONFIG_CHANGED` for concurrent login/logout/environment changes and preserve newer saved configuration, including during invalid-config recovery.
12
+
13
+ - Refresh installation and acceptance documentation, including manual candidate publication and the remaining stable-release gates.
14
+
3
15
  ## 0.0.1-rc.1
4
16
 
5
- Release candidate for UAT acceptance on npm's `next` channel. Production service availability and acceptance are separate from this package release.
17
+ Published on 2026-11-17 to npm's `next` channel. Production service deployment and acceptance are separate from package publication.
6
18
 
7
19
  ### Added
8
20
 
@@ -33,5 +45,5 @@ Release candidate for UAT acceptance on npm's `next` channel. Production service
33
45
  ### Release requirements
34
46
 
35
47
  - Browser authorization, verified environment headers and webhook listening require separately deployed compatible services.
36
- - Production integration acceptance and actual Windows console Ctrl+C acceptance remain release gates.
37
- - npm publication and registry-to-Homebrew delivery have not yet been verified by a public release.
48
+ - Follow-up acceptance verified production login and logout revocation, selected Test/Production business operations, Test sandbox-payment forwarding, and Production listener startup, polling and cleanup. Real Production payment delivery and actual Windows console Ctrl+C remain pending.
49
+ - Published npm/npx installation passed. Registry-to-Homebrew delivery remains pending the first stable release.
package/README.md CHANGED
@@ -2,11 +2,11 @@
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
- **Status: 0.0.1-rc.1 release candidate.** 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.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.
6
6
 
7
7
  ## Try locally without publishing
8
8
 
9
- Install the project's pinned package manager once: `npm install -g pnpm@11.25.0`. Use pnpm for repository development; the published CLI can still be installed with npm, npx or Homebrew.
9
+ Install the project's pinned package manager once: `npm install -g pnpm@11.25.0`. Use pnpm for repository development; the published candidate can be installed with npm or npx. Homebrew installation becomes available after the first stable release.
10
10
 
11
11
  ```sh
12
12
  pnpm install --frozen-lockfile
@@ -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.1/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.1/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.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.
24
24
 
25
- Documentation links serve the published npm package through jsDelivr and become available after this version is published; no GitHub access is needed. 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
+ 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
 
@@ -55,7 +55,7 @@ Automation can inject `WAFFO_MERCHANT_ID` plus exactly one of `WAFFO_PRIVATE_KEY
55
55
 
56
56
  The backend determines test or production from the matching RSA key. The CLI reads `X-Waffo-Environment: test|prod` from the authenticated gateway response, records it per request, and shows `Environment: Test` or `Environment: Production`. Login and whoami expose the same evidence; doctor passes the environment check only when verified. RSA environments cannot be selected locally. Browser sessions send the chosen `X-Environment`; only the authenticated response header verifies it.
57
57
 
58
- **Deployment dependency:** Browser login requires the Dashboard authorization page, user-service device authorization endpoints and gateway routes/header changes. They must be deployed separately from the CLI; production availability has not been verified. Until the gateway returns the header, results remain `Environment: Unknown (unverified)` and doctor reports the missing evidence. Missing or invalid headers never reuse an older request's environment. JSON keeps `meta.actualEnvironment` and `meta.environmentVerified`; a verified merchant identity alone does not verify its environment.
58
+ **Deployment dependency:** Browser login requires the Dashboard authorization page, user-service device authorization endpoints and gateway routes/header changes. They are deployed separately from the CLI. Production browser login, environment verification and listener connections were verified with the published candidate on 2026-11-17; live payment delivery remains pending. Until the gateway returns the header, results remain `Environment: Unknown (unverified)` and doctor reports the missing evidence. Missing or invalid headers never reuse an older request's environment. JSON keeps `meta.actualEnvironment` and `meta.environmentVerified`; a verified merchant identity alone does not verify its environment.
59
59
 
60
60
  Writes require `--yes` and a verified environment. Production writes and Test→Production publication also require `--confirm-production`. Store and notification-recipient changes affect shared Test/Production resources and require `--confirm-shared`; when executed in Production, both flags are required. These confirmations do not change server permissions or require another browser login. Unknown outcomes are never automatically retried. Webhook writes remain Test-only.
61
61
 
@@ -69,24 +69,35 @@ pnpm cli products create --type onetime --file product.json --yes --idempotency-
69
69
 
70
70
  This performs a real write and may affect production. Subscription input also needs `billingPeriod`. Every write requires a durable local intent and is attempted once; keep its operation ID and idempotency key. If the result is unknown or verification is pending, inspect the operation and query the product (or find it in the merchant dashboard if no ID was returned). Never repeat creation to recover a missing response. Product creation results omit metadata, descriptions and URLs; warnings go to stderr while stdout retains one JSON envelope.
71
71
 
72
+ Write intents record the merchant, input fingerprint, impact, API origin and exact endpoint before the business request; known targets and browser-selected environments are included when available. RSA credentials have no local environment selection. Checkout records distinguish the product target (`targetResourceId`) from the returned session (`resourceId`); promotion-code batches use `batchId` as their result ID. Session tokens and content-check request IDs are not resource IDs. Accepted changes retain their returned resource ID in recovery errors if verification, private export or record completion fails. If local record updates remain unavailable, the original intent stays available for investigation. Confirmed rejections preserve their original exit code, including 2 for input/authentication restrictions; unknown outcomes use `OUTCOME_UNKNOWN` and exit 1.
73
+
72
74
  The expanded action commands use `--file input.json`, require `--yes`, and support `--idempotency-key`. Use `schema <command.id>` and `--dry-run` before execution. `products publish` and `groups publish` explicitly copy test data to production. New actions report `response_only` verification, or `acknowledgement_only` for group deletion/publication; they do not claim a resource read-back. Product creation and test-webhook configuration retain read-back verification. Browser login can read Webhook addresses but cannot read `secret`. Secret changes use server acknowledgement (`verification: response_only`), without a secret read-back or an extra Dashboard step.
73
75
 
74
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.
75
77
 
76
- 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.
78
+ 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.
77
79
 
78
80
  ## Install the release candidate
79
81
 
80
- The candidate uses npm's `next` channel. These commands require the package to have been published; preparing this repository does not publish it.
82
+ Version `0.0.1-rc.2` uses npm's `next` channel. Use the explicit channel or version while evaluating the candidate:
81
83
 
82
84
  ```sh
83
85
  npm install -g @waffo/pancake-cli@next
84
86
  pancake --version
85
87
  # Or run the exact candidate without a global installation:
86
- npx @waffo/pancake-cli@0.0.1-rc.1 --help
88
+ npx @waffo/pancake-cli@0.0.1-rc.2 --help
89
+ ```
90
+
91
+ For the hosted service, no URL overrides are needed:
92
+
93
+ ```sh
94
+ pancake login
95
+ pancake whoami
96
+ pancake env test
97
+ pancake stores list
87
98
  ```
88
99
 
89
- For UAT acceptance, get the UAT Dashboard and API origins from your team and pass both explicitly. The selected API origin is saved for later commands.
100
+ For UAT acceptance only, get both origins from your team. The selected API origin is saved for later commands.
90
101
 
91
102
  ```sh
92
103
  pancake login --dashboard-url <uat-dashboard-origin> --api-url <uat-api-origin>
@@ -95,7 +106,7 @@ pancake env test
95
106
  pancake stores list
96
107
  ```
97
108
 
98
- Check the merchant and environment before business operations. Default URLs target production; npm installation does not deploy the hosted services. Production browser login and listening require separate deployment and acceptance. Automated Windows package checks pass; a real Windows console Ctrl+C listener walkthrough remains pending.
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.
99
110
 
100
111
  To update within the candidate channel, run `npm install -g @waffo/pancake-cli@next`. Stable Homebrew does not install prereleases.
101
112
 
@@ -164,13 +175,14 @@ Package smoke tests install the actual tarball in isolated directories and exerc
164
175
  ## CI/CD
165
176
 
166
177
  - PR/main: type checking, tests, build, audit, archive allowlist and npx/global installation on macOS/Linux/Windows with Node 22 and 24, plus installation checks on the minimum runtime, Node 22.14.0.
167
- - Version tags: validate tag/version/changelog and main ancestry, rerun checks, publish the tested archive via npm OIDC, verify registry integrity, create a GitHub release with the same archive/checksum.
178
+ - Manual candidate releases: publish the reviewed and tested archive from main with maintainer authentication and 2FA; verify registry integrity and npm/npx installation.
179
+ - Optional version-tag workflow: validate tag/version/changelog and main ancestry, rerun checks, publish the tested archive via npm OIDC, verify registry integrity, create a GitHub release with the same archive/checksum.
168
180
  - 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.
169
181
  - Weekly Dependabot updates cover dependencies and pinned Actions.
170
182
 
171
- See the [agent reference](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.1/SKILL.md) and [changelog](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.1/CHANGELOG.md). Maintainer release instructions are in `docs/release/README.md` in the source repository and require repository access.
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.
172
184
 
173
- Internal planning documents are maintained outside the source repository. Candidate publication is enabled; publishing still requires npm permissions and passing release checks. Local tests use simulated API responses. Browser-login, product, discount and paid-event listener flows also have shared UAT Test-environment evidence. This does not establish production acceptance. Windows console Ctrl+C, production deployment and first registry installation remain separate acceptance items.
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.
174
186
 
175
187
  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.
176
188
 
@@ -199,9 +211,9 @@ Overrides accept HTTPS, or HTTP on `127.0.0.1` only. No URL credentials, paths,
199
211
 
200
212
  ## Contributing and security
201
213
 
202
- See [CONTRIBUTING.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.1/CONTRIBUTING.md) for development and validation, and [SECURITY.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.1/SECURITY.md) for handling credentials and reporting vulnerabilities. Licensed under [MIT](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.1/LICENSE).
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).
203
215
 
204
- Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). See the Discounts section in the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.1/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. This does not establish production or full CLI release acceptance.
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.
205
217
 
206
218
  ## Listen to merchant events locally
207
219
 
@@ -216,4 +228,4 @@ The CLI preserves the exact event body and existing webhook signature, forwards
216
228
 
217
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.
218
230
 
219
- 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. Production listening has not been acceptance-tested.
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.
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.1`, on the `next` channel once published. Install with `npm install -g @waffo/pancake-cli@next`, or use `npx @waffo/pancake-cli@0.0.1-rc.1`. 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.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.
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
 
@@ -17,7 +17,7 @@ pnpm cli schema webhook.add --json
17
17
  pnpm cli webhook add --help
18
18
  ```
19
19
 
20
- Local examples use `pnpm cli`; the executable is named `pancake` after publication. The official TypeScript compiler emits a complete ESM module tree in `dist/`; `pnpm cli` runs `node dist/index.js`. Commander handles commands, arguments and help. `pnpm dev` watches and recompiles; run commands in a second terminal after compilation succeeds. After renaming or deleting source files, restart `pnpm dev` or run `pnpm run build` to remove old output. `pnpm run pack:release` starts with a clean build. Do not invent commands from the roadmap. Temporary local webhook listening is implemented for browser sessions; simulated event sending and MCP are not implemented. `products create` supports offline preview and real onetime/subscription creation with `--yes`.
20
+ Local examples use `pnpm cli`; the installed executable is named `pancake`. The official TypeScript compiler emits a complete ESM module tree in `dist/`; `pnpm cli` runs `node dist/index.js`. Commander handles commands, arguments and help. `pnpm dev` watches and recompiles; run commands in a second terminal after compilation succeeds. After renaming or deleting source files, restart `pnpm dev` or run `pnpm run build` to remove old output. `pnpm run pack:release` starts with a clean build. Do not invent commands from the roadmap. Temporary local webhook listening is implemented for browser sessions; simulated event sending and MCP are not implemented. `products create` supports offline preview and real onetime/subscription creation with `--yes`.
21
21
 
22
22
  ## Authentication
23
23
 
@@ -71,11 +71,13 @@ Production writes require `--yes --confirm-production`. `products publish` and `
71
71
 
72
72
  `webhook add/update/remove` also perform remote changes. Add requires `testMode:true`. Update/remove require an accessible existing test webhook in the selected store. Channel and test mode cannot be updated. Listing shows Webhook addresses and omits secrets. Configuring a webhook does not verify event delivery.
73
73
 
74
- Use a reviewed input and `--yes`; this confirms intent without bypassing checks. Preserve the operation ID and idempotency key. A write is attempted once, with a persisted local intent before sending. Reusing a locally recorded key is blocked; this is not a distributed or permanent deduplication guarantee.
74
+ Use a reviewed input and `--yes`; this confirms intent without bypassing checks. Preserve the operation ID and idempotency key. A write is attempted once, with a persisted local intent before sending. Reusing a locally recorded key is blocked; this is not a distributed or permanent deduplication guarantee. Before the business request, the intent includes merchant, input fingerprint, impact, exact endpoint and API origin, plus known target/store IDs and the selected environment for browser credentials. RSA credentials do not have a local environment selection.
75
75
 
76
76
  ## Results and recovery
77
77
 
78
- `--json` and non-TTY output produce one JSON object on stdout (except `listen`, which streams NDJSON): `schemaVersion`, `ok`, `data`, `error`, `meta`. Logs go to stderr. Non-interactive calls never prompt. Exit codes: 0 success; 1 execution/verification failure; 2 invalid input/configuration; 130 interruption. Always check `ok` and `meta.outcome`. Authenticated success and error metadata includes `merchantId`, `source`, `actualEnvironment` (`test`, `prod` or `null`) and `environmentVerified`; human output also shows this context and available operation/request IDs. A selected environment alone is not verified evidence.
78
+ `--json` and non-TTY output produce one JSON object on stdout (except `listen`, which streams NDJSON): `schemaVersion`, `ok`, `data`, `error`, `meta`. Logs go to stderr. Non-interactive calls never prompt. Exit codes: 0 success; 1 execution/verification failure; 2 invalid input/configuration; 130 interruption. Always check `ok` and `meta.outcome`. Authenticated success and error metadata includes `merchantId`, `source`, `actualEnvironment` (`test`, `prod` or `null`) and `environmentVerified`; human output also shows this context and available operation/request IDs. A selected environment alone is not verified evidence. Confirmed write rejections preserve their original exit code; unknown write outcomes always use `OUTCOME_UNKNOWN` and exit 1. `CONFIG_CHANGED` means a concurrent login, environment selection or logout found replaced/cleared configuration and preserved the newer state; inspect `whoami` before making another change.
79
+
80
+ Checkout `targetResourceId` identifies the product; its `resourceId` identifies the returned session. Promotion-code batch results use `batchId`; session tokens and content-check request IDs are never resource IDs. Accepted-write recovery errors retain a known result ID even when private export or record completion fails. If record updates remain unavailable, inspect the retained initial intent and merchant dashboard.
79
81
 
80
82
  - `completed`: the command finished; a dry-run still has `data.executed:false`.
81
83
  - `rejected`: the requested operation was not completed; inspect the error.
@@ -91,11 +93,11 @@ pnpm cli doctor --debug --json
91
93
 
92
94
  Diagnostics are local, redacted and never automatically uploaded. Ask before sharing them with another party. No request ID from the server means `requestId:null`; local operation IDs are not server audit IDs. Records are capped at 1000; resolved records older than 30 days are pruned on the next operation. Unresolved records are retained.
93
95
 
94
- After publication use a fixed actual version, such as `npx @waffo/pancake-cli@VERSION ...`. Update via the original package manager outside active tasks; do not mutate the running CLI or overwrite unknown config/record versions.
96
+ For repeatable automation use a fixed published version, such as `npx @waffo/pancake-cli@VERSION ...`. Update via the original package manager outside active tasks; do not mutate the running CLI or overwrite unknown config/record versions.
95
97
 
96
98
  ## Discounts
97
99
 
98
- Use `coupons list|get|create|update|deactivate` and `promotion-codes list|create|generate|deactivate`. Coupon lists require storeId; promotion-code lists require couponId in a JSON file. Coupon update changes only name; deactivation is permanent. Generate accepts 1–500 codes. Schema and dry-run validate offline; execute writes with --yes and an explicit idempotency key. Browser sessions and RSA keys are accepted by gateway source with server-enforced store permissions. Results expose codes and IDs, omit customer restrictions from write summaries, and omit customerEmails from named reads. Use private --output on writes or an explicit arbitrary GraphQL query to export sensitive details. All nine discount commands have isolated Test-environment acceptance evidence, including deactivation read-back; production and full CLI acceptance remain unverified.
100
+ Use `coupons list|get|create|update|deactivate` and `promotion-codes list|create|generate|deactivate`. Coupon lists require storeId; promotion-code lists require couponId in a JSON file. Coupon update changes only name; deactivation is permanent. Generate accepts 1–500 codes. Schema and dry-run validate offline. Discount previews show amounts/percentages, duration, product scope, limits, couponId and batch count/length; customerEmails stay redacted in nested promotion codes too. Execute writes with --yes and an explicit idempotency key. Browser sessions and RSA keys are accepted by gateway source with server-enforced store permissions. Results expose codes and IDs, omit customer restrictions from write summaries, and omit customerEmails from named reads. Use private --output on writes or an explicit arbitrary GraphQL query to export sensitive details. All nine discount commands have isolated Test-environment acceptance evidence, including deactivation read-back; selected Production discount operations also passed, while full stable-release acceptance remains pending.
99
101
 
100
102
  ## Temporary local listener
101
103
 
@@ -103,6 +105,6 @@ Use `pancake listen --store-id STO_example --forward-to http://localhost:3000/we
103
105
 
104
106
  ## Service and verification boundaries
105
107
 
106
- 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. Selected flows have isolated Test-environment evidence; local simulated tests and those flows do not establish full CLI or production acceptance. Production dependencies, hosted cross-platform checks and first publication remain separate gates.
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.
107
109
 
108
110
  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.
@@ -27,6 +27,25 @@ function unsupportedVersion(legacy) {
27
27
  exitCode: 2, recovery: legacy ? 'Run pancake logout to clear the legacy configuration, then pancake login with your existing key file.' : 'Use a CLI version that supports this configuration.',
28
28
  });
29
29
  }
30
+ function parseConfig(raw) {
31
+ if (raw === undefined)
32
+ return { configVersion: 2 };
33
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
34
+ throw new CliError('INVALID_CONFIG', 'Invalid local configuration.', { exitCode: 2, recovery: 'Run pancake logout, then pancake login.' });
35
+ const config = raw;
36
+ if (config.configVersion !== 2)
37
+ throw unsupportedVersion(Number(config.configVersion) === 1);
38
+ if (config.credential !== undefined)
39
+ checkCredential(config.credential);
40
+ return { configVersion: 2, ...(config.revision ? { revision: config.revision } : {}), ...(config.credential ? { credential: config.credential } : {}) };
41
+ }
42
+ function configChanged() {
43
+ return new CliError('CONFIG_CHANGED', 'Your saved login changed during this command. Run the command again.', { stage: 'credentials' });
44
+ }
45
+ function protectFutureVersion(raw) {
46
+ if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion !== 1 && raw.configVersion !== 2)
47
+ throw unsupportedVersion(false);
48
+ }
30
49
  export class ConfigStore {
31
50
  directory;
32
51
  constructor(directory) { this.directory = directory; }
@@ -52,22 +71,13 @@ export class ConfigStore {
52
71
  }
53
72
  async read() {
54
73
  await protectDirectory(this.directory);
55
- const raw = await readJson(join(this.directory, 'config.json'));
56
- if (raw === undefined)
57
- return { configVersion: 2 };
58
- if (!raw || typeof raw !== 'object' || Array.isArray(raw))
59
- throw new CliError('INVALID_CONFIG', 'Invalid local configuration.', { exitCode: 2, recovery: 'Run pancake logout, then pancake login.' });
60
- if (raw.configVersion !== 2)
61
- throw unsupportedVersion(Number(raw.configVersion) === 1);
62
- if (raw.credential !== undefined)
63
- checkCredential(raw.credential);
64
- return { configVersion: 2, ...(raw.revision ? { revision: raw.revision } : {}), ...(raw.credential ? { credential: raw.credential } : {}) };
74
+ return parseConfig(await readJson(join(this.directory, 'config.json')));
65
75
  }
66
- async save(credential, signal, expected) {
76
+ async save(credential, expected, signal) {
67
77
  await withDirectoryLock(this.directory, async () => {
68
78
  const snapshot = await this.read();
69
- if (expected && snapshot.revision !== expected.revision)
70
- throw new CliError('CONFIG_CHANGED', 'Your saved login changed during this command. Run the command again.', { stage: 'credentials' });
79
+ if (snapshot.revision !== expected.revision)
80
+ throw configChanged();
71
81
  const previous = snapshot.credential;
72
82
  if (signal?.aborted)
73
83
  throw new CliError('INTERRUPTED', 'Cancelled.', { exitCode: 130 });
@@ -94,10 +104,39 @@ export class ConfigStore {
94
104
  await this.removeManagedKey(previous, 'saved');
95
105
  });
96
106
  }
107
+ async persistClearedConfig(raw) {
108
+ await atomicJson(join(this.directory, 'config.json'), { configVersion: 2, revision: randomUUID() });
109
+ if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion === 2 && 'credential' in raw)
110
+ await this.removeManagedKey(raw.credential, 'cleared');
111
+ }
97
112
  async clear(expected) {
98
113
  await withDirectoryLock(this.directory, async () => {
99
- if (expected && (await this.read()).revision !== expected.revision)
100
- throw new CliError('CONFIG_CHANGED', 'Your saved login changed during logout. The newer login was preserved.');
114
+ let raw;
115
+ try {
116
+ raw = await readJson(join(this.directory, 'config.json'));
117
+ }
118
+ catch (error) {
119
+ if (error instanceof CliError && error.code === 'INVALID_CONFIG')
120
+ throw configChanged();
121
+ throw error;
122
+ }
123
+ protectFutureVersion(raw);
124
+ let snapshot;
125
+ try {
126
+ snapshot = parseConfig(raw);
127
+ }
128
+ catch (error) {
129
+ if (error instanceof CliError && ['INVALID_CONFIG', 'CONFIG_VERSION_UNSUPPORTED'].includes(error.code))
130
+ throw configChanged();
131
+ throw error;
132
+ }
133
+ if (snapshot.revision !== expected.revision)
134
+ throw configChanged();
135
+ await this.persistClearedConfig(raw);
136
+ });
137
+ }
138
+ async clearInvalid() {
139
+ await withDirectoryLock(this.directory, async () => {
101
140
  let raw;
102
141
  try {
103
142
  raw = await readJson(join(this.directory, 'config.json'));
@@ -105,12 +144,20 @@ export class ConfigStore {
105
144
  catch (error) {
106
145
  if (!(error instanceof CliError) || error.code !== 'INVALID_CONFIG')
107
146
  throw error;
147
+ await this.persistClearedConfig(undefined);
148
+ return;
149
+ }
150
+ protectFutureVersion(raw);
151
+ try {
152
+ parseConfig(raw);
153
+ }
154
+ catch (error) {
155
+ if (!(error instanceof CliError) || !['INVALID_CONFIG', 'CONFIG_VERSION_UNSUPPORTED'].includes(error.code))
156
+ throw error;
157
+ await this.persistClearedConfig(raw);
158
+ return;
108
159
  }
109
- if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion !== 1 && raw.configVersion !== 2)
110
- throw unsupportedVersion(false);
111
- await atomicJson(join(this.directory, 'config.json'), { configVersion: 2, revision: randomUUID() });
112
- if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion === 2 && 'credential' in raw)
113
- await this.removeManagedKey(raw.credential, 'cleared');
160
+ throw configChanged();
114
161
  });
115
162
  }
116
163
  }
@@ -1,5 +1,6 @@
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
4
  import { CliError } from "../../contracts/errors.js";
4
5
  import { serviceOrigin } from "../browser-login.js";
5
6
  import { readPrivateKey } from "../files.js";
@@ -62,7 +63,7 @@ function requestId(response) {
62
63
  export async function createGateway(credentials, observer, fetchImpl = fetch) {
63
64
  if (!/^MER_[A-Za-z0-9]+$/.test(credentials.merchantId))
64
65
  throw new CliError('INVALID_CONFIG', 'Invalid Merchant ID.', { exitCode: 2 });
65
- const apiUrl = serviceOrigin(credentials.apiUrl ?? 'https://api.waffo.ai');
66
+ const apiUrl = serviceOrigin(credentials.apiUrl ?? DEFAULT_API_ORIGIN);
66
67
  if (credentials.sessionToken && !['test', 'prod'].includes(credentials.environment ?? ''))
67
68
  throw new CliError('INVALID_CONFIG', 'Select a valid session environment.', { exitCode: 2 });
68
69
  const raw = credentials.privateKey ?? (credentials.privateKeyFile ? await readPrivateKey(credentials.privateKeyFile) : '');
@@ -184,10 +185,6 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
184
185
  async action(path, body, key, acknowledgementOnly = false) {
185
186
  if (!/^\/v1\/actions\/[a-z-]+\/[a-z-]+$/.test(path))
186
187
  throw new CliError('INVALID_ARGUMENT', 'Invalid action endpoint.', { exitCode: 2 });
187
- if (credentials.sessionToken && path === '/v1/actions/auth/issue-session-token')
188
- throw new CliError('AUTH_METHOD_UNSUPPORTED', 'sessions create requires RSA API-key login; browser login cannot issue customer session tokens.', {
189
- exitCode: 2, stage: 'credentials', recovery: 'Run login --key-login with a merchant RSA API key, then run sessions create again.',
190
- });
191
188
  return (await post(path, body, key, acknowledgementOnly)).data;
192
189
  },
193
190
  async me(signal) {
@@ -212,7 +209,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
212
209
  return data.product;
213
210
  },
214
211
  async createProduct(type, body, idempotencyKey) {
215
- const { data } = await post(`/v1/actions/${type}-product/create-product`, body, idempotencyKey);
212
+ const { data } = await post(productCreateEndpoint(type), body, idempotencyKey);
216
213
  const product = data.product;
217
214
  if (!product || typeof product !== 'object' || Array.isArray(product) || typeof product.id !== 'string' || !/^PROD_[A-Za-z0-9]+$/.test(product.id))
218
215
  throw apiError(200, true);
@@ -228,7 +225,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
228
225
  return store.storeWebhooks;
229
226
  },
230
227
  async mutateWebhook(action, body, idempotencyKey) {
231
- const { data } = await post(`/v1/actions/store/${action}-webhook`, body, idempotencyKey);
228
+ const { data } = await post(webhookEndpoint(action), body, idempotencyKey);
232
229
  const webhook = data.webhook;
233
230
  if (!webhook || typeof webhook.id !== 'string' || typeof webhook.testMode !== 'boolean' || !Array.isArray(webhook.events))
234
231
  throw apiError(200, true);
@@ -0,0 +1,7 @@
1
+ import { CliError } from "../contracts/errors.js";
2
+ export function requireActionAuthentication(authentication, hasSession) {
3
+ if (authentication === 'merchant-rsa' && hasSession)
4
+ throw new CliError('AUTH_METHOD_UNSUPPORTED', 'This command requires RSA API-key login; browser login cannot issue customer session tokens.', {
5
+ exitCode: 2, stage: 'credentials', recovery: 'Run login --key-login with a merchant RSA API key, then run sessions create again.',
6
+ });
7
+ }
@@ -19,7 +19,7 @@ export function actionResult(spec, data) {
19
19
  throw new CliError('OUTCOME_UNKNOWN', 'The API returned an unexpected action response; the operation may have completed.', { outcome: 'unknown', stage: 'api' });
20
20
  if (spec.sensitiveOutput)
21
21
  return { exported: true };
22
- if (spec.acknowledgementOnly)
22
+ if (spec.verification === 'acknowledgement_only')
23
23
  return { acknowledged: true };
24
24
  if (spec.projectResponse)
25
25
  return spec.projectResponse(data);
@@ -31,10 +31,9 @@ export function priceReplacementWarning(command, input) {
31
31
  : undefined;
32
32
  }
33
33
  export function actionPreview(spec, input) {
34
- const visible = new Set(['type', 'id', 'storeId', 'productId', 'groupId', 'orderId', 'recipientId', 'paymentId', 'ticketId', 'status', 'prices', 'billingPeriod', 'requestedAmount', 'currency', 'changeAmount', 'changeCreditAmount', 'originOrderId']);
35
34
  return { executed: false, validation: 'local', command: spec.definition.id, endpoint: actionEndpoint(spec, input),
36
35
  ...operationImpact(spec.definition), targetEnvironment: operationImpact(spec.definition).impact === 'test-to-prod' ? 'prod' : null, environmentVerified: false,
37
- input: Object.fromEntries(Object.entries(input).map(([key, value]) => [key, visible.has(key) ? value : '[redacted]'])),
36
+ input: spec.previewInput(input),
38
37
  requiresPrivateOutput: spec.sensitiveOutput ?? false,
39
38
  ...(priceReplacementWarning(spec.definition.id, input) ? { warning: priceReplacementWarning(spec.definition.id, input) } : {}),
40
39
  };
@@ -1,7 +1,10 @@
1
+ import { requireActionAuthentication } from "./action-auth.js";
1
2
  import { operationImpact } from "../commands/operation-impact.js";
2
3
  import { requireImpactConfirmation } from "./confirmation.js";
3
- import { randomUUID } from 'node:crypto';
4
- import { argumentError, CliError, safeError } from "../contracts/errors.js";
4
+ import { DEFAULT_API_ORIGIN } from "../contracts/action-routes.js";
5
+ import { createIdempotencyKey } from "./idempotency.js";
6
+ import { beginWriteOperation } from "./write-operation.js";
7
+ import { argumentError, CliError } from "../contracts/errors.js";
5
8
  import { productPriceMismatch } from "./product-verification.js";
6
9
  import { requireWriteEnvironment, credentialContext, contextualError, writeWarning } from "./auth-context.js";
7
10
  import { actionEndpoint, actionResult, priceReplacementWarning } from "./action-result.js";
@@ -14,15 +17,14 @@ export async function executeApiAction(spec, input, options, services) {
14
17
  if (spec.sensitiveOutput && !options.output)
15
18
  throw argumentError('This response contains a token or checkout link. Provide --output with a new private file path.');
16
19
  const credentials = await services.credentials(options);
20
+ requireActionAuthentication(spec.authentication, Boolean(credentials.sessionToken));
17
21
  const attempts = [];
18
22
  const storeId = typeof input.storeId === 'string' ? input.storeId
19
23
  : spec.definition.id.startsWith('stores.') && typeof input.id === 'string' ? input.id : undefined;
20
- const targetResourceId = [input.id, input.productId, input.groupId, input.orderId, input.recipientId, input.ticketId, input.paymentId, input.couponId, input.promotionCodeId].find(value => typeof value === 'string');
24
+ const targetResourceId = spec.targetResourceId(input);
21
25
  let impact = operationImpact(spec.definition);
22
26
  const context = () => ({ ...impact, ...credentialContext(credentials, attempts), storeId, targetResourceId, targetEnvironment: production ? 'prod' : null, ...(replacementWarning ? { priceReplacementWarning: replacementWarning } : {}) });
23
- const key = options.idempotencyKey ?? `${credentials.merchantId}_${randomUUID()}`;
24
- if (!/^[A-Za-z0-9_-]{1,256}$/.test(key))
25
- throw argumentError('Idempotency keys must contain 1–256 letters, numbers, underscores or hyphens.');
27
+ const key = createIdempotencyKey(credentials.merchantId, options.idempotencyKey);
26
28
  let output;
27
29
  try {
28
30
  const gateway = await services.gateway(credentials, event => { attempts.push(event); if (options.debug)
@@ -34,39 +36,35 @@ export async function executeApiAction(spec, input, options, services) {
34
36
  if (options.output)
35
37
  output = await services.prepareOutput(options.output);
36
38
  const { type: _type, ...body } = input;
37
- const operation = await services.operations.begin({ command: spec.definition.id, impact: impact.impact, cliVersion: services.cliVersion, merchantId: credentials.merchantId,
39
+ const operation = await beginWriteOperation(services.operations, { command: spec.definition.id, impact: impact.impact, cliVersion: services.cliVersion, merchantId: credentials.merchantId,
38
40
  storeId, inputHash: services.fingerprint(input), idempotencyKey: key,
39
41
  targetResourceId,
40
- endpoint, apiOrigin: credentials.apiUrl ?? 'https://api.waffo.ai', selectedEnvironment: credentials.environment });
41
- const meta = { ...context(), operationId: operation.operationId, idempotencyKey: key, verification: spec.acknowledgementOnly ? 'acknowledgement_only' : 'response_only' };
42
+ endpoint, apiOrigin: credentials.apiUrl ?? DEFAULT_API_ORIGIN, selectedEnvironment: credentials.sessionToken ? credentials.environment : undefined });
43
+ const meta = { ...context(), operationId: operation.operationId, idempotencyKey: key, verification: spec.verification };
42
44
  services.diagnostic({ stage: 'confirmation', command: spec.definition.id, ...meta,
43
45
  warning: [replacementWarning, production ? 'This operation publishes TEST data to PRODUCTION.' : writeWarning(attempts)].filter(Boolean).join(' ') });
44
46
  let raw, displayed;
45
47
  try {
46
- raw = await gateway.action(endpoint, body, key, spec.acknowledgementOnly);
48
+ raw = await gateway.action(endpoint, body, key, spec.verification === 'acknowledgement_only');
47
49
  displayed = actionResult(spec, raw);
48
50
  }
49
51
  catch (error) {
50
- const failure = safeError(error);
51
- const unknown = !(error instanceof CliError) || failure.outcome === 'unknown';
52
- await services.operations.finish(operation.operationId, { outcome: unknown ? 'unknown' : 'rejected', errorCode: failure.code, attempts }).catch(() => { });
53
- throw new CliError(unknown ? 'OUTCOME_UNKNOWN' : failure.code, failure.message, { outcome: unknown ? 'unknown' : 'rejected', stage: failure.stage,
54
- recovery: unknown ? 'Inspect operations show and query the affected resource or merchant dashboard before taking further action. Do not replay an unknown operation.' : failure.recovery, details: { ...failure.details, ...meta } });
52
+ throw await operation.failed(error, attempts, meta, 'Inspect operations show and query the affected resource or merchant dashboard before taking further action. Do not replay an unknown operation.');
55
53
  }
56
54
  const entity = spec.responseKey ? raw[spec.responseKey] : raw;
57
- const resourceId = [entity?.id, raw.orderId, raw.recipientId, input.id, input.productId, input.groupId, input.orderId].find(value => typeof value === 'string');
55
+ const resourceId = spec.resultResourceId(raw, input);
58
56
  try {
59
- await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId, attempts });
57
+ await operation.accepted(resourceId, attempts);
60
58
  if (spec.definition.id === 'products.update' && resourceId && productPriceMismatch(input, entity, resourceId))
61
59
  throw new CliError('PRICE_MISMATCH', 'The API accepted the product update but returned prices different from those requested.');
62
60
  if (output)
63
61
  await output.commit(`${JSON.stringify(raw, null, 2)}\n`);
64
- await services.operations.finish(operation.operationId, { outcome: 'completed', resourceId, attempts });
62
+ await operation.completed(resourceId, attempts);
65
63
  }
66
64
  catch (error) {
67
65
  const mismatch = error instanceof CliError && error.code === 'PRICE_MISMATCH';
68
66
  const errorCode = mismatch ? 'PRICE_MISMATCH' : 'VERIFICATION_PENDING';
69
- await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId, errorCode, attempts }).catch(() => { });
67
+ await operation.accepted(resourceId, attempts, errorCode).catch(() => { });
70
68
  throw new CliError(errorCode, mismatch ? error.message : 'The API accepted the operation, but exporting its result or updating the local record failed.', {
71
69
  outcome: 'committed_unverified', stage: mismatch ? 'verification' : 'local-persistence', recovery: 'Inspect the output file if present, operation record and merchant dashboard. Do not repeat the operation to recover its response.', details: { ...meta, resourceId: resourceId ?? null },
72
70
  });
@@ -26,11 +26,11 @@ export async function login(options, services) {
26
26
  ...(isContent ? { privateKey: key } : { privateKeyFile: resolve(path.startsWith('~/') ? homedir() + path.slice(1) : path) }),
27
27
  storeId: options.storeId, source: 'login' };
28
28
  return authenticatedOperation('login', options, services, credentials, async (observer) => {
29
- await services.config.read();
29
+ const snapshot = await services.config.read();
30
30
  const identity = await (await services.gateway(credentials, observer)).me();
31
31
  if (identity.id !== credentials.merchantId)
32
32
  throw new CliError('AUTH_FAILED', 'The authenticated merchant could not be verified.', { stage: 'identity' });
33
- await services.config.save(credentials);
33
+ await services.config.save(credentials, snapshot, options.signal);
34
34
  return { saved: true, merchantId: identity.id, credentialVerified: true, ...environmentContext(identity.environment),
35
35
  savedLoginActive: !services.environmentCredentialsPresent, ...overrideStatus(services), next: 'Run pancake whoami to verify the effective identity, then pancake stores list.' };
36
36
  });
@@ -66,7 +66,10 @@ export async function logout(services) {
66
66
  const credentials = { ...snapshot.credential, source: 'stored' };
67
67
  serverSessionRevoked = await (await services.gateway(credentials, () => { })).revokeSession();
68
68
  }
69
- await services.config.clear(snapshot ? { revision: snapshot.revision } : undefined);
69
+ if (snapshot)
70
+ await services.config.clear(snapshot);
71
+ else
72
+ await services.config.clearInvalid();
70
73
  return { data: { localCredentialsCleared: true, serverKeyRevoked: false, serverSessionRevoked, ...overrideStatus(services) } };
71
74
  }
72
75
  async function loginInBrowser(options, services) {
@@ -85,7 +88,7 @@ async function loginInBrowser(options, services) {
85
88
  throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the selected environment. Your saved login was not changed.', { stage: 'identity' });
86
89
  if (options.signal?.aborted)
87
90
  throw new CliError('INTERRUPTED', 'Cancelled.', { exitCode: 130 });
88
- await services.config.save(credentials, options.signal, { revision: snapshot.revision });
91
+ await services.config.save(credentials, snapshot, options.signal);
89
92
  return { saved: true, merchantId: identity.id, credentialVerified: true, authentication: 'browser', ...environmentContext(identity.environment), savedLoginActive: !services.environmentCredentialsPresent, ...overrideStatus(services) };
90
93
  });
91
94
  });
@@ -106,7 +109,7 @@ export async function selectEnvironment(environment, options, services) {
106
109
  const identity = await (await services.gateway(credentials, observer)).me();
107
110
  if (identity.id !== credentials.merchantId || identity.environment !== environment)
108
111
  throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the requested merchant environment. The saved environment was not changed.', { stage: 'identity' });
109
- await services.config.save(credentials, options.signal, { revision: snapshot.revision });
112
+ await services.config.save(credentials, snapshot, options.signal);
110
113
  return { saved: true, merchantId: identity.id, ...environmentContext(identity.environment) };
111
114
  });
112
115
  }
@@ -1,3 +1,5 @@
1
+ import { productPreview } from "../commands/product-preview.js";
2
+ import { webhookPreview } from "../commands/webhook-preview.js";
1
3
  import { operationImpact } from "../commands/operation-impact.js";
2
4
  import { listen } from "./listen.js";
3
5
  import { validateDiscountInput } from "../commands/discount-validation.js";
@@ -16,7 +18,7 @@ import { actionPreview } from "./action-result.js";
16
18
  import { executeApiRead } from "./api-reads.js";
17
19
  import { pagination } from "./queries.js";
18
20
  function preview(id, input) {
19
- const displayed = id === 'products.create' ? { type: input.type, storeId: input.storeId, name: input.name, prices: input.prices, billingPeriod: input.billingPeriod, metadata: input.metadata === undefined ? undefined : '[redacted]', description: input.description === undefined ? undefined : '[redacted]', media: input.media === undefined ? undefined : '[redacted]', successUrl: input.successUrl === undefined ? undefined : '[redacted]' } : { ...input, ...(input.url !== undefined ? { url: '[redacted]' } : {}), ...(input.secret !== undefined ? { secret: '[redacted]' } : {}) };
21
+ const displayed = id === 'products.create' ? productPreview(input) : webhookPreview(input);
20
22
  return { data: { executed: false, validation: 'local', environmentVerified: false, command: id, input: displayed }, meta: { executed: false } };
21
23
  }
22
24
  export function createApplication(services) {
@@ -0,0 +1,8 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { argumentError } from "../contracts/errors.js";
3
+ export function createIdempotencyKey(merchantId, supplied) {
4
+ const key = supplied ?? `${merchantId}_${randomUUID()}`;
5
+ if (!/^[A-Za-z0-9_-]{1,256}$/.test(key))
6
+ throw argumentError('Idempotency keys must contain 1–256 letters, numbers, underscores or hyphens.');
7
+ return key;
8
+ }
@@ -1,7 +1,9 @@
1
1
  import { operationImpact } from "../commands/operation-impact.js";
2
2
  import { requireImpactConfirmation } from "./confirmation.js";
3
- import { randomUUID } from 'node:crypto';
4
- import { CliError, argumentError, safeError } from "../contracts/errors.js";
3
+ import { DEFAULT_API_ORIGIN, productCreateEndpoint } from "../contracts/action-routes.js";
4
+ import { createIdempotencyKey } from "./idempotency.js";
5
+ import { beginWriteOperation } from "./write-operation.js";
6
+ import { CliError } from "../contracts/errors.js";
5
7
  import { requireWriteEnvironment, credentialContext, contextualError, writeWarning } from "./auth-context.js";
6
8
  import { productMatches, productPriceMismatch, safeProduct } from "./product-verification.js";
7
9
  const warning = 'The credential environment cannot be verified. Product creation may affect production; the backend selects the environment from the RSA key.';
@@ -21,10 +23,8 @@ export async function createProduct(input, options, services, fingerprint) {
21
23
  const context = () => ({ ...impact, ...credentialContext(credentials, attempts), storeId: input.storeId, product: proposed, warning: writeWarning(attempts) });
22
24
  if (!options.yes)
23
25
  throw new CliError('INVALID_ARGUMENT', 'Product creation requires --yes after reviewing the product and credential environment.', { exitCode: 2, stage: 'confirmation', recovery: warning, details: context() });
24
- const key = options.idempotencyKey ?? `${credentials.merchantId}_${randomUUID()}`;
25
- if (!/^[A-Za-z0-9_-]{1,256}$/.test(key))
26
- throw contextualError(argumentError('Idempotency keys must contain 1–256 letters, numbers, underscores or hyphens.'), context());
27
26
  try {
27
+ const key = createIdempotencyKey(credentials.merchantId, options.idempotencyKey);
28
28
  const gateway = await services.gateway(credentials, event => { attempts.push(event); if (options.debug)
29
29
  services.diagnostic({ stage: 'api', ...event }); });
30
30
  const identity = await gateway.me();
@@ -33,7 +33,8 @@ export async function createProduct(input, options, services, fingerprint) {
33
33
  requireImpactConfirmation(impact, options);
34
34
  const type = input.type;
35
35
  const { type: _type, ...body } = input;
36
- const operation = await services.operations.begin({ command: 'products.create', impact: impact.impact, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId: input.storeId, inputHash: fingerprint, idempotencyKey: key });
36
+ const operation = await beginWriteOperation(services.operations, { command: 'products.create', impact: impact.impact, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId: input.storeId, inputHash: fingerprint, idempotencyKey: key,
37
+ endpoint: productCreateEndpoint(type), apiOrigin: credentials.apiUrl ?? DEFAULT_API_ORIGIN, selectedEnvironment: credentials.sessionToken ? credentials.environment : undefined });
37
38
  const meta = { ...context(), operationId: operation.operationId, idempotencyKey: key };
38
39
  let returned;
39
40
  try {
@@ -41,14 +42,11 @@ export async function createProduct(input, options, services, fingerprint) {
41
42
  returned = await gateway.createProduct(type, body, key);
42
43
  }
43
44
  catch (error) {
44
- const failure = safeError(error);
45
- const unknown = !(error instanceof CliError) || failure.outcome === 'unknown';
46
- await services.operations.finish(operation.operationId, { outcome: unknown ? 'unknown' : 'rejected', errorCode: failure.code, attempts }).catch(() => { });
47
- throw new CliError(unknown ? 'OUTCOME_UNKNOWN' : failure.code, failure.message, { stage: failure.stage, outcome: unknown ? 'unknown' : 'rejected', recovery: unknown ? 'Inspect operations show and the merchant dashboard for this store. If a product ID is found, use products get with its type. Do not repeat creation or use a new key.' : failure.recovery, details: { ...meta, ...failure.details } });
45
+ throw await operation.failed(error, attempts, meta, 'Inspect operations show and the merchant dashboard for this store. If a product ID is found, use products get with its type. Do not repeat creation or use a new key.');
48
46
  }
49
47
  const resourceId = returned.id;
50
48
  try {
51
- await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId, attempts });
49
+ await operation.accepted(resourceId, attempts);
52
50
  if (productPriceMismatch(input, returned, resourceId))
53
51
  throw new CliError('PRICE_MISMATCH', 'The API accepted the product but returned prices different from those requested.');
54
52
  const current = await gateway.product(type, resourceId);
@@ -56,12 +54,12 @@ export async function createProduct(input, options, services, fingerprint) {
56
54
  throw new CliError('PRICE_MISMATCH', 'The saved product prices differ from those requested.');
57
55
  if (!productMatches(input, returned, resourceId) || !productMatches(input, current, resourceId, returned))
58
56
  throw new Error('Verification failed');
59
- await services.operations.finish(operation.operationId, { outcome: 'completed', resourceId, attempts });
57
+ await operation.completed(resourceId, attempts);
60
58
  }
61
59
  catch (error) {
62
60
  const mismatch = error instanceof CliError && error.code === 'PRICE_MISMATCH';
63
61
  const errorCode = mismatch ? 'PRICE_MISMATCH' : 'VERIFICATION_PENDING';
64
- await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId, errorCode, attempts }).catch(() => { });
62
+ await operation.accepted(resourceId, attempts, errorCode).catch(() => { });
65
63
  throw new CliError(errorCode, mismatch ? error.message : 'Product creation was accepted, but its verification or local record update did not complete.', { outcome: 'committed_unverified', stage: 'verification', recovery: `Run pancake products get ${resourceId} --type ${type} --json with the same credentials, then inspect operations show ${operation.operationId}. Do not repeat creation.`, details: { ...meta, resourceId, type } });
66
64
  }
67
65
  return { data: { product: safeProduct(returned, type) }, meta: { ...meta, ...context(), requestId: attempts.at(-1)?.requestId ?? null } };
@@ -1,14 +1,14 @@
1
1
  import { operationImpact } from "../commands/operation-impact.js";
2
- import { randomUUID } from 'node:crypto';
3
- import { CliError, argumentError, safeError } from "../contracts/errors.js";
2
+ import { DEFAULT_API_ORIGIN, webhookEndpoint } from "../contracts/action-routes.js";
3
+ import { createIdempotencyKey } from "./idempotency.js";
4
+ import { beginWriteOperation } from "./write-operation.js";
5
+ import { CliError, argumentError } from "../contracts/errors.js";
4
6
  import { requireWriteEnvironment, credentialContext } from "./auth-context.js";
5
7
  import { safeWebhook, testWebhook } from "./queries.js";
6
8
  export async function mutateWebhook(action, input, options, services, credentials, gateway, attempts, fingerprint) {
7
9
  if (!options.yes)
8
10
  throw argumentError('Remote changes require --yes after reviewing the input or --dry-run output.');
9
- const key = options.idempotencyKey ?? `${credentials.merchantId}_${randomUUID()}`;
10
- if (!/^[A-Za-z0-9_-]{1,256}$/.test(key))
11
- throw argumentError('Idempotency keys must contain 1–256 letters, numbers, underscores or hyphens.');
11
+ const key = createIdempotencyKey(credentials.merchantId, options.idempotencyKey);
12
12
  const identity = await gateway.me();
13
13
  requireWriteEnvironment(credentials, identity);
14
14
  if (identity.environment !== 'test')
@@ -22,9 +22,9 @@ export async function mutateWebhook(action, input, options, services, credential
22
22
  throw new CliError('ENVIRONMENT_MISMATCH', 'New webhook subscriptions must use testMode:true.');
23
23
  const { storeId: _storeId, ...withoutStore } = input;
24
24
  const body = action === 'add' ? input : withoutStore;
25
- const operation = await services.operations.begin({ command: `webhook.${action}`, impact: impact.impact, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId, inputHash: fingerprint, idempotencyKey: key,
26
- targetResourceId: typeof input.id === 'string' ? input.id : undefined, endpoint: `/v1/actions/store/${action}-webhook`,
27
- apiOrigin: credentials.apiUrl ?? 'https://api.waffo.ai', selectedEnvironment: credentials.environment });
25
+ const operation = await beginWriteOperation(services.operations, { command: `webhook.${action}`, impact: impact.impact, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId, inputHash: fingerprint, idempotencyKey: key,
26
+ targetResourceId: typeof input.id === 'string' ? input.id : undefined, endpoint: webhookEndpoint(action),
27
+ apiOrigin: credentials.apiUrl ?? DEFAULT_API_ORIGIN, selectedEnvironment: credentials.sessionToken ? credentials.environment : undefined });
28
28
  const meta = { ...impact, operationId: operation.operationId, idempotencyKey: key, resourceEnvironment: 'test', ...credentialContext(credentials, attempts) };
29
29
  const secretReadbackRestricted = !!credentials.sessionToken && input.secret !== undefined;
30
30
  let returned;
@@ -32,13 +32,10 @@ export async function mutateWebhook(action, input, options, services, credential
32
32
  returned = await gateway.mutateWebhook(action, body, key);
33
33
  }
34
34
  catch (error) {
35
- const failure = safeError(error);
36
- const unknown = !(error instanceof CliError) || failure.outcome === 'unknown';
37
- await services.operations.finish(operation.operationId, { outcome: unknown ? 'unknown' : 'rejected', errorCode: failure.code, attempts }).catch(() => { });
38
- throw new CliError(unknown ? 'OUTCOME_UNKNOWN' : failure.code, failure.message, { stage: failure.stage, outcome: unknown ? 'unknown' : 'rejected', recovery: failure.recovery, details: { ...meta, ...failure.details } });
35
+ throw await operation.failed(error, attempts, meta, 'Inspect operations show and run webhook list for the selected store before taking further action. Do not repeat the change or use a new key.');
39
36
  }
40
37
  try {
41
- await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId: returned.id, attempts });
38
+ await operation.accepted(returned.id, attempts);
42
39
  const after = await gateway.webhooks(storeId, input.secret !== undefined && !secretReadbackRestricted);
43
40
  const current = after.find(item => item.id === returned.id);
44
41
  const targetMatches = action === 'add' || returned.id === input.id;
@@ -49,10 +46,10 @@ export async function mutateWebhook(action, input, options, services, credential
49
46
  (input.events === undefined || JSON.stringify(current.events) === JSON.stringify(input.events));
50
47
  if (!targetMatches || returned.testMode !== true || !fieldsMatch)
51
48
  throw new Error('Verification failed');
52
- await services.operations.finish(operation.operationId, { outcome: 'completed', resourceId: returned.id, attempts });
49
+ await operation.completed(returned.id, attempts);
53
50
  }
54
51
  catch {
55
- await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId: returned.id, errorCode: 'VERIFICATION_PENDING', attempts }).catch(() => { });
52
+ await operation.accepted(returned.id, attempts, 'VERIFICATION_PENDING').catch(() => { });
56
53
  throw new CliError('VERIFICATION_PENDING', 'The change was accepted, but its verification or local record update did not complete.', { outcome: 'committed_unverified', stage: 'verification', recovery: 'Run webhook list for the selected store. Do not repeat the change.', details: { ...meta, resourceId: returned.id } });
57
54
  }
58
55
  return { data: { webhook: safeWebhook(returned), removed: action === 'remove' }, meta: { ...meta, ...credentialContext(credentials, attempts), requestId: attempts.at(-1)?.requestId ?? null, ...(secretReadbackRestricted ? { verification: 'response_only', unverifiedFields: ['secret'] } : {}) } };
@@ -0,0 +1,26 @@
1
+ import { CliError, safeError } from "../contracts/errors.js";
2
+ export async function beginWriteOperation(repository, input) {
3
+ const { idempotencyKey } = input;
4
+ const { operationId } = await repository.begin(input);
5
+ return Object.freeze({
6
+ operationId,
7
+ idempotencyKey,
8
+ async accepted(resourceId, attempts, errorCode) {
9
+ await repository.finish(operationId, { outcome: 'committed_unverified', resourceId, attempts, ...(errorCode ? { errorCode } : {}) });
10
+ },
11
+ async completed(resourceId, attempts) {
12
+ await repository.finish(operationId, { outcome: 'completed', resourceId, attempts });
13
+ },
14
+ async failed(error, attempts, context, unknownRecovery) {
15
+ const failure = safeError(error);
16
+ const unknown = !(error instanceof CliError) || failure.outcome === 'unknown';
17
+ const outcome = unknown ? 'unknown' : 'rejected';
18
+ await repository.finish(operationId, { outcome, errorCode: failure.code, attempts }).catch(() => { });
19
+ return new CliError(unknown ? 'OUTCOME_UNKNOWN' : failure.code, failure.message, {
20
+ exitCode: unknown ? 1 : failure.exitCode, outcome, stage: failure.stage,
21
+ recovery: unknown ? unknownRecovery : failure.recovery,
22
+ details: { ...failure.details, ...context, operationId, idempotencyKey },
23
+ });
24
+ },
25
+ });
26
+ }
@@ -1,3 +1,4 @@
1
+ import { storePreview, productActionPreview, groupPreview, checkoutPreview, subscriptionPreview, refundPreview, sessionPreview, recipientPreview, contentPreview } from "./action-previews.js";
1
2
  import { discountActionSpecs } from "./discount-definitions.js";
2
3
  import { contentScanSchema, groupSchemas, recipientSchemas, refundSchemas, sessionSchema, storeSchemas, subscriptionCancelSchema } from "./action-schemas.js";
3
4
  import { checkoutSchema } from "./checkout-action-schema.js";
@@ -25,6 +26,9 @@ export const actionSpecs = [
25
26
  ...['create', 'update', 'delete'].map(action => ({
26
27
  definition: definition(`stores.${action}`, `${action} a store; requires --yes${action === 'delete' ? '; soft-deletes the store and makes it inaccessible' : ''}`, storeSchemas[action]),
27
28
  endpoint: `/v1/actions/store/${action}-store`, documentation: [docs(`stores/${action}-store`)],
29
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: storePreview,
30
+ targetResourceId: (input) => action === 'create' ? undefined : input.id,
31
+ resultResourceId: (data) => data.store.id,
28
32
  responseKey: 'store', validateResponse: keyedResponse('store'),
29
33
  })),
30
34
  ...[
@@ -35,41 +39,62 @@ export const actionSpecs = [
35
39
  definition: definition(`products.${action}`, `${description}; requires --yes`, schema, true),
36
40
  endpoint: { onetime: `/v1/actions/onetime-product/${endpoint}`, subscription: `/v1/actions/subscription-product/${endpoint}` },
37
41
  documentation: [docs(`onetime-products/${endpoint}`), docs(`subscription-products/${endpoint}`)],
42
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: productActionPreview,
43
+ targetResourceId: (input) => input.id,
44
+ resultResourceId: (data) => data.product.id,
38
45
  responseKey: 'product', validateResponse: keyedResponse('product'),
39
46
  })),
40
47
  ...['create', 'update', 'delete', 'publish'].map(action => ({
41
48
  definition: definition(`groups.${action}`, `${action} a subscription product group; requires --yes${action === 'delete' ? '; permanently deletes only the group' : ''}${action === 'publish' ? '; copies TEST→PRODUCTION using upsert' : ''}`, groupSchemas[action]),
42
49
  endpoint: `/v1/actions/subscription-product-group/${action}-group`, documentation: [docs(`subscription-products/${action}-group`)],
43
- ...(action === 'create' || action === 'update' ? { responseKey: 'group', validateResponse: keyedResponse('group') } : { acknowledgementOnly: true }),
50
+ authentication: 'merchant-session-or-rsa',
51
+ verification: action === 'delete' || action === 'publish' ? 'acknowledgement_only' : 'response_only', previewInput: groupPreview,
52
+ targetResourceId: (input) => action === 'create' ? undefined : input.id,
53
+ resultResourceId: (data, input) => action === 'delete' || action === 'publish' ? input.id : data.group.id,
54
+ ...(action === 'create' || action === 'update' ? { responseKey: 'group', validateResponse: keyedResponse('group') } : {}),
44
55
  })),
45
56
  {
46
57
  definition: definition('checkout.create', 'Create a checkout or plan-change session; requires --yes and --output for the private checkout link', checkoutSchema),
47
58
  endpoint: '/v1/actions/checkout/create-session', documentation: [docs('orders/create-checkout-session')], sensitiveOutput: true,
59
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: checkoutPreview,
60
+ targetResourceId: input => input.productId, resultResourceId: data => data.sessionId,
48
61
  validateResponse: data => hasStrings(data, ['sessionId', 'checkoutUrl', 'expiresAt']),
49
62
  },
50
63
  {
51
64
  definition: definition('subscriptions.cancel', 'Request subscription cancellation; timing follows its current state; requires --yes', subscriptionCancelSchema),
52
65
  endpoint: '/v1/actions/subscription-order/cancel-order', documentation: [docs('subscriptions/cancel-subscription')],
66
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: subscriptionPreview,
67
+ targetResourceId: input => input.orderId, resultResourceId: data => data.orderId,
53
68
  validateResponse: data => hasStrings(data, ['orderId', 'status']) && ['canceling', 'canceled'].includes(data.status),
54
69
  },
55
70
  ...['create', 'resubmit'].map(action => ({
56
71
  definition: definition(`refunds.${action}`, `${action} a refund ticket; this does not confirm completed repayment; requires --yes`, refundSchemas[action]),
57
72
  endpoint: `/v1/actions/refund-ticket/${action}-ticket`, documentation: [docs(`refunds/${action}-refund-ticket`)],
73
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: refundPreview,
74
+ targetResourceId: (input) => (action === 'create' ? input.paymentId : input.ticketId),
75
+ resultResourceId: (data) => data.ticket.id,
58
76
  responseKey: 'ticket', validateResponse: keyedResponse('ticket'),
59
77
  })),
60
78
  {
61
79
  definition: definition('sessions.create', 'Issue a customer token using RSA login; requires --yes and --output', sessionSchema),
62
80
  endpoint: '/v1/actions/auth/issue-session-token', documentation: [docs('auth/issue-session-token')], sensitiveOutput: true,
81
+ authentication: 'merchant-rsa', verification: 'response_only', previewInput: sessionPreview,
82
+ targetResourceId: input => input.productId, resultResourceId: () => undefined,
63
83
  validateResponse: data => hasStrings(data, ['token', 'expiresAt']) && (data.portalUrl === undefined || hasStrings(data, ['portalUrl'])),
64
84
  },
65
85
  ...['add', 'update', 'remove'].map(action => ({
66
86
  definition: definition(`recipients.${action}`, `${action} a store notification recipient; requires --yes${action === 'remove' ? '; removing the last recipient silences merchant notifications' : ''}`, recipientSchemas[action]),
67
87
  endpoint: `/v1/actions/store-notification-recipient/${action}-recipient`, documentation: [docs(`notification-recipients/${action}-recipient`)],
88
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: recipientPreview,
89
+ targetResourceId: (input) => action === 'add' ? undefined : input.recipientId,
90
+ resultResourceId: (data) => action === 'remove' ? data.recipientId : data.recipient.id,
68
91
  ...(action === 'remove' ? { validateResponse: (data) => hasStrings(data, ['recipientId']) && data.removed === true } : { responseKey: 'recipient', validateResponse: keyedResponse('recipient') }),
69
92
  })),
70
93
  {
71
94
  definition: definition('content.scan', 'Check prompt safety; requires --yes', contentScanSchema, false, 'read'),
72
95
  endpoint: '/v1/actions/verification/scan-prompt', documentation: [docs('content-safety/scan-prompt')],
96
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: contentPreview,
97
+ targetResourceId: () => undefined, resultResourceId: () => undefined,
73
98
  validateResponse: data => hasStrings(data, ['action', 'reasonCode', 'requestId', 'semanticStatus']) && ['allow', 'review', 'block'].includes(data.action) && Array.isArray(data.matchedCategories) && data.matchedCategories.every(value => typeof value === 'string'),
74
99
  },
75
100
  ];
@@ -0,0 +1,12 @@
1
+ export function previewFields(input, visible) {
2
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, visible.includes(key) ? value : '[redacted]']));
3
+ }
4
+ export const storePreview = (input) => previewFields(input, ['id', 'status']);
5
+ export const productActionPreview = (input) => previewFields(input, ['type', 'id', 'status', 'prices', 'billingPeriod']);
6
+ export const groupPreview = (input) => previewFields(input, ['id', 'storeId']);
7
+ export const checkoutPreview = (input) => previewFields(input, ['productId', 'currency', 'changeAmount', 'changeCreditAmount', 'originOrderId']);
8
+ export const subscriptionPreview = (input) => previewFields(input, ['orderId']);
9
+ export const refundPreview = (input) => previewFields(input, ['paymentId', 'ticketId', 'requestedAmount']);
10
+ export const sessionPreview = (input) => previewFields(input, ['storeId', 'productId']);
11
+ export const recipientPreview = (input) => previewFields(input, ['storeId', 'recipientId']);
12
+ export const contentPreview = (input) => previewFields(input, []);
@@ -1,3 +1,4 @@
1
+ import { productCreateEndpoint, webhookEndpoint } from "../contracts/action-routes.js";
1
2
  import { actionSpecs } from "./action-definitions.js";
2
3
  import { readSpecs } from "./read-definitions.js";
3
4
  export function commandApi(id) {
@@ -5,17 +6,17 @@ export function commandApi(id) {
5
6
  return { method: 'POST', endpoints: ['/v1/graphql', ...['start', 'poll', 'ack', 'stop'].map(action => `/v1/actions/notification/cli-listen-${action}`)], authentication: 'merchant-session only', targetEnvironment: 'test by default; --live for prod', temporarySessionTtlSeconds: 90 };
6
7
  const action = actionSpecs.find(spec => spec.definition.id === id);
7
8
  if (action)
8
- return { method: 'POST', endpoints: typeof action.endpoint === 'string' ? [action.endpoint] : Object.values(action.endpoint), authentication: id === 'sessions.create' ? 'merchant-rsa' : 'merchant-session or merchant-rsa; server route permissions apply',
9
+ return { method: 'POST', endpoints: typeof action.endpoint === 'string' ? [action.endpoint] : Object.values(action.endpoint), authentication: action.authentication === 'merchant-rsa' ? 'merchant-rsa' : 'merchant-session or merchant-rsa; server route permissions apply',
9
10
  confirmationRequired: true, privateOutputRequired: action.sensitiveOutput ?? false,
10
11
  targetEnvironment: id.endsWith('.publish') ? 'prod' : 'credential-dependent-unverified',
11
- verification: action.acknowledgementOnly ? 'acknowledgement_only' : 'response_only', documentation: action.documentation };
12
+ verification: action.verification, documentation: action.documentation };
12
13
  const read = readSpecs.find(spec => spec.definition.id === id);
13
14
  if (read)
14
15
  return { method: 'POST', endpoints: ['/v1/graphql'], authentication: 'merchant-session or merchant-rsa; server route permissions apply', privateOutputRequired: read.sensitiveOutput ?? false, documentation: read.documentation };
15
16
  if (id === 'products.create')
16
- return { method: 'POST', endpoints: ['/v1/actions/onetime-product/create-product', '/v1/actions/subscription-product/create-product'], authentication: 'merchant-session or merchant-rsa; server route permissions apply', verification: 'read_back' };
17
+ return { method: 'POST', endpoints: [productCreateEndpoint('onetime'), productCreateEndpoint('subscription')], authentication: 'merchant-session or merchant-rsa; server route permissions apply', verification: 'read_back' };
17
18
  if (['webhook.add', 'webhook.update', 'webhook.remove'].includes(id))
18
- return { method: 'POST', endpoints: [`/v1/actions/store/${id.split('.')[1]}-webhook`], authentication: 'merchant-session or merchant-rsa; server route permissions apply', scope: 'test-webhook-resources-only', verification: id === 'webhook.remove' ? 'read_back' : 'conditional', ...(id === 'webhook.remove' ? {} : { verificationPolicy: { default: 'read_back', browserSecretWrite: 'response_only' } }) };
19
+ return { method: 'POST', endpoints: [webhookEndpoint(id.split('.')[1])], authentication: 'merchant-session or merchant-rsa; server route permissions apply', scope: 'test-webhook-resources-only', verification: id === 'webhook.remove' ? 'read_back' : 'conditional', ...(id === 'webhook.remove' ? {} : { verificationPolicy: { default: 'read_back', browserSecretWrite: 'response_only' } }) };
19
20
  if (id === 'login')
20
21
  return { method: 'POST', endpoints: ['/v1/actions/auth/cli-device-start', '/v1/actions/auth/cli-device-token', '/v1/actions/auth/cli-device-complete', '/v1/graphql'], authentication: 'browser device authorization then merchant-session; explicit merchant-rsa supported' };
21
22
  if (['env', 'whoami', 'doctor', 'stores.list', 'products.get', 'webhook.list'].includes(id))
@@ -1,3 +1,4 @@
1
+ import { couponPreview, promotionCodePreview } from "./discount-preview.js";
1
2
  import { couponId, couponListSchema, discountSchemas, promotionListSchema } from "./discount-schemas.js";
2
3
  import { objectSchema } from "./schemas.js";
3
4
  import { selection } from "./read-query.js";
@@ -20,6 +21,9 @@ export const discountActionSpecs = Object.entries(discountSchemas).map(([id, sch
20
21
  options: [['--dry-run', 'Validate and preview offline'], ['--idempotency-key <key>', 'Unique operation key; no automatic replay'], ['--output <path>', 'Export the complete response to a new private file']], example: `pancake ${id.replace('.', ' ')} --file input.json --dry-run --json` },
21
22
  endpoint: `/v1/actions/${coupon ? 'coupon' : 'promotion-code'}/${action}-${coupon ? 'coupon' : batch ? 'promotion-codes' : 'promotion-code'}`,
22
23
  documentation,
24
+ authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: coupon ? couponPreview : promotionCodePreview,
25
+ targetResourceId: input => coupon ? action === 'create' ? undefined : input.id : action === 'deactivate' ? input.id : input.couponId,
26
+ resultResourceId: data => batch ? data.batchId : data[key].id,
23
27
  ...(batch ? {} : { responseKey: key }),
24
28
  validateResponse: data => batch
25
29
  ? typeof data.batchId === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(data.batchId) && Array.isArray(data.promotionCodes) && data.promotionCodes.length > 0 && data.promotionCodes.length <= 500 && data.promotionCodes.every(value => entity(value, 'PMC') && typeof value.code === 'string')
@@ -0,0 +1,17 @@
1
+ import { previewFields } from "./action-previews.js";
2
+ function restrictionsPreview(input) {
3
+ return previewFields(input, ['perCustomerLimit', 'maxRedemptions', 'expiresAt', 'minimumAmount']);
4
+ }
5
+ function promotionPreview(input, visible) {
6
+ const result = previewFields(input, visible);
7
+ if (input.restrictions !== undefined)
8
+ result.restrictions = restrictionsPreview(input.restrictions);
9
+ return result;
10
+ }
11
+ export function couponPreview(input) {
12
+ const result = previewFields(input, ['id', 'storeId', 'discount', 'duration', 'durationInPeriods', 'productIds', 'maxRedemptions', 'redeemBy']);
13
+ if (Array.isArray(input.promotionCodes))
14
+ result.promotionCodes = input.promotionCodes.map(item => promotionPreview(item, []));
15
+ return result;
16
+ }
17
+ export const promotionCodePreview = (input) => promotionPreview(input, ['id', 'couponId', 'count', 'length']);
@@ -0,0 +1,5 @@
1
+ export function productPreview(input) {
2
+ return { type: input.type, storeId: input.storeId, name: input.name, prices: input.prices, billingPeriod: input.billingPeriod,
3
+ metadata: input.metadata === undefined ? undefined : '[redacted]', description: input.description === undefined ? undefined : '[redacted]',
4
+ media: input.media === undefined ? undefined : '[redacted]', successUrl: input.successUrl === undefined ? undefined : '[redacted]' };
5
+ }
@@ -0,0 +1,3 @@
1
+ export function webhookPreview(input) {
2
+ return { ...input, ...(input.url !== undefined ? { url: '[redacted]' } : {}), ...(input.secret !== undefined ? { secret: '[redacted]' } : {}) };
3
+ }
@@ -0,0 +1,7 @@
1
+ export const DEFAULT_API_ORIGIN = 'https://api.waffo.ai';
2
+ export function productCreateEndpoint(type) {
3
+ return `/v1/actions/${type}-product/create-product`;
4
+ }
5
+ export function webhookEndpoint(action) {
6
+ return `/v1/actions/store/${action}-webhook`;
7
+ }
@@ -1,6 +1,6 @@
1
1
  # 商户 API 覆盖矩阵
2
2
 
3
- 折扣契约核对日期:2026-11-03;其余文档快照:2026-10-26。2026-11-05 同步当前注册表。适用版本:0.0.1-rc.1;以当前注册表和官方 API 文档索引为准。**62 条命令,覆盖 33 个商户 API-Key REST action 路由**。此处“覆盖”指已提供命令入口,不表示全部字段、客户身份接口或真实商户验收完成。
3
+ 折扣契约核对日期:2026-11-03;其余文档快照:2026-10-26。2026-11-05 同步当前注册表。适用版本:0.0.1-rc.2;以当前注册表和官方 API 文档索引为准。**62 条命令,覆盖 33 个商户 API-Key REST action 路由**。此处“覆盖”指已提供命令入口,不表示全部字段、客户身份接口或真实商户验收完成。
4
4
 
5
5
  本地前缀为 `pnpm cli`;安装后的命令前缀为 `pancake`;`pnpm dev` 只负责自动构建。下表商户业务 REST Actions 远端执行必须 `--yes`,新增 Actions 使用 `--file`,支持 `--idempotency-key`(未给时生成);建议显式传 key 并保留操作编号。输入以 `schema <命令 ID>` 为准。
6
6
 
@@ -145,10 +145,10 @@ CLI 支持商户 Session 和 RSA API Key,具体路由仍由服务端鉴权;`
145
145
 
146
146
  本次新增 9 条命令、6 个 REST 路由,依据 product-service 请求 schema、graphql-service 类型及 gateway 路由源码核对,未猜测公开 API 文档地址。`coupons list/get/create/update/deactivate` 和 `promotion-codes list/create/generate/deactivate` 均已接入;列表/详情使用 `/v1/graphql`,支持离线 dry-run、schema 和 JSON。完整字段与示例见[折扣使用说明](usage.md#discounts)。
147
147
 
148
- 创建券需要店铺 owner/admin;其他折扣路由接受商户身份并由服务端执行店铺和环境访问控制。JWT Session 与 RSA API Key 均在 gateway 配置中允许。折扣列表不返回买家邮箱;写入默认输出不带客户限制,显式私有文件导出保留完整响应。9 条折扣命令已有隔离 Test 环境商户验收证据,包括停用后的查询确认;命令自身写入核验仍为 response_only,生产与完整 CLI 验收尚未完成。
148
+ 创建券需要店铺 owner/admin;其他折扣路由接受商户身份并由服务端执行店铺和环境访问控制。JWT Session 与 RSA API Key 均在 gateway 配置中允许。折扣列表不返回买家邮箱;写入默认输出不带客户限制,显式私有文件导出保留完整响应。9 条折扣命令已有隔离 Test 环境商户验收证据,包括停用后的查询确认;命令自身写入核验仍为 response_only,部分 Production 折扣操作也已通过;不代表全部折扣操作或稳定版已验收。
149
149
 
150
150
  ### Temporary event listener
151
151
 
152
- `listen` verifies identity with `/v1/graphql`, then uses POST `/v1/actions/notification/cli-listen-start`, `cli-listen-poll`, `cli-listen-ack` and `cli-listen-stop`. All require merchant browser-session authorization and store access; RSA is unsupported. Test is default; production requires `--live`. Start/ACK are never retried automatically. Session TTL is 90 seconds, polling interval three seconds, delivery lease 30 seconds and maximum attempts three. No permanent webhook writes or event trigger routes are used. These four browser-session-only routes and the three device-login routes are separate from the 33 merchant API-Key REST action routes above. Relay/gateway support must be deployed separately; production availability is unverified.
152
+ `listen` verifies identity with `/v1/graphql`, then uses POST `/v1/actions/notification/cli-listen-start`, `cli-listen-poll`, `cli-listen-ack` and `cli-listen-stop`. All require merchant browser-session authorization and store access; RSA is unsupported. Test is default; production requires `--live`. Start/ACK are never retried automatically. Session TTL is 90 seconds, polling interval three seconds, delivery lease 30 seconds and maximum attempts three. No permanent webhook writes or event trigger routes are used. These four browser-session-only routes and the three device-login routes are separate from the 33 merchant API-Key REST action routes above. Relay/gateway support is deployed separately. Production listener startup, polling, mode isolation and cleanup passed with the published candidate; real Production payment delivery remains pending.
153
153
 
154
154
  Browser sessions use the server-enforced CLI business permission preset in Test and Production. Existing merchant/store access still applies. Unlisted routes and GraphQL fields, Webhook `secret` fields, account/API Key/payout/bank operations and other-session management are denied. Own-session logout is allowed. RSA permissions are unchanged.
package/docs/usage.md CHANGED
@@ -4,20 +4,20 @@
4
4
 
5
5
  After signing in, check the account and code against your terminal, then click **Authorize CLI**. Only approve a login you started yourself. Authorization expires after 15 minutes; run login again if it expires. The CLI polls for authorization, verifies and saves its separate session, then confirms completion to the page. You can close the tab afterward. If final confirmation fails, the CLI reports an unconfirmed login and asks you to log in again; that credential may expire within five minutes. Deny, expiry or cancellation before saving preserves the existing login.
6
6
 
7
- Run `pnpm cli login` in a terminal, complete Dashboard sign-in, then use `pnpm cli env test` or `pnpm cli env prod`. The CLI verifies the merchant and environment before saving a separate private session. Failed login or environment changes preserve the saved credentials. Environment selection stops if another command has changed or cleared the saved login. Browser-session writes stop before sending when the gateway cannot confirm the selected environment; conflicting evidence in a write response is treated as an unknown outcome, never a safe retry. `logout` revokes the saved browser session before clearing local credentials. RSA logout only clears local references.
7
+ Run `pnpm cli login` in a terminal, complete Dashboard sign-in, then use `pnpm cli env test` or `pnpm cli env prod`. The CLI verifies the merchant and environment before saving a separate private session. Failed login or environment changes preserve the saved credentials. Concurrent login, environment selection or logout returns `CONFIG_CHANGED` if another command has replaced or cleared its configuration snapshot. The newer configuration is preserved; inspect `whoami` before making another change. Browser-session writes stop before sending when the gateway cannot confirm the selected environment; conflicting evidence in a write response is treated as an unknown outcome, never a safe retry. `logout` revokes the saved browser session before clearing local credentials. RSA logout only clears local references.
8
8
 
9
9
  View CLI sessions under Dashboard → Settings → Security. With the matching service support, new logins show the CLI version, operating system, masked IP and approximate IP-based location. Location may be unavailable or reflect a VPN/proxy exit; existing sessions are not backfilled.
10
10
 
11
11
  Use `pnpm cli login --key-login` for the RSA prompt, or explicit Merchant ID/key-file flags for automation. RSA keys keep their server-assigned environment. Browser login requires the new Dashboard, gateway and user-service routes to be deployed. For local integration, pass `--dashboard-url http://127.0.0.1:3000 --api-url http://127.0.0.1:3002` to login.
12
12
 
13
13
 
14
- 适用版本:0.0.1-rc.1 候选版。以下示例中的 `pnpm cli` 用于源码目录;通过 npm 安装后,替换为 `pancake`,其余参数不变。本说明随安装包提供,无需 GitHub 权限。
14
+ 适用版本:0.0.1-rc.2 候选版。以下示例中的 `pnpm cli` 用于源码目录;通过 npm 安装后,替换为 `pancake`,其余参数不变。本说明随安装包提供,无需 GitHub 权限。
15
15
 
16
16
  ## 当前能力与边界
17
17
 
18
18
  | 能力 | 当前状态 |
19
19
  | --- | --- |
20
- | 单凭证登录/退出、当前身份、店铺/商品查询 | 已实现;部分流程已有隔离 Test 环境证据,完整验收待完成 |
20
+ | 单凭证登录/退出、当前身份、店铺/商品查询 | 已实现;生产登录、退出撤销及部分 Test/Production 查询已验证 |
21
21
  | webhook 查询、添加、修改、删除 | 已实现;写入只允许测试回调配置 |
22
22
  | 店铺、商品、订阅商品组管理 | 创建、修改、状态与发布等商户 Actions;真实操作必须加 `--yes` |
23
23
  | 结账、订阅取消、退款工单、客户 Token、通知联系人、内容检查 | 已实现;Token/结账链接必须导出到私有文件 |
@@ -26,13 +26,14 @@ Use `pnpm cli login --key-login` for the RSA prompt, or explicit Merchant ID/key
26
26
  | 操作记录、脱敏调试、自检、诊断导出 | 已实现 |
27
27
  | 本地 webhook 监听 | 已实现;仅浏览器会话,需要独立部署 relay/gateway 支持 |
28
28
  | 模拟事件发送 | 尚未实现 |
29
- | npm / npx / Homebrew 正式分发 | 流程已准备;首次正式发版尚未执行 |
29
+ | npm / npx | `0.0.1-rc.2` 候选版使用 `next` 渠道 |
30
+ | Homebrew | 等待首个稳定版;候选版不进入正式配方 |
30
31
 
31
32
  当前注册表共 **62 条命令**,覆盖官方索引中的 **33 个商户 API-Key REST 路由**;字段和认证限制见[完整覆盖矩阵](api-coverage.md)。这不代表所有客户侧接口或所有可选字段均开放。
32
33
 
33
34
  后端通过匹配 RSA 密钥区分测试和生产,两种密钥均可登录。CLI 已接入网关的 `X-Waffo-Environment: test|prod` 响应头,登录、查询结果和调试记录使用本次请求的环境,不需要用户手选。
34
35
 
35
- **部署边界:** 环境响应头、网页登录和本地监听依赖配套服务独立部署;隔离 Test 环境已取得部分验证证据,生产可用性尚未确认。缺失或无效的响应头仍显示 `Environment: Unknown (unverified)`;不能把“商户身份验证成功”当成环境已确认。用 `pnpm cli whoami` 核验当前请求。
36
+ **部署边界:** 环境响应头、网页登录和本地监听依赖配套服务独立部署;生产网页登录、环境识别及监听连接已于 2026-11-17 使用已发布候选版验证;生产真实支付通知仍待验收。缺失或无效的响应头仍显示 `Environment: Unknown (unverified)`;不能把“商户身份验证成功”当成环境已确认。用 `pnpm cli whoami` 核验当前请求。
36
37
 
37
38
  写操作必须先验证环境并加 `--yes`。生产写入、测试发布到生产还需 `--confirm-production`;店铺和通知收件人变更属于测试/生产共享配置,还需 `--confirm-shared`,在生产执行时两个确认都要有。无需再次网页登录,原有后端权限不变。预览会说明影响范围和所需确认,但离线无法验证当前环境;实际执行和操作记录会标明 `impact`:`test`、`prod`、`shared` 或 `test-to-prod`。未知结果不自动重试,Webhook 写入仍仅限测试。
38
39
 
@@ -333,7 +334,7 @@ pnpm cli stores list --no-interactive --json
333
334
  }
334
335
  ```
335
336
 
336
- 上例展示输出格式,不代表实际执行了某次操作。退出码:0 成功,1 执行或核验失败,2 参数/配置错误,130 中断。`--dry-run` 成功时仍应检查 `data.executed:false`。
337
+ 上例展示输出格式,不代表实际执行了某次操作。退出码:0 成功,1 执行或核验失败,2 参数/配置错误,130 中断。写入被明确拒绝时保留原退出码;结果未知统一为 `OUTCOME_UNKNOWN`、退出码 1。`--dry-run` 成功时仍应检查 `data.executed:false`。
337
338
 
338
339
  ## 8. 排障与追溯
339
340
 
@@ -357,13 +358,13 @@ pnpm cli diagnostics export --operation OPERATION_ID --output ./diagnostics.json
357
358
 
358
359
  服务端未返回请求编号时 `requestId:null`。本地 `operationId` 不是服务端审计编号,共用密钥也无法准确归因到某位员工或 Agent。
359
360
 
360
- 同一本地记录目录内,已用的幂等 key 会被阻止重放。此机制不覆盖其他电脑、不同目录或记录清理后的操作,服务端去重仍受其自身规则约束。记录上限 1000 条;新操作时清理 30 天前已完成/已拒绝记录。达到上限时,优先轮转最旧的已完成/已拒绝查询记录;未过期的写入记录、未知或待核验记录不会因此删除。若保留记录仍占满上限,写入会停止。已知目标的写操作会在发请求前记录目标 ID、接口、服务地址和所选环境,便于响应丢失后核查。
361
+ 同一本地记录目录内,已用的幂等 key 会被阻止重放。此机制不覆盖其他电脑、不同目录或记录清理后的操作,服务端去重仍受其自身规则约束。记录上限 1000 条;新操作时清理 30 天前已完成/已拒绝记录。达到上限时,优先轮转最旧的已完成/已拒绝查询记录;未过期的写入记录、未知或待核验记录不会因此删除。若保留记录仍占满上限,写入会停止。所有写操作在业务请求前记录商户、输入摘要、影响范围、确切接口与 API 服务地址;已知店铺和目标 ID 一并记录,所选环境仅来自浏览器凭证,RSA 不产生本地环境选择。商品创建也记录具体的 onetime/subscription 接口。Checkout 的 `targetResourceId` 是商品,`resourceId` 是返回的 session;优惠码批次使用 `batchId` 作为结果 ID。客户 token 和内容检查的 requestId 不作为资源 ID。远端已接受后,回查、导出或操作记录更新失败的错误仍包含已知结果 ID;若本地记录始终无法更新,初始意图仍保留供核查,不重复发送请求。
361
362
 
362
363
  默认目录:macOS / Linux 为 `~/.waffo-pancake`;Windows 为 `%USERPROFILE%\.waffo-pancake`。登录凭证保存在其中的 `config.json`。从旧目录升级后需重新登录;旧文件不自动迁移。可用 `WAFFO_CONFIG_DIR` 指向专用目录,不应指向多人共享目录。配置格式为版本 2,操作记录格式仍为版本 1。旧配置版本 1 不自动迁移:显式运行 `logout` 清空旧配置,再用现有密钥文件 `login`。`logout` 可重置能够安全读取的损坏配置,但拒绝符号链接和非普通文件。未知的更高版本始终拒绝改写,包括退出操作。
363
364
 
364
365
  ## 9. 发布后的安装、更新和回退
365
366
 
366
- 候选版使用 `next` 渠道,须等维护者完成 npm 发布后使用:
367
+ `0.0.1-rc.2` 候选版使用 `next` 渠道,安装命令:
367
368
 
368
369
  ```sh
369
370
  npm install -g @waffo/pancake-cli@next
@@ -403,13 +404,13 @@ CLI 不提供独立自更新器,任务执行中不自动换版本。回退前
403
404
 
404
405
  ## 验收尚未完成的部分
405
406
 
406
- 部分浏览器登录、商品、折扣与监听流程已有 Test 环境证据,跨平台 CI 与 Windows ACL 自动测试已通过。生产完整验收、首次发布后的 npm 安装及真实 Windows 终端 Ctrl+C 验收仍需完成。本地测试与单项远端证据不替代这些验收。
407
+ 已发布候选版的 npm/npx 安装、生产登录与退出撤销、Test/Production 部分商品和折扣操作均已通过。Test 模拟支付已验证通知转发、签名、重试及清理;Production 监听连接、轮询、环境隔离及清理已通过。剩余:生产真实支付通知、真实 Windows 终端 Ctrl+C 和首个稳定版的 Homebrew 安装。以上不代表所有命令均完成真实业务验收。
407
408
 
408
409
  开源客户端的使用和开发不要求取得私有服务端源码。联网命令需要可访问、兼容的托管 API 与凭证;网页登录还需要兼容的 Dashboard。离线命令发现、schema 和预览不需要运行服务端。
409
410
 
410
411
  ## Discounts
411
412
 
412
- Nine commands cover coupons and promotion codes. Browser sessions and RSA keys are supported by the gateway route configuration; coupon creation requires store owner/admin permission. Other operations remain subject to server-enforced merchant, store and environment access. All nine discount commands passed isolated Test-environment merchant acceptance, including final deactivation read-back. Production and full CLI release acceptance remain unverified.
413
+ Nine commands cover coupons and promotion codes. Browser sessions and RSA keys are supported by the gateway route configuration; coupon creation requires store owner/admin permission. Other operations remain subject to server-enforced merchant, store and environment access. All nine discount commands passed isolated Test-environment merchant acceptance, including final deactivation read-back. Selected Production coupon and promotion-code operations also passed; acceptance does not cover every discount operation or the full stable release.
413
414
 
414
415
  ```sh
415
416
  pnpm cli coupons list --store-id STO_example --limit 20 --json
@@ -430,6 +431,8 @@ pnpm cli promotion-codes generate --file batch.json --yes --idempotency-key laun
430
431
 
431
432
  `coupon-scope.json` contains `{"couponId":"CPN_0000000000000000000001"}`. Replace the example ID with the actual returned coupon ID. `batch.json` adds `"count":10`, optionally `"prefix":"VIP-"` and `"length":10`. Generation accepts 1–500 codes, a 1–12 character prefix, and 8–16 random characters. Codes are letters, digits or hyphens, 3–32 characters; the server normalizes them to uppercase.
432
433
 
434
+ Offline discount previews show amount/percentage, duration and period count, product scope, redemption/expiry limits, couponId and generation count/length. Customer email restrictions remain redacted, including nested promotion codes. Previews preserve explicit null values and do not create operation records or output files.
435
+
433
436
  Fixed discounts use `"discount":{"type":"fixed_amount","amountOff":{"USD":"5.00"}}`. Amounts are positive display-format strings; currency precision is checked by the server. A repeating duration requires positive `durationInPeriods`; once/forever do not accept a non-null period count. Coupon expiry and promotion-code expiry must be more than 60 seconds in the future. Limits and applicability are checked again by the server against current coupon state.
434
437
 
435
438
  `coupons update` accepts only `id` and `name`. `coupons deactivate` and `promotion-codes deactivate` accept `id`; deactivation is permanent and releases the code for reuse. Deactivating a coupon disables its active promotion codes. `promotion-codes create` accepts `couponId`, optional `code` and `restrictions`. Up to 20 promotion codes can also be supplied as `promotionCodes` during coupon creation. Supported restrictions are `customerEmails` (up to 100), `perCustomerLimit`, `maxRedemptions`, `expiresAt` and `minimumAmount`. `firstTimeOnly` and `dailyRedemptionLimit` are currently unsupported.
@@ -446,7 +449,7 @@ The loopback receiver receives the exact signed body and the allowlisted Content
446
449
 
447
450
  `--json` and piped output stream NDJSON standard envelopes with `ready`, `delivery`, `stopped` events and a terminal error envelope on failure. Event bodies, signatures and response bodies are omitted. Ctrl+C/SIGTERM clean up temporary sessions; kill/crash falls back to a 90-second session TTL. Polls occur every three seconds. Local forwarding times out after ten seconds. Session failures are visible and exit nonzero. The command never modifies configured webhook endpoints and provides no synthetic event trigger.
448
451
 
449
- Isolated Test acceptance verified a test payment event, signatures, retry after HTTP 500, and interruption cleanup. Production listening remains unverified.
452
+ Isolated Test acceptance verified a test payment event, signatures, retry after HTTP 500, and interruption cleanup. The production deployment also passed Test sandbox-payment delivery and Production listener startup, polling, isolation and cleanup. Real Production payment delivery remains pending.
450
453
 
451
454
  ## Browser permission limits
452
455
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waffo/pancake-cli",
3
- "version": "0.0.1-rc.1",
3
+ "version": "0.0.1-rc.2",
4
4
  "packageManager": "pnpm@11.25.0",
5
5
  "description": "Developer CLI for Waffo Pancake",
6
6
  "type": "module",