{"version":3,"file":"index.cjs","names":[],"sources":["../src/core/guard.ts","../src/core/json.ts","../src/operations/names.ts","../src/errors/return-codes.ts","../src/errors/index.ts","../src/core/transport.ts","../src/core/validate.ts","../src/core/response-guards.ts","../src/operations/capture.ts","../src/operations/check-payment-status.ts","../src/operations/check-regkey.ts","../src/operations/confirm.ts","../src/operations/expire-regkey.ts","../src/operations/pay-preapproved.ts","../src/operations/payment-details.ts","../src/operations/refund.ts","../src/operations/request.ts","../src/operations/void.ts","../src/operations/index.ts","../src/core/annotate.ts","../src/middleware/retry-when-not-sent.ts","../src/config.ts","../src/core/query.ts","../src/core/response.ts","../src/core/sign.ts","../src/core/execute.ts","../src/core/pipeline.ts","../src/core/snapshot.ts","../src/core/time.ts","../src/reconcile/rules.ts","../src/reconcile/index.ts","../src/client.ts","../src/helpers/confirm-query.ts","../src/middleware/auto-reconcile.ts"],"sourcesContent":["/**\n * A runtime check that tells the compiler what it found out.\n *\n * Nothing in this library asserts a type with `as`: a value from the network, or\n * from a caller who is not bound by types, is narrowed with a guard, and the\n * compiler takes the guard's word for exactly what it has checked.\n */\nexport type Guard<T> = (value: unknown) => value is T\n\n/**\n * A list of things nothing is known about. `Array.isArray` says `any[]`, so the\n * compiler would let anything be done with an item; this says `unknown`.\n */\nexport const isArray: Guard<readonly unknown[]> = (\n  value\n): value is readonly unknown[] => Array.isArray(value)\n\n/** An object whose keys and values nothing is known about (not an array, not null). */\nexport const isRecord: Guard<Record<string, unknown>> = (\n  value\n): value is Record<string, unknown> =>\n  typeof value === 'object' && value !== null && !isArray(value)\n\nexport const isString: Guard<string> = (value): value is string =>\n  typeof value === 'string'\n\n/** A finite number: `NaN` and the infinities are no amount. */\nexport const isNumber: Guard<number> = (value): value is number =>\n  typeof value === 'number' && Number.isFinite(value)\n\n/**\n * A list of which every item passes `item`. An empty slot of a sparse list is\n * `undefined`, and checked as such.\n */\nexport function isListOf<T>(item: Guard<T>): Guard<T[]> {\n  return (value): value is T[] => {\n    if (!isArray(value)) return false\n    for (let index = 0; index < value.length; index++) {\n      if (!item(value[index])) return false\n    }\n    return true\n  }\n}\n\ntype Shape = Readonly<Record<string, Guard<unknown>>>\n\n/** What the guards of a shape have found out, key by key. */\ntype Checked<S extends Shape> = {\n  [K in keyof S]: S[K] extends Guard<infer T> ? T : never\n}\n\n/**\n * A guard for an object with the keys `required` (each must be there and pass its\n * guard) and the keys `optional` (each may be missing, but if it is there it must\n * pass). Keys it does not know are let through: LINE Pay adds fields.\n *\n * The type it vouches for is the one its two shapes describe. Give it where a\n * `Guard<Interface>` is expected, and the compiler checks that every required\n * field of the interface is among the keys that are checked.\n */\nexport function hasShape<\n  R extends Shape,\n  O extends Shape = Record<never, never>\n>(required: R, optional?: O): Guard<Checked<R> & Partial<Checked<O>>> {\n  // Taken once, when the guard is made, not on every call.\n  const mustHave = Object.entries<Guard<unknown>>(required)\n  const mayHave = Object.entries<Guard<unknown>>(optional ?? {})\n  return (value): value is Checked<R> & Partial<Checked<O>> => {\n    if (!isRecord(value)) return false\n    for (const [key, guard] of mustHave) {\n      if (!guard(value[key])) return false\n    }\n    for (const [key, guard] of mayHave) {\n      const present = value[key]\n      if (present !== undefined && !guard(present)) return false\n    }\n    return true\n  }\n}\n","/**\n * LINE Pay transaction IDs are 19-digit integers, larger than 2^53, so a plain\n * `JSON.parse` rounds them (`2021121300698360311` becomes `2021121300698360300`).\n *\n * The `source` argument of a `JSON.parse` reviver (available since V8 11.4, so on\n * every supported Node.js) carries the original text of a primitive. Every\n * integer outside the safe range is returned as that text, so the ID types in\n * this library are strings. Version 0.9 patched two field names with a regular\n * expression and missed `originalTransactionId`.\n */\ntype Reviver = (\n  this: unknown,\n  key: string,\n  value: unknown,\n  context?: { source?: string }\n) => unknown\n\nconst reviver: Reviver = (_key, value, context) =>\n  typeof value === 'number' &&\n  Number.isInteger(value) &&\n  !Number.isSafeInteger(value) &&\n  typeof context?.source === 'string'\n    ? context.source\n    : value\n\nexport function parseLossless(text: string): unknown {\n  return JSON.parse(text, reviver)\n}\n\n/**\n * Whether this engine hands the source text of a number to the reviver. Without\n * it the IDs are rounded and nothing says so, so a client is not created.\n */\nexport function hasLosslessJson(): boolean {\n  let source: unknown\n  JSON.parse('1', (_key, value: unknown, context?: { source?: string }) => {\n    source = context?.source\n    return value\n  })\n  return typeof source === 'string'\n}\n","/**\n * Every operation the client exposes. The names match the 0.9 API so that call\n * sites only change shape, not vocabulary.\n */\nexport const OPERATION_NAMES = Object.freeze([\n  'request',\n  'confirm',\n  'capture',\n  'void',\n  'refund',\n  'paymentDetails',\n  'checkPaymentStatus',\n  'checkRegKey',\n  'payPreapproved',\n  'expireRegKey'\n] as const)\n\nexport type OperationName = (typeof OPERATION_NAMES)[number]\n\n/**\n * Operations whose \"unknown outcome\" can be resolved by looking at the payment\n * details afterwards. `request`, the read operations and `expireRegKey` are not\n * in this list on purpose: a payment that was only requested moves no money and\n * is asked for again with a new order ID, and the others have nothing to look up.\n * Both lists are frozen: they decide, for every client of the process, which\n * calls are looked up.\n */\nexport const RECONCILABLE_OPERATIONS = Object.freeze([\n  'confirm',\n  'capture',\n  'void',\n  'refund',\n  'payPreapproved'\n] as const)\n\nexport type ReconcilableOperation = (typeof RECONCILABLE_OPERATIONS)[number]\n\nexport function isOperationName(value: unknown): value is OperationName {\n  return OPERATION_NAMES.some(name => name === value)\n}\n\nexport function isReconcilableOperation(\n  value: unknown\n): value is ReconcilableOperation {\n  return RECONCILABLE_OPERATIONS.some(name => name === value)\n}\n\n/**\n * How an operation behaves when its outcome is unknown.\n *\n * - `read`: no side effect, always safe to repeat.\n * - `create`: reserves a payment but moves no money.\n * - `settle`: moves money or changes state, and the server rejects duplicates.\n * - `refund`: moves money and is NOT idempotent (partial refunds can repeat).\n */\nexport type OperationEffect = 'read' | 'create' | 'settle' | 'refund'\n","/**\n * LINE Pay answers HTTP 200 for API-level failures and puts the result in\n * `returnCode`. `0000` is success.\n */\nexport const SUCCESS_RETURN_CODE = '0000'\n\n/**\n * Whether a value is the return code of LINE Pay: four digits (`0000`, `1172`,\n * `9000`, `1900`). A body with anything else in `returnCode` is not an answer of\n * LINE Pay, and the library does not take its word: a word of four letters would\n * be read as a refusal, and a refusal means that the call did not happen.\n */\nexport function isReturnCode(value: unknown): value is string {\n  return typeof value === 'string' && /^\\d{4}$/.test(value)\n}\n\n/**\n * The other codes that start with `0` are statuses, not failures: the status\n * check of a payment answers with them (waiting, cancelled, done). No other\n * operation is known to.\n */\nexport function isStatusReturnCode(returnCode: string): boolean {\n  return returnCode !== SUCCESS_RETURN_CODE && returnCode.startsWith('0')\n}\n\n/**\n * - `duplicate`: the call (or the order ID) already exists. The first call may well\n *   have succeeded.\n * - `unresolved`: LINE Pay answered, but not with a refusal: it failed inside, is\n *   still working on it, or cannot handle the payment in its current state. The\n *   call may have taken effect, so the outcome is `unknown`.\n * - `unclassified`: every other failing code. LINE Pay refused the call.\n */\nexport type ReturnCodeCategory = 'duplicate' | 'unresolved' | 'unclassified'\n\nconst DUPLICATE_CODES: ReadonlySet<string> = new Set([\n  // The transaction already exists.\n  '1152',\n  // The payment has already been refunded. Another refund may exist.\n  '1165',\n  // There is already a transaction with the same order ID / the call was\n  // already made. The first call may well have succeeded.\n  '1172',\n  // The same API call is being processed (duplicate request).\n  '1198'\n])\n\n// The official V4 result-code table identifies processing, temporary and\n// internal errors. Since these do not always prove that a money-moving call\n// had no effect, they remain unresolved. Sandbox also observed 1179 on a\n// void of a captured payment.\nconst UNRESOLVED_CODES: ReadonlySet<string> = new Set([\n  // The payment is being processed.\n  '1145',\n  // The payment cannot be handled in its current state: it may be the effect of\n  // an earlier call that did go through (a void of a voided authorization).\n  '1179',\n  // Internal error while handling the request.\n  '1199',\n  // Temporary credit card payment error: check before repeating a charge.\n  '1280',\n  // V4 refund/void explicitly allow retry for 1999; it is not a duplicate.\n  // Keep the outcome unknown until the transaction has been checked.\n  '1999',\n  // Internal error.\n  '9000'\n])\n\n/** 1900 to 1909: a temporary error, \"try again later\". */\nconst TEMPORARY_ERROR = /^190\\d$/\n\n/**\n * Classify a failing return code.\n *\n * Based on the V4 result-code reference and conservative outcome handling.\n * 2042 specifically means an EPI refund was not executed due to insufficient\n * merchant refund reserve, so it is unclassified (rejected), not unresolved.\n * Unknown future codes remain unclassified pending review.\n */\nexport function classifyReturnCode(returnCode: string): ReturnCodeCategory {\n  if (DUPLICATE_CODES.has(returnCode)) return 'duplicate'\n  if (UNRESOLVED_CODES.has(returnCode) || TEMPORARY_ERROR.test(returnCode)) {\n    return 'unresolved'\n  }\n  return 'unclassified'\n}\n","import type { OperationName } from '../operations/names'\nimport { isReconcilableOperation } from '../operations/names'\nimport {\n  classifyReturnCode,\n  isReturnCode,\n  type ReturnCodeCategory\n} from './return-codes'\n\n/**\n * Brand used by the type guards instead of `instanceof`. A package that ships\n * both ESM and CommonJS can be loaded twice in one process, and `instanceof`\n * is `false` across the two copies. `Symbol.for` returns the same symbol in\n * both, so the brand check keeps working.\n */\nconst BRAND = Symbol.for('line-pay-merchant.error')\n\nexport type LinePayErrorCode =\n  | 'LINE_PAY_VALIDATION_ERROR'\n  | 'LINE_PAY_API_ERROR'\n  | 'LINE_PAY_HTTP_ERROR'\n  | 'LINE_PAY_NETWORK_ERROR'\n  | 'LINE_PAY_TIMEOUT_ERROR'\n  | 'LINE_PAY_ABORT_ERROR'\n  | 'LINE_PAY_MIDDLEWARE_ERROR'\n\n/**\n * What the caller may assume about the request that failed.\n *\n * - `not-sent`: the request definitely did not leave this process (or never\n *   got past the connection phase), so nothing moved. A request that failed on\n *   the way out can be sent again as it is; one that was refused as invalid has\n *   to be fixed first. \"Definitely\" rests on the `fetch` in use sending a request\n *   once per call, and refusing redirects.\n * - `unknown`: the request may have reached LINE Pay and may have been\n *   processed, but no trustworthy response came back. Do not treat it as a\n *   failure; for operations that move money, use `reconcile`.\n * - `rejected`: LINE Pay (or something in front of it) refused the request.\n */\nexport type Outcome = 'not-sent' | 'unknown' | 'rejected'\n\n/**\n * One problem with an input or a configuration.\n *\n * `path` is where it is, written the way the field is reached: `amount`,\n * `packages[0].products[1].price`, `transactionId[2]`. For an input it is relative\n * to the input object, and `input` alone means the whole input (it is not an\n * object that can be copied, say). The call options, the second argument of a\n * call, are `options.timeout` and `options.signal`: the input of `request` has an\n * `options` field of its own, whose paths read `options.payment.capture`. For a\n * configuration it is relative to the configuration object (`timeouts.refund`).\n */\nexport interface ValidationIssue {\n  readonly path: string\n  readonly message: string\n}\n\n/**\n * The minimum facts `reconcile` needs to look a call up. The client attaches one\n * to the error of every call that was made (`error.context`); an error that comes\n * before there is a call, such as bad call options, has none. It never contains\n * headers, signatures or the channel secret.\n *\n * To reconcile a call whose error you never saw, because the process died before\n * it got an answer, write one down before making the call and pass it to\n * `client.reconcile` later. Every field it needs must be there, with the type\n * shown, or `reconcile` answers `indeterminate` and says which one is wrong:\n *\n * | operation        | needs                                 | also uses      |\n * | ---------------- | ------------------------------------- | -------------- |\n * | `confirm`        | `transactionId`, `amount`, `currency` |                |\n * | `capture`        | `transactionId`, `amount`, `currency` |                |\n * | `void`           | `transactionId`                       |                |\n * | `refund`         | `transactionId`                       | `refundAmount` |\n * | `payPreapproved` | `orderId`, `amount`, `currency`       |                |\n *\n * `channelId` is on the context of every error: keep it on a context you save.\n * When a context carries one, `reconcile` refuses to look it up with a client of\n * another channel. Without one it never concludes `not-applied` from a payment\n * that is not there: a client with the wrong credentials sees nothing, and\n * \"nothing\" would read as \"it did not happen\".\n */\nexport interface ReconcileContext {\n  readonly operation: OperationName\n  /**\n   * When the call began. A refund, and a pre-approved payment, are looked for\n   * from this second on. A context that was saved comes back from JSON with a\n   * string or a number here, and `reconcile` accepts an ISO 8601 string with a\n   * time zone or milliseconds too.\n   */\n  readonly startedAt: Date\n  /** The channel of the client that made the call. */\n  readonly channelId?: string\n  /** 1 to 19 digits, as a string. */\n  readonly transactionId?: string\n  /** As a string, the one of the call. */\n  readonly orderId?: string\n  /** What the call asked for; the payment must match it. */\n  readonly amount?: number\n  readonly currency?: string\n  /** Leave it out for a full refund. */\n  readonly refundAmount?: number\n}\n\nexport interface ReconcileConclusion {\n  readonly status: 'not-applied' | 'indeterminate'\n  readonly reason: string\n}\n\n/**\n * How a call went, as far as it is known: `result.meta` for a call that succeeded\n * and `error.meta` for one that failed, in the same shape.\n */\nexport interface CallMeta {\n  operation: OperationName\n  startedAt: Date\n  /** Total time in milliseconds, retries and waiting between them included. */\n  durationMs: number\n  /**\n   * How many times the request was attempted, including attempts that never\n   * connected. A call that was refused before it could be sent counts as one.\n   */\n  attempts: number\n  /**\n   * HTTP status of the last response. Absent when there was none: a network\n   * error, a timeout, an abort, an input that was refused, or a result that was\n   * recovered by `reconcile` (the original call never produced a response).\n   */\n  httpStatus?: number\n}\n\n/** The part of the init of every error that is not about its own kind. */\nexport interface LinePayErrorOptions {\n  /** The operation that was being called, when there is one. */\n  readonly operation?: OperationName | undefined\n  /** The failure underneath, kept as `error.cause`. */\n  readonly cause?: unknown\n}\n\nexport interface LinePayErrorInit extends LinePayErrorOptions {\n  readonly outcome: Outcome\n}\n\n/**\n * The safe view of an error that `toJSON()` returns and that `console.log` and\n * `util.inspect` print: no response body, no context, no headers or signatures,\n * and the cause as its message alone. A key that has no value is left out.\n */\nexport interface LinePayErrorJSON {\n  readonly name: string\n  readonly code: LinePayErrorCode\n  readonly message: string\n  readonly outcome: Outcome\n  readonly operation?: OperationName\n  /** `startedAt` is an ISO 8601 string. */\n  readonly meta?: {\n    readonly operation: OperationName\n    readonly startedAt: string\n    readonly durationMs: number\n    readonly attempts: number\n    readonly httpStatus?: number\n  }\n  readonly reconcileConclusion?: ReconcileConclusion\n  /** The message of the cause, with the paths of any URLs in it removed. */\n  readonly cause?: string\n}\n\n/**\n * Put what LINE Pay sent on an error where whoever asks for it by name finds it\n * (`error.body`), but not where a logger finds it by itself. Serializers such as\n * the `err` of pino, and `{ ...error }`, copy the enumerable properties of an\n * error, and the body of a response can hold a regKey, a masked card number or an\n * address.\n */\nfunction keepApart(target: object, name: string, value: unknown): void {\n  Object.defineProperty(target, name, {\n    value,\n    enumerable: false,\n    writable: true,\n    configurable: true\n  })\n}\n\n/**\n * A message that names a URL names its path, and the path of some calls holds a\n * regKey (`.../preapprovedPay/<regKey>/payment`). The `fetch` of a user may put\n * the URL into the message of its errors (`node-fetch` does), so the host stays\n * and the rest of the URL goes.\n */\nfunction withoutUrlPaths(text: string): string {\n  // The scheme is bounded, so that the search does not start over for every\n  // letter of a long text that has no URL in it (that takes quadratic time).\n  return text.replace(/[a-z][a-z0-9+.-]{0,31}:\\/\\/[^\\s'\"<>)]+/gi, candidate => {\n    try {\n      const url = new URL(candidate)\n      return `${url.protocol}//${url.host}`\n    } catch {\n      return '<url>'\n    }\n  })\n}\n\n/**\n * What can be said of a failure in a log: the message of an error, or a text,\n * without the paths of the URLs in it. Anything else says nothing.\n */\nexport function describeCause(cause: unknown): string | undefined {\n  if (cause instanceof Error) return withoutUrlPaths(cause.message)\n  return typeof cause === 'string' ? withoutUrlPaths(cause) : undefined\n}\n\n/**\n * Base class of every error this library throws on purpose. It cannot be\n * constructed itself: what an error is, is its class, and `code` tells which one\n * (see {@link AnyLinePayError}).\n *\n * `operation`, `context`, `meta` and `reconcileConclusion` are filled in after the\n * error was made, by the client and by the `retryWhenNotSent` and `autoReconcile`\n * middleware, so they can be assigned; they are absent until then.\n *\n * The brand is not part of the type: a `unique symbol` in the declarations is a\n * different type in the ESM and in the CommonJS copy of them, and an error of one\n * would not be assignable to the other.\n *\n * An error does not survive `structuredClone` or `postMessage` as one of these\n * classes: the copy is a plain `Error` with the name, message, stack and cause.\n * Send `error.toJSON()` instead.\n */\nexport abstract class LinePayError extends Error {\n  /** Which class the error is. */\n  abstract readonly code: LinePayErrorCode\n  readonly outcome: Outcome\n  /** The operation that was being called. Set when it is known. */\n  declare operation?: OperationName | undefined\n  /**\n   * Attached by the client so that `reconcile` can look the call up again. Not\n   * enumerable, like the response body: a logger that copies the properties of an\n   * error does not write down the order and the transaction.\n   */\n  declare context?: ReconcileContext | undefined\n  /** How the call went; the totals of a retry are in it. */\n  declare meta?: CallMeta | undefined\n  /** Set by `autoReconcile` when it could not resolve the call to \"applied\". */\n  declare reconcileConclusion?: ReconcileConclusion | undefined\n\n  protected constructor(name: string, message: string, init: LinePayErrorInit) {\n    super(message, init.cause === undefined ? undefined : { cause: init.cause })\n    Object.defineProperty(this, BRAND, { value: true })\n    Object.defineProperty(this, 'name', {\n      value: name,\n      writable: true,\n      configurable: true\n    })\n    keepApart(this, 'context', undefined)\n    this.outcome = init.outcome\n    if (init.operation !== undefined) this.operation = init.operation\n  }\n\n  /** A safe, loggable view: no headers, secrets or signatures. */\n  toJSON(): LinePayErrorJSON {\n    const cause = describeCause(this.cause)\n    const { meta, reconcileConclusion } = this\n    return {\n      name: this.name,\n      code: this.code,\n      message: this.message,\n      outcome: this.outcome,\n      ...(this.operation === undefined ? {} : { operation: this.operation }),\n      ...(meta === undefined\n        ? {}\n        : {\n            meta: {\n              operation: meta.operation,\n              startedAt: meta.startedAt.toJSON(),\n              durationMs: meta.durationMs,\n              attempts: meta.attempts,\n              ...(meta.httpStatus === undefined\n                ? {}\n                : { httpStatus: meta.httpStatus })\n            }\n          }),\n      ...(reconcileConclusion === undefined\n        ? {}\n        : {\n            reconcileConclusion: {\n              status: reconcileConclusion.status,\n              reason: reconcileConclusion.reason\n            }\n          }),\n      ...(cause === undefined ? {} : { cause })\n    }\n  }\n}\n\n/**\n * What `console.log(error)` and `util.inspect(error)` print. Left alone they print\n * every property of the error: the response body, the context, the cause with its\n * own properties. This prints the stack and the same safe view as `toJSON()`, so\n * that a line logged the usual way carries what a log should have and no more.\n * (`error.body` is there for whoever needs it, who asks for it by name.)\n */\nObject.defineProperty(\n  LinePayError.prototype,\n  Symbol.for('nodejs.util.inspect.custom'),\n  {\n    value: function inspectLinePayError(\n      this: LinePayError,\n      _depth: number,\n      options: object,\n      inspect?: (value: unknown, options?: object) => string\n    ): string {\n      const view = this.toJSON()\n      return `${this.stack ?? `${this.name}: ${this.message}`}\\n${\n        inspect === undefined\n          ? JSON.stringify(view, null, 2)\n          : inspect(view, options)\n      }`\n    },\n    writable: true,\n    configurable: true\n  }\n)\n\nexport interface LinePayValidationErrorInit extends LinePayErrorOptions {\n  /** Every problem that was found, not only the first. */\n  readonly issues: readonly ValidationIssue[]\n  /** What was checked. `input` by default. */\n  readonly subject?: 'input' | 'configuration'\n}\n\nfunction formatIssues(init: LinePayValidationErrorInit): string {\n  const where = init.operation === undefined ? '' : ` for ${init.operation}`\n  const detail = init.issues.map(i => `${i.path} ${i.message}`).join('; ')\n  return `Invalid ${init.subject ?? 'input'}${where}: ${detail}`\n}\n\n/** The input or the configuration is invalid. Nothing was sent. */\nexport class LinePayValidationError extends LinePayError {\n  override readonly code = 'LINE_PAY_VALIDATION_ERROR'\n  declare readonly outcome: 'not-sent'\n  readonly issues: readonly ValidationIssue[]\n\n  constructor(init: LinePayValidationErrorInit) {\n    super('LinePayValidationError', formatIssues(init), {\n      outcome: 'not-sent',\n      operation: init.operation,\n      cause: init.cause\n    })\n    this.issues = init.issues\n  }\n\n  override toJSON(): LinePayErrorJSON & {\n    readonly issues: readonly ValidationIssue[]\n  } {\n    return { ...super.toJSON(), issues: this.issues }\n  }\n}\n\nexport interface LinePayApiBody {\n  returnCode: string\n  returnMessage: string\n  [key: string]: unknown\n}\n\nexport interface LinePayApiErrorInit {\n  /** The response body, with a `returnMessage` (an empty one if LINE Pay sent none). */\n  readonly body: LinePayApiBody\n  readonly httpStatus: number\n  /** The category of `body.returnCode` by default. */\n  readonly category?: ReturnCodeCategory\n  /**\n   * `unknown` for the category `unresolved`, `rejected` for any other by default.\n   */\n  readonly outcome?: 'rejected' | 'unknown'\n  readonly operation?: OperationName | undefined\n}\n\n/**\n * LINE Pay answered, and the `returnCode` says the request failed (`rejected`).\n * It is `unknown` when the answer does not say that the call was refused: a code\n * of the category `unresolved` (an internal error, a payment that is still being\n * processed), or a status the operation does not define.\n */\nexport class LinePayApiError extends LinePayError {\n  override readonly code = 'LINE_PAY_API_ERROR'\n  declare readonly outcome: 'rejected' | 'unknown'\n  readonly returnCode: string\n  readonly returnMessage: string\n  readonly httpStatus: number\n  /**\n   * The response body as LINE Pay sent it. Not enumerable: a logger that copies\n   * the properties of an error does not write it down.\n   */\n  declare readonly body: LinePayApiBody\n  readonly category: ReturnCodeCategory\n\n  constructor(init: LinePayApiErrorInit) {\n    const { body } = init\n    const category = init.category ?? classifyReturnCode(body.returnCode)\n    super(\n      'LinePayApiError',\n      body.returnMessage === ''\n        ? `LINE Pay returned ${body.returnCode}`\n        : `LINE Pay returned ${body.returnCode}: ${body.returnMessage}`,\n      {\n        outcome:\n          init.outcome ?? (category === 'unresolved' ? 'unknown' : 'rejected'),\n        operation: init.operation\n      }\n    )\n    this.returnCode = body.returnCode\n    this.returnMessage = body.returnMessage\n    this.httpStatus = init.httpStatus\n    keepApart(this, 'body', body)\n    this.category = category\n  }\n\n  override toJSON(): LinePayErrorJSON & {\n    readonly returnCode: string\n    readonly returnMessage: string\n    readonly httpStatus: number\n    readonly category: ReturnCodeCategory\n  } {\n    return {\n      ...super.toJSON(),\n      returnCode: this.returnCode,\n      returnMessage: this.returnMessage,\n      httpStatus: this.httpStatus,\n      category: this.category\n    }\n  }\n}\n\nexport type HttpErrorReason =\n  'http-status' | 'invalid-response' | 'unexpected-shape' | 'body-too-large'\n\nexport interface LinePayHttpErrorInit extends LinePayErrorOptions {\n  readonly httpStatus: number\n  readonly reason: HttpErrorReason\n  /** `rejected` for a status of 4xx, `unknown` for anything else. */\n  readonly outcome: 'rejected' | 'unknown'\n  readonly body?: unknown\n  readonly bodyText?: string | undefined\n}\n\nconst HTTP_ERROR_MESSAGES: Readonly<\n  Record<HttpErrorReason, (httpStatus: number) => string>\n> = {\n  'http-status': status => `LINE Pay responded with HTTP ${status}`,\n  'invalid-response': status =>\n    `LINE Pay responded with HTTP ${status}, but the body is not a valid LINE Pay response`,\n  'unexpected-shape': status =>\n    `LINE Pay responded with HTTP ${status}, but the body does not have the fields that the operation promises (the body as it was received is in error.body)`,\n  'body-too-large': status =>\n    `LINE Pay responded with HTTP ${status}, but the body is too large to read`\n}\n\n/** The `returnCode` of a body, when it has one: four digits. Else `undefined`. */\nfunction returnCodeOf(body: unknown): string | undefined {\n  if (typeof body !== 'object' || body === null) return undefined\n  const code: unknown = Reflect.get(body, 'returnCode')\n  return isReturnCode(code) ? code : undefined\n}\n\n/**\n * The HTTP status was not 2xx, the body of a 2xx response is not a LINE Pay\n * response (for example an HTML page from a proxy), or it is one without the\n * fields that the operation promises (`reason: 'unexpected-shape'`, the body as\n * it was received is in `body`).\n */\nexport class LinePayHttpError extends LinePayError {\n  override readonly code = 'LINE_PAY_HTTP_ERROR'\n  declare readonly outcome: 'rejected' | 'unknown'\n  readonly httpStatus: number\n  readonly reason: HttpErrorReason\n  /**\n   * The `returnCode` of the answer, for `reason: 'unexpected-shape'` only: an\n   * answer of LINE Pay (it has a return code, four digits) that is not the one the\n   * operation promises. `'0000'` there means that LINE Pay answered that the call\n   * succeeded, only not in the shape this library promises.\n   *\n   * For every other reason there is no property. The body is not an answer of LINE\n   * Pay (an HTML page of a proxy, JSON of something else), or it came with an HTTP\n   * status that is not 2xx, and a `returnCode` in it says nothing about the call.\n   *\n   * It is diagnostic: it does not change the outcome (`unknown`); `reconcile` is\n   * what finds out what became of the call.\n   */\n  declare readonly returnCode?: string | undefined\n  /**\n   * What was received, parsed (for an answer that is no LINE Pay response, or\n   * not the one the operation promises). Not enumerable, like `bodyText`.\n   */\n  declare readonly body?: unknown\n  /** Start of the response text, cut at 2 KB. Not enumerable. */\n  declare readonly bodyText?: string | undefined\n\n  constructor(init: LinePayHttpErrorInit) {\n    super(\n      'LinePayHttpError',\n      HTTP_ERROR_MESSAGES[init.reason](init.httpStatus),\n      init\n    )\n    this.httpStatus = init.httpStatus\n    this.reason = init.reason\n    // Only for an answer that the library took for LINE Pay's: any other body\n    // (a proxy's JSON, a failed HTTP status) says nothing about the call.\n    const returnCode =\n      init.reason === 'unexpected-shape' ? returnCodeOf(init.body) : undefined\n    if (returnCode !== undefined) this.returnCode = returnCode\n    keepApart(this, 'body', init.body)\n    keepApart(this, 'bodyText', init.bodyText)\n  }\n\n  override toJSON(): LinePayErrorJSON & {\n    readonly httpStatus: number\n    readonly reason: HttpErrorReason\n    readonly returnCode?: string\n  } {\n    return {\n      ...super.toJSON(),\n      httpStatus: this.httpStatus,\n      reason: this.reason,\n      ...(this.returnCode === undefined ? {} : { returnCode: this.returnCode })\n    }\n  }\n}\n\nexport type NetworkErrorReason =\n  | 'connection-refused'\n  | 'dns'\n  | 'network-unreachable'\n  | 'connection-reset'\n  | 'redirect'\n  | 'other'\n\nexport interface LinePayNetworkErrorInit extends LinePayErrorOptions {\n  readonly reason: NetworkErrorReason\n  /** Node.js error code of the underlying failure, for example `ECONNREFUSED`. */\n  readonly causeCode?: string | undefined\n  /** `not-sent` only when the connection was never made. */\n  readonly outcome: 'not-sent' | 'unknown'\n}\n\n/** `fetch` failed before a usable HTTP response arrived. */\nexport class LinePayNetworkError extends LinePayError {\n  override readonly code = 'LINE_PAY_NETWORK_ERROR'\n  declare readonly outcome: 'not-sent' | 'unknown'\n  readonly reason: NetworkErrorReason\n  /** Node.js error code of the underlying failure, for example `ECONNREFUSED`. */\n  declare readonly causeCode?: string | undefined\n\n  constructor(init: LinePayNetworkErrorInit) {\n    super(\n      'LinePayNetworkError',\n      `Network error while calling LINE Pay (${init.reason})`,\n      init\n    )\n    this.reason = init.reason\n    if (init.causeCode !== undefined) this.causeCode = init.causeCode\n  }\n\n  override toJSON(): LinePayErrorJSON & {\n    readonly reason: NetworkErrorReason\n    readonly causeCode?: string\n  } {\n    return {\n      ...super.toJSON(),\n      reason: this.reason,\n      ...(this.causeCode === undefined ? {} : { causeCode: this.causeCode })\n    }\n  }\n}\n\nexport interface LinePayTimeoutErrorInit extends LinePayErrorOptions {\n  /** The limit that passed, in milliseconds. */\n  readonly timeoutMs: number\n}\n\n/** The time limit passed before LINE Pay answered. The outcome is unknown. */\nexport class LinePayTimeoutError extends LinePayError {\n  override readonly code = 'LINE_PAY_TIMEOUT_ERROR'\n  declare readonly outcome: 'unknown'\n  readonly timeoutMs: number\n\n  constructor(init: LinePayTimeoutErrorInit) {\n    super(\n      'LinePayTimeoutError',\n      `LINE Pay did not respond within ${init.timeoutMs} ms`,\n      { outcome: 'unknown', operation: init.operation, cause: init.cause }\n    )\n    this.timeoutMs = init.timeoutMs\n  }\n\n  override toJSON(): LinePayErrorJSON & { readonly timeoutMs: number } {\n    return { ...super.toJSON(), timeoutMs: this.timeoutMs }\n  }\n}\n\nexport interface LinePayAbortErrorInit {\n  /** What the signal was aborted with. It is also the `cause`. */\n  readonly abortReason: unknown\n  /** `not-sent` when the request had not gone out yet. */\n  readonly outcome: 'not-sent' | 'unknown'\n  readonly operation?: OperationName | undefined\n}\n\n/** The caller's `AbortSignal` fired. */\nexport class LinePayAbortError extends LinePayError {\n  override readonly code = 'LINE_PAY_ABORT_ERROR'\n  declare readonly outcome: 'not-sent' | 'unknown'\n  readonly abortReason: unknown\n\n  constructor(init: LinePayAbortErrorInit) {\n    super('LinePayAbortError', 'The request was aborted by the caller', {\n      outcome: init.outcome,\n      operation: init.operation,\n      cause: init.abortReason\n    })\n    this.abortReason = init.abortReason\n  }\n}\n\nexport interface LinePayMiddlewareErrorInit extends LinePayErrorOptions {\n  /** The operation whose result was wrong. */\n  readonly operation: OperationName\n}\n\n/**\n * A middleware handed back something that is not the result of the operation. The\n * request may well have been sent, and have taken effect: the outcome is unknown,\n * and the error carries the context, so that `reconcile` can look the call up.\n */\nexport class LinePayMiddlewareError extends LinePayError {\n  override readonly code = 'LINE_PAY_MIDDLEWARE_ERROR'\n  declare readonly outcome: 'unknown'\n\n  constructor(init: LinePayMiddlewareErrorInit) {\n    super(\n      'LinePayMiddlewareError',\n      `A middleware returned something that is not the result of ${init.operation}`,\n      { outcome: 'unknown', operation: init.operation, cause: init.cause }\n    )\n  }\n}\n\n/**\n * An error of this library, as one of its classes. `code` tells them apart, so\n * that a `switch` on it narrows the error to its class (and to the `outcome` it\n * can have), and the compiler can check that every class is handled.\n */\nexport type AnyLinePayError =\n  | LinePayValidationError\n  | LinePayApiError\n  | LinePayHttpError\n  | LinePayNetworkError\n  | LinePayTimeoutError\n  | LinePayAbortError\n  | LinePayMiddlewareError\n\nexport function isLinePayError(error: unknown): error is AnyLinePayError {\n  return (\n    typeof error === 'object' &&\n    error !== null &&\n    Reflect.get(error, BRAND) === true\n  )\n}\n\nfunction hasCode(error: unknown, code: LinePayErrorCode): boolean {\n  return isLinePayError(error) && error.code === code\n}\n\nexport function isLinePayValidationError(\n  error: unknown\n): error is LinePayValidationError {\n  return hasCode(error, 'LINE_PAY_VALIDATION_ERROR')\n}\n\nexport function isLinePayApiError(error: unknown): error is LinePayApiError {\n  return hasCode(error, 'LINE_PAY_API_ERROR')\n}\n\nexport function isLinePayHttpError(error: unknown): error is LinePayHttpError {\n  return hasCode(error, 'LINE_PAY_HTTP_ERROR')\n}\n\nexport function isLinePayNetworkError(\n  error: unknown\n): error is LinePayNetworkError {\n  return hasCode(error, 'LINE_PAY_NETWORK_ERROR')\n}\n\nexport function isLinePayTimeoutError(\n  error: unknown\n): error is LinePayTimeoutError {\n  return hasCode(error, 'LINE_PAY_TIMEOUT_ERROR')\n}\n\nexport function isLinePayAbortError(\n  error: unknown\n): error is LinePayAbortError {\n  return hasCode(error, 'LINE_PAY_ABORT_ERROR')\n}\n\nexport function isLinePayMiddlewareError(\n  error: unknown\n): error is LinePayMiddlewareError {\n  return hasCode(error, 'LINE_PAY_MIDDLEWARE_ERROR')\n}\n\n/**\n * An error of a call that `client.reconcile` can look up: it carries the context.\n * It is what `needsReconcile` narrows to, and not plain `AnyLinePayError`: a type\n * guard to the union would leave `never` in the `else` branch of an error that\n * is a `LinePayError` but needs no lookup.\n */\nexport type ReconcilableError = AnyLinePayError & { context: ReconcileContext }\n\n/**\n * `true` when the failed call may already have taken effect and can be looked up\n * with `client.reconcile(error)`: its outcome is unknown, or LINE Pay said it\n * is a duplicate (`category: 'duplicate'`). Only operations that move money or\n * change state qualify.\n */\nexport function needsReconcile(error: unknown): error is ReconcilableError {\n  if (!isLinePayError(error) || error.context === undefined) return false\n  if (!isReconcilableOperation(error.context.operation)) return false\n  return (\n    error.outcome === 'unknown' ||\n    (isLinePayApiError(error) && error.category === 'duplicate')\n  )\n}\n","import {\n  isLinePayError,\n  LinePayAbortError,\n  type LinePayError,\n  LinePayHttpError,\n  LinePayNetworkError,\n  LinePayTimeoutError,\n  type NetworkErrorReason\n} from '../errors'\nimport { isArray, isRecord } from './guard'\n\nexport type FetchImpl = typeof fetch\n\nexport interface TransportRequest {\n  readonly fetch: FetchImpl\n  readonly method: 'GET' | 'POST'\n  readonly url: string\n  readonly headers: Record<string, string>\n  readonly body?: string | undefined\n  readonly timeoutMs: number\n  readonly signal?: AbortSignal | undefined\n}\n\nexport interface TransportResponse {\n  readonly status: number\n  readonly text: string\n}\n\n/**\n * More than any answer of LINE Pay: a page of 100 transactions is a few hundred\n * kilobytes. A response that goes on longer is not read to the end.\n */\nexport const MAX_RESPONSE_BYTES = 8 * 1024 * 1024\n\n/**\n * Error codes of a connection that could not be made. Nothing was sent when one of\n * these shows up while connecting, so the request can safely be tried again.\n *\n * A `Map`, not an object: an error whose code reads `constructor` or `toString`\n * must not be found in the table through the prototype of an object, because\n * what is found here is taken for \"never sent\" and sent again.\n */\nconst NOT_SENT_CODES: ReadonlyMap<string, NetworkErrorReason> = new Map([\n  ['ECONNREFUSED', 'connection-refused'],\n  ['ENOTFOUND', 'dns'],\n  ['EAI_AGAIN', 'dns'],\n  ['ENETUNREACH', 'network-unreachable'],\n  ['EHOSTUNREACH', 'network-unreachable']\n])\n\n/**\n * Where the failing system call was made. The same codes come from a connection\n * that already exists: the kernel reports an ICMP error on it when it finally\n * declares the connection dead, as `read ECONNREFUSED`. By then the request is\n * out, so only a failure of `connect` or of the lookup of the name shows that\n * nothing was sent.\n */\nconst CONNECTING_SYSCALLS: ReadonlySet<string> = new Set([\n  'connect',\n  'getaddrinfo'\n])\n\n/** What one attempt to connect left behind. */\ninterface Attempt {\n  readonly code: string | undefined\n  readonly syscall: string | undefined\n  readonly message: string | undefined\n}\n\nfunction readAttempt(value: unknown): Attempt {\n  if (!isRecord(value)) {\n    return { code: undefined, syscall: undefined, message: undefined }\n  }\n  const { code, syscall, message } = value\n  return {\n    code: typeof code === 'string' ? code : undefined,\n    syscall: typeof syscall === 'string' ? syscall : undefined,\n    message: typeof message === 'string' ? message : undefined\n  }\n}\n\n/** What an error says caused it, if it says anything. */\nfunction causeOf(error: unknown): unknown {\n  return isRecord(error) ? error.cause : undefined\n}\n\n/**\n * The attempts behind a failure. Node.js reports `fetch` failures as\n * `TypeError: fetch failed` with the real error in `cause`. When several\n * addresses were tried, the cause is an `AggregateError`: its own `code` is only\n * that of the first attempt, so the attempts are read one by one, and one that\n * says nothing counts as something unknown rather than being left out.\n */\nfunction findAttempts(error: unknown): Attempt[] {\n  const cause = causeOf(error)\n  if (cause === undefined || cause === null) return []\n  const nested = isRecord(cause) ? cause.errors : undefined\n  return isArray(nested) ? nested.map(readAttempt) : [readAttempt(cause)]\n}\n\nfunction neverConnected(attempt: Attempt): boolean {\n  if (attempt.message === 'bad port') {\n    // `fetch` refuses some ports before it connects to anything.\n    return true\n  }\n  return (\n    attempt.code !== undefined &&\n    NOT_SENT_CODES.has(attempt.code) &&\n    attempt.syscall !== undefined &&\n    CONNECTING_SYSCALLS.has(attempt.syscall)\n  )\n}\n\nfunction causeMessage(error: unknown): string {\n  const cause = causeOf(error)\n  return cause instanceof Error ? cause.message : ''\n}\n\nexport function classifyFetchError(\n  error: unknown,\n  context: {\n    readonly timeoutMs: number\n    readonly timedOut: boolean\n    readonly userSignal?: AbortSignal | undefined\n    /** The response had begun to arrive: the request was out. */\n    readonly afterResponse?: boolean\n  }\n): LinePayError {\n  // The caller's own cancellation wins over the timeout.\n  if (context.userSignal?.aborted === true) {\n    return new LinePayAbortError({\n      abortReason: context.userSignal.reason,\n      outcome: 'unknown'\n    })\n  }\n  // The timer covers the whole exchange and cannot tell the connection phase\n  // from the read phase, so the outcome is `unknown`.\n  if (context.timedOut) {\n    return new LinePayTimeoutError({\n      timeoutMs: context.timeoutMs,\n      cause: error\n    })\n  }\n\n  const attempts = findAttempts(error)\n  const [first] = attempts\n  if (\n    context.afterResponse !== true &&\n    attempts.length > 0 &&\n    attempts.every(neverConnected)\n  ) {\n    return new LinePayNetworkError({\n      reason: NOT_SENT_CODES.get(first?.code ?? '') ?? 'other',\n      causeCode: first?.code,\n      outcome: 'not-sent',\n      cause: error\n    })\n  }\n\n  let reason: NetworkErrorReason = 'other'\n  if (\n    context.afterResponse === true ||\n    attempts.some(\n      attempt =>\n        attempt.code === 'UND_ERR_SOCKET' ||\n        attempt.code === 'ECONNRESET' ||\n        // Refused or unreachable, but not while connecting: a connection that\n        // existed was torn down.\n        (attempt.code !== undefined && NOT_SENT_CODES.has(attempt.code))\n    )\n  ) {\n    reason = 'connection-reset'\n  } else if (/redirect/i.test(causeMessage(error))) {\n    reason = 'redirect'\n  } else if (error instanceof TypeError && error.message === 'terminated') {\n    reason = 'connection-reset'\n  }\n  return new LinePayNetworkError({\n    reason,\n    causeCode: first?.code,\n    // Anything that is not provably \"never connected\" may have been processed.\n    outcome: 'unknown',\n    cause: error\n  })\n}\n\n/**\n * The text of the response, read in pieces so that a response without an end does\n * not fill the memory. Past the limit it stops reading.\n */\nasync function readText(response: Response): Promise<string> {\n  // A `fetch` of one's own may answer with a body that is no stream.\n  const stream: ReadableStream<unknown> | null = response.body\n  if (stream === null || typeof stream?.getReader !== 'function') {\n    return response.text()\n  }\n\n  const tooLarge = () =>\n    new LinePayHttpError({\n      httpStatus: response.status,\n      reason: 'body-too-large',\n      outcome: 'unknown'\n    })\n  const declared = Number(response.headers?.get('content-length'))\n  const reader: ReadableStreamDefaultReader<unknown> = stream.getReader()\n  if (declared > MAX_RESPONSE_BYTES) {\n    await reader.cancel().catch(() => undefined)\n    throw tooLarge()\n  }\n\n  const chunks: Uint8Array[] = []\n  let size = 0\n  for (;;) {\n    const { done, value } = await reader.read()\n    if (done) break\n    if (!(value instanceof Uint8Array)) {\n      await reader.cancel().catch(() => undefined)\n      throw new LinePayHttpError({\n        httpStatus: response.status,\n        reason: 'invalid-response',\n        outcome: 'unknown'\n      })\n    }\n    size += value.byteLength\n    if (size > MAX_RESPONSE_BYTES) {\n      await reader.cancel().catch(() => undefined)\n      throw tooLarge()\n    }\n    chunks.push(value)\n  }\n  const bytes = new Uint8Array(size)\n  let offset = 0\n  for (const chunk of chunks) {\n    bytes.set(chunk, offset)\n    offset += chunk.byteLength\n  }\n  return new TextDecoder().decode(bytes)\n}\n\n/**\n * Send one HTTP request. Redirects are never followed: `fetch` would forward the\n * custom `X-LINE-Authorization` header to another origin, and the LINE Pay API\n * does not redirect.\n */\nexport async function sendRequest(\n  request: TransportRequest\n): Promise<TransportResponse> {\n  const { signal: userSignal, timeoutMs } = request\n\n  if (userSignal?.aborted === true) {\n    throw new LinePayAbortError({\n      abortReason: userSignal.reason,\n      outcome: 'not-sent'\n    })\n  }\n\n  // One controller ends the exchange, whether the time is up or the caller gives\n  // up. `AbortSignal.any` would do, but on Node.js 22 it keeps a little memory for\n  // every composite made from a signal that lives on, such as one for the whole\n  // server.\n  const controller = new AbortController()\n  let timedOut = false\n  const timer = setTimeout(() => {\n    timedOut = true\n    controller.abort(\n      new DOMException('The operation timed out.', 'TimeoutError')\n    )\n  }, timeoutMs)\n  // Like `AbortSignal.timeout`: the timer alone does not keep a process alive.\n  if (typeof timer === 'object' && typeof timer.unref === 'function') {\n    timer.unref()\n  }\n  const onAbort = () => controller.abort(userSignal?.reason)\n  userSignal?.addEventListener('abort', onAbort, { once: true })\n\n  try {\n    const init: RequestInit = {\n      method: request.method,\n      headers: request.headers,\n      signal: controller.signal,\n      redirect: 'error'\n    }\n    if (request.body !== undefined) init.body = request.body\n\n    // Called on its own, not as `request.fetch(...)`: the global `fetch` of a\n    // browser or a Worker throws \"Illegal invocation\" with any other `this`.\n    const { fetch: send } = request\n    let response: Response\n    try {\n      response = await send(request.url, init)\n    } catch (error) {\n      throw classifyFetchError(error, { timeoutMs, timedOut, userSignal })\n    }\n\n    // From here on the request is out, whatever the error says.\n    try {\n      return { status: response.status, text: await readText(response) }\n    } catch (error) {\n      if (isLinePayError(error)) throw error\n      throw classifyFetchError(error, {\n        timeoutMs,\n        timedOut,\n        userSignal,\n        afterResponse: true\n      })\n    }\n  } finally {\n    clearTimeout(timer)\n    userSignal?.removeEventListener('abort', onAbort)\n  }\n}\n","import {\n  LinePayValidationError,\n  type LinePayValidationErrorInit,\n  type ValidationIssue\n} from '../errors'\nimport type { Currency } from '../types'\n\nconst TRANSACTION_ID = /^\\d{1,19}$/\nconst REG_KEY = /^[A-Za-z0-9]{1,64}$/\n\nexport const CURRENCIES = [\n  'USD',\n  'TWD',\n  'THB'\n] as const satisfies readonly Currency[]\n\n// Every currency of the type is in the list: a currency added to one and not to\n// the other would make every typed call fail its own validation.\nconst _everyCurrencyIsListed: [\n  Exclude<Currency, (typeof CURRENCIES)[number]>\n] extends [never]\n  ? true\n  : never = true\n\n/** Amounts are compared with a tolerance: sums of prices such as 0.1 + 0.2 are not exact. */\nexport const amountsEqual = (a: number, b: number): boolean =>\n  Math.abs(a - b) < 1e-9\n\nexport function isTransactionId(value: unknown): value is string {\n  return typeof value === 'string' && TRANSACTION_ID.test(value)\n}\n\nexport function isRegKey(value: unknown): value is string {\n  return typeof value === 'string' && REG_KEY.test(value)\n}\n\n/**\n * Validate a value that is placed into the URL path and return it encoded.\n *\n * This always runs, even with `validate: false`: the transaction ID usually comes\n * from the query string of the confirmUrl, which the user controls, and it is part\n * of what gets signed. Version 0.9 interpolated it unchecked.\n */\nexport function pathSegment(\n  kind: 'transactionId' | 'regKey',\n  value: unknown\n): string {\n  if (kind === 'transactionId') {\n    if (!isTransactionId(value)) {\n      throw new LinePayValidationError({\n        issues: [\n          {\n            path: 'transactionId',\n            message: 'must be a string of 1 to 19 digits'\n          }\n        ]\n      })\n    }\n    return encodeURIComponent(value)\n  }\n  if (!isRegKey(value)) {\n    throw new LinePayValidationError({\n      issues: [{ path: 'regKey', message: 'must be 1 to 64 letters or digits' }]\n    })\n  }\n  return encodeURIComponent(value)\n}\n\n/** Collects several problems of one input before throwing a single error. */\nexport class Checker {\n  readonly issues: ValidationIssue[] = []\n\n  fail(path: string, message: string): void {\n    this.issues.push({ path, message })\n  }\n\n  nonEmptyString(path: string, value: unknown, maxLength?: number): void {\n    if (typeof value !== 'string' || value.length === 0) {\n      this.fail(path, 'must be a non-empty string')\n    } else if (maxLength !== undefined && value.length > maxLength) {\n      this.fail(path, `must be at most ${maxLength} characters`)\n    }\n  }\n\n  finiteNumber(path: string, value: unknown): void {\n    if (typeof value !== 'number' || !Number.isFinite(value)) {\n      this.fail(path, 'must be a finite number')\n    }\n  }\n\n  nonNegativeNumber(path: string, value: unknown): void {\n    if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n      this.fail(path, 'must be a finite number, 0 or greater')\n    }\n  }\n\n  /**\n   * Fields the operation does not have. A misspelled optional field would be left\n   * out without a word, and a caller who passes on what a user sent (`...req.body`)\n   * would have the user's own fields signed and sent.\n   */\n  onlyFields(\n    path: string,\n    value: object,\n    allowed: readonly string[],\n    what: string\n  ): void {\n    for (const key of Object.keys(value)) {\n      if (!allowed.includes(key)) {\n        this.fail(\n          path === '' ? key : `${path}.${key}`,\n          `is not a field of ${what}`\n        )\n      }\n    }\n  }\n\n  positiveNumber(path: string, value: unknown): void {\n    if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n      this.fail(path, 'must be a finite number greater than 0')\n    }\n  }\n\n  boolean(path: string, value: unknown): void {\n    if (typeof value !== 'boolean') this.fail(path, 'must be true or false')\n  }\n\n  oneOf(path: string, value: unknown, allowed: readonly string[]): void {\n    if (typeof value !== 'string' || !allowed.includes(value)) {\n      this.fail(path, `must be one of ${allowed.join(', ')}`)\n    }\n  }\n\n  throwIfInvalid(\n    about: Pick<LinePayValidationErrorInit, 'operation' | 'subject'> = {}\n  ): void {\n    if (this.issues.length > 0) {\n      throw new LinePayValidationError({ ...about, issues: this.issues })\n    }\n  }\n}\n","import type {\n  Address,\n  PayInfo,\n  PaymentProvider,\n  Product,\n  Recipient,\n  ResponsePackage,\n  SelectedShipping\n} from '../types'\nimport { type Guard, hasShape, isListOf, isNumber, isString } from './guard'\n\n/**\n * The guards of the pieces that LINE Pay responses are made of. A guard checks\n * every field its interface declares: the ones that are always there must be there\n * with the right type, and the others must have the right type when they are.\n * That is what lets a response be given its type without a type assertion.\n */\n\n/** The two fields every response carries. */\nexport const RESPONSE_FIELDS = {\n  returnCode: isString,\n  returnMessage: isString\n}\n\nexport const isRecipient: Guard<Recipient> = hasShape(\n  {},\n  {\n    firstName: isString,\n    lastName: isString,\n    firstNameOptional: isString,\n    lastNameOptional: isString,\n    email: isString,\n    phoneNo: isString\n  }\n)\n\nexport const isAddress: Guard<Address> = hasShape(\n  {},\n  {\n    country: isString,\n    postalCode: isString,\n    state: isString,\n    city: isString,\n    detail: isString,\n    optional: isString,\n    recipient: isRecipient\n  }\n)\n\nexport const isProduct: Guard<Product> = hasShape(\n  { name: isString, quantity: isNumber, price: isNumber },\n  { id: isString, imageUrl: isString, originalPrice: isNumber }\n)\n\nexport const isPayInfo: Guard<PayInfo> = hasShape(\n  { method: isString, amount: isNumber },\n  {\n    creditCardNickname: isString,\n    creditCardBrand: isString,\n    maskedCreditCardNumber: isString\n  }\n)\n\nexport const isSelectedShipping: Guard<SelectedShipping> = hasShape(\n  { methodId: isString, feeAmount: isNumber },\n  { address: isAddress }\n)\n\nexport const isResponsePackage: Guard<ResponsePackage> = hasShape(\n  { id: isString, amount: isNumber },\n  { name: isString, userFeeAmount: isNumber, products: isListOf(isProduct) }\n)\n\n/** V4 sends \"TSP\" or \"EPI\" as a string, not an object. */\nexport const isPaymentProvider: Guard<PaymentProvider> = isString\n","import { type Guard, hasShape, isListOf, isString } from '../core/guard'\nimport {\n  isPayInfo,\n  isPaymentProvider,\n  RESPONSE_FIELDS\n} from '../core/response-guards'\nimport { CURRENCIES, pathSegment } from '../core/validate'\nimport type {\n  Currency,\n  LinePayResponse,\n  PayInfo,\n  PaymentProvider\n} from '../types'\nimport type { OperationDefinition } from './define'\n\nexport interface CaptureOptions {\n  extra: {\n    /**\n     * Points restriction (Taiwan only). `useLimit` is the amount that cannot be\n     * paid with points; `rewardLimit` the amount that earns no reward points.\n     */\n    promotionRestriction: Record<string, unknown>\n  }\n}\n\n/** Fields of the capture API. `transactionId` goes into the URL. */\nexport interface CaptureInput {\n  transactionId: string\n  amount: number\n  currency: Currency\n  options?: CaptureOptions\n}\n\nexport interface CaptureResponse extends LinePayResponse {\n  info: {\n    orderId: string\n    transactionId: string\n    payInfo: PayInfo[]\n    /** V4 settlement provider (`TSP` or `EPI`), when supplied. */\n    paymentProvider?: PaymentProvider\n  }\n}\n\nconst isCaptureResponse: Guard<CaptureResponse> = hasShape({\n  ...RESPONSE_FIELDS,\n  info: hasShape(\n    {\n      orderId: isString,\n      transactionId: isString,\n      payInfo: isListOf(isPayInfo)\n    },\n    { paymentProvider: isPaymentProvider }\n  )\n})\n\nexport const captureOperation: OperationDefinition<\n  CaptureInput,\n  CaptureResponse\n> = {\n  method: 'POST',\n  defaultTimeout: 60_000,\n  effect: 'settle',\n  response: isCaptureResponse,\n  path: input =>\n    `/v4/payments/authorizations/${pathSegment('transactionId', input.transactionId)}/capture`,\n  check(input, c) {\n    c.onlyFields(\n      '',\n      input,\n      ['transactionId', 'amount', 'currency', 'options'],\n      'a capture'\n    )\n    c.positiveNumber('amount', input.amount)\n    c.oneOf('currency', input.currency, CURRENCIES)\n  },\n  body: ({ transactionId: _transactionId, ...body }) => body,\n  reconcileFields: ({ transactionId, amount, currency }) => ({\n    transactionId,\n    amount,\n    currency\n  })\n}\n","import {\n  type Guard,\n  hasShape,\n  isListOf,\n  isNumber,\n  isString\n} from '../core/guard'\nimport { RESPONSE_FIELDS } from '../core/response-guards'\nimport { pathSegment } from '../core/validate'\nimport type { LinePayResponse } from '../types'\nimport type { OperationDefinition } from './define'\n\nexport interface CheckPaymentStatusInput {\n  transactionId: string\n}\n\n/**\n * The status of the request is carried by `returnCode`; codes that start with `0`\n * are returned as they are and not thrown. **Here `0000` is not a success**:\n *\n * | `returnCode` | Meaning                                                  |\n * | ------------ | -------------------------------------------------------- |\n * | `0000`       | The user has not authorized the payment yet.             |\n * | `0110`       | Authorized: `confirm` can be called.                     |\n * | `0121`       | Canceled by the user, or timed out (20 minutes). Final.  |\n * | `0122`       | Failed. Final.                                           |\n * | `0123`       | Completed. Final.                                        |\n *\n * Mark an order paid on the result of `confirm` (or of `reconcile`), never on\n * what this says.\n *\n * The V4 status-check reference defines all five return codes, including 0110.\n * Sandbox testing has observed 0000, 0121, 0122 and 0123. Observing 0110\n * requires a buyer to authorize a sandbox request before confirm.\n */\nexport interface CheckPaymentStatusResponse extends LinePayResponse {\n  info?: { shipping?: { methodId: string; feeAmount: number } }[]\n}\n\nconst isCheckPaymentStatusResponse: Guard<CheckPaymentStatusResponse> =\n  hasShape(RESPONSE_FIELDS, {\n    info: isListOf(\n      hasShape(\n        {},\n        { shipping: hasShape({ methodId: isString, feeAmount: isNumber }) }\n      )\n    )\n  })\n\nexport const checkPaymentStatusOperation: OperationDefinition<\n  CheckPaymentStatusInput,\n  CheckPaymentStatusResponse\n> = {\n  method: 'GET',\n  defaultTimeout: 20_000,\n  effect: 'read',\n  response: isCheckPaymentStatusResponse,\n  statusCodes: true,\n  path: input =>\n    `/v4/payments/requests/${pathSegment('transactionId', input.transactionId)}/check`,\n  check(input, c) {\n    c.onlyFields('', input, ['transactionId'], 'a payment status check')\n  },\n  query: () => ({})\n}\n","import { type Guard, hasShape } from '../core/guard'\nimport { RESPONSE_FIELDS } from '../core/response-guards'\nimport { pathSegment } from '../core/validate'\nimport type { LinePayResponse } from '../types'\nimport type { OperationDefinition } from './define'\n\n/** Fields of the check regKey API. `regKey` goes into the URL. */\nexport interface CheckRegKeyInput {\n  regKey: string\n  /**\n   * `true` verifies the card with a minimum authorization (needs approval from\n   * the LINE Pay manager). `false` checks the status with LINE Pay only. A check\n   * with `true` is not repeated by `retryWhenNotSent` after an unknown outcome.\n   */\n  creditCardAuth?: boolean\n}\n\nexport type CheckRegKeyResponse = LinePayResponse\n\nconst isCheckRegKeyResponse: Guard<CheckRegKeyResponse> =\n  hasShape(RESPONSE_FIELDS)\n\nexport const checkRegKeyOperation: OperationDefinition<\n  CheckRegKeyInput,\n  CheckRegKeyResponse\n> = {\n  method: 'GET',\n  defaultTimeout: 20_000,\n  effect: 'read',\n  response: isCheckRegKeyResponse,\n  // With `creditCardAuth` the check places a card authorization. It is not a\n  // read any more: repeating it after an unknown outcome could authorize the card\n  // again. Anything but an explicit `false` counts, so that a value of the wrong\n  // type, which is sent all the same, does not slip through as a read.\n  effectOf: input =>\n    input.creditCardAuth === undefined || input.creditCardAuth === false\n      ? 'read'\n      : 'create',\n  path: input =>\n    `/v4/payments/preapprovedPay/${pathSegment('regKey', input.regKey)}/check`,\n  check(input, c) {\n    c.onlyFields('', input, ['regKey', 'creditCardAuth'], 'a regKey check')\n    if (input.creditCardAuth !== undefined) {\n      c.boolean('creditCardAuth', input.creditCardAuth)\n    }\n  },\n  query: input => ({ creditCardAuth: input.creditCardAuth })\n}\n","import { type Guard, hasShape, isListOf, isString } from '../core/guard'\nimport {\n  isPayInfo,\n  isPaymentProvider,\n  isResponsePackage,\n  isSelectedShipping,\n  RESPONSE_FIELDS\n} from '../core/response-guards'\nimport { CURRENCIES, pathSegment } from '../core/validate'\nimport type {\n  Currency,\n  LinePayResponse,\n  PayInfo,\n  PaymentProvider,\n  ResponsePackage,\n  SelectedShipping\n} from '../types'\nimport type { OperationDefinition } from './define'\n\n/** Fields of the confirm API. `transactionId` goes into the URL. */\nexport interface ConfirmInput {\n  /**\n   * Transaction ID returned by `request`. It is also on the confirmUrl, but that\n   * one comes from the browser: use the ID you stored for the order, or check\n   * that the one from the URL is that one.\n   */\n  transactionId: string\n  /** Must equal the amount of the request. */\n  amount: number\n  currency: Currency\n}\n\nexport interface ConfirmResponse extends LinePayResponse {\n  info: {\n    orderId: string\n    transactionId: string\n    /** Only when the payment was authorized without capture. ISO 8601. */\n    authorizationExpireDate?: string\n    /**\n     * Key for payments without approval (15 characters). It is only returned\n     * here, so store it right away.\n     */\n    regKey?: string\n    payInfo: PayInfo[]\n    packages?: ResponsePackage[]\n    shipping?: SelectedShipping\n    /** V4 settlement provider (`TSP` or `EPI`), when supplied. */\n    paymentProvider?: PaymentProvider\n  }\n}\n\nconst isConfirmResponse: Guard<ConfirmResponse> = hasShape({\n  ...RESPONSE_FIELDS,\n  info: hasShape(\n    {\n      orderId: isString,\n      transactionId: isString,\n      payInfo: isListOf(isPayInfo)\n    },\n    {\n      authorizationExpireDate: isString,\n      regKey: isString,\n      packages: isListOf(isResponsePackage),\n      shipping: isSelectedShipping,\n      paymentProvider: isPaymentProvider\n    }\n  )\n})\n\nexport const confirmOperation: OperationDefinition<\n  ConfirmInput,\n  ConfirmResponse\n> = {\n  method: 'POST',\n  defaultTimeout: 40_000,\n  effect: 'settle',\n  response: isConfirmResponse,\n  path: input =>\n    `/v4/payments/${pathSegment('transactionId', input.transactionId)}/confirm`,\n  check(input, c) {\n    c.onlyFields(\n      '',\n      input,\n      ['transactionId', 'amount', 'currency'],\n      'a confirm'\n    )\n    c.positiveNumber('amount', input.amount)\n    c.oneOf('currency', input.currency, CURRENCIES)\n  },\n  body: ({ transactionId: _transactionId, ...body }) => body,\n  reconcileFields: ({ transactionId, amount, currency }) => ({\n    transactionId,\n    amount,\n    currency\n  })\n}\n","import { type Guard, hasShape } from '../core/guard'\nimport { RESPONSE_FIELDS } from '../core/response-guards'\nimport { pathSegment } from '../core/validate'\nimport type { LinePayResponse } from '../types'\nimport type { OperationDefinition } from './define'\n\nexport interface ExpireRegKeyInput {\n  regKey: string\n}\n\nexport type ExpireRegKeyResponse = LinePayResponse\n\nconst isExpireRegKeyResponse: Guard<ExpireRegKeyResponse> =\n  hasShape(RESPONSE_FIELDS)\n\nexport const expireRegKeyOperation: OperationDefinition<\n  ExpireRegKeyInput,\n  ExpireRegKeyResponse\n> = {\n  method: 'POST',\n  defaultTimeout: 20_000,\n  effect: 'settle',\n  response: isExpireRegKeyResponse,\n  path: input =>\n    `/v4/payments/preapprovedPay/${pathSegment('regKey', input.regKey)}/expire`,\n  check(input, c) {\n    c.onlyFields('', input, ['regKey'], 'expiring a regKey')\n  },\n  body: () => ({})\n}\n","import { type Guard, hasShape, isString } from '../core/guard'\nimport { isPaymentProvider, RESPONSE_FIELDS } from '../core/response-guards'\nimport { CURRENCIES, pathSegment } from '../core/validate'\nimport type { Currency, LinePayResponse, PaymentProvider } from '../types'\nimport type { OperationDefinition } from './define'\n\n/** Fields of the pre-approved payment API. `regKey` goes into the URL. */\nexport interface PayPreapprovedInput {\n  regKey: string\n  productName: string\n  amount: number\n  currency: Currency\n  /** A unique order ID, at most 100 characters. Also the key to reconcile. */\n  orderId: string\n  /** `false` only authorizes; capture later with `capture`. */\n  capture?: boolean\n}\n\nexport interface PayPreapprovedResponse extends LinePayResponse {\n  info: {\n    orderId?: string\n    /** 19 digits. */\n    transactionId: string\n    /** ISO 8601. */\n    transactionDate: string\n    /** The V4 clearing provider (TSP or EPI). */\n    paymentProvider?: PaymentProvider\n    /** ISO 8601. Only when `capture` is `false`. */\n    authorizationExpireDate?: string\n  }\n}\n\nconst isPayPreapprovedResponse: Guard<PayPreapprovedResponse> = hasShape({\n  ...RESPONSE_FIELDS,\n  info: hasShape(\n    { transactionId: isString, transactionDate: isString },\n    {\n      orderId: isString,\n      authorizationExpireDate: isString,\n      paymentProvider: isPaymentProvider\n    }\n  )\n})\n\nexport const payPreapprovedOperation: OperationDefinition<\n  PayPreapprovedInput,\n  PayPreapprovedResponse\n> = {\n  method: 'POST',\n  defaultTimeout: 40_000,\n  effect: 'settle',\n  response: isPayPreapprovedResponse,\n  path: input =>\n    `/v4/payments/preapprovedPay/${pathSegment('regKey', input.regKey)}/payment`,\n  check(input, c) {\n    c.onlyFields(\n      '',\n      input,\n      ['regKey', 'productName', 'amount', 'currency', 'orderId', 'capture'],\n      'a pre-approved payment'\n    )\n    c.nonEmptyString('productName', input.productName)\n    c.positiveNumber('amount', input.amount)\n    c.oneOf('currency', input.currency, CURRENCIES)\n    c.nonEmptyString('orderId', input.orderId, 100)\n    // `false` authorizes without capturing: a text of 'false' is not that.\n    if (input.capture !== undefined) c.boolean('capture', input.capture)\n  },\n  body: ({ regKey: _regKey, ...body }) => body,\n  // Not the regKey: it is a credential, and reconcile looks the payment up by\n  // its order ID.\n  reconcileFields: ({ orderId, amount, currency }) => ({\n    orderId,\n    amount,\n    currency\n  })\n}\n","import {\n  type Guard,\n  hasShape,\n  isArray,\n  isListOf,\n  isNumber,\n  isString\n} from '../core/guard'\nimport {\n  isPayInfo,\n  isPaymentProvider,\n  isResponsePackage,\n  isSelectedShipping,\n  RESPONSE_FIELDS\n} from '../core/response-guards'\nimport { isTransactionId } from '../core/validate'\nimport { LinePayValidationError, type ValidationIssue } from '../errors'\nimport type {\n  LinePayResponse,\n  OpenString,\n  PayInfo,\n  PaymentProvider,\n  ResponsePackage,\n  SelectedShipping\n} from '../types'\nimport type { OperationDefinition } from './define'\n\n/**\n * Query of the payment details API. Pass at least one of the two ID lists.\n *\n * V4 sandbox accepts multiple IDs as repeated parameters\n * (`transactionId=1&transactionId=2`), as well as comma-joined values.\n * The SDK sends repeated parameters for both transactionId and orderId.\n */\nexport interface PaymentDetailsInput {\n  /** Transaction IDs of payments or refunds. */\n  transactionId?: string[]\n  /** Your order IDs. */\n  orderId?: string[]\n}\n\nexport interface RefundEntry {\n  /** 19 digits. */\n  refundTransactionId: string\n  /** `PAYMENT_REFUND` or `PARTIAL_REFUND`. */\n  transactionType: OpenString<'PAYMENT_REFUND' | 'PARTIAL_REFUND'>\n  /**\n   * The amount that was refunded. The sandbox has been observed to report it as\n   * a negative number, so compare absolute values.\n   */\n  refundAmount: number\n  /** ISO 8601. */\n  refundTransactionDate: string\n}\n\nexport interface PromotionEvent {\n  /** Alphanumeric event code. */\n  code: string\n  totalAmount: number\n  productQuantity: number\n}\n\n/**\n * One payment or refund in the payment details. Sandbox confirmed standalone\n * refund entries have a refund transaction type, originalTransactionId and\n * positive payInfo amounts; the original payment carries a refundList with\n * negative refundAmount values. Other fields differ by entry type.\n */\nexport interface PaymentDetailsInfo {\n  /** 19 digits. */\n  transactionId: string\n  /** `PAYMENT`, `PAYMENT_REFUND` or `PARTIAL_REFUND`. */\n  transactionType: OpenString<'PAYMENT' | 'PAYMENT_REFUND' | 'PARTIAL_REFUND'>\n  orderId?: string\n  /** ISO 8601. */\n  transactionDate?: string\n  /**\n   * - `CAPTURE`: captured\n   * - `AUTHORIZATION`: authorized, not yet captured\n   * - `VOIDED_AUTHORIZATION`: authorization voided\n   * - `EXPIRED_AUTHORIZATION`: authorization expired\n   */\n  payStatus?: OpenString<\n    | 'CAPTURE'\n    | 'AUTHORIZATION'\n    | 'VOIDED_AUTHORIZATION'\n    | 'EXPIRED_AUTHORIZATION'\n  >\n  productName?: string\n  merchantName?: string\n  /** ISO 4217. Older transactions can be in a currency the library no longer lists. */\n  currency?: string\n  /** ISO 8601. Also observed on captured payments; absent from refund entries. */\n  authorizationExpireDate?: string\n  payInfo?: PayInfo[]\n  /** Refunds of the original transaction. */\n  refundList?: RefundEntry[]\n  /** Set when this entry is a refund: the payment that was refunded (19 digits). */\n  originalTransactionId?: string\n  packages?: ResponsePackage[]\n  shipping?: SelectedShipping\n  events?: PromotionEvent[]\n  /** Observed as \"TSP\" on sandbox payment and refund entries. */\n  paymentProvider?: PaymentProvider\n}\n\nexport interface PaymentDetailsResponse extends LinePayResponse {\n  info: PaymentDetailsInfo[]\n}\n\nconst isRefundEntry: Guard<RefundEntry> = hasShape({\n  refundTransactionId: isString,\n  transactionType: isString,\n  refundAmount: isNumber,\n  refundTransactionDate: isString\n})\n\nconst isPromotionEvent: Guard<PromotionEvent> = hasShape({\n  code: isString,\n  totalAmount: isNumber,\n  productQuantity: isNumber\n})\n\nconst isPaymentDetailsInfo: Guard<PaymentDetailsInfo> = hasShape(\n  { transactionId: isString, transactionType: isString },\n  {\n    orderId: isString,\n    transactionDate: isString,\n    payStatus: isString,\n    productName: isString,\n    merchantName: isString,\n    currency: isString,\n    authorizationExpireDate: isString,\n    payInfo: isListOf(isPayInfo),\n    refundList: isListOf(isRefundEntry),\n    originalTransactionId: isString,\n    packages: isListOf(isResponsePackage),\n    shipping: isSelectedShipping,\n    events: isListOf(isPromotionEvent),\n    paymentProvider: isPaymentProvider\n  }\n)\n\nconst isPaymentDetailsResponse: Guard<PaymentDetailsResponse> = hasShape({\n  ...RESPONSE_FIELDS,\n  info: isListOf(isPaymentDetailsInfo)\n})\n\nconst isEmpty = (list: unknown) => !isArray(list) || list.length === 0\n\n/**\n * The transaction IDs of a lookup, as strings. A number would be rounded without\n * a word (`2021121300698360311` becomes `2021121300698360300`) and the wrong\n * payment would be looked up, so this is checked even with `validate: false`.\n */\nfunction transactionIds(ids: unknown): string[] | undefined {\n  if (ids === undefined) return undefined\n  if (!isArray(ids)) {\n    throw new LinePayValidationError({\n      issues: [{ path: 'transactionId', message: 'must be an array of IDs' }]\n    })\n  }\n  const valid: string[] = []\n  const issues: ValidationIssue[] = []\n  ids.forEach((id: unknown, index) => {\n    if (isTransactionId(id)) {\n      valid.push(id)\n    } else {\n      issues.push({\n        path: `transactionId[${index}]`,\n        message: 'must be a string of 1 to 19 digits'\n      })\n    }\n  })\n  if (issues.length > 0) throw new LinePayValidationError({ issues })\n  return valid\n}\n\nexport const paymentDetailsOperation: OperationDefinition<\n  PaymentDetailsInput,\n  PaymentDetailsResponse\n> = {\n  method: 'GET',\n  defaultTimeout: 60_000,\n  effect: 'read',\n  response: isPaymentDetailsResponse,\n  path: () => '/v4/payments',\n  check(input, c) {\n    c.onlyFields(\n      '',\n      input,\n      ['transactionId', 'orderId'],\n      'a payment details lookup'\n    )\n    if (isEmpty(input.transactionId) && isEmpty(input.orderId)) {\n      c.fail('transactionId', 'or orderId must contain at least one value')\n    }\n    if (isArray(input.orderId)) {\n      input.orderId.forEach((id: unknown, index) => {\n        c.nonEmptyString(`orderId[${index}]`, id)\n      })\n    }\n  },\n  query: input => ({\n    transactionId: transactionIds(input.transactionId),\n    orderId: input.orderId\n  })\n}\n","import { type Guard, hasShape, isString } from '../core/guard'\nimport { isPaymentProvider, RESPONSE_FIELDS } from '../core/response-guards'\nimport { pathSegment } from '../core/validate'\nimport type { LinePayResponse, PaymentProvider } from '../types'\nimport type { OperationDefinition } from './define'\n\n/** Fields of the refund API. `transactionId` goes into the URL. */\nexport interface RefundInput {\n  /** The transaction ID of the payment to refund. */\n  transactionId: string\n  /** Leave it out to refund the whole payment. */\n  refundAmount?: number\n}\n\nexport interface RefundResponse extends LinePayResponse {\n  info: {\n    /** The newly issued transaction ID of the refund. */\n    refundTransactionId: string\n    /** ISO 8601. */\n    refundTransactionDate: string\n    /** Provider observed on V4 sandbox refund responses. */\n    paymentProvider?: PaymentProvider\n  }\n}\n\nconst isRefundResponse: Guard<RefundResponse> = hasShape({\n  ...RESPONSE_FIELDS,\n  info: hasShape(\n    {\n      refundTransactionId: isString,\n      refundTransactionDate: isString\n    },\n    { paymentProvider: isPaymentProvider }\n  )\n})\n\nexport const refundOperation: OperationDefinition<RefundInput, RefundResponse> =\n  {\n    method: 'POST',\n    // Refunds are not idempotent: a partial refund can legitimately be repeated.\n    defaultTimeout: 20_000,\n    effect: 'refund',\n    response: isRefundResponse,\n    path: input =>\n      `/v4/payments/${pathSegment('transactionId', input.transactionId)}/refund`,\n    // Leaving the amount out refunds the whole payment, and that cannot be undone.\n    // So whatever is not a plain amount must not turn into that, and these rules\n    // hold with `validate: false` too:\n    invariants(input, c) {\n      // A key that is there without a value (a variable that was never set).\n      if ('refundAmount' in input && input.refundAmount === undefined) {\n        c.fail(\n          'refundAmount',\n          'is undefined; leave it out to refund the whole payment'\n        )\n      } else if (input.refundAmount !== undefined) {\n        // NaN and the infinities are written as `null` by JSON.\n        c.positiveNumber('refundAmount', input.refundAmount)\n      }\n      // A misspelled key (refundAmout) would be a full refund.\n      for (const key of Object.keys(input)) {\n        if (key !== 'transactionId' && key !== 'refundAmount') {\n          c.fail(key, 'is not a field of a refund (the amount is refundAmount)')\n        }\n      }\n    },\n    body: input =>\n      input.refundAmount === undefined\n        ? {}\n        : { refundAmount: input.refundAmount },\n    reconcileFields: ({ transactionId, refundAmount }) =>\n      refundAmount === undefined\n        ? { transactionId }\n        : { transactionId, refundAmount }\n  }\n","import {\n  type Guard,\n  hasShape,\n  isArray,\n  isRecord,\n  isString\n} from '../core/guard'\nimport { RESPONSE_FIELDS } from '../core/response-guards'\nimport { amountsEqual, CURRENCIES } from '../core/validate'\nimport type {\n  Address,\n  Currency,\n  LinePayResponse,\n  OpenString,\n  Product\n} from '../types'\nimport type { OperationDefinition } from './define'\n\nexport interface RequestPackage {\n  /** A unique ID of the package. */\n  id: string\n  /** `sum(products[].quantity * products[].price)` */\n  amount: number\n  /** Commission included in the payment amount, if any. */\n  userFee?: number\n  /** Name of the package or of an internal shop. */\n  name?: string\n  products: Product[]\n}\n\nexport interface RedirectUrlsWithCallbacks {\n  /** Prevents phishing when moving between apps on Android. */\n  appPackageName?: string\n  /** Where the user is sent after approving the payment. */\n  confirmUrl: string\n  /**\n   * How the confirmUrl is used. `NONE` means no redirect: poll\n   * `checkPaymentStatus` instead.\n   *\n   * V4 supports NONE to use polling without redirect callbacks.\n   */\n  confirmUrlType?: OpenString<'CLIENT' | 'SERVER'>\n  /** Where the user is sent after cancelling on the LINE Pay page. */\n  cancelUrl: string\n}\n\n/** Poll the payment request status instead of receiving redirect callbacks. */\nexport interface RedirectUrlsWithoutCallbacks {\n  confirmUrlType: 'NONE'\n  /** URLs are not used when no callback is requested. */\n  confirmUrl?: never\n  cancelUrl?: never\n  appPackageName?: string\n}\n\nexport type RedirectUrls =\n  RedirectUrlsWithCallbacks | RedirectUrlsWithoutCallbacks\n\nexport interface PaymentOptions {\n  /**\n   * `true` authorizes and captures at confirm. `false` only authorizes, and the\n   * payment has to be captured with `capture`. Not available by default: contact\n   * LINE Pay to enable it.\n   */\n  capture?: boolean\n  /** `PREAPPROVED` registers the user for payments without approval (regKey). */\n  payType?: 'NORMAL' | 'PREAPPROVED'\n}\n\nexport interface DisplayOptions {\n  /** Language of the payment screen: `en`, `ja`, `ko`, `th`, `zh_TW` or `zh_CN`. */\n  locale?: string\n  /** Guide the user back to the LINE Pay browser when the confirmUrl browser differs. */\n  checkConfirmUrlBrowser?: boolean\n}\n\nexport interface ShippingOptions {\n  /** `NO_SHIPPING`, `FIXED_ADDRESS` or `SHIPPING`. */\n  type?: OpenString<'NO_SHIPPING' | 'FIXED_ADDRESS' | 'SHIPPING'>\n  feeAmount?: number\n  /** URL LINE Pay calls to look up the shipping method and fee. */\n  feeInquiryUrl?: string\n  /** `CONDITION` re-checks the fee when the address changes; `FIXED` does not. */\n  feeInquiryType?: OpenString<'CONDITION' | 'FIXED'>\n  address?: Address\n}\n\nexport interface AddFriend {\n  /** Service type of the friend list, for example `lineAt`. */\n  type?: string\n  idList?: string[]\n}\n\nexport interface FamilyServiceOptions {\n  addFriends?: AddFriend[]\n}\n\nexport interface ExtraOptions {\n  /** Only the first 100 characters are shown. */\n  branchName?: string\n  branchId?: string\n}\n\nexport interface RequestPaymentOptions {\n  payment?: PaymentOptions\n  display?: DisplayOptions\n  shipping?: ShippingOptions\n  familyService?: FamilyServiceOptions\n  extra?: ExtraOptions\n  /**\n   * Pre-approved payment registration settings added to the V4 request.\n   *\n   * TODO(v4-spec): the child fields remain unverified. Sandbox testing\n   * requires a merchant enabled for PREAPPROVED (otherwise return code 1194).\n   * Keep the input opaque until that flow can be tested.\n   */\n  regPayRequest?: Record<string, unknown>\n}\n\n/** Fields sent in the body of the request API. */\nexport interface RequestPaymentInput {\n  /** `sum(packages[].amount) + sum(packages[].userFee) + options.shipping.feeAmount` */\n  amount: number\n  currency: Currency\n  /** Your unique order ID, at most 100 characters. */\n  orderId: string\n  packages: RequestPackage[]\n  redirectUrls: RedirectUrls\n  options?: RequestPaymentOptions\n}\n\nexport interface RequestPaymentResponse extends LinePayResponse {\n  info: {\n    /** Use it to confirm, void, capture or refund the payment later. */\n    transactionId: string\n    /** The code entered when a code is used instead of the scanner. */\n    paymentAccessToken?: string\n    paymentUrl: {\n      /** Opens the LINE Pay app from your app. */\n      app?: string\n      /** The LINE Pay payment page. In a desktop pop-up use 700 x 546 px. */\n      web: string\n    }\n  }\n}\n\nconst isRequestPaymentResponse: Guard<RequestPaymentResponse> = hasShape({\n  ...RESPONSE_FIELDS,\n  info: hasShape(\n    {\n      transactionId: isString,\n      paymentUrl: hasShape({ web: isString }, { app: isString })\n    },\n    { paymentAccessToken: isString }\n  )\n})\n\nexport const requestOperation: OperationDefinition<\n  RequestPaymentInput,\n  RequestPaymentResponse\n> = {\n  method: 'POST',\n  defaultTimeout: 20_000,\n  effect: 'create',\n  response: isRequestPaymentResponse,\n  path: () => '/v4/payments/request',\n  check(input, c) {\n    c.onlyFields(\n      '',\n      input,\n      ['amount', 'currency', 'orderId', 'packages', 'redirectUrls', 'options'],\n      'a payment request'\n    )\n    c.positiveNumber('amount', input.amount)\n    c.oneOf('currency', input.currency, CURRENCIES)\n    c.nonEmptyString('orderId', input.orderId, 100)\n    if (input.redirectUrls?.confirmUrlType === 'NONE') {\n      if (input.redirectUrls.confirmUrl !== undefined) {\n        c.fail('redirectUrls.confirmUrl', 'must be omitted for NONE')\n      }\n      if (input.redirectUrls.cancelUrl !== undefined) {\n        c.fail('redirectUrls.cancelUrl', 'must be omitted for NONE')\n      }\n    } else {\n      c.nonEmptyString(\n        'redirectUrls.confirmUrl',\n        input.redirectUrls?.confirmUrl\n      )\n      c.nonEmptyString('redirectUrls.cancelUrl', input.redirectUrls?.cancelUrl)\n    }\n    if (isRecord(input.redirectUrls)) {\n      c.onlyFields(\n        'redirectUrls',\n        input.redirectUrls,\n        ['confirmUrl', 'confirmUrlType', 'cancelUrl', 'appPackageName'],\n        'the redirect URLs'\n      )\n    }\n\n    // Reject undeclared nested fields before they are signed and sent.\n    // The unpublished regPayRequest schema intentionally remains opaque.\n    const checkFields = (\n      path: string,\n      value: unknown,\n      allowed: readonly string[]\n    ): void => {\n      if (value === undefined) return\n      if (!isRecord(value)) {\n        c.fail(path, 'must be an object')\n        return\n      }\n      c.onlyFields(path, value, allowed, 'the ' + path + ' object')\n    }\n    const options: unknown = input.options\n    if (options !== undefined) {\n      checkFields('options', options, [\n        'payment',\n        'display',\n        'shipping',\n        'familyService',\n        'extra',\n        'regPayRequest'\n      ])\n      if (isRecord(options)) {\n        checkFields('options.display', options.display, [\n          'locale',\n          'checkConfirmUrlBrowser'\n        ])\n        checkFields('options.shipping', options.shipping, [\n          'type',\n          'feeAmount',\n          'feeInquiryUrl',\n          'feeInquiryType',\n          'address'\n        ])\n        checkFields('options.familyService', options.familyService, [\n          'addFriends'\n        ])\n        checkFields('options.extra', options.extra, ['branchName', 'branchId'])\n        if (isRecord(options.shipping)) {\n          checkFields('options.shipping.address', options.shipping.address, [\n            'country',\n            'postalCode',\n            'state',\n            'city',\n            'detail',\n            'optional',\n            'recipient'\n          ])\n          if (isRecord(options.shipping.address)) {\n            checkFields(\n              'options.shipping.address.recipient',\n              options.shipping.address.recipient,\n              [\n                'firstName',\n                'lastName',\n                'firstNameOptional',\n                'lastNameOptional',\n                'email',\n                'phoneNo'\n              ]\n            )\n          }\n        }\n        if (\n          isRecord(options.familyService) &&\n          isArray(options.familyService.addFriends)\n        ) {\n          options.familyService.addFriends.forEach((friend, index) => {\n            checkFields(\n              'options.familyService.addFriends[' + index + ']',\n              friend,\n              ['type', 'idList']\n            )\n          })\n        }\n      }\n    }\n\n    // What decides whether the payment only authorizes, or registers a regKey.\n    const payment: unknown = input.options?.payment\n    if (payment !== undefined) {\n      if (!isRecord(payment)) {\n        c.fail('options.payment', 'must be an object')\n      } else {\n        c.onlyFields(\n          'options.payment',\n          payment,\n          ['capture', 'payType'],\n          'the payment options'\n        )\n        if (payment.capture !== undefined) {\n          c.boolean('options.payment.capture', payment.capture)\n        }\n        if (payment.payType !== undefined) {\n          c.oneOf('options.payment.payType', payment.payType, [\n            'NORMAL',\n            'PREAPPROVED'\n          ])\n        }\n      }\n    }\n\n    const { packages } = input\n    if (!isArray(packages) || packages.length === 0) {\n      c.fail('packages', 'must be a non-empty array')\n      return\n    }\n\n    // These are added to the amount that has to match; only numbers may be.\n    const shippingFee: unknown = input.options?.shipping?.feeAmount\n    if (shippingFee !== undefined) {\n      c.nonNegativeNumber('options.shipping.feeAmount', shippingFee)\n    }\n    let expected = typeof shippingFee === 'number' ? shippingFee : 0\n\n    packages.forEach((pack, index) => {\n      const at = `packages[${index}]`\n      if (isRecord(pack)) {\n        c.onlyFields(\n          at,\n          pack,\n          ['id', 'amount', 'userFee', 'name', 'products'],\n          'a package'\n        )\n      }\n      c.nonEmptyString(`${at}.id`, pack?.id)\n      c.positiveNumber(`${at}.amount`, pack?.amount)\n      const userFee: unknown = pack?.userFee\n      if (userFee !== undefined) c.nonNegativeNumber(`${at}.userFee`, userFee)\n\n      const products = pack?.products\n      if (!isArray(products) || products.length === 0) {\n        c.fail(`${at}.products`, 'must be a non-empty array')\n        return\n      }\n      let sum = 0\n      products.forEach((product, i) => {\n        if (isRecord(product)) {\n          c.onlyFields(\n            `${at}.products[${i}]`,\n            product,\n            ['id', 'name', 'imageUrl', 'quantity', 'price', 'originalPrice'],\n            'a product'\n          )\n        }\n        c.nonEmptyString(`${at}.products[${i}].name`, product?.name)\n        c.positiveNumber(`${at}.products[${i}].quantity`, product?.quantity)\n        c.finiteNumber(`${at}.products[${i}].price`, product?.price)\n        sum += (product?.quantity ?? 0) * (product?.price ?? 0)\n      })\n      if (typeof pack.amount === 'number' && !amountsEqual(sum, pack.amount)) {\n        c.fail(\n          `${at}.amount`,\n          `must equal sum(products[].quantity * products[].price), which is ${sum}`\n        )\n      }\n      expected +=\n        (typeof pack.amount === 'number' ? pack.amount : 0) +\n        (typeof userFee === 'number' ? userFee : 0)\n    })\n\n    if (\n      typeof input.amount === 'number' &&\n      !amountsEqual(expected, input.amount)\n    ) {\n      c.fail(\n        'amount',\n        `must equal sum(packages[].amount) + sum(packages[].userFee) + options.shipping.feeAmount, which is ${expected}`\n      )\n    }\n  },\n  body: input => input\n}\n","import { type Guard, hasShape } from '../core/guard'\nimport { RESPONSE_FIELDS } from '../core/response-guards'\nimport { pathSegment } from '../core/validate'\nimport type { LinePayResponse } from '../types'\nimport type { OperationDefinition } from './define'\n\n/** Voids an authorization that has not been captured. */\nexport interface VoidInput {\n  transactionId: string\n}\n\nexport type VoidResponse = LinePayResponse\n\nconst isVoidResponse: Guard<VoidResponse> = hasShape(RESPONSE_FIELDS)\n\nexport const voidOperation: OperationDefinition<VoidInput, VoidResponse> = {\n  method: 'POST',\n  defaultTimeout: 20_000,\n  effect: 'settle',\n  response: isVoidResponse,\n  path: input =>\n    `/v4/payments/authorizations/${pathSegment('transactionId', input.transactionId)}/void`,\n  check(input, c) {\n    c.onlyFields('', input, ['transactionId'], 'a void')\n  },\n  body: () => ({}),\n  reconcileFields: ({ transactionId }) => ({ transactionId })\n}\n","import {\n  type CaptureInput,\n  captureOperation,\n  type CaptureResponse\n} from './capture'\nimport {\n  type CheckPaymentStatusInput,\n  checkPaymentStatusOperation,\n  type CheckPaymentStatusResponse\n} from './check-payment-status'\nimport {\n  type CheckRegKeyInput,\n  checkRegKeyOperation,\n  type CheckRegKeyResponse\n} from './check-regkey'\nimport {\n  type ConfirmInput,\n  confirmOperation,\n  type ConfirmResponse\n} from './confirm'\nimport type { OperationDefinition } from './define'\nimport {\n  type ExpireRegKeyInput,\n  expireRegKeyOperation,\n  type ExpireRegKeyResponse\n} from './expire-regkey'\nimport type { OperationName } from './names'\nimport {\n  type PayPreapprovedInput,\n  payPreapprovedOperation,\n  type PayPreapprovedResponse\n} from './pay-preapproved'\nimport {\n  type PaymentDetailsInput,\n  paymentDetailsOperation,\n  type PaymentDetailsResponse\n} from './payment-details'\nimport {\n  type RefundInput,\n  refundOperation,\n  type RefundResponse\n} from './refund'\nimport {\n  requestOperation,\n  type RequestPaymentInput,\n  type RequestPaymentResponse\n} from './request'\nimport { type VoidInput, voidOperation, type VoidResponse } from './void'\n\n/** Input and response type of every operation, keyed by operation name. */\nexport interface OperationTypes {\n  request: { input: RequestPaymentInput; output: RequestPaymentResponse }\n  confirm: { input: ConfirmInput; output: ConfirmResponse }\n  capture: { input: CaptureInput; output: CaptureResponse }\n  void: { input: VoidInput; output: VoidResponse }\n  refund: { input: RefundInput; output: RefundResponse }\n  paymentDetails: { input: PaymentDetailsInput; output: PaymentDetailsResponse }\n  checkPaymentStatus: {\n    input: CheckPaymentStatusInput\n    output: CheckPaymentStatusResponse\n  }\n  checkRegKey: { input: CheckRegKeyInput; output: CheckRegKeyResponse }\n  payPreapproved: { input: PayPreapprovedInput; output: PayPreapprovedResponse }\n  expireRegKey: { input: ExpireRegKeyInput; output: ExpireRegKeyResponse }\n}\n\nexport type OperationInput<K extends OperationName> = OperationTypes[K]['input']\nexport type OperationOutput<K extends OperationName> =\n  OperationTypes[K]['output']\n\n/** Union of every operation's input, tagged by name: narrow with `operation`. */\nexport type AnyOperationInput = {\n  [K in OperationName]: OperationInput<K>\n}[OperationName]\n\nexport const operations: {\n  [K in OperationName]: OperationDefinition<\n    OperationInput<K>,\n    OperationOutput<K>\n  >\n} = {\n  request: requestOperation,\n  confirm: confirmOperation,\n  capture: captureOperation,\n  void: voidOperation,\n  refund: refundOperation,\n  paymentDetails: paymentDetailsOperation,\n  checkPaymentStatus: checkPaymentStatusOperation,\n  checkRegKey: checkRegKeyOperation,\n  payPreapproved: payPreapprovedOperation,\n  expireRegKey: expireRegKeyOperation\n}\n\nexport type { CaptureInput, CaptureOptions, CaptureResponse } from './capture'\nexport type {\n  CheckPaymentStatusInput,\n  CheckPaymentStatusResponse\n} from './check-payment-status'\nexport type { CheckRegKeyInput, CheckRegKeyResponse } from './check-regkey'\nexport type { ConfirmInput, ConfirmResponse } from './confirm'\nexport type { ExpireRegKeyInput, ExpireRegKeyResponse } from './expire-regkey'\nexport type {\n  PayPreapprovedInput,\n  PayPreapprovedResponse\n} from './pay-preapproved'\nexport type {\n  PaymentDetailsInfo,\n  PaymentDetailsInput,\n  PaymentDetailsResponse,\n  PromotionEvent,\n  RefundEntry\n} from './payment-details'\nexport type { RefundInput, RefundResponse } from './refund'\nexport type {\n  AddFriend,\n  DisplayOptions,\n  ExtraOptions,\n  FamilyServiceOptions,\n  PaymentOptions,\n  RedirectUrls,\n  RedirectUrlsWithCallbacks,\n  RedirectUrlsWithoutCallbacks,\n  RequestPackage,\n  RequestPaymentInput,\n  RequestPaymentOptions,\n  RequestPaymentResponse,\n  ShippingOptions\n} from './request'\nexport type { VoidInput, VoidResponse } from './void'\n","import type { CallContext } from '../client-types'\nimport {\n  type AnyLinePayError,\n  type CallMeta,\n  isLinePayApiError,\n  isLinePayHttpError\n} from '../errors'\nimport { operations } from '../operations/index'\nimport type { OperationName } from '../operations/names'\n\n/** What of a call is needed to tell how it went. */\ntype Started = Pick<CallContext, 'operation' | 'startedAt'>\n\n/** How a call went up to now, from its start. */\nexport function callMeta(\n  ctx: Started,\n  attempts: number,\n  httpStatus?: number\n): CallMeta {\n  return {\n    operation: ctx.operation,\n    startedAt: ctx.startedAt,\n    durationMs: Date.now() - ctx.startedAt.getTime(),\n    attempts,\n    ...(httpStatus === undefined ? {} : { httpStatus })\n  }\n}\n\n/**\n * Attach what `reconcile` needs to an error: the operation, when the call started\n * and the identifying fields of the input. It is done here, before the middleware\n * see the error.\n */\nexport function attachContext<K extends OperationName>(\n  error: AnyLinePayError,\n  ctx: CallContext<K>,\n  channelId: string\n): void {\n  error.operation ??= ctx.operation\n  let fields = {}\n  try {\n    fields = operations[ctx.operation].reconcileFields?.(ctx.input) ?? {}\n  } catch {\n    // The input is malformed; there is nothing to look up.\n  }\n  error.context = {\n    ...fields,\n    operation: ctx.operation,\n    startedAt: ctx.startedAt,\n    channelId\n  }\n}\n\n/** The status of the response an error is the answer of LINE Pay to, if it is. */\nexport function statusOf(error: AnyLinePayError): number | undefined {\n  return isLinePayApiError(error) || isLinePayHttpError(error)\n    ? error.httpStatus\n    : undefined\n}\n\n/**\n * Attach how the call went to an error: the attempts so far, the time since it\n * began, and the status of the last response, which is the error's own when it is\n * the answer of LINE Pay.\n */\nexport function attachMeta(\n  error: AnyLinePayError,\n  ctx: Started,\n  attempts: number,\n  httpStatus: number | undefined = statusOf(error)\n): void {\n  error.meta = callMeta(ctx, attempts, httpStatus)\n}\n","import type {\n  AnyCallContext,\n  AnyResult,\n  CallContext,\n  Middleware\n} from '../client-types'\nimport { attachMeta, statusOf } from '../core/annotate'\nimport {\n  type AnyLinePayError,\n  isLinePayAbortError,\n  isLinePayError,\n  isLinePayNetworkError,\n  LinePayAbortError,\n  LinePayValidationError\n} from '../errors'\nimport { operations } from '../operations/index'\nimport type { OperationEffect, OperationName } from '../operations/names'\n\nexport interface RetryOptions {\n  /** Attempts in total, the first one included. Default 3. */\n  maxAttempts?: number\n  /** Start of the exponential backoff in milliseconds. Default 200. */\n  baseDelayMs?: number\n  /** Upper bound of one wait in milliseconds. Default 2000. */\n  maxDelayMs?: number\n  /** Replaces `Math.random`; for tests. */\n  random?: () => number\n  /** Replaces the timer; for tests. */\n  sleep?: (ms: number, signal?: AbortSignal) => Promise<void>\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n  return new Promise((resolve, reject) => {\n    if (signal?.aborted === true) {\n      reject(\n        new LinePayAbortError({\n          abortReason: signal.reason,\n          outcome: 'not-sent'\n        })\n      )\n      return\n    }\n    const onAbort = () => {\n      clearTimeout(timer)\n      reject(\n        new LinePayAbortError({\n          abortReason: signal?.reason,\n          outcome: 'not-sent'\n        })\n      )\n    }\n    const timer = setTimeout(() => {\n      signal?.removeEventListener('abort', onAbort)\n      resolve()\n    }, ms)\n    signal?.addEventListener('abort', onAbort, { once: true })\n  })\n}\n\nfunction positiveInteger(\n  value: number | undefined,\n  fallback: number,\n  path: string\n) {\n  if (value === undefined) return fallback\n  if (!Number.isInteger(value) || value < 1) {\n    throw new LinePayValidationError({\n      issues: [{ path, message: 'must be a positive integer' }],\n      subject: 'configuration'\n    })\n  }\n  return value\n}\n\n/**\n * A retry is safe in two cases only:\n *\n * - the request never left (`not-sent` network error), for every operation;\n * - the operation only reads, and what went wrong leaves its outcome unknown (a\n *   timeout, a broken connection, a server error); a read that LINE Pay refused\n *   would be refused again, and one the caller aborted is not repeated.\n *\n * An operation that moves money is never repeated after an unknown outcome: use\n * `reconcile` to find out what happened.\n */\nfunction canRetry(error: AnyLinePayError, ctx: AnyCallContext): boolean {\n  if (isLinePayAbortError(error)) return false\n  if (isLinePayNetworkError(error) && error.outcome === 'not-sent') return true\n  return effectOf(ctx) === 'read' && error.outcome === 'unknown'\n}\n\n/** What this call does. A call whose input cannot be read is not taken for a read. */\nfunction effectOf<K extends OperationName>(\n  ctx: CallContext<K>\n): OperationEffect {\n  const definition = operations[ctx.operation]\n  try {\n    return definition.effectOf?.(ctx.input) ?? definition.effect\n  } catch {\n    return 'create'\n  }\n}\n\n/**\n * The caller gave up while the middleware was waiting to try again. It is still\n * an abort, but what is known about the call is what its last attempt said: that\n * attempt's outcome, operation, context and last response, which a plain abort\n * does not carry.\n */\nfunction interrupted(\n  abort: unknown,\n  last: AnyLinePayError,\n  ctx: AnyCallContext,\n  attempts: number\n): unknown {\n  if (!isLinePayAbortError(abort)) return abort\n  const error = new LinePayAbortError({\n    abortReason: abort.abortReason,\n    outcome: last.outcome === 'not-sent' ? 'not-sent' : 'unknown',\n    operation: last.operation\n  })\n  error.context = last.context\n  attachMeta(error, ctx, attempts, statusOf(last))\n  return error\n}\n\nfunction withTotals(\n  result: AnyResult,\n  attempts: number,\n  ctx: AnyCallContext\n): AnyResult {\n  return {\n    ...result,\n    meta: {\n      ...result.meta,\n      attempts,\n      durationMs: Date.now() - ctx.startedAt.getTime()\n    }\n  }\n}\n\n/**\n * Repeat a call when that is provably safe, with capped exponential backoff and full\n * jitter. This is the default middleware of a client.\n */\nexport function retryWhenNotSent(options: RetryOptions = {}): Middleware {\n  const maxAttempts = positiveInteger(options.maxAttempts, 3, 'maxAttempts')\n  const baseDelayMs = positiveInteger(options.baseDelayMs, 200, 'baseDelayMs')\n  const maxDelayMs = positiveInteger(options.maxDelayMs, 2000, 'maxDelayMs')\n  const random = options.random ?? Math.random\n  const sleep = options.sleep ?? defaultSleep\n\n  return async (ctx, next) => {\n    for (let attempt = 1; ; attempt++) {\n      try {\n        const result = await next()\n        return attempt === 1 ? result : withTotals(result, attempt, ctx)\n      } catch (error) {\n        if (!isLinePayError(error)) throw error\n        if (attempt >= maxAttempts || !canRetry(error, ctx)) {\n          // The error is the last one: after a retry it says how many attempts\n          // were made. Without one, what a step further in said stands (like the\n          // meta of a result that was not repeated).\n          if (attempt > 1 || error.meta === undefined) {\n            attachMeta(error, ctx, attempt)\n          }\n          throw error\n        }\n        const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n        try {\n          await sleep(random() * ceiling, ctx.options.signal)\n        } catch (abort) {\n          throw interrupted(abort, error, ctx, attempt)\n        }\n      }\n    }\n  }\n}\n","import type { Middleware } from './client-types'\nimport { isArray } from './core/guard'\nimport { hasLosslessJson } from './core/json'\nimport { type FetchImpl } from './core/transport'\nimport { Checker } from './core/validate'\nimport { LinePayValidationError } from './errors'\nimport { retryWhenNotSent } from './middleware/retry-when-not-sent'\nimport { isOperationName, type OperationName } from './operations/names'\n\nexport type LinePayEnv = 'sandbox' | 'production'\n\nexport const BASE_URLS: Readonly<Record<LinePayEnv, string>> = {\n  sandbox: 'https://sandbox-api-pay.line.me',\n  production: 'https://api-pay.line.me'\n}\n\n/** `AbortSignal.timeout` and timers cannot take more than 2^31 - 1 milliseconds. */\nexport const MAX_TIMEOUT_MS = 2_147_483_647\n\n/** What is wrong with a timeout that `isValidTimeout` refuses. */\nexport const TIMEOUT_MESSAGE = `must be a number of milliseconds between 1 and ${MAX_TIMEOUT_MS}`\n\nexport function isValidTimeout(value: unknown): value is number {\n  return (\n    typeof value === 'number' &&\n    Number.isFinite(value) &&\n    value >= 1 &&\n    value <= MAX_TIMEOUT_MS\n  )\n}\n\nexport interface LinePayConfig {\n  /** The channel ID of the merchant (Merchant Center, \"Manage link key\"). */\n  channelId: string\n  /** The channel secret key. Keep it on the server. */\n  channelSecretKey: string\n  /** `sandbox` for testing, `production` for real payments. */\n  env: LinePayEnv\n  /**\n   * Time limit of one attempt in milliseconds. It applies to every operation\n   * without a more specific setting. Order of precedence: the `timeout` of the\n   * call, `timeouts[operation]`, `timeout`, the default of the operation.\n   */\n  timeout?: number\n  /** Time limits per operation. */\n  timeouts?: Partial<Record<OperationName, number>>\n  /** Replaces the global `fetch`: for a proxy, a fixed IP address, or tests. */\n  fetch?: typeof fetch\n  /**\n   * Replaces the host that `env` selects, for example to go through a proxy with a\n   * fixed IP address. It must use https, except for localhost.\n   */\n  baseUrl?: string\n  /**\n   * Sent as `X-LINE-MerchantDeviceProfileId`. Give it together with\n   * `merchantDeviceType`: one without the other is refused.\n   */\n  merchantDeviceProfileId?: string\n  /**\n   * Sent as `X-LINE-MerchantDeviceType`. Give it together with\n   * `merchantDeviceProfileId`: one without the other is refused.\n   */\n  merchantDeviceType?: string\n  /**\n   * Middleware of the client, outermost first. The default is\n   * `[retryWhenNotSent()]`; pass `[]` for none.\n   */\n  middleware?: readonly Middleware[]\n  /**\n   * Check the input before sending it, including that amounts add up. `true` by\n   * default. The checks of path parameters (`transactionId`, `regKey`) cannot be\n   * turned off.\n   */\n  validate?: boolean\n}\n\nexport interface ResolvedConfig {\n  readonly channelId: string\n  readonly channelSecretKey: string\n  readonly baseUrl: string\n  readonly timeout: number | undefined\n  readonly timeouts: Readonly<Partial<Record<OperationName, number>>>\n  readonly fetch: FetchImpl\n  readonly merchantDeviceProfileId: string | undefined\n  readonly merchantDeviceType: string | undefined\n  readonly validate: boolean\n  readonly middleware: readonly Middleware[]\n}\n\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])\n\n/** Printable ASCII, without a space at either end: safe as the value of a header. */\nconst HEADER_VALUE = /^[\\x21-\\x7e](?:[\\x20-\\x7e]*[\\x21-\\x7e])?$/\nconst HEADER_VALUE_MESSAGE =\n  'must be printable ASCII without spaces at either end'\n/** A line break, a tab, NUL or DEL anywhere in the text. */\nconst hasControlCharacter = (text: string): boolean =>\n  Array.from(text).some(character => {\n    const code = character.codePointAt(0) ?? 0\n    return code < 0x20 || code === 0x7f\n  })\n\nfunction resolveBaseUrl(\n  baseUrl: unknown,\n  env: LinePayEnv | undefined,\n  checker: Checker\n): string {\n  if (baseUrl === undefined) return env === undefined ? '' : BASE_URLS[env]\n  if (typeof baseUrl !== 'string') {\n    checker.fail('baseUrl', 'must be a string')\n    return ''\n  }\n  let url: URL\n  try {\n    url = new URL(baseUrl)\n  } catch {\n    checker.fail('baseUrl', 'must be an absolute URL')\n    return ''\n  }\n  if (\n    url.protocol !== 'https:' &&\n    !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))\n  ) {\n    checker.fail(\n      'baseUrl',\n      'must use https (http is only allowed for localhost)'\n    )\n  }\n  if (url.search !== '' || url.hash !== '') {\n    checker.fail('baseUrl', 'must not contain a query or a fragment')\n  }\n  if (url.username !== '' || url.password !== '') {\n    // They would be dropped silently, and the proxy would see no credentials.\n    checker.fail('baseUrl', 'must not contain a user name or a password')\n  }\n  return `${url.origin}${withoutTrailingSlashes(url.pathname)}`\n}\n\n/** A loop, not a regular expression: `/\\/+$/` takes quadratic time on a long run of slashes. */\nfunction withoutTrailingSlashes(path: string): string {\n  let end = path.length\n  while (end > 0 && path.charCodeAt(end - 1) === 47) end--\n  return path.slice(0, end)\n}\n\n/** Validate a configuration and fill in the defaults. */\nexport function resolveConfig(given: LinePayConfig): ResolvedConfig {\n  if (typeof given !== 'object' || given === null) {\n    throw new LinePayValidationError({\n      issues: [{ path: 'config', message: 'must be an object' }],\n      subject: 'configuration'\n    })\n  }\n  if (!hasLosslessJson()) {\n    throw new LinePayValidationError({\n      issues: [\n        {\n          path: 'runtime',\n          message:\n            'JSON.parse must hand the source text of a number to its reviver (V8 11.4, Node.js 22 or later), or the 19-digit transaction IDs of LINE Pay would be rounded'\n        }\n      ],\n      subject: 'configuration'\n    })\n  }\n  // Only what was put on the object itself is a setting. A property that\n  // Object.prototype has gained through a bug somewhere else (prototype\n  // pollution) is not: a polluted `baseUrl` would send every signed request to\n  // another host.\n  const config: LinePayConfig = { ...given }\n  Object.setPrototypeOf(config, null)\n\n  const checker = new Checker()\n  checker.nonEmptyString('channelId', config.channelId)\n  checker.nonEmptyString('channelSecretKey', config.channelSecretKey)\n  // The channel ID goes into a header: anything but printable ASCII would make\n  // `fetch` throw before it sends, and a line break could inject a header.\n  if (typeof config.channelId === 'string' && config.channelId !== '') {\n    if (!HEADER_VALUE.test(config.channelId)) {\n      checker.fail('channelId', HEADER_VALUE_MESSAGE)\n    }\n  }\n  // The secret is not sent, but a newline or a space that came with it from an\n  // environment variable or a file makes every signature wrong.\n  if (\n    typeof config.channelSecretKey === 'string' &&\n    config.channelSecretKey !== '' &&\n    (hasControlCharacter(config.channelSecretKey) ||\n      config.channelSecretKey !== config.channelSecretKey.trim())\n  ) {\n    checker.fail(\n      'channelSecretKey',\n      'must not contain control characters or spaces at either end (is there a line break from an environment variable or a file?)'\n    )\n  }\n\n  const requestedEnv: unknown = config.env\n  let env: LinePayEnv | undefined\n  if (requestedEnv === 'sandbox' || requestedEnv === 'production') {\n    env = requestedEnv\n  } else if (requestedEnv === 'development') {\n    checker.fail('env', \"'development' was renamed to 'sandbox'\")\n  } else {\n    checker.fail('env', \"must be 'sandbox' or 'production'\")\n  }\n\n  if (config.timeout !== undefined && !isValidTimeout(config.timeout)) {\n    checker.fail('timeout', TIMEOUT_MESSAGE)\n  }\n\n  const timeouts: Partial<Record<OperationName, number>> = {}\n  if (config.timeouts !== undefined) {\n    if (typeof config.timeouts !== 'object' || config.timeouts === null) {\n      checker.fail('timeouts', 'must be an object')\n    } else {\n      for (const [name, value] of Object.entries(config.timeouts)) {\n        if (!isOperationName(name)) {\n          checker.fail(`timeouts.${name}`, 'is not an operation name')\n        } else if (!isValidTimeout(value)) {\n          checker.fail(`timeouts.${name}`, TIMEOUT_MESSAGE)\n        } else {\n          timeouts[name] = value\n        }\n      }\n    }\n  }\n\n  if (config.fetch !== undefined && typeof config.fetch !== 'function') {\n    checker.fail('fetch', 'must be a function')\n  }\n  if (config.merchantDeviceProfileId !== undefined) {\n    if (\n      typeof config.merchantDeviceProfileId !== 'string' ||\n      config.merchantDeviceProfileId.length === 0\n    ) {\n      checker.fail('merchantDeviceProfileId', 'must be a non-empty string')\n    } else if (!HEADER_VALUE.test(config.merchantDeviceProfileId)) {\n      checker.fail('merchantDeviceProfileId', HEADER_VALUE_MESSAGE)\n    }\n  }\n  if (config.merchantDeviceType !== undefined) {\n    if (\n      typeof config.merchantDeviceType !== 'string' ||\n      config.merchantDeviceType.length === 0\n    ) {\n      checker.fail('merchantDeviceType', 'must be a non-empty string')\n    } else if (!HEADER_VALUE.test(config.merchantDeviceType)) {\n      checker.fail('merchantDeviceType', HEADER_VALUE_MESSAGE)\n    }\n  }\n  // LINE Pay V4 requires the two optional device headers together.\n  if (\n    typeof config.merchantDeviceProfileId === 'string' &&\n    HEADER_VALUE.test(config.merchantDeviceProfileId) &&\n    config.merchantDeviceType === undefined\n  ) {\n    checker.fail(\n      'merchantDeviceType',\n      'is required with merchantDeviceProfileId'\n    )\n  }\n  if (\n    typeof config.merchantDeviceType === 'string' &&\n    HEADER_VALUE.test(config.merchantDeviceType) &&\n    config.merchantDeviceProfileId === undefined\n  ) {\n    checker.fail(\n      'merchantDeviceProfileId',\n      'is required with merchantDeviceType'\n    )\n  }\n  if (config.validate !== undefined && typeof config.validate !== 'boolean') {\n    checker.fail('validate', 'must be a boolean')\n  }\n  if (\n    config.middleware !== undefined &&\n    (!isArray(config.middleware) ||\n      config.middleware.some((m: unknown) => typeof m !== 'function'))\n  ) {\n    checker.fail('middleware', 'must be an array of functions')\n  }\n\n  const baseUrl = resolveBaseUrl(config.baseUrl, env, checker)\n  checker.throwIfInvalid({ subject: 'configuration' })\n\n  const userFetch = config.fetch\n  const middleware: readonly Middleware[] = config.middleware ?? [\n    retryWhenNotSent()\n  ]\n  return {\n    channelId: config.channelId,\n    channelSecretKey: config.channelSecretKey,\n    baseUrl,\n    timeout: config.timeout,\n    timeouts: Object.freeze(timeouts),\n    // Read the global at call time, so that tests can replace it.\n    fetch: userFetch ?? ((input, init) => globalThis.fetch(input, init)),\n    merchantDeviceProfileId: config.merchantDeviceProfileId,\n    merchantDeviceType: config.merchantDeviceType,\n    validate: config.validate ?? true,\n    middleware: Object.freeze<Middleware[]>([...middleware])\n  }\n}\n","import { LinePayValidationError } from '../errors'\nimport { isArray } from './guard'\n\nexport type QueryScalar = string | number | boolean\nexport type QueryValue = QueryScalar | readonly QueryScalar[] | undefined\nexport type QueryParams = Record<string, QueryValue>\n\n/** `encodeURIComponent` throws on a lone surrogate; that is an input problem. */\nfunction encode(path: string, text: string): string {\n  try {\n    return encodeURIComponent(text)\n  } catch {\n    throw new LinePayValidationError({\n      issues: [\n        {\n          path,\n          message:\n            'must be well-formed text (it holds half of a surrogate pair)'\n        }\n      ]\n    })\n  }\n}\n\n/**\n * Build the query string (without the leading `?`). Arrays use repeated keys,\n * `a=1&a=2`, and `undefined` values are skipped.\n *\n * V4 sandbox accepted both repeated keys and comma-separated values when\n * querying multiple transaction or order IDs. This SDK uses repeated keys,\n * and the signature covers the exact query string being sent.\n */\nexport function buildQuery(params: QueryParams): string {\n  const parts: string[] = []\n  for (const [key, value] of Object.entries(params)) {\n    if (value === undefined) continue\n    // What a caller who is not bound by types passes is turned into text as it is.\n    const values: readonly unknown[] = isArray(value) ? value : [value]\n    for (const item of values) {\n      parts.push(`${encode(key, key)}=${encode(key, String(item))}`)\n    }\n  }\n  return parts.join('&')\n}\n","import {\n  type LinePayApiBody,\n  LinePayApiError,\n  LinePayHttpError\n} from '../errors'\nimport {\n  classifyReturnCode,\n  isReturnCode,\n  isStatusReturnCode,\n  SUCCESS_RETURN_CODE\n} from '../errors/return-codes'\nimport { isRecord } from './guard'\nimport { parseLossless } from './json'\nimport type { TransportResponse } from './transport'\n\nconst BODY_TEXT_LIMIT = 2048\n\n/**\n * A proxy can emit any non-2xx status after forwarding the request to LINE Pay.\n * Even 400, 408 or 429 is not proof that a money-moving call did not happen.\n * LINE Pay documents 200 responses with application-level return codes.\n */\nfunction truncate(text: string): string {\n  return text.length > BODY_TEXT_LIMIT ? text.slice(0, BODY_TEXT_LIMIT) : text\n}\n\nfunction tryParse(text: string): { ok: true; value: unknown } | { ok: false } {\n  try {\n    return { ok: true, value: parseLossless(text) }\n  } catch {\n    return { ok: false }\n  }\n}\n\n/**\n * What a LINE Pay answer has for certain: a return code, four digits. The message\n * may be missing, or `null`: it is never worth losing the code over (a duplicate\n * code must lead to a lookup whatever else the answer lacks). A body with another\n * kind of code is not an answer of LINE Pay, and is not read as a refusal.\n */\ninterface Envelope {\n  returnCode: string\n  returnMessage?: string | null\n  [key: string]: unknown\n}\n\nfunction isEnvelope(value: unknown): value is Envelope {\n  if (!isRecord(value)) return false\n  const { returnCode, returnMessage } = value\n  return (\n    isReturnCode(returnCode) &&\n    (returnMessage === undefined ||\n      returnMessage === null ||\n      typeof returnMessage === 'string')\n  )\n}\n\n/**\n * Turn an HTTP response into a LINE Pay response body, or throw.\n *\n * - non-2xx: an error with `outcome: 'unknown'`, even for 4xx, because a\n *   gateway may already have forwarded a money-moving request to LINE Pay.\n *   A valid failing `returnCode` remains available on `LinePayApiError`\n * - 2xx that is not a LINE Pay response (a proxy page, an empty body):\n *   `LinePayHttpError` with `unknown`, because it may not even come from LINE Pay\n * - 2xx with a failing `returnCode`: `LinePayApiError`\n * - 2xx with a status code (`0xxx` other than `0000`): returned only for an\n *   operation that defines such statuses; for any other it is an\n *   `LinePayApiError` with `unknown`, because it may mean anything\n */\nexport function interpretResponse(\n  response: TransportResponse,\n  options: { statusCodes?: boolean } = {}\n): {\n  body: LinePayApiBody\n  httpStatus: number\n} {\n  const { status, text } = response\n  const parsed = tryParse(text)\n\n  if (status < 200 || status > 299) {\n    // LINE Pay says what failed even with a status that is not 200. Keep the\n    // return code: a duplicate must still lead to a lookup.\n    if (\n      parsed.ok &&\n      isEnvelope(parsed.value) &&\n      parsed.value.returnCode !== SUCCESS_RETURN_CODE &&\n      !isStatusReturnCode(parsed.value.returnCode)\n    ) {\n      const body: LinePayApiBody = {\n        ...parsed.value,\n        returnMessage: parsed.value.returnMessage ?? ''\n      }\n      const category = classifyReturnCode(body.returnCode)\n      throw new LinePayApiError({\n        body,\n        httpStatus: status,\n        category,\n        outcome: 'unknown'\n      })\n    }\n    throw new LinePayHttpError({\n      httpStatus: status,\n      reason: 'http-status',\n      outcome: 'unknown',\n      body: parsed.ok ? parsed.value : undefined,\n      bodyText: truncate(text)\n    })\n  }\n\n  if (!parsed.ok || !isEnvelope(parsed.value)) {\n    throw new LinePayHttpError({\n      httpStatus: status,\n      reason: 'invalid-response',\n      outcome: 'unknown',\n      body: parsed.ok ? parsed.value : undefined,\n      bodyText: truncate(text)\n    })\n  }\n\n  const body: LinePayApiBody = {\n    ...parsed.value,\n    returnMessage: parsed.value.returnMessage ?? ''\n  }\n\n  if (body.returnCode === SUCCESS_RETURN_CODE) {\n    return { body, httpStatus: status }\n  }\n  if (isStatusReturnCode(body.returnCode)) {\n    if (options.statusCodes === true) return { body, httpStatus: status }\n    // A status the operation does not define. LINE Pay answered, but it did not\n    // say what became of the call, so it is not a success and not a refusal.\n    throw new LinePayApiError({\n      body,\n      httpStatus: status,\n      category: 'unclassified',\n      outcome: 'unknown'\n    })\n  }\n  throw new LinePayApiError({ body, httpStatus: status })\n}\n","/**\n * LINE Pay request signature:\n *\n *   Base64( HMAC-SHA256( key = secret, message = secret + path + payload + nonce ) )\n *\n * - `path` is the API path without host and query, for example `/v4/payments/request`.\n * - `payload` is the query string (GET, without `?`) or the JSON body (POST),\n *   exactly as it is sent.\n *\n * Uses WebCrypto, so it works on Node.js, Bun, Deno and edge runtimes alike.\n */\nexport type Signer = (\n  path: string,\n  payload: string,\n  nonce: string\n) => Promise<string>\n\nconst encoder = new TextEncoder()\n\nfunction toBase64(bytes: Uint8Array): string {\n  let binary = ''\n  for (const byte of bytes) binary += String.fromCharCode(byte)\n  return btoa(binary)\n}\n\nexport function createSigner(channelSecretKey: string): Signer {\n  // Import the key once per client, on the first signature.\n  let cryptoKey: ReturnType<typeof crypto.subtle.importKey> | undefined\n\n  const getKey = (): ReturnType<typeof crypto.subtle.importKey> => {\n    if (cryptoKey === undefined) {\n      const pending = crypto.subtle.importKey(\n        'raw',\n        encoder.encode(channelSecretKey),\n        { name: 'HMAC', hash: 'SHA-256' },\n        false,\n        ['sign']\n      )\n      // Do not cache a failure.\n      pending.catch(() => {\n        cryptoKey = undefined\n      })\n      cryptoKey = pending\n    }\n    return cryptoKey\n  }\n\n  return async (path, payload, nonce) => {\n    const key = await getKey()\n    const message = encoder.encode(channelSecretKey + path + payload + nonce)\n    const mac = await crypto.subtle.sign('HMAC', key, message)\n    return toBase64(new Uint8Array(mac))\n  }\n}\n\nexport interface AuthHeaderInput {\n  readonly channelId: string\n  readonly nonce: string\n  readonly signature: string\n  readonly merchantDeviceProfileId?: string | undefined\n  readonly merchantDeviceType?: string | undefined\n}\n\nexport function authHeaders(input: AuthHeaderInput): Record<string, string> {\n  const headers: Record<string, string> = {\n    'Content-Type': 'application/json',\n    'X-LINE-ChannelId': input.channelId,\n    'X-LINE-Authorization-Nonce': input.nonce,\n    'X-LINE-Authorization': input.signature\n  }\n  if (input.merchantDeviceProfileId !== undefined) {\n    headers['X-LINE-MerchantDeviceProfileId'] = input.merchantDeviceProfileId\n  }\n  if (input.merchantDeviceType !== undefined) {\n    headers['X-LINE-MerchantDeviceType'] = input.merchantDeviceType\n  }\n  return headers\n}\n","import type { AnyCallContext, CallContext, ResultOf } from '../client-types'\nimport type { ResolvedConfig } from '../config'\nimport {\n  isLinePayError,\n  isLinePayValidationError,\n  LinePayHttpError,\n  LinePayValidationError\n} from '../errors'\nimport { operations } from '../operations/index'\nimport type { OperationName } from '../operations/names'\nimport { attachContext, attachMeta, callMeta } from './annotate'\nimport type { Terminal } from './pipeline'\nimport { buildQuery } from './query'\nimport { interpretResponse } from './response'\nimport { authHeaders, createSigner } from './sign'\nimport { sendRequest } from './transport'\nimport { Checker } from './validate'\n\n/** The JSON of a body. What cannot be written as JSON is an input problem. */\nfunction stringify(value: unknown): string {\n  try {\n    return JSON.stringify(value)\n  } catch (cause) {\n    throw new LinePayValidationError({\n      issues: [\n        {\n          path: 'input',\n          message:\n            'cannot be written as JSON (a BigInt, or a value that refers to itself)'\n        }\n      ],\n      cause\n    })\n  }\n}\n\n/**\n * A path parameter is checked without knowing which operation it is for. What is\n * refused is refused for the operation that was called, like every other problem\n * with its input.\n */\nfunction refusedFor(error: unknown, operation: OperationName): unknown {\n  return isLinePayValidationError(error)\n    ? new LinePayValidationError({\n        issues: error.issues,\n        operation,\n        cause: error.cause\n      })\n    : error\n}\n\n/** The last step of every call: validate, sign, send, interpret. */\nexport function createExecutor(config: ResolvedConfig): Terminal {\n  const sign = createSigner(config.channelSecretKey)\n\n  const execute = async <K extends OperationName>(\n    ctx: CallContext<K>\n  ): Promise<ResultOf<K>> => {\n    const definition = operations[ctx.operation]\n    const { input } = ctx\n    if (typeof input !== 'object' || input === null) {\n      throw new LinePayValidationError({\n        issues: [{ path: 'input', message: 'must be an object' }],\n        operation: ctx.operation\n      })\n    }\n\n    // Path parameters and the rules about what a request means are always\n    // checked; the business rules can be switched off.\n    let path: string\n    try {\n      path = definition.path(input)\n    } catch (error) {\n      throw refusedFor(error, ctx.operation)\n    }\n    const checker = new Checker()\n    definition.invariants?.(input, checker)\n    if (config.validate) definition.check?.(input, checker)\n    checker.throwIfInvalid({ operation: ctx.operation })\n\n    // The signature covers exactly what is sent. The query is signed the way the\n    // URL parser leaves it, and that URL is what goes to `fetch`: the parser\n    // rewrites a few characters (a quote becomes %27), and a signature made from\n    // the text before it would not match the request.\n    const target = new URL(config.baseUrl + path)\n    let payload: string\n    let body: string | undefined\n    if (definition.method === 'GET') {\n      const query = buildQuery(definition.query(input))\n      if (query !== '') target.search = query\n      payload = target.search.slice(1)\n    } else {\n      payload = stringify(definition.body(input))\n      body = payload\n    }\n\n    const nonce = crypto.randomUUID()\n    const signature = await sign(path, payload, nonce)\n\n    const response = await sendRequest({\n      fetch: config.fetch,\n      method: definition.method,\n      url: target.href,\n      headers: authHeaders({\n        channelId: config.channelId,\n        nonce,\n        signature,\n        merchantDeviceProfileId: config.merchantDeviceProfileId,\n        merchantDeviceType: config.merchantDeviceType\n      }),\n      body,\n      timeoutMs:\n        ctx.options.timeout ??\n        config.timeouts[ctx.operation] ??\n        config.timeout ??\n        definition.defaultTimeout,\n      signal: ctx.options.signal\n    })\n\n    const { body: received, httpStatus } = interpretResponse(response, {\n      statusCodes: definition.statusCodes === true\n    })\n    // The type of the response is what this check found, not what was hoped for.\n    // (It is checked as `unknown` so that the compiler narrows it to the type of\n    // the operation.)\n    const parsed: unknown = received\n    if (!definition.response(parsed)) {\n      throw new LinePayHttpError({\n        httpStatus,\n        reason: 'unexpected-shape',\n        outcome: 'unknown',\n        body: received\n      })\n    }\n    return { body: parsed, meta: callMeta(ctx, 1, httpStatus) }\n  }\n\n  return async (ctx: AnyCallContext) => {\n    try {\n      return await execute(ctx)\n    } catch (error) {\n      if (isLinePayError(error)) {\n        attachContext(error, ctx, config.channelId)\n        attachMeta(error, ctx, 1)\n      }\n      throw error\n    }\n  }\n}\n","import type {\n  AnyCallContext,\n  AnyResult,\n  CallContext,\n  Middleware,\n  ResultOf\n} from '../client-types'\nimport { LinePayMiddlewareError } from '../errors'\nimport { operations } from '../operations/index'\nimport type { OperationName } from '../operations/names'\nimport { attachContext } from './annotate'\n\nexport type Terminal = (ctx: AnyCallContext) => Promise<AnyResult>\n\n/**\n * Chain the middleware around the terminal step. Each `next()` starts the inner\n * part of the chain again, so a middleware may call it several times.\n */\nexport function compose(\n  middleware: readonly Middleware[],\n  terminal: Terminal\n): Terminal {\n  return ctx => {\n    const run = async (index: number): Promise<AnyResult> => {\n      const current = middleware[index]\n      return current === undefined\n        ? terminal(ctx)\n        : current(ctx, () => run(index + 1))\n    }\n    return run(0)\n  }\n}\n\n/**\n * The result of the operation that was called. A middleware may hand back any\n * result the type of `AnyResult` allows, so the body is checked once more against\n * what the operation promises: the caller gets the type it was told it gets, or an\n * error that says a middleware broke the rule. The request may have been sent and\n * taken effect by then, so the error carries the context of the call.\n */\nexport function resultOf<K extends OperationName>(\n  ctx: CallContext<K>,\n  result: AnyResult,\n  channelId: string\n): ResultOf<K> {\n  const body: unknown = result.body\n  if (!operations[ctx.operation].response(body)) {\n    const error = new LinePayMiddlewareError({ operation: ctx.operation })\n    attachContext(error, ctx, channelId)\n    throw error\n  }\n  return { body, meta: result.meta }\n}\n","import { LinePayValidationError } from '../errors'\nimport type { OperationName } from '../operations/names'\nimport { type Guard, isArray } from './guard'\n\n/**\n * Where a copy would leave something out, or fail, and what it is. The path is\n * relative to the input, like the path of every other problem with an input; the\n * input itself is the empty path.\n */\ninterface Loss {\n  readonly path: string\n  readonly message: string\n  readonly cause?: unknown\n}\n\nconst NOT_PLAIN_OBJECT =\n  'must be a plain object (an object literal, or the result of JSON.parse), not an instance of a class or an object with a prototype of its own: what is kept there is not copied, and so not sent'\nconst NOT_PLAIN_ARRAY = 'must be a plain array, not a subclass of Array'\nconst NOT_ENUMERABLE =\n  'is not enumerable, so a copy leaves it out and it would not be sent'\nconst NOT_A_VALUE =\n  'is a getter or a setter: give the value itself, so that what is sent is what the call was given'\nconst NOT_COPYABLE =\n  'must be plain data: strings, numbers, booleans, and arrays and objects of them'\n\nconst child = (path: string, key: string) =>\n  path === '' ? key : `${path}.${key}`\n\n/** An object made with `{}` or `JSON.parse`, or one with no prototype at all. */\nexport const isPlainObject: Guard<Record<string, unknown>> = (\n  value\n): value is Record<string, unknown> => {\n  if (typeof value !== 'object' || value === null || isArray(value)) {\n    return false\n  }\n  const prototype: unknown = Object.getPrototypeOf(value)\n  return prototype === Object.prototype || prototype === null\n}\n\n/**\n * The first place in `value` where a copy (`structuredClone`) would not carry\n * what the caller sees. A copy takes the own, enumerable, plain properties and\n * nothing else, and an input is read by the name of a field: a field that a\n * class keeps in a getter, behind a `#private` name, on a prototype or out of the\n * enumeration is missing from the copy, and for an operation that reads \"no\n * `refundAmount`\" as a full refund that is not a detail.\n */\nfunction lossIn(\n  value: unknown,\n  path: string,\n  seen: Set<object>\n): Loss | undefined {\n  if (typeof value !== 'object' || value === null) return undefined\n  if (seen.has(value)) return undefined\n  seen.add(value)\n\n  if (isArray(value)) {\n    if (Object.getPrototypeOf(value) !== Array.prototype) {\n      return { path, message: NOT_PLAIN_ARRAY }\n    }\n    for (let index = 0; index < value.length; index++) {\n      const loss = lossIn(value[index], `${path}[${index}]`, seen)\n      if (loss !== undefined) return loss\n    }\n    return undefined\n  }\n  if (!isPlainObject(value)) return { path, message: NOT_PLAIN_OBJECT }\n  for (const key of Reflect.ownKeys(value)) {\n    // No field of an operation is named by a symbol: a copy may leave it out.\n    if (typeof key === 'symbol') continue\n    const descriptor = Object.getOwnPropertyDescriptor(value, key)\n    if (descriptor === undefined) continue\n    if (!descriptor.enumerable) {\n      return { path: child(path, key), message: NOT_ENUMERABLE }\n    }\n    if (!('value' in descriptor)) {\n      return { path: child(path, key), message: NOT_A_VALUE }\n    }\n    const loss = lossIn(descriptor.value, child(path, key), seen)\n    if (loss !== undefined) return loss\n  }\n  return undefined\n}\n\nfunction findLoss(input: object): Loss | undefined {\n  try {\n    return lossIn(input, '', new Set())\n  } catch (cause) {\n    // Nested too deep for the walk, or an object (a Proxy) that throws when asked.\n    return { path: '', message: NOT_COPYABLE, cause }\n  }\n}\n\n/**\n * The input as it is at the moment of the call. The call reads it again for every\n * attempt of a retry and, if it fails, for the context that `reconcile` works\n * from; a caller that reuses its object for the next call in the meantime must\n * not change which payment either of them is about.\n *\n * Only plain data is copied. What a copy would leave out is refused, with the\n * place where it is, instead of being left out: the money moves by what the copy\n * says.\n */\nexport function snapshotOf<T>(input: T, operation: OperationName): T {\n  if (typeof input !== 'object' || input === null) return input\n  const loss = findLoss(input)\n  if (loss !== undefined) {\n    throw new LinePayValidationError({\n      issues: [\n        {\n          path: loss.path === '' ? 'input' : loss.path,\n          message: loss.message\n        }\n      ],\n      operation,\n      cause: loss.cause\n    })\n  }\n  try {\n    return structuredClone(input)\n  } catch (cause) {\n    throw new LinePayValidationError({\n      issues: [{ path: 'input', message: NOT_COPYABLE }],\n      operation,\n      cause\n    })\n  }\n}\n","/**\n * A date and a time of the day, and the offset from UTC (the year may be the\n * expanded one, `+002026`, that ISO 8601 and ECMAScript have). Nothing else is\n * read as a timestamp: `Date.parse` takes many more shapes than ISO 8601\n * (`10-27-2026` ends in what looks like an offset), and reads those in the local\n * zone.\n */\nconst ISO_WITH_OFFSET =\n  /^(?:\\d{4}|[+-]\\d{6})-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})$/i\n\n/**\n * The instant of an ISO 8601 timestamp, or `NaN` when it has no UTC offset: a\n * timestamp without one is read in the local zone of this process, which may not\n * be the one LINE Pay meant. Such a time is not trusted.\n */\n// V4 sandbox payment and refund timestamps were observed as UTC strings\n// ending in Z; keep rejecting ambiguous timestamps without an offset.\nexport function instantOf(timestamp: string): number {\n  return ISO_WITH_OFFSET.test(timestamp) ? Date.parse(timestamp) : Number.NaN\n}\n\n/**\n * Milliseconds since the epoch of 2001-09-09. Any moment in the life of this\n * library is later; an earlier one is most likely a count of seconds taken for\n * milliseconds, which would put the call in January 1970 and every payment since\n * then after it. A `Date` made from seconds (`new Date(1761523200)`), a `Date`\n * made from nothing (`new Date(null)`) and a timestamp of 1970 are the same\n * mistake in other forms.\n */\nconst EARLIEST_EPOCH_MS = 1e12\n\n/**\n * A moment given as a `Date`, as an ISO 8601 string with a UTC offset, or as\n * milliseconds since the epoch. What comes back from JSON (a database row, a\n * queue message) is a string or a number, so those work as they are. A moment\n * that is too early to be the time of a call is refused, in whatever form it is\n * given.\n */\nexport function toDate(value: unknown): Date | undefined {\n  let ms: number\n  if (value instanceof Date) ms = value.getTime()\n  else if (typeof value === 'string') ms = instantOf(value)\n  else if (typeof value === 'number') ms = value\n  else return undefined\n  if (ms < EARLIEST_EPOCH_MS) return undefined\n  // What is left is not a moment if it is NaN, an Infinity, or beyond what a Date\n  // reaches (8.64e15 milliseconds either way): the Date made from it is invalid.\n  const date = new Date(ms)\n  return Number.isNaN(date.getTime()) ? undefined : date\n}\n\n/**\n * Seconds since the epoch, rounded down. LINE Pay may report a time without a\n * fraction, so a call and the refund it made are compared by the second.\n */\nexport const wholeSeconds = (ms: number): number => Math.floor(ms / 1000)\n","import type {\n  AppliedResult,\n  CallOptions,\n  LinePayClient,\n  ReconcileResult\n} from '../client-types'\nimport { instantOf, wholeSeconds } from '../core/time'\nimport { amountsEqual } from '../core/validate'\nimport {\n  isLinePayApiError,\n  isLinePayError,\n  type ReconcileContext\n} from '../errors'\nimport type {\n  ConfirmResponse,\n  OperationOutput,\n  PaymentDetailsInfo,\n  PaymentDetailsInput,\n  RefundEntry\n} from '../operations'\nimport type { ReconcilableOperation } from '../operations/names'\nimport type {\n  PayInfo,\n  PaymentProvider,\n  ResponsePackage,\n  SelectedShipping\n} from '../types'\n\nconst RECOVERED = 'Recovered from the payment details by reconcile'\n\nconst UNREADABLE =\n  'The payment details are not in the shape the API promises, so nothing can be concluded from them.'\n\nexport interface RuleEnv {\n  readonly client: LinePayClient\n  readonly context: ReconcileContext\n  readonly options: CallOptions | undefined\n  /** LINE Pay refused this very call as a duplicate. */\n  readonly duplicate: boolean\n}\n\n/**\n * A payment of the payment details, with every field the rules read. The details\n * come from the network, and a rule that read a missing field would answer with a\n * `TypeError` instead of an answer: an entry that lacks one is not read at all.\n */\ninterface Payment {\n  readonly transactionId: string\n  readonly orderId: string\n  /** V4 omits payStatus in ordinary payment-details responses. */\n  readonly payStatus: string | undefined\n  readonly currency: string\n  readonly payInfo: PayInfo[]\n  readonly packages: ResponsePackage[]\n  readonly refundList: RefundEntry[]\n  readonly transactionDate: string | undefined\n  readonly authorizationExpireDate: string | undefined\n  readonly shipping: SelectedShipping | undefined\n  readonly paymentProvider: PaymentProvider | undefined\n}\n\n/** One entry of the payment details. */\ntype Entry =\n  | { readonly kind: 'payment'; readonly payment: Payment }\n  | {\n      readonly kind: 'other'\n      readonly transactionId: string\n      readonly orderId: string | undefined\n      readonly transactionType: string\n    }\n\ntype Details =\n  | { readonly ok: true; readonly entries: readonly Entry[] }\n  | { readonly ok: false; readonly reason: string }\n\nconst applied = <K extends ReconcilableOperation>(\n  operation: K,\n  body: OperationOutput<K>,\n  notes: readonly string[] = []\n): AppliedResult<K> => ({ status: 'applied', operation, body, notes })\n\nconst notApplied = (\n  operation: ReconcilableOperation,\n  reason: string\n): ReconcileResult => ({ status: 'not-applied', operation, reason })\n\nconst indeterminate = (\n  operation: ReconcilableOperation,\n  reason: string\n): ReconcileResult => ({ status: 'indeterminate', operation, reason })\n\n/** A `PAYMENT` entry with everything the rules read, or `undefined`. */\nfunction toPayment(info: PaymentDetailsInfo): Payment | undefined {\n  const { transactionId, orderId, payStatus, currency, payInfo } = info\n  if (\n    transactionId === '' ||\n    orderId === undefined ||\n    currency === undefined ||\n    payInfo === undefined\n  ) {\n    return undefined\n  }\n  return {\n    transactionId,\n    orderId,\n    payStatus,\n    currency,\n    payInfo,\n    packages: info.packages ?? [],\n    refundList: info.refundList ?? [],\n    transactionDate: info.transactionDate,\n    authorizationExpireDate: info.authorizationExpireDate,\n    shipping: info.shipping,\n    paymentProvider: info.paymentProvider\n  }\n}\n\n/**\n * The entries of the payment details, or `undefined` when a payment among them\n * lacks what the rules read. The answer has passed the guard of `paymentDetails`\n * (every entry has an ID and a type, and what else it has is of the right type),\n * so what is left to check is what only a payment must have.\n */\nfunction parseEntries(\n  info: readonly PaymentDetailsInfo[]\n): readonly Entry[] | undefined {\n  const entries: Entry[] = []\n  for (const item of info) {\n    if (item.transactionType === 'PAYMENT') {\n      const payment = toPayment(item)\n      if (payment === undefined) return undefined\n      entries.push({ kind: 'payment', payment })\n    } else {\n      entries.push({\n        kind: 'other',\n        transactionId: item.transactionId,\n        orderId: item.orderId,\n        transactionType: item.transactionType\n      })\n    }\n  }\n  return entries\n}\n\nasync function readDetails(\n  env: RuleEnv,\n  query: PaymentDetailsInput\n): Promise<Details> {\n  try {\n    const { body } = await env.client.paymentDetails(query, env.options)\n    const entries = parseEntries(body.info)\n    return entries === undefined\n      ? { ok: false, reason: UNREADABLE }\n      : { ok: true, entries }\n  } catch (error) {\n    // V4 sandbox payment-details lookups return 1150 for unknown transaction\n    // and order IDs. It is evidence of no record *now*, not proof the call\n    // can never complete later.\n    if (isLinePayApiError(error) && error.returnCode === '1150') {\n      return { ok: true, entries: [] }\n    }\n    if (isLinePayError(error)) {\n      return {\n        ok: false,\n        reason: `The payment details could not be read (${error.code}).`\n      }\n    }\n    throw error\n  }\n}\n\n// The V4 reference shows payInfo entries for combined credit-card and LINE\n// POINTS payments; sandbox testing has confirmed single-card payments, even\n// after partial refunds. TODO(v4-spec): verify discount and promotion totals\n// against real payment details. Mismatched amounts remain indeterminate.\nconst paidAmount = (payment: Payment) =>\n  payment.payInfo.reduce((sum, pay) => sum + pay.amount, 0)\n\n/**\n * The payment is in the currency, and for the amount, that the call asked for.\n * `reconcile` has seen to it that the context carries both; if one is missing all\n * the same, nothing matches.\n */\nconst matchesCall = (payment: Payment, context: ReconcileContext) =>\n  context.currency !== undefined &&\n  context.amount !== undefined &&\n  payment.currency === context.currency &&\n  amountsEqual(paidAmount(payment), context.amount)\n\nfunction byTransactionId(env: RuleEnv): PaymentDetailsInput {\n  return { transactionId: [env.context.transactionId ?? ''] }\n}\n\n/** Every entry that carries the transaction ID. There should be one. */\nfunction withTransactionId(\n  entries: readonly Entry[],\n  transactionId: string | undefined\n): Entry[] {\n  return entries.filter(entry =>\n    entry.kind === 'payment'\n      ? entry.payment.transactionId === transactionId\n      : entry.transactionId === transactionId\n  )\n}\n\ntype Lookup =\n  | { readonly found: 'payment'; readonly payment: Payment }\n  | { readonly found: 'nothing' }\n  | { readonly found: 'unclear'; readonly reason: string }\n\n/** The one payment with the transaction ID of the call, or why there is none. */\nfunction lookUpPayment(\n  entries: readonly Entry[],\n  transactionId: string | undefined\n): Lookup {\n  const [entry, ...more] = withTransactionId(entries, transactionId)\n  if (entry === undefined) return { found: 'nothing' }\n  if (more.length > 0) {\n    return {\n      found: 'unclear',\n      reason: 'Several entries carry this transaction ID.'\n    }\n  }\n  if (entry.kind === 'other') {\n    return {\n      found: 'unclear',\n      reason: `The transaction is a ${entry.transactionType}, not a payment.`\n    }\n  }\n  return { found: 'payment', payment: entry.payment }\n}\n\n/**\n * \"It is not there\" says that the call did not happen only if the search could\n * have found it and nothing speaks against it. Nothing may speak against it:\n *\n * - LINE Pay itself answered that the call duplicates another one, so what it\n *   duplicates exists;\n * - the answer holds entries that are not the one asked for (an ID that differs\n *   in a character LINE Pay does not mind, say), and the one asked for may be\n *   among what cannot be matched;\n * - the context does not say on which channel the call was made, and with the\n *   credentials of another channel nothing would show up either.\n */\nfunction absent(\n  operation: ReconcilableOperation,\n  env: RuleEnv,\n  entries: readonly Entry[],\n  reason: string\n): ReconcileResult {\n  if (env.duplicate) {\n    return indeterminate(\n      operation,\n      'LINE Pay answered that this call duplicates another one, so something exists that it duplicates, and it is not among the payment details: look in the Merchant Center.'\n    )\n  }\n  if (entries.length > 0) {\n    return indeterminate(\n      operation,\n      'The payment details hold entries, but none of them is the payment of this call (an ID that differs in a character, say), so they cannot show that nothing happened.'\n    )\n  }\n  if (env.context.channelId === undefined) {\n    return indeterminate(\n      operation,\n      `${reason} That proves nothing here: the context does not say on which channel the call was made, and with the credentials of another channel the payment would not show up either. Save channelId with the context.`\n    )\n  }\n  return notApplied(operation, reason)\n}\n\n/**\n * Why a confirm or a capture whose payment has been refunded is `indeterminate`.\n *\n * The payment details keep `payStatus: CAPTURE` and the original `payInfo` after a\n * refund, so \"the payment is there, for the amount that was asked\" is also true of\n * a payment that is no longer held. LINE Pay answers a confirm of a refunded\n * payment with `1172`, as it does a repeated one, so a customer who opens an old\n * confirmUrl again lands here. `applied` is what a caller marks the order paid\n * on; the refund list cannot say whether this call is what took the money, or how\n * much of it is still held (a partial refund leaves part of it), so a person looks.\n */\nconst REFUNDED =\n  'The payment has been refunded since (its refundList is not empty), so it is not necessarily held now, and the details cannot tell whether this call is what took it. Look in the Merchant Center before treating the order as paid.'\n\nconst AUTHORIZED_NOTE =\n  'The payment is authorized, not captured. That is as it should be if the call asked not to capture. If it asked to capture (the default), look at the payment again before treating it as paid: an authorization that is never captured expires.'\n\nconst REGKEY_NOTE =\n  'If the payment request used payType PREAPPROVED, the regKey is only returned by confirm. ' +\n  'It cannot be recovered from the payment details, so treat that case by hand. ' +\n  'If the original error is an unexpected-shape one, the response as received is in its body, and the regKey may be in it.'\n\n/**\n * The payment shows in the payment details once confirm went through (as\n * authorized or captured). The amount must match what was asked for.\n */\nexport async function reconcileConfirm(env: RuleEnv): Promise<ReconcileResult> {\n  const { context } = env\n  const details = await readDetails(env, byTransactionId(env))\n  if (!details.ok) return indeterminate('confirm', details.reason)\n\n  const lookup = lookUpPayment(details.entries, context.transactionId)\n  if (lookup.found === 'nothing') {\n    return absent(\n      'confirm',\n      env,\n      details.entries,\n      'The payment is not in the payment details: the user has not approved it, or confirm did not go through.'\n    )\n  }\n  if (lookup.found === 'unclear') return indeterminate('confirm', lookup.reason)\n\n  const { payment } = lookup\n  if (payment.payStatus === undefined) {\n    return indeterminate(\n      'confirm',\n      'The V4 payment details omit payStatus, so capture versus authorization cannot be verified.'\n    )\n  }\n  if (\n    payment.payStatus !== 'CAPTURE' &&\n    payment.payStatus !== 'AUTHORIZATION'\n  ) {\n    return indeterminate(\n      'confirm',\n      `The payment was confirmed but is now ${payment.payStatus}.`\n    )\n  }\n  if (!matchesCall(payment, context)) {\n    return indeterminate(\n      'confirm',\n      'The payment exists, but its amount or currency differs from the confirm call.'\n    )\n  }\n  if (payment.refundList.length > 0) return indeterminate('confirm', REFUNDED)\n\n  const body: ConfirmResponse = {\n    returnCode: '0000',\n    returnMessage: RECOVERED,\n    info: {\n      orderId: payment.orderId,\n      transactionId: payment.transactionId,\n      payInfo: payment.payInfo,\n      packages: payment.packages\n    }\n  }\n  if (typeof payment.authorizationExpireDate === 'string') {\n    body.info.authorizationExpireDate = payment.authorizationExpireDate\n  }\n  if (payment.shipping !== undefined) body.info.shipping = payment.shipping\n  if (payment.paymentProvider !== undefined) {\n    body.info.paymentProvider = payment.paymentProvider\n  }\n  return applied(\n    'confirm',\n    body,\n    payment.payStatus === 'AUTHORIZATION'\n      ? [REGKEY_NOTE, AUTHORIZED_NOTE]\n      : [REGKEY_NOTE]\n  )\n}\n\nexport async function reconcileCapture(env: RuleEnv): Promise<ReconcileResult> {\n  const { context } = env\n  const details = await readDetails(env, byTransactionId(env))\n  if (!details.ok) return indeterminate('capture', details.reason)\n\n  const lookup = lookUpPayment(details.entries, context.transactionId)\n  if (lookup.found === 'nothing') {\n    return indeterminate(\n      'capture',\n      'The payment is not in the payment details.'\n    )\n  }\n  if (lookup.found === 'unclear') return indeterminate('capture', lookup.reason)\n\n  const { payment } = lookup\n  if (payment.payStatus === undefined) {\n    return indeterminate(\n      'capture',\n      'The V4 payment details omit payStatus, so capture cannot be verified.'\n    )\n  }\n  switch (payment.payStatus) {\n    case 'AUTHORIZATION':\n      return notApplied('capture', 'The payment is still only authorized.')\n    case 'CAPTURE':\n      if (!matchesCall(payment, context)) {\n        return indeterminate(\n          'capture',\n          'The payment is captured, but its amount or currency differs from the capture call.'\n        )\n      }\n      if (payment.refundList.length > 0) {\n        return indeterminate('capture', REFUNDED)\n      }\n      return applied(\n        'capture',\n        {\n          returnCode: '0000',\n          returnMessage: RECOVERED,\n          info: {\n            orderId: payment.orderId,\n            transactionId: payment.transactionId,\n            payInfo: payment.payInfo\n          }\n        },\n        [\n          'The payment details do not say who captured it. If another call captured the same payment, this one did not.'\n        ]\n      )\n    default:\n      return indeterminate(\n        'capture',\n        `The payment is ${payment.payStatus}, so it cannot be captured.`\n      )\n  }\n}\n\nexport async function reconcileVoid(env: RuleEnv): Promise<ReconcileResult> {\n  const { context } = env\n  const details = await readDetails(env, byTransactionId(env))\n  if (!details.ok) return indeterminate('void', details.reason)\n\n  const lookup = lookUpPayment(details.entries, context.transactionId)\n  if (lookup.found === 'nothing') {\n    return indeterminate('void', 'The payment is not in the payment details.')\n  }\n  if (lookup.found === 'unclear') return indeterminate('void', lookup.reason)\n\n  const { payment } = lookup\n  if (payment.payStatus === undefined) {\n    return indeterminate(\n      'void',\n      'The V4 payment details omit payStatus, so void cannot be verified.'\n    )\n  }\n  switch (payment.payStatus) {\n    case 'VOIDED_AUTHORIZATION':\n      return applied('void', { returnCode: '0000', returnMessage: RECOVERED })\n    case 'AUTHORIZATION':\n      return notApplied('void', 'The authorization is still open.')\n    case 'CAPTURE':\n      return notApplied(\n        'void',\n        'The payment was captured, so it cannot have been voided.'\n      )\n    case 'EXPIRED_AUTHORIZATION':\n      return notApplied('void', 'The authorization expired; it was not voided.')\n    default:\n      return indeterminate('void', `The payment is ${payment.payStatus}.`)\n  }\n}\n\n/** The transaction types of a refund. */\nconst REFUND_TYPES: ReadonlySet<string> = new Set([\n  'PAYMENT_REFUND',\n  'PARTIAL_REFUND'\n])\n\n/** The order ID is the key: LINE Pay refuses a second payment with the same one. */\nexport async function reconcilePayPreapproved(\n  env: RuleEnv\n): Promise<ReconcileResult> {\n  const { context } = env\n  // A repeated order ID can resolve to an earlier charge. A timestamp and\n  // amount are not enough to attribute that charge to this API invocation.\n  if (env.duplicate) {\n    return indeterminate(\n      'payPreapproved',\n      'LINE Pay rejected this request as a duplicate. An earlier payment may exist for this order ID; do not attribute it to this call.'\n    )\n  }\n  const details = await readDetails(env, { orderId: [context.orderId ?? ''] })\n  if (!details.ok) return indeterminate('payPreapproved', details.reason)\n\n  // An entry with this order ID that is neither a payment nor a refund is\n  // something this rule does not know. Not finding a payment next to it must not\n  // read as \"nothing was charged\".\n  for (const entry of details.entries) {\n    if (\n      entry.kind === 'other' &&\n      entry.orderId === context.orderId &&\n      !REFUND_TYPES.has(entry.transactionType)\n    ) {\n      return indeterminate(\n        'payPreapproved',\n        `An entry with this order ID is a ${entry.transactionType}, which this rule does not know how to read.`\n      )\n    }\n  }\n\n  const matches = details.entries.flatMap(entry =>\n    entry.kind === 'payment' && entry.payment.orderId === context.orderId\n      ? [entry.payment]\n      : []\n  )\n  if (matches.length === 0) {\n    return absent(\n      'payPreapproved',\n      env,\n      details.entries,\n      'No payment with this order ID exists.'\n    )\n  }\n  const [payment] = matches\n  if (matches.length > 1 || payment === undefined) {\n    return indeterminate(\n      'payPreapproved',\n      'Several payments carry this order ID.'\n    )\n  }\n  // A voided or expired authorization with this order ID is not a charge.\n  if (payment.payStatus === undefined) {\n    return indeterminate(\n      'payPreapproved',\n      'The V4 payment details omit payStatus, so the charge cannot be verified.'\n    )\n  }\n  if (\n    payment.payStatus !== 'CAPTURE' &&\n    payment.payStatus !== 'AUTHORIZATION'\n  ) {\n    return indeterminate(\n      'payPreapproved',\n      `A payment with this order ID exists, but it is ${payment.payStatus}.`\n    )\n  }\n  if (!matchesCall(payment, context)) {\n    return indeterminate(\n      'payPreapproved',\n      'A payment with this order ID exists, but its amount or currency differs from the call.'\n    )\n  }\n  if (typeof payment.transactionDate !== 'string') {\n    return indeterminate(\n      'payPreapproved',\n      'A payment with this order ID exists, but it has no transaction date.'\n    )\n  }\n  // Since timestamps may omit milliseconds, a payment in the same second as\n  // this call may have happened *before* it. Never claim it as this call's.\n  // A missing time zone is also not evidence.\n  if (\n    !(\n      wholeSeconds(instantOf(payment.transactionDate)) >\n      wholeSeconds(context.startedAt.getTime())\n    )\n  ) {\n    return indeterminate(\n      'payPreapproved',\n      'A payment with this order ID exists, but it is not provably after the call began (or its date cannot be read), so it may be an earlier use of the order ID.'\n    )\n  }\n\n  const info: {\n    orderId: string\n    transactionId: string\n    transactionDate: string\n    authorizationExpireDate?: string\n  } = {\n    orderId: payment.orderId,\n    transactionId: payment.transactionId,\n    transactionDate: payment.transactionDate\n  }\n  if (typeof payment.authorizationExpireDate === 'string') {\n    info.authorizationExpireDate = payment.authorizationExpireDate\n  }\n  return applied(\n    'payPreapproved',\n    { returnCode: '0000', returnMessage: RECOVERED, info },\n    payment.payStatus === 'AUTHORIZATION' ? [AUTHORIZED_NOTE] : []\n  )\n}\n\n/**\n * A refund is not idempotent, so this rule never concludes `not-applied`: not\n * finding the refund does not prove that LINE Pay did not make it (it may still be\n * processing). It answers `applied` only when exactly one refund of the right\n * amount was made in a later second. Same-second timestamps are ambiguous.\n */\nexport async function reconcileRefund(env: RuleEnv): Promise<ReconcileResult> {\n  const { context } = env\n  // LINE Pay refused this very call as a duplicate. A refund of that amount may\n  // well exist, made by the call it duplicates, but then this call made none: to\n  // report \"applied\" for it would count one refund twice.\n  if (env.duplicate) {\n    return indeterminate(\n      'refund',\n      'LINE Pay refused this call as a duplicate. An earlier refund may exist, but it cannot be told whether it is this call that made it: look in the Merchant Center before refunding again.'\n    )\n  }\n  const details = await readDetails(env, byTransactionId(env))\n  if (!details.ok) return indeterminate('refund', details.reason)\n\n  const lookup = lookUpPayment(details.entries, context.transactionId)\n  if (lookup.found === 'nothing') {\n    return indeterminate('refund', 'The payment is not in the payment details.')\n  }\n  if (lookup.found === 'unclear') return indeterminate('refund', lookup.reason)\n\n  // What could be this call's refund: any refund when the call refunded\n  // everything, else one of the amount it asked for. An entry of those that this\n  // rule cannot read (a type it does not know, a date without a time zone) may be\n  // the one, and must not be left out of the count: a refund that was found would\n  // then pass as \"exactly one\" when it is another's.\n  const possible = lookup.payment.refundList.filter(\n    refund =>\n      context.refundAmount === undefined ||\n      amountsEqual(Math.abs(refund.refundAmount), context.refundAmount)\n  )\n  if (\n    possible.some(\n      refund =>\n        !REFUND_TYPES.has(refund.transactionType) ||\n        Number.isNaN(instantOf(refund.refundTransactionDate))\n    )\n  ) {\n    return indeterminate(\n      'refund',\n      \"The refund list holds an entry that could be this refund but cannot be read (a type this rule does not know, or a date without a time zone), so it cannot be told which refund is this call's: look in the Merchant Center before refunding again.\"\n    )\n  }\n\n  // A timestamp equal to the call's starting second may be an earlier refund.\n  // Never claim a same-second refund as this request's. Other concurrent\n  // refunds are still ambiguous; callers must serialize by transaction ID.\n  const since = wholeSeconds(context.startedAt.getTime())\n  const candidates = possible.filter(\n    refund =>\n      wholeSeconds(instantOf(refund.refundTransactionDate)) > since &&\n      (context.refundAmount !== undefined ||\n        refund.transactionType === 'PAYMENT_REFUND')\n  )\n\n  const [refund] = candidates\n  if (candidates.length === 1 && refund !== undefined) {\n    return applied(\n      'refund',\n      {\n        returnCode: '0000',\n        returnMessage: RECOVERED,\n        info: {\n          refundTransactionId: refund.refundTransactionId,\n          refundTransactionDate: refund.refundTransactionDate\n        }\n      },\n      [\n        'Matched by amount and a later whole second. This does not identify the API call: concurrent refunds of the same amount can still be confused. Serialize refunds of one transaction and check the Merchant Center before relying on an inferred refund.'\n      ]\n    )\n  }\n  return indeterminate(\n    'refund',\n    candidates.length === 0\n      ? 'No matching refund shows up since the call started. It may still be processing: ask again later, or look in the Merchant Center, before refunding again.'\n      : 'Several refunds of this amount were made since the call started; it cannot be told which one belongs to this call.'\n  )\n}\n","import type {\n  CallOptions,\n  LinePayClient,\n  ReconcileResult\n} from '../client-types'\nimport { isNumber, isRecord } from '../core/guard'\nimport { toDate } from '../core/time'\nimport { isTransactionId } from '../core/validate'\nimport {\n  isLinePayApiError,\n  isLinePayError,\n  type LinePayApiError,\n  type LinePayHttpError,\n  needsReconcile,\n  type ReconcileContext\n} from '../errors'\nimport {\n  isOperationName,\n  isReconcilableOperation,\n  type ReconcilableOperation\n} from '../operations/names'\nimport {\n  reconcileCapture,\n  reconcileConfirm,\n  reconcilePayPreapproved,\n  reconcileRefund,\n  reconcileVoid,\n  type RuleEnv\n} from './rules'\n\nconst rules = {\n  confirm: reconcileConfirm,\n  capture: reconcileCapture,\n  void: reconcileVoid,\n  refund: reconcileRefund,\n  payPreapproved: reconcilePayPreapproved\n} as const\n\ntype Field = 'transactionId' | 'orderId' | 'amount' | 'currency'\n\n/** What the lookup of each operation cannot do without. */\nconst NEEDS: Readonly<Record<ReconcilableOperation, readonly Field[]>> = {\n  confirm: ['transactionId', 'amount', 'currency'],\n  capture: ['transactionId', 'amount', 'currency'],\n  void: ['transactionId'],\n  refund: ['transactionId'],\n  payPreapproved: ['orderId', 'amount', 'currency']\n}\n\nconst usableAmount = (value: unknown): number | undefined =>\n  isNumber(value) ? value : undefined\nconst usableText = (value: unknown): string | undefined =>\n  typeof value === 'string' && value.length > 0 ? value : undefined\nconst usableTransactionId = (value: unknown): string | undefined =>\n  isTransactionId(value) ? value : undefined\n\n/** Why a field a lookup needs cannot be used. */\nfunction refusal(field: Field, given: unknown): string {\n  if (field === 'transactionId' || field === 'orderId') {\n    return `The context carries no ${field} to look up.`\n  }\n  if (given === undefined) {\n    return `The context carries no ${field} to compare with.`\n  }\n  return `The context's ${field} must be ${field === 'amount' ? 'a finite number' : 'a non-empty string'}.`\n}\n\n/**\n * The context to look a call up with, from the fields of one. A context may come\n * out of a database, so a field is checked for its type and not just for being\n * there: a number where an order ID belongs would never equal the string LINE Pay\n * reports, and \"nothing found\" would read as \"did not happen\". Returns why the\n * context cannot be used instead when it cannot.\n */\nfunction readContext(\n  fields: Readonly<Record<string, unknown>>,\n  operation: ReconcilableOperation,\n  startedAt: Date\n): ReconcileContext | string {\n  const read = {\n    transactionId: usableTransactionId(fields.transactionId),\n    orderId: usableText(fields.orderId),\n    amount: usableAmount(fields.amount),\n    currency: usableText(fields.currency)\n  }\n  for (const field of NEEDS[operation]) {\n    if (read[field] === undefined) return refusal(field, fields[field])\n  }\n\n  const { refundAmount, channelId } = fields\n  if (refundAmount !== undefined && usableAmount(refundAmount) === undefined) {\n    return \"The context's refundAmount must be a finite number, or left out for a full refund.\"\n  }\n  if (channelId !== undefined && usableText(channelId) === undefined) {\n    return \"The context's channelId must be a non-empty string.\"\n  }\n  return {\n    operation,\n    startedAt,\n    channelId: usableText(channelId),\n    transactionId: read.transactionId,\n    orderId: read.orderId,\n    amount: read.amount,\n    currency: read.currency,\n    refundAmount: usableAmount(refundAmount)\n  }\n}\n\n/** What refused the call: only LINE Pay's answer, or a proxy's, can be `rejected`. */\nfunction describeRefusal(error: LinePayApiError | LinePayHttpError): string {\n  return isLinePayApiError(error)\n    ? `returnCode ${error.returnCode}`\n    : `HTTP ${error.httpStatus}`\n}\n\n/**\n * What a context carries itself. A field it does not have must not be found on\n * `Object.prototype`, where another part of the program may have put one (the\n * same reason `resolveConfig` reads the configuration this way): the lookup would\n * be of a payment the context never named.\n */\nfunction ownFields(value: object): Readonly<Record<string, unknown>> {\n  const own: Record<string, unknown> = { ...value }\n  Object.setPrototypeOf(own, null)\n  return own\n}\n\n/** A context as it was found, before it is checked. */\ninterface Candidate {\n  readonly operation: string\n  readonly startedAt: Date\n  readonly fields: Readonly<Record<string, unknown>>\n}\n\n/** What the caller passed, as a context: an error's own, or one that was saved. */\nfunction candidateOf(subject: unknown): Candidate | string | undefined {\n  if (isLinePayError(subject)) {\n    const { context } = subject\n    return context === undefined\n      ? undefined\n      : {\n          operation: context.operation,\n          startedAt: context.startedAt,\n          fields: ownFields(context)\n        }\n  }\n  if (!isRecord(subject)) return undefined\n  const fields = ownFields(subject)\n  if (typeof fields.operation !== 'string') return undefined\n\n  // A context that was saved comes back from JSON with a string or a number.\n  const startedAt = toDate(fields.startedAt)\n  if (startedAt === undefined) {\n    return 'The context needs startedAt: a Date, an ISO 8601 string with a time zone, or milliseconds since the epoch (a number of seconds is not milliseconds).'\n  }\n  return { operation: fields.operation, startedAt, fields }\n}\n\n/**\n * Look up whether a call took effect. The lookups go through `client`, so its\n * middleware applies to them too.\n *\n * It takes an error of this client, or a context that was saved before the call\n * (the process may have died before it got an answer, and then there is no error).\n *\n * Only an unknown outcome (or a duplicate answer) needs a lookup. An error that\n * proves the call did not happen, because it was never sent or LINE Pay refused\n * it, is answered without one.\n */\nexport async function reconcile(\n  client: LinePayClient,\n  channelId: string,\n  subject: unknown,\n  options?: CallOptions\n): Promise<ReconcileResult> {\n  // Never sent: no context is needed to know that, and an input that was refused\n  // before it could be sent (bad call options, say) has none.\n  if (isLinePayError(subject) && subject.outcome === 'not-sent') {\n    const operation = subject.context?.operation ?? subject.operation\n    if (operation !== undefined && isReconcilableOperation(operation)) {\n      return {\n        status: 'not-applied',\n        operation,\n        reason: 'The request was never sent, so it did not take effect.'\n      }\n    }\n  }\n\n  const candidate = candidateOf(subject)\n  if (typeof candidate === 'string') {\n    return { status: 'indeterminate', reason: candidate }\n  }\n  if (candidate === undefined) {\n    return {\n      status: 'indeterminate',\n      reason:\n        'There is nothing to look up: pass an error thrown by a call of this client, or the context of a call.'\n    }\n  }\n  const { operation } = candidate\n  if (!isReconcilableOperation(operation)) {\n    return {\n      status: 'indeterminate',\n      ...(isOperationName(operation) ? { operation } : {}),\n      reason: `Reconcile is not supported for ${operation}.`\n    }\n  }\n\n  if (isLinePayError(subject)) {\n    if (subject.outcome === 'rejected' && !needsReconcile(subject)) {\n      return {\n        status: 'not-applied',\n        operation,\n        reason: `LINE Pay refused the call (${describeRefusal(subject)}), so it did not take effect.`\n      }\n    }\n  }\n\n  const context = readContext(candidate.fields, operation, candidate.startedAt)\n  if (typeof context === 'string') {\n    return { status: 'indeterminate', operation, reason: context }\n  }\n  if (context.channelId !== undefined && context.channelId !== channelId) {\n    return {\n      status: 'indeterminate',\n      operation,\n      reason: `The call was made on channel ${context.channelId}, and this client is channel ${channelId}: with other credentials the payment would not be found, and that would say nothing.`\n    }\n  }\n\n  const duplicate =\n    isLinePayApiError(subject) && subject.category === 'duplicate'\n  const env: RuleEnv = { client, context, options, duplicate }\n  return rules[operation](env)\n}\n","import type {\n  AnyCallContext,\n  CallContext,\n  CallOptions,\n  LinePayClient,\n  Middleware,\n  ResultOf\n} from './client-types'\nimport {\n  isValidTimeout,\n  type LinePayConfig,\n  resolveConfig,\n  TIMEOUT_MESSAGE\n} from './config'\nimport { createExecutor } from './core/execute'\nimport { compose, resultOf, type Terminal } from './core/pipeline'\nimport { isPlainObject, snapshotOf } from './core/snapshot'\nimport { Checker } from './core/validate'\nimport type { OperationInput } from './operations'\nimport type { OperationName } from './operations/names'\nimport { reconcile } from './reconcile'\n\n/**\n * The options of a call, as the call will use them. What is checked is the copy,\n * not the object that was given: an option that a copy leaves out (behind a\n * getter, on a prototype) would otherwise pass the check and then not be there.\n */\nfunction optionsOf(\n  options: unknown,\n  operation: OperationName\n): Readonly<CallOptions> {\n  const checker = new Checker()\n  let timeout: number | undefined\n  let signal: AbortSignal | undefined\n  if (!isPlainObject(options)) {\n    checker.fail('options', 'must be a plain object')\n  } else {\n    const own = { ...options }\n    checker.onlyFields(\n      'options',\n      own,\n      ['timeout', 'signal'],\n      'the call options'\n    )\n    if (own.timeout !== undefined) {\n      if (isValidTimeout(own.timeout)) timeout = own.timeout\n      else checker.fail('options.timeout', TIMEOUT_MESSAGE)\n    }\n    if (own.signal !== undefined) {\n      if (own.signal instanceof AbortSignal) signal = own.signal\n      else checker.fail('options.signal', 'must be an AbortSignal')\n    }\n  }\n  checker.throwIfInvalid({ operation })\n  return Object.freeze({\n    ...(timeout === undefined ? {} : { timeout }),\n    ...(signal === undefined ? {} : { signal })\n  })\n}\n\nfunction buildClient(\n  terminal: Terminal,\n  middleware: readonly Middleware[],\n  channelId: string\n): LinePayClient {\n  const run = compose(middleware, terminal)\n\n  // Each method names its operation itself, so that the compiler can follow the\n  // call through the middleware (which handle every operation) and back to the\n  // result that this method promises.\n  const contextOf = <K extends OperationName>(\n    operation: K,\n    input: OperationInput<K>,\n    options: CallOptions\n  ): CallContext<K> => {\n    return {\n      operation,\n      options: optionsOf(options, operation),\n      input: snapshotOf(input, operation),\n      startedAt: new Date(),\n      client\n    }\n  }\n\n  // The context is made inside the call, so that a call whose options or input\n  // are refused is a rejection like any other. `K & AnyCallContext` is the context\n  // of one operation, and still a context the middleware accept.\n  const call = async <K extends OperationName>(\n    make: () => CallContext<K> & AnyCallContext\n  ): Promise<ResultOf<K>> => {\n    const ctx = make()\n    return resultOf<K>(ctx, await run(ctx), channelId)\n  }\n\n  const client: LinePayClient = {\n    request: (input, options = {}) =>\n      call(() => contextOf('request', input, options)),\n    confirm: (input, options = {}) =>\n      call(() => contextOf('confirm', input, options)),\n    capture: (input, options = {}) =>\n      call(() => contextOf('capture', input, options)),\n    void: (input, options = {}) =>\n      call(() => contextOf('void', input, options)),\n    refund: (input, options = {}) =>\n      call(() => contextOf('refund', input, options)),\n    paymentDetails: (input, options = {}) =>\n      call(() => contextOf('paymentDetails', input, options)),\n    checkPaymentStatus: (input, options = {}) =>\n      call(() => contextOf('checkPaymentStatus', input, options)),\n    checkRegKey: (input, options = {}) =>\n      call(() => contextOf('checkRegKey', input, options)),\n    payPreapproved: (input, options = {}) =>\n      call(() => contextOf('payPreapproved', input, options)),\n    expireRegKey: (input, options = {}) =>\n      call(() => contextOf('expireRegKey', input, options)),\n    with: (...more) => {\n      // The chain ends at the first thing that is not a function: what follows\n      // it would never run, a guard among it.\n      const checker = new Checker()\n      more.forEach((entry: unknown, index) => {\n        if (typeof entry !== 'function') {\n          checker.fail(`middleware[${index}]`, 'must be a function')\n        }\n      })\n      checker.throwIfInvalid({ subject: 'configuration' })\n      return buildClient(terminal, [...middleware, ...more], channelId)\n    },\n    reconcile: (errorOrContext, options) =>\n      reconcile(client, channelId, errorOrContext, options)\n  }\n  return Object.freeze(client)\n}\n\n/**\n * Create a client. It does not connect to anything and keeps no global state, so\n * creating one per merchant is cheap.\n *\n * @example\n * const linePay = createLinePayClient({\n *   channelId: process.env.LINE_PAY_CHANNEL_ID ?? '',\n *   channelSecretKey: process.env.LINE_PAY_CHANNEL_SECRET ?? '',\n *   env: 'sandbox'\n * })\n *\n * @throws {LinePayValidationError} when the configuration is invalid.\n */\nexport function createLinePayClient(config: LinePayConfig): LinePayClient {\n  const resolved = resolveConfig(config)\n  return buildClient(\n    createExecutor(resolved),\n    resolved.middleware,\n    resolved.channelId\n  )\n}\n","import { isArray } from '../core/guard'\nimport { isTransactionId } from '../core/validate'\nimport { LinePayValidationError, type ValidationIssue } from '../errors'\n\nexport type ConfirmQuerySource =\n  string | URL | URLSearchParams | Readonly<Record<string, unknown>>\n\nexport interface ConfirmQuery {\n  /** 1 to 19 digits, as a string. */\n  transactionId: string\n  /** Present when LINE Pay appended it. 1 to 100 characters. */\n  orderId?: string\n}\n\n/** A whole URL or a path (with or without a query), as opposed to a bare query string. */\nconst LOOKS_LIKE_URL = /^(?:[a-z][a-z0-9+.-]*:\\/\\/|\\/|\\?)/i\n\nfunction searchParamsOf(\n  source: string | URL | URLSearchParams\n): URLSearchParams {\n  if (source instanceof URLSearchParams) return source\n  if (source instanceof URL) return source.searchParams\n  if (!LOOKS_LIKE_URL.test(source)) return new URLSearchParams(source)\n  try {\n    return new URL(source, 'http://localhost').searchParams\n  } catch {\n    throw new LinePayValidationError({\n      issues: [{ path: 'source', message: 'is not a valid URL' }]\n    })\n  }\n}\n\n/** Every value given for each key, as it came in. Nothing is coerced. */\nfunction valuesOf(source: ConfirmQuerySource): Map<string, unknown[]> {\n  const values = new Map<string, unknown[]>()\n  const add = (key: string, value: unknown) => {\n    const list = values.get(key)\n    if (list === undefined) values.set(key, [value])\n    else list.push(value)\n  }\n\n  if (typeof source === 'object' && source !== null) {\n    if (source instanceof URLSearchParams || source instanceof URL) {\n      for (const [key, value] of searchParamsOf(source)) add(key, value)\n      return values\n    }\n    // A parsed query, such as `req.query` of Express. A parameter given more than\n    // once is a list of several values; a list of one (`?transactionId[]=1`) is\n    // not a single value either, and is kept as the list it is.\n    for (const [key, value] of Object.entries(source)) {\n      if (value === undefined) continue\n      if (isArray(value) && value.length !== 1) {\n        for (const item of value) add(key, item)\n      } else {\n        add(key, value)\n      }\n    }\n    return values\n  }\n  if (typeof source === 'string') {\n    for (const [key, value] of searchParamsOf(source)) add(key, value)\n    return values\n  }\n  throw new LinePayValidationError({\n    issues: [\n      {\n        path: 'source',\n        message: 'must be a URL, a query string or an object of parameters'\n      }\n    ]\n  })\n}\n\n/** What reading a parameter found: its value, or what is wrong with it. */\ntype Read<T> = { readonly value: T } | { readonly problem: string }\n\nconst LIST_PROBLEM = 'must be a single value, not a list'\n\nfunction readTransactionId(given: readonly unknown[]): Read<string> {\n  const [transactionId] = given\n  if (given.length === 0) return { problem: 'is missing' }\n  if (given.length > 1) return { problem: 'is given more than once' }\n  if (isArray(transactionId)) return { problem: LIST_PROBLEM }\n  if (!isTransactionId(transactionId)) {\n    return { problem: 'must be a string of 1 to 19 digits' }\n  }\n  return { value: transactionId }\n}\n\nfunction readOrderId(given: readonly unknown[]): Read<string | undefined> {\n  const [orderId] = given\n  if (given.length === 0) return { value: undefined }\n  if (given.length > 1) return { problem: 'is given more than once' }\n  if (isArray(orderId)) return { problem: LIST_PROBLEM }\n  if (\n    typeof orderId !== 'string' ||\n    orderId.length === 0 ||\n    orderId.length > 100\n  ) {\n    return { problem: 'must be a string of 1 to 100 characters' }\n  }\n  return { value: orderId }\n}\n\n/**\n * Read the parameters LINE Pay appends to the confirmUrl. The `transactionId`\n * comes from the user's browser, so anyone can put anything there: it has to be a\n * single string of 1 to 19 digits, and nothing else is let through.\n *\n * Find the order in your own database by the `transactionId` that you stored when\n * you called `request` for it, and take the amount and the currency from that\n * order, never from the URL. Do not find the order by the `orderId` of the URL and\n * then confirm the `transactionId` of the URL: the browser can pair any `orderId`\n * with any `transactionId`, so a cheap order could be paid with the approval of\n * somebody else's payment. If you do look the order up by `orderId`, check that\n * `order.transactionId === transactionId` before you go on.\n *\n * @example\n * const { transactionId } = parseConfirmQuery(req.query)\n * const order = await orders.findByTransactionId(transactionId) // none: answer 404\n *\n * @throws {LinePayValidationError} when a parameter is missing or malformed.\n */\nexport function parseConfirmQuery(source: ConfirmQuerySource): ConfirmQuery {\n  const values = valuesOf(source)\n  const transactionId = readTransactionId(values.get('transactionId') ?? [])\n  const orderId = readOrderId(values.get('orderId') ?? [])\n\n  if ('problem' in transactionId || 'problem' in orderId) {\n    const issues: ValidationIssue[] = []\n    if ('problem' in transactionId) {\n      issues.push({ path: 'transactionId', message: transactionId.problem })\n    }\n    if ('problem' in orderId) {\n      issues.push({ path: 'orderId', message: orderId.problem })\n    }\n    throw new LinePayValidationError({ issues })\n  }\n  return orderId.value === undefined\n    ? { transactionId: transactionId.value }\n    : { transactionId: transactionId.value, orderId: orderId.value }\n}\n","import type { Middleware, ReconcileResult } from '../client-types'\nimport { callMeta } from '../core/annotate'\nimport { describeCause, isLinePayApiError, needsReconcile } from '../errors'\nimport {\n  isReconcilableOperation,\n  RECONCILABLE_OPERATIONS,\n  type ReconcilableOperation\n} from '../operations/names'\n\nexport interface AutoReconcileOptions {\n  /** Operations to reconcile. All five reconcilable operations by default. */\n  operations?: readonly ReconcilableOperation[]\n}\n\n/**\n * When a call ends with an unknown outcome (or LINE Pay answers with a duplicate\n * code), look the payment up with `client.reconcile`. If it was processed, the\n * call returns the inferred result, marked in `meta.recovered`. Otherwise the\n * original error is thrown again, with the conclusion in\n * `error.reconcileConclusion`.\n *\n * It is not on by default: it turns an error into a success, so you opt in.\n * Place it inside `retryWhenNotSent()`.\n */\nexport function autoReconcile(options: AutoReconcileOptions = {}): Middleware {\n  const enabled = new Set<string>(options.operations ?? RECONCILABLE_OPERATIONS)\n\n  return async (ctx, next) => {\n    try {\n      return await next()\n    } catch (error) {\n      if (\n        !enabled.has(ctx.operation) ||\n        !isReconcilableOperation(ctx.operation) ||\n        !needsReconcile(error)\n      ) {\n        throw error\n      }\n\n      let result: ReconcileResult\n      try {\n        result = await ctx.client.reconcile(error, {\n          signal: ctx.options.signal\n        })\n      } catch (lookupFailure) {\n        // The error that matters is the one of the call. A lookup that broke\n        // (a bug in a middleware, say) must not take its place.\n        error.reconcileConclusion = {\n          status: 'indeterminate',\n          reason: `The lookup itself failed: ${\n            describeCause(lookupFailure) ??\n            'with something that is not an error'\n          }`\n        }\n        throw error\n      }\n\n      if (result.status !== 'applied') {\n        error.reconcileConclusion = {\n          status: result.status,\n          reason: result.reason\n        }\n        throw error\n      }\n\n      return {\n        body: result.body,\n        meta: {\n          ...callMeta(ctx, 1),\n          recovered: {\n            reason:\n              isLinePayApiError(error) && error.category === 'duplicate'\n                ? 'duplicate'\n                : 'unknown-outcome',\n            cause: error,\n            notes: result.notes\n          }\n        }\n      }\n    }\n  }\n}\n"],"mappings":";;;;;;AAaA,MAAa,WACX,UACgC,MAAM,QAAQ,KAAK;;AAGrD,MAAa,YACX,UAEA,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,QAAQ,KAAK;AAE/D,MAAa,YAA2B,UACtC,OAAO,UAAU;;AAGnB,MAAa,YAA2B,UACtC,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;;;;;AAMpD,SAAgB,SAAY,MAA4B;CACtD,QAAQ,UAAwB;EAC9B,IAAI,CAAC,QAAQ,KAAK,GAAG,OAAO;EAC5B,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SACxC,IAAI,CAAC,KAAK,MAAM,MAAM,GAAG,OAAO;EAElC,OAAO;CACT;AACF;;;;;;;;;;AAkBA,SAAgB,SAGd,UAAa,UAAuD;CAEpE,MAAM,WAAW,OAAO,QAAwB,QAAQ;CACxD,MAAM,UAAU,OAAO,QAAwB,YAAY,CAAC,CAAC;CAC7D,QAAQ,UAAqD;EAC3D,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;EAC7B,KAAK,MAAM,CAAC,KAAK,UAAU,UACzB,IAAI,CAAC,MAAM,MA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