@visa/cli 4.1.0-rc.166 → 4.1.0-rc.168

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.
@@ -10,6 +10,27 @@ export interface CheckoutAdapter {
10
10
  }
11
11
  export declare function resolveLocator(page: Page, entry: FieldEntry): Locator;
12
12
  export declare function scrubFillErrorMessage(message: string, value: string): string;
13
+ /**
14
+ * A fill failure in a few words, for a message a human reads.
15
+ *
16
+ * Playwright's error is a multi-line call log — useful in the evidence file,
17
+ * unreadable in a refusal message and in the receipt an operator opens a week
18
+ * later. The refusal names WHICH fields refused; without this it never says
19
+ * WHY, so diagnosing a merchant we cannot drive means either reproducing it or
20
+ * reading someone's evidence JSON. Each cause maps to a different fix:
21
+ *
22
+ * not editable — the input exists but is readonly/disabled at fill time
23
+ * (a custom widget owning the value, or a not-yet-ready
24
+ * form). Typing will not help; the field needs an adapter
25
+ * or a longer wait.
26
+ * not a text field — a non-input element pretending to be one. Needs an
27
+ * adapter that drives the widget.
28
+ * not visible /
29
+ * detached — a re-render race. The reveal loop is the lever.
30
+ *
31
+ * Input is already scrubbed by scrubFillErrorMessage; this only ever shortens.
32
+ */
33
+ export declare function summarizeFillFailure(error: string | undefined): string;
13
34
  /**
14
35
  * The contact record and the page rarely agree on name shape: the record may
15
36
  * carry fullName while the page wants first/last inputs, or vice versa. Derive
@@ -74,6 +74,51 @@ export function scrubFillErrorMessage(message, value) {
74
74
  scrubbed = scrubbed.split(value).join('<redacted>');
75
75
  return scrubbed;
76
76
  }
77
+ /**
78
+ * A fill failure in a few words, for a message a human reads.
79
+ *
80
+ * Playwright's error is a multi-line call log — useful in the evidence file,
81
+ * unreadable in a refusal message and in the receipt an operator opens a week
82
+ * later. The refusal names WHICH fields refused; without this it never says
83
+ * WHY, so diagnosing a merchant we cannot drive means either reproducing it or
84
+ * reading someone's evidence JSON. Each cause maps to a different fix:
85
+ *
86
+ * not editable — the input exists but is readonly/disabled at fill time
87
+ * (a custom widget owning the value, or a not-yet-ready
88
+ * form). Typing will not help; the field needs an adapter
89
+ * or a longer wait.
90
+ * not a text field — a non-input element pretending to be one. Needs an
91
+ * adapter that drives the widget.
92
+ * not visible /
93
+ * detached — a re-render race. The reveal loop is the lever.
94
+ *
95
+ * Input is already scrubbed by scrubFillErrorMessage; this only ever shortens.
96
+ */
97
+ export function summarizeFillFailure(error) {
98
+ if (!error)
99
+ return 'no reason recorded';
100
+ if (/not an? <input>|not.*\[contenteditable\]/i.test(error))
101
+ return 'not a text field';
102
+ if (/element is not visible/i.test(error))
103
+ return 'not visible';
104
+ if (/not attached to the DOM|detached/i.test(error))
105
+ return 'detached from the page';
106
+ if (/element is not enabled/i.test(error))
107
+ return 'disabled';
108
+ if (/not editable/i.test(error)) {
109
+ const timeout = /Timeout (\d+)ms exceeded/i.exec(error);
110
+ return timeout
111
+ ? `not editable within ${Math.round(Number(timeout[1]) / 1000)}s`
112
+ : 'not editable';
113
+ }
114
+ if (/Timeout (\d+)ms exceeded/i.test(error)) {
115
+ const timeout = /Timeout (\d+)ms exceeded/i.exec(error);
116
+ return `timed out after ${Math.round(Number(timeout[1]) / 1000)}s`;
117
+ }
118
+ // Unrecognized: the first line, bounded. Better a clipped real message than a
119
+ // confident wrong summary.
120
+ return error.split('\n')[0].slice(0, 120);
121
+ }
77
122
  const DEFAULT_FILL_TIMEOUT_MS = 5000;
78
123
  async function fillOne(page, role, entry, value, displayValue, fillTimeoutMs) {
79
124
  const base = {
@@ -22,6 +22,7 @@ import { checkMandate, checkMandatePreFill } from './mandate.js';
22
22
  import { EvidenceLog, maskOtp } from './evidence.js';
23
23
  import { observeOutcome } from './outcome.js';
24
24
  import { selectAdapter } from './adapters/index.js';
25
+ import { summarizeFillFailure } from './adapters/generic.js';
25
26
  import { traceHandleFields } from './trace-handles.js';
26
27
  import { readGenericPageAmount } from './amount.js';
27
28
  import { webBotAuthHeadersOrNone } from './web-bot-auth.js';
@@ -1210,7 +1211,23 @@ export async function submitApprovedCheckout(reviewId, opts, store = defaultPrep
1210
1211
  // retryably instead of dangerously.
1211
1212
  if (failedFillRoles.length > 0) {
1212
1213
  evidence.setSnapshotSummary(await snapshotSummary(page));
1213
- return makeResult('partial-fill', state.fields, evidence, requiresAdapter, `required field fill failed: ${failedFillRoles.join(', ')} — not submitting an incomplete form. Nothing was charged.`, undefined, 'required-field-unfillable');
1214
+ // Name the CAUSE per field, not just the field. The refusal is the only
1215
+ // artifact that survives to the operator (a v2 receipt carries no evidence
1216
+ // log), and "city, postalCode refused" without a reason means the next
1217
+ // person has to reproduce a live merchant to learn anything. Each cause
1218
+ // points at a different fix — see summarizeFillFailure.
1219
+ //
1220
+ // Last attempt wins: a role that failed differently across reveal passes
1221
+ // is best described by how it failed when we finally gave up on it.
1222
+ const lastFillError = (role) => {
1223
+ const errors = evidence
1224
+ .getSteps()
1225
+ .filter((step) => step.type === 'field-fill' && step.data.ok === false && step.data.role === role)
1226
+ .map((step) => (typeof step.data.error === 'string' ? step.data.error : undefined));
1227
+ return errors[errors.length - 1];
1228
+ };
1229
+ const reasons = failedFillRoles.map((role) => `${role} (${summarizeFillFailure(lastFillError(role))})`);
1230
+ return makeResult('partial-fill', state.fields, evidence, requiresAdapter, `required field fill failed: ${reasons.join(', ')} — not submitting an incomplete form. Nothing was charged.`, undefined, 'required-field-unfillable');
1214
1231
  }
1215
1232
  if (!submit) {
1216
1233
  evidence.setSnapshotSummary(await snapshotSummary(page));
@@ -1251,6 +1268,12 @@ export async function submitApprovedCheckout(reviewId, opts, store = defaultPrep
1251
1268
  credentialExpiresAt,
1252
1269
  });
1253
1270
  }
1271
+ // ORDER IS LOAD-BEARING: record the click BEFORE performing it. The catch
1272
+ // block classifies a throw by whether this step exists — recorded means
1273
+ // "we may have charged" (`unverified`), absent means "retry is safe"
1274
+ // (`failed`). Recording after `submit.click()` would let a throw raised by
1275
+ // the click itself look retry-safe, which is the double-charge direction.
1276
+ // Pinned by "a throw AFTER the pay control was clicked reports unverified".
1254
1277
  evidence.step('submit', { clicked: true, target: submit.desc });
1255
1278
  await submit.click();
1256
1279
  await settle(page);
@@ -44,7 +44,12 @@ export function buildReceipt(input) {
44
44
  // retry.
45
45
  'The charge may have gone through. Confirm with the merchant before retrying.'
46
46
  : result.outcome === 'partial-fill'
47
- ? 'Nothing was submitted and nothing was charged. Safe to try again once the checkout can be filled.'
47
+ ? // A v2 receipt carries no evidence log, so this line is the only
48
+ // place the CAUSE survives — which field refused and why. An
49
+ // operator opening this a week later can act on it; "could not
50
+ // be filled" alone means reproducing a live merchant to learn
51
+ // anything.
52
+ `${result.detail ?? 'Nothing was submitted and nothing was charged.'} Safe to try again once the checkout can be filled.`
48
53
  : 'Review this outcome before retrying.';
49
54
  const recoveryActions = reconciliation.reasons.length > 0 ? reconciliation.reasons : [fallbackAction];
50
55
  const cardLast4 = input.cardLast4 && /^\d{4}$/.test(input.cardLast4) ? input.cardLast4 : null;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Outcomes whose receipt cannot rule out a charge.
3
+ *
4
+ * Both of these record a run where the pay control was clicked and no
5
+ * definitive answer came back:
6
+ * - `unverified` — no confirmation or decline observed before the deadline
7
+ * - `action-required` — an issuer challenge appeared, which happens AFTER the
8
+ * click, so the authorization may already exist
9
+ *
10
+ * Everything else is either definitive (`confirmed`, `declined`) or provably
11
+ * pre-click (`reviewed-dry-run`, `partial-fill`, `failed`, ...). Widening this
12
+ * set blocks legitimate retries; narrowing it lets a double charge through, so
13
+ * an outcome earns a place here only by being genuinely post-click.
14
+ */
15
+ export declare const MAY_HAVE_CHARGED_OUTCOMES: ReadonlySet<string>;
16
+ /** One local attempt that may have taken money and was never resolved. */
17
+ export type UnresolvedCharge = {
18
+ recordedAt: string;
19
+ host: string;
20
+ amount: string;
21
+ amountMinor: number;
22
+ currency: string;
23
+ outcome: string;
24
+ /** Receipt file basename, so a caller can name the evidence a human must check. */
25
+ receiptFile: string;
26
+ };
27
+ /**
28
+ * Local attempts that may have charged, newest first.
29
+ *
30
+ * Never throws: a missing directory (nothing has ever been checked out here)
31
+ * and an unreadable one both read as "no unresolved charges". The caller
32
+ * decides what an empty answer means — see the fail-open note at its call site.
33
+ */
34
+ export declare function readUnresolvedCharges(receiptDir?: string): Promise<UnresolvedCharge[]>;
@@ -0,0 +1,125 @@
1
+ // "Did this device already submit this exact purchase?", read back from the
2
+ // checkout receipts on disk.
3
+ //
4
+ // The engine now reports a submitted-but-unobserved checkout as `unverified`
5
+ // instead of `failed`, and pay_merchant tells the caller not to retry it. This
6
+ // module is the belt to that suspenders: even a caller that ignores the words
7
+ // can be stopped, because the previous attempt left a receipt.
8
+ //
9
+ // It answers one question — which local receipts record an attempt that MAY
10
+ // HAVE CHARGED and was never resolved — and deliberately answers nothing else.
11
+ // The matching (same merchant, same amount, recent enough) lives in the caller,
12
+ // which owns the policy; this side owns only the read.
13
+ //
14
+ // Sibling of confirmed-merchants.ts and loaded through the same seam: it
15
+ // imports node built-ins and types only, so reading receipts never pulls
16
+ // playwright into the CLI process.
17
+ //
18
+ // Reading is best-effort by construction. The receipts directory is an operator
19
+ // artifact that anything on the box can touch, so an unreadable or malformed
20
+ // file is skipped rather than failing the whole read.
21
+ import { readdir, readFile } from 'node:fs/promises';
22
+ import { join } from 'node:path';
23
+ import { RECEIPT_DIR } from './receipt-dir.js';
24
+ /**
25
+ * Outcomes whose receipt cannot rule out a charge.
26
+ *
27
+ * Both of these record a run where the pay control was clicked and no
28
+ * definitive answer came back:
29
+ * - `unverified` — no confirmation or decline observed before the deadline
30
+ * - `action-required` — an issuer challenge appeared, which happens AFTER the
31
+ * click, so the authorization may already exist
32
+ *
33
+ * Everything else is either definitive (`confirmed`, `declined`) or provably
34
+ * pre-click (`reviewed-dry-run`, `partial-fill`, `failed`, ...). Widening this
35
+ * set blocks legitimate retries; narrowing it lets a double charge through, so
36
+ * an outcome earns a place here only by being genuinely post-click.
37
+ */
38
+ export const MAY_HAVE_CHARGED_OUTCOMES = new Set([
39
+ 'unverified',
40
+ 'action-required',
41
+ ]);
42
+ /**
43
+ * Every field this module reads, validated. Deliberately permissive about
44
+ * everything else: older and newer engines only have to carry these.
45
+ *
46
+ * Both receipt schemas expose all of them at the same paths, so unlike
47
+ * confirmed-merchants.ts there is nothing here that needs a per-schema branch.
48
+ */
49
+ function parseUnresolved(json, receiptFile) {
50
+ let parsed;
51
+ try {
52
+ parsed = JSON.parse(json);
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ if (typeof parsed !== 'object' || parsed === null)
58
+ return null;
59
+ const receipt = parsed;
60
+ if (receipt.schema !== 'checkout-agent-receipt/v1' &&
61
+ receipt.schema !== 'checkout-agent-receipt/v2') {
62
+ return null;
63
+ }
64
+ if (typeof receipt.outcome !== 'string' || !MAY_HAVE_CHARGED_OUTCOMES.has(receipt.outcome)) {
65
+ return null;
66
+ }
67
+ if (typeof receipt.recordedAt !== 'string' || Number.isNaN(Date.parse(receipt.recordedAt))) {
68
+ return null;
69
+ }
70
+ const host = receipt.merchant?.host;
71
+ if (typeof host !== 'string' || host.length === 0)
72
+ return null;
73
+ const transaction = receipt.transaction;
74
+ if (typeof transaction?.amount !== 'string')
75
+ return null;
76
+ if (typeof transaction.currency !== 'string')
77
+ return null;
78
+ // A receipt whose amount cannot be compared cannot gate a retry on amount, and
79
+ // a guard that silently matched every amount would be worse than none.
80
+ if (typeof transaction.amountMinor !== 'number' || !Number.isFinite(transaction.amountMinor)) {
81
+ return null;
82
+ }
83
+ return {
84
+ recordedAt: receipt.recordedAt,
85
+ host,
86
+ amount: transaction.amount,
87
+ amountMinor: transaction.amountMinor,
88
+ currency: transaction.currency,
89
+ outcome: receipt.outcome,
90
+ receiptFile,
91
+ };
92
+ }
93
+ /**
94
+ * Local attempts that may have charged, newest first.
95
+ *
96
+ * Never throws: a missing directory (nothing has ever been checked out here)
97
+ * and an unreadable one both read as "no unresolved charges". The caller
98
+ * decides what an empty answer means — see the fail-open note at its call site.
99
+ */
100
+ export async function readUnresolvedCharges(receiptDir = RECEIPT_DIR) {
101
+ let names;
102
+ try {
103
+ names = await readdir(receiptDir);
104
+ }
105
+ catch {
106
+ return [];
107
+ }
108
+ const charges = [];
109
+ for (const name of names) {
110
+ if (!name.endsWith('.json'))
111
+ continue;
112
+ let raw;
113
+ try {
114
+ raw = await readFile(join(receiptDir, name), 'utf8');
115
+ }
116
+ catch {
117
+ continue;
118
+ }
119
+ const charge = parseUnresolved(raw, name);
120
+ if (charge)
121
+ charges.push(charge);
122
+ }
123
+ charges.sort((left, right) => (left.recordedAt < right.recordedAt ? 1 : -1));
124
+ return charges;
125
+ }