@waffo/pancake-cli 0.0.0-stage → 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.
Files changed (75) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/CONTRIBUTING.md +38 -0
  3. package/LICENSE +21 -0
  4. package/README.md +230 -2
  5. package/SECURITY.md +23 -0
  6. package/SKILL.md +110 -0
  7. package/dist/adapters/browser-login.js +210 -0
  8. package/dist/adapters/config.js +180 -0
  9. package/dist/adapters/files.js +222 -0
  10. package/dist/adapters/loopback-forward.js +33 -0
  11. package/dist/adapters/operations.js +89 -0
  12. package/dist/adapters/pancake/client.js +235 -0
  13. package/dist/adapters/pancake/conflict-error.js +18 -0
  14. package/dist/adapters/pancake/graphql-errors.js +41 -0
  15. package/dist/adapters/pancake/http-error-reason.js +12 -0
  16. package/dist/adapters/pancake/queries.js +9 -0
  17. package/dist/adapters/pancake/safe-reason.js +23 -0
  18. package/dist/adapters/system-process.js +12 -0
  19. package/dist/application/action-auth.js +7 -0
  20. package/dist/application/action-result.js +40 -0
  21. package/dist/application/api-actions.js +80 -0
  22. package/dist/application/api-reads.js +56 -0
  23. package/dist/application/auth-context.js +34 -0
  24. package/dist/application/auth.js +115 -0
  25. package/dist/application/confirmation.js +14 -0
  26. package/dist/application/diagnostics.js +48 -0
  27. package/dist/application/dispatch.js +109 -0
  28. package/dist/application/idempotency.js +8 -0
  29. package/dist/application/listen.js +147 -0
  30. package/dist/application/local.js +35 -0
  31. package/dist/application/product-verification.js +96 -0
  32. package/dist/application/products.js +70 -0
  33. package/dist/application/queries.js +26 -0
  34. package/dist/application/read-handlers.js +30 -0
  35. package/dist/application/read-operation.js +30 -0
  36. package/dist/application/webhooks.js +56 -0
  37. package/dist/application/write-operation.js +26 -0
  38. package/dist/cli/guidance.js +29 -0
  39. package/dist/cli/human-output.js +44 -0
  40. package/dist/cli/input.js +62 -0
  41. package/dist/cli/listen-output.js +10 -0
  42. package/dist/cli/login-prompt.js +66 -0
  43. package/dist/cli/output.js +43 -0
  44. package/dist/cli/run.js +128 -0
  45. package/dist/commands/action-definitions.js +100 -0
  46. package/dist/commands/action-previews.js +12 -0
  47. package/dist/commands/action-schemas.js +47 -0
  48. package/dist/commands/action-values.js +11 -0
  49. package/dist/commands/api-coverage.js +25 -0
  50. package/dist/commands/checkout-action-schema.js +25 -0
  51. package/dist/commands/discount-definitions.js +47 -0
  52. package/dist/commands/discount-preview.js +17 -0
  53. package/dist/commands/discount-schemas.js +39 -0
  54. package/dist/commands/discount-validation.js +17 -0
  55. package/dist/commands/listen-input.js +12 -0
  56. package/dist/commands/operation-impact.js +16 -0
  57. package/dist/commands/product-action-schemas.js +26 -0
  58. package/dist/commands/product-preview.js +5 -0
  59. package/dist/commands/read-definitions.js +92 -0
  60. package/dist/commands/read-query.js +49 -0
  61. package/dist/commands/read-schemas.js +17 -0
  62. package/dist/commands/registry.js +45 -0
  63. package/dist/commands/schemas.js +94 -0
  64. package/dist/commands/webhook-preview.js +3 -0
  65. package/dist/contracts/action-routes.js +7 -0
  66. package/dist/contracts/command.js +1 -0
  67. package/dist/contracts/errors.js +26 -0
  68. package/dist/contracts/impact.js +1 -0
  69. package/dist/contracts/listen.js +1 -0
  70. package/dist/contracts/loopback-target.js +14 -0
  71. package/dist/contracts/types.js +1 -0
  72. package/dist/index.js +20 -0
  73. package/docs/api-coverage.md +154 -0
  74. package/docs/usage.md +458 -0
  75. package/package.json +60 -4
@@ -0,0 +1,34 @@
1
+ import { CliError, safeError } from "../contracts/errors.js";
2
+ export function environmentContext(environment) {
3
+ const actualEnvironment = environment === 'test' || environment === 'prod' ? environment : null;
4
+ return { actualEnvironment, environmentVerified: actualEnvironment !== null };
5
+ }
6
+ export function credentialContext(credentials, attempts = []) {
7
+ return { merchantId: credentials.merchantId, source: credentials.source, ...environmentContext(attempts.at(-1)?.environment) };
8
+ }
9
+ export function writeWarning(attempts) {
10
+ const { actualEnvironment } = environmentContext(attempts.at(-1)?.environment);
11
+ if (actualEnvironment === 'test')
12
+ return 'This operation uses the test environment.';
13
+ if (actualEnvironment === 'prod')
14
+ return 'This operation affects production.';
15
+ return 'The credential environment cannot be verified; this operation may affect production.';
16
+ }
17
+ export function contextualError(error, context) {
18
+ const failure = safeError(error);
19
+ return new CliError(failure.code, failure.message, { exitCode: failure.exitCode, stage: failure.stage, recovery: failure.recovery, outcome: failure.outcome, details: { ...failure.details, ...context } });
20
+ }
21
+ export function requireWriteEnvironment(credentials, identity) {
22
+ if (!credentials.sessionToken && identity.environment !== 'test' && identity.environment !== 'prod') {
23
+ throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the credential environment. No write was sent.', {
24
+ stage: 'identity', recovery: 'Run whoami and verify your environment before trying again.',
25
+ details: environmentContext(identity.environment),
26
+ });
27
+ }
28
+ if (credentials.sessionToken && identity.environment !== credentials.environment) {
29
+ throw new CliError('ENVIRONMENT_MISMATCH', 'The gateway did not verify the selected environment. No write was sent.', {
30
+ stage: 'identity', recovery: 'Run whoami and verify your environment before trying again.',
31
+ details: { selectedEnvironment: credentials.environment, ...environmentContext(identity.environment) },
32
+ });
33
+ }
34
+ }
@@ -0,0 +1,115 @@
1
+ import { resolve } from 'node:path';
2
+ import { homedir } from 'node:os';
3
+ import { argumentError, CliError } from "../contracts/errors.js";
4
+ import { environmentContext } from "./auth-context.js";
5
+ import { authenticatedOperation, readOperation } from "./read-operation.js";
6
+ function overrideStatus(services) {
7
+ return { environmentCredentialsPresent: services.environmentCredentialsPresent,
8
+ ...(services.environmentCredentialsPresent ? { warning: 'Environment credentials still take precedence. Unset WAFFO_MERCHANT_ID, WAFFO_PRIVATE_KEY and WAFFO_PRIVATE_KEY_FILE to use the saved login or finish logging out.' } : {}),
9
+ };
10
+ }
11
+ export async function login(options, services) {
12
+ if (!options.keyLogin && !options.merchantId && !options.key && !options.privateKeyFile)
13
+ return loginInBrowser(options, services);
14
+ if (options.apiUrl || options.dashboardUrl)
15
+ throw argumentError('Service URL overrides are only supported for browser login.');
16
+ if (!options.merchantId || (!options.key && !options.privateKeyFile))
17
+ throw argumentError('Provide a Merchant ID and a private key or file path.');
18
+ if (options.key && options.privateKeyFile)
19
+ throw argumentError('Provide one key input, not both --key and --private-key-file.');
20
+ if (!/^MER_[A-Za-z0-9]+$/.test(options.merchantId) || (options.storeId !== undefined && !/^STO_[A-Za-z0-9]+$/.test(options.storeId)))
21
+ throw argumentError('Provide a valid Merchant ID and optional Store ID.');
22
+ const key = options.key?.trim();
23
+ const isContent = !!key && (key.startsWith('-----BEGIN') || /^MII[A-Za-z0-9+/=\s]+$/.test(key));
24
+ const path = isContent ? undefined : (options.privateKeyFile ?? key).replace(/^(['"])(.*)\1$/, '$2');
25
+ const credentials = { merchantId: options.merchantId,
26
+ ...(isContent ? { privateKey: key } : { privateKeyFile: resolve(path.startsWith('~/') ? homedir() + path.slice(1) : path) }),
27
+ storeId: options.storeId, source: 'login' };
28
+ return authenticatedOperation('login', options, services, credentials, async (observer) => {
29
+ const snapshot = await services.config.read();
30
+ const identity = await (await services.gateway(credentials, observer)).me();
31
+ if (identity.id !== credentials.merchantId)
32
+ throw new CliError('AUTH_FAILED', 'The authenticated merchant could not be verified.', { stage: 'identity' });
33
+ await services.config.save(credentials, snapshot, options.signal);
34
+ return { saved: true, merchantId: identity.id, credentialVerified: true, ...environmentContext(identity.environment),
35
+ savedLoginActive: !services.environmentCredentialsPresent, ...overrideStatus(services), next: 'Run pancake whoami to verify the effective identity, then pancake stores list.' };
36
+ });
37
+ }
38
+ export async function whoami(options, services) {
39
+ let credentials;
40
+ try {
41
+ credentials = await services.credentials(options);
42
+ }
43
+ catch (error) {
44
+ if (error instanceof CliError && error.code === 'AUTH_REQUIRED')
45
+ return { data: { authenticated: false, merchantId: null, source: null, credentialVerified: false, actualEnvironment: null, environmentVerified: false } };
46
+ throw error;
47
+ }
48
+ return readOperation('whoami', options, services, async (gateway) => {
49
+ const identity = await gateway.me();
50
+ if (identity.id !== credentials.merchantId)
51
+ throw new CliError('AUTH_FAILED', 'The authenticated merchant could not be verified.', { stage: 'identity' });
52
+ return { authenticated: true, merchantId: identity.id, source: credentials.source, credentialVerified: true, ...environmentContext(identity.environment) };
53
+ }, credentials);
54
+ }
55
+ export async function logout(services) {
56
+ let snapshot;
57
+ try {
58
+ snapshot = await services.config.read();
59
+ }
60
+ catch (error) {
61
+ if (!(error instanceof CliError) || !['INVALID_CONFIG', 'CONFIG_VERSION_UNSUPPORTED'].includes(error.code))
62
+ throw error;
63
+ }
64
+ let serverSessionRevoked = false;
65
+ if (snapshot?.credential?.sessionToken) {
66
+ const credentials = { ...snapshot.credential, source: 'stored' };
67
+ serverSessionRevoked = await (await services.gateway(credentials, () => { })).revokeSession();
68
+ }
69
+ if (snapshot)
70
+ await services.config.clear(snapshot);
71
+ else
72
+ await services.config.clearInvalid();
73
+ return { data: { localCredentialsCleared: true, serverKeyRevoked: false, serverSessionRevoked, ...overrideStatus(services) } };
74
+ }
75
+ async function loginInBrowser(options, services) {
76
+ if (!options.interactive || !services.browserLogin)
77
+ throw argumentError('Browser login needs an interactive terminal. Run pancake login, or use --merchant-id and --private-key-file for automation.');
78
+ const snapshot = await services.config.read();
79
+ const previous = snapshot.credential;
80
+ return services.browserLogin(options, async (authorized) => {
81
+ const sameBrowserAccount = previous?.sessionToken && previous.merchantId === authorized.merchantId && previous.apiUrl === authorized.apiUrl;
82
+ const credentials = { ...authorized, environment: sameBrowserAccount ? previous.environment ?? 'test' : 'test' };
83
+ return authenticatedOperation('login', options, services, credentials, async (observer) => {
84
+ const identity = await (await services.gateway(credentials, observer)).me();
85
+ if (identity.id !== credentials.merchantId)
86
+ throw new CliError('AUTH_FAILED', 'The authenticated merchant could not be verified.', { stage: 'identity' });
87
+ if (!identity.environment || identity.environment !== credentials.environment)
88
+ throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the selected environment. Your saved login was not changed.', { stage: 'identity' });
89
+ if (options.signal?.aborted)
90
+ throw new CliError('INTERRUPTED', 'Cancelled.', { exitCode: 130 });
91
+ await services.config.save(credentials, snapshot, options.signal);
92
+ return { saved: true, merchantId: identity.id, credentialVerified: true, authentication: 'browser', ...environmentContext(identity.environment), savedLoginActive: !services.environmentCredentialsPresent, ...overrideStatus(services) };
93
+ });
94
+ });
95
+ }
96
+ export async function selectEnvironment(environment, options, services) {
97
+ if (environment !== 'test' && environment !== 'prod')
98
+ throw argumentError('Choose test or prod.');
99
+ if (services.environmentCredentialsPresent)
100
+ throw argumentError('Environment RSA credentials take precedence. Unset them before switching a browser login.');
101
+ const snapshot = await services.config.read();
102
+ const current = snapshot.credential;
103
+ if (!current)
104
+ throw new CliError('AUTH_REQUIRED', 'No saved login. Run login first.', { stage: 'credentials' });
105
+ if (!current.sessionToken)
106
+ throw argumentError('Environment switching requires browser login. RSA keys keep their server-assigned environment.');
107
+ const credentials = { ...current, environment, source: 'stored' };
108
+ return authenticatedOperation('env', options, services, credentials, async (observer) => {
109
+ const identity = await (await services.gateway(credentials, observer)).me();
110
+ if (identity.id !== credentials.merchantId || identity.environment !== environment)
111
+ throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the requested merchant environment. The saved environment was not changed.', { stage: 'identity' });
112
+ await services.config.save(credentials, snapshot, options.signal);
113
+ return { saved: true, merchantId: identity.id, ...environmentContext(identity.environment) };
114
+ });
115
+ }
@@ -0,0 +1,14 @@
1
+ import { CliError } from "../contracts/errors.js";
2
+ /** Local confirmation is separate from server authorization and generic --yes. */
3
+ export function requireImpactConfirmation(impact, options) {
4
+ const missing = [impact.requiresProductionConfirmation === true && !options.confirmProduction ? '--confirm-production' : null,
5
+ impact.requiresSharedConfirmation && !options.confirmShared ? '--confirm-shared' : null].filter(Boolean);
6
+ if (missing.length === 0)
7
+ return;
8
+ throw new CliError('CONFIRMATION_REQUIRED', impact.impact === 'shared'
9
+ ? 'This change affects shared Test and Production resources. No write was sent.'
10
+ : 'This change affects Production. No write was sent.', {
11
+ exitCode: 2, stage: 'confirmation', recovery: `Review the merchant, store and impact, then add ${missing.join(' and ')} with --yes.`,
12
+ details: { ...impact },
13
+ });
14
+ }
@@ -0,0 +1,48 @@
1
+ import { CliError, safeError } from "../contracts/errors.js";
2
+ import { readOperation } from "./read-operation.js";
3
+ export function diagnosticRecord(record) {
4
+ return {
5
+ operationRecordVersion: record.operationRecordVersion, operationId: record.operationId,
6
+ command: record.command, impact: record.impact, cliVersion: record.cliVersion, startedAt: record.startedAt,
7
+ finishedAt: record.finishedAt, outcome: record.outcome, merchantId: record.merchantId,
8
+ storeId: record.storeId, inputHash: record.inputHash, idempotencyKey: record.idempotencyKey,
9
+ targetResourceId: record.targetResourceId, endpoint: record.endpoint, apiOrigin: record.apiOrigin, selectedEnvironment: record.selectedEnvironment,
10
+ resourceId: record.resourceId, errorCode: record.errorCode,
11
+ attempts: record.attempts.map(attempt => ({ attemptId: attempt.attemptId, endpoint: attempt.endpoint, durationMs: attempt.durationMs, status: attempt.status, requestId: attempt.requestId, environment: attempt.environment })),
12
+ };
13
+ }
14
+ export async function doctor(options, services) {
15
+ const checks = [{ name: 'runtime', status: 'passed' }];
16
+ try {
17
+ await services.config.read();
18
+ checks.push({ name: 'config', status: 'passed' });
19
+ return await readOperation('doctor', options, services, async (gateway, credentials) => {
20
+ checks.push({ name: 'credentials', status: 'passed' }, { name: 'key', status: 'passed' });
21
+ const identity = await gateway.me();
22
+ checks.push({ name: 'networkAndIdentity', status: 'passed' });
23
+ if (credentials.storeId) {
24
+ await gateway.webhooks(credentials.storeId);
25
+ checks.push({ name: 'storeAccess', status: 'passed' });
26
+ }
27
+ else
28
+ checks.push({ name: 'storeAccess', status: 'skipped' });
29
+ if (identity.environment) {
30
+ checks.push({ name: 'credentialEnvironment', status: 'passed' });
31
+ return { checks };
32
+ }
33
+ checks.push({ name: 'credentialEnvironment', status: 'unknown' });
34
+ throw new CliError('ENVIRONMENT_UNVERIFIED', 'Identity verified, but the gateway did not return a verified environment.', {
35
+ stage: 'doctor', recovery: 'Writes are blocked. Ask your account administrator to check the environment, then run doctor again.',
36
+ details: { checks, environmentVerified: false },
37
+ });
38
+ });
39
+ }
40
+ catch (error) {
41
+ const failure = safeError(error);
42
+ if (failure.code === 'ENVIRONMENT_UNVERIFIED')
43
+ throw failure;
44
+ checks.push({ name: 'connection', status: 'failed', code: failure.code });
45
+ checks.push({ name: 'credentialEnvironment', status: 'skipped' });
46
+ throw new CliError(failure.code, 'Connection self-check did not pass.', { exitCode: failure.exitCode, stage: 'doctor', recovery: failure.recovery, details: { ...failure.details, checks } });
47
+ }
48
+ }
@@ -0,0 +1,109 @@
1
+ import { productPreview } from "../commands/product-preview.js";
2
+ import { webhookPreview } from "../commands/webhook-preview.js";
3
+ import { operationImpact } from "../commands/operation-impact.js";
4
+ import { listen } from "./listen.js";
5
+ import { validateDiscountInput } from "../commands/discount-validation.js";
6
+ import { argumentError } from "../contracts/errors.js";
7
+ import { definitions } from "../commands/registry.js";
8
+ import { createValidator, validateTrial, validateTrialPrices, validateProductPrices } from "../commands/schemas.js";
9
+ import { localHandlers } from "./local.js";
10
+ import { readHandlers } from "./read-handlers.js";
11
+ import { credentialContext, contextualError } from "./auth-context.js";
12
+ import { mutateWebhook } from "./webhooks.js";
13
+ import { createProduct } from "./products.js";
14
+ import { actionSpecs } from "../commands/action-definitions.js";
15
+ import { readSpecs } from "../commands/read-definitions.js";
16
+ import { executeApiAction } from "./api-actions.js";
17
+ import { actionPreview } from "./action-result.js";
18
+ import { executeApiRead } from "./api-reads.js";
19
+ import { pagination } from "./queries.js";
20
+ function preview(id, input) {
21
+ const displayed = id === 'products.create' ? productPreview(input) : webhookPreview(input);
22
+ return { data: { executed: false, validation: 'local', environmentVerified: false, command: id, input: displayed }, meta: { executed: false } };
23
+ }
24
+ export function createApplication(services) {
25
+ const validate = createValidator();
26
+ const webhookHandlers = Object.fromEntries(['add', 'update', 'remove'].map(action => [`webhook.${action}`, async (input, options) => {
27
+ if (!options.yes)
28
+ throw argumentError('Remote changes require --yes after reviewing the input or --dry-run output.');
29
+ const credentials = await services.credentials(options);
30
+ const attempts = [];
31
+ try {
32
+ const gateway = await services.gateway(credentials, event => { attempts.push(event); if (options.debug)
33
+ services.diagnostic({ stage: 'api', ...event }); });
34
+ return await mutateWebhook(action, input, options, services, credentials, gateway, attempts, services.fingerprint(input));
35
+ }
36
+ catch (error) {
37
+ throw contextualError(error, { ...credentialContext(credentials, attempts), requestId: attempts.at(-1)?.requestId ?? null });
38
+ }
39
+ }]));
40
+ const handlers = { ...localHandlers(services), ...readHandlers(services), ...webhookHandlers,
41
+ listen: (_input, options) => listen(options, services),
42
+ 'products.create': (input, options) => createProduct(input, options, services, services.fingerprint(input)),
43
+ };
44
+ return async function execute({ id, options, input: provided }) {
45
+ const definition = definitions.find(item => item.id === id);
46
+ const handler = handlers[id];
47
+ const action = actionSpecs.find(item => item.definition.id === id);
48
+ const read = readSpecs.find(item => item.definition.id === id);
49
+ if (!definition || (!handler && !action && !read))
50
+ throw argumentError('Unknown command.');
51
+ const input = { ...provided };
52
+ if (action || read) {
53
+ const schema = definition.schema;
54
+ if (options.storeId !== undefined) {
55
+ if (!schema.properties?.storeId)
56
+ throw argumentError('This command does not accept --store-id; use its documented JSON fields.');
57
+ if (input.storeId !== undefined)
58
+ throw argumentError('storeId was provided both in the input and --store-id.');
59
+ input.storeId = options.storeId;
60
+ }
61
+ if (action && typeof action.endpoint !== 'string') {
62
+ if (options.type !== undefined && input.type !== undefined)
63
+ throw argumentError('Product type was provided twice.');
64
+ input.type ??= options.type;
65
+ }
66
+ }
67
+ if (id === 'products.create' || id.startsWith('webhook.')) {
68
+ if (options.storeId !== undefined) {
69
+ if (input.storeId !== undefined)
70
+ throw argumentError('storeId was provided both in the input and --store-id.');
71
+ input.storeId = options.storeId;
72
+ }
73
+ if (id === 'products.create') {
74
+ if (options.type !== undefined && input.type !== undefined)
75
+ throw argumentError('Product type was provided twice.');
76
+ input.type ??= options.type;
77
+ }
78
+ if (!options.dryRun && id.startsWith('webhook.') && !input.storeId)
79
+ input.storeId = (await services.credentials(options)).storeId;
80
+ }
81
+ validate(definition.schema, input);
82
+ if (id === 'products.create' || id === 'products.update')
83
+ validateProductPrices(input);
84
+ if (action) {
85
+ validateDiscountInput(id, input);
86
+ if (id === 'products.update')
87
+ validateTrialPrices(input);
88
+ if (options.dryRun)
89
+ return { data: actionPreview(action, input), meta: { executed: false, ...operationImpact(definition) } };
90
+ return executeApiAction(action, input, options, services);
91
+ }
92
+ if (read) {
93
+ if (definition.options?.some(([flag]) => flag.startsWith('--limit')))
94
+ pagination(options);
95
+ const request = read.request(input, options);
96
+ if (options.dryRun)
97
+ return { data: { executed: false, validation: 'local', command: id, endpoint: '/v1/graphql', query: '[redacted]', variableNames: Object.keys(request.variables), requiresPrivateOutput: read.sensitiveOutput ?? false }, meta: { executed: false } };
98
+ return executeApiRead(read, request, options, services);
99
+ }
100
+ if (id === 'products.create')
101
+ validateTrial(input);
102
+ if (options.dryRun) {
103
+ const result = preview(id, input);
104
+ const impact = operationImpact(definition);
105
+ return { data: { ...result.data, ...impact }, meta: { ...result.meta, ...impact } };
106
+ }
107
+ return handler(input, options);
108
+ };
109
+ }
@@ -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
+ }
@@ -0,0 +1,147 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { listenInput } from "../commands/listen-input.js";
3
+ import { CliError, safeError } from "../contracts/errors.js";
4
+ import { credentialContext, contextualError } from "./auth-context.js";
5
+ function invalidResponse() {
6
+ return new CliError('INVALID_RESPONSE', 'The listener received an invalid API response.', { stage: 'listen' });
7
+ }
8
+ function terminalFailure(error) {
9
+ const messages = {
10
+ DELIVERY_FAILED: 'Local delivery attempts were exhausted. Check your receiver before restarting.',
11
+ QUEUE_OVERFLOW: 'The listener queue overflowed. Restart after your receiver can keep up with events.',
12
+ PAYLOAD_TOO_LARGE: 'An event exceeded the listener payload limit. Inspect the event before restarting.',
13
+ SESSION_CAPACITY: 'The listener session reached its capacity limit. Start a new session.',
14
+ };
15
+ const candidate = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
16
+ const code = typeof candidate === 'string' && Object.hasOwn(messages, candidate) ? candidate : 'LISTEN_FAILED';
17
+ return new CliError(code, messages[code] ?? 'The listener session failed. Start a new session after resolving delivery or capacity issues.', { stage: 'listen' });
18
+ }
19
+ function cancelledRequest(error, signal, attempt) {
20
+ if (!signal?.aborted)
21
+ return false;
22
+ if (error instanceof Error && error.name === 'AbortError')
23
+ return true;
24
+ return error instanceof CliError && ['NETWORK_ERROR', 'OUTCOME_UNKNOWN'].includes(error.code) && attempt?.status === undefined;
25
+ }
26
+ function deliveries(data, sessionId) {
27
+ if (data.sessionId !== sessionId || !['active', 'failed'].includes(String(data.status)))
28
+ throw invalidResponse();
29
+ if (data.status === 'failed')
30
+ throw terminalFailure(data.error);
31
+ if (!Array.isArray(data.deliveries) || data.deliveries.length > 1)
32
+ throw invalidResponse();
33
+ return data.deliveries.map((item) => {
34
+ if (!item || typeof item !== 'object')
35
+ throw invalidResponse();
36
+ const value = item;
37
+ if (typeof value.id !== 'string' || !/^[\x20-\x7E]{1,160}$/.test(value.id) || typeof value.eventType !== 'string' || !/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(value.eventType) || typeof value.body !== 'string' || Buffer.byteLength(value.body) > 65536 || !Number.isInteger(value.attempt) || Number(value.attempt) < 1 || Number(value.attempt) > 3 || !value.headers || typeof value.headers !== 'object' || Array.isArray(value.headers))
38
+ throw invalidResponse();
39
+ const headers = value.headers;
40
+ if (Object.entries(headers).some(([key, header]) => !/^[A-Za-z0-9-]+$/.test(key) || typeof header !== 'string' || header.length > 8192 || /[\r\n]/.test(header)))
41
+ throw invalidResponse();
42
+ return value;
43
+ });
44
+ }
45
+ function verifyEnvironment(attempt, expected) {
46
+ if (attempt?.environment !== expected)
47
+ throw new CliError('ENVIRONMENT_MISMATCH', 'The API did not verify the requested listener environment.', { stage: 'listen', details: { expectedEnvironment: expected } });
48
+ }
49
+ export async function listen(options, services) {
50
+ const input = listenInput(options);
51
+ const saved = await services.credentials(options);
52
+ if (!saved.sessionToken)
53
+ throw new CliError('BROWSER_LOGIN_REQUIRED', 'Listening requires browser login. RSA keys are not supported.', { exitCode: 2, recovery: 'Run pancake login in a terminal.' });
54
+ const credentials = { ...saved, environment: input.environment };
55
+ const attempts = [];
56
+ const gateway = await services.gateway(credentials, attempt => {
57
+ // A listener can run indefinitely; retain only the latest request evidence.
58
+ attempts[0] = attempt;
59
+ if (options.debug)
60
+ services.diagnostic({ stage: 'api', ...attempt });
61
+ });
62
+ const emit = (event) => options.onListenEvent?.(event, credentialContext(credentials, attempts));
63
+ const request = async (action, body, signal) => {
64
+ attempts.length = 0;
65
+ const result = await gateway.listen(action, body, signal);
66
+ return result;
67
+ };
68
+ let sessionId;
69
+ let startRequested = false;
70
+ let failure;
71
+ let cleanedUp = false;
72
+ try {
73
+ if (!services.forwardLoopback)
74
+ throw new CliError('LOCAL_ERROR', 'Local forwarding is unavailable.');
75
+ await gateway.me(options.signal);
76
+ verifyEnvironment(attempts[0], input.environment);
77
+ if (options.signal?.aborted)
78
+ return { data: { type: 'stopped', sessionId: null, cleanedUp: true } };
79
+ startRequested = true;
80
+ const started = await request('start', { storeId: input.storeId, ...(input.events ? { events: input.events } : {}), live: input.environment === 'prod' }, options.signal);
81
+ if (typeof started.sessionId === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(started.sessionId))
82
+ sessionId = started.sessionId;
83
+ verifyEnvironment(attempts[0], input.environment);
84
+ if (!sessionId || started.environment !== input.environment || started.expiresIn !== 90 || started.pollIntervalMs !== 3000 || started.maxAttempts !== 3)
85
+ throw invalidResponse();
86
+ emit({ type: 'ready', sessionId, environment: input.environment });
87
+ while (!options.signal?.aborted) {
88
+ const polled = await request('poll', { storeId: input.storeId, sessionId }, options.signal);
89
+ verifyEnvironment(attempts[0], input.environment);
90
+ for (const delivery of deliveries(polled, sessionId)) {
91
+ if (options.signal?.aborted)
92
+ break;
93
+ const httpStatus = await services.forwardLoopback({ url: input.url, delivery, signal: options.signal });
94
+ emit({ type: 'delivery', sessionId, deliveryId: delivery.id, eventId: delivery.id, eventType: delivery.eventType, attempt: delivery.attempt, httpStatus });
95
+ if (options.signal?.aborted)
96
+ break;
97
+ const ack = await request('ack', { storeId: input.storeId, sessionId, deliveryId: delivery.id, attempt: delivery.attempt, httpStatus }, options.signal);
98
+ verifyEnvironment(attempts[0], input.environment);
99
+ const success = httpStatus !== null && httpStatus >= 200 && httpStatus < 300;
100
+ if (ack.status === 'failed')
101
+ throw terminalFailure(ack.error ?? { code: 'DELIVERY_FAILED' });
102
+ if (ack.accepted !== true || ack.success !== success || ack.status !== 'active')
103
+ throw invalidResponse();
104
+ }
105
+ if (!options.signal?.aborted)
106
+ await delay(3000, undefined, { signal: options.signal });
107
+ }
108
+ }
109
+ catch (error) {
110
+ if (!cancelledRequest(error, options.signal, attempts[0]))
111
+ failure = !sessionId && error instanceof CliError && error.code === 'OUTCOME_UNKNOWN' ? new CliError('LISTEN_START_UNKNOWN', 'The listener start result is unknown.', { recovery: 'Any temporary session expires within 90 seconds without polling. No permanent webhook was changed.' }) : error;
112
+ }
113
+ finally {
114
+ if (!startRequested && options.signal?.aborted && !failure) {
115
+ cleanedUp = true;
116
+ emit({ type: 'stopped', sessionId: null, cleanedUp });
117
+ }
118
+ if (startRequested && !sessionId) {
119
+ failure = failure ?? new CliError('LISTEN_START_UNKNOWN', 'The listener start result could not be confirmed.', { recovery: 'Any temporary session expires within 90 seconds without polling. No permanent webhook was changed.' });
120
+ emit({ type: 'stopped', sessionId: null, cleanedUp: false });
121
+ }
122
+ if (sessionId) {
123
+ try {
124
+ const stopped = await request('stop', { storeId: input.storeId, sessionId });
125
+ verifyEnvironment(attempts[0], input.environment);
126
+ if (stopped.stopped !== true)
127
+ throw invalidResponse();
128
+ cleanedUp = true;
129
+ }
130
+ catch (error) {
131
+ if (error instanceof CliError && error.code === 'NOT_FOUND' && attempts[0]?.environment === input.environment)
132
+ cleanedUp = true;
133
+ else {
134
+ const original = failure ? safeError(failure) : undefined;
135
+ failure = new CliError(original?.code ?? 'LISTEN_CLEANUP_FAILED', original?.message ?? 'The listener could not confirm session cleanup.', {
136
+ stage: 'listen', recovery: 'The temporary session expires within 90 seconds after its last successful poll. No permanent webhook was changed.',
137
+ details: { cleanupFailed: true },
138
+ });
139
+ }
140
+ }
141
+ emit({ type: 'stopped', sessionId, cleanedUp });
142
+ }
143
+ }
144
+ if (failure)
145
+ throw contextualError(failure, credentialContext(credentials, attempts));
146
+ return { data: { type: 'stopped', sessionId: sessionId ?? null, cleanedUp }, meta: credentialContext(credentials, attempts) };
147
+ }
@@ -0,0 +1,35 @@
1
+ import { operationImpact } from "../commands/operation-impact.js";
2
+ import { argumentError } from "../contracts/errors.js";
3
+ import { definitions, globalOptions, outputContract } from "../commands/registry.js";
4
+ import { login, logout, selectEnvironment } from "./auth.js";
5
+ import { diagnosticRecord } from "./diagnostics.js";
6
+ import { pagination } from "./queries.js";
7
+ import { commandApi } from "../commands/api-coverage.js";
8
+ export function localHandlers(services) {
9
+ return {
10
+ commands: async () => ({ data: definitions.map(item => ({ id: item.id, command: `pancake ${item.path}`, description: item.description, effect: item.effect, ...operationImpact(item), supportsDryRun: item.options?.some(([flag]) => flag === '--dry-run') ?? false, api: commandApi(item.id), availability: 'available' })) }),
11
+ schema: async (input) => {
12
+ const item = definitions.find(item => item.id === input.command);
13
+ if (!item)
14
+ throw argumentError('Unknown command ID. Run pancake commands.');
15
+ const api = commandApi(item.id);
16
+ return { data: { id: item.id, input: item.schema, output: outputContract, effect: item.effect, ...operationImpact(item), example: item.example, api, options: item.options ?? [], globalOptions, argument: item.argument ?? null, file: item.file ? '--file <path> or --file - for stdin' : null, authentication: api?.authentication === 'merchant-rsa' ? 'merchant-rsa (not needed for offline dry-run)' : ['env', 'listen'].includes(item.id) ? 'merchant-session' : item.id === 'login' || ['read', 'write'].includes(item.effect) ? 'merchant-session or merchant-rsa (not needed for offline dry-run)' : 'none', permissions: 'server-enforced; fine-grained credential scopes are not verified', availability: 'available' } };
17
+ },
18
+ login: async (_input, options) => login(options, services),
19
+ env: async (input, options) => selectEnvironment(input.environment, options, services),
20
+ logout: async () => logout(services),
21
+ 'config.show': async () => {
22
+ const { configVersion, credential } = await services.config.read();
23
+ return { data: { configVersion, credential: credential ? { merchantId: credential.merchantId, storeId: credential.storeId, authentication: credential.sessionToken ? 'browser' : 'rsa', ...(credential.sessionToken ? { selectedEnvironment: credential.environment, expiresAt: credential.expiresAt, sessionToken: '[redacted]' } : { privateKeyFile: '[redacted]' }), environmentVerified: false, actualEnvironment: null } : null, environmentCredentialsPresent: services.environmentCredentialsPresent } };
24
+ },
25
+ 'operations.list': async (_input, options) => ({ data: { items: (await services.operations.list(pagination(options).limit)).map(diagnosticRecord) } }),
26
+ 'operations.show': async (input) => ({ data: diagnosticRecord(await services.operations.show(input.id)) }),
27
+ 'diagnostics.export': async (_input, options) => {
28
+ if (!options.operation || !options.output)
29
+ throw argumentError('Provide --operation and a new --output file.');
30
+ const record = diagnosticRecord(await services.operations.show(options.operation));
31
+ await services.exportFile(options.output, `${JSON.stringify({ diagnosticVersion: 1, cliVersion: services.cliVersion, nodeVersion: process.version, platform: process.platform, operation: record }, null, 2)}\n`);
32
+ return { data: { output: options.output, uploaded: false, includes: ['operation metadata', 'request attempts', 'CLI, Node and OS versions'] } };
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,96 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ function object(value) { return !!value && typeof value === 'object' && !Array.isArray(value); }
3
+ function decimal(value) {
4
+ if (typeof value !== 'string' || !/^\d+(\.\d+)?$/.test(value))
5
+ return null;
6
+ const [whole, fraction = ''] = value.split('.');
7
+ const trailing = fraction.replace(/0+$/, '');
8
+ return `${whole.replace(/^0+(?=\d)/, '')}${trailing ? `.${trailing}` : ''}`;
9
+ }
10
+ function pricesMatch(expected, actual) {
11
+ if (!object(expected))
12
+ return false;
13
+ let prices;
14
+ if (Array.isArray(actual)) {
15
+ prices = {};
16
+ for (const row of actual) {
17
+ if (!object(row) || typeof row.currency !== 'string' || Object.hasOwn(prices, row.currency))
18
+ return false;
19
+ prices[row.currency] = row.priceInfo;
20
+ }
21
+ }
22
+ else if (object(actual))
23
+ prices = actual;
24
+ else
25
+ return false;
26
+ if (Object.keys(expected).length !== Object.keys(prices).length)
27
+ return false;
28
+ return Object.entries(expected).every(([currency, requested]) => {
29
+ const returned = prices[currency];
30
+ if (!object(requested) || !object(returned))
31
+ return false;
32
+ const amount = decimal(requested.amount);
33
+ return amount !== null && decimal(returned.amount) === amount && returned.taxCategory === requested.taxCategory &&
34
+ (requested.trialAmount === undefined ? returned.trialAmount == null : decimal(requested.trialAmount) !== null && decimal(returned.trialAmount) === decimal(requested.trialAmount));
35
+ });
36
+ }
37
+ export function productPriceMismatch(input, product, id) {
38
+ if (!product || product.id !== id || !object(input.prices))
39
+ return false;
40
+ const actual = Array.isArray(product.prices)
41
+ ? Object.fromEntries(product.prices.filter(row => object(row) && typeof row.currency === 'string').map(row => [row.currency, row.priceInfo]))
42
+ : product.prices;
43
+ if (!object(actual))
44
+ return false;
45
+ return Object.entries(input.prices).some(([currency, requested]) => {
46
+ const returned = actual[currency];
47
+ if (!object(requested) || !object(returned))
48
+ return false;
49
+ return ['amount', 'trialAmount'].some(field => {
50
+ const expected = decimal(requested[field]), observed = decimal(returned[field]);
51
+ return expected !== null && observed !== null && expected !== observed;
52
+ });
53
+ });
54
+ }
55
+ function media(value) {
56
+ return Array.isArray(value) ? value.map(item => object(item) ? Object.fromEntries(Object.entries(item).filter(([, field]) => field !== null)) : item) : value;
57
+ }
58
+ function normalizedMedia(expected, created) {
59
+ if (typeof expected === 'string' && expected.startsWith('data:image/'))
60
+ return typeof created === 'string' && created.startsWith('https://') ? created : expected;
61
+ if (Array.isArray(expected))
62
+ return expected.map((item, index) => normalizedMedia(item, Array.isArray(created) ? created[index] : undefined));
63
+ if (object(expected))
64
+ return Object.fromEntries(Object.entries(expected).map(([key, value]) => [key, key === 'url' || key === 'thumbnail' ? normalizedMedia(value, object(created) ? created[key] : undefined) : value]));
65
+ return expected;
66
+ }
67
+ export function productMatches(input, product, id, created = product) {
68
+ if (!product || product.id !== id || product.storeId !== input.storeId || product.name !== input.name || !pricesMatch(input.prices, product.prices))
69
+ return false;
70
+ if (input.type === 'subscription' && product.billingPeriod !== input.billingPeriod)
71
+ return false;
72
+ for (const field of ['description', 'successUrl', 'media', 'thumbnail', 'metadata']) {
73
+ if (input[field] === undefined)
74
+ continue;
75
+ let actual = product[field];
76
+ if (field === 'metadata' && typeof actual === 'string') {
77
+ try {
78
+ actual = JSON.parse(actual);
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ }
84
+ const expected = field === 'media' || field === 'thumbnail' ? normalizedMedia(input[field], created?.[field]) : input[field];
85
+ if (!isDeepStrictEqual(field === 'media' ? media(expected) : expected, field === 'media' ? media(actual) : actual))
86
+ return false;
87
+ }
88
+ return true;
89
+ }
90
+ export function safeProduct(product, type) {
91
+ const fields = ['id', 'storeId', 'name', 'status', 'billingPeriod', 'createdAt', 'updatedAt'];
92
+ const result = { type, ...Object.fromEntries(fields.filter(field => typeof product[field] === 'string').map(field => [field, product[field]])) };
93
+ if (object(product.prices))
94
+ result.prices = Object.fromEntries(Object.entries(product.prices).map(([currency, value]) => [currency, object(value) ? Object.fromEntries(['amount', 'taxCategory', 'trialAmount'].filter(field => typeof value[field] === 'string').map(field => [field, value[field]])) : {}]));
95
+ return result;
96
+ }