@instabrain-sdks/api-client 2.4.0 → 2.5.0

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.
@@ -517,9 +517,67 @@ var APIErrorCode;
517
517
  APIErrorCode["AgentNotFound"] = "agentNotFound";
518
518
  /** Unexpected backend failure while processing a Start Application request. */
519
519
  APIErrorCode["InternalServerError"] = "internalServerError";
520
+ /**
521
+ * IB Term / Pure Term Start Application — the quote response referenced by
522
+ * `quoteResponseId` could not be found. HTTP 400 with `value: null`.
523
+ *
524
+ * Note: this code was removed in the 2.3.0 cleanup as "not returned by the
525
+ * API". That was true for the products checked at the time; it **is** returned
526
+ * by the IB Term and Pure Term start-application endpoints, so it is back and
527
+ * scoped. Do not delete it again without checking those two products.
528
+ */
529
+ APIErrorCode["DataNotFound"] = "dataNotFound";
520
530
  // ─── Payment & quote update (after Start Application) ─────────────────────
521
- /** Update quote or save EFT when payment is already recorded for the opportunity. */
531
+ /**
532
+ * Update quote or `saveEftPayment()` when a **successful** payment already
533
+ * exists for the opportunity — a prior EFT save, or a credit card that has
534
+ * already been charged.
535
+ *
536
+ * A credit card that was only captured and not yet charged does not trigger
537
+ * this on request validation. Do not rely on that edge case: treat EFT and
538
+ * credit card as mutually exclusive per `opportunityId`.
539
+ */
522
540
  APIErrorCode["PaymentAlreadyMade"] = "PaymentAlreadyMade";
541
+ // ─── Credit card payment — iframe gates (ADB / GIGDB / Final Expense) ─────
542
+ /** `getCcPaymentIframeUrl()` — a link already exists and the latest attempt has not failed (capture is `pending` or already `approved`). Reuse the URL you already have; a new one is only issued after a `failed` attempt. */
543
+ APIErrorCode["TcIframeLinkAlreadyGenerated"] = "TcIframeLinkAlreadyGenerated";
544
+ /** `getCcPaymentIframeUrl()` — the product does not support the credit card iframe. Returned for IB Term / Pure Term, which use shared EFT or their hand-off links instead. */
545
+ APIErrorCode["CcPaymentIframeNotSupportedForProduct"] = "CcPaymentIframeNotSupportedForProduct";
546
+ /** `getCcPaymentIframeUrl()` / `prepareDocsAndGetDeliveryChannels()` — Start Application has not completed successfully yet. */
547
+ APIErrorCode["ApplicationNotReady"] = "ApplicationNotReady";
548
+ /** `getCcPaymentIframeUrl()` — a successful EFT payment already exists. EFT and credit card are mutually exclusive per opportunity. */
549
+ APIErrorCode["EftPaymentAlreadyCompleted"] = "EftPaymentAlreadyCompleted";
550
+ // ─── Credit card decline codes — `finalSubmit()`, ADB / GIGDB only ────────
551
+ // Returned when the stored card is charged at final submit and the charge is
552
+ // declined. The application is NOT submitted. Recovery is always: request a
553
+ // new iframe URL → poll to `approved` → retry `finalSubmit()`.
554
+ // Final Expense never produces these — the carrier charges after underwriting.
555
+ /** Card CVV was rejected. */
556
+ APIErrorCode["PaymentCvvInvalid"] = "PaymentCvvInvalid";
557
+ /** Declined — the applicant must contact their bank. */
558
+ APIErrorCode["PaymentDeclinedContactBank"] = "PaymentDeclinedContactBank";
559
+ /** Card declined. */
560
+ APIErrorCode["PaymentDeclined"] = "PaymentDeclined";
561
+ /** Card declined permanently — do not retry the same card. */
562
+ APIErrorCode["PaymentDeclinedPermanent"] = "PaymentDeclinedPermanent";
563
+ /** Card PIN is locked. */
564
+ APIErrorCode["PaymentPinLocked"] = "PaymentPinLocked";
565
+ /** Insufficient funds on the card. */
566
+ APIErrorCode["PaymentInsufficientFunds"] = "PaymentInsufficientFunds";
567
+ /** Processor-side error while charging the card. */
568
+ APIErrorCode["PaymentProcessingError"] = "PaymentProcessingError";
569
+ /** Charge blocked as suspected fraud. */
570
+ APIErrorCode["PaymentSuspectedFraud"] = "PaymentSuspectedFraud";
571
+ /** Card is expired. */
572
+ APIErrorCode["PaymentCardExpired"] = "PaymentCardExpired";
573
+ /** Card data supplied in the iframe was invalid. */
574
+ APIErrorCode["PaymentInvalidCardData"] = "PaymentInvalidCardData";
575
+ /** Generic card error. */
576
+ APIErrorCode["PaymentCardError"] = "PaymentCardError";
577
+ /** Issuer requires the applicant to contact their bank. */
578
+ APIErrorCode["PaymentContactBank"] = "PaymentContactBank";
579
+ /** Generic payment-related failure at final submit. */
580
+ APIErrorCode["PaymentRelatedError"] = "PaymentRelatedError";
523
581
  // ─── Secure Sign ───────────────────────────────────────────────────────────
524
582
  /** Generic Secure Sign failure. */
525
583
  APIErrorCode["SecureSignRelatedError"] = "SecureSignRelatedError";
@@ -537,9 +595,34 @@ var APIErrorCode;
537
595
  APIErrorCode["EmailDeliveryFailed"] = "EmailDeliveryFailed";
538
596
  /** SMS delivery failed on Send PIN / Resend PIN. */
539
597
  APIErrorCode["MessageNotDelivered"] = "MessageNotDelivered";
540
- // ─── Final Submit ──────────────────────────────────────────────────────────
541
- /** EFT payment not saved — call `saveEftPayment()` before `finalSubmit()`. */
598
+ // ─── Final Submit — pre-submit gates, checked in this order ────────────────
599
+ // 1. SecureSignNotCompleted → 2. PaymentNotMade → 3. LatestPaymentNotSuccessful
600
+ // These are three distinct, separately actionable states. Do NOT collapse
601
+ // PaymentNotMade and LatestPaymentNotSuccessful into one client-side case:
602
+ // the first means "nothing to submit yet", the second means "a payment was
603
+ // tried and failed, start a new capture".
604
+ /** Secure signing has not been completed for the opportunity — finish the PIN flow (or confirm `isSignCompleted`) before `finalSubmit()`. */
605
+ APIErrorCode["SecureSignNotCompleted"] = "SecureSignNotCompleted";
606
+ /**
607
+ * No payment has been completed for the opportunity. Covers **two** cases:
608
+ * no payment was ever started (neither `saveEftPayment()` nor
609
+ * `getCcPaymentIframeUrl()`), **or** a credit card capture is still pending
610
+ * (iframe issued, `cc-payment-status` is `'pending'`).
611
+ *
612
+ * Recovery: complete the payment — finish the iframe and poll to `'approved'`,
613
+ * or save EFT — then retry. While capture is pending, reuse the stored iframe
614
+ * URL; do not request a new one.
615
+ */
542
616
  APIErrorCode["PaymentNotMade"] = "paymentNotMade";
617
+ /**
618
+ * A payment was attempted and the most recent attempt finished unsuccessfully
619
+ * (`cc-payment-status` is `'failed'` after a capture or charge decline).
620
+ *
621
+ * Recovery: call `getCcPaymentIframeUrl()` for a new capture, poll to
622
+ * `'approved'`, then retry `finalSubmit()`. Retrying `finalSubmit()` without a
623
+ * new successful capture returns this code again, not a fresh decline code.
624
+ */
625
+ APIErrorCode["LatestPaymentNotSuccessful"] = "LatestPaymentNotSuccessful";
543
626
  /** Fidelity carrier rejected or failed to process final submit. */
544
627
  APIErrorCode["FidelityFinalSubmitError"] = "FidelityFinalSubmitError";
545
628
  /** Underwriting status polling is not supported for the product (ADB/GIGDB) — Final Expense only. Returned by `pingFinalExpenseUnderwritingStatus()` / `pollFinalExpenseUnderwritingStatus()` for a non-Final-Expense opportunity. */
@@ -81,19 +81,43 @@ class APIValidationError extends InstaBrainError {
81
81
  'MessageNotDelivered': 'SMS delivery failed. Retry or switch to email.',
82
82
  'FidelityFinalSubmitError': 'Fidelity carrier rejected or failed to process the submission. Contact support with the opportunityId.',
83
83
  'FinalSubmitStatusNotSupported': 'Underwriting status polling is not supported for this product — Final Expense only.',
84
+ // Credit card payment — iframe gates
85
+ 'TcIframeLinkAlreadyGenerated': 'A payment link was already generated for this application. Reuse the existing link; a new one can only be issued after the current card attempt fails.',
86
+ 'CcPaymentIframeNotSupportedForProduct': 'Credit card payment is not available for this product. Use EFT payment instead.',
87
+ 'ApplicationNotReady': 'The application is not ready for this step. Complete the start-application step successfully, then retry.',
88
+ 'EftPaymentAlreadyCompleted': 'An EFT payment has already been completed for this application. EFT and credit card cannot both be used.',
89
+ // Credit card decline codes (ADB / GIGDB charge at final submit)
90
+ 'PaymentCvvInvalid': 'The card security code (CVV) was rejected. Please re-enter the card details.',
91
+ 'PaymentDeclinedContactBank': 'The card was declined. The cardholder should contact their bank, then try a different card.',
92
+ 'PaymentDeclined': 'The card was declined. Please try a different card.',
93
+ 'PaymentDeclinedPermanent': 'The card was permanently declined. Please use a different card.',
94
+ 'PaymentPinLocked': 'The card PIN is locked. Please use a different card.',
95
+ 'PaymentInsufficientFunds': 'The card has insufficient funds. Please use a different card.',
96
+ 'PaymentProcessingError': 'The payment processor could not complete the charge. Please try again or use a different card.',
97
+ 'PaymentSuspectedFraud': 'The charge was blocked as suspected fraud. Please use a different card.',
98
+ 'PaymentCardExpired': 'The card has expired. Please use a different card.',
99
+ 'PaymentInvalidCardData': 'The card details entered were invalid. Please re-enter them.',
100
+ 'PaymentCardError': 'There was a problem with the card. Please try a different card.',
101
+ 'PaymentContactBank': 'The card issuer requires the cardholder to contact their bank before this charge can proceed.',
102
+ 'PaymentRelatedError': 'The payment could not be completed. Capture a new card and retry the submission.',
103
+ // IB Term / Pure Term Start Application
104
+ 'dataNotFound': 'The quote could not be found for the supplied quoteResponseId. Create a new quote and retry.',
105
+ // Final Submit — pre-submit gates (checked in this order)
106
+ 'SecureSignNotCompleted': 'Secure signing is not complete. Finish the PIN flow before submitting.',
107
+ 'LatestPaymentNotSuccessful': 'The most recent payment attempt failed. Capture a new card and poll until approved, then retry final submit.',
84
108
  'AgentLogout': 'Agent session has expired. Please re-authenticate.',
85
109
  'InvalidBirthCountry': 'The birth country provided is not valid.',
86
110
  'InvalidBirthState': 'The birth state provided is not valid.',
87
111
  'InvalidResidenceState': 'The residence state provided is not valid.',
88
112
  'OneOfTheExistingCoveragesQuestionsNotFound': 'One or more existing coverage questions were not answered.',
89
- 'PaymentAlreadyMade': 'Payment has already been made for this application.',
113
+ 'PaymentAlreadyMade': 'A successful payment already exists for this application. EFT and credit card are mutually exclusive per opportunity.',
90
114
  'ErrorInSaveEftPaymentDetails': 'Failed to save EFT payment details. Please verify account information.',
91
115
  'InvalidPaymentScheduledDate': 'The scheduled payment date is not valid.',
92
116
  'ThirdPartyQuoteError': 'An error occurred while retrieving the quote.',
93
117
  'InvalidQuoteParameters': 'The quote parameters provided are not valid.',
94
118
  'InvalidStateCode': 'State not supported for ADB (MA, NH, AK unavailable; CA coming next release).',
95
119
  'InvalidAdbAgeRange': 'Age must be between 20 and 59 for ADB.',
96
- 'paymentNotMade': 'EFT payment must be completed before submitting the application.'
120
+ 'paymentNotMade': 'No payment has been completed — either none was started, or a credit card capture is still pending. Complete payment, then retry final submit.'
97
121
  };
98
122
  return errorMessages[this.errorCode] || this.message;
99
123
  }
@@ -125,9 +125,41 @@ export interface ThirdPartyGigdbAppReq {
125
125
  /** Required for KS or WA when willOtherCoverageBeReplacedOrFinanced === true */
126
126
  willOtherCoverageBeReplacedOrFinancedData?: GigdbWillOtherCoverageBeReplacedOrFinancedData | null;
127
127
  }
128
+ /**
129
+ * Request body for `POST /api/ThirdPartyPayment/save-eft-payment`.
130
+ *
131
+ * Shared across all full-flow products (GIGDB, ADB, Final Expense). Call after
132
+ * Start Application and before Prepare Signing Docs. Once EFT is saved, quote
133
+ * updates for the same `opportunityId` are blocked.
134
+ *
135
+ * Every field is required server-side. Format failures return
136
+ * `InvalidRequestFormat` with the offending PascalCase key under `value.fields`.
137
+ */
128
138
  export interface ThirdPartyEftPaymentReq {
139
+ /**
140
+ * The `opportunityId` from the Start Application response.
141
+ *
142
+ * Unlike `getCcPaymentIframeUrl()`, this endpoint applies **no
143
+ * application-readiness gate** — it only checks that the opportunity exists
144
+ * and that payment has not already completed. Still call it after Start
145
+ * Application in the integration flow.
146
+ *
147
+ * Errors: `OpportunityId is required.` / `OpportunityId does not exist.`
148
+ * (`InvalidRequestFormat`), or `PaymentAlreadyMade` when a successful payment
149
+ * already exists.
150
+ */
129
151
  opportunityId: string;
152
+ /**
153
+ * Name on the bank account. **Max 100 characters**, and may contain only
154
+ * **letters, spaces, hyphens, and apostrophes**.
155
+ *
156
+ * Errors: `Account holder name is required.` /
157
+ * `Account holder name must be 100 characters or fewer.` /
158
+ * `Account holder name may only contain letters, spaces, hyphens, and apostrophes.`
159
+ */
130
160
  accountHolderName: string | null;
161
+ /** 9-digit US bank routing number. Error: `Routing number must be 9 digits.` */
131
162
  routingNumber: string | null;
163
+ /** Bank account number, 4–17 digits. Error: `Account number must be 4 to 17 digits.` */
132
164
  accountNumber: string | null;
133
165
  }
@@ -237,8 +237,11 @@ export interface IBTermChildRiderInfo {
237
237
  /**
238
238
  * Request body for `POST /api/ThirdPartyIBTermApplication/start-application`.
239
239
  *
240
- * Source of truth: `THIRD_PARTY_ERROR_CODES.md` (IB Term Start Application section,
241
- * 2026-05). IB Term has product-specific fields ADB and GIGDB do not — height,
240
+ * Source of truth: the IB Term Start Application API page. The single
241
+ * `THIRD_PARTY_ERROR_CODES.md` catalog it previously cited has been retired —
242
+ * validation and business errors are now documented per endpoint instead.
243
+ *
244
+ * IB Term has product-specific fields ADB and GIGDB do not — height,
242
245
  * weight, driver license, primary care physician, structured tobacco/nicotine
243
246
  * usage, and the Dependent Child Rider's nested child + child-existing-coverage
244
247
  * arrays.
@@ -11,6 +11,7 @@ export * from './adb.types';
11
11
  export * from './ibterm.types';
12
12
  export * from './pureterm.types';
13
13
  export * from './finalexpense.types';
14
+ export * from './payment.types';
14
15
  export * from './secure-sign.types';
15
16
  /**
16
17
  * Base configuration for the InstaBrain SDK
@@ -28,4 +28,5 @@ __exportStar(require("./adb.types"), exports);
28
28
  __exportStar(require("./ibterm.types"), exports);
29
29
  __exportStar(require("./pureterm.types"), exports);
30
30
  __exportStar(require("./finalexpense.types"), exports);
31
+ __exportStar(require("./payment.types"), exports);
31
32
  __exportStar(require("./secure-sign.types"), exports);
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Card-capture status reported by
3
+ * `GET /api/ThirdPartyPayment/cc-payment-status`.
4
+ *
5
+ * `'pending'` is the only non-terminal value. Note that `'approved'` means the
6
+ * card **details were captured**, not that money moved:
7
+ * - **ADB / GIGDB** — the stored card is charged later, at `finalSubmit()`.
8
+ * - **Final Expense** — the carrier collects after underwriting; `finalSubmit()`
9
+ * never charges.
10
+ */
11
+ export type CcPaymentStatus = 'pending' | 'approved' | 'failed';
12
+ /**
13
+ * Response from `GET /api/ThirdPartyPayment/cc-payment-status`.
14
+ *
15
+ * Drive polling loops off {@link shouldContinuePolling} rather than comparing
16
+ * `status` — same convention as the Final Expense underwriting poller.
17
+ */
18
+ export interface ThirdPartyCcPaymentStatusRes {
19
+ status: CcPaymentStatus;
20
+ /** `true` only while `status` is `'pending'`; `false` for `'approved'` / `'failed'`. */
21
+ shouldContinuePolling: boolean;
22
+ }
23
+ /**
24
+ * Tuning options for {@link PaymentService.pollCcPaymentStatus}.
25
+ * All durations are in milliseconds.
26
+ *
27
+ * The status endpoint is rate-limited to **1 request per 10 seconds** per
28
+ * `opportunityId`, so `intervalMs` should never be set below `10_000`.
29
+ */
30
+ export interface PollCcPaymentStatusOptions {
31
+ /**
32
+ * Interval between polls. Default `10_000` (10s) — matches the documented
33
+ * rate limit. Do not go below `10_000` or the endpoint returns HTTP 429.
34
+ */
35
+ intervalMs?: number;
36
+ /**
37
+ * Client-side safety net. Default `1_800_000` (30 min) — the same budget as
38
+ * the Final Expense underwriting poller. Unlike that flow (which the backend
39
+ * terminates with `'TimedOut'` at 30 min), card capture has **no server-side
40
+ * timeout** — it simply stays `'pending'` until the applicant finishes the
41
+ * hosted form, so this budget is the only stop. On expiry the poll resolves
42
+ * with the last response rather than throwing.
43
+ */
44
+ maxTotalDurationMs?: number;
45
+ /**
46
+ * Progress callback invoked after every poll, including the terminal one.
47
+ * Useful for surfacing "waiting for card capture…" feedback instead of
48
+ * awaiting silently. Receives the result, the 1-based attempt number, and
49
+ * milliseconds elapsed since polling began.
50
+ */
51
+ onPoll?: (result: ThirdPartyCcPaymentStatusRes, attempt: number, elapsedMs: number) => void;
52
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ // ── Credit Card Payment (shared — ADB / GIGDB / Final Expense) ───────────────
3
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,59 +1,214 @@
1
1
  import { Gender, PaymentFrequency, PureTermRateClass, HealthClass } from './enums';
2
2
  import { ThirdPartyQuoteReqHeight, ThirdPartyQuoteReqRider } from './quote.types';
3
+ import { IBTermStartApplicationReq } from './ibterm.types';
4
+ /**
5
+ * Query parameters for the Pure Term rider lookup
6
+ * (`GET /api/ThirdPartyIbPureTermLookup/get-rider-details`).
7
+ *
8
+ * The `getPureTermRiderDetails()` facade takes positional arguments to match the
9
+ * IB Term convention; this interface is exported for callers who prefer to type
10
+ * their own request object.
11
+ */
12
+ export interface PureTermRiderDetailsRequest {
13
+ /** Two-letter US state code (e.g. "TX"). */
14
+ stateCode: string;
15
+ /** Applicant age, integer, 18–60 inclusive. */
16
+ age: number;
17
+ /** Whether the applicant uses nicotine. Must be sent explicitly — not optional. */
18
+ flagNicotineUse: boolean;
19
+ }
20
+ /** A single Pure Term rider option returned for a state/age/nicotine combination. */
21
+ export interface PureTermRider {
22
+ /**
23
+ * Pass into the Pure Term Quote request `riders[n].rider` to include this rider
24
+ * in the quote. Typed as string; tighten to an enum once the concrete value set
25
+ * is known.
26
+ */
27
+ riderCode: string;
28
+ /** Display title for UI rendering. */
29
+ riderTitle: string;
30
+ /** Display description for UI rendering. */
31
+ riderDescription: string;
32
+ }
33
+ /**
34
+ * Response from `GET /api/ThirdPartyIbPureTermLookup/get-rider-details`.
35
+ *
36
+ * Optional pre-quote step that filters available Pure Term riders by state, age,
37
+ * and nicotine use. When `flagProductNotAvailableForState` is `true`, the
38
+ * `riders` array is empty and Pure Term is not available for the given inputs —
39
+ * do not proceed to the Quote API.
40
+ *
41
+ * Shape is identical to the IB Term rider lookup response; the two products
42
+ * differ only in endpoint path and underlying availability rules.
43
+ */
44
+ export interface PureTermRiderDetailsResp {
45
+ /**
46
+ * `true` → Pure Term not available for the given `stateCode` / `age` /
47
+ * `flagNicotineUse` combination (e.g. WY, NY); the SDK returns this response
48
+ * as-is (it is a valid business state, not an error).
49
+ *
50
+ * `false` → Pure Term is available; `riders` lists the eligible rider options
51
+ * (may still be empty if no optional riders are configured for the combo).
52
+ */
53
+ flagProductNotAvailableForState: boolean;
54
+ /** Available riders for the state/age/nicotine combo. */
55
+ riders: PureTermRider[];
56
+ }
3
57
  /**
4
58
  * Request body for `POST /api/ThirdPartyIbPureTermQuote/get`.
5
59
  *
6
60
  * Source of truth: ThirdPartyTermQuoteRequest.cs (InstaPureTerm product).
7
61
  *
8
- * **Validation rules (enforced server-side):**
9
- * - `benefitPeriod` is required.
10
- * - **One rating input group is required** — supply ONE of:
11
- * (a) `rateClass`, OR
12
- * (b) `healthClass`, OR
13
- * (c) `height` + `weightInLbs` (both together).
14
- * - `age` OR `dateOfBirth` required; resolved age must be 18–60. When both
15
- * are provided, `dateOfBirth` takes priority.
16
- * - `stateCode` required.
62
+ * Pure Term uses the **same request shape and validation model as IB Term**;
63
+ * what differs is the product data — rate classes (which add Rated C / Rated D),
64
+ * term lengths (which add 15), and the coverage / benefit-period tables.
65
+ *
66
+ * **Validation rules, in the order the server checks them:**
67
+ * 1. `benefitPeriod` is required.
68
+ * 2. `stateCode`, when present, must be a state where Pure Term is available
69
+ * (not available in WY / NY).
70
+ * 3. At least one of `rateClass`, `healthClass`, or (`height` **and**
71
+ * `weightInLbs`) must be provided.
72
+ * 4. `rateClass`, when present, must be a valid Pure Term rate class.
73
+ * 5. `healthClass`, when present, must be valid.
74
+ * 6. `height` / `weightInLbs`, when present, must be a valid combination.
75
+ * 7. Age — derived from `dateOfBirth` when present, else `age` — must be 18–60
76
+ * inclusive.
77
+ * 8. `riders`, when present, must be valid for Pure Term.
78
+ * 9. When `stateCode` and (`age` or `dateOfBirth`) are present, `benefitPeriod`
79
+ * is checked against carrier availability (`BenefitPeriodNotAvailable`) and
80
+ * `faceAmount` against coverage rules (`CoverageNotAvailable`).
81
+ *
82
+ * **Error surfacing happens in two stages.** Request validation issues dedicated
83
+ * top-level codes only for `BenefitPeriodNotAvailable` and
84
+ * `CoverageNotAvailable`; every other failure at that stage — including an
85
+ * invalid rate class — surfaces as `InvalidRequestFormat` with a PascalCase
86
+ * field key under `value.fields`, at most one message per field.
87
+ *
88
+ * Once validation passes, the request runs through the shared quote-eligibility
89
+ * pipeline, which can still return top-level `NotAvailableForState`,
90
+ * `QuoteNotEligibleForGivenConditions`, `RiderNotAvailable`,
91
+ * `RiderFaceAmountNotValid`, or `outsideBuildChart`. Handle the full IB Term
92
+ * code set — do not assume those never occur for Pure Term.
17
93
  */
18
94
  export interface ThirdPartyPureTermQuoteReq {
19
95
  /**
20
- * Coverage amount in dollars.
21
- * Age-based limits apply — same schedule as IB Term.
22
- */
23
- faceAmount?: number | null;
24
- /** Term length in years. **Required.** Available: 10, 20, 30 (state/age/tobacco dependent). */
25
- benefitPeriod?: number | null;
26
- /** Whether the applicant uses tobacco or nicotine. */
27
- flagTobaccoUse: boolean;
28
- /** Applicant gender. */
29
- gender?: Gender | null;
30
- /** 2-letter US state code. Required. */
31
- stateCode?: string | null;
32
- /** Rate class — one of the three rating groups (†). */
96
+ * Coverage amount in dollars. **Required.**
97
+ *
98
+ * Allowed range depends on state, age, and nicotine use:
99
+ * up to age 55 — $50,000–$1,000,000; age 56 — max $900,000;
100
+ * 57 — $800,000; 58 — $700,000; 59 — $600,000; 60 — $500,000.
101
+ * Out-of-range values return `CoverageNotAvailable`.
102
+ */
103
+ faceAmount: number;
104
+ /**
105
+ * Term length in years. **Required.**
106
+ *
107
+ * Availability by age and nicotine use:
108
+ * ages 18–45 → 10, 15, 20, 30; ages 46–50 non-smoker → 10, 15, 20, 30;
109
+ * ages 46–50 smoker → 10, 15, 20; ages 51–60 → 10, 15, 20.
110
+ * Disallowed values return `BenefitPeriodNotAvailable`.
111
+ *
112
+ * Note 15 is a Pure-Term-only term length — IB Term offers 10 / 20 / 30.
113
+ */
114
+ benefitPeriod: number;
115
+ /** Applicant gender. **Required.** */
116
+ gender: Gender;
117
+ /**
118
+ * 2-letter US state code (e.g. "TX"). **Required.**
119
+ *
120
+ * Pure Term is not available in WY or NY. Send `stateCode` only — do **not**
121
+ * send `zipCode` on the Pure Term quote.
122
+ */
123
+ stateCode: string;
124
+ /** Payment frequency. **Required.** */
125
+ paymentFreq: PaymentFrequency;
126
+ /**
127
+ * Whether the applicant uses tobacco or nicotine.
128
+ * Defaults to `false` server-side when omitted.
129
+ */
130
+ flagTobaccoUse?: boolean | null;
131
+ /**
132
+ * Rate class — one of the three rating groups.
133
+ *
134
+ * Pure Term does **not** offer `Guaranteed`, unlike the general IB Term list.
135
+ * An invalid value returns `InvalidRequestFormat` with the field message
136
+ * "Rate class is invalid. Allowed values: Preferred Plus, Preferred, Standard,
137
+ * Standard Extra, Rated C, Rated D."
138
+ */
33
139
  rateClass?: PureTermRateClass | null;
34
- /** Health class — one of the three rating groups (†). */
140
+ /** Health class — one of the three rating groups. Case-insensitive server-side. */
35
141
  healthClass?: HealthClass | null;
36
142
  /**
37
143
  * Applicant height. Required together with `weightInLbs` when using the
38
144
  * height/weight rating path. Omit when rating via `rateClass` or `healthClass`.
145
+ * `feet` must be 1–8 and `inches` 0–11.
39
146
  */
40
147
  height?: ThirdPartyQuoteReqHeight | null;
41
148
  /** Applicant weight in lbs. Required together with `height`. */
42
149
  weightInLbs?: number | null;
43
150
  /** Applicant age (18–60). Provide `age` OR `dateOfBirth`. */
44
151
  age?: number | null;
45
- /** Applicant date of birth (ISO 8601). Takes priority over `age` when both are provided. */
152
+ /**
153
+ * Applicant date of birth (ISO 8601, e.g. `1990-10-10`). Must be in the past.
154
+ * Takes priority over `age` when both are provided.
155
+ */
46
156
  dateOfBirth?: string | null;
47
- /** Riders to include. Use `riderCode` values returned by the rider lookup endpoint. */
157
+ /**
158
+ * Riders to include. Omit or send `null` to quote without riders — the array is
159
+ * validated only when sent. Use `riderCode` values from
160
+ * {@link PureTermRiderDetailsResp}. A rider's face amount must not exceed
161
+ * `faceAmount`. Typical ranges: ADB Rider $25,000–$250,000;
162
+ * Dependent Child Rider $5,000–$25,000.
163
+ */
48
164
  riders?: ThirdPartyQuoteReqRider[] | null;
49
- /** Payment frequency. */
50
- paymentFreq?: PaymentFrequency | null;
51
- /** First name — alphabetic only. Lead capture. */
165
+ /** First name — alphabetic only when provided. Lead capture. */
52
166
  firstName?: string | null;
53
- /** Last name — alphabetic only. Lead capture. */
167
+ /** Last name — alphabetic only when provided. Lead capture. */
54
168
  lastName?: string | null;
55
- /** Email address. Lead capture. */
169
+ /** Email address — validated only when provided. Lead capture. */
56
170
  email?: string | null;
57
- /** Phone number — 10-digit local or E.164 format. Lead capture. */
171
+ /**
172
+ * Phone number — 10 digits or `+1XXXXXXXXXX` when provided. Formatted on
173
+ * success. Lead capture.
174
+ */
58
175
  phoneNum?: string | null;
59
176
  }
177
+ /**
178
+ * Request shape for the Pure Term Get Existing Quote lookup
179
+ * (`GET /api/ThirdPartyIbPureTermQuote/get-existing-quote?opportunityId={guid}`).
180
+ *
181
+ * The `getPureTermExistingQuote()` facade takes a plain `opportunityId` string to
182
+ * match the IB Term / ADB / GIGDB convention; this interface is exported for
183
+ * callers who prefer to type their own request object. `opportunityId` must be a
184
+ * valid UUID.
185
+ */
186
+ export interface PureTermGetExistingQuoteRequest {
187
+ opportunityId: string;
188
+ }
189
+ /**
190
+ * Request body for `POST /api/ThirdPartyPureTermApplication/start-application`.
191
+ *
192
+ * The backend shares one request contract between IB Term and Pure Term
193
+ * start-application — same fields, same nesting, same optionality, same
194
+ * validation messages. This alias exists so Pure Term integrations read
195
+ * naturally; it is structurally the same type as
196
+ * {@link IBTermStartApplicationReq}, not a divergent shape.
197
+ *
198
+ * **Pure Term differences are behavioral, not structural:**
199
+ * - `quoteResponseId` must come from a Pure Term quote and belong to the Pure
200
+ * Term product, otherwise: "QuoteResponseId does not exist or does not belong
201
+ * to the requested product."
202
+ * - `childRiderInfo` is required only when the Dependent Child Rider was selected
203
+ * on the originating quote, and must **not** be sent otherwise — sending it
204
+ * without the rider fails with "Child rider was not included in the quote.
205
+ * Cannot add child rider details."
206
+ * - `tobaccoNicotineUsage.cigarUsagePerYear` is required only when
207
+ * `productTypesUsed` is **exactly** `['cigars']`. When cigars are selected
208
+ * alongside other product types it is not required.
209
+ * - `physicianDetails.stateCode` rejects both `"Outside Of The USA"` and
210
+ * `"OutsideUSA"`.
211
+ * - Pure Term does **not** run the `ApplicationLimitReached` duplicate
212
+ * SSN/email/phone check (that applies to ADB / GIGDB / Final Expense).
213
+ */
214
+ export type PureTermStartApplicationReq = IBTermStartApplicationReq;
@@ -2,7 +2,15 @@
2
2
  * Extract an error code from an API response.
3
3
  *
4
4
  * 1. Checks `response.errorCode` first (structured field).
5
- * 2. Falls back to scanning `response.error` string for known error code substrings.
5
+ * 2. Then an exact match against `response.error`.
6
+ * 3. Falls back to scanning `response.error` for known error codes as
7
+ * substrings, preferring the **longest** match.
8
+ *
9
+ * The longest-match rule matters because several codes are prefixes of others —
10
+ * e.g. `PaymentDeclined` is contained in both `PaymentDeclinedPermanent` and
11
+ * `PaymentDeclinedContactBank`. Returning the first match in enum-declaration
12
+ * order would silently report the less specific code, breaking `isErrorType()`
13
+ * and `getUserFriendlyMessage()` for the more specific one.
6
14
  *
7
15
  * @returns The error code string if found, `null` otherwise.
8
16
  */
@@ -11,7 +11,15 @@ const ALL_KNOWN_ERROR_CODES = Object.values(enums_1.APIErrorCode);
11
11
  * Extract an error code from an API response.
12
12
  *
13
13
  * 1. Checks `response.errorCode` first (structured field).
14
- * 2. Falls back to scanning `response.error` string for known error code substrings.
14
+ * 2. Then an exact match against `response.error`.
15
+ * 3. Falls back to scanning `response.error` for known error codes as
16
+ * substrings, preferring the **longest** match.
17
+ *
18
+ * The longest-match rule matters because several codes are prefixes of others —
19
+ * e.g. `PaymentDeclined` is contained in both `PaymentDeclinedPermanent` and
20
+ * `PaymentDeclinedContactBank`. Returning the first match in enum-declaration
21
+ * order would silently report the less specific code, breaking `isErrorType()`
22
+ * and `getUserFriendlyMessage()` for the more specific one.
15
23
  *
16
24
  * @returns The error code string if found, `null` otherwise.
17
25
  */
@@ -20,11 +28,18 @@ function extractErrorCode(response) {
20
28
  return response.errorCode;
21
29
  }
22
30
  if (response.error && typeof response.error === 'string') {
31
+ const errorText = response.error;
32
+ // An exact match is unambiguous — take it before any substring scanning.
33
+ if (ALL_KNOWN_ERROR_CODES.includes(errorText)) {
34
+ return errorText;
35
+ }
36
+ let longestMatch = null;
23
37
  for (const code of ALL_KNOWN_ERROR_CODES) {
24
- if (response.error.includes(code)) {
25
- return code;
38
+ if (errorText.includes(code) && (longestMatch === null || code.length > longestMatch.length)) {
39
+ longestMatch = code;
26
40
  }
27
41
  }
42
+ return longestMatch;
28
43
  }
29
44
  return null;
30
45
  }
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.HttpClient = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const types_1 = require("../types");
9
+ const error_utils_1 = require("./error-utils");
9
10
  /**
10
11
  * HTTP client for making requests to the InstaBrain API
11
12
  */
@@ -44,6 +45,7 @@ class HttpClient {
44
45
  });
45
46
  // Response interceptor for error handling
46
47
  this.axiosInstance.interceptors.response.use((response) => response, (error) => {
48
+ var _a;
47
49
  if (error.response) {
48
50
  const { status, data } = error.response;
49
51
  // Handle specific error status codes
@@ -52,8 +54,15 @@ class HttpClient {
52
54
  // Clear invalid token
53
55
  this.jwtToken = null;
54
56
  throw new types_1.AuthenticationError((data === null || data === void 0 ? void 0 : data.error) || 'Authentication failed');
55
- case 400:
56
- throw new types_1.ValidationError((data === null || data === void 0 ? void 0 : data.error) || 'Validation failed');
57
+ case 400: {
58
+ // Mirror BaseService's flagStatus-false handling so a 400 and a
59
+ // 200-with-flagStatus-false produce the same error type. Callers
60
+ // documented to use isErrorType() / getUserFriendlyMessage() need
61
+ // APIValidationError, and the body carries value.fields.
62
+ const errorMessage = (data === null || data === void 0 ? void 0 : data.error) || (data === null || data === void 0 ? void 0 : data.errorCode) || 'Validation failed';
63
+ const errorCode = (_a = (0, error_utils_1.extractErrorCode)(data !== null && data !== void 0 ? data : {})) !== null && _a !== void 0 ? _a : errorMessage;
64
+ throw new types_1.APIValidationError(errorMessage, errorCode, data);
65
+ }
57
66
  case 404:
58
67
  throw new types_1.InstaBrainError('Resource not found', 404, data);
59
68
  case 500:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instabrain-sdks/api-client",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "description": "Official Node.js SDK for InstaBrain APIs - Insurance quotes and application processing",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",