@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.
- package/CHANGELOG.md +37 -0
- package/CONTRIBUTING.md +38 -0
- package/LICENSE +21 -0
- package/README.md +218 -2
- package/SECURITY.md +23 -0
- package/SKILL.md +108 -0
- package/dist/adapters/browser-login.js +210 -0
- package/dist/adapters/config.js +133 -0
- package/dist/adapters/files.js +222 -0
- package/dist/adapters/loopback-forward.js +33 -0
- package/dist/adapters/operations.js +89 -0
- package/dist/adapters/pancake/client.js +238 -0
- package/dist/adapters/pancake/conflict-error.js +18 -0
- package/dist/adapters/pancake/graphql-errors.js +41 -0
- package/dist/adapters/pancake/http-error-reason.js +12 -0
- package/dist/adapters/pancake/queries.js +9 -0
- package/dist/adapters/pancake/safe-reason.js +23 -0
- package/dist/adapters/system-process.js +12 -0
- package/dist/application/action-result.js +41 -0
- package/dist/application/api-actions.js +82 -0
- package/dist/application/api-reads.js +56 -0
- package/dist/application/auth-context.js +34 -0
- package/dist/application/auth.js +112 -0
- package/dist/application/confirmation.js +14 -0
- package/dist/application/diagnostics.js +48 -0
- package/dist/application/dispatch.js +107 -0
- package/dist/application/listen.js +147 -0
- package/dist/application/local.js +35 -0
- package/dist/application/product-verification.js +96 -0
- package/dist/application/products.js +72 -0
- package/dist/application/queries.js +26 -0
- package/dist/application/read-handlers.js +30 -0
- package/dist/application/read-operation.js +30 -0
- package/dist/application/webhooks.js +59 -0
- package/dist/cli/guidance.js +29 -0
- package/dist/cli/human-output.js +44 -0
- package/dist/cli/input.js +62 -0
- package/dist/cli/listen-output.js +10 -0
- package/dist/cli/login-prompt.js +66 -0
- package/dist/cli/output.js +43 -0
- package/dist/cli/run.js +128 -0
- package/dist/commands/action-definitions.js +75 -0
- package/dist/commands/action-schemas.js +47 -0
- package/dist/commands/action-values.js +11 -0
- package/dist/commands/api-coverage.js +24 -0
- package/dist/commands/checkout-action-schema.js +25 -0
- package/dist/commands/discount-definitions.js +43 -0
- package/dist/commands/discount-schemas.js +39 -0
- package/dist/commands/discount-validation.js +17 -0
- package/dist/commands/listen-input.js +12 -0
- package/dist/commands/operation-impact.js +16 -0
- package/dist/commands/product-action-schemas.js +26 -0
- package/dist/commands/read-definitions.js +92 -0
- package/dist/commands/read-query.js +49 -0
- package/dist/commands/read-schemas.js +17 -0
- package/dist/commands/registry.js +45 -0
- package/dist/commands/schemas.js +94 -0
- package/dist/contracts/command.js +1 -0
- package/dist/contracts/errors.js +26 -0
- package/dist/contracts/impact.js +1 -0
- package/dist/contracts/listen.js +1 -0
- package/dist/contracts/loopback-target.js +14 -0
- package/dist/contracts/types.js +1 -0
- package/dist/index.js +20 -0
- package/docs/api-coverage.md +154 -0
- package/docs/usage.md +455 -0
- package/package.json +60 -4
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { discountActionSpecs } from "./discount-definitions.js";
|
|
2
|
+
import { contentScanSchema, groupSchemas, recipientSchemas, refundSchemas, sessionSchema, storeSchemas, subscriptionCancelSchema } from "./action-schemas.js";
|
|
3
|
+
import { checkoutSchema } from "./checkout-action-schema.js";
|
|
4
|
+
import { productPublishSchema, productStatusSchema, productUpdateSchema } from "./product-action-schemas.js";
|
|
5
|
+
const options = [
|
|
6
|
+
['--dry-run', 'Validate and preview offline without sending a request'],
|
|
7
|
+
['--idempotency-key <key>', 'Unique operation key; used keys are never automatically replayed'],
|
|
8
|
+
['--output <path>', 'Export the response to a new private file; required for checkout and session results'],
|
|
9
|
+
];
|
|
10
|
+
const docs = (path) => `https://docs.waffo.ai/api-reference/endpoints/${path}`;
|
|
11
|
+
const keyedResponse = (key) => (data) => {
|
|
12
|
+
const value = data[key];
|
|
13
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) && typeof value.id === 'string' && value.id !== '';
|
|
14
|
+
};
|
|
15
|
+
const hasStrings = (data, keys) => keys.every(key => typeof data[key] === 'string' && data[key] !== '');
|
|
16
|
+
function definition(id, description, schema, product = false, effect = 'write') {
|
|
17
|
+
return {
|
|
18
|
+
id, path: id.replace('.', ' '), description, schema, effect, file: true,
|
|
19
|
+
options: [...(product ? [['--type <type>', 'onetime or subscription (required)']] : []), ...options],
|
|
20
|
+
example: `pancake ${id.replace('.', ' ')}${product ? ' --type onetime' : ''} --file input.json --dry-run --json`,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export const actionSpecs = [
|
|
24
|
+
...discountActionSpecs,
|
|
25
|
+
...['create', 'update', 'delete'].map(action => ({
|
|
26
|
+
definition: definition(`stores.${action}`, `${action} a store; requires --yes${action === 'delete' ? '; soft-deletes the store and makes it inaccessible' : ''}`, storeSchemas[action]),
|
|
27
|
+
endpoint: `/v1/actions/store/${action}-store`, documentation: [docs(`stores/${action}-store`)],
|
|
28
|
+
responseKey: 'store', validateResponse: keyedResponse('store'),
|
|
29
|
+
})),
|
|
30
|
+
...[
|
|
31
|
+
['update', 'update-product', productUpdateSchema, 'Update product content; prices replaces all currencies (omitted currencies are removed); existing purchases keep their version; taxIncluded is unsupported'],
|
|
32
|
+
['publish', 'publish-product', productPublishSchema, 'Publish a product TEST→PRODUCTION for the first time'],
|
|
33
|
+
['set-status', 'update-status', productStatusSchema, 'Set product checkout availability without canceling existing purchases'],
|
|
34
|
+
].map(([action, endpoint, schema, description]) => ({
|
|
35
|
+
definition: definition(`products.${action}`, `${description}; requires --yes`, schema, true),
|
|
36
|
+
endpoint: { onetime: `/v1/actions/onetime-product/${endpoint}`, subscription: `/v1/actions/subscription-product/${endpoint}` },
|
|
37
|
+
documentation: [docs(`onetime-products/${endpoint}`), docs(`subscription-products/${endpoint}`)],
|
|
38
|
+
responseKey: 'product', validateResponse: keyedResponse('product'),
|
|
39
|
+
})),
|
|
40
|
+
...['create', 'update', 'delete', 'publish'].map(action => ({
|
|
41
|
+
definition: definition(`groups.${action}`, `${action} a subscription product group; requires --yes${action === 'delete' ? '; permanently deletes only the group' : ''}${action === 'publish' ? '; copies TEST→PRODUCTION using upsert' : ''}`, groupSchemas[action]),
|
|
42
|
+
endpoint: `/v1/actions/subscription-product-group/${action}-group`, documentation: [docs(`subscription-products/${action}-group`)],
|
|
43
|
+
...(action === 'create' || action === 'update' ? { responseKey: 'group', validateResponse: keyedResponse('group') } : { acknowledgementOnly: true }),
|
|
44
|
+
})),
|
|
45
|
+
{
|
|
46
|
+
definition: definition('checkout.create', 'Create a checkout or plan-change session; requires --yes and --output for the private checkout link', checkoutSchema),
|
|
47
|
+
endpoint: '/v1/actions/checkout/create-session', documentation: [docs('orders/create-checkout-session')], sensitiveOutput: true,
|
|
48
|
+
validateResponse: data => hasStrings(data, ['sessionId', 'checkoutUrl', 'expiresAt']),
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
definition: definition('subscriptions.cancel', 'Request subscription cancellation; timing follows its current state; requires --yes', subscriptionCancelSchema),
|
|
52
|
+
endpoint: '/v1/actions/subscription-order/cancel-order', documentation: [docs('subscriptions/cancel-subscription')],
|
|
53
|
+
validateResponse: data => hasStrings(data, ['orderId', 'status']) && ['canceling', 'canceled'].includes(data.status),
|
|
54
|
+
},
|
|
55
|
+
...['create', 'resubmit'].map(action => ({
|
|
56
|
+
definition: definition(`refunds.${action}`, `${action} a refund ticket; this does not confirm completed repayment; requires --yes`, refundSchemas[action]),
|
|
57
|
+
endpoint: `/v1/actions/refund-ticket/${action}-ticket`, documentation: [docs(`refunds/${action}-refund-ticket`)],
|
|
58
|
+
responseKey: 'ticket', validateResponse: keyedResponse('ticket'),
|
|
59
|
+
})),
|
|
60
|
+
{
|
|
61
|
+
definition: definition('sessions.create', 'Issue a customer token using RSA login; requires --yes and --output', sessionSchema),
|
|
62
|
+
endpoint: '/v1/actions/auth/issue-session-token', documentation: [docs('auth/issue-session-token')], sensitiveOutput: true,
|
|
63
|
+
validateResponse: data => hasStrings(data, ['token', 'expiresAt']) && (data.portalUrl === undefined || hasStrings(data, ['portalUrl'])),
|
|
64
|
+
},
|
|
65
|
+
...['add', 'update', 'remove'].map(action => ({
|
|
66
|
+
definition: definition(`recipients.${action}`, `${action} a store notification recipient; requires --yes${action === 'remove' ? '; removing the last recipient silences merchant notifications' : ''}`, recipientSchemas[action]),
|
|
67
|
+
endpoint: `/v1/actions/store-notification-recipient/${action}-recipient`, documentation: [docs(`notification-recipients/${action}-recipient`)],
|
|
68
|
+
...(action === 'remove' ? { validateResponse: (data) => hasStrings(data, ['recipientId']) && data.removed === true } : { responseKey: 'recipient', validateResponse: keyedResponse('recipient') }),
|
|
69
|
+
})),
|
|
70
|
+
{
|
|
71
|
+
definition: definition('content.scan', 'Check prompt safety; requires --yes', contentScanSchema, false, 'read'),
|
|
72
|
+
endpoint: '/v1/actions/verification/scan-prompt', documentation: [docs('content-safety/scan-prompt')],
|
|
73
|
+
validateResponse: data => hasStrings(data, ['action', 'reasonCode', 'requestId', 'semanticStatus']) && ['allow', 'review', 'block'].includes(data.action) && Array.isArray(data.matchedCategories) && data.matchedCategories.every(value => typeof value === 'string'),
|
|
74
|
+
},
|
|
75
|
+
];
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { objectSchema, storeId, string, uuid } from "./schemas.js";
|
|
2
|
+
import { currency, notificationFlags, orderId, positiveAmount, productId } from "./action-values.js";
|
|
3
|
+
const nullable = (schema) => ({ anyOf: [schema, { type: 'null' }] });
|
|
4
|
+
const storeName = { type: 'string', minLength: 1, maxLength: 48, allOf: [{ pattern: '\\S' }, { not: { pattern: '[\\u0000-\\u001f\\u007f]' } }] };
|
|
5
|
+
const checkoutTheme = objectSchema({
|
|
6
|
+
checkoutLogo: nullable({ type: 'string' }), checkoutColorPrimary: nullable({ type: 'string' }),
|
|
7
|
+
checkoutColorBackground: nullable({ type: 'string' }), checkoutColorCard: nullable({ type: 'string' }),
|
|
8
|
+
checkoutColorText: nullable({ type: 'string' }), checkoutBorderRadius: nullable({ type: 'string' }),
|
|
9
|
+
});
|
|
10
|
+
export const storeSchemas = {
|
|
11
|
+
create: objectSchema({ name: storeName }, ['name']),
|
|
12
|
+
update: objectSchema({
|
|
13
|
+
id: storeId, name: storeName, status: { enum: ['active', 'inactive', 'suspended'] }, logo: nullable({ type: 'string' }),
|
|
14
|
+
notificationSettings: nullable(objectSchema(Object.fromEntries(Object.keys({ ...notificationFlags, emailUpcomingCharge: true, emailTrialEnding: true }).map(key => [key, nullable({ type: 'boolean' })])))),
|
|
15
|
+
checkoutSettings: nullable(objectSchema({ defaultDarkMode: nullable({ type: 'boolean' }), light: nullable(checkoutTheme), dark: nullable(checkoutTheme) })),
|
|
16
|
+
}, ['id']),
|
|
17
|
+
delete: objectSchema({ id: storeId }, ['id']),
|
|
18
|
+
};
|
|
19
|
+
const groupFields = {
|
|
20
|
+
name: string, description: { type: 'string' },
|
|
21
|
+
rules: nullable(objectSchema({ sharedTrial: { type: 'boolean' }, selfServicePlanChange: { type: 'boolean' } })),
|
|
22
|
+
productIds: { type: 'array', items: productId },
|
|
23
|
+
};
|
|
24
|
+
export const groupSchemas = {
|
|
25
|
+
create: objectSchema({ storeId, ...groupFields }, ['storeId', 'name']),
|
|
26
|
+
update: objectSchema({ id: uuid, ...groupFields }, ['id']),
|
|
27
|
+
delete: objectSchema({ id: uuid }, ['id']),
|
|
28
|
+
publish: objectSchema({ id: uuid }, ['id']),
|
|
29
|
+
};
|
|
30
|
+
const refundFields = { reason: string, requestedAmount: objectSchema({ amount: positiveAmount, currency }, ['amount', 'currency']) };
|
|
31
|
+
export const refundSchemas = {
|
|
32
|
+
create: objectSchema({ paymentId: { type: 'string', pattern: '^PAY_[A-Za-z0-9]+$' }, ...refundFields, refundTicketMerchantExternalId: { type: 'string', maxLength: 128 } }, ['paymentId', 'reason', 'requestedAmount']),
|
|
33
|
+
resubmit: objectSchema({ ticketId: { type: 'string', pattern: '^TKT_[A-Za-z0-9]+$' }, ...refundFields }, ['ticketId', 'reason', 'requestedAmount']),
|
|
34
|
+
};
|
|
35
|
+
export const sessionSchema = {
|
|
36
|
+
...objectSchema({ storeId, productId, buyerIdentity: string, purpose: { const: 'portal' } }, ['buyerIdentity']),
|
|
37
|
+
anyOf: [{ required: ['storeId'] }, { required: ['productId'] }],
|
|
38
|
+
if: { required: ['purpose'], properties: { purpose: { const: 'portal' } } },
|
|
39
|
+
then: { required: ['storeId'], not: { required: ['productId'] } },
|
|
40
|
+
};
|
|
41
|
+
export const recipientSchemas = {
|
|
42
|
+
add: objectSchema({ storeId, email: string }, ['storeId', 'email']),
|
|
43
|
+
update: objectSchema({ storeId, recipientId: uuid, preferences: objectSchema(notificationFlags) }, ['storeId', 'recipientId', 'preferences']),
|
|
44
|
+
remove: objectSchema({ storeId, recipientId: uuid }, ['storeId', 'recipientId']),
|
|
45
|
+
};
|
|
46
|
+
export const subscriptionCancelSchema = objectSchema({ orderId }, ['orderId']);
|
|
47
|
+
export const contentScanSchema = objectSchema({ prompt: { type: 'string', minLength: 1, maxLength: 10000 }, locale: { enum: ['ja', 'en', 'zh'] }, semantic: { enum: ['off', 'shadow', 'enforce'] } }, ['prompt']);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const productId = { type: 'string', pattern: '^PROD_[A-Za-z0-9]+$' };
|
|
2
|
+
export const orderId = { type: 'string', pattern: '^ORD_[A-Za-z0-9]+$' };
|
|
3
|
+
export const amount = { type: 'string', pattern: '^\\d+(\\.\\d+)?$' };
|
|
4
|
+
export const positiveAmount = { ...amount, pattern: '^(?=.*[1-9])\\d+(\\.\\d+)?$' };
|
|
5
|
+
export const currency = { type: 'string', pattern: '^[A-Z]{3}$' };
|
|
6
|
+
export const taxCategory = { enum: ['digital_goods', 'saas', 'software', 'ebook', 'online_course', 'consulting', 'professional_service'] };
|
|
7
|
+
export const notificationFlags = Object.fromEntries([
|
|
8
|
+
'notifyNewOrders', 'notifyNewSubscriptions', 'notifySubscriptionCanceled', 'notifySubscriptionEnded',
|
|
9
|
+
'notifySubscriptionPastDue', 'notifySubscriptionRenewed', 'notifySubscriptionUncanceled',
|
|
10
|
+
'notifySubscriptionPlanChanged', 'notifyChargeback', 'notifyRefundSucceeded',
|
|
11
|
+
].map(key => [key, { type: 'boolean' }]));
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { actionSpecs } from "./action-definitions.js";
|
|
2
|
+
import { readSpecs } from "./read-definitions.js";
|
|
3
|
+
export function commandApi(id) {
|
|
4
|
+
if (id === 'listen')
|
|
5
|
+
return { method: 'POST', endpoints: ['/v1/graphql', ...['start', 'poll', 'ack', 'stop'].map(action => `/v1/actions/notification/cli-listen-${action}`)], authentication: 'merchant-session only', targetEnvironment: 'test by default; --live for prod', temporarySessionTtlSeconds: 90 };
|
|
6
|
+
const action = actionSpecs.find(spec => spec.definition.id === id);
|
|
7
|
+
if (action)
|
|
8
|
+
return { method: 'POST', endpoints: typeof action.endpoint === 'string' ? [action.endpoint] : Object.values(action.endpoint), authentication: id === 'sessions.create' ? 'merchant-rsa' : 'merchant-session or merchant-rsa; server route permissions apply',
|
|
9
|
+
confirmationRequired: true, privateOutputRequired: action.sensitiveOutput ?? false,
|
|
10
|
+
targetEnvironment: id.endsWith('.publish') ? 'prod' : 'credential-dependent-unverified',
|
|
11
|
+
verification: action.acknowledgementOnly ? 'acknowledgement_only' : 'response_only', documentation: action.documentation };
|
|
12
|
+
const read = readSpecs.find(spec => spec.definition.id === id);
|
|
13
|
+
if (read)
|
|
14
|
+
return { method: 'POST', endpoints: ['/v1/graphql'], authentication: 'merchant-session or merchant-rsa; server route permissions apply', privateOutputRequired: read.sensitiveOutput ?? false, documentation: read.documentation };
|
|
15
|
+
if (id === 'products.create')
|
|
16
|
+
return { method: 'POST', endpoints: ['/v1/actions/onetime-product/create-product', '/v1/actions/subscription-product/create-product'], authentication: 'merchant-session or merchant-rsa; server route permissions apply', verification: 'read_back' };
|
|
17
|
+
if (['webhook.add', 'webhook.update', 'webhook.remove'].includes(id))
|
|
18
|
+
return { method: 'POST', endpoints: [`/v1/actions/store/${id.split('.')[1]}-webhook`], authentication: 'merchant-session or merchant-rsa; server route permissions apply', scope: 'test-webhook-resources-only', verification: id === 'webhook.remove' ? 'read_back' : 'conditional', ...(id === 'webhook.remove' ? {} : { verificationPolicy: { default: 'read_back', browserSecretWrite: 'response_only' } }) };
|
|
19
|
+
if (id === 'login')
|
|
20
|
+
return { method: 'POST', endpoints: ['/v1/actions/auth/cli-device-start', '/v1/actions/auth/cli-device-token', '/v1/actions/auth/cli-device-complete', '/v1/graphql'], authentication: 'browser device authorization then merchant-session; explicit merchant-rsa supported' };
|
|
21
|
+
if (['env', 'whoami', 'doctor', 'stores.list', 'products.get', 'webhook.list'].includes(id))
|
|
22
|
+
return { method: 'POST', endpoints: ['/v1/graphql'], authentication: 'merchant-session or merchant-rsa; server route permissions apply' };
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { objectSchema, string } from "./schemas.js";
|
|
2
|
+
import { amount, currency, orderId, productId, taxCategory } from "./action-values.js";
|
|
3
|
+
const paymentMethods = { type: 'array', items: { enum: ['card', 'applepay', 'googlepay', 'wechat'] } };
|
|
4
|
+
export const checkoutSchema = {
|
|
5
|
+
...objectSchema({
|
|
6
|
+
productId, currency,
|
|
7
|
+
priceSnapshot: objectSchema({ amount, taxIncluded: { type: 'boolean' }, taxCategory }, ['amount', 'taxCategory']),
|
|
8
|
+
withTrial: { type: 'boolean' }, buyerEmail: string,
|
|
9
|
+
billingDetail: objectSchema({
|
|
10
|
+
country: { type: 'string', pattern: '^[A-Z]{2}$' }, isBusiness: { type: 'boolean' },
|
|
11
|
+
postcode: { type: 'string' }, state: { type: 'string' }, businessName: { type: 'string' }, taxId: { type: 'string' },
|
|
12
|
+
}, ['country', 'isBusiness']),
|
|
13
|
+
successUrl: { type: 'string', format: 'https-url' }, expiresInSeconds: { type: 'number' },
|
|
14
|
+
darkMode: { type: 'boolean' }, metadata: { type: 'object', additionalProperties: true },
|
|
15
|
+
orderMerchantExternalId: { type: 'string', minLength: 1, maxLength: 128, pattern: '\\S' },
|
|
16
|
+
language: { enum: ['en', 'pt-BR', 'es-MX', 'id-ID', 'vi-VN', 'ru-RU', 'en-KE', 'es-PE', 'es-CO', 'es-CL', 'zh-Hant-TW', 'zh-Hant-HK', 'th-TH', 'ja-JP', 'en-NG', 'ko-KR', 'en-HK', 'zh-Hans-HK', 'pl-PL', 'tr-TR', 'zh-Hans', 'ms-MY'] },
|
|
17
|
+
includePaymentMethods: paymentMethods, excludePaymentMethods: paymentMethods,
|
|
18
|
+
originOrderId: orderId, changeTiming: { enum: ['immediate', 'next_period'] }, changeAmount: amount, changeCreditAmount: amount,
|
|
19
|
+
}, ['productId', 'currency']),
|
|
20
|
+
dependencies: { changeTiming: ['originOrderId'], changeAmount: ['originOrderId'], changeCreditAmount: ['originOrderId'] },
|
|
21
|
+
allOf: [
|
|
22
|
+
{ not: { required: ['includePaymentMethods', 'excludePaymentMethods'] } },
|
|
23
|
+
{ not: { required: ['changeAmount', 'changeCreditAmount'] } },
|
|
24
|
+
],
|
|
25
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { couponId, couponListSchema, discountSchemas, promotionListSchema } from "./discount-schemas.js";
|
|
2
|
+
import { objectSchema } from "./schemas.js";
|
|
3
|
+
import { selection } from "./read-query.js";
|
|
4
|
+
const documentation = ['https://github.com/waffo-com/waffo-pancake-cli/blob/main/docs/usage.md#discounts'];
|
|
5
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
const entity = (value, prefix) => object(value) && typeof value.id === 'string' && new RegExp(`^${prefix}_[A-Za-z0-9]{22}$`).test(value.id) && typeof value.status === 'string' && (prefix === 'CPN' ? ['active', 'inactive', 'failed'] : ['active', 'inactive']).includes(value.status);
|
|
7
|
+
function publicEntity(value) {
|
|
8
|
+
const result = Object.fromEntries(['id', 'storeId', 'couponId', 'name', 'code', 'status', 'batchId'].filter(key => ['string', 'number', 'boolean'].includes(typeof value[key])).map(key => [key, value[key]]));
|
|
9
|
+
if (Array.isArray(value.promotionCodes))
|
|
10
|
+
result.promotionCodes = value.promotionCodes.map(item => publicEntity(item));
|
|
11
|
+
return result;
|
|
12
|
+
}
|
|
13
|
+
export const discountActionSpecs = Object.entries(discountSchemas).map(([id, schema]) => {
|
|
14
|
+
const [resource, action] = id.split('.');
|
|
15
|
+
const coupon = resource === 'coupons';
|
|
16
|
+
const batch = action === 'generate';
|
|
17
|
+
const key = coupon ? 'coupon' : 'promotionCode';
|
|
18
|
+
return {
|
|
19
|
+
definition: { id, path: id.replace('.', ' '), description: `${action} ${resource}; requires --yes${action === 'deactivate' ? '; permanent deactivation' : ''}${id === 'coupons.update' ? '; name only' : ''}`, effect: 'write', file: true, schema,
|
|
20
|
+
options: [['--dry-run', 'Validate and preview offline'], ['--idempotency-key <key>', 'Unique operation key; no automatic replay'], ['--output <path>', 'Export the complete response to a new private file']], example: `pancake ${id.replace('.', ' ')} --file input.json --dry-run --json` },
|
|
21
|
+
endpoint: `/v1/actions/${coupon ? 'coupon' : 'promotion-code'}/${action}-${coupon ? 'coupon' : batch ? 'promotion-codes' : 'promotion-code'}`,
|
|
22
|
+
documentation,
|
|
23
|
+
...(batch ? {} : { responseKey: key }),
|
|
24
|
+
validateResponse: data => batch
|
|
25
|
+
? typeof data.batchId === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(data.batchId) && Array.isArray(data.promotionCodes) && data.promotionCodes.length > 0 && data.promotionCodes.length <= 500 && data.promotionCodes.every(value => entity(value, 'PMC') && typeof value.code === 'string')
|
|
26
|
+
: entity(data[key], coupon ? 'CPN' : 'PMC') && (!coupon || !object(data[key]) || data[key].promotionCodes === undefined || (Array.isArray(data[key].promotionCodes) && data[key].promotionCodes.every(value => entity(value, 'PMC') && typeof value.code === 'string'))) && (action === 'deactivate' ? data[key].status === 'inactive' : typeof data[key].code === 'string'),
|
|
27
|
+
projectResponse: data => batch ? { batchId: data.batchId, promotionCodes: data.promotionCodes.map(publicEntity) } : { [key]: publicEntity(data[key]) },
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
const fields = (...names) => Object.fromEntries(names.map(name => [name, name]));
|
|
31
|
+
const couponFields = { ...fields('id', 'storeId', 'name', 'code', 'status', 'redeemable', 'notRedeemableReason', 'discountType', 'percentOff', 'duration', 'durationInPeriods', 'productIds', 'maxRedemptions', 'redeemBy', 'timesRedeemed', 'promotionCodesCount', 'createdAt', 'updatedAt'), amountOff: 'amountOff { amount currency display }' };
|
|
32
|
+
const promotionFields = { ...fields('id', 'couponId', 'code', 'status', 'batchId', 'timesRedeemed', 'createdAt'), restrictions: 'restrictions { perCustomerLimit maxRedemptions expiresAt minimumAmount { amount currency display } }' };
|
|
33
|
+
const preview = ['--dry-run', 'Validate and preview offline'];
|
|
34
|
+
const fieldOption = ['--fields <names>', 'Comma-separated documented resource fields'];
|
|
35
|
+
export const discountReadSpecs = [
|
|
36
|
+
...[['coupons', 'coupons', 'storeId', 'CouponFilter', couponListSchema, couponFields], ['promotion-codes', 'promotionCodes', 'couponId', 'PromotionCodeFilter', promotionListSchema, promotionFields]].map(([id, root, scope, filter, schema, resourceFields]) => ({
|
|
37
|
+
scalarListFields: id === 'coupons' ? ['productIds'] : [],
|
|
38
|
+
definition: { id: `${id}.list`, path: `${id} list`, effect: 'read', description: `Read one page of ${id}; customer emails are omitted`, file: true, schema, options: [['--limit <number>', 'Page size, 1–100 (default 20)'], ['--offset <number>', 'Zero-based offset'], fieldOption, preview], example: `pancake ${id} list --file input.json --json` }, documentation,
|
|
39
|
+
request: (input, options) => ({ query: `query CliDiscounts($scope: String!, $limit: Int!, $offset: Int!, $filter: ${filter}) { items: ${root}(${scope}: $scope, limit: $limit, offset: $offset, filter: $filter) { ${selection(resourceFields, options.fields)} } }`, variables: { scope: input[scope], limit: options.limit ?? 20, offset: options.offset ?? 0, filter: input.filter ?? {} } }),
|
|
40
|
+
})),
|
|
41
|
+
{ scalarListFields: ['productIds'], definition: { id: 'coupons.get', path: 'coupons get', effect: 'read', argument: 'id', description: 'Get a coupon by ID', schema: objectSchema({ id: couponId }, ['id']), options: [fieldOption, preview], example: 'pancake coupons get CPN_0000000000000000000001 --json' }, documentation,
|
|
42
|
+
request: (input, options) => ({ query: `query CliCoupon($id: String!) { item: coupon(id: $id) { ${selection(couponFields, options.fields)} } }`, variables: { id: input.id } }) },
|
|
43
|
+
];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { objectSchema, storeId } from "./schemas.js";
|
|
2
|
+
import { positiveAmount, currency, productId } from "./action-values.js";
|
|
3
|
+
export const couponId = { type: 'string', pattern: '^CPN_[A-Za-z0-9]{22}$' };
|
|
4
|
+
const promotionId = { type: 'string', pattern: '^PMC_[A-Za-z0-9]{22}$' };
|
|
5
|
+
const name = { type: 'string', minLength: 1, maxLength: 64, pattern: '\\S' };
|
|
6
|
+
const code = { type: 'string', pattern: '^[A-Za-z0-9-]{3,32}$' };
|
|
7
|
+
const limit = { type: ['integer', 'null'], minimum: 1, maximum: 2147483647 };
|
|
8
|
+
const date = { type: ['string', 'null'], pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$' };
|
|
9
|
+
const amounts = { type: 'object', minProperties: 1, propertyNames: currency, additionalProperties: positiveAmount };
|
|
10
|
+
const restrictions = objectSchema({
|
|
11
|
+
customerEmails: { type: 'array', maxItems: 100, items: { type: 'string', pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$' } },
|
|
12
|
+
perCustomerLimit: limit, maxRedemptions: limit, expiresAt: date,
|
|
13
|
+
minimumAmount: { anyOf: [amounts, { type: 'null' }] },
|
|
14
|
+
});
|
|
15
|
+
const promotion = { code, restrictions };
|
|
16
|
+
export const discountSchemas = {
|
|
17
|
+
'coupons.create': {
|
|
18
|
+
...objectSchema({ storeId, name, code,
|
|
19
|
+
discount: { oneOf: [objectSchema({ type: { const: 'percentage' }, percentOff: { type: 'number', exclusiveMinimum: 0, maximum: 100, multipleOf: 0.01 } }, ['type', 'percentOff']), objectSchema({ type: { const: 'fixed_amount' }, amountOff: amounts }, ['type', 'amountOff'])] },
|
|
20
|
+
duration: { enum: ['once', 'repeating', 'forever'] }, durationInPeriods: limit,
|
|
21
|
+
productIds: { type: 'array', maxItems: 100, items: productId }, maxRedemptions: limit, redeemBy: date,
|
|
22
|
+
promotionCodes: { type: 'array', maxItems: 20, items: objectSchema(promotion) },
|
|
23
|
+
}, ['storeId', 'name', 'discount']),
|
|
24
|
+
if: { required: ['duration'], properties: { duration: { const: 'repeating' } } },
|
|
25
|
+
then: { required: ['durationInPeriods'], properties: { durationInPeriods: { type: 'integer' } } },
|
|
26
|
+
else: { properties: { durationInPeriods: { type: 'null' } } },
|
|
27
|
+
},
|
|
28
|
+
'coupons.update': objectSchema({ id: couponId, name }, ['id', 'name']),
|
|
29
|
+
'coupons.deactivate': objectSchema({ id: couponId }, ['id']),
|
|
30
|
+
'promotion-codes.create': objectSchema({ couponId, ...promotion }, ['couponId']),
|
|
31
|
+
'promotion-codes.generate': objectSchema({ couponId, count: { type: 'integer', minimum: 1, maximum: 500 }, prefix: { type: 'string', pattern: '^[A-Za-z0-9-]{1,12}$' }, length: { type: 'integer', minimum: 8, maximum: 16 }, restrictions }, ['couponId', 'count']),
|
|
32
|
+
'promotion-codes.deactivate': objectSchema({ id: promotionId }, ['id']),
|
|
33
|
+
};
|
|
34
|
+
const string = { type: 'string' };
|
|
35
|
+
const stringFilter = objectSchema({ eq: string, ne: string, in: { type: 'array', items: string }, notIn: { type: 'array', items: string }, contains: string, startsWith: string, endsWith: string, isNull: { type: 'boolean' } });
|
|
36
|
+
const statusFilter = (values) => objectSchema({ eq: { enum: values }, ne: { enum: values }, in: { type: 'array', items: { enum: values } }, notIn: { type: 'array', items: { enum: values } } });
|
|
37
|
+
const createdAt = objectSchema({ ...Object.fromEntries(['eq', 'ne', 'gt', 'gte', 'lt', 'lte'].map(key => [key, string])), isNull: { type: 'boolean' } });
|
|
38
|
+
export const couponListSchema = objectSchema({ storeId, filter: objectSchema({ id: stringFilter, name: stringFilter, code: stringFilter, anyCode: objectSchema({ eq: string, in: { type: 'array', items: string }, startsWith: string, contains: string }), status: statusFilter(['active', 'inactive', 'failed']), isExhausted: { type: 'boolean' }, isExpired: { type: 'boolean' }, isRedeemable: { type: 'boolean' }, createdAt }) }, ['storeId']);
|
|
39
|
+
export const promotionListSchema = objectSchema({ couponId, filter: objectSchema({ id: stringFilter, code: stringFilter, batchId: stringFilter, status: statusFilter(['active', 'inactive']), createdAt }) }, ['couponId']);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { argumentError } from "../contracts/errors.js";
|
|
2
|
+
export function validateDiscountInput(id, input) {
|
|
3
|
+
if (!id.startsWith('coupons.') && !id.startsWith('promotion-codes.'))
|
|
4
|
+
return;
|
|
5
|
+
if (id === 'coupons.create') {
|
|
6
|
+
const codes = [input.code, ...(input.promotionCodes ?? []).map(item => item.code)].filter((value) => typeof value === 'string').map(value => value.toUpperCase());
|
|
7
|
+
if (new Set(codes).size !== codes.length)
|
|
8
|
+
throw argumentError('Coupon and promotion codes must be unique within the request (case-insensitive).');
|
|
9
|
+
}
|
|
10
|
+
const restrictions = [input.restrictions, ...(input.promotionCodes ?? []).map(item => item.restrictions)].filter((value) => !!value && typeof value === 'object');
|
|
11
|
+
for (const value of [input.redeemBy, ...restrictions.map(item => item.expiresAt)]) {
|
|
12
|
+
if (value === undefined || value === null)
|
|
13
|
+
continue;
|
|
14
|
+
if (typeof value !== 'string' || !Number.isFinite(Date.parse(value)) || Date.parse(value) <= Date.now() + 60_000)
|
|
15
|
+
throw argumentError('Discount expiry must be a valid ISO datetime more than 60 seconds in the future.');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { loopbackTarget } from "../contracts/loopback-target.js";
|
|
2
|
+
import { argumentError } from "../contracts/errors.js";
|
|
3
|
+
export function listenInput(options) {
|
|
4
|
+
if (!options.storeId || !/^STO_[A-Za-z0-9]+$/.test(options.storeId))
|
|
5
|
+
throw argumentError('Provide a valid --store-id.');
|
|
6
|
+
const url = loopbackTarget(options.forwardTo);
|
|
7
|
+
const events = options.events?.split(',');
|
|
8
|
+
if (events && (events.length > 100 || events.some(event => !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(event)) || new Set(events).size !== events.length)) {
|
|
9
|
+
throw argumentError('--events requires unique comma-separated event names.');
|
|
10
|
+
}
|
|
11
|
+
return { storeId: options.storeId, url, events, environment: options.live ? 'prod' : 'test' };
|
|
12
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const policies = {
|
|
2
|
+
'products.publish': 'test-to-prod', 'groups.publish': 'test-to-prod',
|
|
3
|
+
'stores.create': 'shared', 'stores.update': 'shared', 'stores.delete': 'shared',
|
|
4
|
+
'recipients.add': 'shared', 'recipients.update': 'shared', 'recipients.remove': 'shared',
|
|
5
|
+
'webhook.add': 'test-only', 'webhook.update': 'test-only', 'webhook.remove': 'test-only',
|
|
6
|
+
};
|
|
7
|
+
/** One command rule for discovery, offline previews and verified execution. */
|
|
8
|
+
export function operationImpact(command, environment) {
|
|
9
|
+
const impactPolicy = command.effect === 'write' ? policies[command.id] ?? 'selected-environment' : 'none';
|
|
10
|
+
const fixedImpacts = { none: null, 'test-only': 'test', shared: 'shared', 'test-to-prod': 'test-to-prod' };
|
|
11
|
+
const impact = impactPolicy === 'selected-environment' ? environment ?? null : fixedImpacts[impactPolicy];
|
|
12
|
+
const production = environment === undefined ? 'when-prod' : environment === 'prod';
|
|
13
|
+
const requiresProductionConfirmation = { none: false, 'test-only': false, shared: production, 'test-to-prod': true, 'selected-environment': production };
|
|
14
|
+
return { impact, impactPolicy, requiresProductionConfirmation: requiresProductionConfirmation[impactPolicy],
|
|
15
|
+
requiresSharedConfirmation: impactPolicy === 'shared' };
|
|
16
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { objectSchema, string } from "./schemas.js";
|
|
2
|
+
import { amount, currency, productId, positiveAmount, taxCategory } from "./action-values.js";
|
|
3
|
+
const priceSchema = (subscription) => ({
|
|
4
|
+
type: 'object', description: 'Replaces all existing prices. Omitted currencies are removed; include every currency and price setting to keep.', minProperties: 1, propertyNames: currency,
|
|
5
|
+
additionalProperties: objectSchema({
|
|
6
|
+
amount: positiveAmount, taxCategory,
|
|
7
|
+
...(subscription ? { trialAmount: amount } : {}),
|
|
8
|
+
}, ['amount', 'taxCategory']),
|
|
9
|
+
});
|
|
10
|
+
const updateFields = {
|
|
11
|
+
id: productId,
|
|
12
|
+
name: { ...string, maxLength: 64 },
|
|
13
|
+
description: { type: ['string', 'null'] },
|
|
14
|
+
media: { type: 'array', items: objectSchema({ type: { enum: ['image', 'video'] }, url: string, alt: { type: 'string' }, thumbnail: string }, ['type', 'url']) },
|
|
15
|
+
successUrl: { anyOf: [{ type: 'string', format: 'http-url', maxLength: 512 }, { const: '' }, { type: 'null' }] },
|
|
16
|
+
};
|
|
17
|
+
export const productUpdateSchema = { oneOf: [
|
|
18
|
+
objectSchema({ ...updateFields, type: { const: 'onetime' }, prices: priceSchema(false), metadata: { type: 'object', maxProperties: 50, additionalProperties: true } }, ['type', 'id']),
|
|
19
|
+
objectSchema({
|
|
20
|
+
...updateFields, type: { const: 'subscription' }, prices: priceSchema(true),
|
|
21
|
+
billingPeriod: { enum: ['weekly', 'monthly', 'quarterly', 'yearly'] },
|
|
22
|
+
metadata: { type: 'object', properties: { trialDays: { type: 'integer', minimum: 1, maximum: 365 } }, additionalProperties: true },
|
|
23
|
+
}, ['type', 'id']),
|
|
24
|
+
] };
|
|
25
|
+
export const productPublishSchema = objectSchema({ type: { enum: ['onetime', 'subscription'] }, id: productId }, ['type', 'id']);
|
|
26
|
+
export const productStatusSchema = objectSchema({ type: { enum: ['onetime', 'subscription'] }, id: productId, status: { enum: ['active', 'inactive'] } }, ['type', 'id', 'status']);
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { discountReadSpecs } from "./discount-definitions.js";
|
|
2
|
+
import { argumentError } from "../contracts/errors.js";
|
|
3
|
+
import { objectSchema, storeId, merchantId } from "./schemas.js";
|
|
4
|
+
import { orderListSchema, productId, productListSchema, querySchema, readFilters, readId } from "./read-schemas.js";
|
|
5
|
+
import { filterArgument, readOnlyRequest, selection } from "./read-query.js";
|
|
6
|
+
const docs = 'https://docs.waffo.ai/api-reference/endpoints/';
|
|
7
|
+
const productDocs = `${docs}graphql/stores-and-products`;
|
|
8
|
+
const orderDocs = `${docs}graphql/orders-and-payments`;
|
|
9
|
+
const previewOption = ['--dry-run', 'Validate and preview the query offline'];
|
|
10
|
+
const fieldOption = ['--fields <names>', 'Comma-separated documented top-level resource fields'];
|
|
11
|
+
const typeOption = ['--type <type>', 'onetime or subscription (required)'];
|
|
12
|
+
const listOptions = [['--limit <number>', 'Page size, 1–100 (default 20)'], ['--offset <number>', 'Zero-based offset (default 0)'], fieldOption, previewOption];
|
|
13
|
+
const fields = (...names) => Object.fromEntries(names.map(name => [name, name]));
|
|
14
|
+
const productFields = { ...fields('id', 'name', 'status', 'createdAt', 'updatedAt'), prices: 'prices { currency priceInfo { amount taxCategory } }' };
|
|
15
|
+
const subscriptionFields = { ...productFields, billingPeriod: 'billingPeriod', prices: 'prices { currency priceInfo { amount taxCategory trialAmount } }' };
|
|
16
|
+
const onetimeOrderFields = { ...fields('id', 'buyerEmail', 'currency', 'status', 'orderMerchantExternalId', 'createdAt'), priceSnapshot: 'priceSnapshot { currency subtotal taxAmount total taxCategory }' };
|
|
17
|
+
const subscriptionOrderFields = fields('id', 'buyerEmail', 'status', 'billingPeriod', 'orderMerchantExternalId', 'createdAt', 'currentPeriodStart', 'currentPeriodEnd', 'currentPeriodNumber');
|
|
18
|
+
const paymentFields = { ...fields('id', 'orderId', 'status', 'refundStatus', 'orderMerchantExternalId', 'periodNumber', 'createdAt'), snapshotAmountDetails: 'snapshotAmountDetails { subtotal taxAmount total currency }' };
|
|
19
|
+
const refundFields = { ...fields('id', 'paymentId', 'ticketId', 'status', 'orderMerchantExternalId', 'refundTicketMerchantExternalId', 'createdAt'), pspAmountDetails: 'pspAmountDetails { amount currency }' };
|
|
20
|
+
const refundTicketFields = { ...fields('id', 'status', 'refundTicketMerchantExternalId', 'reviewNote', 'rejectReason', 'executedAt', 'createdAt'), versionData: 'versionData { reason requestedAmount { amount currency } }' };
|
|
21
|
+
const storeFields = fields('id', 'name', 'status', 'slug', 'supportEmail', 'website', 'prodEnabled', 'createdAt', 'updatedAt');
|
|
22
|
+
function productType(options) {
|
|
23
|
+
if (options.type !== 'onetime' && options.type !== 'subscription')
|
|
24
|
+
throw argumentError('Provide --type onetime or --type subscription.');
|
|
25
|
+
return options.type;
|
|
26
|
+
}
|
|
27
|
+
function listRequest(root, resourceFields, input, options, storeArgument = false) {
|
|
28
|
+
const args = ['limit: $limit', 'offset: $offset', filterArgument((input.filter ?? {}))];
|
|
29
|
+
if (storeArgument)
|
|
30
|
+
args.push('storeId: $storeId');
|
|
31
|
+
return {
|
|
32
|
+
query: `query CliRead($limit: Int!, $offset: Int!${storeArgument ? ', $storeId: String!' : ''}) { items: ${root}(${args.filter(Boolean).join(', ')}) { ${selection(resourceFields, options.fields)} } }`,
|
|
33
|
+
variables: { limit: options.limit ?? 20, offset: options.offset ?? 0, ...(storeArgument ? { storeId: input.storeId } : {}) },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function listSpec(id, root, resourceFields, schema, documentation, storeArgument = false) {
|
|
37
|
+
return {
|
|
38
|
+
definition: { id: `${id}.list`, path: `${id} list`, description: `Read one page of ${id}`, effect: 'read', file: true, schema, options: listOptions, example: `pancake ${id} list${storeArgument ? ' --store-id STO_abc' : ''} --limit 20 --json` },
|
|
39
|
+
documentation: [documentation], request: (input, options) => listRequest(root, resourceFields, input, options, storeArgument),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function getSpec(id, root, resourceFields, idSchema, documentation, exampleId) {
|
|
43
|
+
return {
|
|
44
|
+
definition: { id: `${id}.get`, path: `${id} get`, argument: 'id', description: `Get a ${root} by ID`, effect: 'read', schema: objectSchema({ id: idSchema }, ['id']), options: [fieldOption, previewOption], example: `pancake ${id} get ${exampleId} --json` },
|
|
45
|
+
documentation: [documentation], request: (input, options) => ({ query: `query CliRead($id: String!) { item: ${root}(id: $id) { ${selection(resourceFields, options.fields)} } }`, variables: { id: input.id } }),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const ordersList = listSpec('orders', 'onetimeOrders', onetimeOrderFields, orderListSchema, orderDocs, true);
|
|
49
|
+
export const readSpecs = [
|
|
50
|
+
...discountReadSpecs,
|
|
51
|
+
getSpec('stores', 'store', storeFields, storeId, productDocs, 'STO_abc'),
|
|
52
|
+
{
|
|
53
|
+
definition: { id: 'products.list', path: 'products list', description: 'List products in the credential environment; JSON filter file is optional', effect: 'read', file: true, schema: productListSchema, options: [typeOption, ...listOptions], example: 'pancake products list --type onetime --store-id STO_abc --json' },
|
|
54
|
+
documentation: [productDocs, `${docs}graphql/overview`],
|
|
55
|
+
request(input, options) {
|
|
56
|
+
const type = productType(options);
|
|
57
|
+
return listRequest(`${type}Products`, type === 'onetime' ? productFields : subscriptionFields, input, options, input.storeId !== undefined);
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
definition: { id: 'products.versions', path: 'products versions', argument: 'id', description: 'Read product version history (no pagination)', effect: 'read', schema: objectSchema({ id: productId }, ['id']), options: [typeOption, fieldOption, previewOption], example: 'pancake products versions PROD_abc --type onetime --json' },
|
|
62
|
+
documentation: [productDocs],
|
|
63
|
+
request(input, options) {
|
|
64
|
+
const type = productType(options);
|
|
65
|
+
const versionFields = fields('id', 'versionNumber', 'name', 'createdAt');
|
|
66
|
+
if (type === 'subscription')
|
|
67
|
+
versionFields.billingPeriod = 'billingPeriod';
|
|
68
|
+
return { query: `query CliVersions($productId: String!) { items: ${type}ProductVersions(productId: $productId) { ${selection(versionFields, options.fields)} } }`, variables: { productId: input.id } };
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
...ordersList,
|
|
73
|
+
definition: { ...ordersList.definition, description: 'List onetime or subscription orders in a store', options: [typeOption, ...listOptions], example: 'pancake orders list --type onetime --store-id STO_abc --json' },
|
|
74
|
+
request: (input, options) => {
|
|
75
|
+
const type = productType(options);
|
|
76
|
+
return listRequest(`${type}Orders`, type === 'onetime' ? onetimeOrderFields : subscriptionOrderFields, input, options, true);
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
listSpec('subscriptions', 'subscriptionOrders', subscriptionOrderFields, orderListSchema, orderDocs, true),
|
|
80
|
+
listSpec('payments', 'payments', paymentFields, objectSchema({ filter: readFilters.payments }), orderDocs),
|
|
81
|
+
getSpec('payments', 'payment', paymentFields, readId, orderDocs, 'PAY_abc'),
|
|
82
|
+
listSpec('refunds', 'refunds', refundFields, objectSchema({ filter: readFilters.refunds }), orderDocs),
|
|
83
|
+
getSpec('refunds', 'refund', refundFields, readId, orderDocs, 'RFD_abc'),
|
|
84
|
+
listSpec('refund-tickets', 'refundTickets', refundTicketFields, objectSchema({ filter: readFilters.refundTickets }), orderDocs),
|
|
85
|
+
listSpec('recipients', 'storeNotificationRecipients', { ...fields('id', 'email', 'isPrimary', 'createdAt'), preferences: 'preferences { notifyNewOrders notifyNewSubscriptions notifySubscriptionCanceled notifySubscriptionRenewed notifySubscriptionEnded notifySubscriptionPastDue notifySubscriptionUncanceled notifySubscriptionPlanChanged notifyChargeback notifyRefundSucceeded }' }, objectSchema({ storeId }, ['storeId']), `${docs}notification-recipients/overview`, true),
|
|
86
|
+
listSpec('merchants', 'merchants', fields('id', 'email', 'status', 'createdAt'), objectSchema({}), productDocs),
|
|
87
|
+
getSpec('merchants', 'merchant', fields('id', 'email', 'status', 'createdAt', 'updatedAt'), merchantId, productDocs, 'MER_abc'),
|
|
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` },
|
|
90
|
+
sensitiveOutput: true, documentation: [`${docs}graphql/${resource === 'analytics' ? 'analytics' : 'overview'}`], request: (input) => readOnlyRequest(input),
|
|
91
|
+
})),
|
|
92
|
+
];
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Kind, getOperationAST, parse, print } from 'graphql';
|
|
2
|
+
import { argumentError } from "../contracts/errors.js";
|
|
3
|
+
export function graphqlValue(value) {
|
|
4
|
+
if (value === null)
|
|
5
|
+
return { kind: Kind.NULL };
|
|
6
|
+
if (typeof value === 'string')
|
|
7
|
+
return { kind: Kind.STRING, value };
|
|
8
|
+
if (typeof value === 'boolean')
|
|
9
|
+
return { kind: Kind.BOOLEAN, value };
|
|
10
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
11
|
+
return { kind: Number.isInteger(value) ? Kind.INT : Kind.FLOAT, value: String(value) };
|
|
12
|
+
if (Array.isArray(value))
|
|
13
|
+
return { kind: Kind.LIST, values: value.map(graphqlValue) };
|
|
14
|
+
if (typeof value === 'object' && value !== null) {
|
|
15
|
+
return { kind: Kind.OBJECT, fields: Object.entries(value).map(([key, field]) => {
|
|
16
|
+
if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(key))
|
|
17
|
+
throw argumentError('Filter keys must be GraphQL names.');
|
|
18
|
+
return { kind: Kind.OBJECT_FIELD, name: { kind: Kind.NAME, value: key }, value: graphqlValue(field) };
|
|
19
|
+
}) };
|
|
20
|
+
}
|
|
21
|
+
throw argumentError('Filters must contain JSON values.');
|
|
22
|
+
}
|
|
23
|
+
export function filterArgument(filter) {
|
|
24
|
+
return Object.keys(filter).length ? `filter: ${print(graphqlValue(filter))}` : '';
|
|
25
|
+
}
|
|
26
|
+
export function selection(fields, selected) {
|
|
27
|
+
const names = selected === undefined ? Object.keys(fields) : selected.split(',');
|
|
28
|
+
if (!names.length || names.some(name => !Object.hasOwn(fields, name)))
|
|
29
|
+
throw argumentError('Unknown field selection. Use the documented result field names.');
|
|
30
|
+
return [...new Set(names)].map(name => fields[name]).join(' ');
|
|
31
|
+
}
|
|
32
|
+
export function readOnlyRequest(input) {
|
|
33
|
+
if (typeof input.query !== 'string' || !input.query.trim())
|
|
34
|
+
throw argumentError('Provide a GraphQL query string in the JSON file.');
|
|
35
|
+
if (input.variables !== undefined && (typeof input.variables !== 'object' || input.variables === null || Array.isArray(input.variables)))
|
|
36
|
+
throw argumentError('GraphQL variables must be a JSON object.');
|
|
37
|
+
let document;
|
|
38
|
+
try {
|
|
39
|
+
document = parse(input.query);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw argumentError('The GraphQL document has invalid syntax.');
|
|
43
|
+
}
|
|
44
|
+
const operation = getOperationAST(document);
|
|
45
|
+
if (!operation || operation.operation !== 'query' || document.definitions.some(definition => definition.kind !== Kind.FRAGMENT_DEFINITION && (definition.kind !== Kind.OPERATION_DEFINITION || definition.operation !== 'query'))) {
|
|
46
|
+
throw argumentError('Provide exactly one query operation; mutations, subscriptions and schema definitions are not allowed.');
|
|
47
|
+
}
|
|
48
|
+
return { query: print(document), variables: (input.variables ?? {}) };
|
|
49
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { objectSchema, storeId } from "./schemas.js";
|
|
2
|
+
export const readId = { type: 'string', minLength: 1, maxLength: 128 };
|
|
3
|
+
export const productId = { type: 'string', pattern: '^PROD_[A-Za-z0-9]+$' };
|
|
4
|
+
const string = { type: 'string' };
|
|
5
|
+
const stringFilter = objectSchema({ eq: string, ne: string, in: { type: 'array', items: string }, contains: string });
|
|
6
|
+
const dateFilter = objectSchema({ eq: string, gt: string, lt: string, gte: string, lte: string });
|
|
7
|
+
const amountFilter = objectSchema(Object.fromEntries(['eq', 'ne', 'gt', 'gte', 'lt', 'lte'].map(key => [key, { type: 'string', pattern: '^\\d+(\\.\\d+)?$' }])));
|
|
8
|
+
export const readFilters = {
|
|
9
|
+
products: objectSchema({ status: stringFilter }),
|
|
10
|
+
orders: objectSchema({ status: stringFilter, createdAt: dateFilter, orderMerchantExternalId: stringFilter }),
|
|
11
|
+
payments: { ...objectSchema({ status: stringFilter, createdAt: dateFilter, orderMerchantExternalId: stringFilter, amount: amountFilter, currency: stringFilter }), if: { required: ['amount'] }, then: { required: ['currency'], properties: { currency: objectSchema({ eq: { type: 'string', pattern: '^[A-Za-z]{3}$' } }, ['eq']) } } },
|
|
12
|
+
refunds: objectSchema({ paymentId: stringFilter, refundTicketMerchantExternalId: stringFilter }),
|
|
13
|
+
refundTickets: objectSchema({ status: stringFilter, subjectId: stringFilter, refundTicketMerchantExternalId: stringFilter }),
|
|
14
|
+
};
|
|
15
|
+
export const productListSchema = objectSchema({ storeId, filter: readFilters.products });
|
|
16
|
+
export const orderListSchema = objectSchema({ storeId, filter: readFilters.orders }, ['storeId']);
|
|
17
|
+
export const querySchema = objectSchema({ query: { type: 'string', minLength: 1 }, variables: { type: 'object', additionalProperties: true } }, ['query']);
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { actionSpecs } from "./action-definitions.js";
|
|
2
|
+
import { readSpecs } from "./read-definitions.js";
|
|
3
|
+
import { objectSchema, productSchema, storeId, string, webhookSchemas } from "./schemas.js";
|
|
4
|
+
const noInput = objectSchema({});
|
|
5
|
+
export const globalOptions = [
|
|
6
|
+
['--json', 'Output JSON (listen streams NDJSON)'], ['--no-interactive', 'Never prompt'],
|
|
7
|
+
['--store-id <id>', 'Target store ID'], ['--yes', 'Confirm a remote change; does not bypass validation'],
|
|
8
|
+
['--confirm-production', 'Explicitly allow this operation to affect Production; still requires --yes'],
|
|
9
|
+
['--confirm-shared', 'Explicitly allow changes shared by Test and Production; still requires --yes'],
|
|
10
|
+
['--debug', 'Write redacted request diagnostics to stderr'],
|
|
11
|
+
];
|
|
12
|
+
const paginationOptions = [['--limit <number>', 'Page size, 1–100 (default 20)'], ['--offset <number>', 'Zero-based offset (default 0)'], ['--fields <names>', 'Comma-separated top-level result fields']];
|
|
13
|
+
export const definitions = [
|
|
14
|
+
{ id: 'listen', path: 'listen', description: 'Forward temporary merchant event deliveries to a loopback receiver', schema: noInput, effect: 'read', options: [['--forward-to <url>', 'HTTP(S) loopback receiver URL (required)'], ['--events <names>', 'Comma-separated event names'], ['--live', 'Explicitly listen in production; defaults to test']], example: 'pancake listen --store-id STO_abc --forward-to http://localhost:3000/webhook --json' },
|
|
15
|
+
{ id: 'commands', path: 'commands', description: 'List available commands (offline)', schema: noInput, effect: 'none', example: 'pancake commands --json' },
|
|
16
|
+
{ id: 'schema', path: 'schema', argument: 'command', description: 'Show command fields, output format and an example', schema: objectSchema({ command: string }, ['command']), effect: 'none', example: 'pancake schema webhook.add --json' },
|
|
17
|
+
{ id: 'login', path: 'login', description: 'Log in through your browser, or use an RSA key', schema: noInput, effect: 'local', options: [['--key-login', 'Enter an RSA key instead of opening a browser'], ['--api-url <origin>', 'Explicit API origin for browser login (HTTPS or local loopback)'], ['--dashboard-url <origin>', 'Explicit Dashboard origin for browser login (HTTPS or local loopback)'], ['--merchant-id <id>', 'Merchant ID for RSA login'], ['--private-key-file <path>', 'RSA private-key file path'], ['--key <value>', 'Auto-detect key or path; use the hidden prompt for secret contents']], example: 'pancake login --merchant-id MER_abc --private-key-file ./key.pem' },
|
|
18
|
+
{ id: 'env', path: 'env', argument: 'environment', description: 'Verify and select test or prod for your browser login', schema: objectSchema({ environment: { type: 'string', enum: ['test', 'prod'] } }, ['environment']), effect: 'local', example: 'pancake env test' },
|
|
19
|
+
{ id: 'whoami', path: 'whoami', description: 'Check your login and merchant identity', schema: noInput, effect: 'read', example: 'pancake whoami --json' },
|
|
20
|
+
{ id: 'logout', path: 'logout', description: 'Clear your saved login', schema: noInput, effect: 'local', example: 'pancake logout --json' },
|
|
21
|
+
{ id: 'config.show', path: 'config show', description: 'Show settings with secrets hidden', schema: noInput, effect: 'none', example: 'pancake config show --json' },
|
|
22
|
+
{ id: 'doctor', path: 'doctor', description: 'Check settings, connection and identity', schema: noInput, effect: 'read', example: 'pancake doctor --json' },
|
|
23
|
+
{ id: 'stores.list', path: 'stores list', description: 'Read one page of accessible stores', schema: noInput, options: paginationOptions, effect: 'read', example: 'pancake stores list --limit 20 --json' },
|
|
24
|
+
{ id: 'products.get', path: 'products get', argument: 'id', description: 'Read an onetime or subscription product', schema: objectSchema({ id: { type: 'string', pattern: '^PROD_[A-Za-z0-9]+$' } }, ['id']), options: [['--type <type>', 'onetime or subscription (required)'], ['--fields <names>', 'Comma-separated top-level result fields']], effect: 'read', example: 'pancake products get PROD_abc --type onetime --json' },
|
|
25
|
+
{ id: 'products.create', path: 'products create', description: 'Create an onetime or subscription product; requires --yes and may affect production', schema: productSchema, file: true, options: [['--type <type>', 'onetime or subscription (required)'], ['--dry-run', 'Validate and preview offline without any side effects'], ['--idempotency-key <key>', 'Unique operation key; used keys are never automatically replayed']], effect: 'write', example: 'pancake products create --type onetime --file product.json --dry-run --json' },
|
|
26
|
+
{ id: 'webhook.list', path: 'webhook list', description: 'List the configured store webhooks with the secret field omitted', schema: objectSchema({ storeId }, ['storeId']), effect: 'read', example: 'pancake webhook list --store-id STO_abc --json' },
|
|
27
|
+
...['add', 'update', 'remove'].map(action => ({
|
|
28
|
+
id: `webhook.${action}`, path: `webhook ${action}`, description: `${action} a test webhook using the existing API; requires --yes`,
|
|
29
|
+
schema: webhookSchemas[action], effect: 'write', argument: action === 'add' ? undefined : 'id', file: action !== 'remove',
|
|
30
|
+
options: [['--dry-run', 'Validate and preview offline without writing'], ['--idempotency-key <key>', 'Unique operation key; used keys are never automatically replayed']],
|
|
31
|
+
example: action === 'add' ? 'pancake webhook add --file webhook.json --yes --json' : `pancake webhook ${action} 11111111-2222-3333-4444-555555555555 --store-id STO_abc${action === 'update' ? ' --file changes.json' : ''} --yes --json`,
|
|
32
|
+
})),
|
|
33
|
+
{ id: 'operations.list', path: 'operations list', description: 'List local operation records', schema: noInput, options: [['--limit <number>', 'Maximum records, 1–100 (default 20)']], effect: 'none', example: 'pancake operations list --json' },
|
|
34
|
+
{ id: 'operations.show', path: 'operations show', argument: 'id', description: 'Show a local operation record', schema: objectSchema({ id: string }, ['id']), effect: 'none', example: 'pancake operations show <operation-id> --json' },
|
|
35
|
+
{ id: 'diagnostics.export', path: 'diagnostics export', description: 'Save a private diagnostics file locally', schema: noInput, options: [['--operation <id>', 'Operation ID (required)'], ['--output <path>', 'New output file path (required)']], effect: 'local', example: 'pancake diagnostics export --operation <operation-id> --output ./diagnostics.json' },
|
|
36
|
+
...actionSpecs.map(spec => spec.definition),
|
|
37
|
+
...readSpecs.map(spec => spec.definition),
|
|
38
|
+
];
|
|
39
|
+
export const outputContract = {
|
|
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
|
+
schemaVersion: 1, fields: ['schemaVersion', 'ok', 'data', 'error', 'meta'],
|
|
42
|
+
errorFields: ['code', 'message', 'stage', 'recovery', 'details'],
|
|
43
|
+
metaFields: ['cliVersion', 'outcome', 'operationId', 'requestId', 'merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'],
|
|
44
|
+
exitCodes: { success: 0, executionOrVerification: 1, argumentsOrConfiguration: 2, interrupted: 130 },
|
|
45
|
+
};
|