@waffo/pancake-cli 0.0.0-stage → 0.0.1-rc.1

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 (67) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/CONTRIBUTING.md +38 -0
  3. package/LICENSE +21 -0
  4. package/README.md +218 -2
  5. package/SECURITY.md +23 -0
  6. package/SKILL.md +108 -0
  7. package/dist/adapters/browser-login.js +210 -0
  8. package/dist/adapters/config.js +133 -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 +238 -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-result.js +41 -0
  20. package/dist/application/api-actions.js +82 -0
  21. package/dist/application/api-reads.js +56 -0
  22. package/dist/application/auth-context.js +34 -0
  23. package/dist/application/auth.js +112 -0
  24. package/dist/application/confirmation.js +14 -0
  25. package/dist/application/diagnostics.js +48 -0
  26. package/dist/application/dispatch.js +107 -0
  27. package/dist/application/listen.js +147 -0
  28. package/dist/application/local.js +35 -0
  29. package/dist/application/product-verification.js +96 -0
  30. package/dist/application/products.js +72 -0
  31. package/dist/application/queries.js +26 -0
  32. package/dist/application/read-handlers.js +30 -0
  33. package/dist/application/read-operation.js +30 -0
  34. package/dist/application/webhooks.js +59 -0
  35. package/dist/cli/guidance.js +29 -0
  36. package/dist/cli/human-output.js +44 -0
  37. package/dist/cli/input.js +62 -0
  38. package/dist/cli/listen-output.js +10 -0
  39. package/dist/cli/login-prompt.js +66 -0
  40. package/dist/cli/output.js +43 -0
  41. package/dist/cli/run.js +128 -0
  42. package/dist/commands/action-definitions.js +75 -0
  43. package/dist/commands/action-schemas.js +47 -0
  44. package/dist/commands/action-values.js +11 -0
  45. package/dist/commands/api-coverage.js +24 -0
  46. package/dist/commands/checkout-action-schema.js +25 -0
  47. package/dist/commands/discount-definitions.js +43 -0
  48. package/dist/commands/discount-schemas.js +39 -0
  49. package/dist/commands/discount-validation.js +17 -0
  50. package/dist/commands/listen-input.js +12 -0
  51. package/dist/commands/operation-impact.js +16 -0
  52. package/dist/commands/product-action-schemas.js +26 -0
  53. package/dist/commands/read-definitions.js +92 -0
  54. package/dist/commands/read-query.js +49 -0
  55. package/dist/commands/read-schemas.js +17 -0
  56. package/dist/commands/registry.js +45 -0
  57. package/dist/commands/schemas.js +94 -0
  58. package/dist/contracts/command.js +1 -0
  59. package/dist/contracts/errors.js +26 -0
  60. package/dist/contracts/impact.js +1 -0
  61. package/dist/contracts/listen.js +1 -0
  62. package/dist/contracts/loopback-target.js +14 -0
  63. package/dist/contracts/types.js +1 -0
  64. package/dist/index.js +20 -0
  65. package/docs/api-coverage.md +154 -0
  66. package/docs/usage.md +455 -0
  67. package/package.json +60 -4
@@ -0,0 +1,72 @@
1
+ import { operationImpact } from "../commands/operation-impact.js";
2
+ import { requireImpactConfirmation } from "./confirmation.js";
3
+ import { randomUUID } from 'node:crypto';
4
+ import { CliError, argumentError, safeError } from "../contracts/errors.js";
5
+ import { requireWriteEnvironment, credentialContext, contextualError, writeWarning } from "./auth-context.js";
6
+ import { productMatches, productPriceMismatch, safeProduct } from "./product-verification.js";
7
+ const warning = 'The credential environment cannot be verified. Product creation may affect production; the backend selects the environment from the RSA key.';
8
+ export async function createProduct(input, options, services, fingerprint) {
9
+ const proposed = safeProduct(input, input.type);
10
+ let credentials;
11
+ try {
12
+ credentials = await services.credentials(options);
13
+ }
14
+ catch (error) {
15
+ if (options.yes || !(error instanceof CliError) || error.code !== 'AUTH_REQUIRED')
16
+ throw error;
17
+ throw new CliError('INVALID_ARGUMENT', 'Product creation requires --yes after reviewing the product and credential environment.', { exitCode: 2, stage: 'confirmation', recovery: warning, details: { product: proposed, actualEnvironment: null, environmentVerified: false } });
18
+ }
19
+ const attempts = [];
20
+ let impact = operationImpact({ id: 'products.create', effect: 'write' });
21
+ const context = () => ({ ...impact, ...credentialContext(credentials, attempts), storeId: input.storeId, product: proposed, warning: writeWarning(attempts) });
22
+ if (!options.yes)
23
+ 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
+ try {
28
+ const gateway = await services.gateway(credentials, event => { attempts.push(event); if (options.debug)
29
+ services.diagnostic({ stage: 'api', ...event }); });
30
+ const identity = await gateway.me();
31
+ requireWriteEnvironment(credentials, identity);
32
+ impact = operationImpact({ id: 'products.create', effect: 'write' }, identity.environment);
33
+ requireImpactConfirmation(impact, options);
34
+ const type = input.type;
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 });
37
+ const meta = { ...context(), operationId: operation.operationId, idempotencyKey: key };
38
+ let returned;
39
+ try {
40
+ services.diagnostic({ stage: 'confirmation', ...meta });
41
+ returned = await gateway.createProduct(type, body, key);
42
+ }
43
+ 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 } });
48
+ }
49
+ const resourceId = returned.id;
50
+ try {
51
+ await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId, attempts });
52
+ if (productPriceMismatch(input, returned, resourceId))
53
+ throw new CliError('PRICE_MISMATCH', 'The API accepted the product but returned prices different from those requested.');
54
+ const current = await gateway.product(type, resourceId);
55
+ if (productPriceMismatch(input, current, resourceId))
56
+ throw new CliError('PRICE_MISMATCH', 'The saved product prices differ from those requested.');
57
+ if (!productMatches(input, returned, resourceId) || !productMatches(input, current, resourceId, returned))
58
+ throw new Error('Verification failed');
59
+ await services.operations.finish(operation.operationId, { outcome: 'completed', resourceId, attempts });
60
+ }
61
+ catch (error) {
62
+ const mismatch = error instanceof CliError && error.code === 'PRICE_MISMATCH';
63
+ const errorCode = mismatch ? 'PRICE_MISMATCH' : 'VERIFICATION_PENDING';
64
+ await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId, errorCode, attempts }).catch(() => { });
65
+ 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
+ }
67
+ return { data: { product: safeProduct(returned, type) }, meta: { ...meta, ...context(), requestId: attempts.at(-1)?.requestId ?? null } };
68
+ }
69
+ catch (error) {
70
+ throw contextualError(error, { ...context(), requestId: attempts.at(-1)?.requestId ?? null });
71
+ }
72
+ }
@@ -0,0 +1,26 @@
1
+ import { argumentError, CliError } from "../contracts/errors.js";
2
+ export function pagination(options) {
3
+ const limit = options.limit ?? 20, offset = options.offset ?? 0;
4
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
5
+ throw argumentError('Use an integer limit from 1 to 100 and a non-negative integer offset.');
6
+ return { limit, offset };
7
+ }
8
+ export function selectFields(rows, fields, allowed) {
9
+ if (!fields)
10
+ return rows;
11
+ const names = fields.split(',');
12
+ if (!names.length || names.some(name => !allowed.includes(name)))
13
+ throw argumentError('Unknown field selection. Use the documented result field names.');
14
+ return rows.map(row => Object.fromEntries(names.filter(name => Object.hasOwn(row, name)).map(name => [name, row[name]])));
15
+ }
16
+ export function safeWebhook(webhook) {
17
+ return { id: webhook.id, channel: webhook.channel, events: webhook.events, testMode: webhook.testMode, createdAt: webhook.createdAt, url: '[redacted]', secret: '[redacted]' };
18
+ }
19
+ export function testWebhook(webhooks, id) {
20
+ const record = webhooks.find(webhook => webhook.id === id);
21
+ if (!record)
22
+ throw new CliError('NOT_FOUND', 'Webhook was not found in the selected store and credential environment.');
23
+ if (record.testMode !== true)
24
+ throw new CliError('ENVIRONMENT_MISMATCH', 'Only test webhooks can be changed by this CLI.', { stage: 'environment' });
25
+ return record;
26
+ }
@@ -0,0 +1,30 @@
1
+ import { argumentError, CliError } from "../contracts/errors.js";
2
+ import { whoami } from "./auth.js";
3
+ import { doctor } from "./diagnostics.js";
4
+ import { pagination, safeWebhook, selectFields } from "./queries.js";
5
+ import { readOperation } from "./read-operation.js";
6
+ export function readHandlers(services) {
7
+ return {
8
+ doctor: async (_input, options) => doctor(options, services),
9
+ whoami: async (_input, options) => whoami(options, services),
10
+ 'stores.list': async (_input, options) => {
11
+ const { limit, offset } = pagination(options);
12
+ const fields = ['id', 'name', 'status', 'slug'];
13
+ selectFields([], options.fields, fields);
14
+ return readOperation('stores.list', options, services, async (gateway) => { const rows = await gateway.stores(limit, offset); return { items: selectFields(rows, options.fields, fields), pagination: { limit, offset, nextOffset: rows.length === limit ? offset + limit : null, hasMore: rows.length === limit ? 'unknown' : false } }; });
15
+ },
16
+ 'products.get': async (input, options) => {
17
+ if (!options.type || !['onetime', 'subscription'].includes(options.type))
18
+ throw argumentError('Provide --type onetime or --type subscription.');
19
+ const fields = ['id', 'storeId', 'name', 'description', 'status', 'prices', 'createdAt', 'updatedAt', 'billingPeriod'];
20
+ selectFields([], options.fields, fields);
21
+ return readOperation('products.get', options, services, async (gateway) => {
22
+ const product = await gateway.product(options.type, input.id);
23
+ if (!product)
24
+ throw new CliError('NOT_FOUND', 'Product not found or not accessible in the credential environment.');
25
+ return selectFields([product], options.fields ?? fields.join(','), fields)[0];
26
+ });
27
+ },
28
+ 'webhook.list': async (input, options) => readOperation('webhook.list', { ...options, storeId: input.storeId }, services, async (gateway) => ({ items: (await gateway.webhooks(input.storeId)).map(item => ({ ...safeWebhook(item), url: item.url })) })),
29
+ };
30
+ }
@@ -0,0 +1,30 @@
1
+ import { safeError } from "../contracts/errors.js";
2
+ import { credentialContext, contextualError } from "./auth-context.js";
3
+ export async function readOperation(id, options, services, work, suppliedCredentials) {
4
+ const credentials = suppliedCredentials ?? await services.credentials(options);
5
+ return authenticatedOperation(id, options, services, credentials, async (observer) => work(await services.gateway(credentials, observer), credentials));
6
+ }
7
+ export async function authenticatedOperation(id, options, services, credentials, work) {
8
+ const attempts = [];
9
+ 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' });
15
+ }
16
+ const observer = (event) => { attempts.push(event); if (options.debug)
17
+ services.diagnostic({ stage: 'api', ...event }); };
18
+ try {
19
+ const data = await work(observer);
20
+ if (operationId)
21
+ 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) } };
23
+ }
24
+ catch (error) {
25
+ const failure = safeError(error);
26
+ if (operationId)
27
+ 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 });
29
+ }
30
+ }
@@ -0,0 +1,59 @@
1
+ import { operationImpact } from "../commands/operation-impact.js";
2
+ import { randomUUID } from 'node:crypto';
3
+ import { CliError, argumentError, safeError } from "../contracts/errors.js";
4
+ import { requireWriteEnvironment, credentialContext } from "./auth-context.js";
5
+ import { safeWebhook, testWebhook } from "./queries.js";
6
+ export async function mutateWebhook(action, input, options, services, credentials, gateway, attempts, fingerprint) {
7
+ if (!options.yes)
8
+ 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.');
12
+ const identity = await gateway.me();
13
+ requireWriteEnvironment(credentials, identity);
14
+ if (identity.environment !== 'test')
15
+ throw new CliError('ENVIRONMENT_MISMATCH', 'Webhook changes require the test environment. Run env test, or log in with a Test key. No write was sent.', { stage: 'identity' });
16
+ const impact = operationImpact({ id: `webhook.${action}`, effect: 'write' }, identity.environment);
17
+ const storeId = input.storeId;
18
+ const before = await gateway.webhooks(storeId);
19
+ if (action !== 'add')
20
+ testWebhook(before, input.id);
21
+ if (action === 'add' && input.testMode !== true)
22
+ throw new CliError('ENVIRONMENT_MISMATCH', 'New webhook subscriptions must use testMode:true.');
23
+ const { storeId: _storeId, ...withoutStore } = input;
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 });
28
+ const meta = { ...impact, operationId: operation.operationId, idempotencyKey: key, resourceEnvironment: 'test', ...credentialContext(credentials, attempts) };
29
+ const secretReadbackRestricted = !!credentials.sessionToken && input.secret !== undefined;
30
+ let returned;
31
+ try {
32
+ returned = await gateway.mutateWebhook(action, body, key);
33
+ }
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 } });
39
+ }
40
+ try {
41
+ await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId: returned.id, attempts });
42
+ const after = await gateway.webhooks(storeId, input.secret !== undefined && !secretReadbackRestricted);
43
+ const current = after.find(item => item.id === returned.id);
44
+ const targetMatches = action === 'add' || returned.id === input.id;
45
+ const fieldsMatch = action === 'remove' ? !current : current?.testMode === true &&
46
+ (input.url === undefined || current.url === input.url) &&
47
+ (input.channel === undefined || current.channel === input.channel) &&
48
+ (input.secret === undefined || secretReadbackRestricted || current.secret === input.secret) &&
49
+ (input.events === undefined || JSON.stringify(current.events) === JSON.stringify(input.events));
50
+ if (!targetMatches || returned.testMode !== true || !fieldsMatch)
51
+ throw new Error('Verification failed');
52
+ await services.operations.finish(operation.operationId, { outcome: 'completed', resourceId: returned.id, attempts });
53
+ }
54
+ catch {
55
+ await services.operations.finish(operation.operationId, { outcome: 'committed_unverified', resourceId: returned.id, errorCode: 'VERIFICATION_PENDING', attempts }).catch(() => { });
56
+ 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
+ }
58
+ 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'] } : {}) } };
59
+ }
@@ -0,0 +1,29 @@
1
+ export function invocationName(env) {
2
+ if (env.npm_lifecycle_event !== 'cli' || env.npm_package_name !== '@waffo/pancake-cli')
3
+ return 'pancake';
4
+ return env.npm_config_user_agent?.startsWith('pnpm/') ? 'pnpm cli' : 'npm run cli --';
5
+ }
6
+ export function credentialGuide(command) {
7
+ return `Run ${command} login to sign in with your browser.
8
+ Switch environments: ${command} env test or ${command} env prod.
9
+ For RSA keys: Dashboard > API & Development > API Keys.
10
+ Use ${command} login --key-login for hidden key entry.
11
+ Automation: ${command} login --merchant-id MER_example --private-key-file /absolute/path/key.pem
12
+ `;
13
+ }
14
+ export function welcome(command) {
15
+ return `Pancake CLI
16
+
17
+ 1. Log in with your browser: ${command} login
18
+ 2. Select Test: ${command} env test
19
+ 3. List stores: ${command} stores list
20
+
21
+ RSA keys: Dashboard > API & Development > API Keys; ${command} login --key-login.
22
+ Status: ${command} whoami | Commands: ${command} commands
23
+ Help: ${command} --help | JSON for scripts: ${command} commands --json
24
+ `;
25
+ }
26
+ // Only apply to CLI-authored guidance, never to resource values or JSON envelopes.
27
+ export function localizeCommand(text, command) {
28
+ return text.replace(/\bpancake(?=\s)/g, () => command);
29
+ }
@@ -0,0 +1,44 @@
1
+ import { localizeCommand } from "./guidance.js";
2
+ function valueText(value) {
3
+ if (typeof value === 'string')
4
+ return value.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
5
+ if (value === null)
6
+ return '—';
7
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
8
+ }
9
+ function rows(items) {
10
+ if (!items.length)
11
+ return 'No records.\n';
12
+ return items.map((item, index) => {
13
+ if (!item || typeof item !== 'object' || Array.isArray(item))
14
+ return `${index + 1}. ${valueText(item)}`;
15
+ return `${index + 1}. ` + Object.entries(item).map(([key, value]) => `${key}: ${valueText(value)}`).join(' | ');
16
+ }).join('\n') + '\n';
17
+ }
18
+ export function humanData(data, id, command) {
19
+ if (id === 'commands' && Array.isArray(data)) {
20
+ return data.map(item => `${localizeCommand(item.command, command)} — ${item.description}`).join('\n')
21
+ + `\n\nHelp: ${command} <command> --help\nJSON: ${command} commands --json\n`;
22
+ }
23
+ const record = data && typeof data === 'object' && !Array.isArray(data) ? data : null;
24
+ if (id === 'whoami' && record) {
25
+ return record.authenticated
26
+ ? 'Logged in. Merchant verified.\n'
27
+ : `Not logged in. Run ${command} login.\n`;
28
+ }
29
+ if (id === 'login' && record) {
30
+ return `Credentials verified and saved.\n${record.warning ? valueText(record.warning) + '\n' : ''}Next: ${command} whoami, then ${command} stores list.\n`;
31
+ }
32
+ if (id === 'logout' && record) {
33
+ return `Local login cleared. Records kept; server credentials not revoked.\n${record.warning ? valueText(record.warning) + '\n' : ''}`;
34
+ }
35
+ if (Array.isArray(data))
36
+ return rows(data);
37
+ if (record && Array.isArray(record.items)) {
38
+ const rest = Object.entries(record).filter(([key]) => key !== 'items').map(([key, value]) => `${key}: ${valueText(value)}\n`).join('');
39
+ return (id === 'products.list' && record.items.length === 0 ? 'No products found.\n' : rows(record.items)) + rest;
40
+ }
41
+ if (record)
42
+ return Object.entries(record).map(([key, value]) => `${key}: ${id === 'schema' && key === 'example' ? localizeCommand(String(value), command) : valueText(value)}`).join('\n') + '\n';
43
+ return valueText(data) + '\n';
44
+ }
@@ -0,0 +1,62 @@
1
+ import { openRegularFile } from "../adapters/files.js";
2
+ import { argumentError } from "../contracts/errors.js";
3
+ const MAX_BYTES = 1024 * 1024;
4
+ async function readStdin(stream) {
5
+ return new Promise((resolve, reject) => {
6
+ const chunks = [];
7
+ let size = 0;
8
+ const cleanup = () => { clearTimeout(timer); stream.off('data', data); stream.off('end', end); stream.off('error', error); stream.pause(); };
9
+ const error = () => { cleanup(); reject(argumentError('Cannot read stdin JSON.')); };
10
+ const data = (chunk) => {
11
+ const bytes = Buffer.from(chunk);
12
+ size += bytes.length;
13
+ if (size > MAX_BYTES) {
14
+ cleanup();
15
+ reject(argumentError('Input exceeds the 1 MiB limit.'));
16
+ }
17
+ else
18
+ chunks.push(bytes);
19
+ };
20
+ const end = () => { cleanup(); resolve(Buffer.concat(chunks).toString('utf8')); };
21
+ const timer = setTimeout(() => { cleanup(); reject(argumentError('Timed out waiting for stdin. Pipe one complete JSON object and close stdin.')); }, 5000);
22
+ stream.on('data', data);
23
+ stream.once('end', end);
24
+ stream.once('error', error);
25
+ stream.resume();
26
+ });
27
+ }
28
+ export async function loadInput(path, stdin) {
29
+ if (!path)
30
+ return {};
31
+ let text;
32
+ if (path === '-')
33
+ text = await readStdin(stdin);
34
+ else {
35
+ try {
36
+ const handle = await openRegularFile(path);
37
+ try {
38
+ const stat = await handle.stat();
39
+ if (!stat.isFile() || stat.size > MAX_BYTES)
40
+ throw argumentError('Input must be a regular JSON file no larger than 1 MiB.');
41
+ text = await handle.readFile('utf8');
42
+ if (Buffer.byteLength(text) > MAX_BYTES)
43
+ throw argumentError('Input exceeds the 1 MiB limit.');
44
+ }
45
+ finally {
46
+ await handle.close();
47
+ }
48
+ }
49
+ catch {
50
+ throw argumentError('Cannot read the JSON input file (maximum 1 MiB).');
51
+ }
52
+ }
53
+ try {
54
+ const parsed = JSON.parse(text);
55
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
56
+ throw new Error('Expected object');
57
+ return parsed;
58
+ }
59
+ catch {
60
+ throw argumentError('Input must be one valid JSON object.');
61
+ }
62
+ }
@@ -0,0 +1,10 @@
1
+ import { renderResult, successEnvelope } from "./output.js";
2
+ export function renderListenEvent(event, meta, version, json) {
3
+ if (json)
4
+ return renderResult(successEnvelope({ data: event, meta }, version), true);
5
+ if (event.type === 'ready')
6
+ return `Listening in ${event.environment === 'prod' ? 'Production' : 'Test'} (${event.sessionId}). Press Ctrl+C to stop.\n`;
7
+ if (event.type === 'delivery')
8
+ return `${event.eventType} ${event.deliveryId} attempt ${event.attempt}: ${event.httpStatus ?? 'network failure'}\n`;
9
+ return `Listener stopped. Cleanup ${event.cleanedUp ? 'confirmed' : 'unconfirmed'}.\n`;
10
+ }
@@ -0,0 +1,66 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import { Writable } from 'node:stream';
3
+ import { argumentError } from "../contracts/errors.js";
4
+ import { CliError } from "../contracts/errors.js";
5
+ import { credentialGuide } from "./guidance.js";
6
+ export function interruption(writeDispatched) {
7
+ return new CliError('INTERRUPTED', writeDispatched
8
+ ? 'The command was interrupted; any in-flight write may have completed.'
9
+ : 'Cancelled.', {
10
+ exitCode: 130, outcome: writeDispatched ? 'unknown' : 'rejected', stage: 'interrupt',
11
+ recovery: writeDispatched ? 'Inspect pancake operations list and query the resource before repeating a write.' : '',
12
+ });
13
+ }
14
+ export async function promptCredentials(options, command) {
15
+ process.stderr.write(credentialGuide(command));
16
+ let hidden = false;
17
+ const output = new Writable({ write(chunk, _encoding, done) { if (!hidden)
18
+ process.stderr.write(chunk); done(); } });
19
+ const prompt = createInterface({ input: process.stdin, output, terminal: !!process.stdin.isTTY });
20
+ const controller = new AbortController();
21
+ const cancel = () => controller.abort();
22
+ prompt.once('SIGINT', cancel);
23
+ prompt.once('close', cancel);
24
+ try {
25
+ const merchantId = options.merchantId || (await prompt.question('Merchant ID: ', { signal: controller.signal })).trim();
26
+ if (options.privateKeyFile || options.key)
27
+ return { ...options, merchantId };
28
+ hidden = true;
29
+ const key = await new Promise((resolve, reject) => {
30
+ let value = '';
31
+ const cleanup = () => { prompt.off('line', line); controller.signal.removeEventListener('abort', abort); };
32
+ const abort = () => { cleanup(); reject(interruption(false)); };
33
+ const line = (text) => {
34
+ value += (value ? '\n' : '') + text.trim();
35
+ if (value.length > 65536) {
36
+ cleanup();
37
+ reject(argumentError('Private key input is too large.'));
38
+ return;
39
+ }
40
+ if (value.startsWith('-----BEGIN') && !/-----END (?:RSA )?PRIVATE KEY-----/.test(value))
41
+ return;
42
+ cleanup();
43
+ process.stderr.write('\n');
44
+ resolve(value.trim());
45
+ };
46
+ prompt.on('line', line);
47
+ controller.signal.addEventListener('abort', abort, { once: true });
48
+ if (controller.signal.aborted) {
49
+ abort();
50
+ return;
51
+ }
52
+ process.stderr.write('Private key or file path (hidden): ');
53
+ });
54
+ return { ...options, merchantId, key };
55
+ }
56
+ catch (error) {
57
+ if (controller.signal.aborted)
58
+ throw interruption(false);
59
+ throw error;
60
+ }
61
+ finally {
62
+ prompt.off('SIGINT', cancel);
63
+ prompt.off('close', cancel);
64
+ prompt.close();
65
+ }
66
+ }
@@ -0,0 +1,43 @@
1
+ import { safeError } from "../contracts/errors.js";
2
+ import { humanData } from "./human-output.js";
3
+ import { credentialGuide, localizeCommand } from "./guidance.js";
4
+ export function successEnvelope(result, cliVersion) {
5
+ return { schemaVersion: 1, ok: true, data: result.data, error: null, meta: { cliVersion, outcome: 'completed', operationId: null, requestId: null, ...result.meta } };
6
+ }
7
+ export function failureEnvelope(error, cliVersion) {
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]]));
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
+ }
12
+ function environmentHeading(meta) {
13
+ if (!meta.merchantId && !Object.hasOwn(meta, 'actualEnvironment') && !Object.hasOwn(meta, 'environmentVerified'))
14
+ return '';
15
+ const labels = { test: 'Test', prod: 'Production' };
16
+ const verified = meta.environmentVerified === true && (meta.actualEnvironment === 'test' || meta.actualEnvironment === 'prod');
17
+ return `Environment: ${verified ? labels[meta.actualEnvironment] : 'Unknown (unverified)'}\n`;
18
+ }
19
+ export function renderResult(envelope, json, command = 'pancake', id) {
20
+ if (json)
21
+ return `${JSON.stringify(envelope)}\n`;
22
+ const meta = envelope.meta;
23
+ const impacts = { test: 'Test', prod: 'Production', shared: 'Shared by Test and Production', 'test-to-prod': 'Test → Production' };
24
+ const impact = typeof meta.impact === 'string' && impacts[meta.impact] ? `Impact: ${impacts[meta.impact]}\n` : '';
25
+ const environment = environmentHeading(meta) + impact;
26
+ const context = meta.merchantId ? `Merchant: ${meta.merchantId} | source: ${meta.source}\n` : '';
27
+ const traces = [meta.operationId ? `Operation: ${meta.operationId}` : '', meta.requestId ? `Request: ${meta.requestId}` : ''].filter(Boolean).join(' | ');
28
+ const footer = `${context}${traces ? traces + '\n' : ''}`;
29
+ if (!envelope.ok) {
30
+ const error = envelope.error;
31
+ if (error.code === 'INTERRUPTED' && meta.outcome === 'rejected')
32
+ return 'Cancelled.\n';
33
+ if (error.code === 'AUTH_REQUIRED')
34
+ return `${environment}Not logged in. Run ${command} login.\n${footer}`;
35
+ return `${environment}${error.code}: ${localizeCommand(error.message, command)}\n${localizeCommand(error.recovery, command)}\n${id === 'login' && error.code === 'INVALID_ARGUMENT' ? credentialGuide(command) : ''}${Object.keys(error.details).length ? JSON.stringify(error.details, null, 2) + '\n' : ''}${footer}`;
36
+ }
37
+ const data = envelope.data;
38
+ if (data?.help)
39
+ return localizeCommand(data.help, command);
40
+ if (data?.version)
41
+ return `${data.version}\n`;
42
+ return `${environment}${humanData(envelope.data, id, command)}${footer}`;
43
+ }
@@ -0,0 +1,128 @@
1
+ import { renderListenEvent } from "./listen-output.js";
2
+ import { Command, CommanderError } from 'commander';
3
+ import { definitions, globalOptions } from "../commands/registry.js";
4
+ import { argumentError, safeError } from "../contracts/errors.js";
5
+ import { loadInput } from "./input.js";
6
+ import { failureEnvelope, renderResult, successEnvelope } from "./output.js";
7
+ import { credentialGuide, invocationName, welcome } from "./guidance.js";
8
+ import { interruption, promptCredentials } from "./login-prompt.js";
9
+ export async function runCli(argv, version, execute) {
10
+ const json = argv.includes('--json') || !process.stdout.isTTY;
11
+ const interactive = !json && !argv.includes('--no-interactive') && !!process.stdin.isTTY;
12
+ const commandName = invocationName(process.env);
13
+ let listenAbort;
14
+ let browserAbort;
15
+ let rendered = false;
16
+ let helpOutput = '';
17
+ let commandId;
18
+ let writeDispatched = false;
19
+ const print = (result) => { if (!rendered) {
20
+ rendered = true;
21
+ process.stdout.write(renderResult(successEnvelope(result, version), json, commandName, commandId));
22
+ } };
23
+ const fail = (error) => {
24
+ const failure = safeError(error);
25
+ if (!rendered) {
26
+ rendered = true;
27
+ (json ? process.stdout : process.stderr).write(renderResult(failureEnvelope(failure, version), json, commandName, commandId));
28
+ }
29
+ return failure.exitCode;
30
+ };
31
+ const interrupted = () => { if (listenAbort) {
32
+ listenAbort.abort();
33
+ return;
34
+ } if (browserAbort) {
35
+ browserAbort.abort();
36
+ return;
37
+ } const code = fail(interruption(writeDispatched)); process.exit(code); };
38
+ process.on('SIGINT', interrupted);
39
+ const terminated = () => { if (listenAbort)
40
+ listenAbort.abort(); };
41
+ const root = new Command().name('pancake').description('Waffo Pancake CLI for developers and AI agents').version(version);
42
+ for (const [flag, description] of globalOptions)
43
+ root.option(flag, description);
44
+ const configure = (command) => command.configureHelp({ showGlobalOptions: true }).allowExcessArguments(false).exitOverride().showSuggestionAfterError(false).configureOutput({ writeOut: text => { helpOutput += text; }, writeErr: () => { } });
45
+ configure(root);
46
+ root.addHelpText('after', '\n' + welcome('pancake'));
47
+ const groups = new Map();
48
+ for (const definition of definitions) {
49
+ const parts = definition.path.split(' ');
50
+ let parent = root;
51
+ if (parts.length === 2) {
52
+ if (!groups.has(parts[0])) {
53
+ const group = configure(root.command(parts[0]));
54
+ group.action(() => print({ data: { help: group.helpInformation() } }));
55
+ groups.set(parts[0], group);
56
+ }
57
+ parent = groups.get(parts[0]);
58
+ }
59
+ const command = configure(parent.command(parts.at(-1))).description(definition.description);
60
+ if (definition.id === 'login')
61
+ command.addHelpText('after', '\n' + credentialGuide('pancake'));
62
+ if (definition.argument)
63
+ command.argument(`<${definition.argument}>`);
64
+ if (definition.file)
65
+ command.option('--file <path>', 'JSON input file, or - for stdin (maximum 1 MiB)');
66
+ for (const [flags, description] of definition.options ?? [])
67
+ command.option(flags, description);
68
+ command.action(async (...args) => {
69
+ commandId = definition.id;
70
+ const leaf = args.at(-1);
71
+ const raw = leaf.optsWithGlobals();
72
+ let options = { ...raw, interactive };
73
+ for (const field of ['limit', 'offset'])
74
+ if (raw[field] !== undefined) {
75
+ if (!/^\d+$/.test(String(raw[field])))
76
+ throw argumentError('Pagination requires whole non-negative numbers.');
77
+ options[field] = Number(raw[field]);
78
+ }
79
+ if (interactive && definition.id === 'login' && (options.keyLogin || options.merchantId || options.privateKeyFile || options.key) && (!options.merchantId || (!options.privateKeyFile && !options.key))) {
80
+ options = { ...options, ...await promptCredentials(options, commandName) };
81
+ }
82
+ const input = await loadInput(options.file, process.stdin);
83
+ if (definition.argument) {
84
+ if (Object.hasOwn(input, definition.argument))
85
+ throw argumentError('An argument is present both in the JSON file and command line.');
86
+ input[definition.argument] = args[0];
87
+ }
88
+ writeDispatched = definition.effect === 'write' && !options.dryRun && options.yes === true;
89
+ if (definition.id === 'login' && interactive && !options.keyLogin && !options.merchantId && !options.key && !options.privateKeyFile) {
90
+ browserAbort = new AbortController();
91
+ options.signal = browserAbort.signal;
92
+ }
93
+ if (definition.id === 'listen') {
94
+ process.on('SIGTERM', terminated);
95
+ listenAbort = new AbortController();
96
+ options.signal = listenAbort.signal;
97
+ options.onListenEvent = (event, meta) => {
98
+ process.stdout.write(renderListenEvent(event, meta, version, json));
99
+ };
100
+ }
101
+ const result = await execute({ id: definition.id, input, options });
102
+ browserAbort = undefined;
103
+ writeDispatched = false;
104
+ if (definition.id === 'listen')
105
+ rendered = true;
106
+ else
107
+ print(result);
108
+ });
109
+ }
110
+ root.action(() => print({ data: { help: json ? root.helpInformation() : welcome('pancake') } }));
111
+ try {
112
+ await root.parseAsync(argv, { from: 'user' });
113
+ if (!rendered)
114
+ print({ data: { help: root.helpInformation() } });
115
+ return listenAbort?.signal.aborted ? 130 : 0;
116
+ }
117
+ catch (error) {
118
+ if (error instanceof CommanderError && ['commander.helpDisplayed', 'commander.version', 'commander.help'].includes(error.code)) {
119
+ print({ data: error.code === 'commander.version' ? { version } : { help: helpOutput } });
120
+ return 0;
121
+ }
122
+ return fail(error instanceof CommanderError ? argumentError('Invalid command, missing argument, or unsupported option. Run pancake --help or pancake schema <command>.') : error);
123
+ }
124
+ finally {
125
+ process.off('SIGINT', interrupted);
126
+ process.off('SIGTERM', terminated);
127
+ }
128
+ }