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

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,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.1-rc.3
4
+
5
+ Release candidate for npm’s `next` channel. No stable release.
6
+
7
+ - Point the packaged CLI agent reference to the official Docs page while retaining the bundled offline `SKILL.md`.
8
+ - Add `graphql query --background` for recurring reads that skip local operation records while retaining authenticated context and private response export.
9
+ - Pass an explicit local archive path to the manual npm publishing command.
10
+
3
11
  ## 0.0.1-rc.2
4
12
 
5
13
  Release candidate for npm’s `next` channel. No stable release.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Developer CLI for Waffo Pancake, built with TypeScript, Node.js and Commander. The official TypeScript compiler builds the CLI.
4
4
 
5
- **Release candidate: 0.0.1-rc.2, using npm’s `next` channel. No stable release yet.** Implemented: 62 commands covering merchant authentication, resource queries, 33 supported merchant API-Key REST action routes within the scope below, read-only GraphQL, offline previews, operation records and redacted diagnostics. Manage stores, products, subscription groups, checkout sessions, subscription cancellation, refund tickets, customer session tokens, notification recipients, content-safety checks, coupons, promotion codes and test webhooks. Temporary local webhook listening is available for browser sessions; event triggering is not implemented. This is separate from the Pancake migration CLI.
5
+ **Release candidate: 0.0.1-rc.3, 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
 
@@ -20,9 +20,9 @@ JSON
20
20
  pnpm cli products create --type onetime --file product.json --dry-run --json
21
21
  ```
22
22
 
23
- See the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/docs/usage.md) for input examples and safe operations, and the [API coverage matrix](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/docs/api-coverage.md) for every command, endpoint and authentication boundary. `commands`, `schema` and supported `--dry-run` options work offline without credentials. Pipe output or use `--json` for one JSON envelope (`listen` streams NDJSON envelopes); debugging goes to stderr. Monetary amounts are decimal strings.
23
+ See the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/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.3/docs/api-coverage.md) for every command, endpoint and authentication boundary. `commands`, `schema` and supported `--dry-run` options work offline without credentials. Pipe output or use `--json` for one JSON envelope (`listen` streams NDJSON envelopes); debugging goes to stderr. Monetary amounts are decimal strings.
24
24
 
25
- Documentation links serve the published npm package through jsDelivr; no GitHub access is needed. They are versioned snapshots, so later repository edits appear only in a new package release. The same Markdown guides ship in the package for offline reading. For a global npm installation, run `npm root -g` and open `@waffo/pancake-cli/docs/usage.md` under that directory. In a source checkout, open `docs/usage.md` directly.
25
+ The agent reference is hosted on official Docs and identifies the release it documents; use the bundled `SKILL.md` for your installed CLI. Other documentation links serve the published npm package through jsDelivr; no GitHub access is needed. They are versioned snapshots, so later repository edits appear only in a new package release. The same Markdown guides ship in the package for offline reading. For a global npm installation, run `npm root -g` and open `@waffo/pancake-cli/docs/usage.md` under that directory. In a source checkout, open `docs/usage.md` directly.
26
26
 
27
27
  CLI prompts and help use concise English. In a terminal, `pnpm cli` shows the first-use steps, `commands` prints a compact command list, and `whoami` explains how to log in when no credentials are present. Use `--json` (or pipe stdout) for the complete machine envelope. Local pnpm/npm script help uses the corresponding local command; installed CLI help uses `pancake`.
28
28
 
@@ -75,17 +75,19 @@ The expanded action commands use `--file input.json`, require `--yes`, and suppo
75
75
 
76
76
  Checkout and customer-session creation require `--output` to a new private file. Customer-session issuance requires RSA login; browser login is unsupported for this command. It is not CLI login. Arbitrary `graphql query` and `analytics query` also require private output for execution; their parser rejects mutations, subscriptions and multiple operations before credentials or network access. There is no raw REST passthrough. Customer-token-only order cancellation/reactivation is outside merchant coverage. Product create/update rejects `taxIncluded`; webhook writes remain test-only. No real merchant acceptance or release is implied by route coverage.
77
77
 
78
+ For recurring read-only queries, `pancake graphql query --background --file query.json --output ./query-result.json --json` skips the local operation record for that invocation. Use a fresh private output path for each call. The gateway must verify the environment before the response can be exported, and a browser session must match its selected environment. Authenticated results include the effective `meta.apiOrigin` and set `meta.operationId` to `null`.
79
+
78
80
  Configuration uses version 2. Legacy version 1 is not migrated: run `logout`, then `login` with your existing key. Unknown future versions are never overwritten, including by logout. Concurrent login, environment selection or logout returns `CONFIG_CHANGED` if another command replaced or cleared its saved configuration; the newer configuration is preserved. Inspect `whoami` before starting another login or environment change.
79
81
 
80
82
  ## Install the release candidate
81
83
 
82
- Version `0.0.1-rc.2` uses npm's `next` channel. Use the explicit channel or version while evaluating the candidate:
84
+ Version `0.0.1-rc.3` uses npm's `next` channel. Use the explicit channel or version while evaluating the candidate:
83
85
 
84
86
  ```sh
85
87
  npm install -g @waffo/pancake-cli@next
86
88
  pancake --version
87
89
  # Or run the exact candidate without a global installation:
88
- npx @waffo/pancake-cli@0.0.1-rc.2 --help
90
+ npx @waffo/pancake-cli@0.0.1-rc.3 --help
89
91
  ```
90
92
 
91
93
  For the hosted service, no URL overrides are needed:
@@ -180,7 +182,7 @@ Package smoke tests install the actual tarball in isolated directories and exerc
180
182
  - Homebrew: CLI CI installs the tested package artifact on macOS/Linux using pinned public tap tooling, without publishing it. The [tap](https://github.com/waffo-com/homebrew-pancake) detects stable npm versions, verifies integrity and tests installation before updating.
181
183
  - Weekly Dependabot updates cover dependencies and pinned Actions.
182
184
 
183
- See the [agent reference](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/SKILL.md) and [changelog](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/CHANGELOG.md). Maintainer release instructions are in `docs/release/README.md` in the source repository and require repository access.
185
+ See the [agent reference](https://docs.waffo.ai/waffo-pancake-cli-skill) and [changelog](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/CHANGELOG.md). Maintainer release instructions are in `docs/release/README.md` in the source repository and require repository access.
184
186
 
185
187
  Internal planning documents are maintained outside the source repository. The published `0.0.1-rc.1` candidate passed npm/npx installation checks and selected business operations in Test and Production. Production login and logout revocation, 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.
186
188
 
@@ -211,9 +213,9 @@ Overrides accept HTTPS, or HTTP on `127.0.0.1` only. No URL credentials, paths,
211
213
 
212
214
  ## Contributing and security
213
215
 
214
- See [CONTRIBUTING.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/CONTRIBUTING.md) for development and validation, and [SECURITY.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/SECURITY.md) for handling credentials and reporting vulnerabilities. Licensed under [MIT](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/LICENSE).
216
+ See [CONTRIBUTING.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/CONTRIBUTING.md) for development and validation, and [SECURITY.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/SECURITY.md) for handling credentials and reporting vulnerabilities. Licensed under [MIT](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/LICENSE).
215
217
 
216
- Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). Offline previews show discount amounts or percentages, duration, product scope, redemption limits, coupon IDs and batch count/length. Customer email restrictions remain redacted, including inside nested promotion codes. See the Discounts section in the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.2/docs/usage.md). Gateway source permits browser sessions and RSA keys; merchant/store permissions still apply. Discount writes have response-only verification; the nine discount commands passed isolated Test-environment merchant acceptance, including final deactivation read-back. Selected coupon and promotion-code operations also passed Production acceptance; this does not establish coverage of every discount operation or full stable-release acceptance.
218
+ Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). Offline previews show discount amounts or percentages, duration, product scope, redemption limits, coupon IDs and batch count/length. Customer email restrictions remain redacted, including inside nested promotion codes. See the Discounts section in the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/docs/usage.md). Gateway source permits browser sessions and RSA keys; merchant/store permissions still apply. Discount writes have response-only verification; the nine discount commands passed isolated Test-environment merchant acceptance, including final deactivation read-back. Selected coupon and promotion-code operations also passed Production acceptance; this does not establish coverage of every discount operation or full stable-release acceptance.
217
219
 
218
220
  ## Listen to merchant events locally
219
221
 
package/SKILL.md CHANGED
@@ -5,7 +5,7 @@ description: Discover and use the Waffo Pancake CLI for merchant API operations,
5
5
 
6
6
  # Waffo Pancake CLI
7
7
 
8
- Release candidate: `0.0.1-rc.2`, using the `next` channel. Install with `npm install -g @waffo/pancake-cli@next`, or use `npx @waffo/pancake-cli@0.0.1-rc.2`. In a source checkout, use `pnpm cli` after `pnpm install --frozen-lockfile && pnpm run build`. Runtime and development require Node.js >=22.14; Node.js 24 LTS is recommended for development. Use the pinned pnpm 11.25.0.
8
+ Release candidate: `0.0.1-rc.3`, using the `next` channel. Install with `npm install -g @waffo/pancake-cli@next`, or use `npx @waffo/pancake-cli@0.0.1-rc.3`. 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
 
@@ -65,6 +65,8 @@ Production writes require `--yes --confirm-production`. `products publish` and `
65
65
 
66
66
  `graphql query` and `analytics query` accept a JSON file containing `query` and optional `variables`. A real parser rejects mutations, subscriptions and multiple operations before credentials/network, including dry-run. Real execution requires private `--output` because arbitrary aliases/fragments can contain secrets. There is no raw REST passthrough. Group query fields must be confirmed using official documentation/introspection before use; do not invent a group root field. Customer-token-only onetime cancellation, customer subscription cancellation and reactivation are excluded from merchant scope.
67
67
 
68
+ For recurring reads, opt into `graphql query --background` to skip the local operation record for that call. Supply a fresh private `--output` for every execution. Responses are exported only after the gateway verifies the environment, which must match the selection for browser sessions. Authenticated responses include the effective `meta.apiOrigin` and a null `meta.operationId`. When a `RATE_LIMITED` error has `error.details.retryAfterMs`, wait at least that many milliseconds before the next request.
69
+
68
70
  ## Remote changes
69
71
 
70
72
  `products create --type onetime|subscription --file product.json --yes --idempotency-key KEY` creates a real product using the effective credential environment. Review the merchant, store, name and prices before confirming. The CLI requires verified environment evidence before writing and requires explicit production confirmation for Production. Subscription input requires `billingPeriod`; trial prices require positive `metadata.trialDays`. For product creation or updates, do not supply `taxIncluded`: the backend fixes tax-exclusive pricing and this CLI rejects that option. Results contain safe product fields; descriptions, metadata and URLs are omitted.
@@ -3,20 +3,8 @@ import { execFile } from 'node:child_process';
3
3
  import { promisify } from 'node:util';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
5
  import pkg from '../../package.json' with { type: 'json' };
6
+ import { serviceOrigin } from "../contracts/action-routes.js";
6
7
  import { CliError } from "../contracts/errors.js";
7
- export function serviceOrigin(value) {
8
- let url;
9
- try {
10
- url = new URL(value);
11
- }
12
- catch {
13
- throw new CliError('INVALID_ARGUMENT', 'Provide a valid API or Dashboard origin.', { exitCode: 2 });
14
- }
15
- if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === '127.0.0.1'))) {
16
- throw new CliError('INVALID_ARGUMENT', 'Service URLs must be HTTPS origins, or explicit http://127.0.0.1:<port> origins for local testing.', { exitCode: 2 });
17
- }
18
- return url.origin;
19
- }
20
8
  async function openBrowser(url) {
21
9
  const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? windowsSystemTool('browser') : 'xdg-open';
22
10
  const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
@@ -3,7 +3,7 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
3
  import { atomicJson, readJson, protectDirectory, withDirectoryLock, exportPrivateFile, hasCode } from "./files.js";
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { lstat, unlink } from 'node:fs/promises';
6
- import { serviceOrigin } from "./browser-login.js";
6
+ import { serviceOrigin } from "../contracts/action-routes.js";
7
7
  import { CliError } from "../contracts/errors.js";
8
8
  export function configDirectory(env = process.env) {
9
9
  if (env.WAFFO_CONFIG_DIR)
@@ -1,13 +1,13 @@
1
1
  import { createHash, createPrivateKey, randomUUID, sign } from 'node:crypto';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
- import { DEFAULT_API_ORIGIN, productCreateEndpoint, webhookEndpoint } from "../../contracts/action-routes.js";
3
+ import { DEFAULT_API_ORIGIN, productCreateEndpoint, serviceOrigin, webhookEndpoint } from "../../contracts/action-routes.js";
4
4
  import { CliError } from "../../contracts/errors.js";
5
- import { serviceOrigin } from "../browser-login.js";
6
5
  import { readPrivateKey } from "../files.js";
7
6
  import { ME_QUERY, PRODUCT_QUERIES, STORES_QUERY, WEBHOOKS_QUERY, WEBHOOK_SECRETS_QUERY } from "./queries.js";
8
7
  import { graphqlValidationError } from "./graphql-errors.js";
9
8
  import { conflictError } from "./conflict-error.js";
10
9
  import { httpErrorReason } from "./http-error-reason.js";
10
+ import { parseRetryAfter } from "./retry-after.js";
11
11
  export function parsePrivateKey(raw) {
12
12
  let value = raw.trim().replace(/\\n/g, '\n');
13
13
  if (!value.startsWith('-----BEGIN'))
@@ -22,12 +22,12 @@ export function parsePrivateKey(raw) {
22
22
  throw new CliError('INVALID_KEY', 'A valid RSA private key in PKCS#8 or PKCS#1 format is required.', { exitCode: 2, stage: 'credentials' });
23
23
  }
24
24
  }
25
- function apiError(status, write, reason, requestId, session = false) {
25
+ function apiError(status, write, reason, requestId, session = false, retryAfterMs) {
26
26
  const codes = { 400: 'INVALID_REQUEST', 401: 'AUTH_FAILED', 403: 'PERMISSION_DENIED', 404: 'NOT_FOUND', 429: 'RATE_LIMITED' };
27
27
  const unknown = write && (status >= 500 || status === 409 || (status >= 200 && status < 300));
28
28
  const message = unknown ? 'The write result is unknown; do not create a new operation to retry it.' : status === 401 && session ? 'Your login was not accepted. Run login again.' : 'The API rejected or could not complete the request.';
29
29
  return new CliError(unknown ? 'OUTCOME_UNKNOWN' : codes[status] ?? 'REMOTE_ERROR', reason ? `${message} Server reason: ${reason}` : message, {
30
- stage: 'api', outcome: unknown ? 'unknown' : 'rejected', details: { status, ...(requestId ? { requestId } : {}) },
30
+ stage: 'api', outcome: unknown ? 'unknown' : 'rejected', details: { status, ...(requestId ? { requestId } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) },
31
31
  recovery: unknown ? 'Inspect the operation record and query the affected resource before taking further action.' : 'Check credentials, store access and command input. Run doctor for connection checks.',
32
32
  });
33
33
  }
@@ -68,9 +68,9 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
68
68
  throw new CliError('INVALID_CONFIG', 'Select a valid session environment.', { exitCode: 2 });
69
69
  const raw = credentials.privateKey ?? (credentials.privateKeyFile ? await readPrivateKey(credentials.privateKeyFile) : '');
70
70
  const key = credentials.sessionToken ? undefined : parsePrivateKey(raw);
71
- async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal, singleAttempt = false) {
71
+ async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal, options = {}) {
72
72
  const serialized = JSON.stringify(body);
73
- const write = idempotencyKey !== undefined || singleAttempt;
73
+ const write = idempotencyKey !== undefined || options.singleAttempt === true;
74
74
  const deadline = Date.now() + 20000;
75
75
  for (let index = 0;; index++) {
76
76
  const started = Date.now(), timestamp = Math.floor(started / 1000).toString();
@@ -111,8 +111,9 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
111
111
  if (!response.ok) {
112
112
  const retryable = response.status === 429 || response.status >= 500;
113
113
  const retryHeader = response.headers.get('retry-after');
114
- const retryMs = retryHeader ? (/^\d+$/.test(retryHeader) ? Number(retryHeader) * 1000 : Math.max(0, Date.parse(retryHeader) - Date.now())) : 100 * (index + 1);
115
- if (!signal?.aborted && !write && retryable && index < 2 && Number.isFinite(retryMs) && Date.now() + retryMs < deadline) {
114
+ const retryAfterMs = retryHeader ? parseRetryAfter(retryHeader) : undefined;
115
+ const retryMs = retryHeader ? retryAfterMs : 100 * (index + 1);
116
+ if (!signal?.aborted && !write && retryable && index < 2 && retryMs !== undefined && Date.now() + retryMs < deadline) {
116
117
  await delay(retryMs);
117
118
  continue;
118
119
  }
@@ -122,7 +123,8 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
122
123
  throw conflict;
123
124
  }
124
125
  const reason = httpErrorReason(response.status, envelope, [credentials.sessionToken ?? '', raw, headers['X-Signature'] ?? '']);
125
- throw apiError(response.status, write, reason, attempt.requestId, Boolean(credentials.sessionToken));
126
+ const retryHint = options.includeRetryAfter && response.status === 429 ? retryAfterMs : undefined;
127
+ throw apiError(response.status, write, reason, attempt.requestId, Boolean(credentials.sessionToken), retryHint);
126
128
  }
127
129
  if (Array.isArray(envelope.errors) && envelope.errors.length > 0) {
128
130
  if (!write && path === '/v1/graphql' && response.status === 200 && 'query' in body && typeof body.query === 'string') {
@@ -143,7 +145,19 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
143
145
  return { data: envelope.data, environment: attempt.environment };
144
146
  }
145
147
  }
146
- async function query(query, variables = {}) { return (await post('/v1/graphql', { query, variables })).data; }
148
+ const query = async (query, variables = {}, options) => {
149
+ const { data, environment } = await post('/v1/graphql', { query, variables }, undefined, false, undefined, { includeRetryAfter: options?.background });
150
+ if (options?.background) {
151
+ if (!environment)
152
+ throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the credential environment. No result was exported.', { stage: 'api' });
153
+ if (credentials.sessionToken && environment !== credentials.environment) {
154
+ throw new CliError('ENVIRONMENT_MISMATCH', 'The gateway did not confirm the selected environment. No result was exported.', {
155
+ stage: 'api', details: { selectedEnvironment: credentials.environment },
156
+ });
157
+ }
158
+ }
159
+ return data;
160
+ };
147
161
  return {
148
162
  query,
149
163
  async revokeSession() {
@@ -159,7 +173,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
159
173
  if (typeof payload.jti !== 'string' || !/^mer_[A-Za-z0-9_-]{16}$/.test(payload.jti))
160
174
  throw new CliError('INVALID_CONFIG', 'Saved session ID is invalid. Revoke it in Dashboard Security.');
161
175
  try {
162
- const result = await post('/v1/actions/merchant/sign-out-session', { jti: payload.jti }, undefined, false, undefined, true);
176
+ const result = await post('/v1/actions/merchant/sign-out-session', { jti: payload.jti }, undefined, false, undefined, { singleAttempt: true });
163
177
  if (result.data.success !== true)
164
178
  throw new Error('Revocation not confirmed');
165
179
  return true;
@@ -174,7 +188,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
174
188
  if (!['start', 'poll', 'ack', 'stop'].includes(action))
175
189
  throw new CliError('INVALID_ARGUMENT', 'Invalid listener action.', { exitCode: 2 });
176
190
  try {
177
- return (await post(`/v1/actions/notification/cli-listen-${action}`, body, undefined, false, signal, true)).data;
191
+ return (await post(`/v1/actions/notification/cli-listen-${action}`, body, undefined, false, signal, { singleAttempt: true })).data;
178
192
  }
179
193
  catch (error) {
180
194
  if (error instanceof CliError && error.code === 'OUTCOME_UNKNOWN')
@@ -0,0 +1,46 @@
1
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
2
+ const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
3
+ const imfFixdate = /^(?<weekday>[A-Z][a-z]{2}), (?<day>\d{2}) (?<month>[A-Z][a-z]{2}) (?<year>\d{4}) (?<time>\d{2}:\d{2}:\d{2}) GMT$/;
4
+ const rfc850Date = /^(?<weekday>[A-Z][a-z]{5,8}), (?<day>\d{2})-(?<month>[A-Z][a-z]{2})-(?<year>\d{2}) (?<time>\d{2}:\d{2}:\d{2}) GMT$/;
5
+ const asctimeDate = /^(?<weekday>[A-Z][a-z]{2}) (?<month>[A-Z][a-z]{2}) (?<day>\d{2}| \d) (?<time>\d{2}:\d{2}:\d{2}) (?<year>\d{4})$/;
6
+ function httpDate(value, now) {
7
+ const parts = imfFixdate.exec(value)?.groups ?? rfc850Date.exec(value)?.groups ?? asctimeDate.exec(value)?.groups;
8
+ if (!parts)
9
+ return;
10
+ const month = months.indexOf(parts.month) + 1;
11
+ if (!month)
12
+ return;
13
+ const leapSecond = parts.time === '23:59:60';
14
+ const time = leapSecond ? '23:59:59' : parts.time;
15
+ const dateAndTime = `${String(month).padStart(2, '0')}-${parts.day.trimStart().padStart(2, '0')}T${time}`;
16
+ const shortYear = parts.year.length === 2;
17
+ let year = Number(parts.year);
18
+ if (shortYear) {
19
+ // Resolve the latest matching year no more than 50 years in the future.
20
+ const limit = new Date(now);
21
+ limit.setUTCFullYear(limit.getUTCFullYear() + 50);
22
+ year += Math.floor(limit.getUTCFullYear() / 100) * 100;
23
+ const candidate = new Date(`${year}-${dateAndTime}Z`).getTime();
24
+ if (candidate + (leapSecond ? 1000 : 0) > limit.getTime())
25
+ year -= 100;
26
+ }
27
+ if (year < 1900)
28
+ return;
29
+ const normalized = `${String(year).padStart(4, '0')}-${dateAndTime}`;
30
+ const date = new Date(`${normalized}Z`);
31
+ if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 19) !== normalized)
32
+ return;
33
+ const weekday = weekdays[date.getUTCDay()];
34
+ if (parts.weekday !== (shortYear ? weekday : weekday.slice(0, 3)))
35
+ return;
36
+ return date.getTime() + (leapSecond ? 1000 : 0);
37
+ }
38
+ /** Parse RFC 9110 delay-seconds and HTTP-date without permissive date coercion. */
39
+ export function parseRetryAfter(value, now = Date.now()) {
40
+ if (/^\d+$/.test(value)) {
41
+ const milliseconds = Number(value) * 1000;
42
+ return Number.isSafeInteger(milliseconds) ? milliseconds : undefined;
43
+ }
44
+ const timestamp = httpDate(value, now);
45
+ return timestamp === undefined ? undefined : Math.max(0, timestamp - now);
46
+ }
@@ -28,7 +28,7 @@ export async function executeApiRead(spec, request, options, services) {
28
28
  const output = options.output ? await services.prepareOutput(options.output) : undefined;
29
29
  try {
30
30
  return await readOperation(spec.definition.id, options, services, async (gateway) => {
31
- const response = await gateway.query(request.query, request.variables);
31
+ const response = await gateway.query(request.query, request.variables, spec.definition.id === 'graphql.query' && options.background ? { background: true } : undefined);
32
32
  if (output) {
33
33
  await output.commit(`${JSON.stringify(response, null, 2)}\n`);
34
34
  return { output: options.output, exported: true };
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_API_ORIGIN, serviceOrigin } from "../contracts/action-routes.js";
1
2
  import { safeError } from "../contracts/errors.js";
2
3
  import { credentialContext, contextualError } from "./auth-context.js";
3
4
  export async function readOperation(id, options, services, work, suppliedCredentials) {
@@ -6,25 +7,32 @@ export async function readOperation(id, options, services, work, suppliedCredent
6
7
  }
7
8
  export async function authenticatedOperation(id, options, services, credentials, work) {
8
9
  const attempts = [];
10
+ const background = id === 'graphql.query' && options.background;
9
11
  let operationId;
10
- try {
11
- operationId = (await services.operations.begin({ command: id, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId: credentials.storeId })).operationId;
12
- }
13
- catch {
14
- services.diagnostic({ level: 'warning', code: 'OPERATION_RECORD_UNAVAILABLE' });
12
+ let apiOrigin;
13
+ if (!background) {
14
+ try {
15
+ operationId = (await services.operations.begin({ command: id, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId: credentials.storeId })).operationId;
16
+ }
17
+ catch {
18
+ services.diagnostic({ level: 'warning', code: 'OPERATION_RECORD_UNAVAILABLE' });
19
+ }
15
20
  }
21
+ const metadata = () => ({ ...credentialContext(credentials, attempts), ...(apiOrigin ? { apiOrigin } : {}), operationId: operationId ?? null, requestId: attempts.at(-1)?.requestId ?? null });
16
22
  const observer = (event) => { attempts.push(event); if (options.debug)
17
23
  services.diagnostic({ stage: 'api', ...event }); };
18
24
  try {
25
+ if (background)
26
+ apiOrigin = serviceOrigin(credentials.apiUrl ?? DEFAULT_API_ORIGIN);
19
27
  const data = await work(observer);
20
28
  if (operationId)
21
29
  await services.operations.finish(operationId, { outcome: 'completed', attempts }).catch(() => services.diagnostic({ level: 'warning', code: 'OPERATION_RECORD_UNAVAILABLE' }));
22
- return { data, meta: { operationId: operationId ?? null, requestId: attempts.at(-1)?.requestId ?? null, ...credentialContext(credentials, attempts) } };
30
+ return { data, meta: metadata() };
23
31
  }
24
32
  catch (error) {
25
33
  const failure = safeError(error);
26
34
  if (operationId)
27
35
  await services.operations.finish(operationId, { outcome: failure.outcome, errorCode: failure.code, attempts }).catch(() => { });
28
- throw contextualError(failure, { ...credentialContext(credentials, attempts), operationId: operationId ?? null, requestId: attempts.at(-1)?.requestId ?? null });
36
+ throw contextualError(failure, metadata());
29
37
  }
30
38
  }
@@ -6,7 +6,7 @@ export function successEnvelope(result, cliVersion) {
6
6
  }
7
7
  export function failureEnvelope(error, cliVersion) {
8
8
  const failure = safeError(error);
9
- const context = Object.fromEntries(['merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'].filter(key => Object.hasOwn(failure.details, key)).map(key => [key, failure.details[key]]));
9
+ const context = Object.fromEntries(['merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'apiOrigin', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'].filter(key => Object.hasOwn(failure.details, key)).map(key => [key, failure.details[key]]));
10
10
  return { schemaVersion: 1, ok: false, data: null, error: { code: failure.code, message: failure.message, stage: failure.stage, recovery: failure.recovery, details: failure.details }, meta: { cliVersion, ...context, outcome: failure.outcome, operationId: failure.details.operationId ?? null, requestId: failure.details.requestId ?? null } };
11
11
  }
12
12
  function environmentHeading(meta) {
@@ -86,7 +86,15 @@ export const readSpecs = [
86
86
  listSpec('merchants', 'merchants', fields('id', 'email', 'status', 'createdAt'), objectSchema({}), productDocs),
87
87
  getSpec('merchants', 'merchant', fields('id', 'email', 'status', 'createdAt', 'updatedAt'), merchantId, productDocs, 'MER_abc'),
88
88
  ...['graphql', 'analytics'].map(resource => ({
89
- definition: { id: `${resource}.query`, path: `${resource} query`, description: resource === 'analytics' ? 'Run a custom read-only analytics GraphQL document with explicit nested selections' : 'Run exactly one read-only GraphQL operation; fragments and variables are supported', effect: 'read', file: true, schema: querySchema, options: [previewOption, ['--output <path>', 'Export response to a new private file; required for arbitrary GraphQL']], example: `pancake ${resource} query --file query.json --dry-run --json` },
89
+ definition: {
90
+ id: `${resource}.query`, path: `${resource} query`, description: resource === 'analytics' ? 'Run a custom read-only analytics GraphQL document with explicit nested selections' : 'Run exactly one read-only GraphQL operation; fragments and variables are supported',
91
+ effect: 'read', file: true, schema: querySchema, options: [
92
+ previewOption,
93
+ ['--output <path>', 'Export response to a new private file; required for arbitrary GraphQL'],
94
+ ...(resource === 'graphql' ? [['--background', 'Run this read without adding a local operation record']] : []),
95
+ ],
96
+ example: `pancake ${resource} query --file query.json --dry-run --json`,
97
+ },
90
98
  sensitiveOutput: true, documentation: [`${docs}graphql/${resource === 'analytics' ? 'analytics' : 'overview'}`], request: (input) => readOnlyRequest(input),
91
99
  })),
92
100
  ];
@@ -40,6 +40,6 @@ export const outputContract = {
40
40
  streams: { listen: { format: 'ndjson', envelope: 'one standard envelope per event or error', eventTypes: ['ready', 'delivery', 'stopped'], eventId: 'Stable delivery ID identifies the same event across retries', authentication: 'browser session only', defaultEnvironment: 'test', production: '--live' } },
41
41
  schemaVersion: 1, fields: ['schemaVersion', 'ok', 'data', 'error', 'meta'],
42
42
  errorFields: ['code', 'message', 'stage', 'recovery', 'details'],
43
- metaFields: ['cliVersion', 'outcome', 'operationId', 'requestId', 'merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'],
43
+ metaFields: ['cliVersion', 'outcome', 'operationId', 'requestId', 'merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'apiOrigin', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'],
44
44
  exitCodes: { success: 0, executionOrVerification: 1, argumentsOrConfiguration: 2, interrupted: 130 },
45
45
  };
@@ -1,4 +1,18 @@
1
+ import { CliError } from "./errors.js";
1
2
  export const DEFAULT_API_ORIGIN = 'https://api.waffo.ai';
3
+ export function serviceOrigin(value) {
4
+ let url;
5
+ try {
6
+ url = new URL(value);
7
+ }
8
+ catch {
9
+ throw new CliError('INVALID_ARGUMENT', 'Provide a valid API or Dashboard origin.', { exitCode: 2 });
10
+ }
11
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === '127.0.0.1'))) {
12
+ throw new CliError('INVALID_ARGUMENT', 'Service URLs must be HTTPS origins, or explicit http://127.0.0.1:<port> origins for local testing.', { exitCode: 2 });
13
+ }
14
+ return url.origin;
15
+ }
2
16
  export function productCreateEndpoint(type) {
3
17
  return `/v1/actions/${type}-product/create-product`;
4
18
  }
@@ -1,6 +1,6 @@
1
1
  # 商户 API 覆盖矩阵
2
2
 
3
- 折扣契约核对日期:2026-11-03;其余文档快照:2026-10-26。2026-11-05 同步当前注册表。适用版本:0.0.1-rc.2;以当前注册表和官方 API 文档索引为准。**62 条命令,覆盖 33 个商户 API-Key REST action 路由**。此处“覆盖”指已提供命令入口,不表示全部字段、客户身份接口或真实商户验收完成。
3
+ 折扣契约核对日期:2026-11-03;其余文档快照:2026-10-26。2026-11-05 同步当前注册表。适用版本:0.0.1-rc.3;以当前注册表和官方 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
 
@@ -105,7 +105,7 @@ CLI 支持商户 Session 和 RSA API Key,具体路由仍由服务端鉴权;`
105
105
  | `pnpm cli recipients list` | `--file <path / ->`, `--limit <number>`, `--offset <number>`, `--fields <names>`, `--dry-run` | `/v1/graphql` |
106
106
  | `pnpm cli merchants list` | `--file <path / ->`, `--limit <number>`, `--offset <number>`, `--fields <names>`, `--dry-run` | `/v1/graphql` |
107
107
  | `pnpm cli merchants get` | `<id>`, `--fields <names>`, `--dry-run` | `/v1/graphql` |
108
- | `pnpm cli graphql query` | `--file <path / ->`, `--dry-run`, `--output <path>` | `/v1/graphql` |
108
+ | `pnpm cli graphql query` | `--file <path / ->`, `--dry-run`, `--output <path>`, `--background` | `/v1/graphql` |
109
109
  | `pnpm cli analytics query` | `--file <path / ->`, `--dry-run`, `--output <path>` | `/v1/graphql` |
110
110
  | `pnpm cli coupons list` | `--file`, `--limit`, `--offset`, `--fields`, `--dry-run` | `/v1/graphql` |
111
111
  | `pnpm cli coupons get` | `<id>`, `--fields`, `--dry-run` | `/v1/graphql` |
package/docs/usage.md CHANGED
@@ -11,7 +11,7 @@ View CLI sessions under Dashboard → Settings → Security. With the matching s
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.2 候选版。以下示例中的 `pnpm cli` 用于源码目录;通过 npm 安装后,替换为 `pancake`,其余参数不变。本说明随安装包提供,无需 GitHub 权限。
14
+ 适用版本:0.0.1-rc.3 候选版。以下示例中的 `pnpm cli` 用于源码目录;通过 npm 安装后,替换为 `pancake`,其余参数不变。本说明随安装包提供,无需 GitHub 权限。
15
15
 
16
16
  ## 当前能力与边界
17
17
 
@@ -26,7 +26,7 @@ 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 | `0.0.1-rc.2` 候选版使用 `next` 渠道 |
29
+ | npm / npx | `0.0.1-rc.3` 候选版使用 `next` 渠道 |
30
30
  | Homebrew | 等待首个稳定版;候选版不进入正式配方 |
31
31
 
32
32
  当前注册表共 **62 条命令**,覆盖官方索引中的 **33 个商户 API-Key REST 路由**;字段和认证限制见[完整覆盖矩阵](api-coverage.md)。这不代表所有客户侧接口或所有可选字段均开放。
@@ -305,6 +305,8 @@ pnpm cli analytics query --file analytics-query.json --output ./analytics-result
305
305
 
306
306
  `analytics-query.json` 需按[官方分析查询文档](https://docs.waffo.ai/api-reference/endpoints/graphql/analytics)提供真实字段与嵌套 selection。两个入口均只接受恰好一个 query 操作,可带变量和 fragment;在读取凭证或联网前拒绝 mutation/subscription,包括 dry-run。它们不会根据名字猜测字段敏感性,执行时必须把完整响应导出到新私有文件。没有任意 REST POST 命令。
307
307
 
308
+ 定时查询可使用 `pancake graphql query --background --file - --output ./query-result.json --json`。每次执行需要新的私有输出路径。`--background` 跳过这次查询的本地操作记录,`meta.operationId` 为 `null`。取得有效凭证和 API 地址后,响应的 `meta.apiOrigin` 会包含规范化的 API origin。导出前须由网关验证环境。浏览器登录的响应环境须与已选择的环境一致。若服务端的 `Retry-After` 有效,最终返回的 `RATE_LIMITED` 错误会在 `error.details.retryAfterMs` 中提供建议等待的毫秒数。
309
+
308
310
  客户 Session Token 专属的一次性订单取消、客户侧订阅取消和恢复订阅不在商户命令范围内;商户 `subscriptions cancel` 的 API-Key 权限与客户同路径权限必须分开看待。
309
311
 
310
312
  ## 7. AI 和脚本调用
@@ -364,7 +366,7 @@ pnpm cli diagnostics export --operation OPERATION_ID --output ./diagnostics.json
364
366
 
365
367
  ## 9. 发布后的安装、更新和回退
366
368
 
367
- `0.0.1-rc.2` 候选版使用 `next` 渠道,安装命令:
369
+ `0.0.1-rc.3` 候选版使用 `next` 渠道,安装命令:
368
370
 
369
371
  ```sh
370
372
  npm install -g @waffo/pancake-cli@next
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waffo/pancake-cli",
3
- "version": "0.0.1-rc.2",
3
+ "version": "0.0.1-rc.3",
4
4
  "packageManager": "pnpm@11.25.0",
5
5
  "description": "Developer CLI for Waffo Pancake",
6
6
  "type": "module",