facturas 0.22.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/config.ts","../src/services/issuance-fields.ts","../src/services/qr.ts","../src/services/wsfe-amounts.ts","../src/services/wsfe-derive.ts","../src/services/wsfex.ts","../src/store/types.ts","../src/services/wsfe-identity.ts","../src/wsaa/session-store.ts","../src/wsaa/index.ts","../src/internal/abort.ts","../src/internal/http.ts","../src/internal/xml.ts","../src/internal/logger.ts","../src/store/lock.ts","../src/services/issuance-wsfex.ts","../src/services/issuance-wsmtxca.ts","../src/services/wsfe-credit-note.ts","../src/services/vouchers.ts","../src/soap/index.ts","../src/wsaa/store-adapter.ts","../src/client.ts","../src/store/file.ts"],"sourcesContent":["import { ArcaConfigurationError } from \"./errors\";\nimport type {\n ArcaClientConfig,\n ArcaClientOptions,\n ArcaEnvironment,\n ArcaLogLevel,\n ArcaServiceName,\n ArcaSoapVersion,\n} from \"./internal/types\";\n\n/** Valid ARCA environment names. */\nexport const ARCA_ENVIRONMENTS = [\"production\", \"test\"] as const;\n\n/** Default environment variable names read by {@link createArcaClientConfigFromEnv}. */\nexport const ARCA_ENV_VARIABLES = {\n taxId: \"ARCA_TAX_ID\",\n certificatePem: \"ARCA_CERTIFICATE_PEM\",\n privateKeyPem: \"ARCA_PRIVATE_KEY_PEM\",\n environment: \"ARCA_ENVIRONMENT\",\n} as const;\n\ntype ArcaClientConfigEnvironment = Record<string, string | undefined>;\n/** Options for {@link createArcaClientConfigFromEnv}. */\nexport type CreateArcaClientConfigFromEnvOptions = {\n env?: ArcaClientConfigEnvironment;\n defaultEnvironment?: ArcaEnvironment;\n variableNames?: Partial<typeof ARCA_ENV_VARIABLES>;\n};\n\nconst PRIVATE_KEY_PEM_PREFIXES = [\n \"-----BEGIN PRIVATE KEY-----\",\n \"-----BEGIN RSA PRIVATE KEY-----\",\n] as const;\nconst ENCRYPTED_PRIVATE_KEY_PEM_PREFIX =\n \"-----BEGIN ENCRYPTED PRIVATE KEY-----\";\nconst LEGACY_ENCRYPTED_RSA_PRIVATE_KEY_PATTERN =\n /^-----BEGIN RSA PRIVATE KEY-----[\\s\\S]*^Proc-Type:\\s*4,\\s*ENCRYPTED\\s*$/m;\nconst VALID_ARCA_LOG_LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] as const;\nconst DEFAULT_ARCA_TIMEOUT_MS = 30_000;\nconst DEFAULT_ARCA_RETRIES = 0;\nconst DEFAULT_ARCA_RETRY_DELAY_MS = 500;\n\n/**\n * Builds an {@link ArcaClientConfig} from environment variables.\n * Reads `process.env` by default; override with `options.env`.\n *\n * @throws {ArcaConfigurationError} When required variables are missing or invalid.\n */\nexport function createArcaClientConfigFromEnv(\n options: CreateArcaClientConfigFromEnvOptions = {}\n): ArcaClientConfig {\n const env = options.env ?? process.env;\n const variableNames = {\n ...ARCA_ENV_VARIABLES,\n ...options.variableNames,\n };\n const environmentInput = readEnv(env, variableNames.environment);\n const environmentValue = normalizeEnvironmentValue(environmentInput);\n\n const config: ArcaClientConfig = {\n taxId: readEnv(env, variableNames.taxId) ?? \"\",\n certificatePem: readEnv(env, variableNames.certificatePem) ?? \"\",\n privateKeyPem: readEnv(env, variableNames.privateKeyPem) ?? \"\",\n environment:\n environmentValue ??\n (environmentInput as ArcaEnvironment | undefined) ??\n options.defaultEnvironment ??\n \"test\",\n };\n\n assertArcaClientConfig(config);\n return normalizeArcaClientConfig(config);\n}\n\n/**\n * Validates an {@link ArcaClientConfig} and throws if any field is invalid.\n *\n * @throws {ArcaConfigurationError} With a list of invalid field names.\n */\nexport function assertArcaClientConfig(config: ArcaClientConfig): void {\n const invalidFields: string[] = [];\n const normalized = normalizeArcaClientConfig(config);\n const timeout = normalized.timeout ?? DEFAULT_ARCA_TIMEOUT_MS;\n const retries = normalized.retries ?? DEFAULT_ARCA_RETRIES;\n const retryDelay = normalized.retryDelay ?? DEFAULT_ARCA_RETRY_DELAY_MS;\n\n if (\n normalized.privateKeyPem.startsWith(ENCRYPTED_PRIVATE_KEY_PEM_PREFIX) ||\n LEGACY_ENCRYPTED_RSA_PRIVATE_KEY_PATTERN.test(normalized.privateKeyPem)\n ) {\n throw new ArcaConfigurationError(\n \"Encrypted private keys are not supported. Provide an unencrypted PKCS#8 or RSA private key PEM.\"\n );\n }\n\n invalidFields.push(...invalidCredentialFields(normalized));\n\n if (!ARCA_ENVIRONMENTS.includes(normalized.environment)) {\n invalidFields.push(\"environment\");\n }\n\n if (!Number.isFinite(timeout) || timeout <= 0) {\n invalidFields.push(\"timeout\");\n }\n\n if (!Number.isInteger(retries) || retries < 0) {\n invalidFields.push(\"retries\");\n }\n\n if (!Number.isFinite(retryDelay) || retryDelay < 0) {\n invalidFields.push(\"retryDelay\");\n }\n\n const loggerLevel = normalized.logger?.level;\n if (\n loggerLevel !== undefined &&\n !VALID_ARCA_LOG_LEVELS.includes(loggerLevel)\n ) {\n invalidFields.push(\"logger.level\");\n }\n\n if (\n normalized.logger?.log !== undefined &&\n typeof normalized.logger.log !== \"function\"\n ) {\n invalidFields.push(\"logger.log\");\n }\n\n invalidFields.push(...getInvalidWsaaSessionStoreFields(normalized));\n\n if (invalidFields.length > 0) {\n throw new ArcaConfigurationError(\n `Missing or invalid ARCA client config fields: ${invalidFields.join(\", \")}`\n );\n }\n}\n\nfunction getInvalidWsaaSessionStoreFields(config: ArcaClientConfig): string[] {\n const store = config.wsaaSessionStore;\n if (store === undefined) {\n return [];\n }\n\n const invalidFields: string[] = [];\n if (typeof store.get !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.get\");\n }\n if (typeof store.set !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.set\");\n }\n if (store.delete !== undefined && typeof store.delete !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.delete\");\n }\n if (store.withLock !== undefined && typeof store.withLock !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.withLock\");\n }\n\n return invalidFields;\n}\n\nexport type ArcaServiceConfig = {\n namespace: string;\n endpoint: Record<ArcaEnvironment, string>;\n soapVersion: ArcaSoapVersion;\n soapActionBase: string;\n usesEmptySoapAction?: boolean;\n useLegacyTlsSecurityLevel0?: boolean;\n};\n\nexport const ARCA_WSAA_CONFIG: ArcaServiceConfig = {\n namespace: \"http://wsaa.view.sua.dvadac.desein.afip.gov\",\n endpoint: {\n production: \"https://wsaa.afip.gov.ar/ws/services/LoginCms\",\n test: \"https://wsaahomo.afip.gov.ar/ws/services/LoginCms\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"\",\n usesEmptySoapAction: true,\n};\n\nexport const ARCA_SERVICE_CONFIG: Record<ArcaServiceName, ArcaServiceConfig> = {\n wsaa: ARCA_WSAA_CONFIG,\n wsfe: {\n namespace: \"http://ar.gov.afip.dif.FEV1/\",\n endpoint: {\n production: \"https://servicios1.afip.gov.ar/wsfev1/service.asmx\",\n test: \"https://wswhomo.afip.gov.ar/wsfev1/service.asmx\",\n },\n soapVersion: \"1.2\",\n soapActionBase: \"http://ar.gov.afip.dif.FEV1/\",\n useLegacyTlsSecurityLevel0: true,\n },\n wsfex: {\n namespace: \"http://ar.gov.afip.dif.fexv1/\",\n endpoint: {\n production: \"https://servicios1.afip.gov.ar/wsfexv1/service.asmx\",\n test: \"https://wswhomo.afip.gov.ar/wsfexv1/service.asmx\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"http://ar.gov.afip.dif.fexv1/\",\n useLegacyTlsSecurityLevel0: true,\n },\n wsmtxca: {\n namespace: \"http://impl.service.wsmtxca.afip.gov.ar/service/\",\n endpoint: {\n production:\n \"https://serviciosjava.afip.gov.ar/wsmtxca/services/MTXCAService\",\n test: \"https://fwshomo.afip.gov.ar/wsmtxca/services/MTXCAService\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"http://impl.service.wsmtxca.afip.gov.ar/service/\",\n },\n \"padron-a5\": {\n namespace: \"http://a5.soap.ws.server.puc.sr/\",\n endpoint: {\n production:\n \"https://aws.afip.gov.ar/sr-padron/webservices/personaServiceA5\",\n test: \"https://awshomo.afip.gov.ar/sr-padron/webservices/personaServiceA5\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"\",\n usesEmptySoapAction: true,\n },\n \"padron-a13\": {\n namespace: \"http://a13.soap.ws.server.puc.sr/\",\n endpoint: {\n production:\n \"https://aws.afip.gov.ar/sr-padron/webservices/personaServiceA13\",\n test: \"https://awshomo.afip.gov.ar/sr-padron/webservices/personaServiceA13\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"\",\n usesEmptySoapAction: true,\n },\n};\n\nexport function getArcaServiceConfig(\n service: ArcaServiceName\n): ArcaServiceConfig {\n const serviceConfig = ARCA_SERVICE_CONFIG[service];\n if (!serviceConfig) {\n throw new ArcaConfigurationError(\n `Unsupported ARCA service configuration: ${service}`\n );\n }\n return serviceConfig;\n}\n\nexport function normalizeArcaClientConfig(\n config: ArcaClientConfig\n): ResolvedArcaClientConfig {\n const normalizedEnvironment =\n normalizeEnvironmentValue(String(config.environment)) ?? config.environment;\n const normalizedLoggerLevel = normalizeLogLevelValue(config.logger?.level);\n\n return {\n taxId: config.taxId?.trim() ?? \"\",\n certificatePem: config.certificatePem?.trim() ?? \"\",\n privateKeyPem: config.privateKeyPem?.trim() ?? \"\",\n environment: normalizedEnvironment ?? \"test\",\n ...(config.store === undefined ? {} : { store: config.store }),\n timeout: config.timeout ?? DEFAULT_ARCA_TIMEOUT_MS,\n retries: config.retries ?? DEFAULT_ARCA_RETRIES,\n retryDelay: config.retryDelay ?? DEFAULT_ARCA_RETRY_DELAY_MS,\n ...(config.logger === undefined\n ? {}\n : {\n logger: {\n ...config.logger,\n ...(normalizedLoggerLevel === undefined\n ? {}\n : { level: normalizedLoggerLevel }),\n },\n }),\n ...(config.wsaaSessionStore === undefined\n ? {}\n : { wsaaSessionStore: config.wsaaSessionStore }),\n };\n}\n\nfunction normalizeEnvironmentValue(value: string | undefined) {\n if (!value) {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n if (ARCA_ENVIRONMENTS.includes(normalized as ArcaEnvironment)) {\n return normalized as ArcaEnvironment;\n }\n\n return undefined;\n}\n\nfunction readEnv(\n env: ArcaClientConfigEnvironment,\n variableName: string\n): string | undefined {\n return env[variableName]?.trim() || undefined;\n}\n\nfunction normalizeLogLevelValue(value: string | undefined) {\n if (!value) {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n if (VALID_ARCA_LOG_LEVELS.includes(normalized as ArcaLogLevel)) {\n return normalized as ArcaLogLevel;\n }\n\n return value as ArcaLogLevel;\n}\n\nexport type ResolvedArcaClientConfig = ArcaClientConfig & {\n taxId: string;\n certificatePem: string;\n privateKeyPem: string;\n environment: ArcaEnvironment;\n};\n\nexport function discoverArcaClientConfig(\n config: ArcaClientOptions\n): ArcaClientConfig {\n const environment =\n config.environment ??\n (readEnv(process.env, ARCA_ENV_VARIABLES.environment) as\n | ArcaEnvironment\n | undefined);\n if (environment === undefined) {\n throw new ArcaConfigurationError(\n `environment is required: pass environment or set ${ARCA_ENV_VARIABLES.environment} to \"test\" or \"production\".`\n );\n }\n return {\n ...config,\n taxId: config.taxId ?? readEnv(process.env, ARCA_ENV_VARIABLES.taxId) ?? \"\",\n certificatePem:\n config.certificatePem ??\n readEnv(process.env, ARCA_ENV_VARIABLES.certificatePem) ??\n \"\",\n privateKeyPem:\n config.privateKeyPem ??\n readEnv(process.env, ARCA_ENV_VARIABLES.privateKeyPem) ??\n \"\",\n environment,\n };\n}\n\nfunction invalidCredentialFields(\n normalized: ResolvedArcaClientConfig\n): string[] {\n const invalidFields: string[] = [];\n if (!/^\\d{11}$/.test(normalized.taxId)) {\n invalidFields.push(normalized.taxId ? \"taxId\" : \"taxId (ARCA_TAX_ID)\");\n }\n\n if (!normalized.certificatePem.startsWith(\"-----BEGIN CERTIFICATE-----\")) {\n invalidFields.push(\n normalized.certificatePem\n ? \"certificatePem\"\n : \"certificatePem (ARCA_CERTIFICATE_PEM)\"\n );\n }\n\n if (\n !PRIVATE_KEY_PEM_PREFIXES.some((prefix) =>\n normalized.privateKeyPem.startsWith(prefix)\n )\n ) {\n invalidFields.push(\n normalized.privateKeyPem\n ? \"privateKeyPem\"\n : \"privateKeyPem (ARCA_PRIVATE_KEY_PEM)\"\n );\n }\n\n return invalidFields;\n}\n","import type { VoucherClass } from \"../constants\";\nimport { ArcaInputError } from \"../errors\";\nimport {\n arcaMinorUnitsToNumber,\n assertArcaMinorUnits,\n} from \"../internal/decimal\";\nimport { normalizeWsfeDateInput, type WsfeVoucherInput } from \"./wsfe\";\n\n/** Monetary values in the high-level API are integer minor units. */\nexport type Tribute = {\n id: number;\n description?: string;\n base: number;\n rate: number;\n amount: number;\n};\n/** An already-reviewed fiscal breakdown; no recalculation of historical VAT. */\nexport type VoucherAmounts = {\n net: number;\n vat: number;\n exempt?: number;\n untaxed?: number;\n vatRates?: readonly { id: number; base: number; amount: number }[];\n};\nexport type InvoiceFamily = \"ordinary\" | \"retention_legend\" | \"fce\";\nexport type IssuanceFields = {\n fce?: FceOptions;\n taxes?: readonly Tribute[];\n amounts?: VoucherAmounts;\n concept?: \"products\" | \"services\" | \"products_and_services\";\n dueDate?: import(\"./wsfe\").WsfeDateInput;\n paidInForeignCurrency?: boolean;\n optionalFields?: WsfeVoucherInput[\"optionalFields\"];\n buyers?: WsfeVoucherInput[\"buyers\"];\n activities?: WsfeVoucherInput[\"activities\"];\n};\n\n/** ARCA's concept id for each `concept` the facade takes. */\nexport const CONCEPT_IDS = {\n products: 1,\n services: 2,\n products_and_services: 3,\n} as const;\n\nexport const FAMILIES = {\n ordinary: { A: [1, 2, 3], B: [6, 7, 8], C: [11, 12, 13] },\n retention_legend: { A: [51, 52, 53] },\n fce: { A: [201, 202, 203], B: [206, 207, 208], C: [211, 212, 213] },\n} as const;\n\nexport function voucherFamily(type: number): {\n family: InvoiceFamily;\n voucherClass: VoucherClass;\n types: readonly number[];\n} {\n for (const [family, classes] of Object.entries(FAMILIES)) {\n for (const [voucherClass, types] of Object.entries(classes)) {\n if ((types as readonly number[]).includes(type)) {\n return {\n family: family as InvoiceFamily,\n voucherClass: voucherClass as VoucherClass,\n types,\n };\n }\n }\n }\n throw new ArcaInputError(\"Unsupported invoice or note type.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"voucherType\",\n expected: \"an invoice or note type the SDK issues\",\n });\n}\n\n/**\n * Export vouchers (19, 20, 21) report `family: \"export\"` and class `\"E\"`;\n * neither is an `issue()` input, where an export is chosen by `export`.\n */\nexport type VoucherTypeInfo = {\n family: InvoiceFamily | \"export\";\n voucherClass: VoucherClass | \"E\";\n kind: \"invoice\" | \"debit_note\" | \"credit_note\";\n};\n\nconst KINDS = [\"invoice\", \"debit_note\", \"credit_note\"] as const;\n/** Factura E, Nota de Débito E and Nota de Crédito E, in KINDS order. */\nexport const EXPORT_TYPES = [19, 20, 21] as const;\n\n/** What an ARCA voucher type the SDK issues is. Pure; throws for any other. */\nexport function describeVoucherType(voucherType: number): VoucherTypeInfo {\n const exportIndex = (EXPORT_TYPES as readonly number[]).indexOf(voucherType);\n if (exportIndex !== -1) {\n return {\n family: \"export\",\n voucherClass: \"E\",\n kind: KINDS[exportIndex] as VoucherTypeInfo[\"kind\"],\n };\n }\n const { family, voucherClass, types } = voucherFamily(voucherType);\n return {\n family,\n voucherClass,\n kind: KINDS[types.indexOf(voucherType)] as VoucherTypeInfo[\"kind\"],\n };\n}\nexport function invoiceType(\n family: InvoiceFamily,\n voucherClass: VoucherClass\n): number {\n const classes = FAMILIES[family];\n const types =\n classes &&\n (classes as Partial<Record<VoucherClass, readonly number[]>>)[voucherClass];\n if (!types) {\n throw new ArcaInputError(\"Invoice family does not support this class.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"family\",\n });\n }\n return types[0] as number;\n}\nexport function minor(value: number, field: string): number {\n return arcaMinorUnitsToNumber(assertArcaMinorUnits(value, field), field);\n}\nexport function applyIssuanceFields(\n data: WsfeVoucherInput,\n fields: IssuanceFields\n): void {\n if (fields.taxes !== undefined) {\n if (!Array.isArray(fields.taxes)) {\n throw new ArcaInputError(\"taxes must be an array\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"taxes\",\n });\n }\n data.taxes = fields.taxes.map((tax) => ({\n id: tax.id,\n description: tax.description,\n baseAmount: minor(tax.base, \"taxes.base\"),\n rate: tax.rate,\n amount: minor(tax.amount, \"taxes.amount\"),\n }));\n data.taxAmount = minor(tributeTotal(fields.taxes), \"taxes.total\");\n }\n if (fields.amounts) {\n Object.assign(data, reviewedHeaderAmounts(fields.amounts));\n }\n if (fields.concept) {\n data.concept = CONCEPT_IDS[fields.concept];\n }\n if (fields.dueDate) {\n data.paymentDueDate = fields.dueDate;\n }\n if (fields.paidInForeignCurrency !== undefined) {\n if (typeof fields.paidInForeignCurrency !== \"boolean\") {\n throw new ArcaInputError(\"paidInForeignCurrency must be boolean\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n });\n }\n data.sameCurrencyForeignCancellation = fields.paidInForeignCurrency\n ? \"S\"\n : \"N\";\n }\n for (const key of [\"optionalFields\", \"buyers\", \"activities\"] as const) {\n if (fields[key] !== undefined) {\n Object.assign(data, { [key]: structuredClone(fields[key]) });\n }\n }\n applyFceFields(data, fields.fce);\n}\n/** Tributes are outside the item arithmetic; they add to the total in cents. */\nexport function tributeTotal(taxes: readonly Tribute[]): number {\n return taxes.reduce((sum, tax) => sum + tax.amount, 0);\n}\n/** A reviewed breakdown becomes the header verbatim: no VAT is recomputed. */\nexport function reviewedHeaderAmounts(\n amounts: VoucherAmounts\n): Pick<\n WsfeVoucherInput,\n \"netAmount\" | \"vatAmount\" | \"exemptAmount\" | \"nonTaxableAmount\" | \"vatRates\"\n> {\n return {\n netAmount: minor(amounts.net, \"amounts.net\"),\n vatAmount: minor(amounts.vat, \"amounts.vat\"),\n exemptAmount: minor(amounts.exempt ?? 0, \"amounts.exempt\"),\n nonTaxableAmount: minor(amounts.untaxed ?? 0, \"amounts.untaxed\"),\n vatRates: amounts.vatRates?.map((rate) => ({\n id: rate.id,\n baseAmount: minor(rate.base, \"amounts.vatRates.base\"),\n amount: minor(rate.amount, \"amounts.vatRates.amount\"),\n })),\n };\n}\nexport const ISSUANCE_KEYS = [\n \"fce\",\n \"taxes\",\n \"amounts\",\n \"concept\",\n \"dueDate\",\n \"paidInForeignCurrency\",\n \"optionalFields\",\n \"buyers\",\n \"activities\",\n];\n\nexport function validateIssuanceFields(fields: IssuanceFields): void {\n validateRows(\n fields.taxes,\n \"taxes\",\n [\"id\", \"description\", \"base\", \"rate\", \"amount\"],\n (row) => {\n positiveId(row.id, \"taxes.id\");\n if (\n row.description !== undefined &&\n typeof row.description !== \"string\"\n ) {\n bad(\"taxes.description\");\n }\n minor(row.base as number, \"taxes.base\");\n minor(row.amount as number, \"taxes.amount\");\n if (\n typeof row.rate !== \"number\" ||\n !Number.isFinite(row.rate) ||\n row.rate < 0\n ) {\n bad(\"taxes.rate\");\n }\n }\n );\n if (fields.amounts !== undefined) {\n objectKeys(fields.amounts, \"amounts\", [\n \"net\",\n \"vat\",\n \"exempt\",\n \"untaxed\",\n \"vatRates\",\n ]);\n minor(fields.amounts.net, \"amounts.net\");\n minor(fields.amounts.vat, \"amounts.vat\");\n validateRows(\n fields.amounts.vatRates,\n \"amounts.vatRates\",\n [\"id\", \"base\", \"amount\"],\n (row) => {\n if (![3, 4, 5, 6, 8, 9].includes(row.id as number)) {\n bad(\"amounts.vatRates.id\");\n }\n minor(row.base as number, \"amounts.vatRates.base\");\n minor(row.amount as number, \"amounts.vatRates.amount\");\n }\n );\n const ids = fields.amounts.vatRates?.map((r) => r.id) ?? [];\n if (new Set(ids).size !== ids.length) {\n bad(\"amounts.vatRates\");\n }\n }\n validateRows(\n fields.optionalFields,\n \"optionalFields\",\n [\"id\", \"value\"],\n (row) => {\n if (\n typeof row.id !== \"string\" ||\n !/^\\d+$/.test(row.id) ||\n typeof row.value !== \"string\"\n ) {\n bad(\"optionalFields\");\n }\n }\n );\n validateRows(\n fields.buyers,\n \"buyers\",\n [\"documentType\", \"documentNumber\", \"percentage\"],\n (row) => {\n positiveId(row.documentType, \"buyers.documentType\");\n positiveId(row.documentNumber, \"buyers.documentNumber\");\n if (\n typeof row.percentage !== \"number\" ||\n !Number.isFinite(row.percentage) ||\n row.percentage <= 0 ||\n row.percentage > 100\n ) {\n bad(\"buyers.percentage\");\n }\n }\n );\n validateRows(fields.activities, \"activities\", [\"id\"], (row) =>\n positiveId(row.id, \"activities.id\")\n );\n if (\n fields.concept !== undefined &&\n ![\"products\", \"services\", \"products_and_services\"].includes(fields.concept)\n ) {\n bad(\"concept\");\n }\n if (fields.fce !== undefined) {\n objectKeys(fields.fce, \"fce\", [\n \"cbu\",\n \"alias\",\n \"transfer\",\n \"annulment\",\n \"reference\",\n ]);\n validateFceOptions(fields.fce);\n }\n normalizedFceAnnulment(fields);\n}\nfunction positiveId(value: unknown, field: string): void {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0) {\n bad(field);\n }\n}\nfunction bad(field: string): never {\n throw new ArcaInputError(`Invalid ${field}`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n });\n}\nfunction objectKeys(\n value: unknown,\n field: string,\n keys: readonly string[]\n): asserts value is Record<string, unknown> {\n if (\n !value ||\n typeof value !== \"object\" ||\n Array.isArray(value) ||\n Object.keys(value).some((key) => !keys.includes(key))\n ) {\n bad(field);\n }\n}\nfunction validateRows(\n value: unknown,\n field: string,\n keys: readonly string[],\n check: (row: Record<string, unknown>) => void\n): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n bad(field);\n }\n for (const row of value) {\n objectKeys(row, field, keys);\n check(row);\n }\n}\n\nexport function validateFiscalHeader(data: WsfeVoucherInput): void {\n const family = voucherFamily(data.voucherType);\n validateFceHeader(data);\n if (\n family.voucherClass === \"C\" &&\n (data.vatAmount !== 0 ||\n data.vatRates?.length ||\n data.exemptAmount !== 0 ||\n data.nonTaxableAmount !== 0)\n ) {\n bad(\"amounts\");\n }\n if (![1, 2, 3].includes(data.concept)) {\n bad(\"concept\");\n }\n const date = normalizeWsfeDateInput(data.voucherDate, \"date\");\n if (data.concept === 1 && (data.serviceStartDate || data.serviceEndDate)) {\n bad(\"service\");\n }\n if (data.concept === 2 || data.concept === 3) {\n if (\n !(data.serviceStartDate && data.serviceEndDate && data.paymentDueDate)\n ) {\n bad(\"service\");\n }\n const start = normalizeWsfeDateInput(data.serviceStartDate, \"service.from\");\n const end = normalizeWsfeDateInput(data.serviceEndDate, \"service.to\");\n if (start > end) {\n bad(\"service.to\");\n }\n }\n if (\n data.paymentDueDate &&\n normalizeWsfeDateInput(data.paymentDueDate, \"dueDate\") < date\n ) {\n bad(\"dueDate\");\n }\n if (\n data.currencyId === \"PES\" &&\n data.sameCurrencyForeignCancellation !== undefined\n ) {\n bad(\"paidInForeignCurrency\");\n }\n}\n\n/** FCE business fields; the SDK encodes each provider's different option layout. */\nexport type FceOptions = {\n cbu?: string;\n alias?: string;\n transfer?: \"ADC\" | \"SCA\";\n annulment?: boolean;\n reference?: string;\n};\nexport function applyFceFields(\n data: Pick<WsfeVoucherInput, \"voucherType\" | \"optionalFields\">,\n fce: FceOptions | undefined\n): void {\n if (fce === undefined) {\n return;\n }\n objectKeys(fce, \"fce\", [\n \"cbu\",\n \"alias\",\n \"transfer\",\n \"annulment\",\n \"reference\",\n ]);\n if (voucherFamily(data.voucherType).family !== \"fce\") {\n bad(\"fce\");\n }\n validateFceOptions(fce);\n normalizedFceAnnulment({ fce, optionalFields: data.optionalFields });\n const extra = [\n ...(fce.cbu === undefined ? [] : [{ id: \"2101\", value: fce.cbu }]),\n ...(fce.alias === undefined ? [] : [{ id: \"2102\", value: fce.alias }]),\n ...(fce.transfer === undefined ? [] : [{ id: \"27\", value: fce.transfer }]),\n ...(fce.annulment === undefined\n ? []\n : [{ id: \"22\", value: fce.annulment ? \"S\" : \"N\" }]),\n ...(fce.reference === undefined\n ? []\n : [{ id: \"23\", value: fce.reference }]),\n ];\n const options = [...(data.optionalFields ?? []), ...extra];\n if (new Set(options.map((o) => o.id)).size !== options.length) {\n bad(\"fce\");\n }\n data.optionalFields = options;\n}\n\n/** Reads the two accepted FCE annulment encodings and rejects ambiguity. */\nexport function normalizedFceAnnulment(\n fields: Pick<IssuanceFields, \"fce\" | \"optionalFields\">\n): boolean | undefined {\n const encoded = (fields.optionalFields ?? []).filter(\n (field) => field.id === \"22\"\n );\n if (encoded.length > 1) {\n bad(\"optionalFields\");\n }\n const encodedValue = encoded[0]?.value;\n if (encodedValue !== undefined && ![\"S\", \"N\"].includes(encodedValue)) {\n bad(\"fce.annulment\");\n }\n const direct = fields.fce?.annulment;\n if (direct !== undefined && encodedValue !== undefined) {\n throw new ArcaInputError(\n direct === (encodedValue === \"S\")\n ? \"FCE annulment is duplicated in fce and optionalFields.\"\n : \"FCE annulment conflicts between fce and optionalFields.\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"fce.annulment\" }\n );\n }\n return (\n direct ?? (encodedValue === undefined ? undefined : encodedValue === \"S\")\n );\n}\n\nfunction validateFceHeader(data: WsfeVoucherInput): void {\n const family = voucherFamily(data.voucherType);\n if (family.family === \"fce\") {\n const options = new Map(\n (data.optionalFields ?? []).map((o) => [o.id, o.value])\n );\n if (family.types[0] === data.voucherType) {\n if (!/^\\d{22}$/.test(options.get(\"2101\") ?? \"\") || options.has(\"22\")) {\n bad(\"fce.cbu\");\n }\n if (!data.paymentDueDate) {\n bad(\"dueDate\");\n }\n } else if (\n ![\"S\", \"N\"].includes(options.get(\"22\") ?? \"\") ||\n options.has(\"2101\") ||\n options.has(\"2102\") ||\n options.has(\"27\")\n ) {\n bad(\"fce.annulment\");\n }\n }\n}\n\nfunction validateFceOptions(fce: FceOptions): void {\n if (\n fce.cbu !== undefined &&\n (typeof fce.cbu !== \"string\" || !/^\\d{22}$/.test(fce.cbu))\n ) {\n bad(\"fce.cbu\");\n }\n if (\n fce.alias !== undefined &&\n (typeof fce.alias !== \"string\" || !/^[A-Za-z0-9.-]{6,20}$/.test(fce.alias))\n ) {\n bad(\"fce.alias\");\n }\n if (fce.transfer !== undefined && ![\"ADC\", \"SCA\"].includes(fce.transfer)) {\n bad(\"fce.transfer\");\n }\n if (fce.annulment !== undefined && typeof fce.annulment !== \"boolean\") {\n bad(\"fce.annulment\");\n }\n if (\n fce.reference !== undefined &&\n (typeof fce.reference !== \"string\" || !fce.reference.trim())\n ) {\n bad(\"fce.reference\");\n }\n}\n","import { ArcaInputError } from \"../errors\";\nimport { toIsoDate } from \"../internal/dates\";\nimport { assertArcaMinorUnits } from \"../internal/decimal\";\nimport { normalizeWsfeDateInput, type WsfeDateInput } from \"./wsfe\";\n\n/** Where every printed voucher's QR points, per ARCA's QR specification v1. */\nexport const ARCA_QR_URL = \"https://www.arca.gob.ar/fe/qr/\";\n\n/** What the QR of a printed voucher encodes. Amounts are minor units. */\nexport type ArcaQrInput = {\n /** The issuer's CUIT. */\n taxId: number | string;\n salesPoint: number;\n voucherType: number;\n number: number;\n /** `YYYY-MM-DD` or `YYYYMMDD`. */\n date: string;\n /** The total in the voucher's currency, in minor units. */\n total: number;\n /** ARCA currency id; `PES` when omitted. */\n currency?: string;\n /** Pesos per unit of `currency`; 1 for pesos. */\n exchangeRate?: number | string;\n /** The CAE, or the CAEA when `authorization` is `\"CAEA\"`. */\n cae: string;\n authorization?: \"CAE\" | \"CAEA\";\n /**\n * The receiver's document as sent to ARCA, type 99 and number 0 included\n * for an unidentified consumidor final. Omitted, the QR names no receiver.\n */\n document?: { type: number; number: number | string };\n};\n\n/** The JSON the QR carries, in the field order of ARCA's specification. */\nexport type ArcaQrPayload = {\n ver: 1;\n fecha: string;\n cuit: number;\n ptoVta: number;\n tipoCmp: number;\n nroCmp: number;\n importe: number;\n moneda: string;\n ctz: number;\n tipoDocRec?: number;\n nroDocRec?: number;\n tipoCodAut: \"E\" | \"A\";\n codAut: number;\n};\n\n/** Builds the URL a printed voucher's QR must encode. Pure, no I/O. */\nexport function arcaQrUrl(input: ArcaQrInput): string {\n return qrUrlForPayload(arcaQrPayload(input));\n}\n\n/** @internal The URL for a payload `arcaQrPayload()` already built. */\nexport function qrUrlForPayload(payload: ArcaQrPayload): string {\n const json = JSON.stringify(payload);\n return `${ARCA_QR_URL}?p=${Buffer.from(json, \"utf8\").toString(\"base64\")}`;\n}\n\nexport function arcaQrPayload(input: ArcaQrInput): ArcaQrPayload {\n const fecha = isoCalendarDate(input.date);\n const cuit = digits(input.taxId, \"taxId\", 11, 11);\n for (const [field, max] of [\n [\"salesPoint\", 99_999],\n [\"voucherType\", 999],\n [\"number\", 99_999_999],\n ] as const) {\n const value = input[field];\n if (!(Number.isSafeInteger(value) && value >= 1 && value <= max)) {\n invalid(field, `an integer from 1 through ${max}`);\n }\n }\n const total = Number(assertArcaMinorUnits(input.total, \"total\"));\n const currency = (input.currency ?? \"PES\").trim().toUpperCase();\n if (!/^[A-Z0-9]{3}$/.test(currency)) {\n invalid(\"currency\", \"a three-character ARCA currency id\");\n }\n const ctz = currency === \"PES\" ? 1 : exchangeRate(input.exchangeRate);\n const codAut = digits(input.cae, \"cae\", 14, 14);\n const document = receiverDocument(input.document);\n return {\n ver: 1,\n fecha,\n cuit,\n ptoVta: input.salesPoint,\n tipoCmp: input.voucherType,\n nroCmp: input.number,\n importe: Number((total / 100).toFixed(2)),\n moneda: currency,\n ctz,\n ...document,\n tipoCodAut: input.authorization === \"CAEA\" ? \"A\" : \"E\",\n codAut,\n };\n}\n\n/** `toIsoDate` only checks the shape, so the calendar is checked here too. */\nfunction isoCalendarDate(value: string): string {\n let compact: string;\n try {\n compact = normalizeWsfeDateInput(value as WsfeDateInput, \"date\");\n } catch {\n invalid(\"date\", \"a YYYY-MM-DD or YYYYMMDD calendar date\");\n }\n const iso = toIsoDate(compact);\n if (iso === undefined) {\n invalid(\"date\", \"a YYYY-MM-DD or YYYYMMDD calendar date\");\n }\n return iso;\n}\n\n/** Pesos per unit of a non-peso currency: the specification never defaults it. */\nfunction exchangeRate(value: ArcaQrInput[\"exchangeRate\"]): number {\n if (value === undefined) {\n invalid(\"exchangeRate\", \"a positive exchange rate for a non-peso currency\");\n }\n const rate = Number(value);\n if (!(Number.isFinite(rate) && rate > 0)) {\n invalid(\"exchangeRate\", \"a positive number\");\n }\n return rate;\n}\n\n/**\n * The specification marks both fields \"de corresponder\". ARCA's verification\n * page leaves an unidentified receiver blank without them, so the QR carries\n * the document as sent, 99 and 0 included.\n */\nfunction receiverDocument(\n document: ArcaQrInput[\"document\"]\n): Pick<ArcaQrPayload, \"tipoDocRec\" | \"nroDocRec\"> {\n if (document === undefined) {\n return {};\n }\n if (\n !(\n Number.isSafeInteger(document.type) &&\n document.type >= 0 &&\n document.type <= 99\n )\n ) {\n invalid(\"document.type\", \"an ARCA document type\");\n }\n const number = digits(document.number, \"document.number\", 0, 20);\n return { tipoDocRec: document.type, nroDocRec: number };\n}\n\nfunction digits(\n value: number | string,\n field: string,\n min: number,\n max: number\n): number {\n const text = String(value).trim();\n if (!/^\\d*$/.test(text) || text.length < min || text.length > max) {\n invalid(field, min === max ? `${min} digits` : `${min} to ${max} digits`);\n }\n if (text === \"\") {\n return 0;\n }\n const parsed = Number(text);\n if (!Number.isSafeInteger(parsed)) {\n invalid(field, \"a safe integer\");\n }\n return parsed;\n}\n\nfunction invalid(field: string, expected: string): never {\n throw new ArcaInputError(`qr.${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n","import { ARCA_VAT_RATES, type VoucherClass } from \"../constants\";\nimport { ArcaError, ArcaInputError } from \"../errors\";\nimport {\n arcaMinorUnitsToNumber,\n assertArcaMinorUnits,\n roundHalfEvenRatio,\n type SupportedVatRate,\n} from \"../internal/decimal\";\nimport type { WsmtxcaLine } from \"./issuance-wsmtxca\";\nimport type { WsfeVatRate, WsfeVoucherInput } from \"./wsfe\";\n\n/**\n * The line an item describes. WSFE ignores every field here and derives its\n * header from the money alone; WSMTXCA requires `description`, `quantity`,\n * `unit`, `unitPrice`, and `matrixCode` with `matrixUnits` unless `unit` is 97\n * or 99, and sends the line as it is. The line never carries its own VAT\n * amount: that follows from the item's `vat` and its money.\n */\nexport type ItemLine = {\n description?: string;\n quantity?: number;\n unit?: number;\n /** A major-unit decimal string with up to six decimals, unlike every other amount. */\n unitPrice?: string;\n discount?: number;\n /** Your own product code, at most 50 characters. */\n code?: string;\n /** The product's GTIN, or one of `ARCA_WSMTXCA_GENERIC_CODES`. */\n matrixCode?: string;\n /** Whole units of `matrixCode`, from 1 to 999999. */\n matrixUnits?: number;\n};\nexport type VatRate = SupportedVatRate | \"exempt\" | \"untaxed\";\nexport type VatItem = ItemLine &\n (\n | { net: number; gross?: never; amount?: never; vat: VatRate }\n | { gross: number; net?: never; amount?: never; vat: VatRate }\n );\nexport type AmountItem = ItemLine & {\n amount: number;\n vat?: never;\n net?: never;\n gross?: never;\n};\nexport type IssueAmounts = {\n computedTotal: number;\n sentTotal: number;\n vatAdjustment: number;\n};\n/** The class, not the issuer, fixes the accepted item shape and the arithmetic. */\nexport type WsfeAmountsInput = {\n voucherClass: VoucherClass;\n items: readonly (VatItem | AmountItem)[];\n total?: number;\n};\ntype ExactAmounts = Pick<\n WsfeVoucherInput,\n | \"totalAmount\"\n | \"netAmount\"\n | \"vatAmount\"\n | \"nonTaxableAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatRates\"\n>;\n\nconst RATES: Record<SupportedVatRate, { id: number; basisPoints: bigint }> = {\n 0: { id: ARCA_VAT_RATES.IVA_0, basisPoints: 0n },\n 2.5: { id: ARCA_VAT_RATES.IVA_2_5, basisPoints: 250n },\n 5: { id: ARCA_VAT_RATES.IVA_5, basisPoints: 500n },\n 10.5: { id: ARCA_VAT_RATES.IVA_10_5, basisPoints: 1050n },\n 21: { id: ARCA_VAT_RATES.IVA_21, basisPoints: 2100n },\n 27: { id: ARCA_VAT_RATES.IVA_27, basisPoints: 2700n },\n};\n\n/**\n * Pure integer money core. Amount fields are provider major units.\n * Invoices and credit notes share it: both resolve a class first.\n */\nexport function calculateWsfeAmounts(input: WsfeAmountsInput): {\n data: ExactAmounts;\n amounts: IssueAmounts;\n} {\n if (!Array.isArray(input.items) || input.items.length === 0) {\n invalidItem(\"items\", \"a non-empty array of items\");\n }\n const isVat = input.voucherClass === \"A\" || input.voucherClass === \"B\";\n if (!(isVat || input.voucherClass === \"C\")) {\n invalidItem(\"voucherClass\", \"A, B or C\");\n }\n const totals = collectItems(input.items, isVat);\n let net = totals.net;\n let vat = 0n;\n const { exempt, untaxed, groups } = totals;\n const vatRates: WsfeVatRate[] = [];\n // 10022: totalize by rate before rounding; never round each line.\n for (const [rate, group] of groups) {\n const { id, basisPoints } = RATES[rate];\n const netFromGross = roundHalfEvenRatio(\n group.gross * 10_000n,\n 10_000n + basisPoints\n );\n const base = group.net + netFromGross;\n const tax =\n roundHalfEvenRatio(group.net * basisPoints, 10_000n) +\n group.gross -\n netFromGross;\n if (base === 0n) {\n continue;\n }\n net += base;\n vat += tax;\n vatRates.push({\n id,\n baseAmount: arcaMinorUnitsToNumber(base, \"netAmount\"),\n amount: arcaMinorUnitsToNumber(tax, \"vatAmount\"),\n });\n }\n // 10047: class C has only ImpNeto; 10048: exact header decomposition.\n const computed = net + vat + exempt + untaxed;\n arcaMinorUnitsToNumber(computed, \"totalAmount\");\n const sent =\n input.total === undefined\n ? computed\n : assertArcaMinorUnits(input.total, \"total\");\n const adjustment = sent - computed;\n // 10023: the high-level API deliberately uses only the absolute cents-per-rate allowance.\n const allowance = BigInt(vatRates.length);\n if (\n adjustment < -allowance ||\n adjustment > allowance ||\n vat + adjustment < 0n\n ) {\n throw new ArcaInputError(\n \"total does not match the computed amount within the VAT allowance.\",\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: \"total\",\n expected: `${computed} minor units (at most ${allowance} minor units of VAT adjustment, with non-negative VAT)`,\n }\n );\n }\n return {\n data: {\n totalAmount: arcaMinorUnitsToNumber(sent, \"totalAmount\"),\n netAmount: arcaMinorUnitsToNumber(net, \"netAmount\"),\n vatAmount: arcaMinorUnitsToNumber(vat + adjustment, \"vatAmount\"),\n nonTaxableAmount: arcaMinorUnitsToNumber(untaxed, \"nonTaxableAmount\"),\n exemptAmount: arcaMinorUnitsToNumber(exempt, \"exemptAmount\"),\n taxAmount: 0,\n ...(isVat ? { vatRates } : {}),\n },\n amounts: {\n computedTotal: Number(computed),\n sentTotal: Number(sent),\n vatAdjustment: Number(adjustment),\n },\n };\n}\n\nfunction collectItems(\n items: readonly (VatItem | AmountItem)[],\n isVat: boolean\n) {\n let net = 0n;\n let exempt = 0n;\n let untaxed = 0n;\n const groups = new Map<SupportedVatRate, { net: bigint; gross: bigint }>();\n for (const [index, item] of items.entries()) {\n const path = `items[${index}]`;\n if (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n invalidItem(path, \"an item object\");\n }\n if (!isVat) {\n net += classCAmount(item, path);\n continue;\n }\n const { amount, field, rate } = vatItemAmount(item, path);\n if (rate === \"exempt\") {\n exempt += amount;\n continue;\n }\n if (rate === \"untaxed\") {\n untaxed += amount;\n continue;\n }\n const group = groups.get(rate) ?? { net: 0n, gross: 0n };\n group[field] += amount;\n groups.set(rate, group);\n }\n return { net, exempt, untaxed, groups };\n}\n\nfunction classCAmount(item: VatItem | AmountItem, path: string): bigint {\n if (\"vat\" in item || \"net\" in item || \"gross\" in item) {\n invalidItem(\"items\", \"amount items for a class C voucher\");\n }\n return assertArcaMinorUnits(item.amount as number, `${path}.amount`);\n}\n\nfunction vatItemAmount(item: VatItem | AmountItem, path: string) {\n if (\"amount\" in item || \"net\" in item === \"gross\" in item) {\n invalidItem(\n \"items\",\n \"exactly one of net or gross, and vat, for a class A or B voucher\"\n );\n }\n const field: \"net\" | \"gross\" = \"net\" in item ? \"net\" : \"gross\";\n const amount = assertArcaMinorUnits(\n item[field] as number,\n `${path}.${field}`\n );\n const rate = item.vat;\n if (\n rate !== \"exempt\" &&\n rate !== \"untaxed\" &&\n (typeof rate !== \"number\" || !Object.hasOwn(RATES, rate))\n ) {\n invalidItem(`${path}.vat`, \"0, 2.5, 5, 10.5, 21, 27, exempt, or untaxed\");\n }\n return { amount, field, rate };\n}\n\nfunction invalidItem(field: string, expected: string): never {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n\n/** WSMTXCA condition codes for the item rates WSFE has no rate id for. */\nconst UNTAXED_CONDITION = 1;\nconst EXEMPT_CONDITION = 2;\n\ntype LineDraft = {\n line: WsmtxcaLine;\n vat: bigint;\n amount: bigint;\n rate?: SupportedVatRate;\n field?: \"net\" | \"gross\";\n vatFormula?: { numerator: bigint; denominator: bigint };\n amountFormula: { numerator: bigint; denominator: bigint };\n};\n\nexport type WsmtxcaSettlement = {\n lines: WsmtxcaLine[];\n vatByCondition: ReadonlyMap<number, number>;\n};\n\n/**\n * Derives the WSMTXCA provider lines from the same items the header came from,\n * so the two can never describe different money. Per-line VAT is reconciled\n * against the grouped Half Even arithmetic of `calculateWsfeAmounts()`: the\n * rounding residual of a rate, and the header's VAT adjustment, land on lines\n * of that rate, so the lines sum to the header exactly. WSMTXCA authorizes\n * classes A and B only, so every item carries its `vat`.\n */\nexport function deriveWsmtxcaLines(\n input: WsfeAmountsInput,\n vatAdjustment: number\n): WsmtxcaLine[] {\n return deriveWsmtxcaSettlement(input, vatAdjustment).lines;\n}\n\n/** Also exposes the reconciled per-rate VAT needed by WSMTXCA subtotals. */\nexport function deriveWsmtxcaSettlement(\n input: WsfeAmountsInput,\n vatAdjustment: number\n): WsmtxcaSettlement {\n if (!Array.isArray(input.items) || input.items.length === 0) {\n invalidItem(\"items\", \"a non-empty array of items\");\n }\n const drafts: LineDraft[] = [];\n const groups = new Map<SupportedVatRate, { net: bigint; gross: bigint }>();\n for (const [index, item] of input.items.entries()) {\n const path = `items[${index}]`;\n if (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n invalidItem(path, \"an item object\");\n }\n drafts.push(lineDraft(item, path, groups));\n }\n reconcileGroups(drafts, groups);\n absorbAdjustment(drafts, BigInt(vatAdjustment));\n const lines = drafts.map(({ line, vat, amount }) => ({\n ...line,\n amount: Number(amount),\n ...(input.voucherClass === \"A\" ? { vatAmount: Number(vat) } : {}),\n }));\n const vatByCondition = new Map<number, number>();\n for (const draft of drafts) {\n if (draft.rate === undefined) {\n continue;\n }\n const condition = RATES[draft.rate].id;\n vatByCondition.set(\n condition,\n (vatByCondition.get(condition) ?? 0) + Number(draft.vat)\n );\n }\n return { lines, vatByCondition };\n}\n\nfunction lineDraft(\n item: VatItem | AmountItem,\n path: string,\n groups: Map<SupportedVatRate, { net: bigint; gross: bigint }>\n): LineDraft {\n const line = assertItemLine(item, path);\n const { amount, field, rate } = vatItemAmount(item, path);\n if (rate === \"exempt\" || rate === \"untaxed\") {\n return {\n line: {\n ...line,\n vatCondition: rate === \"exempt\" ? EXEMPT_CONDITION : UNTAXED_CONDITION,\n amount: 0,\n },\n vat: 0n,\n amount,\n amountFormula: { numerator: amount, denominator: 1n },\n };\n }\n const { id, basisPoints } = RATES[rate];\n const group = groups.get(rate) ?? { net: 0n, gross: 0n };\n group[field] += amount;\n groups.set(rate, group);\n // A gross line already includes its VAT; a net line adds it.\n const vat =\n field === \"gross\"\n ? amount - roundHalfEvenRatio(amount * 10_000n, 10_000n + basisPoints)\n : roundHalfEvenRatio(amount * basisPoints, 10_000n);\n return {\n line: { ...line, vatCondition: id, amount: 0 },\n vat,\n amount: field === \"gross\" ? amount : amount + vat,\n rate,\n field,\n vatFormula:\n field === \"gross\"\n ? {\n numerator: amount * basisPoints,\n denominator: 10_000n + basisPoints,\n }\n : { numerator: amount * basisPoints, denominator: 10_000n },\n amountFormula:\n field === \"gross\"\n ? { numerator: amount, denominator: 1n }\n : {\n numerator: amount * (10_000n + basisPoints),\n denominator: 10_000n,\n },\n };\n}\n\n/**\n * The header totalizes by rate before rounding, so the line VATs of one rate\n * can miss the rate's VAT by cents. The difference is spread back over the\n * lines of that rate, a cent at a time, so no line ends with negative VAT.\n */\nfunction reconcileGroups(\n drafts: readonly LineDraft[],\n groups: ReadonlyMap<SupportedVatRate, { net: bigint; gross: bigint }>\n): void {\n for (const [rate, group] of groups) {\n const { basisPoints } = RATES[rate];\n const netFromGross = roundHalfEvenRatio(\n group.gross * 10_000n,\n 10_000n + basisPoints\n );\n settle(\n drafts,\n (draft) => draft.rate === rate && draft.field === \"net\",\n roundHalfEvenRatio(group.net * basisPoints, 10_000n) -\n sumVat(drafts, (d) => d.rate === rate && d.field === \"net\"),\n true\n );\n // A gross line's own amount is fixed: its VAT moves inside that amount.\n settle(\n drafts,\n (draft) => draft.rate === rate && draft.field === \"gross\",\n group.gross -\n netFromGross -\n sumVat(drafts, (d) => d.rate === rate && d.field === \"gross\"),\n false\n );\n }\n}\n\nfunction sumVat(\n drafts: readonly LineDraft[],\n of: (draft: LineDraft) => boolean\n): bigint {\n return drafts.reduce((sum, draft) => (of(draft) ? sum + draft.vat : sum), 0n);\n}\n\n/**\n * Moves `amount` cents of VAT across matching lines, one at a time. A move\n * must keep VAT non-negative and both line formulas within ARCA's absolute\n * one-cent tolerance.\n */\nfunction settle(\n drafts: readonly LineDraft[],\n of: (draft: LineDraft) => boolean,\n amount: bigint,\n movesItem: boolean\n): void {\n let remaining = amount;\n const targets = drafts.filter(of);\n let cursor = 0;\n while (remaining !== 0n) {\n const step = remaining > 0n ? 1n : -1n;\n let target: LineDraft | undefined;\n for (let offset = 0; offset < targets.length; offset++) {\n const index = (cursor + offset) % targets.length;\n const candidate = targets[index];\n if (candidate && canMove(candidate, step, movesItem)) {\n target = candidate;\n cursor = (index + 1) % targets.length;\n break;\n }\n }\n if (target === undefined) {\n throw new ArcaError(\n \"The derived WSMTXCA VAT does not fit its lines. This is an SDK invariant failure.\",\n \"ARCA_ISSUE_INVARIANT\"\n );\n }\n applyMove(target, step, movesItem);\n remaining -= step;\n }\n}\n\nfunction canMove(draft: LineDraft, step: bigint, movesItem: boolean): boolean {\n const vat = draft.vat + step;\n if (vat < 0n || (draft.rate === 0 && vat !== 0n)) {\n return false;\n }\n if (\n draft.vatFormula !== undefined &&\n !withinAbsoluteCent(vat, draft.vatFormula)\n ) {\n return false;\n }\n return (\n !movesItem || withinAbsoluteCent(draft.amount + step, draft.amountFormula)\n );\n}\n\nfunction withinAbsoluteCent(\n value: bigint,\n formula: { numerator: bigint; denominator: bigint }\n): boolean {\n const difference = value * formula.denominator - formula.numerator;\n return (difference < 0n ? -difference : difference) <= formula.denominator;\n}\n\nfunction applyMove(draft: LineDraft, step: bigint, movesItem: boolean): void {\n draft.vat += step;\n if (movesItem) {\n draft.amount += step;\n }\n}\n\n/**\n * An asserted `total` shifts at most one eligible line in each positive rate.\n * A zero-rate line never absorbs VAT, and a total that cannot fit the item\n * formulas is rejected before WSMTXCA sees it.\n */\nfunction absorbAdjustment(drafts: readonly LineDraft[], adjustment: bigint) {\n if (adjustment === 0n) {\n return;\n }\n const step = adjustment > 0n ? 1n : -1n;\n let remaining = adjustment;\n const rates = [\n ...new Set(\n drafts\n .map((draft) => draft.rate)\n .filter(\n (rate): rate is SupportedVatRate => rate !== undefined && rate > 0\n )\n ),\n ];\n for (const rate of rates) {\n const target = drafts.find(\n (draft) => draft.rate === rate && canMove(draft, step, true)\n );\n if (target === undefined) {\n continue;\n }\n applyMove(target, step, true);\n remaining -= step;\n if (remaining === 0n) {\n return;\n }\n }\n throw new ArcaInputError(\n \"total cannot be reconciled with WSMTXCA item formulas within ARCA's tolerance.\",\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: \"total\",\n }\n );\n}\n\nconst ITEM_KEYS = [\n \"net\",\n \"gross\",\n \"amount\",\n \"vat\",\n \"description\",\n \"quantity\",\n \"unit\",\n \"unitPrice\",\n \"discount\",\n \"code\",\n \"matrixCode\",\n \"matrixUnits\",\n];\n\n/** WSMTXCA needs the line fields on every item; the index names the offender. */\nfunction assertItemLine(\n item: VatItem | AmountItem,\n path: string\n): Omit<WsmtxcaLine, \"amount\" | \"vatAmount\" | \"vatCondition\"> {\n assertRequiredLineFields(item, path);\n for (const key of [\"code\", \"matrixCode\"] as const) {\n if (item[key] !== undefined && typeof item[key] !== \"string\") {\n invalidItem(`${path}.${key}`, \"a string\");\n }\n }\n assertMatrixFields(item, path);\n return {\n ...(item.matrixUnits === undefined\n ? {}\n : { matrixUnits: item.matrixUnits }),\n ...(item.matrixCode === undefined ? {} : { matrixCode: item.matrixCode }),\n ...(item.code === undefined ? {} : { code: item.code }),\n description: item.description as string,\n quantity: item.quantity as number,\n unit: item.unit as number,\n unitPrice: item.unitPrice as string,\n discount: Number(\n assertArcaMinorUnits(item.discount ?? 0, `${path}.discount`)\n ),\n };\n}\n\n/** Units ARCA exempts from the matrix code: 97 (señas) and 99 (bonificación). */\nconst MATRIX_EXEMPT_UNITS = new Set([97, 99]);\n\n/**\n * WSMTXCA rules 500-505 and 520: every line but units 97 and 99 carries a\n * GTIN or generic code with whole matrix units, and the two travel together.\n */\nfunction assertMatrixFields(item: VatItem | AmountItem, path: string): void {\n const { code, matrixCode, matrixUnits, unit } = item;\n if (code !== undefined && code.length > 50) {\n invalidItem(`${path}.code`, \"at most 50 characters\");\n }\n if (matrixCode !== undefined && matrixCode.trim() === \"\") {\n invalidItem(`${path}.matrixCode`, \"a GTIN or ARCA generic code\");\n }\n if (\n matrixUnits !== undefined &&\n !(\n Number.isInteger(matrixUnits) &&\n matrixUnits >= 1 &&\n matrixUnits <= 999_999\n )\n ) {\n invalidItem(`${path}.matrixUnits`, \"a whole number from 1 to 999999\");\n }\n if ((matrixCode === undefined) !== (matrixUnits === undefined)) {\n invalidItem(\n matrixCode === undefined ? `${path}.matrixCode` : `${path}.matrixUnits`,\n \"matrixCode and matrixUnits together\"\n );\n }\n if (matrixCode === undefined && !MATRIX_EXEMPT_UNITS.has(unit as number)) {\n invalidItem(\n `${path}.matrixCode`,\n \"a GTIN or ARCA generic code with matrixUnits, unless unit is 97 or 99\"\n );\n }\n}\n\nfunction assertRequiredLineFields(\n item: VatItem | AmountItem,\n path: string\n): void {\n for (const key of Object.keys(item)) {\n if (!ITEM_KEYS.includes(key)) {\n invalidItem(`${path}.${key}`, \"a supported item field\");\n }\n }\n const { description, quantity, unit, unitPrice } = item;\n if (typeof description !== \"string\" || description.trim() === \"\") {\n invalidItem(`${path}.description`, \"a non-empty description\");\n }\n if (!Number.isFinite(quantity) || (quantity as number) <= 0) {\n invalidItem(`${path}.quantity`, \"a positive quantity\");\n }\n if (!Number.isInteger(unit) || (unit as number) < 0) {\n invalidItem(`${path}.unit`, \"an ARCA unit of measure code\");\n }\n if (typeof unitPrice !== \"string\" || !/^\\d+(\\.\\d{1,6})?$/.test(unitPrice)) {\n invalidItem(\n `${path}.unitPrice`,\n \"a major-unit decimal string with at most six decimals\"\n );\n }\n}\n","import {\n ARCA_CURRENCY_IDS,\n ARCA_DOCUMENT_TYPES,\n ARCA_FINAL_CONSUMER_IDENTIFICATION_THRESHOLD_MINOR_UNITS,\n ARCA_INVOICE_CLASS_BY_ISSUER,\n ARCA_ISSUER_CONDITION_IDS,\n ARCA_RECEIVER_CONDITION_IDS,\n ARCA_VOUCHER_TYPES,\n type IssuerCondition,\n type IssuerConditionId,\n type ReceiverCondition,\n type VoucherClass,\n} from \"../constants\";\nimport { ArcaError, ArcaInputError, type VoucherDateWindow } from \"../errors\";\nimport { toIsoDate } from \"../internal/dates\";\nimport {\n normalizeArcaAmountToMinorUnits,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport {\n applyIssuanceFields,\n CONCEPT_IDS,\n EXPORT_TYPES,\n FAMILIES,\n type InvoiceFamily,\n ISSUANCE_KEYS,\n type IssuanceFields,\n invoiceType,\n minor,\n reviewedHeaderAmounts,\n type Tribute,\n tributeTotal,\n type VoucherAmounts,\n validateFiscalHeader,\n validateIssuanceFields,\n voucherFamily,\n} from \"./issuance-fields\";\nimport {\n normalizeWsfeDateInput,\n normalizeWsfeVoucherInput,\n type WsfeDateInput,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport {\n type AmountItem,\n calculateWsfeAmounts,\n type IssueAmounts,\n type VatItem,\n type WsfeAmountsInput,\n} from \"./wsfe-amounts\";\n\nexport type Receiver =\n | {\n condition: number;\n cuit?: string | number;\n dni?: string | number;\n document?: { type: number; number: string | number };\n }\n | {\n condition: \"consumidor_final\";\n cuit?: number | string;\n dni?: number | string;\n }\n | {\n condition: Exclude<ReceiverCondition, \"consumidor_final\">;\n cuit: number | string;\n dni?: never;\n };\nexport type IssueCommon = IssuanceFields & {\n family?: InvoiceFamily;\n salesPoint: number;\n to: Receiver;\n total?: number;\n date?: WsfeDateInput;\n currency?: \"ARS\" | \"USD\" | { id: string };\n exchangeRate?: string;\n service?: { from: WsfeDateInput; to: WsfeDateInput; dueDate: WsfeDateInput };\n};\nexport type IssueInput = IssueCommon &\n (\n | {\n issuer: \"responsable_inscripto\" | 1;\n items: readonly VatItem[];\n amounts?: never;\n }\n | {\n issuer: \"monotributo\" | \"exento\" | \"no_alcanzado\" | 4 | 6 | 15;\n items: readonly AmountItem[];\n amounts?: never;\n }\n | {\n issuer: IssuerCondition | IssuerConditionId;\n amounts: import(\"./issuance-fields\").VoucherAmounts;\n items?: never;\n }\n );\n\nconst INVOICE_TYPES = {\n A: ARCA_VOUCHER_TYPES.FACTURA_A,\n B: ARCA_VOUCHER_TYPES.FACTURA_B,\n C: ARCA_VOUCHER_TYPES.FACTURA_C,\n};\n\n/** No I/O: all caller validation finishes before the next-number read. */\nexport function deriveWsfeInvoice(\n input: IssueInput,\n now = new Date()\n): {\n data: WsfeVoucherInput;\n voucherClass: VoucherClass;\n amounts: IssueAmounts;\n /** The items the header came from, so provider lines derive from the same money. */\n lineSource?: WsfeAmountsInput;\n} {\n assertIssueObject(input, \"input\");\n assertIssueKeys(\n input,\n [\n ...ISSUANCE_KEYS,\n \"family\",\n \"issuer\",\n \"items\",\n \"salesPoint\",\n \"to\",\n \"total\",\n \"date\",\n \"currency\",\n \"exchangeRate\",\n \"service\",\n ],\n \"input\"\n );\n validateIssuanceFields(input);\n if (input.amounts !== undefined && input.items !== undefined) {\n invalid(\"amounts\", \"used instead of items, never with items\");\n }\n const issuer = issuerCondition(input.issuer);\n assertSalesPoint(input.salesPoint);\n const receiver = deriveReceiver(input.to);\n const voucherClass = resolveInvoiceClass(issuer, input.to.condition);\n const lineSource: WsfeAmountsInput | undefined = input.amounts\n ? undefined\n : {\n voucherClass,\n items: input.items,\n total:\n input.total === undefined\n ? undefined\n : input.total - tributeTotal(input.taxes ?? []),\n };\n const { data: amountsData, amounts } =\n lineSource === undefined\n ? reviewedInvoiceAmounts(input.amounts as VoucherAmounts, input.taxes)\n : calculateWsfeAmounts(lineSource);\n const currency = deriveCurrency(input);\n const voucherDate = normalizeWsfeDateInput(\n input.date === undefined ? buenosAiresDate(now) : input.date,\n \"date\"\n ) as WsfeDateInput;\n const data: WsfeVoucherInput = {\n salesPoint: input.salesPoint,\n voucherType:\n input.family === undefined\n ? INVOICE_TYPES[voucherClass]\n : invoiceType(input.family, voucherClass),\n voucherDate,\n ...receiver,\n ...currency,\n ...amountsData,\n ...deriveService(input.service, voucherDate),\n };\n applyIssuanceFields(data, input);\n // Tributes reach the header after the item arithmetic, so the sent total is\n // reconciled from the header itself.\n const headerTotal = Number(\n normalizeArcaAmountToMinorUnits(data.netAmount, \"net\") +\n normalizeArcaAmountToMinorUnits(data.vatAmount, \"vat\") +\n normalizeArcaAmountToMinorUnits(data.exemptAmount, \"exempt\") +\n normalizeArcaAmountToMinorUnits(data.nonTaxableAmount, \"untaxed\") +\n normalizeArcaAmountToMinorUnits(data.taxAmount, \"tax\")\n );\n const reviewedTotal = input.amounts ? input.total : undefined;\n data.totalAmount =\n reviewedTotal === undefined\n ? headerTotal / 100\n : minor(reviewedTotal, \"total\");\n amounts.computedTotal += headerTotal - amounts.sentTotal;\n amounts.sentTotal = reviewedTotal ?? headerTotal;\n if (\n receiver.receiverVatConditionId === 5 &&\n receiver.documentType === ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL\n ) {\n const [whole, fraction = \"\"] = currency.exchangeRate.split(\".\");\n const rate = BigInt(whole) * 1_000_000n + BigInt(fraction.padEnd(6, \"0\"));\n // Compare exact peso equivalents; rounding below the threshold must not hide it.\n if (\n BigInt(amounts.sentTotal) * rate >=\n ARCA_FINAL_CONSUMER_IDENTIFICATION_THRESHOLD_MINOR_UNITS * 1_000_000n\n ) {\n throw new ArcaInputError(\n \"The final consumer must be identified for this amount.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"to\",\n expected:\n \"cuit or dni for operations at or above ARS 10,000,000 (RG 5866)\",\n }\n );\n }\n }\n validateFiscalHeader(data);\n try {\n normalizeWsfeVoucherInput(data);\n } catch (cause) {\n if (cause instanceof ArcaInputError) {\n throw cause;\n }\n throw new ArcaError(\n \"The derived invoice failed WSFE validation. This is an SDK invariant failure.\",\n \"ARCA_ISSUE_INVARIANT\",\n { cause }\n );\n }\n return {\n data,\n voucherClass,\n amounts,\n ...(lineSource === undefined ? {} : { lineSource }),\n };\n}\n\ntype HeaderAmounts = Pick<\n WsfeVoucherInput,\n | \"totalAmount\"\n | \"netAmount\"\n | \"vatAmount\"\n | \"nonTaxableAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatRates\"\n>;\n/**\n * Reviewed mode: the caller's breakdown and tributes are the header as given.\n * Nothing is recomputed, so there is never a VAT adjustment; an explicit\n * `total` is applied by the caller of this function and is not rewritten here.\n * Invoices and notes share it, so both derive a reviewed header the same way.\n */\nexport function reviewedInvoiceAmounts(\n amounts: VoucherAmounts,\n taxes: readonly Tribute[] | undefined\n): { data: HeaderAmounts; amounts: IssueAmounts } {\n const taxTotal = taxes === undefined ? 0 : tributeTotal(taxes);\n const total =\n amounts.net +\n amounts.vat +\n (amounts.exempt ?? 0) +\n (amounts.untaxed ?? 0) +\n taxTotal;\n return {\n data: {\n totalAmount: minor(total, \"total\"),\n taxAmount: minor(taxTotal, \"taxes.total\"),\n ...reviewedHeaderAmounts(amounts),\n },\n amounts: { computedTotal: total, sentTotal: total, vatAdjustment: 0 },\n };\n}\n\n/** The name of an issuer condition given as its ARCA identifier, if one is. */\nexport function issuerConditionName(\n issuer: unknown\n): IssuerCondition | undefined {\n return (Object.keys(ARCA_ISSUER_CONDITION_IDS) as IssuerCondition[]).find(\n (condition) => ARCA_ISSUER_CONDITION_IDS[condition] === issuer\n );\n}\n\n/** The issuer's condition by name, given its name or its ARCA identifier. */\nfunction issuerCondition(issuer: unknown): IssuerCondition {\n const name = issuerConditionName(issuer);\n if (name !== undefined) {\n return name;\n }\n if (\n typeof issuer !== \"string\" ||\n !Object.hasOwn(ARCA_ISSUER_CONDITION_IDS, issuer)\n ) {\n invalid(\n \"issuer\",\n \"responsable_inscripto, monotributo, exento, no_alcanzado, or their ARCA ids 1, 6, 4, 15\"\n );\n }\n return issuer as IssuerCondition;\n}\n\nfunction assertSalesPoint(salesPoint: number) {\n if (\n !Number.isSafeInteger(salesPoint) ||\n salesPoint < 1 ||\n salesPoint > 99_999\n ) {\n invalid(\"salesPoint\", \"an integer from 1 through 99999\");\n }\n}\n\n/** Class resolution: the issuer's condition and the receiver's condition fix it. */\nfunction resolveInvoiceClass(\n issuer: IssuerCondition,\n condition: ReceiverCondition | number\n): VoucherClass {\n if (typeof condition === \"number\") {\n return issuer === \"responsable_inscripto\"\n ? [1, 6, 13, 16].includes(condition)\n ? \"A\"\n : \"B\"\n : \"C\";\n }\n return ARCA_INVOICE_CLASS_BY_ISSUER[issuer][condition];\n}\n\nfunction deriveReceiver(to: Receiver) {\n assertIssueObject(to, \"to\");\n assertIssueKeys(to, [\"condition\", \"cuit\", \"dni\", \"document\"], \"to\");\n if (typeof to.condition === \"number\") {\n return deriveNumericReceiver(\n to as Extract<Receiver, { condition: number }>\n );\n }\n if (\n typeof to.condition !== \"string\" ||\n !Object.hasOwn(ARCA_RECEIVER_CONDITION_IDS, to.condition)\n ) {\n invalid(\"to.condition\", \"one of the five supported receiver conditions\");\n }\n if (to.cuit !== undefined && to.dni !== undefined) {\n invalid(\"to\", \"either cuit or dni, never both\");\n }\n if (to.condition !== \"consumidor_final\" && to.cuit === undefined) {\n throw new ArcaInputError(\n \"to.cuit is required for this receiver (WSFE 10063 for class A).\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"to.cuit\",\n expected: \"an 11-digit CUIT\",\n }\n );\n }\n const documentType =\n to.cuit === undefined\n ? to.dni === undefined\n ? ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL\n : ARCA_DOCUMENT_TYPES.DNI\n : ARCA_DOCUMENT_TYPES.CUIT;\n // WSFE DocNro is Long(11); do not impose an undocumented DNI-only width.\n const documentNumber =\n to.cuit === undefined\n ? to.dni === undefined\n ? 0\n : issueDocumentNumber(to.dni, \"to.dni\", 1, 11)\n : issueDocumentNumber(to.cuit, \"to.cuit\", 11, 11);\n return {\n documentType,\n documentNumber,\n receiverVatConditionId: ARCA_RECEIVER_CONDITION_IDS[to.condition],\n };\n}\n\nexport function issueDocumentNumber(\n value: unknown,\n field: string,\n min: number,\n max: number\n): number {\n if (typeof value !== \"number\" && typeof value !== \"string\") {\n invalid(field, `a positive document number with ${min} to ${max} digits`);\n }\n const text = String(value);\n if (\n !/^\\d+$/.test(text) ||\n text.length < min ||\n text.length > max ||\n !Number.isSafeInteger(Number(text)) ||\n Number(text) <= 0\n ) {\n invalid(field, `a positive document number with ${min} to ${max} digits`);\n }\n return Number(text);\n}\n\nfunction deriveCurrency(input: IssueCommon) {\n const currency = input.currency === undefined ? \"ARS\" : input.currency;\n if (typeof currency === \"object\" && currency !== null) {\n assertIssueKeys(currency, [\"id\"], \"currency\");\n if (!/^[A-Z0-9]{3}$/.test(currency.id)) {\n invalid(\"currency.id\", \"a three-character ARCA currency code\");\n }\n if (input.exchangeRate === undefined) {\n invalid(\"exchangeRate\", \"an explicit rate for this currency\");\n }\n return {\n currencyId: currency.id,\n exchangeRate: serializeArcaExchangeRate(\n input.exchangeRate,\n \"exchangeRate\"\n ),\n };\n }\n if (currency !== \"ARS\" && currency !== \"USD\") {\n invalid(\"currency\", \"ARS or USD\");\n }\n if (\n input.exchangeRate !== undefined &&\n typeof input.exchangeRate !== \"string\"\n ) {\n invalid(\"exchangeRate\", \"a decimal string\");\n }\n if (currency === \"USD\" && input.exchangeRate === undefined) {\n throw new ArcaInputError(\"exchangeRate is required for USD.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"exchangeRate\",\n expected: \"a positive decimal string\",\n });\n }\n const exchangeRate = serializeArcaExchangeRate(\n input.exchangeRate ?? \"1\",\n \"exchangeRate\"\n );\n if (currency === \"ARS\" && exchangeRate !== \"1\") {\n throw new ArcaInputError(\"exchangeRate must be 1 for ARS.\", {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"1 for ARS\",\n });\n }\n return { currencyId: ARCA_CURRENCY_IDS[currency], exchangeRate };\n}\n\nfunction deriveService(service: IssueCommon[\"service\"], date: WsfeDateInput) {\n if (service === undefined) {\n return { concept: 1 };\n }\n assertIssueObject(service, \"service\");\n assertIssueKeys(service, [\"from\", \"to\", \"dueDate\"], \"service\");\n for (const field of [\"from\", \"to\", \"dueDate\"] as const) {\n if (service[field] === undefined) {\n throw new ArcaInputError(`service.${field} is required.`, {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: `service.${field}`,\n expected: \"a calendar date\",\n });\n }\n }\n const serviceStartDate = normalizeWsfeDateInput(\n service.from,\n \"service.from\"\n ) as WsfeDateInput;\n const serviceEndDate = normalizeWsfeDateInput(\n service.to,\n \"service.to\"\n ) as WsfeDateInput;\n const paymentDueDate = normalizeWsfeDateInput(\n service.dueDate,\n \"service.dueDate\"\n ) as WsfeDateInput;\n if (serviceEndDate < serviceStartDate) {\n invalid(\"service.to\", \"a date on or after service.from\");\n }\n if (paymentDueDate < date) {\n invalid(\"service.dueDate\", \"a date on or after date\");\n }\n return { concept: 2, serviceStartDate, serviceEndDate, paymentDueDate };\n}\n\nexport function buenosAiresDate(now: Date): WsfeDateInput {\n const parts = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone: \"America/Argentina/Buenos_Aires\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n }).formatToParts(now);\n return [\"year\", \"month\", \"day\"]\n .map((part) => parts.find((entry) => entry.type === part)?.value)\n .join(\"\") as WsfeDateInput;\n}\n\nconst FCE_TYPES: readonly (readonly number[])[] = Object.values(FAMILIES.fce);\nconst FCE_INVOICE_TYPES = FCE_TYPES.map(([invoice]) => invoice);\nconst FCE_NOTE_TYPES = FCE_TYPES.flatMap(([, ...notes]) => notes);\n\nexport type VoucherDateWindowInput = {\n voucherType: number;\n /**\n * What the voucher bills; `\"products\"` when omitted, as in `issue()`. For\n * an export voucher (19, 20, 21), `\"services\"` is an export of services.\n */\n concept?: NonNullable<IssuanceFields[\"concept\"]>;\n /**\n * The service that will authorize it; `\"wsfe\"` when omitted. Omit it for\n * an export voucher, which WSFEX always authorizes.\n */\n service?: \"wsfe\" | \"wsmtxca\";\n /** When it will be sent; its day in Argentina anchors the window. */\n now?: Date;\n};\n\n/**\n * The dates ARCA accepts for a voucher sent now, the same window `issue()`\n * checks before any call. Pure, no I/O. ARCA still rejects a date before the\n * last voucher of the same type and sales point.\n */\nexport function voucherDateWindow(\n input: VoucherDateWindowInput\n): VoucherDateWindow {\n assertIssueObject(input, \"input\");\n assertIssueKeys(\n input,\n [\"voucherType\", \"concept\", \"service\", \"now\"],\n \"input\",\n \"voucherDateWindow()\"\n );\n const concept = input.concept ?? \"products\";\n if (!Object.hasOwn(CONCEPT_IDS, concept)) {\n invalid(\"concept\", \"products, services, or products_and_services\");\n }\n const service = input.service ?? \"wsfe\";\n if (service !== \"wsfe\" && service !== \"wsmtxca\") {\n invalid(\"service\", \"wsfe or wsmtxca\");\n }\n const now = input.now ?? new Date();\n if (!(now instanceof Date) || Number.isNaN(now.getTime())) {\n invalid(\"now\", \"a valid Date\");\n }\n if ((EXPORT_TYPES as readonly number[]).includes(input.voucherType)) {\n if (input.service !== undefined) {\n invalid(\"service\", \"absent: export vouchers always use WSFEX\");\n }\n // WSFEX rule 1500: only an export of services stays within the month.\n const { from, to } = exportDateWindow(\n concept === \"services\",\n buenosAiresDate(now)\n );\n return { from: isoDay(from), to: isoDay(to) };\n }\n voucherFamily(input.voucherType);\n const { from, to } = dateWindow(\n { concept: CONCEPT_IDS[concept], voucherType: input.voucherType },\n service,\n buenosAiresDate(now)\n );\n return { from: isoDay(from), to: isoDay(to) };\n}\n\n/**\n * ARCA only accepts a voucher dated near the day it is sent (WSFE 10016,\n * WSMTXCA 103): products 5 days either side without leaving the month,\n * services 10. On WSFE an FCE invoice also stays within 5 days before and 1\n * after, and an FCE note within 5 days before. `today` is Argentina's date.\n */\nfunction dateWindow(\n data: Pick<WsfeVoucherInput, \"concept\" | \"voucherType\">,\n service: \"wsfe\" | \"wsmtxca\",\n today: WsfeDateInput\n): { from: WsfeDateInput; to: WsfeDateInput } {\n const products = data.concept === 1;\n let from = addDays(today, products ? -5 : -10);\n let to = addDays(today, products ? 5 : 10);\n if (products) {\n to = minDate(to, endOfMonth(today));\n }\n if (service === \"wsfe\" && FCE_INVOICE_TYPES.includes(data.voucherType)) {\n from = maxDate(from, addDays(today, -5));\n to = minDate(to, addDays(today, 1));\n }\n if (service === \"wsfe\" && FCE_NOTE_TYPES.includes(data.voucherType)) {\n from = maxDate(from, addDays(today, -5));\n }\n return { from, to };\n}\n\nexport function assertVoucherDateWindow(\n data: Pick<WsfeVoucherInput, \"concept\" | \"voucherDate\" | \"voucherType\">,\n service: \"wsfe\" | \"wsmtxca\",\n today: WsfeDateInput\n): void {\n const { from, to } = dateWindow(data, service, today);\n if (data.voucherDate < from || data.voucherDate > to) {\n throwOutsideWindow(from, to, today);\n }\n}\n\n/**\n * WSFEX rule 1500: 5 days either side of the day it is sent, and an export\n * of services never dated after the current month.\n */\nexport function assertExportDateWindow(\n voucherDate: WsfeDateInput,\n services: boolean,\n today: WsfeDateInput\n): void {\n const { from, to } = exportDateWindow(services, today);\n if (voucherDate < from || voucherDate > to) {\n throwOutsideWindow(from, to, today);\n }\n}\n\nfunction exportDateWindow(\n services: boolean,\n today: WsfeDateInput\n): { from: WsfeDateInput; to: WsfeDateInput } {\n const from = addDays(today, -5);\n const to = addDays(today, 5);\n return { from, to: services ? minDate(to, endOfMonth(today)) : to };\n}\n\nfunction throwOutsideWindow(\n from: WsfeDateInput,\n to: WsfeDateInput,\n today: WsfeDateInput\n): never {\n const window = { from: isoDay(from), to: isoDay(to) };\n throw new ArcaInputError(\n `date must be from ${window.from} through ${window.to}, the window ARCA accepts on ${isoDay(today)}.`,\n {\n code: \"ARCA_INPUT_DATE_OUTSIDE_WINDOW\",\n field: \"date\",\n expected: `a date from ${window.from} through ${window.to}`,\n window,\n }\n );\n}\n\nfunction isoDay(date: WsfeDateInput): string {\n return toIsoDate(date) ?? date;\n}\n\n/** Day arithmetic on `YYYYMMDD`; `Date.UTC` rolls overflowing days and months. */\nfunction shiftDate(\n date: WsfeDateInput,\n days: number,\n months = 0\n): WsfeDateInput {\n const utc = Date.UTC(\n Number(date.slice(0, 4)),\n Number(date.slice(4, 6)) - 1 + months,\n Number(date.slice(6, 8)) + days\n );\n return new Date(utc)\n .toISOString()\n .slice(0, 10)\n .replaceAll(\"-\", \"\") as WsfeDateInput;\n}\nfunction addDays(date: WsfeDateInput, days: number): WsfeDateInput {\n return shiftDate(date, days);\n}\n/** Day 0 of the next month is the last day of this one. */\nfunction endOfMonth(date: WsfeDateInput): WsfeDateInput {\n return shiftDate(date, -Number(date.slice(6, 8)), 1);\n}\nfunction minDate(a: WsfeDateInput, b: WsfeDateInput): WsfeDateInput {\n return a < b ? a : b;\n}\nfunction maxDate(a: WsfeDateInput, b: WsfeDateInput): WsfeDateInput {\n return a > b ? a : b;\n}\n\nexport function assertIssueObject(\n value: unknown,\n field: string\n): asserts value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n invalid(field, \"an object\");\n }\n}\nexport function assertIssueKeys(\n value: object,\n keys: readonly string[],\n prefix: string,\n method = \"issue()\"\n): void {\n for (const key of Object.keys(value)) {\n if (!keys.includes(key)) {\n const field = prefix === \"input\" ? key : `${prefix}.${key}`;\n throw new ArcaInputError(`${field} is not supported by ${method}.`, {\n code: \"ARCA_INPUT_RESERVED_FIELD\",\n field,\n expected: \"a field the facade supports\",\n });\n }\n }\n}\nfunction invalid(field: string, expected: string): never {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n\nconst NUMERIC_RECEIVER_CONDITIONS = [1, 4, 5, 6, 7, 8, 9, 10, 13, 15, 16];\n\n/** The ARCA identifier for a receiver condition given by name or by number. */\nexport function receiverConditionId(condition: unknown, path: string): number {\n if (typeof condition === \"number\") {\n if (!NUMERIC_RECEIVER_CONDITIONS.includes(condition)) {\n invalid(path, \"an ARCA receiver condition\");\n }\n return condition;\n }\n if (\n typeof condition !== \"string\" ||\n !Object.hasOwn(ARCA_RECEIVER_CONDITION_IDS, condition)\n ) {\n invalid(path, \"one of the five supported receiver conditions\");\n }\n return ARCA_RECEIVER_CONDITION_IDS[condition as ReceiverCondition];\n}\n\nfunction deriveNumericReceiver(to: Extract<Receiver, { condition: number }>) {\n if (!NUMERIC_RECEIVER_CONDITIONS.includes(to.condition)) {\n invalid(\"to.condition\", \"an ARCA receiver condition\");\n }\n const document = \"document\" in to ? to.document : undefined;\n if (document) {\n assertIssueKeys(document, [\"type\", \"number\"], \"to.document\");\n if (to.cuit !== undefined || to.dni !== undefined) {\n invalid(\"to\", \"one document identity\");\n }\n if (\n !Number.isInteger(document.type) ||\n document.type < 0 ||\n document.type > 99 ||\n !/^\\d{1,11}$/.test(String(document.number)) ||\n !Number.isSafeInteger(Number(document.number))\n ) {\n invalid(\"to.document\", \"a valid document type and number\");\n }\n if (document.type === 80 && String(document.number).length !== 11) {\n invalid(\"to.document.number\", \"an 11-digit CUIT\");\n }\n return {\n documentType: document.type,\n documentNumber: Number(document.number),\n receiverVatConditionId: to.condition,\n };\n }\n if (to.cuit === undefined && to.dni === undefined) {\n invalid(\"to\", \"an explicit document\");\n }\n if (to.cuit !== undefined && to.dni !== undefined) {\n invalid(\"to\", \"one document identity\");\n }\n return {\n documentType: to.cuit === undefined ? 96 : 80,\n documentNumber: issueDocumentNumber(\n to.cuit ?? to.dni,\n \"to.document\",\n to.cuit === undefined ? 1 : 11,\n 11\n ),\n receiverVatConditionId: to.condition,\n };\n}\n","import {\n ArcaInputError,\n ArcaInvalidSoapResponseError,\n ArcaServiceError,\n ArcaSoapFaultError,\n ArcaTransportError,\n} from \"../errors\";\nimport {\n classifyArcaAuthenticationError,\n classifyArcaAuthenticationIssues,\n createArcaAuthenticationEvidence,\n executeWithAuthenticationRecovery,\n} from \"../internal/authentication\";\nimport { toIsoDate } from \"../internal/dates\";\nimport {\n serializeArcaAmount,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport type { ArcaClientConfig, ArcaRepresentedTaxId } from \"../internal/types\";\nimport type { SoapTransport } from \"../soap\";\nimport type { WsaaAuthModule } from \"../wsaa\";\nimport type {\n ArcaAuthorizationIndeterminateReason,\n ArcaAuthorizationOutcome,\n ArcaFiscalIssue,\n ArcaFiscalResultLevel,\n ArcaVoucherLookupResult,\n} from \"./fiscal-evidence\";\n\n/** Factura E (19), Nota de Débito E (20) and Nota de Crédito E (21). */\nexport type WsfexVoucherType = 19 | 20 | 21;\n/** `Tipo_expo`: goods (1), services (2) or other (4). */\nexport type WsfexExportType = 1 | 2 | 4;\n/** `Idioma_cbte`: Spanish (1), English (2) or Portuguese (3). */\nexport type WsfexLanguage = 1 | 2 | 3;\n\n/**\n * One `Item`. Money is in major units like `WsfeVoucherInput`: `amount` has\n * at most two decimals, `discount` at most six. `unitPrice` is a decimal\n * string with up to six decimals, the SDK's one monetary exception.\n */\nexport type WsfexItem = {\n code?: string;\n description: string;\n /** A number, or an exact decimal string; a lookup answers the string. */\n quantity?: number | string;\n unit: number;\n unitPrice?: string;\n /** A number, or an exact decimal string; a lookup answers the string. */\n discount?: number | string;\n amount: number;\n};\nexport type WsfexPermit = { id: string; destination: number };\nexport type WsfexAssociatedVoucher = {\n voucherType: number;\n salesPoint: number;\n number: number;\n issuerTaxId?: string;\n};\n\n/**\n * The fiscal content of one `FEXAuthorize` `Cmp`, without its request `Id`\n * and number. Dates are `YYYYMMDD`. Field order here is not the wire order:\n * the service serializes in WSDL order.\n */\nexport type WsfexVoucherInput = {\n voucherType: WsfexVoucherType;\n salesPoint: number;\n voucherDate?: string;\n exportType: WsfexExportType;\n /** `Permiso_existente`: absent sends it empty, as notes and services require. */\n permitExists?: \"S\" | \"N\";\n permits?: readonly WsfexPermit[];\n /** `Dst_cmp`, an ARCA country code from `getCountries()`. */\n destination: number;\n receiverName: string;\n /** `Cuit_pais_cliente`, one of `getCountryTaxIds()`. */\n receiverCountryTaxId?: string;\n receiverAddress: string;\n /** `Id_impositivo`, the receiver's tax ID abroad. */\n receiverTaxId?: string;\n currencyId: string;\n /** `Moneda_ctz` as an exact decimal string; ARCA may fill it when `sameCurrencyForeignCancellation` is `S`. */\n exchangeRate?: string;\n /** `CanMisMonExt`. Invoices in a foreign currency only. */\n sameCurrencyForeignCancellation?: \"S\" | \"N\";\n commercialObservations?: string;\n totalAmount: number;\n observations?: string;\n associatedVouchers?: readonly WsfexAssociatedVoucher[];\n /** `Forma_pago`, required on invoices (rule 1620). */\n paymentTerms?: string;\n incoterms?: string;\n incotermsDetail?: string;\n language: WsfexLanguage;\n items: readonly WsfexItem[];\n /** `Fecha_pago`, required on service and other invoices (rule 1672). */\n paymentDate?: string;\n activities?: readonly { id: string }[];\n};\n\nexport type WsfexIssueInput = WsfexVoucherInput & {\n /** `Cmp.Id`. Resending the same id returns ARCA's stored answer. */\n id: number;\n number: number;\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n abortSignal?: AbortSignal;\n};\n\n/**\n * Structured evidence of one `FEXAuthorize`. `echo` is what ARCA says it\n * authorized: callers must compare it with what they sent, since a reused\n * `Id` returns another request's stored answer with `reprocessed: true`.\n */\nexport type WsfexAuthorizationOutcome = ArcaAuthorizationOutcome<\"wsfex\"> & {\n reprocessed?: boolean;\n echo?: {\n id?: number;\n salesPoint?: number;\n voucherType?: number;\n number?: number;\n date?: string;\n };\n};\n\n/** One authorized voucher as `FEXGetCMP` reports it, in ARCA's units. */\nexport type WsfexVoucherInfo = Omit<\n WsfexVoucherInput,\n \"voucherType\" | \"language\" | \"exportType\"\n> & {\n id?: number;\n voucherType: number;\n number: number;\n exportType?: number;\n language?: number;\n result?: string;\n cae?: string;\n /** `Fch_venc_Cae`, `YYYYMMDD`. */\n caeExpiry?: string;\n /** `Fecha_cbte_cae`, `YYYYMMDD`. */\n authorizedAt?: string;\n observations?: string;\n};\nexport type WsfexVoucherLookupResult = ArcaVoucherLookupResult<\n WsfexVoucherInfo,\n \"wsfex\"\n>;\n\nexport type WsfexCatalogEntry = { id: string; description: string };\nexport type WsfexCountryTaxId = {\n taxId: string;\n description: string;\n};\nexport type WsfexSalesPoint = {\n number: number;\n blocked: boolean;\n /** `YYYY-MM-DD`, absent when active. */\n deactivatedAt?: string;\n};\nexport type WsfexExchangeRate = {\n currencyId: string;\n /** Exact decimal string. */\n rate: string;\n /** `YYYY-MM-DD`. */\n date: string;\n};\n\ntype Auth = { representedTaxId?: number | string; forceRefresh?: boolean };\n\nexport type WsfexService = {\n /**\n * One `FEXAuthorize` with the caller's `Id` and number. Never throws a\n * provider answer: `authorized`, `rejected` or `indeterminate`. Transport\n * retries are safe because ARCA answers a repeated `Id` from its records.\n */\n issue(input: WsfexIssueInput): Promise<WsfexAuthorizationOutcome>;\n /** `FEXGetLast_ID`: the highest request `Id` ARCA received for the CUIT. */\n getLastRequestId(\n input?: Auth & { abortSignal?: AbortSignal }\n ): Promise<number>;\n /** `FEXGetLast_CMP`: the last authorized number; `0` when none. */\n getLastVoucherNumber(\n input: Auth & {\n salesPoint: number;\n voucherType: number;\n abortSignal?: AbortSignal;\n }\n ): Promise<number>;\n /** `FEXGetCMP`; error 1020 becomes `not_found`. */\n lookupVoucher(\n input: Auth & {\n salesPoint: number;\n voucherType: number;\n number: number;\n abortSignal?: AbortSignal;\n }\n ): Promise<WsfexVoucherLookupResult>;\n getSalesPoints(input?: Auth): Promise<WsfexSalesPoint[]>;\n getCountries(input?: Auth): Promise<WsfexCatalogEntry[]>;\n getCountryTaxIds(input?: Auth): Promise<WsfexCountryTaxId[]>;\n getCurrencies(input?: Auth): Promise<WsfexCatalogEntry[]>;\n getIncoterms(input?: Auth): Promise<WsfexCatalogEntry[]>;\n getUnits(input?: Auth): Promise<WsfexCatalogEntry[]>;\n getLanguages(input?: Auth): Promise<WsfexCatalogEntry[]>;\n getVoucherTypes(input?: Auth): Promise<WsfexCatalogEntry[]>;\n getExportTypes(input?: Auth): Promise<WsfexCatalogEntry[]>;\n getActivities(input?: Auth): Promise<WsfexCatalogEntry[]>;\n /**\n * `FEXGetPARAM_Ctz`. ARCA's rate for `date` (`YYYY-MM-DD`), or its latest\n * when omitted. Homologation answers a test rate, not the real one.\n */\n getExchangeRate(\n input: Auth & { currencyId: string; date?: string }\n ): Promise<WsfexExchangeRate>;\n /** `FEXCheck_Permiso`: whether a shipping permit exists for a destination. */\n checkPermit(\n input: Auth & { id: string; destination: number }\n ): Promise<boolean>;\n};\n\nexport type CreateWsfexServiceOptions = {\n config: ArcaClientConfig;\n auth: WsaaAuthModule;\n soap: SoapTransport;\n};\n\ntype WsfexCallInput = {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n abortSignal?: AbortSignal;\n};\n\ntype WsfexEcho = NonNullable<WsfexAuthorizationOutcome[\"echo\"]>;\n\n/** Creates a WSFEX service instance wired with authentication and SOAP transport. */\nexport function createWsfexService(\n options: CreateWsfexServiceOptions\n): WsfexService {\n async function executeWsfexRawOperation(\n operation: string,\n input: WsfexCallInput,\n body: Record<string, unknown> = {},\n authFields: Record<string, unknown> = {}\n ) {\n const auth = await options.auth.login(\"wsfex\", {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n abortSignal: input.abortSignal,\n });\n const response = await options.soap.execute<\n Record<string, unknown>,\n Record<string, unknown>\n >({\n service: \"wsfex\",\n operation,\n signal: input.abortSignal,\n body: {\n Auth: {\n ...createWsfexAuth(\n input.representedTaxId ?? options.config.taxId,\n auth.token,\n auth.sign\n ),\n ...authFields,\n },\n ...body,\n },\n });\n\n return unwrapWsfexOperationEnvelope(operation, response.result);\n }\n\n function executeWsfexOperation(\n operation: string,\n input: WsfexCallInput,\n body: Record<string, unknown> = {},\n authFields: Record<string, unknown> = {}\n ) {\n return executeWithAuthenticationRecovery({\n service: \"wsfex\",\n operation,\n forceRefresh: input.forceRefresh,\n async execute(forceRefresh) {\n const result = await executeWsfexRawOperation(\n operation,\n {\n representedTaxId: input.representedTaxId,\n forceRefresh,\n abortSignal: input.abortSignal,\n },\n body,\n authFields\n );\n throwForWsfexOperationError(operation, result);\n return result;\n },\n });\n }\n\n async function getWsfexResultRows(\n operation: string,\n rowKey: string,\n input: Auth\n ) {\n const result = await executeWsfexOperation(operation, {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n });\n return getWsfexRows(result.FEXResultGet, rowKey);\n }\n\n async function getWsfexCatalog(\n operation: string,\n rowKey: string,\n fields: { id: string; description: string },\n input: Auth\n ): Promise<WsfexCatalogEntry[]> {\n const rows = await getWsfexResultRows(operation, rowKey, input);\n return rows.flatMap((row) => {\n const id = readWsfexText(row[fields.id]);\n return id === undefined\n ? []\n : [{ id, description: readWsfexText(row[fields.description]) ?? \"\" }];\n });\n }\n\n function issue(input: WsfexIssueInput): Promise<WsfexAuthorizationOutcome> {\n const request = createWsfexRequest(input);\n return executeWsfexAuthorization(input, request);\n }\n\n async function executeWsfexAuthorization(\n input: WsfexIssueInput,\n request: Record<string, unknown>\n ): Promise<WsfexAuthorizationOutcome> {\n try {\n // No `retries` override: ARCA answers a repeated Cmp.Id from its\n // records (Reproceso=S), so a resent request cannot authorize twice.\n const result = await executeWsfexRawOperation(\n \"FEXAuthorize\",\n {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n abortSignal: input.abortSignal,\n },\n { Cmp: request }\n );\n return classifyWsfexAuthorization(result);\n } catch (error) {\n return createWsfexIndeterminateOutcome(error);\n }\n }\n\n function lookupVoucher(\n input: Parameters<WsfexService[\"lookupVoucher\"]>[0]\n ): Promise<WsfexVoucherLookupResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsfex\",\n operation: \"FEXGetCMP\",\n forceRefresh: input.forceRefresh,\n execute: (forceRefresh) => lookupVoucherOnce({ ...input, forceRefresh }),\n });\n }\n\n async function lookupVoucherOnce(\n input: Parameters<WsfexService[\"lookupVoucher\"]>[0]\n ): Promise<WsfexVoucherLookupResult> {\n const operation = \"FEXGetCMP\";\n const result = await executeWsfexRawOperation(operation, input, {\n // ClsFEXGetCMP spells it `Cbte_tipo`; the manual's `Cbte_Tipo` would\n // be dropped by the server and consult type 0.\n Cmp: {\n Cbte_tipo: input.voucherType,\n Punto_vta: input.salesPoint,\n Cbte_nro: input.number,\n },\n });\n const errors = extractWsfexErrors(result, operation);\n\n if (errors.length > 0 && errors.every((issue) => issue.code === \"1020\")) {\n return {\n kind: \"not_found\",\n service: \"wsfex\",\n operation,\n errors,\n observations: [],\n raw: result,\n };\n }\n\n if (errors.length > 0) {\n throw createWsfexServiceError(operation, errors);\n }\n\n const raw = toWsfexRecord(result.FEXResultGet);\n if (!raw) {\n throw new ArcaServiceError(\"WSFEX did not return the consulted voucher\", {\n service: \"wsfex\",\n operation,\n });\n }\n\n return {\n kind: \"found\",\n service: \"wsfex\",\n operation,\n voucher: mapWsfexVoucherInfo(raw),\n observations: extractWsfexReasons(\n raw.Motivos_Obs,\n operation,\n \"observation\"\n ),\n raw: result,\n };\n }\n\n return {\n issue,\n async getLastRequestId(input = {}) {\n const operation = \"FEXGetLast_ID\";\n const result = await executeWsfexOperation(operation, input);\n return parseWsfexInteger(toWsfexRecord(result.FEXResultGet)?.Id, {\n operation,\n field: \"Id\",\n min: 0,\n max: WSFEX_MAX_REQUEST_ID,\n });\n },\n async getLastVoucherNumber({ salesPoint, voucherType, ...input }) {\n const operation = \"FEXGetLast_CMP\";\n // The only operation whose point and type travel inside Auth.\n const result = await executeWsfexOperation(\n operation,\n input,\n {},\n { Pto_venta: salesPoint, Cbte_Tipo: voucherType }\n );\n return parseWsfexInteger(\n toWsfexRecord(result.FEXResult_LastCMP)?.Cbte_nro,\n { operation, field: \"Cbte_nro\", min: 0, max: 99_999_999 }\n );\n },\n lookupVoucher,\n async getSalesPoints(input = {}) {\n const rows = await getWsfexResultRows(\n \"FEXGetPARAM_PtoVenta\",\n \"ClsFEXResponse_PtoVenta\",\n input\n );\n return rows.map(mapWsfexSalesPoint);\n },\n getCountries(input = {}) {\n return getWsfexCatalog(\n \"FEXGetPARAM_DST_pais\",\n \"ClsFEXResponse_DST_pais\",\n { id: \"DST_Codigo\", description: \"DST_Ds\" },\n input\n );\n },\n async getCountryTaxIds(input = {}) {\n const rows = await getWsfexResultRows(\n \"FEXGetPARAM_DST_CUIT\",\n \"ClsFEXResponse_DST_cuit\",\n input\n );\n return rows.flatMap((row) => {\n const taxId = readWsfexText(row.DST_CUIT);\n return taxId === undefined\n ? []\n : [{ taxId, description: readWsfexText(row.DST_Ds) ?? \"\" }];\n });\n },\n getCurrencies(input = {}) {\n return getWsfexCatalog(\n \"FEXGetPARAM_MON\",\n \"ClsFEXResponse_Mon\",\n { id: \"Mon_Id\", description: \"Mon_Ds\" },\n input\n );\n },\n getIncoterms(input = {}) {\n return getWsfexCatalog(\n \"FEXGetPARAM_Incoterms\",\n \"ClsFEXResponse_Inc\",\n { id: \"Inc_Id\", description: \"Inc_Ds\" },\n input\n );\n },\n getUnits(input = {}) {\n return getWsfexCatalog(\n \"FEXGetPARAM_UMed\",\n \"ClsFEXResponse_UMed\",\n { id: \"Umed_Id\", description: \"Umed_Ds\" },\n input\n );\n },\n getLanguages(input = {}) {\n return getWsfexCatalog(\n \"FEXGetPARAM_Idiomas\",\n \"ClsFEXResponse_Idi\",\n { id: \"Idi_Id\", description: \"Idi_Ds\" },\n input\n );\n },\n getVoucherTypes(input = {}) {\n return getWsfexCatalog(\n \"FEXGetPARAM_Cbte_Tipo\",\n \"ClsFEXResponse_Cbte_Tipo\",\n { id: \"Cbte_Id\", description: \"Cbte_Ds\" },\n input\n );\n },\n getExportTypes(input = {}) {\n return getWsfexCatalog(\n \"FEXGetPARAM_Tipo_Expo\",\n \"ClsFEXResponse_Tex\",\n { id: \"Tex_Id\", description: \"Tex_Ds\" },\n input\n );\n },\n async getActivities(input = {}) {\n const rows = await getWsfexResultRows(\n \"FEXGetPARAM_Actividades\",\n \"ClsFEXResponse_ActividadTipo\",\n input\n );\n return rows.flatMap((row) => {\n const id = toWsfexActivityId(row.Id);\n return id === undefined\n ? []\n : [{ id, description: readWsfexText(row.Desc) ?? \"\" }];\n });\n },\n async getExchangeRate({ currencyId, date, ...input }) {\n const operation = \"FEXGetPARAM_Ctz\";\n // Error 1003 documents FchCotiz as YYYY-MM-DD, unlike every other\n // WSFEX date.\n const quotationDate =\n date === undefined\n ? undefined\n : toIsoDate(normalizeWsfexDate(date, \"date\"));\n const result = await executeWsfexOperation(operation, input, {\n Mon_id: currencyId,\n ...optionalWsfexField(\"FchCotiz\", quotationDate),\n });\n const raw = toWsfexRecord(result.FEXResultGet);\n const rate = canonicalizeWsfexDecimal(raw?.Mon_ctz);\n const rateDate = toIsoDate(readWsfexText(raw?.Mon_fecha));\n if (rate === undefined || rateDate === undefined) {\n throw new ArcaInvalidSoapResponseError(\"Invalid WSFEX exchange rate\", {\n service: \"wsfex\",\n operation,\n });\n }\n return { currencyId, rate, date: rateDate };\n },\n async checkPermit({ id, destination, ...input }) {\n const operation = \"FEXCheck_Permiso\";\n const result = await executeWsfexOperation(operation, input, {\n ID_Permiso: id,\n Dst_merc: destination,\n });\n const status = readWsfexText(\n toWsfexRecord(result.FEXResultGet)?.Status\n )?.toUpperCase();\n if (status === \"OK\" || status === \"NO\") {\n return status === \"OK\";\n }\n throw new ArcaInvalidSoapResponseError(\"Invalid WSFEX permit status\", {\n service: \"wsfex\",\n operation,\n });\n },\n };\n}\n\nconst WSFEX_MAX_REQUEST_ID = 999_999_999_999_999;\nconst WSFEX_VOUCHER_TYPES = [19, 20, 21] as const;\nconst WSFEX_EXPORT_TYPES = [1, 2, 4] as const;\nconst WSFEX_LANGUAGES = [1, 2, 3] as const;\n// Pro_qty, Pro_precio_uni and Pro_bonificacion are N12,6.\nconst WSFEX_ITEM_DECIMAL_PATTERN = /^(\\d{1,12})(?:\\.(\\d{1,6}))?$/;\nconst WSFEX_TAX_ID_PATTERN = /^\\d{11}$/;\n\n/**\n * Builds `Cmp` in `ClsFEXRequest` sequence order, checking only the shape of\n * each field. Business rules (which fields a voucher type needs) belong to the\n * caller and to ARCA.\n */\n/**\n * Throws every structural error `issue()` would throw for this voucher, with\n * no I/O. Run it before a reservation stores the voucher, so a retry never\n * replays one that cannot be sent.\n */\nexport function assertWsfexVoucherInput(voucher: WsfexVoucherInput): void {\n createWsfexRequest({ ...voucher, id: 0, number: 1 });\n}\n\nfunction createWsfexRequest(input: WsfexIssueInput): Record<string, unknown> {\n return {\n Id: assertWsfexInteger(input.id, \"id\", 0, WSFEX_MAX_REQUEST_ID),\n ...optionalWsfexField(\n \"Fecha_cbte\",\n normalizeOptionalWsfexDate(input.voucherDate, \"voucherDate\")\n ),\n Cbte_Tipo: assertWsfexCode(\n input.voucherType,\n \"voucherType\",\n WSFEX_VOUCHER_TYPES\n ),\n Punto_vta: assertWsfexInteger(input.salesPoint, \"salesPoint\", 1, 99_999),\n Cbte_nro: assertWsfexInteger(input.number, \"number\", 1, 99_999_999),\n Tipo_expo: assertWsfexCode(\n input.exportType,\n \"exportType\",\n WSFEX_EXPORT_TYPES\n ),\n // ARCA expects the element present and empty for notes and services.\n Permiso_existente:\n assertOptionalWsfexFlag(input.permitExists, \"permitExists\") ?? \"\",\n ...optionalWsfexField(\n \"Permisos\",\n createWsfexList(input.permits, \"Permiso\", createWsfexPermit)\n ),\n Dst_cmp: assertWsfexInteger(input.destination, \"destination\", 1, 999),\n Cliente: requireWsfexText(input.receiverName, \"receiverName\"),\n ...optionalWsfexField(\n \"Cuit_pais_cliente\",\n assertOptionalWsfexTaxId(\n input.receiverCountryTaxId,\n \"receiverCountryTaxId\"\n )\n ),\n Domicilio_cliente: requireWsfexText(\n input.receiverAddress,\n \"receiverAddress\"\n ),\n ...optionalWsfexField(\n \"Id_impositivo\",\n optionalWsfexText(input.receiverTaxId, \"receiverTaxId\")\n ),\n Moneda_Id: requireWsfexText(input.currencyId, \"currencyId\"),\n ...optionalWsfexField(\n \"Moneda_ctz\",\n input.exchangeRate === undefined\n ? undefined\n : serializeArcaExchangeRate(input.exchangeRate, \"exchangeRate\")\n ),\n ...optionalWsfexField(\n \"CanMisMonExt\",\n assertOptionalWsfexFlag(\n input.sameCurrencyForeignCancellation,\n \"sameCurrencyForeignCancellation\"\n )\n ),\n ...optionalWsfexField(\n \"Obs_comerciales\",\n optionalWsfexText(input.commercialObservations, \"commercialObservations\")\n ),\n Imp_total: serializeArcaAmount(input.totalAmount, \"totalAmount\"),\n ...optionalWsfexField(\n \"Obs\",\n optionalWsfexText(input.observations, \"observations\")\n ),\n ...optionalWsfexField(\n \"Cmps_asoc\",\n createWsfexList(\n input.associatedVouchers,\n \"Cmp_asoc\",\n createWsfexAssociatedVoucher\n )\n ),\n ...optionalWsfexField(\n \"Forma_pago\",\n optionalWsfexText(input.paymentTerms, \"paymentTerms\")\n ),\n ...optionalWsfexField(\n \"Incoterms\",\n optionalWsfexText(input.incoterms, \"incoterms\")\n ),\n ...optionalWsfexField(\n \"Incoterms_Ds\",\n optionalWsfexText(input.incotermsDetail, \"incotermsDetail\")\n ),\n Idioma_cbte: assertWsfexCode(input.language, \"language\", WSFEX_LANGUAGES),\n Items: createWsfexItems(input.items),\n ...optionalWsfexField(\n \"Fecha_pago\",\n normalizeOptionalWsfexDate(input.paymentDate, \"paymentDate\")\n ),\n ...optionalWsfexField(\n \"Actividades\",\n createWsfexList(input.activities, \"Actividad\", createWsfexActivity)\n ),\n };\n}\n\n// ARCA rejects an empty wrapper (1720, 1820, 2100), so an empty list is absent.\nfunction createWsfexList<T>(\n rows: readonly T[] | undefined,\n key: string,\n map: (row: T, index: number) => Record<string, unknown>\n): Record<string, unknown> | undefined {\n if (rows === undefined || rows.length === 0) {\n return undefined;\n }\n return { [key]: rows.map(map) };\n}\n\nfunction createWsfexPermit(permit: WsfexPermit, index: number) {\n return {\n Id_permiso: requireWsfexText(permit.id, `permits[${index}].id`),\n Dst_merc: assertWsfexInteger(\n permit.destination,\n `permits[${index}].destination`,\n 1,\n 999\n ),\n };\n}\n\nfunction createWsfexAssociatedVoucher(\n voucher: WsfexAssociatedVoucher,\n index: number\n) {\n const field = `associatedVouchers[${index}]`;\n return {\n Cbte_tipo: assertWsfexInteger(\n voucher.voucherType,\n `${field}.voucherType`,\n 1,\n 999\n ),\n Cbte_punto_vta: assertWsfexInteger(\n voucher.salesPoint,\n `${field}.salesPoint`,\n 1,\n 99_999\n ),\n Cbte_nro: assertWsfexInteger(\n voucher.number,\n `${field}.number`,\n 1,\n 999_999_999\n ),\n ...optionalWsfexField(\n \"Cbte_cuit\",\n assertOptionalWsfexTaxId(voucher.issuerTaxId, `${field}.issuerTaxId`)\n ),\n };\n}\n\nfunction createWsfexItems(items: readonly WsfexItem[]) {\n if (!Array.isArray(items) || items.length === 0) {\n throw new ArcaInputError(\"items must contain at least one item.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"items\",\n expected: \"from 1 to 9999 items\",\n });\n }\n return { Item: items.map(createWsfexItem) };\n}\n\nfunction createWsfexItem(item: WsfexItem, index: number) {\n const field = `items[${index}]`;\n return {\n ...optionalWsfexField(\n \"Pro_codigo\",\n optionalWsfexText(item.code, `${field}.code`)\n ),\n Pro_ds: requireWsfexText(item.description, `${field}.description`),\n ...optionalWsfexField(\n \"Pro_qty\",\n serializeWsfexItemDecimal(item.quantity, `${field}.quantity`)\n ),\n Pro_umed: assertWsfexInteger(item.unit, `${field}.unit`, 0, 99),\n ...optionalWsfexField(\n \"Pro_precio_uni\",\n serializeWsfexItemDecimal(item.unitPrice, `${field}.unitPrice`)\n ),\n ...optionalWsfexField(\n \"Pro_bonificacion\",\n serializeWsfexItemDecimal(item.discount, `${field}.discount`)\n ),\n Pro_total_item: serializeWsfexSignedAmount(item.amount, `${field}.amount`),\n };\n}\n\nfunction createWsfexActivity(activity: { id: string }, index: number) {\n const field = `activities[${index}].id`;\n if (typeof activity.id !== \"string\" || !/^\\d{1,6}$/.test(activity.id)) {\n throw new ArcaInputError(`${field} must be an activity code.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected: \"a code of up to 6 digits from getActivities()\",\n });\n }\n return { Id: Number.parseInt(activity.id, 10) };\n}\n\n// Unit 97 allows any sign and unit 99 requires a negative total (rule 1810).\nfunction serializeWsfexSignedAmount(value: number, field: string): string {\n return typeof value === \"number\" && value < 0\n ? `-${serializeArcaAmount(-value, field)}`\n : serializeArcaAmount(value, field);\n}\n\n/**\n * N12,6 fields go out in the shortest exact form, without trailing zeros. A\n * number is read through its shortest round-trip string, so `0.1` stays `0.1`.\n */\nfunction serializeWsfexItemDecimal(\n value: number | string | undefined,\n field: string\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n const text =\n typeof value === \"number\" && Number.isFinite(value) ? String(value) : value;\n const match =\n typeof text === \"string\"\n ? WSFEX_ITEM_DECIMAL_PATTERN.exec(text.trim())\n : null;\n if (!match) {\n throw new ArcaInputError(\n `${field} must be a non-negative decimal with at most 12 integer and 6 fractional digits.`,\n {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected:\n \"a non-negative decimal with up to 12 integer and 6 fractional digits\",\n }\n );\n }\n return formatWsfexDecimal(match[1] ?? \"0\", match[2]);\n}\n\nfunction formatWsfexDecimal(integerPart: string, fractionPart = \"\"): string {\n const integer = integerPart.replace(/^0+(?=\\d)/, \"\");\n const fraction = fractionPart.replace(/0+$/, \"\");\n return fraction ? `${integer}.${fraction}` : integer;\n}\n\n/** Reads an ARCA decimal into the same canonical form the requests use. */\nfunction canonicalizeWsfexDecimal(value: unknown): string | undefined {\n const match = /^(\\d+)(?:\\.(\\d+))?$/.exec(readWsfexText(value) ?? \"\");\n return match ? formatWsfexDecimal(match[1] ?? \"0\", match[2]) : undefined;\n}\n\nfunction optionalWsfexField(\n key: string,\n value: unknown\n): Record<string, unknown> {\n return value === undefined ? {} : { [key]: value };\n}\n\nfunction assertWsfexInteger(\n value: unknown,\n field: string,\n min: number,\n max: number\n): number {\n if (\n typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= min &&\n value <= max\n ) {\n return value;\n }\n return throwWsfexInvalidInput(\n value,\n field,\n `an integer from ${min} to ${max}`\n );\n}\n\nfunction assertWsfexCode<T extends number>(\n value: unknown,\n field: string,\n allowed: readonly T[]\n): T {\n if (allowed.includes(value as T)) {\n return value as T;\n }\n return throwWsfexInvalidInput(value, field, `one of ${allowed.join(\", \")}`);\n}\n\nfunction assertOptionalWsfexFlag(\n value: unknown,\n field: string\n): \"S\" | \"N\" | undefined {\n if (value === undefined || value === \"S\" || value === \"N\") {\n return value;\n }\n return throwWsfexInvalidInput(value, field, \"S or N\");\n}\n\nfunction assertOptionalWsfexTaxId(\n value: unknown,\n field: string\n): string | undefined {\n if (\n value === undefined ||\n (typeof value === \"string\" && WSFEX_TAX_ID_PATTERN.test(value))\n ) {\n return value;\n }\n return throwWsfexInvalidInput(value, field, \"an 11-digit CUIT string\");\n}\n\nfunction requireWsfexText(value: unknown, field: string): string {\n if (typeof value === \"string\" && value.trim() !== \"\") {\n return value;\n }\n return throwWsfexInvalidInput(value, field, \"a non-empty string\");\n}\n\nfunction optionalWsfexText(value: unknown, field: string): string | undefined {\n if (value === undefined || typeof value === \"string\") {\n return value;\n }\n return throwWsfexInvalidInput(value, field, \"a string\");\n}\n\nfunction throwWsfexInvalidInput(\n value: unknown,\n field: string,\n expected: string\n): never {\n throw new ArcaInputError(\n value === undefined\n ? `${field} is required.`\n : `${field} must be ${expected}.`,\n {\n code:\n value === undefined\n ? \"ARCA_INPUT_MISSING_FIELD\"\n : \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n }\n );\n}\n\nfunction normalizeOptionalWsfexDate(\n value: string | undefined,\n field: string\n): string | undefined {\n return value === undefined ? undefined : normalizeWsfexDate(value, field);\n}\n\n/** Accepts `YYYYMMDD` or `YYYY-MM-DD` and returns ARCA's `YYYYMMDD`. */\nfunction normalizeWsfexDate(value: unknown, field: string): string {\n const text = typeof value === \"string\" ? value.trim() : \"\";\n const [, year = \"\", month = \"\", day = \"\"] =\n /^(\\d{4})(\\d{2})(\\d{2})$/.exec(text) ??\n /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text) ??\n [];\n const candidate = new Date(\n Date.UTC(Number(year), Number(month) - 1, Number(day))\n );\n if (\n year !== \"\" &&\n candidate.getUTCFullYear() === Number(year) &&\n candidate.getUTCMonth() === Number(month) - 1 &&\n candidate.getUTCDate() === Number(day)\n ) {\n return `${year}${month}${day}`;\n }\n throw new ArcaInputError(\n `Invalid WSFEX ${field}: expected an existing YYYYMMDD or YYYY-MM-DD date`,\n {\n code: \"ARCA_INPUT_INVALID_DATE\",\n field,\n expected: \"an existing YYYYMMDD or YYYY-MM-DD calendar date\",\n }\n );\n}\n\nfunction createWsfexAuth(\n representedTaxId: number | string,\n token: string,\n sign: string\n) {\n return {\n Token: token,\n Sign: sign,\n Cuit: Number.parseInt(String(representedTaxId), 10),\n };\n}\n\nfunction unwrapWsfexOperationEnvelope(\n operation: string,\n response: Record<string, unknown>\n) {\n const operationResponse = response[`${operation}Response`] as\n | Record<string, unknown>\n | undefined;\n const result = (operationResponse?.[`${operation}Result`] ??\n response[`${operation}Result`] ??\n response) as Record<string, unknown>;\n\n return result;\n}\n\nfunction throwForWsfexOperationError(\n operation: string,\n result: Record<string, unknown>\n) {\n const errors = extractWsfexErrors(result, operation);\n if (errors.length > 0) {\n throw createWsfexServiceError(operation, errors);\n }\n}\n\nfunction createWsfexServiceError(operation: string, issues: ArcaFiscalIssue[]) {\n const authenticationError = classifyArcaAuthenticationIssues(issues, {\n service: \"wsfex\",\n operation,\n });\n if (authenticationError) {\n return authenticationError;\n }\n\n const firstIssue = issues[0];\n return new ArcaServiceError(\n firstIssue\n ? formatWsfexIssue(firstIssue)\n : \"WSFEX returned a service error\",\n {\n service: \"wsfex\",\n operation,\n ...(firstIssue?.code === undefined\n ? {}\n : { serviceCode: firstIssue.code }),\n issues,\n }\n );\n}\n\nfunction formatWsfexIssue(issue: ArcaFiscalIssue) {\n return issue.code ? `(${issue.code}) ${issue.message}` : issue.message;\n}\n\n/** `FEXErr` holds one error; `ErrCode` 0 means none. Some answers spell it `Errmsg`. */\nfunction extractWsfexErrors(\n result: Record<string, unknown>,\n operation: string,\n resultLevel?: ArcaFiscalResultLevel\n): ArcaFiscalIssue[] {\n const error = toWsfexRecord(result.FEXErr);\n const code = readWsfexText(error?.ErrCode);\n if (code === undefined || /^0+$/.test(code)) {\n return [];\n }\n return [\n {\n service: \"wsfex\",\n operation,\n source: \"error\",\n category: getWsfexErrorCategory(operation, code),\n code,\n message:\n readWsfexText(error?.ErrMsg) ??\n readWsfexText(error?.Errmsg) ??\n \"Unknown WSFEX error\",\n ...(resultLevel === undefined ? {} : { resultLevel }),\n },\n ];\n}\n\nfunction getWsfexErrorCategory(\n operation: string,\n code: string\n): ArcaFiscalIssue[\"category\"] {\n if (operation !== \"FEXAuthorize\") {\n return \"unknown\";\n }\n return WSFEX_AUTHORIZATION_INFRASTRUCTURE_CODES.has(code)\n ? \"infrastructure\"\n : \"business\";\n}\n\n// 500/501/502/505 are ARCA's internal failures; 1000/1001 reject the ticket.\n// Neither proves what ARCA did with the request.\nconst WSFEX_AUTHORIZATION_INFRASTRUCTURE_CODES = new Set([\n \"500\",\n \"501\",\n \"502\",\n \"505\",\n \"1000\",\n \"1001\",\n]);\n\n/**\n * `Motivos_Obs` is an undocumented C40 string. A list of numeric codes\n * becomes one issue per code; anything else stays one issue with ARCA's text.\n */\nfunction extractWsfexReasons(\n value: unknown,\n operation: string,\n category: ArcaFiscalIssue[\"category\"]\n): ArcaFiscalIssue[] {\n const text = readWsfexText(value);\n if (text === undefined) {\n return [];\n }\n const base = {\n service: \"wsfex\" as const,\n operation,\n source: \"observation\" as const,\n category,\n resultLevel: \"header\" as const,\n };\n if (!/^\\d+(?:\\s*[,;|\\s]\\s*\\d+)*$/.test(text)) {\n return [{ ...base, message: text }];\n }\n return text\n .split(/\\D+/)\n .filter(Boolean)\n .map((token) => {\n const code = String(Number.parseInt(token, 10));\n return { ...base, code, message: code };\n });\n}\n\ntype WsfexAuthorizationBase = {\n service: \"wsfex\";\n operation: string;\n results: { header?: string };\n errors: ArcaFiscalIssue[];\n observations: ArcaFiscalIssue[];\n raw: Record<string, unknown>;\n reprocessed?: boolean;\n echo?: WsfexEcho;\n};\n\ntype WsfexAuthorizationContext = {\n base: WsfexAuthorizationBase;\n resultCode?: string;\n cae?: string;\n caeExpiry?: string;\n voucherNumber?: number;\n};\n\n/**\n * WSFEX answers one voucher per request, so every result is header level.\n * Parsing never throws: a malformed field becomes absent evidence, never an\n * `invalid_response` that would discard the CAE and the echo.\n */\nfunction classifyWsfexAuthorization(\n result: Record<string, unknown>\n): WsfexAuthorizationOutcome {\n const operation = \"FEXAuthorize\";\n const authorization = toWsfexRecord(result.FEXResultAuth);\n const resultCode = normalizeWsfexResult(authorization?.Resultado);\n const echo = readWsfexEcho(authorization);\n const reprocessed = readWsfexReprocessed(authorization?.Reproceso);\n const base: WsfexAuthorizationBase = {\n service: \"wsfex\",\n operation,\n results: resultCode === undefined ? {} : { header: resultCode },\n errors: extractWsfexErrors(result, operation, \"header\"),\n observations: extractWsfexReasons(\n authorization?.Motivos_Obs,\n operation,\n resultCode === \"R\" ? \"business\" : \"observation\"\n ),\n raw: result,\n };\n assignWsfexValue(base, \"reprocessed\", reprocessed);\n assignWsfexValue(base, \"echo\", echo);\n const context: WsfexAuthorizationContext = {\n base,\n resultCode,\n cae: readWsfexText(authorization?.Cae),\n caeExpiry: readWsfexText(authorization?.Fch_venc_Cae),\n voucherNumber: echo?.number,\n };\n\n return base.errors.length > 0\n ? classifyWsfexErrorAnswer(context)\n : classifyWsfexResultAnswer(context);\n}\n\nfunction classifyWsfexErrorAnswer(\n context: WsfexAuthorizationContext\n): WsfexAuthorizationOutcome {\n if (context.cae || context.resultCode === \"A\") {\n return createWsfexStructuredIndeterminate(\n context,\n \"contradictory_response\"\n );\n }\n\n const authenticationError = classifyArcaAuthenticationIssues(\n context.base.errors,\n { service: \"wsfex\", operation: context.base.operation }\n );\n if (authenticationError) {\n return {\n ...createWsfexStructuredIndeterminate(context, \"authentication_rejected\"),\n authentication: createArcaAuthenticationEvidence(authenticationError),\n };\n }\n\n if (\n context.base.errors.some((issue) => issue.category === \"infrastructure\")\n ) {\n return createWsfexStructuredIndeterminate(context, \"incomplete_response\");\n }\n\n // ARCA validates the request before storing it, so a validation error\n // consumed neither the number nor the Id.\n return {\n ...context.base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"header\",\n };\n}\n\nfunction classifyWsfexResultAnswer(\n context: WsfexAuthorizationContext\n): WsfexAuthorizationOutcome {\n const { cae, caeExpiry, voucherNumber } = context;\n if (context.resultCode === \"A\") {\n return cae && caeExpiry && voucherNumber !== undefined\n ? {\n ...context.base,\n kind: \"authorized\",\n result: \"A\",\n resultLevel: \"header\",\n cae,\n caeExpiry,\n voucherNumber,\n }\n : createWsfexStructuredIndeterminate(context, \"incomplete_response\");\n }\n\n if (context.resultCode === \"R\") {\n return cae\n ? createWsfexStructuredIndeterminate(context, \"contradictory_response\")\n : {\n ...context.base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"header\",\n };\n }\n\n return createWsfexStructuredIndeterminate(context, \"incomplete_response\");\n}\n\nfunction createWsfexStructuredIndeterminate(\n context: WsfexAuthorizationContext,\n reason: ArcaAuthorizationIndeterminateReason\n): Extract<WsfexAuthorizationOutcome, { kind: \"indeterminate\" }> {\n const outcome: Extract<WsfexAuthorizationOutcome, { kind: \"indeterminate\" }> =\n {\n ...context.base,\n kind: \"indeterminate\",\n reason,\n };\n assignWsfexValue(outcome, \"result\", context.resultCode);\n if (context.resultCode !== undefined) {\n outcome.resultLevel = \"header\";\n }\n assignWsfexValue(outcome, \"cae\", context.cae);\n assignWsfexValue(outcome, \"caeExpiry\", context.caeExpiry);\n return outcome;\n}\n\nfunction createWsfexIndeterminateOutcome(\n error: unknown\n): WsfexAuthorizationOutcome {\n const operation = \"FEXAuthorize\";\n const authenticationError = classifyArcaAuthenticationError(error, {\n service: \"wsfex\",\n operation,\n });\n return {\n kind: \"indeterminate\",\n service: \"wsfex\",\n operation,\n results: {},\n reason: authenticationError\n ? \"authentication_rejected\"\n : getWsfexIndeterminateReason(error),\n ...(authenticationError\n ? {\n authentication: createArcaAuthenticationEvidence(authenticationError),\n }\n : {}),\n errors: [],\n observations: [],\n };\n}\n\nfunction getWsfexIndeterminateReason(\n error: unknown\n): ArcaAuthorizationIndeterminateReason {\n if (error instanceof ArcaTransportError) {\n return \"transport_error\";\n }\n if (error instanceof ArcaSoapFaultError) {\n return \"soap_fault\";\n }\n if (error instanceof ArcaInvalidSoapResponseError) {\n return \"invalid_response\";\n }\n return \"unexpected_error\";\n}\n\n/**\n * What ARCA says it authorized. A failed request can come back zero-filled,\n * so a zero point, type or number is absent rather than echoed.\n */\nfunction readWsfexEcho(\n authorization: Record<string, unknown> | undefined\n): WsfexEcho | undefined {\n if (!authorization) {\n return undefined;\n }\n const echo: WsfexEcho = {};\n assignWsfexValue(\n echo,\n \"id\",\n readWsfexInteger(authorization.Id, 0, WSFEX_MAX_REQUEST_ID)\n );\n assignWsfexValue(\n echo,\n \"salesPoint\",\n readWsfexInteger(authorization.Punto_vta, 1, 99_999)\n );\n assignWsfexValue(\n echo,\n \"voucherType\",\n readWsfexInteger(authorization.Cbte_tipo ?? authorization.Cbte_Tipo, 1, 999)\n );\n assignWsfexValue(\n echo,\n \"number\",\n readWsfexInteger(authorization.Cbte_nro, 1, 99_999_999)\n );\n assignWsfexValue(echo, \"date\", readWsfexText(authorization.Fch_cbte));\n return Object.keys(echo).length > 0 ? echo : undefined;\n}\n\nfunction readWsfexReprocessed(value: unknown): boolean | undefined {\n const flag = normalizeWsfexResult(value);\n return flag === \"S\" || flag === \"N\" ? flag === \"S\" : undefined;\n}\n\n/** `FEXGetCMP` in the facade's shape: amounts as numbers, rates exact. */\nfunction mapWsfexVoucherInfo(raw: Record<string, unknown>): WsfexVoucherInfo {\n const operation = \"FEXGetCMP\";\n const voucher: WsfexVoucherInfo = {\n voucherType: parseWsfexInteger(raw.Cbte_tipo ?? raw.Cbte_Tipo, {\n operation,\n field: \"Cbte_tipo\",\n min: 1,\n max: 999,\n }),\n salesPoint: parseWsfexInteger(raw.Punto_vta, {\n operation,\n field: \"Punto_vta\",\n min: 1,\n max: 99_999,\n }),\n number: parseWsfexInteger(raw.Cbte_nro, {\n operation,\n field: \"Cbte_nro\",\n min: 1,\n max: 99_999_999,\n }),\n destination: parseWsfexNumber(raw.Dst_cmp, operation, \"Dst_cmp\"),\n receiverName: readWsfexText(raw.Cliente) ?? \"\",\n receiverAddress: readWsfexText(raw.Domicilio_cliente) ?? \"\",\n currencyId: readWsfexText(raw.Moneda_Id) ?? \"\",\n totalAmount: parseWsfexNumber(raw.Imp_total, operation, \"Imp_total\"),\n items: getWsfexRows(raw.Items, \"Item\").map(mapWsfexLookupItem),\n };\n\n assignWsfexValue(\n voucher,\n \"id\",\n readWsfexInteger(raw.Id, 0, WSFEX_MAX_REQUEST_ID)\n );\n assignWsfexValue(voucher, \"voucherDate\", readWsfexText(raw.Fecha_cbte));\n assignWsfexValue(voucher, \"exportType\", readWsfexNumber(raw.Tipo_expo));\n assignWsfexValue(\n voucher,\n \"permitExists\",\n readWsfexFlag(raw.Permiso_existente)\n );\n assignWsfexValue(\n voucher,\n \"permits\",\n mapWsfexLookupList(raw.Permisos, \"Permiso\", mapWsfexLookupPermit)\n );\n assignWsfexValue(\n voucher,\n \"receiverCountryTaxId\",\n readWsfexTaxId(raw.Cuit_pais_cliente)\n );\n assignWsfexValue(voucher, \"receiverTaxId\", readWsfexText(raw.Id_impositivo));\n assignWsfexValue(\n voucher,\n \"exchangeRate\",\n canonicalizeWsfexDecimal(raw.Moneda_ctz)\n );\n assignWsfexValue(\n voucher,\n \"sameCurrencyForeignCancellation\",\n readWsfexFlag(raw.CanMisMonExt)\n );\n assignWsfexValue(\n voucher,\n \"commercialObservations\",\n readWsfexText(raw.Obs_comerciales)\n );\n // `observations` is the voucher's `Obs`, as sent. `Motivos_Obs` goes to the\n // lookup result's structured `observations`.\n assignWsfexValue(voucher, \"observations\", readWsfexText(raw.Obs));\n assignWsfexValue(\n voucher,\n \"associatedVouchers\",\n mapWsfexLookupList(\n raw.Cmps_asoc,\n \"Cmp_asoc\",\n mapWsfexLookupAssociatedVoucher\n )\n );\n assignWsfexValue(voucher, \"paymentTerms\", readWsfexText(raw.Forma_pago));\n assignWsfexValue(voucher, \"incoterms\", readWsfexText(raw.Incoterms));\n assignWsfexValue(voucher, \"incotermsDetail\", readWsfexText(raw.Incoterms_Ds));\n assignWsfexValue(voucher, \"language\", readWsfexNumber(raw.Idioma_cbte));\n assignWsfexValue(voucher, \"paymentDate\", readWsfexText(raw.Fecha_pago));\n assignWsfexValue(\n voucher,\n \"activities\",\n mapWsfexLookupList(raw.Actividades, \"Actividad\", (row) => {\n const id = toWsfexActivityId(row.Id);\n return id === undefined ? undefined : { id };\n })\n );\n assignWsfexValue(voucher, \"result\", normalizeWsfexResult(raw.Resultado));\n assignWsfexValue(voucher, \"cae\", readWsfexText(raw.Cae));\n assignWsfexValue(voucher, \"caeExpiry\", readWsfexText(raw.Fch_venc_Cae));\n assignWsfexValue(voucher, \"authorizedAt\", readWsfexText(raw.Fecha_cbte_cae));\n return voucher;\n}\n\nfunction mapWsfexLookupItem(row: Record<string, unknown>): WsfexItem {\n const operation = \"FEXGetCMP\";\n const code = readWsfexText(row.Pro_codigo);\n // N12,6 needs up to 18 digits, more than a number keeps: stay exact.\n const quantity = canonicalizeWsfexDecimal(row.Pro_qty);\n const unitPrice = canonicalizeWsfexDecimal(row.Pro_precio_uni);\n const discount = canonicalizeWsfexDecimal(row.Pro_bonificacion);\n return {\n ...(code === undefined ? {} : { code }),\n description: readWsfexText(row.Pro_ds) ?? \"\",\n ...(quantity === undefined ? {} : { quantity }),\n unit: parseWsfexNumber(row.Pro_umed, operation, \"Pro_umed\"),\n ...(unitPrice === undefined ? {} : { unitPrice }),\n ...(discount === undefined ? {} : { discount }),\n amount: parseWsfexNumber(row.Pro_total_item, operation, \"Pro_total_item\"),\n };\n}\n\nfunction mapWsfexLookupPermit(\n row: Record<string, unknown>\n): WsfexPermit | undefined {\n const id = readWsfexText(row.Id_permiso);\n const destination = readWsfexNumber(row.Dst_merc);\n return id === undefined || destination === undefined\n ? undefined\n : { id, destination };\n}\n\nfunction mapWsfexLookupAssociatedVoucher(\n row: Record<string, unknown>\n): WsfexAssociatedVoucher | undefined {\n const voucherType = readWsfexNumber(row.Cbte_tipo ?? row.Cbte_Tipo);\n const salesPoint = readWsfexNumber(row.Cbte_punto_vta);\n const number = readWsfexNumber(row.Cbte_nro);\n if (\n voucherType === undefined ||\n salesPoint === undefined ||\n number === undefined\n ) {\n return undefined;\n }\n const issuerTaxId = readWsfexTaxId(row.Cbte_cuit);\n return {\n voucherType,\n salesPoint,\n number,\n ...(issuerTaxId === undefined ? {} : { issuerTaxId }),\n };\n}\n\n// A missing or malformed detail stays absent; never fabricate partial evidence.\nfunction mapWsfexLookupList<T>(\n container: unknown,\n key: string,\n map: (row: Record<string, unknown>) => T | undefined\n): T[] | undefined {\n const rows = getWsfexRows(container, key);\n if (rows.length === 0) {\n return undefined;\n }\n const result: T[] = [];\n for (const row of rows) {\n const mapped = map(row);\n if (mapped === undefined) {\n return undefined;\n }\n result.push(mapped);\n }\n return result;\n}\n\n/** ARCA answers `Pve_Bloqueado` as `S`/`N` and an active point's `Pve_FchBaja` empty or nil. */\nfunction mapWsfexSalesPoint(row: Record<string, unknown>): WsfexSalesPoint {\n const deactivatedAt = toIsoDate(readWsfexText(row.Pve_FchBaja));\n return {\n number: parseWsfexInteger(row.Pve_Nro, {\n operation: \"FEXGetPARAM_PtoVenta\",\n field: \"Pve_Nro\",\n min: 1,\n max: 99_999,\n }),\n blocked: normalizeWsfexResult(row.Pve_Bloqueado) === \"S\",\n ...(deactivatedAt === undefined ? {} : { deactivatedAt }),\n };\n}\n\n// ARCA answers the NAES code as a number, which drops its leading zero.\nfunction toWsfexActivityId(value: unknown): string | undefined {\n const text = readWsfexText(value);\n return text !== undefined && /^\\d+$/.test(text) && Number(text) !== 0\n ? text.padStart(6, \"0\")\n : undefined;\n}\n\n// `Cuit_pais_cliente` and `Cbte_cuit` are required longs, so ARCA fills 0.\nfunction readWsfexTaxId(value: unknown): string | undefined {\n const text = readWsfexText(value);\n return text !== undefined && /^\\d+$/.test(text) && Number(text) !== 0\n ? text\n : undefined;\n}\n\nfunction readWsfexFlag(value: unknown): \"S\" | \"N\" | undefined {\n const flag = normalizeWsfexResult(value);\n return flag === \"S\" || flag === \"N\" ? flag : undefined;\n}\n\n/** Rows of an ARCA array. One row arrives as an object; nil rows are skipped. */\nfunction getWsfexRows(\n container: unknown,\n key: string\n): Record<string, unknown>[] {\n const value = toWsfexRecord(container)?.[key];\n if (value === undefined) {\n return [];\n }\n return (Array.isArray(value) ? value : [value]).flatMap((row) => {\n const record = toWsfexRecord(row);\n return record ? [record] : [];\n });\n}\n\n/** A record with only attributes, such as `xsi:nil`, is absent. */\nfunction toWsfexRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n const record = value as Record<string, unknown>;\n return Object.keys(record).some((key) => !key.startsWith(\"@_\"))\n ? record\n : undefined;\n}\n\nfunction readWsfexText(value: unknown): string | undefined {\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n return undefined;\n }\n const text = String(value).trim();\n return text || undefined;\n}\n\nfunction readWsfexNumber(value: unknown): number | undefined {\n const text = readWsfexText(value);\n return text !== undefined && /^-?\\d+(?:\\.\\d+)?$/.test(text)\n ? Number(text)\n : undefined;\n}\n\nfunction readWsfexInteger(\n value: unknown,\n min: number,\n max: number\n): number | undefined {\n const text = readWsfexText(value);\n if (text === undefined || !/^\\d+$/.test(text)) {\n return undefined;\n }\n const parsed = Number(text);\n return Number.isSafeInteger(parsed) && parsed >= min && parsed <= max\n ? parsed\n : undefined;\n}\n\nfunction parseWsfexInteger(\n value: unknown,\n options: { operation: string; field: string; min: number; max: number }\n): number {\n const parsed = readWsfexInteger(value, options.min, options.max);\n if (parsed === undefined) {\n throw new ArcaInvalidSoapResponseError(`Invalid WSFEX ${options.field}`, {\n service: \"wsfex\",\n operation: options.operation,\n });\n }\n return parsed;\n}\n\nfunction parseWsfexNumber(\n value: unknown,\n operation: string,\n field: string\n): number {\n const parsed = readWsfexNumber(value);\n if (parsed === undefined) {\n throw new ArcaInvalidSoapResponseError(`Invalid WSFEX ${field}`, {\n service: \"wsfex\",\n operation,\n });\n }\n return parsed;\n}\n\nfunction normalizeWsfexResult(value: unknown): string | undefined {\n return readWsfexText(value)?.toUpperCase();\n}\n\nfunction assignWsfexValue<TTarget, TKey extends keyof TTarget>(\n target: TTarget,\n key: TKey,\n value: TTarget[TKey] | undefined\n) {\n if (value !== undefined) {\n target[key] = value;\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { ArcaConfigurationError } from \"../errors\";\nimport type { ArcaEnvironment } from \"../internal/types\";\nimport type { WsfeVoucherInput } from \"../services/wsfe\";\n\n/** What a caller may pass to `withLock`: a signal that stops the wait. */\nexport type ArcaLockOptions = { signal?: AbortSignal };\n\n/**\n * Durable values. add must atomically create only when the key is absent.\n * withLock runs `fn` exclusively across processes. `options.signal` only stops\n * the wait: an abort before the lock is taken throws `ArcaLockTimeoutError`\n * with `reason: \"aborted\"` and never runs `fn`.\n */\nexport type ArcaStore = {\n get(key: string): Promise<string | null>;\n set(key: string, value: string): Promise<void>;\n add(key: string, value: string): Promise<boolean>;\n delete?(key: string): Promise<void>;\n withLock?<T>(\n key: string,\n fn: () => Promise<T>,\n options?: ArcaLockOptions\n ): Promise<T>;\n};\n\n/**\n * Reservation record. Version 1 is a plain WSFE reservation, readable by every\n * release since 0.9. Version 2 carries a WSMTXCA provider or detailed items and\n * always names its `service`, so an older reader refuses it instead of\n * replaying a WSMTXCA reservation through WSFE. Version 2 has three compatible\n * line spellings: releases through 0.12 wrote `details`; 0.13 writes `lines`,\n * or `authorizedLines` when a full note mirrors provider-authorized history.\n *\n * `rejectedAt` marks a reservation whose every submission ARCA rejected, so\n * this key never wrote its number and any voucher found there is a\n * stranger's. It is the one field rewritten with `set`: cleared before a\n * retry resends the number and written again only if ARCA rejects that send\n * too. A rejection that follows a submission left without an answer is not\n * marked, since that write may still land: the reservation stays pending and\n * its retries match a voucher there by its fiscal fields.\n * Readers that predate it ignore it and match a voucher there by its fiscal\n * fields, so every process sharing a store must run a release that knows it.\n */\nexport type ArcaAttemptRecord = {\n v: 1 | 2;\n operation: \"issue\" | \"creditNote\" | \"debitNote\";\n service?: \"wsfe\" | \"wsmtxca\";\n representedTaxId?: string;\n salesPoint: number;\n voucherType: number;\n number: number;\n inputHash: string;\n sent: WsfeVoucherInput & {\n lines?: readonly import(\"../services/issuance-wsmtxca\").WsmtxcaLine[];\n authorizedLines?: readonly import(\"../services/issuance-wsmtxca\").WsmtxcaLine[];\n details?: readonly import(\"../services/issuance-wsmtxca\").LegacyWsmtxcaLine[];\n };\n createdAt: string;\n rejectedAt?: string;\n};\n\n/**\n * Settled outcome of a reservation, created once with `add` and never\n * rewritten. A `conflict` records the voucher found at the reserved number, which without\n * `withLock` can be this key's own after a double submit. A\n * `superseded` record says the sequence moved past this reservation: the\n * barrier proved the number was empty and handed it to `by`, so this key can\n * never write. Authorizations are not recorded, because ARCA is their source of\n * truth, and rejections live on the reservation as `rejectedAt`, because a\n * retry may still write the number. A reader that does not know a future\n * `kind` refuses the record instead of guessing.\n */\nexport type ArcaSettledRecord =\n | {\n /** Version 1 stored `found` in ARCA's units; version 2 stores it normalized. */\n v: 1 | 2;\n kind: \"conflict\";\n number: number;\n found: import(\"../services/wsfe-identity\").VoucherSummary;\n settledAt: string;\n }\n | {\n v: 1;\n kind: \"superseded\";\n number: number;\n by: string;\n /** The CUIT `by` was claimed under. Without it, `by` shares this issuer. */\n byTaxId?: string;\n settledAt: string;\n };\n\nexport function attemptKey(\n environment: ArcaEnvironment,\n taxId: string,\n key: string\n): string {\n return `arca:v1:attempt:${environment}:${taxId}:${key}`;\n}\n\n/**\n * The last reservation claimed on one sequence through this store, written\n * with `set` under the sequence lock and before the reservation it names, so\n * no reservation can exist that the barrier does not see. `resolvedAt` marks a\n * claim whose fate ARCA already reported, on its first submission or on a\n * retry, so the next claim needs no consultation. A rejected key takes the\n * marker back, unresolved, before it resends its number. Only an unanswered\n * claim stays unresolved.\n */\nexport type ArcaSequenceRecord = {\n v: 1;\n key: string;\n /**\n * The issuer's CUIT: `key` names a reservation under it. Several issuers may\n * represent the taxpayer that owns the sequence. A marker without it names\n * the caller's own reservation.\n */\n issuerTaxId?: string;\n number: number;\n claimedAt: string;\n resolvedAt?: string;\n};\n\nexport function sequenceKey(\n environment: ArcaEnvironment,\n taxId: string,\n salesPoint: number,\n voucherType: number\n): string {\n return `arca:v1:sequence:${environment}:${taxId}:${salesPoint}:${voucherType}`;\n}\n\nexport function sequenceLockKey(\n environment: ArcaEnvironment,\n taxId: string,\n salesPoint: number,\n voucherType: number\n): string {\n return `arca:v1:lock:sequence:${environment}:${taxId}:${salesPoint}:${voucherType}`;\n}\n\nexport function settledKey(\n environment: ArcaEnvironment,\n taxId: string,\n key: string\n): string {\n return `arca:v1:settled:${environment}:${taxId}:${key}`;\n}\n\nexport function canonicalHash(input: unknown): string {\n return createHash(\"sha256\")\n .update(JSON.stringify(canonical(input)))\n .digest(\"hex\");\n}\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(canonical);\n }\n if (value instanceof Date) {\n return value.toJSON();\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, item]) => [key, canonical(item)])\n );\n }\n return value;\n}\n\nexport async function storeCall<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (cause) {\n throw new ArcaConfigurationError(\"ARCA store operation failed.\", { cause });\n }\n}\n","import { toIsoDate } from \"../internal/dates\";\nimport {\n normalizeArcaAmountToMinorUnits,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport { canonicalHash } from \"../store/types\";\nimport type { WsfeVatRate, WsfeVoucherInfo, WsfeVoucherInput } from \"./wsfe\";\nimport { normalizeWsfeDateInput } from \"./wsfe\";\n\nexport type VoucherCoordinates = {\n salesPoint: number;\n voucherType: number;\n number: number;\n};\n\n/**\n * Raw-free consultation evidence in the facade's units: money in minor units,\n * dates in `YYYY-MM-DD`. A field ARCA omits or reports unparseably is absent.\n */\nexport type VoucherSummary = {\n number: number;\n salesPoint?: number;\n voucherType?: number;\n date?: string;\n concept?: number;\n documentType?: number;\n documentNumber?: string;\n receiverVatConditionId?: number;\n currencyId?: string;\n exchangeRate?: number;\n totalAmount?: number;\n netAmount?: number;\n vatAmount?: number;\n exemptAmount?: number;\n nonTaxableAmount?: number;\n taxAmount?: number;\n vatRates?: { id: number; baseAmount: number; amount: number }[];\n serviceStartDate?: string;\n serviceEndDate?: string;\n paymentDueDate?: string;\n result?: string;\n cae?: string;\n caeExpiry?: string;\n};\n\nexport type WsfeIdentityMatch =\n | { matches: true }\n | { matches: false; evidence: \"conflict\" | \"incomplete\"; reason: string };\n\n/**\n * Compares the invoice subset supported by issue(): header identity, amounts,\n * VAT, tributes, associations, optional fields, buyers, activities and the\n * foreign-currency payment flag. This proves consistency, not authorship.\n * Configure a store and pass idempotencyKey for retries. Provider fields\n * outside that subset stay incomplete; a missing field is never proof.\n */\nexport function matchWsfeVoucherIdentity(\n sent: WsfeVoucherInput,\n number: number,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n let missing: string | undefined;\n const compare = (\n field: string,\n expected: unknown,\n actual: unknown,\n normalize?: (value: never) => unknown\n ): WsfeIdentityMatch | undefined => {\n if (actual === undefined || actual === null || expected === undefined) {\n missing ??= field;\n return undefined;\n }\n try {\n const left = normalize ? normalize(expected as never) : expected;\n const right = normalize ? normalize(actual as never) : actual;\n if (left !== right) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `${field} differs from the sent input`,\n };\n }\n } catch {\n missing ??= field;\n }\n return undefined;\n };\n const checks: [string, unknown, unknown, ((value: never) => unknown)?][] = [\n [\"voucherType\", sent.voucherType, found.voucherType],\n [\"salesPoint\", sent.salesPoint, found.salesPoint],\n [\"number\", number, found.voucherNumber, normalizeVoucherNumber],\n [\n \"date\",\n sent.voucherDate,\n found.voucherDate,\n (value) => normalizeWsfeDateInput(value, \"date\"),\n ],\n [\"concept\", sent.concept, found.concept],\n [\"documentType\", sent.documentType, found.documentType],\n [\n \"documentNumber\",\n sent.documentNumber,\n found.documentNumber,\n normalizeDocument,\n ],\n [\n \"receiverVatConditionId\",\n sent.receiverVatConditionId,\n found.receiverVatConditionId,\n ],\n [\"currencyId\", sent.currencyId, found.currencyId],\n [\n \"exchangeRate\",\n sent.exchangeRate ?? (sent.currencyId === \"PES\" ? 1 : undefined),\n found.exchangeRate,\n (value) => serializeArcaExchangeRate(value, \"exchangeRate\"),\n ],\n ];\n for (const field of [\n \"totalAmount\",\n \"netAmount\",\n \"vatAmount\",\n \"exemptAmount\",\n \"nonTaxableAmount\",\n \"taxAmount\",\n ] as const) {\n checks.push([\n field,\n sent[field],\n found[field],\n (value) => normalizeArcaAmountToMinorUnits(value, field),\n ]);\n }\n if (sent.concept === 2 || sent.concept === 3) {\n for (const field of [\n \"serviceStartDate\",\n \"serviceEndDate\",\n \"paymentDueDate\",\n ] as const) {\n checks.push([\n field,\n sent[field],\n found[field],\n (value) => normalizeWsfeDateInput(value, field),\n ]);\n }\n }\n if (sent.concept === 1 && sent.paymentDueDate) {\n checks.push([\n \"paymentDueDate\",\n sent.paymentDueDate,\n found.paymentDueDate,\n (value) => normalizeWsfeDateInput(value, \"paymentDueDate\"),\n ]);\n }\n for (const check of checks) {\n const result = compare(...check);\n if (result) {\n return result;\n }\n }\n const detailMatch = compareDetails(sent, found);\n if (!detailMatch.matches) {\n if (detailMatch.evidence === \"conflict\") {\n return detailMatch;\n }\n missing ??= detailMatch.reason;\n }\n missing ??= incompleteAuthorization(sent, found);\n return missing\n ? {\n matches: false,\n evidence: \"incomplete\",\n reason: `Cannot verify ${missing}`,\n }\n : { matches: true };\n}\n\nfunction incompleteAuthorization(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): string | undefined {\n let missing: string | undefined;\n // Authorization must be explicit even when all fiscal fields match.\n if (sent.concept !== 1 && sent.concept !== 2 && sent.concept !== 3) {\n missing ??= \"unsupported concept\";\n }\n if (!(found.result === \"A\" || found.result === \"O\")) {\n missing ??= \"authorized result\";\n }\n if (!found.cae?.trim()) {\n missing ??= \"cae\";\n }\n if (!found.caeExpiry?.trim()) {\n missing ??= \"caeExpiry\";\n }\n return missing;\n}\n\nfunction normalizeVoucherNumber(value: number): number {\n // The exact lookup mapper maps missing/malformed numbers to 0 or NaN.\n // Neither is evidence that a different voucher occupies the attempted number.\n if (!Number.isSafeInteger(value) || value < 1 || value > 99_999_999) {\n throw new Error(\"Invalid voucher number\");\n }\n return value;\n}\n\nfunction normalizeDocument(value: string | number): bigint {\n const text = String(value);\n if (!/^\\d+$/.test(text)) {\n throw new Error(\"Invalid document number\");\n }\n return BigInt(text);\n}\n\nfunction compareVatRates(\n expected: WsfeVatRate[],\n actual: WsfeVatRate[] | undefined\n): WsfeIdentityMatch {\n if (actual === undefined) {\n return expected.length === 0\n ? { matches: true }\n : { matches: false, evidence: \"incomplete\", reason: \"vatRates\" };\n }\n if (\n actual.length !== expected.length ||\n new Set(actual.map((rate) => rate.id)).size !== actual.length\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: \"vatRates ids differ from the sent input\",\n };\n }\n for (const rate of expected) {\n const found = actual.find((item) => item.id === rate.id);\n if (!found) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `vatRates id ${rate.id} differs from the sent input`,\n };\n }\n for (const field of [\"baseAmount\", \"amount\"] as const) {\n try {\n if (\n normalizeArcaAmountToMinorUnits(rate[field], field) !==\n normalizeArcaAmountToMinorUnits(found[field], field)\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `vatRates[${rate.id}].${field} differs from the sent input`,\n };\n }\n } catch {\n return {\n matches: false,\n evidence: \"incomplete\",\n reason: `vatRates[${rate.id}].${field}`,\n };\n }\n }\n }\n return { matches: true };\n}\n\n/**\n * Raw-free evidence in the facade's units: money in minor units, dates in\n * `YYYY-MM-DD`. A provider value that does not parse is left absent rather\n * than guessed.\n */\nexport function toVoucherSummary(found: WsfeVoucherInfo): VoucherSummary {\n const summary: VoucherSummary = { number: found.voucherNumber };\n for (const field of [\n \"salesPoint\",\n \"voucherType\",\n \"concept\",\n \"documentType\",\n \"documentNumber\",\n \"receiverVatConditionId\",\n \"currencyId\",\n \"exchangeRate\",\n \"result\",\n \"cae\",\n ] as const) {\n if (found[field] !== undefined) {\n Object.assign(summary, { [field]: found[field] });\n }\n }\n for (const field of [\n \"totalAmount\",\n \"netAmount\",\n \"vatAmount\",\n \"exemptAmount\",\n \"nonTaxableAmount\",\n \"taxAmount\",\n ] as const) {\n const minor = minorUnits(found[field]);\n if (minor !== undefined) {\n summary[field] = minor;\n }\n }\n for (const field of [\n \"serviceStartDate\",\n \"serviceEndDate\",\n \"paymentDueDate\",\n \"caeExpiry\",\n ] as const) {\n const iso = toIsoDate(found[field]);\n if (iso !== undefined) {\n summary[field] = iso;\n }\n }\n const date = toIsoDate(found.voucherDate);\n if (date !== undefined) {\n summary.date = date;\n }\n // One rate that does not parse drops the whole list: a half-converted row\n // would read as minor units and be off by a hundred.\n const vatRates = found.vatRates?.map(({ id, baseAmount, amount }) => {\n const base = minorUnits(baseAmount);\n const minor = minorUnits(amount);\n return base === undefined || minor === undefined\n ? undefined\n : { id, baseAmount: base, amount: minor };\n });\n if (vatRates?.every((rate) => rate !== undefined)) {\n summary.vatRates = vatRates as NonNullable<VoucherSummary[\"vatRates\"]>;\n }\n return summary;\n}\n\n/** A summary recorded before 0.15 kept ARCA's units; it reads as one now. */\nexport function normalizeLegacySummary(found: VoucherSummary): VoucherSummary {\n const { number, date, ...rest } = found;\n return toVoucherSummary({\n ...rest,\n voucherNumber: number,\n ...(date === undefined ? {} : { voucherDate: date }),\n raw: {},\n } as WsfeVoucherInfo);\n}\n\nfunction minorUnits(value: number | undefined): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n try {\n return Number(normalizeArcaAmountToMinorUnits(value, \"amount\"));\n } catch {\n return undefined;\n }\n}\n\nfunction compareAssociations(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n const expected = sent.associatedVouchers ?? [];\n const actual = found.associatedVouchers;\n if (!actual) {\n return expected.length\n ? { matches: false, evidence: \"incomplete\", reason: \"associatedVouchers\" }\n : { matches: true };\n }\n if (expected.length !== actual.length) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: \"associatedVouchers count differs\",\n };\n }\n for (const association of expected) {\n const match = actual.find(\n (v) =>\n v.type === association.type &&\n v.salesPoint === association.salesPoint &&\n v.number === association.number\n );\n if (!match) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: \"associatedVouchers differ from the sent input\",\n };\n }\n const metadata = compareAssociationMetadata(association, match);\n if (!metadata.matches) {\n return metadata;\n }\n }\n return { matches: true };\n}\nfunction compareDetails(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n let incomplete: WsfeIdentityMatch | undefined;\n for (const result of [\n compareVatRates(sent.vatRates ?? [], found.vatRates),\n compareAssociations(sent, found),\n compareExtensions(sent, found),\n ]) {\n if (result.matches) {\n continue;\n }\n if (result.evidence === \"conflict\") {\n return result;\n }\n incomplete ??= result;\n }\n return incomplete ?? { matches: true };\n}\n\nfunction extensionIdentity(field: string, value: unknown): string {\n if (Array.isArray(value)) {\n return canonicalHash(\n value\n .map((item) => {\n if (field === \"taxes\") {\n const tax = item as NonNullable<WsfeVoucherInput[\"taxes\"]>[number];\n return {\n id: tax.id,\n base: String(\n normalizeArcaAmountToMinorUnits(tax.baseAmount, \"base\")\n ),\n amount: String(\n normalizeArcaAmountToMinorUnits(tax.amount, \"amount\")\n ),\n rate: Number(tax.rate),\n };\n }\n return item;\n })\n .sort((a, b) => canonicalHash(a).localeCompare(canonicalHash(b)))\n );\n }\n if (field === \"associatedPeriod\" && value) {\n const period = value as NonNullable<WsfeVoucherInput[\"associatedPeriod\"]>;\n return canonicalHash({\n start: normalizeWsfeDateInput(period.startDate, \"start\"),\n end: normalizeWsfeDateInput(period.endDate, \"end\"),\n });\n }\n return canonicalHash(value ?? null);\n}\n\nfunction compareExtensions(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n let missing: string | undefined;\n for (const field of [\n \"taxes\",\n \"optionalFields\",\n \"buyers\",\n \"activities\",\n \"associatedPeriod\",\n \"sameCurrencyForeignCancellation\",\n ] as const) {\n const expected = sent[field];\n const actual = found[field];\n const empty = (value: unknown) =>\n value === undefined || (Array.isArray(value) && value.length === 0);\n if (empty(expected) && empty(actual)) {\n continue;\n }\n if (actual === undefined) {\n missing ??= field;\n continue;\n }\n try {\n if (\n extensionIdentity(field, expected) !== extensionIdentity(field, actual)\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `${field} differs from the sent input`,\n };\n }\n } catch {\n missing ??= field;\n }\n }\n\n return missing\n ? { matches: false, evidence: \"incomplete\", reason: missing }\n : { matches: true };\n}\n\nfunction compareAssociationMetadata(\n association: NonNullable<WsfeVoucherInput[\"associatedVouchers\"]>[number],\n match: NonNullable<WsfeVoucherInput[\"associatedVouchers\"]>[number]\n): WsfeIdentityMatch {\n for (const field of [\"taxId\", \"voucherDate\"] as const) {\n if (association[field] === undefined) {\n continue;\n }\n if (match[field] === undefined) {\n return {\n matches: false,\n evidence: \"incomplete\",\n reason: `associatedVouchers.${field}`,\n };\n }\n const normalize = (value: string) =>\n field === \"taxId\"\n ? String(BigInt(value))\n : normalizeWsfeDateInput(\n value as import(\"./wsfe\").WsfeDateInput,\n \"association.date\"\n );\n try {\n if (\n normalize(association[field] as string) !==\n normalize(match[field] as string)\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `associatedVouchers.${field} differs`,\n };\n }\n } catch {\n return {\n matches: false,\n evidence: \"incomplete\",\n reason: `associatedVouchers.${field}`,\n };\n }\n }\n return { matches: true };\n}\n","import type {\n ArcaAuthCredentials,\n ArcaWsaaSessionKey,\n ArcaWsaaSessionStore,\n} from \"../internal/types\";\n\nconst CREDENTIAL_EXPIRY_SAFETY_MARGIN_MS = 60_000;\n\nexport function createMemoryWsaaSessionStore(): ArcaWsaaSessionStore {\n const sessions = new Map<string, ArcaAuthCredentials>();\n const locks = new Map<string, Promise<void>>();\n\n return {\n get(key) {\n const credentials = sessions.get(serializeWsaaSessionKey(key));\n if (!(credentials && isWsaaCredentialValid(credentials))) {\n return Promise.resolve(null);\n }\n\n return Promise.resolve({ ...credentials });\n },\n set(key, credentials) {\n sessions.set(serializeWsaaSessionKey(key), { ...credentials });\n return Promise.resolve();\n },\n delete(key) {\n sessions.delete(serializeWsaaSessionKey(key));\n return Promise.resolve();\n },\n async withLock(key, fn) {\n const lockKey = serializeWsaaSessionKey(key);\n const previous = locks.get(lockKey) ?? Promise.resolve();\n let release: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const queued = previous.catch(() => undefined).then(() => current);\n locks.set(lockKey, queued);\n\n await previous.catch(() => undefined);\n\n try {\n return await fn();\n } finally {\n release();\n if (locks.get(lockKey) === queued) {\n locks.delete(lockKey);\n }\n }\n },\n };\n}\n\nexport function serializeWsaaSessionKey(key: ArcaWsaaSessionKey): string {\n return [key.environment, key.service, key.certificateFingerprint].join(\":\");\n}\n\nexport function isWsaaCredentialValid(\n credentials: ArcaAuthCredentials\n): boolean {\n return (\n new Date(credentials.expiresAt).getTime() - Date.now() >\n CREDENTIAL_EXPIRY_SAFETY_MARGIN_MS\n );\n}\n","import { createHash } from \"node:crypto\";\nimport forge from \"node-forge\";\nimport { ARCA_WSAA_CONFIG } from \"../config\";\nimport {\n ArcaConfigurationError,\n ArcaLockTimeoutError,\n ArcaSoapFaultError,\n ArcaTransportError,\n} from \"../errors\";\nimport { abortable } from \"../internal/abort\";\nimport { postXmlWithMetadata } from \"../internal/http\";\nimport type { ArcaLogger } from \"../internal/logger\";\nimport { createSafeErrorDiagnostic } from \"../internal/redaction\";\nimport type {\n ArcaAuthCredentials,\n ArcaAuthOptions,\n ArcaClientConfig,\n ArcaWsaaServiceId,\n ArcaWsaaSessionKey,\n} from \"../internal/types\";\nimport {\n buildSoapEnvelope,\n getSingleBodyEntry,\n parseSoapBody,\n parseXmlDocument,\n} from \"../internal/xml\";\nimport {\n isWsaaCredentialValid,\n serializeWsaaSessionKey,\n} from \"./session-store\";\n\nexport type WsaaAuthModule = {\n login(\n service: ArcaWsaaServiceId,\n options?: ArcaAuthOptions\n ): Promise<ArcaAuthCredentials>;\n};\n\nexport type CreateWsaaAuthModuleOptions = {\n config: ArcaClientConfig;\n logger?: ArcaLogger;\n};\n\ntype ForgeSignerOptions = Parameters<\n forge.pkcs7.PkcsSignedData[\"addSigner\"]\n>[0];\ntype ForgeAuthenticatedAttribute = NonNullable<\n ForgeSignerOptions[\"authenticatedAttributes\"]\n>[number];\ntype WsaaAuthenticatedAttribute = Omit<ForgeAuthenticatedAttribute, \"value\"> & {\n value?: string | Date;\n};\n\nexport function createWsaaAuthModule(\n options: CreateWsaaAuthModuleOptions\n): WsaaAuthModule {\n const cache = new Map<string, ArcaAuthCredentials>();\n const ordinaryInFlight = new Map<string, Promise<ArcaAuthCredentials>>();\n const forcedInFlight = new Map<string, Promise<ArcaAuthCredentials>>();\n\n function trackLogin(\n target: Map<string, Promise<ArcaAuthCredentials>>,\n cacheKey: string,\n login: () => Promise<ArcaAuthCredentials>\n ): Promise<ArcaAuthCredentials> {\n const promise = login();\n target.set(cacheKey, promise);\n const cleanup = () => {\n if (target.get(cacheKey) === promise) {\n target.delete(cacheKey);\n }\n };\n promise.then(cleanup, cleanup);\n return promise;\n }\n\n async function requestOrReuseWsaaCredentials(\n service: ArcaWsaaServiceId,\n sessionKey: ArcaWsaaSessionKey,\n cacheKey: string,\n forceRefresh: boolean\n ): Promise<ArcaAuthCredentials> {\n const reuse = await getReusableCredentials({\n config: options.config,\n cache,\n cacheKey,\n sessionKey,\n logger: options.logger,\n service,\n allowStore: !forceRefresh,\n allowCache: !forceRefresh,\n });\n if (reuse) {\n return reuse;\n }\n\n const refresh = () =>\n refreshWsaaCredentials({\n config: options.config,\n cache,\n cacheKey,\n sessionKey,\n logger: options.logger,\n service,\n forceRefresh,\n });\n\n if (options.config.wsaaSessionStore?.withLock) {\n return await withWsaaSessionStoreLock(\n options.config,\n sessionKey,\n service,\n refresh\n );\n }\n\n return await refresh();\n }\n\n async function performLogin(\n service: ArcaWsaaServiceId,\n sessionKey: ArcaWsaaSessionKey,\n cacheKey: string,\n forceRefresh: boolean\n ): Promise<ArcaAuthCredentials> {\n try {\n return await requestOrReuseWsaaCredentials(\n service,\n sessionKey,\n cacheKey,\n forceRefresh\n );\n } catch (error) {\n if (\n error instanceof ArcaSoapFaultError &&\n error.faultCode === \"ns1:coe.alreadyAuthenticated\"\n ) {\n const recovered = await getReusableCredentials({\n config: options.config,\n cache,\n cacheKey,\n sessionKey,\n logger: options.logger,\n service,\n allowStore: true,\n allowCache: true,\n });\n if (recovered) {\n options.logger?.warn(\n \"Recovered WSAA coe.alreadyAuthenticated fault\",\n {\n service,\n faultCode: error.faultCode,\n }\n );\n return recovered;\n }\n\n if (!options.config.wsaaSessionStore) {\n throw new ArcaConfigurationError(\n \"WSAA login failed because another process likely owns a valid TA. Configure a durable wsaaSessionStore for multi-process or serverless deployments.\",\n { cause: error }\n );\n }\n }\n\n if (error instanceof ArcaSoapFaultError) {\n options.logger?.error(\"WSAA SOAP fault response\", {\n service,\n operation: \"loginCms\",\n url: ARCA_WSAA_CONFIG.endpoint[options.config.environment],\n ...createSafeErrorDiagnostic(error),\n });\n }\n\n throw error;\n }\n }\n\n return {\n login(service, authOptions = {}) {\n // A deduplicated login is shared: the caller stops waiting on its own\n // deadline, and the request keeps running for the other waiters.\n return abortable(runLogin(service, authOptions), authOptions.abortSignal);\n },\n };\n\n function runLogin(\n service: ArcaWsaaServiceId,\n authOptions: ArcaAuthOptions\n ): Promise<ArcaAuthCredentials> {\n const sessionKey = buildWsaaSessionKey(options.config, service);\n const cacheKey = serializeWsaaSessionKey(sessionKey);\n\n if (authOptions.forceRefresh) {\n const runningForced = forcedInFlight.get(cacheKey);\n if (runningForced) {\n return runningForced;\n }\n\n const runningOrdinary = ordinaryInFlight.get(cacheKey);\n return trackLogin(forcedInFlight, cacheKey, async () => {\n await runningOrdinary?.catch(() => undefined);\n return await performLogin(service, sessionKey, cacheKey, true);\n });\n }\n\n const runningOrdinary = ordinaryInFlight.get(cacheKey);\n if (runningOrdinary) {\n return runningOrdinary;\n }\n\n const runningForced = forcedInFlight.get(cacheKey);\n if (runningForced) {\n return runningForced;\n }\n\n return trackLogin(ordinaryInFlight, cacheKey, () =>\n performLogin(service, sessionKey, cacheKey, false)\n );\n }\n}\n\nasync function requestCredentials(\n config: ArcaClientConfig,\n service: ArcaWsaaServiceId,\n options?: {\n logger?: ArcaLogger;\n }\n): Promise<ArcaAuthCredentials> {\n const loginTicketRequestXml = buildLoginTicketRequest(service);\n const signedCms = signLoginTicketRequest(loginTicketRequestXml, {\n certificatePem: config.certificatePem,\n privateKeyPem: config.privateKeyPem,\n });\n\n const requestXml = buildSoapEnvelope(\n ARCA_WSAA_CONFIG.soapVersion,\n \"loginCms\",\n ARCA_WSAA_CONFIG.namespace,\n { in0: signedCms }\n );\n\n const url = ARCA_WSAA_CONFIG.endpoint[config.environment];\n const response = await postXmlWithMetadata({\n url: ARCA_WSAA_CONFIG.endpoint[config.environment],\n body: requestXml,\n contentType: 'text/xml; charset=\"utf-8\"',\n soapAction: ARCA_WSAA_CONFIG.soapActionBase,\n timeout: config.timeout,\n retries: config.retries,\n retryDelay: config.retryDelay,\n logger: options?.logger,\n service: \"wsaa\",\n operation: \"loginCms\",\n });\n const parseContext = {\n service: \"wsaa\" as const,\n operation: \"loginCms\",\n endpointUrl: url,\n statusCode: response.statusCode,\n contentType: response.contentType,\n responseBody: response.body,\n };\n\n const soapBody = parseSoapBody(response.body, parseContext);\n const [, responseBody] = getSingleBodyEntry<Record<string, unknown>>(\n soapBody,\n parseContext\n );\n const loginCmsReturn = responseBody.loginCmsReturn;\n\n if (typeof loginCmsReturn !== \"string\" || loginCmsReturn.trim().length < 1) {\n throw new ArcaTransportError(\n \"WSAA response did not include loginCmsReturn XML\"\n );\n }\n\n return parseLoginTicketResponse(loginCmsReturn);\n}\n\nfunction buildWsaaSessionKey(\n config: ArcaClientConfig,\n service: ArcaWsaaServiceId\n): ArcaWsaaSessionKey {\n return {\n environment: config.environment,\n service,\n certificateFingerprint: getCertificateFingerprint(config),\n };\n}\n\nfunction getCertificateFingerprint(config: ArcaClientConfig): string {\n return createHash(\"sha256\").update(config.certificatePem).digest(\"hex\");\n}\n\nfunction getCachedCredentials(\n cache: Map<string, ArcaAuthCredentials>,\n cacheKey: string\n): ArcaAuthCredentials | null {\n const localCached = cache.get(cacheKey);\n if (localCached && isWsaaCredentialValid(localCached)) {\n return localCached;\n }\n\n return null;\n}\n\nasync function getReusableCredentials(options: {\n config: ArcaClientConfig;\n cache: Map<string, ArcaAuthCredentials>;\n cacheKey: string;\n sessionKey: ArcaWsaaSessionKey;\n logger?: ArcaLogger;\n service: ArcaWsaaServiceId;\n allowStore: boolean;\n allowCache: boolean;\n}): Promise<ArcaAuthCredentials | null> {\n if (options.allowCache) {\n const cached = getCachedCredentials(options.cache, options.cacheKey);\n if (cached) {\n options.logger?.debug(\"Attempting WSAA login\", {\n service: options.service,\n source: \"cached\",\n });\n return cached;\n }\n }\n\n if (!(options.allowStore && options.config.wsaaSessionStore)) {\n return null;\n }\n\n const stored = await getStoredCredentials(\n options.config,\n options.sessionKey,\n options.service\n );\n if (!stored) {\n return null;\n }\n\n options.cache.set(options.cacheKey, stored);\n options.logger?.debug(\"Attempting WSAA login\", {\n service: options.service,\n source: \"store\",\n });\n return stored;\n}\n\nasync function refreshWsaaCredentials(options: {\n config: ArcaClientConfig;\n cache: Map<string, ArcaAuthCredentials>;\n cacheKey: string;\n sessionKey: ArcaWsaaSessionKey;\n logger?: ArcaLogger;\n service: ArcaWsaaServiceId;\n forceRefresh: boolean;\n}): Promise<ArcaAuthCredentials> {\n if (!options.forceRefresh) {\n const reuse = await getReusableCredentials({\n config: options.config,\n cache: options.cache,\n cacheKey: options.cacheKey,\n sessionKey: options.sessionKey,\n logger: options.logger,\n service: options.service,\n allowStore: true,\n allowCache: true,\n });\n if (reuse) {\n return reuse;\n }\n }\n\n options.logger?.debug(\"Attempting WSAA login\", {\n service: options.service,\n source: \"fresh\",\n });\n\n const credentials = await requestCredentials(\n options.config,\n options.service,\n {\n logger: options.logger,\n }\n );\n options.logger?.info(\"WSAA login succeeded\", {\n service: options.service,\n expiresAt: credentials.expiresAt,\n });\n options.cache.set(options.cacheKey, credentials);\n await setStoredCredentials(options.config, options.sessionKey, credentials);\n return credentials;\n}\n\nasync function getStoredCredentials(\n config: ArcaClientConfig,\n key: ArcaWsaaSessionKey,\n service: ArcaWsaaServiceId\n): Promise<ArcaAuthCredentials | null> {\n if (!config.wsaaSessionStore) {\n return null;\n }\n\n try {\n const credentials = await config.wsaaSessionStore.get(key);\n if (!(credentials && isWsaaCredentialValid(credentials))) {\n return null;\n }\n\n return credentials;\n } catch (error) {\n throw new ArcaConfigurationError(\n `WSAA session store get failed for service ${service}`,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n}\n\nasync function setStoredCredentials(\n config: ArcaClientConfig,\n key: ArcaWsaaSessionKey,\n credentials: ArcaAuthCredentials\n): Promise<void> {\n if (!config.wsaaSessionStore) {\n return;\n }\n\n try {\n await config.wsaaSessionStore.set(key, credentials);\n } catch (error) {\n throw new ArcaConfigurationError(\n `WSAA session store set failed for service ${key.service}`,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n}\n\nasync function withWsaaSessionStoreLock<T>(\n config: ArcaClientConfig,\n key: ArcaWsaaSessionKey,\n service: ArcaWsaaServiceId,\n fn: () => Promise<T>\n): Promise<T> {\n const store = config.wsaaSessionStore;\n if (!store?.withLock) {\n return await fn();\n }\n\n let entered = false;\n try {\n return await store.withLock(key, async () => {\n entered = true;\n return await fn();\n });\n } catch (error) {\n if (entered) {\n throw error;\n }\n\n if (\n error instanceof ArcaConfigurationError ||\n error instanceof ArcaLockTimeoutError\n ) {\n throw error;\n }\n\n throw new ArcaConfigurationError(\n `WSAA session store lock failed for service ${service}`,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n}\n\nfunction buildLoginTicketRequest(service: ArcaWsaaServiceId): string {\n const uniqueId = Math.floor(Date.now() / 1000);\n const generationTime = new Date(Date.now() - 5 * 60_000)\n .toISOString()\n .replace(\".000Z\", \"Z\");\n const expirationTime = new Date(Date.now() + 5 * 60_000)\n .toISOString()\n .replace(\".000Z\", \"Z\");\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<loginTicketRequest version=\"1.0\">\n <header>\n <uniqueId>${uniqueId}</uniqueId>\n <generationTime>${generationTime}</generationTime>\n <expirationTime>${expirationTime}</expirationTime>\n </header>\n <service>${service}</service>\n</loginTicketRequest>`;\n}\n\nfunction signLoginTicketRequest(\n loginTicketRequestXml: string,\n options: Pick<ArcaClientConfig, \"certificatePem\" | \"privateKeyPem\">\n): string {\n const certificate = forge.pki.certificateFromPem(options.certificatePem);\n const privateKey = forge.pki.privateKeyFromPem(options.privateKeyPem);\n const signedData = forge.pkcs7.createSignedData();\n\n signedData.content = forge.util.createBuffer(loginTicketRequestXml, \"utf8\");\n signedData.addCertificate(certificate);\n const authenticatedAttributes: WsaaAuthenticatedAttribute[] = [\n {\n type: String(forge.pki.oids.contentType),\n value: String(forge.pki.oids.data),\n },\n {\n type: String(forge.pki.oids.messageDigest),\n },\n {\n type: String(forge.pki.oids.signingTime),\n value: new Date(),\n },\n ];\n\n const signerOptions: ForgeSignerOptions = {\n key: privateKey,\n certificate,\n digestAlgorithm: String(forge.pki.oids.sha1),\n authenticatedAttributes:\n authenticatedAttributes as unknown as ForgeSignerOptions[\"authenticatedAttributes\"],\n };\n\n signedData.addSigner(signerOptions);\n signedData.sign();\n\n const der = forge.asn1.toDer(signedData.toAsn1()).getBytes();\n return Buffer.from(der, \"binary\").toString(\"base64\");\n}\n\nfunction parseLoginTicketResponse(xml: string): ArcaAuthCredentials {\n const parsed = parseXmlDocument<Record<string, unknown>>(xml);\n const response =\n (parsed.loginTicketResponse as Record<string, unknown> | undefined) ??\n parsed;\n const header = response.header as Record<string, unknown> | undefined;\n const credentials = response.credentials as\n | Record<string, unknown>\n | undefined;\n const token = credentials?.token;\n const sign = credentials?.sign;\n const expiresAt = header?.expirationTime;\n\n if (\n typeof token !== \"string\" ||\n typeof sign !== \"string\" ||\n typeof expiresAt !== \"string\"\n ) {\n throw new ArcaTransportError(\n \"Invalid WSAA login ticket response structure\"\n );\n }\n\n return {\n token,\n sign,\n expiresAt,\n };\n}\n","import { ArcaTransportError } from \"../errors\";\n\n/** The caller's deadline, reported as a transport failure with its reason. */\nexport function abortedError(signal?: AbortSignal): ArcaTransportError {\n return new ArcaTransportError(\"The ARCA call was aborted\", {\n cause: signal?.reason,\n });\n}\n\n/**\n * Stops waiting when the caller's deadline fires. Shared work, such as a WSAA\n * login another call is also waiting for, keeps running for its other waiters.\n */\nexport function abortable<T>(\n promise: Promise<T>,\n signal?: AbortSignal\n): Promise<T> {\n if (!signal) {\n return promise;\n }\n if (signal.aborted) {\n // The caller still owns the promise; keep its rejection handled.\n promise.catch(() => undefined);\n return Promise.reject(abortedError(signal));\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortedError(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise\n .then(resolve, reject)\n .finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n","import https from \"node:https\";\nimport { ArcaTransportError } from \"../errors\";\nimport type { ArcaLogger } from \"./logger\";\nimport {\n createResponseBodyDiagnostic,\n createSafeErrorDiagnostic,\n} from \"./redaction\";\n\nconst defaultAgent = new https.Agent({\n keepAlive: true,\n});\n\nconst legacyTlsAgent = new https.Agent({\n keepAlive: true,\n ciphers: \"DEFAULT@SECLEVEL=0\",\n});\n\ntype PostXmlOptions = {\n url: string;\n body: string;\n contentType: string;\n soapAction?: string;\n useLegacyTlsSecurityLevel0?: boolean;\n timeout?: number;\n retries?: number;\n retryDelay?: number;\n logger?: ArcaLogger;\n service?: string;\n operation?: string;\n signal?: AbortSignal;\n};\n\nexport type PostXmlResponse = {\n body: string;\n statusCode?: number;\n contentType?: string;\n};\n\nexport async function postXml({ ...options }: PostXmlOptions): Promise<string> {\n const response = await postXmlWithMetadata(options);\n return response.body;\n}\n\nexport async function postXmlWithMetadata({\n url,\n body,\n contentType,\n soapAction,\n useLegacyTlsSecurityLevel0 = false,\n timeout = 30_000,\n retries = 0,\n retryDelay = 500,\n logger,\n service,\n operation,\n signal,\n}: PostXmlOptions): Promise<PostXmlResponse> {\n const totalAttempts = retries + 1;\n for (let attempt = 1; attempt <= totalAttempts; attempt += 1) {\n try {\n return await postXmlOnce({\n url,\n body,\n contentType,\n soapAction,\n useLegacyTlsSecurityLevel0,\n timeout,\n signal,\n });\n } catch (error) {\n if (!(error instanceof ArcaTransportError)) {\n throw error;\n }\n\n // An aborted call is the caller's deadline, never a transient failure.\n if (attempt >= totalAttempts || signal?.aborted) {\n logger?.error(\"ARCA transport request failed\", {\n service,\n operation,\n url,\n attempt,\n attempts: totalAttempts,\n ...createSafeErrorDiagnostic(error),\n });\n throw error;\n }\n\n const nextAttempt = attempt + 1;\n logger?.warn(\n `Retrying ARCA request after transport failure (attempt ${nextAttempt}/${totalAttempts})`,\n {\n service,\n operation,\n url,\n attempt: nextAttempt,\n attempts: totalAttempts,\n ...createSafeErrorDiagnostic(error),\n }\n );\n await delay(retryDelay);\n }\n }\n\n throw new ArcaTransportError(\"ARCA HTTP request exhausted retries\");\n}\n\nasync function postXmlOnce({\n url,\n body,\n contentType,\n soapAction,\n useLegacyTlsSecurityLevel0,\n timeout,\n signal,\n}: Required<\n Pick<\n PostXmlOptions,\n \"url\" | \"body\" | \"contentType\" | \"useLegacyTlsSecurityLevel0\" | \"timeout\"\n >\n> &\n Pick<PostXmlOptions, \"soapAction\" | \"signal\">): Promise<PostXmlResponse> {\n const endpoint = new URL(url);\n const requestBody = Buffer.from(body, \"utf8\");\n if (signal?.aborted) {\n throw new ArcaTransportError(\"ARCA HTTP request was aborted\", {\n cause: signal.reason,\n });\n }\n\n return await new Promise((resolve, reject) => {\n let settled = false;\n const settleResolve = (response: PostXmlResponse) => {\n if (settled) {\n return;\n }\n settled = true;\n resolve(response);\n };\n const settleReject = (error: ArcaTransportError) => {\n if (settled) {\n return;\n }\n settled = true;\n reject(error);\n };\n const request = https.request(\n {\n protocol: endpoint.protocol,\n hostname: endpoint.hostname,\n port: endpoint.port || undefined,\n path: `${endpoint.pathname}${endpoint.search}`,\n method: \"POST\",\n agent: useLegacyTlsSecurityLevel0 ? legacyTlsAgent : defaultAgent,\n headers: {\n Accept: \"text/xml, application/soap+xml\",\n \"Content-Length\": requestBody.byteLength,\n \"Content-Type\": contentType,\n ...(soapAction === undefined\n ? {}\n : { SOAPAction: `\"${soapAction}\"` }),\n },\n },\n (response) => {\n const chunks: Buffer[] = [];\n const getResponseBody = () => Buffer.concat(chunks).toString(\"utf8\");\n\n response.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(\n typeof chunk === \"string\" ? Buffer.from(chunk, \"utf8\") : chunk\n );\n });\n\n response.on(\"error\", (error) => {\n settleReject(\n new ArcaTransportError(\"ARCA HTTP response stream failed\", {\n cause: error,\n statusCode: response.statusCode,\n ...createResponseBodyDiagnostic(getResponseBody()),\n })\n );\n });\n\n response.on(\"aborted\", () => {\n settleReject(\n new ArcaTransportError(\"ARCA HTTP response was aborted\", {\n statusCode: response.statusCode,\n ...createResponseBodyDiagnostic(getResponseBody()),\n })\n );\n });\n\n response.on(\"end\", () => {\n const responseBody = getResponseBody();\n const statusCode = response.statusCode ?? 500;\n const responseContentType = Array.isArray(\n response.headers[\"content-type\"]\n )\n ? response.headers[\"content-type\"].join(\"; \")\n : response.headers[\"content-type\"];\n\n if (statusCode >= 200 && statusCode < 300) {\n settleResolve({\n body: responseBody,\n statusCode,\n contentType: responseContentType,\n });\n return;\n }\n\n // SOAP services commonly return structured fault payloads with HTTP\n // 500. Let higher layers parse those XML faults instead of forcing a\n // transport error here.\n if (isXmlLikeResponse(responseBody, responseContentType)) {\n settleResolve({\n body: responseBody,\n statusCode,\n contentType: responseContentType,\n });\n return;\n }\n\n settleReject(\n new ArcaTransportError(\n `ARCA HTTP request failed with status ${statusCode}`,\n {\n statusCode,\n contentType: responseContentType,\n ...createResponseBodyDiagnostic(responseBody),\n }\n )\n );\n });\n }\n );\n\n request.setTimeout(timeout, () => {\n const timeoutCause = new Error(\n `ARCA HTTP request timed out after ${timeout}ms`\n );\n settleReject(\n new ArcaTransportError(\n `ARCA HTTP request timed out after ${timeout}ms`,\n { cause: timeoutCause }\n )\n );\n request.destroy(timeoutCause);\n });\n\n request.on(\"error\", (error) => {\n settleReject(\n new ArcaTransportError(\"ARCA HTTP request failed\", {\n cause: error,\n })\n );\n });\n\n const abort = () => {\n const cause = new Error(\"ARCA HTTP request was aborted\");\n settleReject(\n new ArcaTransportError(\"ARCA HTTP request was aborted\", { cause })\n );\n request.destroy(cause);\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n request.on(\"close\", () => signal?.removeEventListener(\"abort\", abort));\n\n request.write(requestBody);\n request.end();\n });\n}\n\nfunction isXmlLikeResponse(body: string, contentType?: string): boolean {\n const normalizedContentType = contentType?.toLowerCase() ?? \"\";\n if (\n normalizedContentType.includes(\"xml\") ||\n normalizedContentType.includes(\"soap\")\n ) {\n return true;\n }\n\n return body.trimStart().startsWith(\"<\");\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","import { XMLBuilder, XMLParser } from \"fast-xml-parser\";\nimport { ArcaInvalidSoapResponseError, ArcaSoapFaultError } from \"../errors\";\nimport type { ArcaServiceName, ArcaSoapVersion } from \"../internal/types\";\nimport { createResponseBodyDiagnostic } from \"./redaction\";\n\nconst xmlBuilder = new XMLBuilder({\n attributeNamePrefix: \"@_\",\n format: false,\n ignoreAttributes: false,\n suppressBooleanAttributes: false,\n suppressEmptyNode: true,\n});\n\nconst xmlParser = new XMLParser({\n attributeNamePrefix: \"@_\",\n ignoreAttributes: false,\n parseAttributeValue: false,\n parseTagValue: false,\n removeNSPrefix: true,\n trimValues: true,\n});\n\nexport type ArcaSoapParseContext = {\n service?: ArcaServiceName;\n operation?: string;\n endpointUrl?: string;\n statusCode?: number;\n contentType?: string;\n responseBody?: string;\n responseBodyPreviewLength?: number;\n};\n\nexport function buildSoapEnvelope(\n soapVersion: ArcaSoapVersion,\n operation: string,\n namespace: string,\n body: Record<string, unknown>,\n options?: {\n namespaceMode?: \"default\" | \"prefix\";\n }\n): string {\n const prefix = soapVersion === \"1.2\" ? \"soap12\" : \"soap\";\n const envelopeNamespace =\n soapVersion === \"1.2\"\n ? \"http://www.w3.org/2003/05/soap-envelope\"\n : \"http://schemas.xmlsoap.org/soap/envelope/\";\n const namespaceMode = options?.namespaceMode ?? \"default\";\n const operationElementName =\n namespaceMode === \"prefix\" ? `tns:${operation}` : operation;\n const operationNamespaceAttributes =\n namespaceMode === \"prefix\"\n ? { \"@_xmlns:tns\": namespace }\n : { \"@_xmlns\": namespace };\n\n const payload = {\n [`${prefix}:Envelope`]: {\n \"@_xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\n \"@_xmlns:xsd\": \"http://www.w3.org/2001/XMLSchema\",\n [`@_xmlns:${prefix}`]: envelopeNamespace,\n [`${prefix}:Body`]: {\n [operationElementName]: {\n ...operationNamespaceAttributes,\n ...pruneUndefinedDeep(body),\n },\n },\n },\n };\n\n return `<?xml version=\"1.0\" encoding=\"utf-8\"?>${xmlBuilder.build(payload)}`;\n}\n\nexport function parseSoapBody(\n xml: string,\n context: ArcaSoapParseContext = {}\n): Record<string, unknown> {\n let parsed: Record<string, unknown>;\n try {\n parsed = xmlParser.parse(xml) as Record<string, unknown>;\n } catch (error) {\n throw createInvalidSoapResponseError(\n \"Invalid SOAP response: XML parse failed\",\n context,\n error instanceof Error ? error : undefined\n );\n }\n\n const envelope = parsed.Envelope as Record<string, unknown> | undefined;\n const body = envelope?.Body as Record<string, unknown> | undefined;\n\n if (!body) {\n throw createInvalidSoapResponseError(\n \"Invalid SOAP response: missing body\",\n context\n );\n }\n\n const fault = body.Fault as Record<string, unknown> | undefined;\n if (fault) {\n throw createSoapFaultError(fault);\n }\n\n return body;\n}\n\nexport function getSingleBodyEntry<T = unknown>(\n body: Record<string, unknown>,\n context: ArcaSoapParseContext = {}\n): [string, T] {\n const entries = Object.entries(body).filter(([key]) => key !== \"@_xmlns\");\n if (entries.length !== 1) {\n throw createInvalidSoapResponseError(\n `Invalid SOAP response: expected a single body entry, got ${entries.length}`,\n context\n );\n }\n\n return entries[0] as [string, T];\n}\n\nfunction createInvalidSoapResponseError(\n message: string,\n context: ArcaSoapParseContext,\n cause?: Error\n): ArcaInvalidSoapResponseError {\n const responseBody = context.responseBody ?? \"\";\n\n return new ArcaInvalidSoapResponseError(message, {\n cause,\n service: context.service,\n operation: context.operation,\n endpointUrl: context.endpointUrl,\n statusCode: context.statusCode,\n contentType: context.contentType,\n ...createResponseBodyDiagnostic(\n responseBody,\n context.responseBodyPreviewLength\n ),\n });\n}\n\nexport function parseXmlDocument<T = unknown>(xml: string): T {\n return xmlParser.parse(xml) as T;\n}\n\nexport function pruneUndefinedDeep<T>(value: T): T {\n if (Array.isArray(value)) {\n return value\n .map((item) => pruneUndefinedDeep(item))\n .filter((item) => item !== undefined) as T;\n }\n\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, nestedValue]) => nestedValue !== undefined)\n .map(([key, nestedValue]) => [key, pruneUndefinedDeep(nestedValue)]);\n return Object.fromEntries(entries) as T;\n }\n\n return value;\n}\n\nfunction createSoapFaultError(\n fault: Record<string, unknown>\n): ArcaSoapFaultError {\n const faultCode =\n typeof fault.faultcode === \"string\"\n ? fault.faultcode\n : getNestedString(fault, [\"Code\", \"Value\"]);\n const message =\n typeof fault.faultstring === \"string\"\n ? fault.faultstring\n : (getNestedString(fault, [\"Reason\", \"Text\"]) ??\n \"ARCA SOAP fault response\");\n\n return new ArcaSoapFaultError(message, {\n faultCode: faultCode ?? undefined,\n });\n}\n\nfunction getNestedString(\n value: Record<string, unknown>,\n path: string[]\n): string | null {\n let current: unknown = value;\n for (const key of path) {\n if (!current || typeof current !== \"object\") {\n return null;\n }\n current = (current as Record<string, unknown>)[key];\n }\n return typeof current === \"string\" ? current : null;\n}\n","import type { ArcaLoggerConfig, ArcaLogLevel } from \"./types\";\n\nconst ARCA_LOG_LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] as const;\n\nexport type ArcaLogger = {\n disabled: boolean;\n level: ArcaLogLevel;\n log: (level: ArcaLogLevel, message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n};\n\nexport function createArcaLogger(config?: ArcaLoggerConfig): ArcaLogger {\n const disabled = config?.disabled ?? false;\n const level = resolveArcaLogLevel(config?.level);\n const sink = config?.log ?? defaultArcaLog;\n\n const log = (\n messageLevel: ArcaLogLevel,\n message: string,\n ...args: unknown[]\n ) => {\n if (disabled || !shouldLog(level, messageLevel)) {\n return;\n }\n\n sink(messageLevel, message, ...args);\n };\n\n return {\n disabled,\n level,\n log,\n debug(message, ...args) {\n log(\"debug\", message, ...args);\n },\n info(message, ...args) {\n log(\"info\", message, ...args);\n },\n warn(message, ...args) {\n log(\"warn\", message, ...args);\n },\n error(message, ...args) {\n log(\"error\", message, ...args);\n },\n };\n}\n\nexport function resolveArcaLogLevel(level?: string): ArcaLogLevel {\n if (isArcaLogLevel(level)) {\n return level;\n }\n\n const envLevel = process.env.ARCA_LOG_LEVEL?.trim().toLowerCase();\n if (isArcaLogLevel(envLevel)) {\n return envLevel;\n }\n\n return \"warn\";\n}\n\nfunction shouldLog(\n threshold: ArcaLogLevel,\n messageLevel: ArcaLogLevel\n): boolean {\n return (\n ARCA_LOG_LEVELS.indexOf(messageLevel) >= ARCA_LOG_LEVELS.indexOf(threshold)\n );\n}\n\nfunction isArcaLogLevel(value: string | undefined): value is ArcaLogLevel {\n return ARCA_LOG_LEVELS.includes(value as ArcaLogLevel);\n}\n\nfunction defaultArcaLog(\n level: ArcaLogLevel,\n message: string,\n ...args: unknown[]\n): void {\n const method =\n level === \"debug\"\n ? console.debug\n : level === \"info\"\n ? console.info\n : level === \"warn\"\n ? console.warn\n : console.error;\n method(message, ...args);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { ArcaLockTimeoutError } from \"../errors\";\nimport type { ArcaLockOptions } from \"./types\";\n\n/**\n * Lease duration and renewal are internal. A holder renews while it works, so\n * the lease only expires when its process is gone, and a caller never tunes it.\n */\nexport const ARCA_LEASE_MS = 60_000;\nconst RENEW_MS = 20_000;\nconst POLL_MS = 50;\n/** How long a caller waits for any ARCA lock before giving up. */\nexport const MAX_WAIT_MS = 2 * ARCA_LEASE_MS;\n\n/** One lease backend: acquire, keep alive, and give back only what it owns. */\nexport type ArcaLeaseDriver = {\n acquire(owner: string): Promise<boolean>;\n renew(owner: string): Promise<void>;\n release(owner: string): Promise<void>;\n};\n\n/**\n * Runs `fn` while holding a lease other processes honor. A holder that dies\n * loses the lease when it expires; a holder that works keeps renewing it. The\n * caller's signal only stops the wait: once the lease is taken, `fn` runs.\n */\nexport async function withLease<T>(\n driver: ArcaLeaseDriver,\n fn: () => Promise<T>,\n { signal }: ArcaLockOptions = {}\n): Promise<T> {\n const owner = randomUUID();\n const deadline = Date.now() + MAX_WAIT_MS;\n throwIfAborted(signal);\n let held = await driver.acquire(owner);\n while (!held) {\n if (Date.now() >= deadline) {\n throw new ArcaLockTimeoutError(\n \"ARCA store lock stayed held; no work was attempted.\",\n { reason: \"held\" }\n );\n }\n // An abort ends the wait early; the check below reports it.\n await delay(POLL_MS + Math.floor(Math.random() * POLL_MS), signal);\n throwIfAborted(signal);\n held = await driver.acquire(owner);\n }\n if (signal?.aborted) {\n // The signal fired while the winning acquire was in flight: give the\n // lease back before any work, so the caller's deadline still holds.\n await driver.release(owner).catch(() => undefined);\n throwIfAborted(signal);\n }\n const renewal = setInterval(() => {\n driver.renew(owner).catch(() => undefined);\n }, RENEW_MS);\n renewal.unref?.();\n try {\n return await fn();\n } finally {\n clearInterval(renewal);\n await driver.release(owner).catch(() => undefined);\n }\n}\n\n/**\n * Stops a wait for a lock the caller no longer wants. Nothing was taken. The\n * message never names the lock key, which carries the taxpayer's CUIT.\n */\nexport function throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw new ArcaLockTimeoutError(\n \"Stopped waiting for an ARCA store lock: the caller's signal aborted; no work was attempted.\",\n { reason: \"aborted\", cause: signal.reason }\n );\n }\n}\n\n/** Sleeps between polls, and wakes early when the signal aborts. */\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n // An abort already past never fires again: skip the sleep.\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n const wake = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", wake);\n resolve();\n }, ms);\n timer.unref?.();\n signal?.addEventListener(\"abort\", wake, { once: true });\n });\n}\n","import { ARCA_CURRENCY_IDS, ARCA_VOUCHER_TYPES } from \"../constants\";\nimport {\n ArcaConfigurationError,\n ArcaInputError,\n ArcaLockTimeoutError,\n type ArcaSafeErrorMetadata,\n toArcaSafeErrorMetadata,\n} from \"../errors\";\nimport { toIsoDate } from \"../internal/dates\";\nimport {\n roundHalfEvenRatio,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport type { ArcaEnvironment } from \"../internal/types\";\nimport { MAX_WAIT_MS, throwIfAborted } from \"../store/lock\";\nimport {\n type ArcaStore,\n attemptKey,\n canonicalHash,\n storeCall,\n} from \"../store/types\";\nimport type { ArcaFiscalIssue } from \"./fiscal-evidence\";\nimport { EXPORT_TYPES } from \"./issuance-fields\";\nimport { type ArcaQrPayload, arcaQrPayload, qrUrlForPayload } from \"./qr\";\nimport type { IssueOptions } from \"./vouchers-types\";\nimport { normalizeWsfeDateInput, type WsfeDateInput } from \"./wsfe\";\nimport type { IssueAmounts, ItemLine } from \"./wsfe-amounts\";\nimport {\n assertExportDateWindow,\n assertIssueKeys,\n assertIssueObject,\n buenosAiresDate,\n} from \"./wsfe-derive\";\nimport type { VoucherCoordinates } from \"./wsfe-identity\";\nimport {\n assertWsfexVoucherInput,\n type WsfexAuthorizationOutcome,\n type WsfexExportType,\n type WsfexItem,\n type WsfexLanguage,\n type WsfexService,\n type WsfexVoucherInfo,\n type WsfexVoucherInput,\n} from \"./wsfex\";\n\n/** Factura E (19), Nota de Débito E (20) and Nota de Crédito E (21). */\nexport type ExportVoucherType = 19 | 20 | 21;\n\n/** A receiver abroad. ARCA needs `taxId`, `countryTaxId` or both (rule 1580). */\nexport type ExportReceiver = {\n /** ARCA destination country, from `wsfex.getCountries()`: 203 is Brasil. */\n country: number;\n name: string;\n address: string;\n /** The receiver's tax ID in its own country. */\n taxId?: string;\n /** ARCA's CUIT for the receiver's country, from `wsfex.getCountryTaxIds()`. */\n countryTaxId?: string;\n};\n\n/**\n * One exported line. `unit` is an ARCA unit of measure from\n * `wsfex.getUnits()`. Except for units 0, 97 and 99, `quantity` and\n * `unitPrice` are required and `amount` must equal their product less\n * `discount`. `amount` and `discount` are minor units; `amount` is negative\n * only for unit 99, a discount line, or 97, an advance.\n */\nexport type ExportItem = Pick<\n ItemLine,\n \"quantity\" | \"unitPrice\" | \"discount\" | \"code\"\n> & {\n description: string;\n unit: number;\n amount: number;\n};\n\nexport type ExportOfGoods = {\n kind: \"goods\";\n /** An Incoterm from `wsfex.getIncoterms()`, such as `FOB`. */\n incoterms: string;\n incotermsDetail?: string;\n /**\n * The shipping permits already issued, each with its destination. Omit it\n * while the goods have none yet: ARCA records that the permit is pending.\n */\n permits?: readonly { id: string; destination: number }[];\n};\nexport type ExportOfServices = {\n /** Services, or `other` for exports that are neither goods nor services. */\n kind: \"services\" | \"other\";\n /** When the receiver pays, on or after the voucher date. */\n paymentDate: WsfeDateInput;\n};\n\n/**\n * A Factura E. ARCA authorizes it through WSFEX, never WSFE: `issue()` takes\n * this shape whenever `export` is present. The issuer's tax condition does\n * not change the class, so there is no `issuer`.\n */\nexport type ExportIssueInput = {\n salesPoint: number;\n to: ExportReceiver;\n export: ExportOfGoods | ExportOfServices;\n items: readonly ExportItem[];\n /** The reviewed total in minor units; must equal the sum of `items`. */\n total?: number;\n date?: WsfeDateInput;\n /** `ARS`, `USD`, or any ARCA currency id such as `{ id: \"060\" }` for euros. */\n currency?: \"ARS\" | \"USD\" | { id: string };\n /**\n * Pesos per unit, required for every currency but ARS. ARCA checks it\n * against its own rate: take it from `wsfex.getExchangeRate()`.\n */\n exchangeRate?: string;\n /** The receiver pays in the invoice's foreign currency (`CanMisMonExt`). */\n paidInForeignCurrency?: boolean;\n /** How the receiver pays, such as \"Transferencia bancaria\" (`Forma_pago`). */\n paymentTerms: string;\n /** The language of the printed voucher; Spanish when omitted. */\n language?: \"es\" | \"en\" | \"pt\";\n observations?: string;\n commercialObservations?: string;\n};\n\ntype ExportNoteCommon = {\n /** The authorized export voucher the note adjusts. */\n for: VoucherCoordinates & { voucherType: ExportVoucherType };\n salesPoint?: number;\n date?: WsfeDateInput;\n /**\n * Overrides the original's rate. Services notes must keep the original's\n * rate (rule 2053), so it is refused for them.\n */\n exchangeRate?: string;\n observations?: string;\n commercialObservations?: string;\n};\n/** A Nota de Crédito E for chosen lines, or for every line with `all`. */\nexport type ExportCreditNoteInput = ExportNoteCommon &\n (\n | { items: readonly ExportItem[]; all?: never }\n | { all: true; items?: never }\n );\n/** A Nota de Débito E always lists what it adds. */\nexport type ExportDebitNoteInput = ExportNoteCommon & {\n items: readonly ExportItem[];\n all?: never;\n};\n\n/** The normalized fiscal fields of an export voucher. Dates are `YYYY-MM-DD`. */\nexport type ExportHeader = {\n exportType: WsfexExportType;\n destination: number;\n receiverName: string;\n receiverAddress: string;\n receiverTaxId?: string;\n receiverCountryTaxId?: string;\n currencyId: string;\n exchangeRate?: string;\n paidInForeignCurrency?: boolean;\n language: WsfexLanguage;\n incoterms?: string;\n incotermsDetail?: string;\n /** Whether the voucher declared an issued shipping permit; absent on notes and services. */\n permitExists?: boolean;\n paymentTerms?: string;\n paymentDate?: string;\n};\n\nexport type ExportIssuedVoucher = VoucherCoordinates & {\n voucherClass: \"E\";\n /** The request id (`Cmp.Id`) ARCA stored this voucher under. */\n requestId: number;\n date: string;\n header: ExportHeader;\n cae: string;\n caeExpiry: string;\n amounts: IssueAmounts;\n qr?: string;\n qrPayload?: ArcaQrPayload;\n};\n\n/** Raw-free consultation of one export voucher, money in minor units. */\nexport type ExportVoucherSummary = {\n /** Tells an export summary apart from a WSFE or WSMTXCA one. */\n voucherClass: \"E\";\n number: number;\n salesPoint?: number;\n voucherType?: number;\n requestId?: number;\n date?: string;\n exportType?: number;\n destination?: number;\n receiverName?: string;\n receiverAddress?: string;\n receiverTaxId?: string;\n receiverCountryTaxId?: string;\n currencyId?: string;\n exchangeRate?: string;\n totalAmount?: number;\n result?: string;\n cae?: string;\n caeExpiry?: string;\n};\n\nexport type ExportPreview = {\n voucherClass: \"E\";\n voucherType: ExportVoucherType;\n date: string;\n header: ExportHeader;\n amounts: IssueAmounts;\n request: WsfexVoucherInput;\n service: \"wsfex\";\n /** The original a note adjusts. */\n originals?: readonly ExportVoucherSummary[];\n};\n\n/** The outcome without `raw`, kept per kind so `reason` and `cae` survive. */\ntype Evidence = (WsfexAuthorizationOutcome extends infer T\n ? T extends unknown\n ? Omit<T, \"raw\">\n : never\n : never) & { rawResponse?: Record<string, unknown> };\n/** What `issue()` sent: the voucher with the request id and number it took. */\nexport type ExportIssueRequest = WsfexVoucherInput & {\n id: number;\n number: number;\n};\n/** `request` is always present when `include.request` is `true`. */\n/** What happened to one export attempt, before the service tag. */\ntype ExportResult =\n | {\n kind: \"authorized\";\n recoveredByMatch: false;\n voucher: ExportIssuedVoucher;\n authorization: Evidence;\n }\n | {\n kind: \"authorized\";\n recoveredByMatch: true;\n voucher: ExportIssuedVoucher;\n attempt: Evidence;\n lookup: ExportVoucherSummary;\n }\n | {\n kind: \"rejected\";\n attempted: VoucherCoordinates;\n issues: ArcaFiscalIssue[];\n authorization: Evidence;\n }\n | {\n kind: \"indeterminate\";\n attempted: VoucherCoordinates;\n attempt: Evidence;\n lookup:\n | { kind: \"not_found\" }\n /** ARCA has this voucher but reports no approval, CAE or expiry. */\n | { kind: \"incomplete\"; reason: string }\n | { kind: \"failed\"; error: ArcaSafeErrorMetadata }\n | { kind: \"aborted\" };\n }\n | {\n kind: \"conflict\";\n attempted: VoucherCoordinates;\n attempt: Evidence;\n found: ExportVoucherSummary;\n reason: string;\n };\n/**\n * `service: \"wsfex\"` tells an export outcome apart at the top level: where a\n * result may be domestic or export, `\"service\" in outcome` narrows it. With\n * `include.request: true`, `request` is always present.\n */\nexport type ExportIssueOutcome<O extends IssueOptions = { include?: never }> =\n ExportResult & { service: \"wsfex\" } & (O extends {\n include: { request: true };\n }\n ? { request: ExportIssueRequest }\n : { request?: ExportIssueRequest });\n\ntype ExportOperation = \"issue\" | \"creditNote\" | \"debitNote\";\ntype Prepared = { data: WsfexVoucherInput; amounts: IssueAmounts };\ntype Context = {\n store?: ArcaStore;\n environment: ArcaEnvironment;\n taxId: string;\n};\n/** Version 2 with `service: \"wsfex\"`: WSFE readers refuse it by its service. */\ntype ExportAttemptRecord = {\n v: 2;\n operation: ExportOperation;\n service: \"wsfex\";\n representedTaxId?: string;\n salesPoint: number;\n voucherType: number;\n number: number;\n requestId: number;\n inputHash: string;\n sent: WsfexVoucherInput;\n createdAt: string;\n};\n\nconst LANGUAGES = { es: 1, en: 2, pt: 3 } as const;\nconst EXPORT_KINDS = { goods: 1, services: 2, other: 4 } as const;\n/** Units whose lines carry no quantity or price (rule 1775). */\nconst UNPRICED_UNITS: readonly number[] = [0, 97, 99];\n\nexport function isExportVoucherType(voucherType: unknown): boolean {\n return (\n typeof voucherType === \"number\" &&\n (EXPORT_TYPES as readonly number[]).includes(voucherType)\n );\n}\n\nexport function isExportInput(input: unknown): input is ExportIssueInput {\n return input !== null && typeof input === \"object\" && \"export\" in input;\n}\n\nexport function isExportNoteInput(\n input: unknown\n): input is ExportCreditNoteInput {\n if (input === null || typeof input !== \"object\" || !(\"for\" in input)) {\n return false;\n }\n const target = (input as { for: unknown }).for;\n return (\n target !== null &&\n typeof target === \"object\" &&\n !Array.isArray(target) &&\n isExportVoucherType((target as { voucherType?: unknown }).voucherType)\n );\n}\n\n/** No I/O: every caller error throws before the first ARCA call. */\nexport function deriveExportInvoice(\n input: ExportIssueInput,\n now = new Date()\n): Prepared {\n assertIssueObject(input, \"input\");\n assertIssueKeys(\n input,\n [\n \"salesPoint\",\n \"to\",\n \"export\",\n \"items\",\n \"total\",\n \"date\",\n \"currency\",\n \"exchangeRate\",\n \"paidInForeignCurrency\",\n \"paymentTerms\",\n \"language\",\n \"observations\",\n \"commercialObservations\",\n ],\n \"input\"\n );\n assertSalesPoint(input.salesPoint, \"salesPoint\");\n const receiver = deriveReceiver(input.to);\n const exported = deriveExport(input.export);\n const voucherDate = normalizeWsfeDateInput(\n input.date ?? buenosAiresDate(now),\n \"date\"\n ) as string;\n if (\n exported.paymentDate !== undefined &&\n exported.paymentDate < voucherDate\n ) {\n invalid(\"export.paymentDate\", \"on or after the voucher date\");\n }\n const currency = deriveCurrency(input.currency, input.exchangeRate);\n if (input.paidInForeignCurrency !== undefined) {\n if (typeof input.paidInForeignCurrency !== \"boolean\") {\n invalid(\"paidInForeignCurrency\", \"a boolean\");\n }\n if (currency.currencyId === ARCA_CURRENCY_IDS.ARS) {\n invalid(\"paidInForeignCurrency\", \"absent for an invoice in pesos\");\n }\n }\n const { items, total } = deriveItems(input.items, \"items\");\n const reviewed = reviewedTotal(input.total, total);\n const data: WsfexVoucherInput = {\n voucherType: ARCA_VOUCHER_TYPES.FACTURA_E,\n salesPoint: input.salesPoint,\n voucherDate,\n exportType: exported.exportType,\n ...(exported.permitExists === undefined\n ? {}\n : { permitExists: exported.permitExists }),\n ...(exported.permits === undefined ? {} : { permits: exported.permits }),\n ...receiver,\n ...currency,\n ...(input.paidInForeignCurrency === undefined\n ? {}\n : {\n sameCurrencyForeignCancellation: input.paidInForeignCurrency\n ? \"S\"\n : \"N\",\n }),\n ...optionalText(\n input.commercialObservations,\n \"commercialObservations\",\n 4000\n ),\n totalAmount: reviewed / 100,\n ...optionalText(input.observations, \"observations\", 1000),\n paymentTerms: text(input.paymentTerms, \"paymentTerms\", 50),\n ...(exported.incoterms === undefined\n ? {}\n : { incoterms: exported.incoterms }),\n ...(exported.incotermsDetail === undefined\n ? {}\n : { incotermsDetail: exported.incotermsDetail }),\n language: deriveLanguage(input.language),\n items,\n ...(exported.paymentDate === undefined\n ? {}\n : { paymentDate: exported.paymentDate }),\n };\n assertWsfexVoucherInput(data);\n return {\n data,\n amounts: { computedTotal: total, sentTotal: reviewed, vatAdjustment: 0 },\n };\n}\n\n/**\n * A note inherits everything from its original but its lines, sales point,\n * date and observations. ARCA associates exactly one export voucher.\n */\nexport function deriveExportNote(\n original: WsfexVoucherInfo,\n input: ExportCreditNoteInput | ExportDebitNoteInput,\n kind: \"creditNote\" | \"debitNote\",\n now = new Date()\n): Prepared {\n assertIssueKeys(\n input,\n [\n \"for\",\n \"salesPoint\",\n \"date\",\n \"exchangeRate\",\n \"observations\",\n \"commercialObservations\",\n \"items\",\n ...(kind === \"creditNote\" ? [\"all\"] : []),\n ],\n \"input\",\n kind === \"creditNote\" ? \"issueCreditNote()\" : \"issueDebitNote()\"\n );\n const exportType = noteExportType(original, kind);\n const salesPoint = input.salesPoint ?? original.salesPoint;\n assertSalesPoint(salesPoint, \"salesPoint\");\n const voucherDate = normalizeWsfeDateInput(\n input.date ?? buenosAiresDate(now),\n \"date\"\n ) as string;\n if (\n exportType === 2 &&\n original.voucherDate !== undefined &&\n voucherDate < original.voucherDate\n ) {\n invalid(\"date\", \"on or after the original's date for services\");\n }\n const exchangeRate = noteRate(original, input.exchangeRate, exportType);\n const lines = noteLines(original, input);\n const data: WsfexVoucherInput = {\n voucherType:\n kind === \"creditNote\"\n ? ARCA_VOUCHER_TYPES.NOTA_CREDITO_E\n : ARCA_VOUCHER_TYPES.NOTA_DEBITO_E,\n salesPoint,\n voucherDate,\n exportType,\n ...inheritedReceiver(original),\n currencyId: original.currencyId,\n ...(exchangeRate === undefined ? {} : { exchangeRate }),\n ...optionalText(\n input.commercialObservations,\n \"commercialObservations\",\n 4000\n ),\n totalAmount: lines.total / 100,\n ...optionalText(input.observations, \"observations\", 1000),\n associatedVouchers: [\n {\n voucherType: original.voucherType,\n salesPoint: original.salesPoint,\n number: original.number,\n },\n ],\n ...(original.incoterms === undefined\n ? {}\n : { incoterms: original.incoterms }),\n language:\n original.language === 2 || original.language === 3\n ? original.language\n : 1,\n items: lines.items,\n };\n // An inherited line ARCA reported oddly fails here, before any reservation.\n assertWsfexVoucherInput(data);\n return {\n data,\n amounts: {\n computedTotal: lines.total,\n sentTotal: lines.total,\n vatAdjustment: 0,\n },\n };\n}\n\n/** A credit note adjusts an invoice or a debit note, a debit note an invoice. */\nfunction noteExportType(\n original: WsfexVoucherInfo,\n kind: \"creditNote\" | \"debitNote\"\n): WsfexExportType {\n if (original.result !== undefined && original.result !== \"A\") {\n invalid(\"for\", \"an authorized voucher\");\n }\n const allowed: readonly number[] =\n kind === \"creditNote\"\n ? [ARCA_VOUCHER_TYPES.FACTURA_E, ARCA_VOUCHER_TYPES.NOTA_DEBITO_E]\n : [ARCA_VOUCHER_TYPES.FACTURA_E];\n if (!allowed.includes(original.voucherType)) {\n invalid(\n \"for.voucherType\",\n kind === \"creditNote\" ? \"19 or 20\" : \"19, a Factura E\"\n );\n }\n const exportType = original.exportType;\n if (exportType !== 1 && exportType !== 2 && exportType !== 4) {\n throw new ArcaConfigurationError(\n \"The original voucher reports no export type.\"\n );\n }\n return exportType;\n}\n\n/** Services notes keep the original's rate (rule 2053); others may set one. */\nfunction noteRate(\n original: WsfexVoucherInfo,\n rate: string | undefined,\n exportType: WsfexExportType\n): string | undefined {\n if (rate === undefined) {\n return original.exchangeRate;\n }\n if (exportType === 2) {\n invalid(\"exchangeRate\", \"absent: services notes keep the original's\");\n }\n return deriveCurrency(\n original.currencyId === ARCA_CURRENCY_IDS.ARS\n ? \"ARS\"\n : { id: original.currencyId },\n rate\n ).exchangeRate;\n}\n\nfunction noteLines(\n original: WsfexVoucherInfo,\n input: ExportCreditNoteInput | ExportDebitNoteInput\n): { items: readonly WsfexItem[]; total: number } {\n const all = \"all\" in input ? input.all : undefined;\n if ((input.items === undefined) === (all === undefined)) {\n throw new ArcaInputError(\n \"issueCreditNote needs exactly one mode: items for a partial note, or all: true for the whole original.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: input.items === undefined ? \"items\" : \"all\",\n expected: \"exactly one of items or all: true\",\n }\n );\n }\n if (all === undefined) {\n return deriveItems(input.items as readonly ExportItem[], \"items\");\n }\n if (all !== true) {\n invalid(\"all\", \"true\");\n }\n if (original.items.length === 0) {\n throw new ArcaInputError(\n \"ARCA reports no lines for the original, so all: true has nothing to credit; list the items instead.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"all\",\n expected: \"items, since the original reports no lines\",\n }\n );\n }\n return { items: original.items, total: originalTotal(original) };\n}\n\nfunction inheritedReceiver(original: WsfexVoucherInfo) {\n return {\n destination: original.destination,\n receiverName: original.receiverName,\n ...(original.receiverCountryTaxId === undefined\n ? {}\n : { receiverCountryTaxId: original.receiverCountryTaxId }),\n receiverAddress: original.receiverAddress,\n ...(original.receiverTaxId === undefined\n ? {}\n : { receiverTaxId: original.receiverTaxId }),\n };\n}\n\n/** Checked where a new voucher would be sent, never on replay. */\nexport function assertExportWindow(data: WsfexVoucherInput, now = new Date()) {\n assertExportDateWindow(\n (data.voucherDate ?? buenosAiresDate(now)) as WsfeDateInput,\n data.exportType === 2,\n buenosAiresDate(now)\n );\n}\n\nexport function exportPreview(\n prepared: Prepared,\n originals?: readonly ExportVoucherSummary[]\n): ExportPreview {\n return {\n voucherClass: \"E\",\n voucherType: prepared.data.voucherType,\n date: isoDate(prepared.data.voucherDate) as string,\n header: exportHeader(prepared.data),\n amounts: { ...prepared.amounts },\n request: structuredClone(prepared.data) as WsfexVoucherInput,\n service: \"wsfex\",\n ...(originals === undefined ? {} : { originals }),\n };\n}\n\nexport type ExportIssuance = {\n /**\n * `prepare` derives the voucher and runs only when this key has no\n * reservation: a replay resends what was stored, whatever today's date.\n */\n issue(\n prepare: () => Prepared | Promise<Prepared>,\n operation: ExportOperation,\n hashInput: unknown,\n options: IssueOptions\n ): Promise<ExportIssueOutcome>;\n /** Consults the original a note adjusts; `null` when ARCA has none. */\n original(\n coordinates: VoucherCoordinates,\n options: IssueOptions\n ): Promise<WsfexVoucherInfo | null>;\n lookup(\n coordinates: VoucherCoordinates,\n options: IssueOptions\n ): Promise<ExportVoucherSummary | null>;\n lastAuthorized(\n sequence: Omit<VoucherCoordinates, \"number\">,\n options: IssueOptions\n ): Promise<number>;\n /**\n * Settles an export reservation from ARCA's record of its number. Reads\n * only: it never sends the voucher, so it never authorizes one.\n */\n recover(\n key: string,\n record: string,\n options: IssueOptions\n ): Promise<ExportIssueOutcome>;\n};\n\n/**\n * Keyed export issuance rests on WSFEX's own request id: resending the same\n * `Cmp.Id` returns ARCA's stored answer instead of a second voucher. The id\n * belongs to the whole CUIT, not to one sales point, so the id and the number\n * are read and the voucher sent under one lock per CUIT.\n */\nexport function createExportIssuance(\n wsfex: WsfexService,\n context: Context\n): ExportIssuance {\n return {\n issue: (prepare, operation, hashInput, options) =>\n issueExport(wsfex, context, prepare, operation, hashInput, options),\n async original(coordinates, options) {\n const result = await wsfex.lookupVoucher({\n ...auth(options),\n ...coordinates,\n });\n return result.kind === \"found\" ? result.voucher : null;\n },\n async lookup(coordinates, options) {\n const result = await wsfex.lookupVoucher({\n ...auth(options),\n ...coordinates,\n });\n return result.kind === \"found\" ? exportSummary(result.voucher) : null;\n },\n lastAuthorized: (sequence, options) =>\n wsfex.getLastVoucherNumber({ ...auth(options), ...sequence }),\n recover: (key, json, options) =>\n recoverExport(wsfex, context, key, json, options),\n };\n}\n\nasync function recoverExport(\n wsfex: WsfexService,\n context: Context,\n key: string,\n json: string,\n options: IssueOptions\n): Promise<ExportIssueOutcome> {\n const first = readExportRecord(json);\n const issuer = first.representedTaxId ?? context.taxId;\n if (\n options.representedTaxId !== undefined &&\n String(options.representedTaxId) !== issuer\n ) {\n throw new ArcaInputError(\n \"Reservation belongs to another represented taxpayer\",\n { code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\" }\n );\n }\n const consulted: IssueOptions = {\n ...options,\n ...(first.representedTaxId === undefined\n ? {}\n : { representedTaxId: first.representedTaxId }),\n };\n // A retry of this key resends under the CUIT lock and may move its request\n // id there. Waiting for the lock and reading the reservation again keeps\n // this consultation on the id and number the retry left.\n return await exportLock(\n context,\n issuer,\n options\n )(async () => {\n const store = context.store;\n const latest = store\n ? await storeCall(() =>\n store.get(attemptKey(context.environment, context.taxId, key))\n )\n : null;\n const record = latest === null ? first : readExportRecord(latest);\n const outcome = await consultReservation(wsfex, record, consulted, issuer);\n return {\n ...outcome,\n service: \"wsfex\" as const,\n ...(options.include?.request\n ? {\n request: {\n ...structuredClone(record.sent),\n id: record.requestId,\n number: record.number,\n },\n }\n : {}),\n };\n });\n}\n\nasync function consultReservation(\n wsfex: WsfexService,\n record: ExportAttemptRecord,\n options: IssueOptions,\n issuer: string\n): Promise<ExportResult> {\n const attempted = {\n salesPoint: record.salesPoint,\n voucherType: record.voucherType,\n number: record.number,\n };\n // No write was observed here: the attempt is the reservation itself.\n const attempt: Evidence = {\n service: \"wsfex\",\n operation: \"FEXAuthorize\",\n kind: \"indeterminate\",\n reason: \"incomplete_response\",\n results: {},\n errors: [],\n observations: [],\n };\n const total = Math.round(record.sent.totalAmount * 100);\n const amounts = { computedTotal: total, sentTotal: total, vatAdjustment: 0 };\n let found: WsfexVoucherInfo | null;\n try {\n const result = await wsfex.lookupVoucher({\n ...auth(options),\n ...attempted,\n });\n found = result.kind === \"found\" ? result.voucher : null;\n } catch (error) {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: options.abortSignal?.aborted\n ? { kind: \"aborted\" }\n : { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n };\n }\n return settled(\n attempt as WsfexAuthorizationOutcome,\n attempt,\n found,\n record.requestId,\n attempted,\n record.sent,\n (authorization) =>\n issuedVoucher(\n record.sent,\n attempted,\n record.requestId,\n authorization,\n amounts,\n issuer\n )\n );\n}\n\n/** One lock per CUIT: its request ids and every export sequence share it. */\nfunction exportLock(context: Context, issuer: string, options: IssueOptions) {\n const key = `arca:v1:lock:wsfex:${context.environment}:${issuer}`;\n return <T>(fn: () => Promise<T>) =>\n context.store?.withLock\n ? context.store.withLock(key, fn, { signal: options.abortSignal })\n : withLocalLock(key, fn, options.abortSignal);\n}\n\nfunction auth(options: IssueOptions) {\n return {\n ...(options.representedTaxId === undefined\n ? {}\n : { representedTaxId: options.representedTaxId }),\n ...(options.forceRefresh === undefined\n ? {}\n : { forceRefresh: options.forceRefresh }),\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n };\n}\n\nasync function issueExport(\n wsfex: WsfexService,\n context: Context,\n prepare: () => Prepared | Promise<Prepared>,\n operation: ExportOperation,\n hashInput: unknown,\n options: IssueOptions\n): Promise<ExportIssueOutcome> {\n if (options.service !== undefined) {\n invalid(\"options.service\", \"absent: export vouchers always use WSFEX\");\n }\n if (options.number !== undefined) {\n invalid(\"options.number\", \"absent: WSFEX numbers are read under a lock\");\n }\n const representedTaxId =\n options.representedTaxId === undefined\n ? undefined\n : String(options.representedTaxId);\n const issuer = representedTaxId ?? context.taxId;\n const lock = exportLock(context, issuer, options);\n const idempotencyKey = options.idempotencyKey;\n if (idempotencyKey === undefined || !context.store) {\n const prepared = await prepare();\n assertExportWindow(prepared.data);\n return lock(() => fresh(prepared));\n }\n const store = context.store;\n const recordKey = attemptKey(\n context.environment,\n context.taxId,\n idempotencyKey\n );\n const inputHash = canonicalHash({\n input: hashInput,\n representedTaxId,\n service: \"wsfex\",\n });\n const existing = await storeCall(() => store.get(recordKey));\n if (existing !== null) {\n // Read again under the lock: a fresh claim may have moved its request id.\n return lock(async () =>\n replay((await storeCall(() => store.get(recordKey))) ?? existing)\n );\n }\n const prepared = await prepare();\n assertExportWindow(prepared.data);\n return lock(async () => {\n const prior = await storeCall(() => store.get(recordKey));\n return prior === null ? fresh(prepared) : replay(prior);\n });\n\n async function fresh(prepared: Prepared): Promise<ExportIssueOutcome> {\n const { data } = prepared;\n const number =\n (await wsfex.getLastVoucherNumber({\n ...auth(options),\n salesPoint: data.salesPoint,\n voucherType: data.voucherType,\n })) + 1;\n const id = await nextRequestId();\n if (idempotencyKey === undefined || !context.store) {\n return submit({ id, number, data, fresh: true });\n }\n const record: ExportAttemptRecord = {\n v: 2,\n operation,\n service: \"wsfex\",\n ...(representedTaxId === undefined ? {} : { representedTaxId }),\n salesPoint: data.salesPoint,\n voucherType: data.voucherType,\n number,\n requestId: id,\n inputHash,\n sent: data,\n createdAt: new Date().toISOString(),\n };\n const store = context.store;\n if (await storeCall(() => store.add(recordKey, JSON.stringify(record)))) {\n return submit({ id, number, data, fresh: true, record });\n }\n const winner = await storeCall(() => store.get(recordKey));\n if (winner === null) {\n throw new ArcaConfigurationError(\n \"ARCA reservation disappeared after atomic creation lost.\"\n );\n }\n return replay(winner);\n }\n\n function replay(json: string): Promise<ExportIssueOutcome> {\n const stored = readExportRecord(json);\n if (\n stored.operation !== operation ||\n stored.inputHash !== inputHash ||\n stored.representedTaxId !== representedTaxId\n ) {\n throw new ArcaInputError(\n \"The idempotency key was already used with different input or operation.\",\n {\n code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\",\n field: \"options.idempotencyKey\",\n }\n );\n }\n return submit({\n id: stored.requestId,\n number: stored.number,\n data: stored.sent,\n fresh: false,\n record: stored,\n });\n }\n\n async function submit(claim: {\n id: number;\n number: number;\n data: WsfexVoucherInput;\n fresh: boolean;\n record?: ExportAttemptRecord;\n }): Promise<ExportIssueOutcome> {\n const first = await attemptOnce(claim, claim.id, claim.fresh);\n if (first !== \"collided\") {\n return first;\n }\n // A reused id answered another request's voucher, so ARCA never processed\n // this one: a fresh claim takes a new id, once.\n const id = await nextRequestId();\n await moveRecord(claim.record, id);\n const second = await attemptOnce(claim, id, true);\n if (second === \"collided\") {\n throw new ArcaConfigurationError(\"WSFEX answered a reused id twice.\");\n }\n return second;\n }\n\n async function attemptOnce(\n claim: { number: number; data: WsfexVoucherInput },\n id: number,\n mayCollide: boolean\n ): Promise<ExportIssueOutcome | \"collided\"> {\n const { number, data } = claim;\n const attempted = {\n salesPoint: data.salesPoint,\n voucherType: data.voucherType,\n number,\n };\n const finish = (outcome: ExportResult): ExportIssueOutcome => ({\n ...outcome,\n service: \"wsfex\",\n ...(options.include?.request\n ? { request: { ...structuredClone(data), id, number } }\n : {}),\n });\n const outcome = await send(data, id, number);\n const attempt = evidence(outcome);\n const direct = answered(outcome, attempt, id, attempted);\n if (direct !== undefined) {\n return finish(\n direct.kind === \"authorized\"\n ? { ...direct, voucher: issued(data, attempted, id, direct.voucher) }\n : direct\n );\n }\n // Reprocessed, contradictory, out of sequence or unanswered: ARCA's\n // record of this number decides, matched by the request id it stored.\n const consulted = await consult(outcome, attempt, attempted);\n if (\"outcome\" in consulted) {\n return finish(consulted.outcome);\n }\n const { found } = consulted;\n if (\n mayCollide &&\n outcome.kind === \"authorized\" &&\n outcome.reprocessed === true &&\n found === null\n ) {\n return \"collided\";\n }\n return finish(\n settled(outcome, attempt, found, id, attempted, data, (voucher) =>\n issued(data, attempted, id, voucher)\n )\n );\n }\n\n async function consult(\n outcome: WsfexAuthorizationOutcome,\n attempt: Evidence,\n attempted: VoucherCoordinates\n ): Promise<{ found: WsfexVoucherInfo | null } | { outcome: ExportResult }> {\n const aborted = () => ({\n outcome: {\n kind: \"indeterminate\" as const,\n attempted,\n attempt,\n lookup: { kind: \"aborted\" as const },\n },\n });\n if (options.abortSignal?.aborted && outcome.kind !== \"authorized\") {\n return aborted();\n }\n try {\n const result = await wsfex.lookupVoucher({\n ...auth(options),\n ...attempted,\n });\n return { found: result.kind === \"found\" ? result.voucher : null };\n } catch (error) {\n return options.abortSignal?.aborted\n ? aborted()\n : {\n outcome: {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n },\n };\n }\n }\n\n /**\n * ARCA's last id only counts requests it received. A reservation whose send\n * never arrived keeps its id, so the next one starts past every id this\n * store handed out, and a replay can never meet another key's voucher. Read\n * and written under the CUIT lock, before the reservation that uses it.\n */\n async function nextRequestId(): Promise<number> {\n const received = await wsfex.getLastRequestId(auth(options));\n const key = requestIdKey(context.environment, issuer);\n const store = context.store;\n const issued = store\n ? readRequestIdMarker(await storeCall(() => store.get(key)))\n : (localRequestIds.get(key) ?? 0);\n const id = Math.max(received, issued) + 1;\n if (id > MAX_REQUEST_ID) {\n throw new ArcaConfigurationError(\"WSFEX request ids are exhausted.\");\n }\n if (store) {\n const marker: RequestIdMarker = { v: 1, id };\n await storeCall(() => store.set(key, JSON.stringify(marker)));\n } else {\n localRequestIds.set(key, id);\n }\n return id;\n }\n\n function send(data: WsfexVoucherInput, id: number, number: number) {\n const once = (forceRefresh?: boolean) =>\n wsfex.issue({\n ...data,\n id,\n number,\n ...auth({\n ...options,\n ...(forceRefresh ? { forceRefresh: true } : {}),\n }),\n });\n // A caller that already forced a fresh ticket got its one fresh attempt.\n return once().then((outcome) =>\n outcome.kind === \"indeterminate\" &&\n outcome.reason === \"authentication_rejected\" &&\n options.forceRefresh !== true\n ? once(true)\n : outcome\n );\n }\n\n async function moveRecord(\n record: ExportAttemptRecord | undefined,\n id: number\n ) {\n const store = context.store;\n if (record === undefined || store === undefined) {\n return;\n }\n const moved: ExportAttemptRecord = { ...record, requestId: id };\n await storeCall(() => store.set(recordKey, JSON.stringify(moved)));\n }\n\n function issued(\n data: WsfexVoucherInput,\n attempted: VoucherCoordinates,\n id: number,\n authorization: Authorized\n ): ExportIssuedVoucher {\n // An export voucher's total is the sum of its lines: nothing to adjust.\n const total = Math.round(data.totalAmount * 100);\n return issuedVoucher(\n data,\n attempted,\n id,\n authorization,\n { computedTotal: total, sentTotal: total, vatAdjustment: 0 },\n issuer\n );\n }\n\n function evidence(outcome: WsfexAuthorizationOutcome): Evidence {\n const { raw, ...rest } = outcome;\n return options.include?.rawResponse && raw !== undefined\n ? { ...rest, rawResponse: raw }\n : rest;\n }\n}\n\ntype Authorized = { cae: string; caeExpiry?: string };\n\nfunction issuedVoucher(\n data: WsfexVoucherInput,\n attempted: VoucherCoordinates,\n id: number,\n authorization: Authorized,\n amounts: IssueAmounts,\n issuer: string\n): ExportIssuedVoucher {\n const date = isoDate(data.voucherDate) as string;\n return {\n ...attempted,\n voucherClass: \"E\",\n requestId: id,\n date,\n header: exportHeader(data),\n cae: authorization.cae,\n caeExpiry: isoDate(authorization.caeExpiry) ?? \"\",\n amounts: { ...amounts },\n ...exportQr(issuer, attempted, data, date, authorization.cae),\n };\n}\n\n/**\n * An answer that needs no lookup: a plain authorization that names this\n * request, or a rejection other than an out-of-sequence number.\n */\nfunction answered(\n outcome: WsfexAuthorizationOutcome,\n attempt: Evidence,\n id: number,\n attempted: VoucherCoordinates\n):\n | {\n kind: \"authorized\";\n recoveredByMatch: false;\n voucher: Authorized;\n authorization: Evidence;\n }\n | Extract<ExportResult, { kind: \"rejected\" }>\n | undefined {\n if (\n outcome.kind === \"authorized\" &&\n !outcome.reprocessed &&\n echoes(outcome, id, attempted)\n ) {\n return {\n kind: \"authorized\",\n recoveredByMatch: false,\n voucher: { cae: outcome.cae, caeExpiry: outcome.caeExpiry },\n authorization: attempt,\n };\n }\n if (outcome.kind === \"rejected\" && !hasError(outcome, \"1535\")) {\n return {\n kind: \"rejected\",\n attempted,\n issues: [...outcome.errors, ...outcome.observations],\n authorization: attempt,\n };\n }\n return undefined;\n}\n\n/** What ARCA's record of the number says about this request. */\nfunction settled(\n outcome: WsfexAuthorizationOutcome,\n attempt: Evidence,\n found: WsfexVoucherInfo | null,\n id: number,\n attempted: VoucherCoordinates,\n sent: WsfexVoucherInput,\n issue: (authorization: Authorized) => ExportIssuedVoucher\n): ExportResult {\n if (found !== null && found.id === id && sameVoucher(found, sent)) {\n const authorized = outcome.kind === \"authorized\" ? outcome : undefined;\n const cae = found.cae ?? authorized?.cae;\n const caeExpiry = found.caeExpiry ?? authorized?.caeExpiry;\n // Matching fields prove whose voucher it is, never that ARCA approved it.\n if (found.result !== \"A\" || !cae || !caeExpiry) {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: {\n kind: \"incomplete\",\n reason: \"ARCA reports no approved result, CAE and CAE expiry\",\n },\n };\n }\n const voucher = issue({ cae, caeExpiry });\n return authorized\n ? {\n kind: \"authorized\",\n recoveredByMatch: false,\n voucher,\n authorization: attempt,\n }\n : {\n kind: \"authorized\",\n recoveredByMatch: true,\n voucher,\n attempt,\n lookup: exportSummary(found),\n };\n }\n if (found !== null) {\n return {\n kind: \"conflict\",\n attempted,\n attempt,\n found: exportSummary(found),\n reason:\n found.id === id\n ? \"ARCA stored different fiscal fields under this request id\"\n : \"Another request holds this voucher number\",\n };\n }\n if (outcome.kind === \"rejected\") {\n return {\n kind: \"rejected\",\n attempted,\n issues: [...outcome.errors, ...outcome.observations],\n authorization: attempt,\n };\n }\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"not_found\" },\n };\n}\n\nfunction echoes(\n outcome: WsfexAuthorizationOutcome,\n id: number,\n attempted: VoucherCoordinates\n): boolean {\n const echo = outcome.echo ?? {};\n return (\n (echo.id === undefined || echo.id === id) &&\n (echo.salesPoint === undefined ||\n echo.salesPoint === attempted.salesPoint) &&\n (echo.voucherType === undefined ||\n echo.voucherType === attempted.voucherType) &&\n (echo.number === undefined || echo.number === attempted.number)\n );\n}\n\nfunction hasError(outcome: WsfexAuthorizationOutcome, code: string): boolean {\n return outcome.errors.some((issue) => issue.code === code);\n}\n\n/**\n * The stored id names the request, but another system on the same CUIT may\n * reuse an id, and ARCA answers a repeated id with whatever it stored. So the\n * voucher is this one only if every fiscal field it reports equals what this\n * key sent: header, receiver, money, rate, associations, permits, activities\n * and every line. Both sides go through one canonical form, so a decimal\n * written as \"750.00\" or 750 compares equal.\n */\nfunction sameVoucher(found: WsfexVoucherInfo, sent: WsfexVoucherInput) {\n return (\n canonicalHash(fiscalIdentity(found)) === canonicalHash(fiscalIdentity(sent))\n );\n}\n\nfunction fiscalIdentity(voucher: WsfexVoucherInput | WsfexVoucherInfo) {\n return {\n voucherType: voucher.voucherType,\n salesPoint: voucher.salesPoint,\n voucherDate: trimmed(voucher.voucherDate),\n exportType: voucher.exportType,\n permitExists: trimmed(voucher.permitExists),\n permits: (voucher.permits ?? []).map((permit) => [\n trimmed(permit.id),\n permit.destination,\n ]),\n destination: voucher.destination,\n receiverName: trimmed(voucher.receiverName),\n receiverCountryTaxId: trimmed(voucher.receiverCountryTaxId),\n receiverAddress: trimmed(voucher.receiverAddress),\n receiverTaxId: trimmed(voucher.receiverTaxId),\n currencyId: trimmed(voucher.currencyId),\n exchangeRate: decimal(voucher.exchangeRate),\n sameCurrencyForeignCancellation: trimmed(\n voucher.sameCurrencyForeignCancellation\n ),\n commercialObservations: trimmed(voucher.commercialObservations),\n totalAmount: decimal(voucher.totalAmount),\n observations: trimmed(voucher.observations),\n // ARCA may fill the issuer's CUIT; the original is named by coordinates.\n associatedVouchers: (voucher.associatedVouchers ?? []).map((original) => [\n original.voucherType,\n original.salesPoint,\n original.number,\n ]),\n paymentTerms: trimmed(voucher.paymentTerms),\n incoterms: trimmed(voucher.incoterms),\n incotermsDetail: trimmed(voucher.incotermsDetail),\n language: voucher.language,\n items: voucher.items.map((item) => [\n trimmed(item.code),\n trimmed(item.description),\n decimal(item.quantity ?? 0),\n item.unit,\n decimal(item.unitPrice ?? \"0\"),\n decimal(item.discount ?? 0),\n decimal(item.amount),\n ]),\n paymentDate: trimmed(voucher.paymentDate),\n activities: (voucher.activities ?? []).map((activity) =>\n trimmed(activity.id)?.padStart(6, \"0\")\n ),\n };\n}\n\n/** XML reads every line break as LF, so both sides compare that way. */\nfunction trimmed(value: string | undefined): string | undefined {\n return value?.replace(/\\r\\n?/g, \"\\n\").trim() || undefined;\n}\n\n/** One spelling per decimal: no exponent, no trailing zeros, no leading ones. */\nfunction decimal(value: string | number | undefined): string | undefined {\n if (value === undefined) {\n return;\n }\n const written = typeof value === \"number\" ? value.toFixed(6) : value.trim();\n const match = /^(-?)(\\d+)(?:\\.(\\d+))?$/.exec(written);\n if (!match) {\n return written;\n }\n const whole = (match[2] ?? \"0\").replace(/^0+(?=\\d)/, \"\");\n const fraction = (match[3] ?? \"\").replace(/0+$/, \"\");\n const sign = whole === \"0\" && fraction === \"\" ? \"\" : (match[1] ?? \"\");\n return `${sign}${whole}${fraction ? `.${fraction}` : \"\"}`;\n}\n\n/** `Cmp.Id` is N15. */\nconst MAX_REQUEST_ID = 999_999_999_999_999;\n/** The highest request id this store handed out for a CUIT. */\ntype RequestIdMarker = { v: 1; id: number };\nconst localRequestIds = new Map<string, number>();\n\nfunction requestIdKey(environment: ArcaEnvironment, issuer: string) {\n return `arca:v1:wsfex:request-id:${environment}:${issuer}`;\n}\n\nfunction readRequestIdMarker(json: string | null): number {\n if (json === null) {\n return 0;\n }\n try {\n const marker = JSON.parse(json) as RequestIdMarker;\n if (marker?.v === 1 && Number.isSafeInteger(marker.id) && marker.id >= 0) {\n return marker.id;\n }\n } catch {\n // Reported below.\n }\n throw new ArcaConfigurationError(\n \"Invalid WSFEX request id marker; preserve it for reconciliation.\"\n );\n}\n\nconst localLocks = new Map<string, Promise<void>>();\n/**\n * Without a store lock, serializes the CUIT inside this process at least. Like\n * the store lock, the caller's signal and the same deadline stop only the\n * wait: a call that gives up never runs `fn`, and the queue behind it moves on.\n */\nasync function withLocalLock<T>(\n key: string,\n fn: () => Promise<T>,\n signal?: AbortSignal\n) {\n const previous = localLocks.get(key) ?? Promise.resolve();\n let release: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const chained = previous.then(() => current);\n localLocks.set(key, chained);\n // The entry leaves only once every holder before it and this call are done:\n // a waiter that gives up still keeps later callers behind the holder.\n chained.then(() => {\n if (localLocks.get(key) === chained) {\n localLocks.delete(key);\n }\n });\n try {\n await waitForTurn(previous, signal);\n } catch (error) {\n release();\n throw error;\n }\n try {\n return await fn();\n } finally {\n release();\n }\n}\n\nfunction waitForTurn(previous: Promise<void>, signal?: AbortSignal) {\n throwIfAborted(signal);\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onAbort: (() => void) | undefined;\n const stopped = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new ArcaLockTimeoutError(\n \"ARCA store lock stayed held; no work was attempted.\",\n { reason: \"held\" }\n )\n ),\n MAX_WAIT_MS\n );\n timer.unref?.();\n onAbort = () => {\n try {\n throwIfAborted(signal);\n } catch (error) {\n reject(error);\n }\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n return Promise.race([previous, stopped]).finally(() => {\n clearTimeout(timer);\n if (onAbort) {\n signal?.removeEventListener(\"abort\", onAbort);\n }\n });\n}\n\nfunction readExportRecord(json: string): ExportAttemptRecord {\n let record: ExportAttemptRecord;\n try {\n record = JSON.parse(json) as ExportAttemptRecord;\n } catch (cause) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA reservation record; preserve it for reconciliation.\",\n { cause }\n );\n }\n if (record?.service !== \"wsfex\") {\n throw new ArcaInputError(\n \"The idempotency key was already used with different input or operation.\",\n {\n code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\",\n field: \"options.idempotencyKey\",\n }\n );\n }\n if (\n record.v !== 2 ||\n ![\"issue\", \"creditNote\", \"debitNote\"].includes(record.operation) ||\n typeof record.inputHash !== \"string\" ||\n !record.sent ||\n !Number.isSafeInteger(record.number) ||\n !Number.isSafeInteger(record.requestId) ||\n record.sent.salesPoint !== record.salesPoint ||\n record.sent.voucherType !== record.voucherType\n ) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA reservation record; preserve it for reconciliation.\"\n );\n }\n return record;\n}\n\nfunction exportHeader(data: WsfexVoucherInput): ExportHeader {\n const header: ExportHeader = {\n exportType: data.exportType,\n destination: data.destination,\n receiverName: data.receiverName,\n receiverAddress: data.receiverAddress,\n currencyId: data.currencyId,\n language: data.language,\n };\n assign(header, \"receiverTaxId\", data.receiverTaxId);\n assign(header, \"receiverCountryTaxId\", data.receiverCountryTaxId);\n assign(header, \"exchangeRate\", data.exchangeRate);\n assign(\n header,\n \"paidInForeignCurrency\",\n data.sameCurrencyForeignCancellation === undefined\n ? undefined\n : data.sameCurrencyForeignCancellation === \"S\"\n );\n assign(header, \"incoterms\", data.incoterms);\n assign(header, \"incotermsDetail\", data.incotermsDetail);\n assign(\n header,\n \"permitExists\",\n data.permitExists === undefined ? undefined : data.permitExists === \"S\"\n );\n assign(header, \"paymentTerms\", data.paymentTerms);\n assign(header, \"paymentDate\", isoDate(data.paymentDate));\n return header;\n}\n\nexport function exportSummary(voucher: WsfexVoucherInfo): ExportVoucherSummary {\n const summary: ExportVoucherSummary = {\n voucherClass: \"E\",\n number: voucher.number,\n };\n assign(summary, \"salesPoint\", voucher.salesPoint);\n assign(summary, \"voucherType\", voucher.voucherType);\n assign(summary, \"requestId\", voucher.id);\n assign(summary, \"date\", isoDate(voucher.voucherDate));\n assign(summary, \"exportType\", voucher.exportType);\n assign(summary, \"destination\", voucher.destination);\n assign(summary, \"receiverName\", voucher.receiverName);\n assign(summary, \"receiverAddress\", voucher.receiverAddress);\n assign(summary, \"receiverTaxId\", voucher.receiverTaxId);\n assign(summary, \"receiverCountryTaxId\", voucher.receiverCountryTaxId);\n assign(summary, \"currencyId\", voucher.currencyId);\n assign(summary, \"exchangeRate\", voucher.exchangeRate);\n assign(\n summary,\n \"totalAmount\",\n voucher.totalAmount === undefined\n ? undefined\n : Math.round(voucher.totalAmount * 100)\n );\n assign(summary, \"result\", voucher.result);\n assign(summary, \"cae\", voucher.cae);\n assign(summary, \"caeExpiry\", isoDate(voucher.caeExpiry));\n return summary;\n}\n\nfunction exportQr(\n taxId: string,\n attempted: VoucherCoordinates,\n data: WsfexVoucherInput,\n date: string,\n cae: string\n): Pick<ExportIssuedVoucher, \"qr\" | \"qrPayload\"> {\n try {\n const qrPayload = arcaQrPayload({\n taxId,\n ...attempted,\n date,\n total: Math.round(data.totalAmount * 100),\n currency: data.currencyId,\n ...(data.exchangeRate === undefined\n ? {}\n : { exchangeRate: data.exchangeRate }),\n cae,\n });\n return { qr: qrUrlForPayload(qrPayload), qrPayload };\n } catch {\n return {};\n }\n}\n\nfunction originalTotal(original: WsfexVoucherInfo): number {\n return Math.round(original.totalAmount * 100);\n}\n\nfunction deriveReceiver(to: unknown) {\n assertIssueObject(to, \"to\");\n assertIssueKeys(\n to,\n [\"country\", \"name\", \"address\", \"taxId\", \"countryTaxId\"],\n \"to\"\n );\n const receiver = to as ExportReceiver;\n if (\n !(\n Number.isSafeInteger(receiver.country) &&\n receiver.country >= 1 &&\n receiver.country <= 999\n )\n ) {\n invalid(\"to.country\", \"an ARCA destination country code\");\n }\n if (receiver.taxId === undefined && receiver.countryTaxId === undefined) {\n throw new ArcaInputError(\"to.taxId or to.countryTaxId is required.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"to.taxId\",\n expected: \"the receiver's tax ID abroad, ARCA's country CUIT, or both\",\n });\n }\n if (\n receiver.countryTaxId !== undefined &&\n !(\n typeof receiver.countryTaxId === \"string\" &&\n /^\\d{11}$/.test(receiver.countryTaxId)\n )\n ) {\n invalid(\"to.countryTaxId\", \"an 11-digit string\");\n }\n return {\n destination: receiver.country,\n receiverName: text(receiver.name, \"to.name\", 200),\n ...(receiver.countryTaxId === undefined\n ? {}\n : { receiverCountryTaxId: receiver.countryTaxId }),\n receiverAddress: text(receiver.address, \"to.address\", 300),\n ...optionalText(receiver.taxId, \"receiverTaxId\", 50, \"to.taxId\"),\n };\n}\n\nfunction deriveExport(value: unknown): {\n exportType: WsfexExportType;\n permitExists?: \"S\" | \"N\";\n permits?: { id: string; destination: number }[];\n incoterms?: string;\n incotermsDetail?: string;\n paymentDate?: string;\n} {\n assertIssueObject(value, \"export\");\n const exported = value as ExportOfGoods | ExportOfServices;\n if (exported.kind === \"goods\") {\n assertIssueKeys(\n exported,\n [\"kind\", \"incoterms\", \"incotermsDetail\", \"permits\"],\n \"export\"\n );\n if (\n typeof exported.incoterms !== \"string\" ||\n !/^[A-Z]{3}$/.test(exported.incoterms)\n ) {\n invalid(\"export.incoterms\", \"a three-letter Incoterm such as FOB\");\n }\n let permits: { id: string; destination: number }[] | undefined;\n if (exported.permits !== undefined) {\n if (!Array.isArray(exported.permits) || exported.permits.length === 0) {\n invalid(\"export.permits\", \"a non-empty list, or absent while pending\");\n }\n const seen = new Set<string>();\n permits = exported.permits.map((entry, index) => {\n const field = `export.permits[${index}]`;\n const permit = entry as { id: unknown; destination: unknown };\n assertIssueObject(permit, field);\n assertIssueKeys(permit, [\"id\", \"destination\"], field);\n if (\n typeof permit.id !== \"string\" ||\n !/^\\d{5}[A-Z0-9]{4}\\d{6}[A-Z]$/.test(permit.id)\n ) {\n invalid(`${field}.id`, \"a shipping permit such as 09052EC01006154G\");\n }\n if (\n !(\n typeof permit.destination === \"number\" &&\n Number.isSafeInteger(permit.destination) &&\n permit.destination >= 1 &&\n permit.destination <= 999\n )\n ) {\n invalid(`${field}.destination`, \"an ARCA destination country code\");\n }\n const pair = `${permit.id}:${permit.destination}`;\n if (seen.has(pair)) {\n invalid(field, \"a permit and destination listed once\");\n }\n seen.add(pair);\n return {\n id: permit.id as string,\n destination: permit.destination as number,\n };\n });\n }\n return {\n exportType: 1,\n permitExists: permits === undefined ? \"N\" : \"S\",\n ...(permits === undefined ? {} : { permits }),\n incoterms: exported.incoterms,\n ...optionalText(\n exported.incotermsDetail,\n \"incotermsDetail\",\n 20,\n \"export.incotermsDetail\"\n ),\n };\n }\n if (exported.kind === \"services\" || exported.kind === \"other\") {\n assertIssueKeys(exported, [\"kind\", \"paymentDate\"], \"export\");\n if (exported.paymentDate === undefined) {\n throw new ArcaInputError(\"export.paymentDate is required.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"export.paymentDate\",\n expected: \"the date the receiver pays\",\n });\n }\n return {\n exportType: EXPORT_KINDS[exported.kind],\n paymentDate: normalizeWsfeDateInput(\n exported.paymentDate,\n \"export.paymentDate\"\n ) as string,\n };\n }\n return invalid(\"export.kind\", \"goods, services or other\");\n}\n\nfunction deriveCurrency(\n currency: ExportIssueInput[\"currency\"],\n rate: unknown\n): { currencyId: string; exchangeRate: string } {\n const value = currency ?? \"ARS\";\n let currencyId: string;\n if (typeof value === \"object\" && value !== null) {\n assertIssueKeys(value, [\"id\"], \"currency\");\n if (typeof value.id !== \"string\" || !/^[A-Z0-9]{3}$/.test(value.id)) {\n invalid(\"currency.id\", \"a three-character ARCA currency code\");\n }\n currencyId = value.id;\n } else if (value === \"ARS\" || value === \"USD\") {\n currencyId = ARCA_CURRENCY_IDS[value];\n } else {\n return invalid(\"currency\", \"ARS, USD or { id }\");\n }\n if (rate !== undefined && typeof rate !== \"string\") {\n invalid(\"exchangeRate\", \"a decimal string\");\n }\n if (currencyId === ARCA_CURRENCY_IDS.ARS) {\n const exchangeRate = serializeArcaExchangeRate(rate ?? \"1\", \"exchangeRate\");\n if (Number(exchangeRate) !== 1) {\n invalid(\"exchangeRate\", \"1 for pesos\");\n }\n return { currencyId, exchangeRate };\n }\n if (rate === undefined) {\n throw new ArcaInputError(\"exchangeRate is required for this currency.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"exchangeRate\",\n expected: \"ARCA's rate, from wsfex.getExchangeRate()\",\n });\n }\n return {\n currencyId,\n exchangeRate: serializeArcaExchangeRate(rate, \"exchangeRate\"),\n };\n}\n\nfunction deriveLanguage(language: unknown): WsfexLanguage {\n if (language === undefined) {\n return 1;\n }\n if (typeof language !== \"string\" || !Object.hasOwn(LANGUAGES, language)) {\n return invalid(\"language\", \"es, en or pt\");\n }\n return LANGUAGES[language as keyof typeof LANGUAGES];\n}\n\nconst SCALE_6 = 1_000_000n;\n\nfunction deriveItems(\n value: unknown,\n path: string\n): { items: WsfexItem[]; total: number } {\n if (!Array.isArray(value) || value.length < 1 || value.length > 9999) {\n invalid(path, \"a list of 1 to 9999 items\");\n }\n let total = 0n;\n const items = (value as readonly ExportItem[]).map((item, index) => {\n const line = deriveItem(item, `${path}[${index}]`);\n total += BigInt(item.amount);\n return line;\n });\n if (total < 0n) {\n invalid(path, \"lines whose total is zero or positive\");\n }\n return { items, total: Number(total) };\n}\n\nfunction deriveItem(item: ExportItem, field: string): WsfexItem {\n assertIssueObject(item, field);\n assertIssueKeys(\n item,\n [\n \"description\",\n \"unit\",\n \"quantity\",\n \"unitPrice\",\n \"discount\",\n \"code\",\n \"amount\",\n ],\n field\n );\n if (!(Number.isSafeInteger(item.unit) && item.unit >= 0 && item.unit <= 99)) {\n invalid(`${field}.unit`, \"an ARCA unit of measure\");\n }\n assertItemAmount(item, field);\n const line: WsfexItem = {\n ...optionalText(item.code, \"code\", 50, `${field}.code`),\n description: text(item.description, `${field}.description`, 4000),\n unit: item.unit,\n amount: item.amount / 100,\n };\n if (!UNPRICED_UNITS.includes(item.unit)) {\n return { ...line, ...pricedLine(item, field) };\n }\n // Rule 1775: these units carry no quantity, price or discount.\n for (const key of [\"quantity\", \"unitPrice\", \"discount\"] as const) {\n if (item[key] !== undefined && Number(item[key]) !== 0) {\n invalid(`${field}.${key}`, `absent for unit ${item.unit}`);\n }\n }\n return line;\n}\n\n/** Rule 1810: unit 99 discounts, 97 advances of either sign, the rest not negative. */\nfunction assertItemAmount(item: ExportItem, field: string) {\n if (!Number.isSafeInteger(item.amount)) {\n invalid(`${field}.amount`, \"an integer amount in minor units\");\n }\n if (item.unit === 99 && item.amount >= 0) {\n invalid(`${field}.amount`, \"negative for a discount line\");\n }\n if (item.unit !== 97 && item.unit !== 99 && item.amount < 0) {\n invalid(`${field}.amount`, \"zero or positive for this unit\");\n }\n if (Math.abs(item.amount) > 999_999_999_999_999) {\n invalid(`${field}.amount`, \"at most 13 integer digits\");\n }\n}\n\n/** Rule 1815: the line equals quantity × unitPrice less its discount. */\nfunction pricedLine(\n item: ExportItem,\n field: string\n): Pick<WsfexItem, \"quantity\" | \"unitPrice\" | \"discount\"> {\n const quantity = scaledQuantity(item.quantity, `${field}.quantity`);\n const price = scaledPrice(item.unitPrice, `${field}.unitPrice`);\n const discount = item.discount ?? 0;\n if (!(Number.isSafeInteger(discount) && discount >= 0)) {\n invalid(`${field}.discount`, \"a non-negative amount in minor units\");\n }\n // quantity × price is scaled 10^12, and a minor unit is 10^10 of that.\n const exact = quantity * price - BigInt(discount) * 10_000_000_000n;\n if (exact < 0n) {\n invalid(`${field}.discount`, \"at most the line's quantity × unitPrice\");\n }\n if (!withinLineTolerance(exact, BigInt(item.amount))) {\n throw new ArcaInputError(\n `${field}.amount must equal quantity × unitPrice less discount.`,\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: `${field}.amount`,\n expected: String(roundHalfEvenRatio(exact, 10_000_000_000n)),\n }\n );\n }\n return {\n quantity: item.quantity as number,\n unitPrice: item.unitPrice as string,\n ...(discount > 0 ? { discount: discount / 100 } : {}),\n };\n}\n\n/**\n * WSFEX rule 1815 and section 2.18: ARCA rounds quantity × price − discount\n * half-even to 5 decimals and accepts the line if it differs from the amount\n * by at most 0.01, or by at most 0.01% of it. The relative bound uses the\n * smaller side, so this never accepts a line ARCA would reject.\n */\nfunction withinLineTolerance(exact: bigint, amountMinorUnits: bigint) {\n // Both sides at 5 decimals: 10^12 → 10^5, and a minor unit is 10^3.\n const computed = roundHalfEvenRatio(exact, 10_000_000n);\n const amount = amountMinorUnits * 1000n;\n const error = computed > amount ? computed - amount : amount - computed;\n if (error <= 1000n) {\n return true;\n }\n const base = computed < amount ? computed : amount;\n return base > 0n && error * 10_000n <= base;\n}\n\nfunction scaledQuantity(value: unknown, field: string): bigint {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n return invalid(field, \"a positive number\");\n }\n const fixed = value.toFixed(6);\n if (Number(fixed) !== value || fixed.split(\".\")[0].length > 12) {\n invalid(field, \"at most 12 integer digits and 6 decimals\");\n }\n const [whole, fraction = \"\"] = fixed.split(\".\");\n return BigInt(whole) * SCALE_6 + BigInt(fraction.padEnd(6, \"0\"));\n}\n\nfunction scaledPrice(value: unknown, field: string): bigint {\n if (typeof value !== \"string\" || !/^\\d{1,12}(\\.\\d{1,6})?$/.test(value)) {\n return invalid(field, \"a decimal string with at most 6 decimals\");\n }\n const [whole, fraction = \"\"] = value.split(\".\");\n return BigInt(whole) * SCALE_6 + BigInt(fraction.padEnd(6, \"0\"));\n}\n\nfunction reviewedTotal(total: unknown, computed: number): number {\n if (total === undefined) {\n return computed;\n }\n if (!Number.isSafeInteger(total) || (total as number) < 0) {\n invalid(\"total\", \"a non-negative integer amount in minor units\");\n }\n if (total !== computed) {\n throw new ArcaInputError(\"total must equal the sum of items.\", {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: \"total\",\n expected: String(computed),\n });\n }\n return computed;\n}\n\nfunction assertSalesPoint(value: unknown, field: string) {\n if (\n !(\n typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= 1 &&\n value <= 99_998\n )\n ) {\n invalid(field, \"an integer from 1 through 99998\");\n }\n}\n\nfunction text(value: unknown, field: string, max: number): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ArcaInputError(`${field} is required.`, {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field,\n expected: `a non-empty string of at most ${max} characters`,\n });\n }\n if (value.length > max) {\n invalid(field, `at most ${max} characters`);\n }\n return value;\n}\n\nfunction optionalText<K extends string>(\n value: unknown,\n key: K,\n max: number,\n field: string = key\n): { [P in K]?: string } {\n if (value === undefined) {\n return {};\n }\n return { [key]: text(value, field, max) } as { [P in K]?: string };\n}\n\nfunction isoDate(value: string | undefined): string | undefined {\n return value === undefined ? undefined : (toIsoDate(value) ?? value);\n}\n\nfunction assign<T, K extends keyof T>(target: T, key: K, value: T[K]) {\n if (value !== undefined) {\n target[key] = value;\n }\n}\n\nfunction invalid(field: string, expected: string): never {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n","import { ARCA_DOCUMENT_TYPES } from \"../constants\";\nimport { ArcaError, ArcaInputError } from \"../errors\";\nimport {\n isWithinArcaTolerance,\n normalizeArcaAmountToMinorUnits,\n} from \"../internal/decimal\";\nimport { minor, voucherFamily } from \"./issuance-fields\";\nimport {\n normalizeWsfeDateInput,\n type WsfeVoucherInfo,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport type { WsmtxcaService, WsmtxcaVoucherInfo } from \"./wsmtxca\";\n\n/**\n * One WSMTXCA provider line, derived from an `items` entry on the way out and\n * read back from ARCA on the way in. Amounts are cents; `unitPrice` is a\n * decimal major-unit string, the SDK's one monetary exception.\n */\nexport type WsmtxcaLine = {\n description: string;\n quantity: number;\n unit: number;\n unitPrice: string;\n discount: number;\n vatCondition: number;\n vatAmount?: number;\n amount: number;\n code?: string;\n matrixCode?: string;\n matrixUnits?: number;\n};\n/** @internal Shape written by facturas 0.10 through 0.12. */\nexport type LegacyWsmtxcaLine = Omit<WsmtxcaLine, \"discount\"> & {\n discount?: number;\n};\nexport type WsmtxcaIssueRequest = ReturnType<typeof wsmtxcaRequest>;\nexport type FiscalHeader = WsfeVoucherInput & {\n /** Derived provider lines. WSFE never reads them; WSMTXCA sends them. */\n lines?: readonly WsmtxcaLine[];\n /** @internal Lines mirrored from an authorized WSMTXCA consultation. */\n authorizedLines?: readonly WsmtxcaLine[];\n /** @internal Durable v2 reservation evidence written before `lines`. */\n details?: readonly LegacyWsmtxcaLine[];\n};\nconst iso = (value: string | undefined) => {\n if (value === undefined) {\n return undefined;\n }\n const date = normalizeWsfeDateInput(\n value as import(\"./wsfe\").WsfeDateInput,\n \"date\"\n ) as string;\n return `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`;\n};\n\n/**\n * Rule 100: WSMTXCA authorizes classes A and B only, never class C. Checked\n * where a new voucher is prepared, before its lines or any lookup.\n */\nexport function assertWsmtxcaVoucherType(voucherType: number): void {\n if (voucherFamily(voucherType).voucherClass === \"C\") {\n invalid(\n \"voucherType\",\n \"WSMTXCA authorizes class A and B vouchers only; issue class C through WSFE\"\n );\n }\n}\n\n/**\n * Rules 108 and 128: an unidentified receiver sends neither field. The keys\n * stay, undefined, so the consultation match still checks ARCA sent none.\n */\nfunction wsmtxcaReceiverDocument(data: FiscalHeader) {\n const unidentified =\n data.documentType === ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL;\n return {\n codigoTipoDocumento: unidentified ? undefined : data.documentType,\n numeroDocumento: unidentified ? undefined : data.documentNumber,\n };\n}\n\nexport function wsmtxcaRequest(data: FiscalHeader, number?: number) {\n const legacy = data.details !== undefined;\n const authorized = data.authorizedLines !== undefined;\n const lines = data.lines ?? data.authorizedLines ?? data.details;\n const sources = [data.lines, data.authorizedLines, data.details].filter(\n (source) => source !== undefined\n ).length;\n if (!lines?.length || sources !== 1) {\n invalid(\"items\", \"WSMTXCA requires items with line detail\");\n }\n const items = lines.map((line) => ({\n unidadesMtx: line.matrixUnits,\n codigoMtx: line.matrixCode,\n codigo: line.code,\n descripcion: line.description,\n cantidad: line.quantity,\n codigoUnidadMedida: line.unit,\n precioUnitario: line.unitPrice,\n // Old durable records omitted a zero discount. Rebuild the exact request\n // those releases sent without rewriting the stored fiscal evidence.\n importeBonificacion: minor(line.discount ?? 0, \"items.discount\"),\n codigoCondicionIVA: line.vatCondition,\n ...(line.vatAmount === undefined\n ? {}\n : { importeIVA: minor(line.vatAmount, \"items.vatAmount\") }),\n importeItem: minor(line.amount, \"items.amount\"),\n }));\n // Newly derived lines and their header come from the same items, so they\n // must match exactly. Authorized consultations and legacy reservations can\n // retain ARCA's historical one-cent reconciliation difference.\n const itemTotal = lines.reduce((sum, line) => sum + BigInt(line.amount), 0n);\n const expected =\n normalizeArcaAmountToMinorUnits(data.totalAmount, \"total\") -\n normalizeArcaAmountToMinorUnits(data.taxAmount, \"taxes\");\n if (\n legacy || authorized\n ? !isWithinArcaTolerance(itemTotal, expected, 1)\n : itemTotal !== expected\n ) {\n throw new ArcaError(\n \"The derived WSMTXCA items do not sum to the voucher header excluding tributes. This is an SDK invariant failure.\",\n \"ARCA_ISSUE_INVARIANT\"\n );\n }\n // WSMTXCA error 114: the tribute amount and its detail travel together or\n // not at all. A zero amount with no detail is still an amount to ARCA.\n const tributes = data.taxes?.length ? data.taxes : undefined;\n if (\n tributes === undefined &&\n normalizeArcaAmountToMinorUnits(data.taxAmount, \"taxes\") !== 0n\n ) {\n invalid(\"taxes\", \"Tribute amount requires tribute details\");\n }\n return {\n comprobanteCAERequest: {\n codigoTipoComprobante: data.voucherType,\n numeroPuntoVenta: data.salesPoint,\n ...(number === undefined ? {} : { numeroComprobante: number }),\n fechaEmision: iso(data.voucherDate),\n ...wsmtxcaReceiverDocument(data),\n condicionIVAReceptor: data.receiverVatConditionId,\n importeGravado: data.netAmount,\n importeNoGravado: data.nonTaxableAmount,\n importeExento: data.exemptAmount,\n importeSubtotal:\n Number(\n normalizeArcaAmountToMinorUnits(data.netAmount, \"net\") +\n normalizeArcaAmountToMinorUnits(data.nonTaxableAmount, \"untaxed\") +\n normalizeArcaAmountToMinorUnits(data.exemptAmount, \"exempt\")\n ) / 100,\n ...(tributes === undefined\n ? {}\n : { importeOtrosTributos: data.taxAmount }),\n importeTotal: data.totalAmount,\n codigoMoneda: data.currencyId,\n cotizacionMoneda: data.exchangeRate,\n codigoConcepto: data.concept,\n fechaServicioDesde: iso(data.serviceStartDate),\n fechaServicioHasta: iso(data.serviceEndDate),\n fechaVencimientoPago: iso(data.paymentDueDate),\n ...(data.sameCurrencyForeignCancellation === undefined\n ? {}\n : {\n cancelaEnMismaMonedaExtranjera:\n data.sameCurrencyForeignCancellation,\n }),\n arrayComprobantesAsociados: data.associatedVouchers?.length\n ? {\n comprobanteAsociado: data.associatedVouchers.map((v) => ({\n codigoTipoComprobante: v.type,\n numeroPuntoVenta: v.salesPoint,\n numeroComprobante: v.number,\n cuit: v.taxId,\n fechaEmision: iso(v.voucherDate),\n })),\n }\n : undefined,\n periodoComprobantesAsociados: data.associatedPeriod\n ? {\n fechaDesde: iso(data.associatedPeriod.startDate),\n fechaHasta: iso(data.associatedPeriod.endDate),\n }\n : undefined,\n arrayCompradores: data.buyers?.length\n ? {\n comprador: data.buyers.map((b) => ({\n codigoTipoDocumento: b.documentType,\n numeroDocumento: b.documentNumber,\n porcentaje: b.percentage,\n })),\n }\n : undefined,\n ...(tributes\n ? {\n arrayOtrosTributos: {\n otroTributo: tributes.map((t) => ({\n codigo: t.id,\n descripcion: t.description,\n baseImponible: t.baseAmount,\n importe: t.amount,\n })),\n },\n }\n : {}),\n arrayItems: { item: items },\n arraySubtotalesIVA: data.vatRates?.length\n ? {\n subtotalIVA: data.vatRates.map((v) => ({\n codigo: v.id,\n importe: v.amount,\n })),\n }\n : undefined,\n arrayDatosAdicionales: wsmtxcaAdditionalData(data.optionalFields),\n arrayActividades: data.activities?.length\n ? { actividad: data.activities.map((a) => ({ codigo: a.id })) }\n : undefined,\n },\n };\n}\nfunction invalid(field: string, message: string): never {\n throw new ArcaInputError(message, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n });\n}\nfunction rows(\n value: unknown,\n key: string\n): Record<string, unknown>[] | undefined {\n const data =\n value && typeof value === \"object\"\n ? (value as Record<string, unknown>)[key]\n : undefined;\n if (data === undefined) {\n return undefined;\n }\n const list = Array.isArray(data) ? data : [data];\n if (list.some((item) => !item || typeof item !== \"object\")) {\n return undefined;\n }\n return list as Record<string, unknown>[];\n}\nexport function wsmtxcaHeader(\n found: WsmtxcaVoucherInfo\n): WsfeVoucherInfo & { lines?: WsmtxcaLine[] } {\n const raw = found.raw;\n const items = rows(raw.arrayItems, \"item\");\n const lines = items?.map((i) => ({\n description: String(i.descripcion ?? \"\"),\n quantity: Number(i.cantidad),\n unit: Number(i.codigoUnidadMedida),\n unitPrice: String(i.precioUnitario),\n discount: Number(\n normalizeArcaAmountToMinorUnits(\n Number(i.importeBonificacion ?? 0),\n \"discount\"\n )\n ),\n vatCondition: Number(i.codigoCondicionIVA),\n vatAmount:\n i.importeIVA === undefined\n ? undefined\n : Number(normalizeArcaAmountToMinorUnits(Number(i.importeIVA), \"vat\")),\n amount: Number(\n normalizeArcaAmountToMinorUnits(Number(i.importeItem), \"amount\")\n ),\n code: i.codigo === undefined ? undefined : String(i.codigo),\n matrixCode: i.codigoMtx === undefined ? undefined : String(i.codigoMtx),\n matrixUnits:\n i.unidadesMtx === undefined ? undefined : Number(i.unidadesMtx),\n }));\n return {\n ...found,\n voucherNumber: found.voucherNumber ?? 0,\n voucherDate: found.invoiceDate,\n netAmount: found.taxableAmount,\n // consultarComprobante is an authorized-voucher lookup. No result flag is returned.\n result: found.cae ? \"A\" : undefined,\n serviceStartDate:\n raw.fechaServicioDesde === undefined\n ? undefined\n : String(raw.fechaServicioDesde),\n serviceEndDate:\n raw.fechaServicioHasta === undefined\n ? undefined\n : String(raw.fechaServicioHasta),\n paymentDueDate:\n raw.fechaVencimientoPago === undefined\n ? undefined\n : String(raw.fechaVencimientoPago),\n lines,\n vatRates: rows(raw.arraySubtotalesIVA, \"subtotalIVA\")?.map((v) => ({\n id: Number(v.codigo),\n amount: Number(v.importe),\n baseAmount:\n Number(\n (lines ?? [])\n .filter((i) => i.vatCondition === Number(v.codigo))\n .reduce((sum, i) => sum + BigInt(i.amount), 0n) -\n normalizeArcaAmountToMinorUnits(Number(v.importe), \"vat\")\n ) / 100,\n })),\n taxes: rows(raw.arrayOtrosTributos, \"otroTributo\")?.map((t) => ({\n id: Number(t.codigo),\n description:\n t.descripcion === undefined ? undefined : String(t.descripcion),\n baseAmount: Number(t.baseImponible),\n amount: Number(t.importe),\n rate: 0,\n })),\n sameCurrencyForeignCancellation:\n found.currencyId !== \"PES\" &&\n (raw.cancelaEnMismaMonedaExtranjera === \"S\" ||\n raw.cancelaEnMismaMonedaExtranjera === \"N\")\n ? raw.cancelaEnMismaMonedaExtranjera\n : undefined,\n optionalFields: rows(raw.arrayDatosAdicionales, \"datoAdicional\")?.map(\n (v) => ({ id: String(v.t), value: String(v.c1) })\n ),\n activities: rows(raw.arrayActividades, \"actividad\")?.map((v) => ({\n id: Number(v.codigo),\n })),\n buyers: rows(raw.arrayCompradores, \"comprador\")?.map((v) => ({\n documentType: Number(v.codigoTipoDocumento),\n documentNumber: Number(v.numeroDocumento),\n percentage: Number(v.porcentaje),\n })),\n associatedVouchers: rows(\n raw.arrayComprobantesAsociados,\n \"comprobanteAsociado\"\n )?.map((v) => ({\n type: Number(v.codigoTipoComprobante),\n salesPoint: Number(v.numeroPuntoVenta),\n number: Number(v.numeroComprobante),\n taxId: v.cuit === undefined ? undefined : String(v.cuit),\n voucherDate: v.fechaEmision as import(\"./wsfe\").WsfeDateInput | undefined,\n })),\n };\n}\n\n/** Compare wire evidence, never inject expected values into the lookup. */\nexport function matchWsmtxcaDetails(\n data: FiscalHeader,\n number: number,\n raw: Record<string, unknown>\n): \"match\" | \"incomplete\" | \"conflict\" {\n const request: Record<string, unknown> = wsmtxcaRequest(\n data,\n number\n ).comprobanteCAERequest;\n let missing = false;\n for (const key of Object.keys(request)) {\n const expected = request[key];\n const actual = raw[key];\n if (expected === undefined) {\n if (!(emptyWire(actual) || unidentifiedEcho(data, key, actual))) {\n return \"conflict\";\n }\n continue;\n }\n const result = compareWire(\n normalizeWire(expected, key),\n normalizeWire(actual, key)\n );\n if (result === \"conflict\") {\n return \"conflict\";\n }\n missing ||= result === \"incomplete\";\n }\n return missing ? \"incomplete\" : \"match\";\n}\n/**\n * An omitted receiver document may come back as ARCA's own 99/0 for an\n * unidentified receiver. Any other document is a different voucher.\n */\nfunction unidentifiedEcho(\n data: FiscalHeader,\n key: string,\n actual: unknown\n): boolean {\n if (data.documentType !== ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL) {\n return false;\n }\n if (key === \"codigoTipoDocumento\") {\n return String(actual) === String(ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL);\n }\n return key === \"numeroDocumento\" && String(actual) === \"0\";\n}\nfunction emptyWire(value: unknown): boolean {\n return (\n value === undefined ||\n value === null ||\n (typeof value === \"object\" && Object.values(value).every(emptyWire))\n );\n}\nfunction compareWire(\n expected: unknown,\n actual: unknown\n): \"match\" | \"incomplete\" | \"conflict\" {\n if (actual === undefined || actual === null) {\n return \"incomplete\";\n }\n if (expected !== null && typeof expected === \"object\") {\n if (\n typeof actual !== \"object\" ||\n Array.isArray(expected) !== Array.isArray(actual)\n ) {\n return \"conflict\";\n }\n const left = expected as Record<string, unknown>;\n const right = actual as Record<string, unknown>;\n if (\n Object.keys(right).some((key) => !(key in left || emptyWire(right[key])))\n ) {\n return \"conflict\";\n }\n let missing = false;\n for (const key of Object.keys(left)) {\n const result = compareWire(left[key], right[key]);\n if (result === \"conflict\") {\n return result;\n }\n missing ||= result === \"incomplete\";\n }\n return missing ? \"incomplete\" : \"match\";\n }\n return expected === actual ? \"match\" : \"conflict\";\n}\nconst LIST_KEYS = new Set([\n \"item\",\n \"comprobanteAsociado\",\n \"otroTributo\",\n \"subtotalIVA\",\n \"datoAdicional\",\n \"actividad\",\n \"comprador\",\n]);\nconst TEXT_KEYS = new Set([\n \"codigo\",\n \"descripcion\",\n \"codigoMtx\",\n \"c1\",\n \"c2\",\n \"c3\",\n \"c4\",\n \"c5\",\n \"c6\",\n \"codigoMoneda\",\n \"cancelaEnMismaMonedaExtranjera\",\n]);\nfunction normalizeWire(value: unknown, key = \"\"): unknown {\n if (value === undefined || value === null) {\n return value;\n }\n if (LIST_KEYS.has(key)) {\n return (Array.isArray(value) ? value : [value]).map((v) =>\n normalizeWire(v)\n );\n }\n if (Array.isArray(value)) {\n return value.map((v) => normalizeWire(v));\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => [k, normalizeWire(v, k)])\n );\n }\n if (TEXT_KEYS.has(key) && value !== undefined && value !== null) {\n return String(value);\n }\n if (\n !TEXT_KEYS.has(key) &&\n typeof value === \"string\" &&\n /^\\d+(\\.\\d+)?$/.test(value)\n ) {\n return Number(value);\n }\n return value;\n}\nexport function createWsmtxcaIssuanceService(wsmtxca: WsmtxcaService) {\n return {\n getNextVoucherNumber: async (\n input: Parameters<import(\"./wsfe\").WsfeService[\"getNextVoucherNumber\"]>[0]\n ) => (await wsmtxca.getLastAuthorizedVoucher(input)).voucherNumber + 1,\n issue: (input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n data: FiscalHeader;\n voucherNumber: number;\n abortSignal?: AbortSignal;\n }) =>\n wsmtxca.issue({\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n abortSignal: input.abortSignal,\n data: wsmtxcaRequest(input.data, input.voucherNumber),\n }),\n lookupVoucher: async (\n input: Parameters<import(\"./wsfe\").WsfeService[\"lookupVoucher\"]>[0]\n ) => {\n const result = await wsmtxca.lookupVoucher({\n ...input,\n voucherNumber: input.number,\n });\n return result.kind === \"found\"\n ? { ...result, voucher: wsmtxcaHeader(result.voucher) }\n : result;\n },\n };\n}\n\nfunction wsmtxcaAdditionalData(fields: WsfeVoucherInput[\"optionalFields\"]) {\n if (!fields?.length) {\n return undefined;\n }\n const options = new Map(fields.map((f) => [f.id, f.value]));\n return {\n datoAdicional: [\n ...(options.has(\"2101\")\n ? [{ t: 21, c1: options.get(\"2101\"), c2: options.get(\"2102\") }]\n : []),\n ...fields\n .filter((f) => f.id !== \"2101\" && f.id !== \"2102\")\n .map((f) => ({ t: Number(f.id), c1: f.value })),\n ],\n };\n}\n","import {\n ARCA_DOCUMENT_TYPES,\n type ReceiverCondition,\n type VoucherClass,\n} from \"../constants\";\nimport { ArcaInputError } from \"../errors\";\nimport {\n assertArcaMinorUnits,\n normalizeArcaAmountToMinorUnits,\n} from \"../internal/decimal\";\nimport {\n applyFceFields,\n applyIssuanceFields,\n type IssuanceFields,\n minor,\n tributeTotal,\n validateIssuanceFields,\n voucherFamily,\n} from \"./issuance-fields\";\nimport {\n normalizeWsfeDateInput,\n normalizeWsfeVoucherInput,\n type WsfeDateInput,\n type WsfeVoucherInfo,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport {\n calculateWsfeAmounts,\n type IssueAmounts,\n type VatItem,\n type WsfeAmountsInput,\n} from \"./wsfe-amounts\";\nimport {\n assertIssueKeys,\n assertIssueObject,\n buenosAiresDate,\n type IssueInput,\n receiverConditionId,\n reviewedInvoiceAmounts,\n} from \"./wsfe-derive\";\nimport type { VoucherCoordinates } from \"./wsfe-identity\";\n\n/**\n * The credited lines and, at most, the note's own sales point and date.\n * Class, receiver, currency, concept and service dates come from the originals.\n *\n * The mode is explicit: `items` or a reviewed `amounts` breakdown credits the\n * chosen lines, `all: true` credits the whole original. A forgotten field never\n * credits the whole invoice. A full note mirrors the original's tributes; a\n * partial note carries the `taxes` the caller chose, never a prorated share.\n */\nexport type CreditNoteInput = Pick<\n IssuanceFields,\n \"taxes\" | \"optionalFields\" | \"fce\"\n> & {\n /**\n * The authorized invoice or debit note the note corrects, or a non-empty\n * list of them. Every original is consulted and every one is associated to\n * the note; they must agree on everything the note inherits.\n */\n for: VoucherCoordinates | readonly VoucherCoordinates[];\n salesPoint?: number;\n date?: WsfeDateInput;\n /**\n * The receiver's IVA condition, used only when the consulted original does\n * not report one. ARCA omits it on vouchers authorized before the field\n * existed. When the original reports it, the two must agree.\n */\n to?: { condition: ReceiverCondition | number };\n} & (\n | {\n items: NonNullable<IssueInput[\"items\"]>;\n total?: number;\n all?: never;\n amounts?: never;\n }\n | {\n amounts: import(\"./issuance-fields\").VoucherAmounts;\n items?: never;\n total?: number;\n all?: never;\n }\n | { all: true; items?: never; total?: never; amounts?: never }\n );\n\ntype CreditNote = { voucherType: number; voucherClass: VoucherClass };\ntype CreditNoteHeader = Omit<\n WsfeVoucherInput,\n | \"totalAmount\"\n | \"netAmount\"\n | \"vatAmount\"\n | \"nonTaxableAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatRates\"\n>;\ntype DerivedCreditNote = {\n data: WsfeVoucherInput;\n voucherClass: VoucherClass;\n amounts: IssueAmounts;\n /** The items the header came from, so provider lines derive from the same money. */\n lineSource?: WsfeAmountsInput;\n};\n\nfunction invalid(reason: string): never {\n throw new ArcaInputError(`issueCreditNote cannot proceed: ${reason}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n });\n}\n/**\n * WSMTXCA omits the document of an unidentified receiver, or echoes part of\n * ARCA's 99/0. An original whose fields are each absent or that 99/0 is the\n * receiver WSFE would have reported, as the consultation match accepts.\n */\nfunction originalReceiverDocument(original: WsfeVoucherInfo): {\n documentType: number;\n documentNumber: number;\n} {\n const { documentType, documentNumber } = original;\n if (\n (documentType === undefined ||\n documentType === ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL) &&\n (documentNumber === undefined || String(documentNumber) === \"0\")\n ) {\n return {\n documentType: ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL,\n documentNumber: 0,\n };\n }\n return {\n documentType: required(original.documentType, \"documentType\"),\n documentNumber: Number(required(original.documentNumber, \"documentNumber\")),\n };\n}\n\nfunction required<T>(value: T | undefined, field: string): T {\n if (value === undefined || value === null) {\n invalid(`original is missing ${field}`);\n }\n return value;\n}\n\n/**\n * Mirrors the original line by line, which items cannot reproduce cent-exact.\n * There is only ever one original here: a full note of several has no total.\n */\nexport function deriveWsfeFullCreditNote(\n original: WsfeVoucherInfo,\n input: CreditNoteInput,\n now = new Date(),\n kind: \"creditNote\" | \"debitNote\" = \"creditNote\"\n): DerivedCreditNote {\n const { note, header } = prepareCreditNote([original], input, now, kind);\n const data: WsfeVoucherInput = {\n ...header,\n ...(original.taxes ? { taxes: structuredClone(original.taxes) } : {}),\n totalAmount: required(original.totalAmount, \"totalAmount\"),\n netAmount: required(original.netAmount, \"netAmount\"),\n vatAmount: required(original.vatAmount, \"vatAmount\"),\n exemptAmount: required(original.exemptAmount, \"exemptAmount\"),\n nonTaxableAmount: required(original.nonTaxableAmount, \"nonTaxableAmount\"),\n taxAmount: required(original.taxAmount, \"taxAmount\"),\n ...(original.vatRates === undefined\n ? {}\n : { vatRates: original.vatRates.map((rate) => ({ ...rate })) }),\n };\n normalizeWsfeVoucherInput(data);\n const total = Number(\n normalizeArcaAmountToMinorUnits(data.totalAmount, \"totalAmount\")\n );\n return {\n data,\n voucherClass: note.voucherClass,\n amounts: { computedTotal: total, sentTotal: total, vatAdjustment: 0 },\n };\n}\n\n/** Credits chosen lines through the same amount pipeline as issue(). */\nexport function deriveWsfePartialCreditNote(\n originals: readonly WsfeVoucherInfo[],\n input: CreditNoteInput,\n now = new Date(),\n kind: \"creditNote\" | \"debitNote\" = \"creditNote\"\n): DerivedCreditNote {\n if (input.items === undefined && input.amounts === undefined) {\n invalid(\"items is required to credit chosen lines\");\n }\n // A requested total is minor units like every other amount. It is checked\n // here, before the original is read, so a non-integer never reaches BigInt().\n const requestedTotal =\n input.total === undefined\n ? undefined\n : assertArcaMinorUnits(input.total, \"total\");\n const { note, header } = prepareCreditNote(originals, input, now, kind);\n // The class comes from the original, so the item shape must match it.\n // A reviewed breakdown takes the same path invoices take.\n const lineSource: WsfeAmountsInput | undefined = input.amounts\n ? undefined\n : {\n voucherClass: note.voucherClass,\n items: input.items as NonNullable<IssueInput[\"items\"]>,\n total:\n input.total === undefined\n ? undefined\n : input.total - tributeTotal(input.taxes ?? []),\n };\n const { data: amountsData, amounts } =\n lineSource === undefined\n ? reviewedInvoiceAmounts(\n input.amounts as NonNullable<CreditNoteInput[\"amounts\"]>,\n input.taxes\n )\n : calculateWsfeAmounts(lineSource);\n // The ceiling is the sum of every original the note is associated to.\n const originalTotal = originals.reduce(\n (sum, original) =>\n sum +\n normalizeArcaAmountToMinorUnits(\n required(original.totalAmount, \"totalAmount\"),\n \"totalAmount\"\n ),\n 0n\n );\n const ceiling =\n originals.length === 1 ? \"the original\" : \"the sum of the originals\";\n if (\n kind === \"creditNote\" &&\n (requestedTotal ?? BigInt(amounts.sentTotal)) > originalTotal\n ) {\n invalid(\n `the note total is greater than ${ceiling}; the SDK does not track earlier notes against an original`\n );\n }\n const data: WsfeVoucherInput = { ...header, ...amountsData };\n applyIssuanceFields(data, {\n ...input,\n fce: undefined,\n optionalFields: undefined,\n });\n const total = Number(\n [\n data.netAmount,\n data.vatAmount,\n data.exemptAmount,\n data.nonTaxableAmount,\n data.taxAmount,\n ].reduce(\n (sum, amount) => sum + normalizeArcaAmountToMinorUnits(amount, \"amount\"),\n 0n\n )\n );\n const sentTotal =\n input.amounts && requestedTotal !== undefined\n ? Number(requestedTotal)\n : total;\n if (kind === \"creditNote\" && BigInt(sentTotal) > originalTotal) {\n invalid(`the note total is greater than ${ceiling}`);\n }\n data.totalAmount = minor(sentTotal, \"total\");\n amounts.computedTotal += total - amounts.sentTotal;\n amounts.sentTotal = sentTotal;\n normalizeWsfeVoucherInput(data);\n return {\n data,\n voucherClass: note.voucherClass,\n amounts,\n ...(lineSource === undefined ? {} : { lineSource }),\n };\n}\n\n/**\n * Shared evidence: everything except the amounts comes from the originals.\n * Each original derives a header of its own and they must come out identical,\n * because the note has one of each inherited field and several sources for it.\n * Only the associations accumulate.\n */\nfunction prepareCreditNote(\n originals: readonly WsfeVoucherInfo[],\n input: CreditNoteInput,\n now: Date,\n kind: \"creditNote\" | \"debitNote\"\n): { note: CreditNote; header: CreditNoteHeader } {\n const derived = originals.map((original) =>\n prepareOneCreditNote(original, input, now, kind)\n );\n const [first, ...rest] = derived;\n if (first === undefined) {\n invalid(\"for must name at least one original\");\n }\n for (const other of rest) {\n assertInheritedHeader(first.header, other.header);\n }\n return {\n note: first.note,\n header: {\n ...first.header,\n associatedVouchers: derived.flatMap(\n (one) => one.header.associatedVouchers ?? []\n ),\n },\n };\n}\n\n/**\n * Everything the note inherits must be the same for every original. A field\n * that differs has no single value on the note, so the note is not derivable\n * and the caller issues one note per group instead.\n */\nfunction assertInheritedHeader(\n first: CreditNoteHeader,\n other: CreditNoteHeader\n): void {\n for (const field of new Set([...Object.keys(first), ...Object.keys(other)])) {\n if (field === \"associatedVouchers\") {\n continue;\n }\n const left = first[field as keyof CreditNoteHeader];\n const right = other[field as keyof CreditNoteHeader];\n if (JSON.stringify(left) !== JSON.stringify(right)) {\n invalid(\n `the originals disagree on ${field}, which the note inherits from them`\n );\n }\n }\n}\n\n/**\n * The original's reported condition wins. ARCA omits it on vouchers authorized\n * before the field existed, and only then does the caller's `to.condition`\n * stand in for it.\n */\nfunction resolveReceiverCondition(\n original: WsfeVoucherInfo,\n input: CreditNoteInput\n): number {\n const supplied =\n input.to === undefined\n ? undefined\n : receiverConditionId(input.to.condition, \"to.condition\");\n const reported = original.receiverVatConditionId;\n if (reported === undefined) {\n if (supplied === undefined) {\n invalid(\n \"original is missing receiverVatConditionId; pass to.condition with the receiver's condition\"\n );\n }\n return supplied;\n }\n if (supplied !== undefined && supplied !== reported) {\n invalid(\n `to.condition (${supplied}) does not match the original's receiver condition (${reported})`\n );\n }\n return reported;\n}\n\nfunction prepareOneCreditNote(\n original: WsfeVoucherInfo,\n input: CreditNoteInput,\n now: Date,\n kind: \"creditNote\" | \"debitNote\"\n): { note: CreditNote; header: CreditNoteHeader } {\n assertOriginalExtensions(original);\n const family = voucherFamily(original.voucherType ?? 0);\n if (family.types[2] === original.voucherType) {\n invalid(\"original must be an invoice or debit note\");\n }\n const note = {\n voucherClass: family.voucherClass,\n voucherType: family.types[kind === \"creditNote\" ? 2 : 1] as number,\n };\n if (\n !(\n [\"A\", \"O\"].includes(original.result ?? \"\") &&\n original.cae?.trim() &&\n original.caeExpiry?.trim()\n )\n ) {\n invalid(\"original is not authorized\");\n }\n\n const voucherDate = normalizeWsfeDateInput(\n input.date ?? buenosAiresDate(now),\n \"date\"\n ) as WsfeDateInput;\n const originalDate = normalizeWsfeDateInput(\n required(original.voucherDate, \"voucherDate\") as WsfeDateInput,\n \"original.voucherDate\"\n ) as WsfeDateInput;\n if (\n originalDate > voucherDate &&\n originalDate.slice(0, 6) !== voucherDate.slice(0, 6)\n ) {\n invalid(\n \"original date is later than the note and outside its month (10210)\"\n );\n }\n const header: CreditNoteHeader = {\n salesPoint: input.salesPoint ?? required(original.salesPoint, \"salesPoint\"),\n voucherType: note.voucherType,\n concept: required(original.concept, \"concept\"),\n ...originalReceiverDocument(original),\n receiverVatConditionId: resolveReceiverCondition(original, input),\n currencyId: required(original.currencyId, \"currencyId\"),\n ...(original.sameCurrencyForeignCancellation === undefined\n ? {}\n : {\n sameCurrencyForeignCancellation:\n original.sameCurrencyForeignCancellation,\n }),\n ...(original.buyers ? { buyers: structuredClone(original.buyers) } : {}),\n ...(original.activities\n ? { activities: structuredClone(original.activities) }\n : {}),\n ...(input.optionalFields\n ? { optionalFields: structuredClone(input.optionalFields) }\n : {}),\n exchangeRate: required(original.exchangeRate, \"exchangeRate\"),\n voucherDate,\n associatedVouchers: [\n {\n type: required(original.voucherType, \"voucherType\"),\n salesPoint: required(original.salesPoint, \"salesPoint\"),\n number: original.voucherNumber,\n voucherDate: originalDate,\n },\n ],\n };\n applyFceFields(header, input.fce);\n copyServiceDates(original, header);\n return { note, header };\n}\n\nfunction copyServiceDates(original: WsfeVoucherInfo, header: CreditNoteHeader) {\n if (header.concept !== 2 && header.concept !== 3) {\n return;\n }\n header.serviceStartDate = required(\n original.serviceStartDate,\n \"serviceStartDate\"\n ) as WsfeDateInput;\n header.serviceEndDate = required(\n original.serviceEndDate,\n \"serviceEndDate\"\n ) as WsfeDateInput;\n const due = normalizeWsfeDateInput(\n required(original.paymentDueDate, \"paymentDueDate\") as WsfeDateInput,\n \"original.paymentDueDate\"\n ) as WsfeDateInput;\n header.paymentDueDate = due < header.voucherDate ? header.voucherDate : due;\n}\n\nconst CREDIT_NOTE_KEYS = [\n \"for\",\n \"salesPoint\",\n \"date\",\n \"to\",\n \"items\",\n \"total\",\n \"all\",\n \"taxes\",\n \"amounts\",\n \"optionalFields\",\n \"fce\",\n];\nconst TARGET_BOUNDS = [\n [\"salesPoint\", 99_999],\n [\"voucherType\", 999],\n [\"number\", 99_999_999],\n] as const;\n\n/** Only the condition: the receiver's document always comes from the original. */\nfunction assertNoteReceiver(to: CreditNoteInput[\"to\"]): void {\n if (to === undefined) {\n return;\n }\n assertIssueObject(to, \"to\");\n assertIssueKeys(to, [\"condition\"], \"to\", \"issueCreditNote()\");\n try {\n receiverConditionId(to.condition, \"to.condition\");\n } catch {\n invalid(\"to.condition must be a supported receiver condition\");\n }\n}\n\n/** Zero I/O: rejects an ambiguous mode and copies the lines the caller owns. */\nexport function assertCreditNoteInput(input: CreditNoteInput): CreditNoteInput {\n assertIssueObject(input, \"input\");\n validateIssuanceFields(input);\n if (\"associatedPeriod\" in input) {\n throw new ArcaInputError(\n \"issueCreditNote adjusts either the originals named in for or a period, never both; drop one of them.\",\n {\n code: \"ARCA_INPUT_RESERVED_FIELD\",\n field: \"associatedPeriod\",\n expected: \"an associated invoice through for\",\n }\n );\n }\n assertIssueKeys(input, CREDIT_NOTE_KEYS, \"input\", \"issueCreditNote()\");\n const target = assertCreditNoteTargets(input.for);\n if (input.salesPoint !== undefined) {\n assertCreditNoteBound(input.salesPoint, 99_999, \"salesPoint\");\n }\n const date =\n input.date === undefined\n ? undefined\n : (normalizeWsfeDateInput(input.date, \"date\") as WsfeDateInput);\n assertNoteReceiver(input.to);\n const common = {\n ...(input.fce === undefined ? {} : { fce: structuredClone(input.fce) }),\n ...(input.taxes === undefined\n ? {}\n : { taxes: structuredClone(input.taxes) }),\n ...(input.optionalFields === undefined\n ? {}\n : { optionalFields: structuredClone(input.optionalFields) }),\n for: target,\n ...(input.salesPoint === undefined ? {} : { salesPoint: input.salesPoint }),\n ...(date === undefined ? {} : { date }),\n ...(input.to === undefined\n ? {}\n : { to: { condition: input.to.condition } }),\n };\n if (input.items !== undefined && input.amounts !== undefined) {\n invalid(\"use items or amounts, never both\");\n }\n if (\n (input.items === undefined && input.amounts === undefined) ===\n (input.all === undefined)\n ) {\n throw new ArcaInputError(\n \"issueCreditNote needs exactly one mode: items or amounts for a partial note, or all: true for the whole original.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: input.items === undefined ? \"input.items\" : \"input.all\",\n expected: \"exactly one of items, amounts or all: true\",\n }\n );\n }\n if (input.all !== undefined) {\n assertFullMode(input);\n return { ...common, all: true };\n }\n if (input.amounts !== undefined) {\n return {\n ...common,\n amounts: structuredClone(input.amounts),\n ...(input.total === undefined ? {} : { total: input.total }),\n };\n }\n return {\n ...common,\n amounts: undefined,\n items: copyCreditNoteItems(input.items as NonNullable<IssueInput[\"items\"]>),\n ...(input.total === undefined ? {} : { total: input.total }),\n };\n}\n\n/** One object stays one object; a list stays a list, so the input hash does. */\nfunction assertCreditNoteTargets(\n value: CreditNoteInput[\"for\"]\n): VoucherCoordinates | VoucherCoordinates[] {\n if (Array.isArray(value)) {\n if (value.length === 0) {\n throw new ArcaInputError(\n \"issueCreditNote requires for to name at least one authorized original.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"input.for\",\n expected: \"a non-empty array of { salesPoint, voucherType, number }\",\n }\n );\n }\n const targets = value.map((target, index) =>\n assertCreditNoteTarget(target, `for[${index}]`)\n );\n const seen = new Set<string>();\n for (const [index, target] of targets.entries()) {\n const key = `${target.salesPoint}:${target.voucherType}:${target.number}`;\n if (seen.has(key)) {\n throw new ArcaInputError(\n \"issueCreditNote requires each original in for to be unique.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: `input.for[${index}]`,\n expected: \"unique voucher coordinates\",\n }\n );\n }\n seen.add(key);\n }\n return targets;\n }\n return assertCreditNoteTarget(value as VoucherCoordinates, \"for\");\n}\n\nfunction assertCreditNoteTarget(\n value: VoucherCoordinates,\n path: string\n): VoucherCoordinates {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new ArcaInputError(\n \"issueCreditNote requires for: the coordinates of the authorized invoice the note corrects.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: `input.${path}`,\n expected: \"{ salesPoint, voucherType, number }\",\n }\n );\n }\n assertIssueKeys(\n value,\n [\"salesPoint\", \"voucherType\", \"number\"],\n `input.${path}`,\n \"issueCreditNote()\"\n );\n for (const [field, max] of TARGET_BOUNDS) {\n assertCreditNoteBound(value[field], max, `${path}.${field}`);\n }\n if (\n ![1, 2, 6, 7, 11, 12, 51, 52, 201, 202, 206, 207, 211, 212].includes(\n value.voucherType\n )\n ) {\n throw new ArcaInputError(\n \"issueCreditNote requires an authorized invoice or debit note in a supported family in for.voucherType.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: `input.${path}.voucherType`,\n expected: \"1, 6 or 11\",\n }\n );\n }\n return {\n salesPoint: value.salesPoint,\n voucherType: value.voucherType,\n number: value.number,\n };\n}\n\n/** The originals a note input names, in the order the caller gave them. */\nexport function creditNoteTargets(\n input: CreditNoteInput\n): readonly VoucherCoordinates[] {\n return Array.isArray(input.for)\n ? input.for\n : [input.for as VoucherCoordinates];\n}\n\nfunction assertCreditNoteBound(value: number, max: number, path: string) {\n if (!Number.isSafeInteger(value) || value < 1 || value > max) {\n throw new ArcaInputError(\n `issueCreditNote requires input.${path} to be an integer from 1 through ${max}.`,\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: `input.${path}` }\n );\n }\n}\n\n// The caller keeps the array it passed; a later mutation must not reach ARCA.\nfunction copyCreditNoteItems<T extends readonly VatItem[] | readonly object[]>(\n items: T\n): T {\n if (!Array.isArray(items)) {\n throw new ArcaInputError(\n \"issueCreditNote requires items to be a non-empty array of items.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.items\",\n expected: \"a non-empty array of items\",\n }\n );\n }\n return items.map((item) =>\n item === null || typeof item !== \"object\" ? item : { ...item }\n ) as unknown as T;\n}\n\nfunction assertOriginalExtensions(original: WsfeVoucherInfo) {\n for (const [field, rawField] of [\n [\"taxes\", \"Tributos\"],\n [\"optionalFields\", \"Opcionales\"],\n [\"buyers\", \"Compradores\"],\n [\"activities\", \"Actividades\"],\n [\"associatedPeriod\", \"PeriodoAsoc\"],\n ] as const) {\n if (original.raw[rawField] && original[field] === undefined) {\n invalid(`original ${field} could not be decoded`);\n }\n }\n try {\n validateIssuanceFields({\n taxes: original.taxes?.map((t) => ({\n id: t.id,\n description: t.description,\n base: Number(\n normalizeArcaAmountToMinorUnits(t.baseAmount, \"taxes.base\")\n ),\n rate: t.rate,\n amount: Number(\n normalizeArcaAmountToMinorUnits(t.amount, \"taxes.amount\")\n ),\n })),\n optionalFields: original.optionalFields,\n buyers: original.buyers,\n activities: original.activities,\n });\n if (original.associatedPeriod) {\n normalizeWsfeDateInput(\n original.associatedPeriod.startDate,\n \"associatedPeriod.startDate\"\n );\n normalizeWsfeDateInput(\n original.associatedPeriod.endDate,\n \"associatedPeriod.endDate\"\n );\n }\n } catch {\n invalid(\"original extension fields are incomplete or malformed\");\n }\n}\n\nfunction assertFullMode(input: CreditNoteInput): void {\n if (input.all !== true) {\n throw new ArcaInputError(\n \"issueCreditNote accepts only all: true; pass items to credit chosen lines.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.all\",\n expected: \"the literal true\",\n }\n );\n }\n if (\n input.total !== undefined ||\n input.taxes !== undefined ||\n input.amounts !== undefined\n ) {\n throw new ArcaInputError(\n \"issueCreditNote takes total only with items; all: true credits the original's own total.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.total\",\n expected: \"no total when all is true\",\n }\n );\n }\n if (Array.isArray(input.for) && input.for.length > 1) {\n throw new ArcaInputError(\n \"issueCreditNote takes all: true against one original; a full note of several originals has no single total. Pass items or amounts instead.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.all\",\n expected: \"one original in for when all is true\",\n }\n );\n }\n}\n","import type { VoucherClass } from \"../constants\";\nimport {\n ArcaConfigurationError,\n ArcaInputError,\n ArcaServiceError,\n toArcaSafeErrorMetadata,\n} from \"../errors\";\nimport { toIsoDate } from \"../internal/dates\";\nimport {\n arcaMinorUnitsToNumber,\n normalizeArcaAmountToMinorUnits,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport type { ArcaEnvironment } from \"../internal/types\";\nimport {\n type ArcaAttemptRecord,\n type ArcaSequenceRecord,\n type ArcaSettledRecord,\n type ArcaStore,\n attemptKey,\n canonicalHash,\n sequenceKey,\n sequenceLockKey,\n settledKey,\n storeCall,\n} from \"../store/types\";\nimport type {\n ArcaAuthorizationOutcome,\n IssuanceService,\n} from \"./fiscal-evidence\";\nimport {\n type FAMILIES,\n normalizedFceAnnulment,\n validateFiscalHeader,\n voucherFamily,\n} from \"./issuance-fields\";\nimport {\n assertExportWindow,\n createExportIssuance,\n deriveExportInvoice,\n deriveExportNote,\n type ExportCreditNoteInput,\n type ExportDebitNoteInput,\n type ExportIssuance,\n type ExportIssueInput,\n type ExportIssueOutcome,\n type ExportPreview,\n type ExportVoucherSummary,\n type ExportVoucherType,\n exportPreview,\n exportSummary,\n isExportInput,\n isExportNoteInput,\n isExportVoucherType,\n} from \"./issuance-wsfex\";\nimport {\n assertWsmtxcaVoucherType,\n createWsmtxcaIssuanceService,\n type FiscalHeader as IssuanceHeader,\n matchWsmtxcaDetails,\n wsmtxcaRequest,\n} from \"./issuance-wsmtxca\";\nimport { arcaQrPayload, qrUrlForPayload } from \"./qr\";\nimport type {\n FiscalHeader,\n IssuedVoucher,\n IssueOptions,\n IssueOutcome,\n IssuePreview,\n IssueRequest,\n ServiceFor,\n} from \"./vouchers-types\";\nimport {\n normalizeWsfeDateInput,\n normalizeWsfeVoucherInput,\n type WsfeService,\n type WsfeVoucherInfo,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport { deriveWsmtxcaSettlement, type IssueAmounts } from \"./wsfe-amounts\";\nimport {\n assertCreditNoteInput,\n type CreditNoteInput,\n creditNoteTargets,\n deriveWsfeFullCreditNote,\n deriveWsfePartialCreditNote,\n} from \"./wsfe-credit-note\";\nimport {\n assertIssueKeys,\n assertIssueObject,\n assertVoucherDateWindow,\n buenosAiresDate,\n deriveWsfeInvoice,\n type IssueInput,\n issueDocumentNumber,\n issuerConditionName,\n} from \"./wsfe-derive\";\nimport {\n matchWsfeVoucherIdentity,\n normalizeLegacySummary,\n toVoucherSummary,\n type VoucherCoordinates,\n type VoucherSummary,\n} from \"./wsfe-identity\";\nimport type { WsfexService } from \"./wsfex\";\nimport type { WsmtxcaService } from \"./wsmtxca\";\n\nexport type PeriodNoteInput = IssueInput & {\n associatedPeriod: {\n from: import(\"./wsfe\").WsfeDateInput;\n to: import(\"./wsfe\").WsfeDateInput;\n };\n for?: never;\n};\nexport type DebitNoteInput =\n | (CreditNoteInput & { all?: never })\n | PeriodNoteInput;\nexport type NotePreview<S extends IssuanceService = \"wsfe\"> =\n IssuePreview<S> & {\n /** The originals consulted, in input order; absent for a period note. */\n originals?: readonly VoucherSummary[];\n };\n/** Every voucher type the WSFE and WSMTXCA facade issues, as literals. */\ntype DomesticVoucherType = {\n [F in keyof typeof FAMILIES]: (typeof FAMILIES)[F][keyof (typeof FAMILIES)[F]];\n}[keyof typeof FAMILIES][number];\ntype DomesticCoordinates = VoucherCoordinates & {\n voucherType: DomesticVoucherType;\n};\n/**\n * A note whose original is a literal domestic type, or a list of originals,\n * which are always domestic. Only a `voucherType` typed as plain `number` may\n * hold 19 to 21 at run time, so only that input gets the result union.\n */\ntype DomesticNote<T> = T & {\n for?: DomesticCoordinates | readonly VoucherCoordinates[];\n};\nexport type RecoveryOptions = Pick<\n IssueOptions,\n \"representedTaxId\" | \"forceRefresh\" | \"include\" | \"abortSignal\"\n>;\nexport type VouchersService = {\n /**\n * Consults one authorized voucher by its coordinates, the same shape a\n * credit note's `for` takes. Returns `null` when ARCA has no such voucher and\n * throws on any other provider error. Reads only: no store and no reserve.\n */\n lookup: {\n (\n voucher: VoucherCoordinates & { voucherType: ExportVoucherType },\n options?: PreviewOptions\n ): Promise<ExportVoucherSummary | null>;\n (\n voucher: DomesticCoordinates,\n options?: PreviewOptions\n ): Promise<VoucherSummary | null>;\n /**\n * A `voucherType` typed as plain `number` may hold 19 to 21 at run time,\n * so its answer may be an export summary: narrow on `voucherClass`.\n */\n (\n voucher: VoucherCoordinates,\n options?: PreviewOptions\n ): Promise<VoucherSummary | ExportVoucherSummary | null>;\n };\n /**\n * The number of the last voucher ARCA authorized for a sales point and\n * voucher type, on WSFE or WSMTXCA; `0` when none was ever authorized.\n */\n lastAuthorized(\n sequence: Omit<VoucherCoordinates, \"number\">,\n options?: PreviewOptions\n ): Promise<number>;\n /** Consults a durable reservation. Never allocates or authorizes a voucher. */\n recover<O extends RecoveryOptions = { include?: never }>(\n idempotencyKey: string,\n options?: O\n ): Promise<\n IssueOutcome<O & { service?: \"wsfe\" | \"wsmtxca\" }> | ExportIssueOutcome<O>\n >;\n /**\n * Issues a debit note against the same originals `issueCreditNote()` accepts,\n * or against a period with `associatedPeriod`. It has no `all: true` mode:\n * a debit note adds to the account, so its lines are always explicit.\n */\n issueDebitNote: {\n <O extends IssueOptions = { include?: never }>(\n input: ExportDebitNoteInput,\n options?: O\n ): Promise<ExportIssueOutcome<O>>;\n <O extends IssueOptions = { include?: never }>(\n input: DomesticNote<DebitNoteInput>,\n options?: O\n ): Promise<IssueOutcome<O>>;\n /**\n * A `for.voucherType` typed as plain `number` may hold 19 to 21 at run\n * time, so the result may be an export one: narrow with `\"service\" in outcome`.\n */\n <O extends IssueOptions = { include?: never }>(\n input: DebitNoteInput,\n options?: O\n ): Promise<IssueOutcome<O> | ExportIssueOutcome<O>>;\n };\n /**\n * Derives what issueCreditNote() would send. Unlike the zero-I/O preview(),\n * it consults each original once: reads only, no write and no number\n * reserved. A linked note returns those raw-free originals in `originals`. A\n * period note carries its own business input and needs no lookup at all.\n */\n previewCreditNote: {\n (\n input: ExportCreditNoteInput,\n options?: PreviewOptions\n ): Promise<ExportPreview>;\n <O extends PreviewOptions = { service?: never }>(\n input: DomesticNote<CreditNoteInput | PeriodNoteInput>,\n options?: O\n ): Promise<NotePreview<ServiceFor<O>>>;\n /**\n * A `for.voucherType` typed as plain `number` may hold 19 to 21 at run\n * time, so the preview may be an export one: narrow on `voucherClass`.\n */\n <O extends PreviewOptions = { service?: never }>(\n input: CreditNoteInput | PeriodNoteInput,\n options?: O\n ): Promise<NotePreview<ServiceFor<O>> | ExportPreview>;\n };\n /** Same contract as previewCreditNote(), for issueDebitNote() input. */\n previewDebitNote: {\n (\n input: ExportDebitNoteInput,\n options?: PreviewOptions\n ): Promise<ExportPreview>;\n <O extends PreviewOptions = { service?: never }>(\n input: DomesticNote<DebitNoteInput>,\n options?: O\n ): Promise<NotePreview<ServiceFor<O>>>;\n /**\n * A `for.voucherType` typed as plain `number` may hold 19 to 21 at run\n * time, so the preview may be an export one: narrow on `voucherClass`.\n */\n <O extends PreviewOptions = { service?: never }>(\n input: DebitNoteInput,\n options?: O\n ): Promise<NotePreview<ServiceFor<O>> | ExportPreview>;\n };\n /**\n * Issues a credit note against an authorized invoice or debit note of the\n * ordinary, retention-legend or FCE families, or against a period with\n * `associatedPeriod`. The note credits the chosen `items` or reviewed\n * `amounts`, or the whole original with `all: true`.\n *\n * For a linked note everything except the credited lines, the note's sales\n * point and its date comes from the originals: class, receiver, currency,\n * concept and service dates. `for` takes one original or a list of them,\n * and every one is associated to the note. ARCA has no cancellation; every\n * mode writes a real fiscal document.\n */\n issueCreditNote: {\n <O extends IssueOptions = { include?: never }>(\n input: ExportCreditNoteInput,\n options?: O\n ): Promise<ExportIssueOutcome<O>>;\n <O extends IssueOptions = { include?: never }>(\n input: DomesticNote<CreditNoteInput | PeriodNoteInput>,\n options?: O\n ): Promise<IssueOutcome<O>>;\n /**\n * A `for.voucherType` typed as plain `number` may hold 19 to 21 at run\n * time, so the result may be an export one: narrow with `\"service\" in outcome`.\n */\n <O extends IssueOptions = { include?: never }>(\n input: CreditNoteInput | PeriodNoteInput,\n options?: O\n ): Promise<IssueOutcome<O> | ExportIssueOutcome<O>>;\n };\n /**\n * Configure a store and pass idempotencyKey to recover retries after a crash.\n *\n * Without a key: one next-number read, one authorization and at most one lookup.\n * Keyed replay consults the reserved number; only not_found permits a write.\n * Local validation and next-number read failures throw before authorization.\n */\n issue: {\n <O extends IssueOptions = { include?: never }>(\n input: ExportIssueInput,\n options?: O\n ): Promise<ExportIssueOutcome<O>>;\n <O extends IssueOptions = { include?: never }>(\n input: IssueInput,\n options?: O\n ): Promise<IssueOutcome<O>>;\n };\n /**\n * Derives what issue() would send for the same input, with no I/O at all:\n * no store, no WSAA, no SOAP and no next-number read.\n *\n * It throws every input error issue() throws before its first call, so a\n * caller that previews and then issues sees no new local error.\n */\n preview: {\n (\n input: ExportIssueInput,\n options?: Pick<PreviewOptions, \"representedTaxId\">\n ): ExportPreview;\n <\n O extends Pick<PreviewOptions, \"representedTaxId\" | \"service\"> = {\n service?: never;\n },\n >(\n input: IssueInput,\n options?: O\n ): IssuePreview<ServiceFor<O>>;\n };\n};\n\nexport type PreviewOptions = {\n representedTaxId?: number | string;\n service?: \"wsfe\" | \"wsmtxca\";\n forceRefresh?: boolean;\n abortSignal?: AbortSignal;\n};\n\ntype IssueWsfeService = {\n getNextVoucherNumber: WsfeService[\"getNextVoucherNumber\"];\n issue: (\n input: Parameters<WsfeService[\"issue\"]>[0]\n ) => Promise<ArcaAuthorizationOutcome>;\n lookupVoucher: (\n input: Parameters<WsfeService[\"lookupVoucher\"]>[0]\n ) => Promise<\n import(\"./fiscal-evidence\").ArcaVoucherLookupResult<\n import(\"./wsfe\").WsfeVoucherInfo\n >\n >;\n};\ntype SelectService = (options: IssueOptions) => IssueWsfeService;\ntype StoreContext = {\n store?: ArcaStore;\n environment: ArcaEnvironment;\n taxId: string;\n};\ntype Settling = {\n /** The marker a fresh claim just wrote under the lock. */\n written?: ArcaSequenceRecord;\n /** ARCA rejected every earlier send of this key, if there was any. */\n everyRejected?: boolean;\n /**\n * The answer rests on this key never having written its number: without\n * withLock, a conflict found this way is not kept.\n */\n presumed?: boolean;\n /**\n * Another call of this key may be writing the same number: without\n * withLock, a 10016 that follows says nothing, so it is not marked.\n */\n racing?: boolean;\n};\ntype Prepared = Omit<ReturnType<typeof deriveWsfeInvoice>, \"data\"> & {\n data: IssuanceHeader;\n};\n\nexport function createVouchersService(\n wsfe: IssueWsfeService,\n context?: StoreContext,\n wsmtxca?: WsmtxcaService,\n wsfex?: WsfexService\n): VouchersService {\n const select = (options: IssueOptions = {}): IssueWsfeService => {\n validateOptions(options);\n if (options.service !== \"wsmtxca\") {\n return wsfe;\n }\n if (!wsmtxca) {\n throw new ArcaConfigurationError(\"WSMTXCA service is not configured\");\n }\n return createWsmtxcaIssuanceService(wsmtxca);\n };\n const exportIssuance =\n wsfex && context ? createExportIssuance(wsfex, context) : undefined;\n const exporting = (): ExportIssuance => {\n if (!exportIssuance) {\n throw new ArcaConfigurationError(\"WSFEX service is not configured\");\n }\n return exportIssuance;\n };\n const exportOptions = (options: IssueOptions | undefined) => {\n const cloned = cloneOptions(options ?? {});\n validateOptions(cloned);\n validateKeyStore(cloned, context);\n return cloned;\n };\n async function prepareExportNote(\n input: ExportCreditNoteInput | ExportDebitNoteInput,\n options: IssueOptions,\n kind: \"creditNote\" | \"debitNote\"\n ) {\n assertIssueObject(input, \"input\");\n assertIssueObject(input.for, \"for\");\n assertIssueKeys(input.for, [\"salesPoint\", \"voucherType\", \"number\"], \"for\");\n for (const [field, max] of [\n [\"salesPoint\", 99_998],\n [\"number\", 99_999_999],\n ] as const) {\n const value = input.for[field];\n if (!(Number.isSafeInteger(value) && value >= 1 && value <= max)) {\n throw new ArcaInputError(\n `for.${field} must be an integer from 1 through ${max}.`,\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: `for.${field}`,\n }\n );\n }\n }\n const original = await exporting().original(input.for, options);\n if (original === null) {\n throw new ArcaInputError(\"ARCA has no voucher at for.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"for\",\n expected: \"an authorized export voucher\",\n });\n }\n return { original, prepared: deriveExportNote(original, input, kind) };\n }\n async function issueExportNote(\n input: ExportCreditNoteInput | ExportDebitNoteInput,\n inputOptions: IssueOptions | undefined,\n kind: \"creditNote\" | \"debitNote\"\n ) {\n const options = exportOptions(inputOptions);\n // One copy taken before any await: the original, the note and the\n // reservation's hash all come from the same input.\n const snapshot = structuredClone(input);\n return await exporting().issue(\n async () => (await prepareExportNote(snapshot, options, kind)).prepared,\n kind,\n snapshot,\n options\n );\n }\n async function previewExportNote(\n input: ExportCreditNoteInput | ExportDebitNoteInput,\n inputOptions: PreviewOptions | undefined,\n kind: \"creditNote\" | \"debitNote\"\n ) {\n const options = cloneOptions(inputOptions ?? {});\n assertIssueObject(options, \"options\");\n // The options issuance accepts for an export note, and nothing more.\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"forceRefresh\", \"abortSignal\"],\n \"options\",\n kind === \"creditNote\" ? \"previewCreditNote()\" : \"previewDebitNote()\"\n );\n validateOptions(options);\n const { original, prepared } = await prepareExportNote(\n structuredClone(input),\n options,\n kind\n );\n assertExportWindow(prepared.data);\n return exportPreview(prepared, [exportSummary(original)]);\n }\n /**\n * Reads the reservation once: an export one settles through WSFEX, any other\n * goes on to the WSFE recovery with the record already in hand.\n */\n async function readReservation(\n key: string,\n inputOptions: RecoveryOptions | undefined\n ) {\n const store = context?.store;\n if (exportIssuance === undefined || store === undefined || !context) {\n return;\n }\n const options = cloneOptions(inputOptions ?? {});\n assertIssueObject(options, \"options\");\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"forceRefresh\", \"include\", \"abortSignal\"],\n \"options\"\n );\n validateOptions(options);\n validateKeyStore({ ...options, idempotencyKey: key }, context);\n const json = await storeCall(() =>\n store.get(attemptKey(context.environment, context.taxId, key))\n );\n return { json, options: options as IssueOptions };\n }\n // Each cast is checked against its own overloads; a wrong branch fails.\n const service: VouchersService = {\n lookup: (async (voucher: VoucherCoordinates, options?: PreviewOptions) => {\n if (!isExportVoucherType(voucher?.voucherType)) {\n return await lookupVoucher(select(options), voucher, options ?? {});\n }\n const checked = cloneOptions(options ?? {});\n assertLookup(voucher, checked);\n return await exporting().lookup(voucher, checked);\n }) as VouchersService[\"lookup\"],\n lastAuthorized: (async (\n sequence: Omit<VoucherCoordinates, \"number\">,\n options?: PreviewOptions\n ) => {\n if (!isExportVoucherType(sequence?.voucherType)) {\n return await lastAuthorizedNumber(\n select(options),\n sequence,\n options ?? {}\n );\n }\n const checked = cloneOptions(options ?? {});\n assertSequence(sequence, checked);\n return await exporting().lastAuthorized(sequence, checked);\n }) as VouchersService[\"lastAuthorized\"],\n recover: (async (key: string, options?: RecoveryOptions) => {\n const read = await readReservation(key, options);\n if (typeof read?.json === \"string\" && isExportRecord(read.json)) {\n return await exporting().recover(key, read.json, read.options);\n }\n return await recoverOperation(\n select,\n key,\n options === undefined ? {} : options,\n context,\n read?.json\n );\n }) as VouchersService[\"recover\"],\n issueDebitNote: (async (\n input: DebitNoteInput | ExportDebitNoteInput,\n options?: IssueOptions\n ) =>\n isExportNoteInput(input)\n ? issueExportNote(input, options, \"debitNote\")\n : issueCreditNote(\n select(options),\n input as DebitNoteInput,\n options ?? {},\n context,\n \"debitNote\",\n select\n )) as VouchersService[\"issueDebitNote\"],\n previewCreditNote: (async (\n input: CreditNoteInput | PeriodNoteInput | ExportCreditNoteInput,\n options?: PreviewOptions\n ) =>\n isExportNoteInput(input)\n ? previewExportNote(input, options, \"creditNote\")\n : previewNote(\n select(options),\n input as CreditNoteInput | PeriodNoteInput,\n options ?? {},\n context,\n \"creditNote\"\n )) as VouchersService[\"previewCreditNote\"],\n previewDebitNote: (async (\n input: DebitNoteInput | ExportDebitNoteInput,\n options?: PreviewOptions\n ) =>\n isExportNoteInput(input)\n ? previewExportNote(input, options, \"debitNote\")\n : previewNote(\n select(options),\n input as DebitNoteInput,\n options ?? {},\n context,\n \"debitNote\"\n )) as VouchersService[\"previewDebitNote\"],\n issueCreditNote: (async (\n input: CreditNoteInput | PeriodNoteInput | ExportCreditNoteInput,\n options?: IssueOptions\n ) =>\n isExportNoteInput(input)\n ? issueExportNote(input, options, \"creditNote\")\n : issueCreditNote(\n select(options),\n input as CreditNoteInput | PeriodNoteInput,\n options === undefined ? {} : options,\n context,\n \"creditNote\",\n select\n )) as VouchersService[\"issueCreditNote\"],\n issue: (async (\n input: IssueInput | ExportIssueInput,\n options?: IssueOptions\n ) => {\n if (isExportInput(input)) {\n const checked = exportOptions(options);\n const snapshot = structuredClone(input);\n return await exporting().issue(\n () => deriveExportInvoice(snapshot),\n \"issue\",\n snapshot,\n checked\n );\n }\n return await issueInvoice(\n select(options),\n input,\n options === undefined ? {} : options,\n context,\n select\n );\n }) as VouchersService[\"issue\"],\n preview: ((\n input: IssueInput | ExportIssueInput,\n options?: Pick<PreviewOptions, \"representedTaxId\" | \"service\">\n ) => {\n if (isExportInput(input)) {\n const checked = options ?? {};\n assertIssueObject(checked, \"options\");\n assertIssueKeys(checked, [\"representedTaxId\"], \"options\");\n validateOptions(checked);\n const prepared = deriveExportInvoice(input);\n assertExportWindow(prepared.data);\n return exportPreview(prepared);\n }\n return previewInvoice(input, options === undefined ? {} : options);\n }) as VouchersService[\"preview\"],\n };\n return service;\n}\n\nfunction previewInvoice(\n input: IssueInput,\n options: PreviewOptions\n): IssuePreview<IssuanceService> {\n assertIssueObject(options, \"options\");\n assertIssueKeys(options, [\"representedTaxId\", \"service\"], \"options\");\n validateOptions(options);\n if (options.representedTaxId !== undefined) {\n issueDocumentNumber(\n options.representedTaxId,\n \"options.representedTaxId\",\n 11,\n 11\n );\n }\n return toPreview(\n withinDateWindow(prepareInvoice(input, options), options),\n options\n );\n}\n/**\n * Checked where a new voucher would be sent, never on replay: a keyed retry\n * returns what ARCA authorized even after the window has moved on.\n */\nfunction withinDateWindow<P extends Prepared>(\n prepared: P,\n options: IssueOptions\n): P {\n assertVoucherDateWindow(\n prepared.data,\n options.service ?? \"wsfe\",\n buenosAiresDate(new Date())\n );\n return prepared;\n}\nfunction prepareInvoice(input: IssueInput, options: IssueOptions): Prepared {\n const prepared: Prepared = deriveWsfeInvoice(input);\n attachLines(prepared, options);\n validatePrepared(prepared, options);\n return prepared;\n}\n/**\n * WSMTXCA sends the lines the items describe. WSFE ignores them, so nothing is\n * derived for it and the reservation stays a version-1 record.\n */\nfunction attachLines(prepared: Prepared, options: IssueOptions): void {\n if (options.service !== \"wsmtxca\") {\n return;\n }\n assertWsmtxcaVoucherType(prepared.data.voucherType);\n if (prepared.lineSource === undefined) {\n throw new ArcaInputError(\n \"WSMTXCA needs items with line detail; a reviewed amounts breakdown has no lines.\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"amounts\" }\n );\n }\n const settlement = deriveWsmtxcaSettlement(\n prepared.lineSource,\n prepared.amounts.vatAdjustment\n );\n prepared.data.lines = settlement.lines;\n prepared.data.vatRates = prepared.data.vatRates?.map((rate) => ({\n ...rate,\n amount: arcaMinorUnitsToNumber(\n BigInt(settlement.vatByCondition.get(rate.id) ?? 0),\n \"vatAmount\"\n ),\n }));\n}\nfunction validatePrepared(prepared: Prepared, options: IssueOptions): void {\n validateFiscalHeader(prepared.data);\n if (options.service === \"wsmtxca\") {\n wsmtxcaRequest(prepared.data);\n }\n}\nfunction toPreview(\n prepared: Prepared,\n options: IssueOptions\n): IssuePreview<IssuanceService> {\n const { data, voucherClass, amounts } = prepared;\n return {\n voucherClass,\n voucherType: data.voucherType,\n date: toIsoDate(data.voucherDate) ?? data.voucherDate,\n header: fiscalHeader(data),\n amounts,\n request: options.service === \"wsmtxca\" ? wsmtxcaRequest(data) : data,\n ...(options.service === \"wsmtxca\" ? { service: \"wsmtxca\" as const } : {}),\n };\n}\n\nasync function issueInvoice(\n wsfe: IssueWsfeService,\n input: IssueInput,\n inputOptions: IssueOptions,\n context?: StoreContext,\n select?: SelectService\n): Promise<IssueOutcome<IssueOptions>> {\n const options = cloneOptions(inputOptions);\n validateOptions(options);\n validateKeyStore(options, context);\n // One copy taken before any await: the invoice and the reservation's hash\n // both come from the same input.\n const snapshot = structuredClone(input);\n return await runOperation(\n wsfe,\n \"issue\",\n snapshot,\n async () => prepareInvoice(snapshot, options),\n options,\n context,\n select\n );\n}\n\n/** Hashes `issuer: 1` and `issuer: \"responsable_inscripto\"` alike. */\nfunction withIssuerName(input: unknown): unknown {\n if (input === null || typeof input !== \"object\" || !(\"issuer\" in input)) {\n return input;\n }\n const name = issuerConditionName(input.issuer);\n return name === undefined ? input : { ...input, issuer: name };\n}\n\n/**\n * `prepare` derives the voucher and runs only when this key has no\n * reservation: a replay resends what was stored, whatever today's date.\n */\nasync function runOperation(\n wsfe: IssueWsfeService,\n operation: ArcaAttemptRecord[\"operation\"],\n input: unknown,\n prepare: () => Promise<Prepared>,\n options: IssueOptions,\n context?: StoreContext,\n select?: SelectService\n): Promise<IssueOutcome<IssueOptions>> {\n const issuer = issuerTaxId(options, context);\n if (options.idempotencyKey === undefined || !context?.store) {\n return runAuthorization(\n wsfe,\n withinDateWindow(await prepare(), options),\n options,\n issuer\n );\n }\n const store: ArcaStore = context.store;\n const { environment, taxId } = context;\n const idempotencyKey = options.idempotencyKey;\n const key = attemptKey(environment, taxId, idempotencyKey);\n const representedTaxId =\n options.representedTaxId === undefined\n ? undefined\n : String(options.representedTaxId);\n const inputHash = canonicalHash({\n input: withIssuerName(input),\n representedTaxId,\n ...(options.service === \"wsmtxca\" ? { service: \"wsmtxca\" } : {}),\n ...(options.number === undefined ? {} : { number: options.number }),\n });\n const settled = settledKey(environment, taxId, idempotencyKey);\n const existing = await storeCall(() => store.get(key));\n if (existing !== null) {\n return await replay(existing);\n }\n const prepared = withinDateWindow(await prepare(), options);\n // The sequence belongs to the taxpayer whose numbering ARCA advances.\n const sequence = sequenceOf(environment, taxId, {\n representedTaxId,\n salesPoint: prepared.data.salesPoint,\n voucherType: prepared.data.voucherType,\n });\n if (!store.withLock) {\n return await claim();\n }\n // Serialize the claim across every process that shares this store: read the\n // next number, reserve it, submit and resolve while holding the lease.\n return await store.withLock(\n sequence.lock,\n async () => {\n // A call with this same key may have claimed while this one waited for\n // the lease. Its reservation is the one to consult, never to supersede.\n const prior = await storeCall(() => store.get(key));\n if (prior !== null) {\n return await replay(prior, true);\n }\n const barrier = await runSequenceBarrier({\n store,\n environment,\n taxId,\n sequence: sequence.marker,\n sequenceTaxId: sequence.taxId,\n select: select ?? (() => wsfe),\n options,\n supersededBy: idempotencyKey,\n readNext: () =>\n nextNumber(wsfe, prepared.data, { ...options, number: undefined }),\n });\n return \"blocked\" in barrier\n ? {\n ...barrier.blocked,\n ...requestEvidence(prepared.data, undefined, options),\n }\n : await claim(barrier.reserved);\n },\n // The deadline also bounds the wait: giving up there reserved nothing.\n { signal: options.abortSignal }\n );\n\n /**\n * A WSMTXCA or detailed reservation is a v2 record: 0.10 accepts any v1\n * record and would replay it through WSFE, so it must not read this one.\n */\n function reservation(number: number): ArcaAttemptRecord {\n const service = options.service ?? \"wsfe\";\n const versioned =\n service === \"wsmtxca\" || prepared.data.lines !== undefined;\n return {\n v: versioned ? 2 : 1,\n operation,\n ...(versioned ? { service } : {}),\n representedTaxId,\n inputHash,\n number,\n salesPoint: prepared.data.salesPoint,\n voucherType: prepared.data.voucherType,\n sent: prepared.data,\n createdAt: new Date().toISOString(),\n };\n }\n\n async function claim(reserved?: number) {\n const coordinated = store.withLock !== undefined;\n const number =\n options.number ??\n reserved ??\n (await nextNumber(wsfe, prepared.data, options));\n const record = reservation(number);\n const claimed: ArcaSequenceRecord = {\n v: 1,\n key: idempotencyKey,\n issuerTaxId: taxId,\n number,\n claimedAt: new Date().toISOString(),\n };\n if (coordinated) {\n // The marker goes first. A reservation the barrier cannot see is a\n // number the next claim takes, and recovering it would find that\n // stranger and match it by fiscal fields. A marker whose reservation\n // never followed is harmless: that key never submitted, so the barrier\n // hands the number over.\n await storeCall(() =>\n store.set(sequence.marker, JSON.stringify(claimed))\n );\n }\n if (await storeCall(() => store.add(key, JSON.stringify(record)))) {\n return await settle(\n record,\n runAuthorization(wsfe, prepared, options, issuer, number, {\n strangerAtNumber: true,\n }),\n // Without the lock, a retry of this key may write the number while\n // this claim is still in flight: its 10016 is not marked.\n { written: claimed, everyRejected: true, racing: !coordinated }\n );\n }\n const winner = await storeCall(() => store.get(key));\n if (winner === null) {\n throw new ArcaConfigurationError(\n \"ARCA reservation disappeared after atomic creation lost.\"\n );\n }\n // Already inside the sequence lock: the winner's replay must not retake it.\n return await replay(winner, true);\n }\n\n async function replay(json: string, locked = false) {\n const stored = readRecord(json);\n if (\n (stored.service ?? \"wsfe\") !== (options.service ?? \"wsfe\") ||\n stored.operation !== operation ||\n stored.inputHash !== inputHash ||\n stored.representedTaxId !== representedTaxId\n ) {\n throw new ArcaInputError(\n \"The idempotency key was already used with different input or operation.\",\n {\n code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\",\n field: \"options.idempotencyKey\",\n }\n );\n }\n return await consultKey(\n { store, environment, taxId, idempotencyKey },\n stored,\n locked,\n select ?? (() => wsfe),\n options,\n resend\n );\n }\n\n /**\n * Sends the reserved number again. A resend after a rejection skips the\n * replay lookup, which just ran, and treats a voucher that appears meanwhile\n * as a stranger's. Any other retry follows a send that got no answer and\n * may still land.\n */\n async function resend(current: ArcaAttemptRecord) {\n const rejected = current.rejectedAt !== undefined;\n if (rejected) {\n const held = await clearRejection(current);\n if (held !== undefined) {\n return held;\n }\n }\n return await settle(\n current,\n runAuthorization(\n wsfe,\n preparedFromRecord(current),\n options,\n issuer,\n current.number,\n { lookupFirst: !rejected, strangerAtNumber: rejected }\n ),\n { everyRejected: rejected, presumed: rejected, racing: rejected }\n );\n }\n /**\n * Every conflict becomes durable before it reaches the caller, and every\n * answer from ARCA is kept. A rejection is marked on the reservation before\n * the sequence marker resolves, so a claim that stops in between leaves the\n * barrier a rejection to find. The marker resolves only while it still\n * names this claim. A fresh claim passes the marker it just wrote under the\n * lock; a retry reads it again.\n */\n async function settle(\n record: ArcaAttemptRecord,\n running: Promise<IssueOutcome<IssueOptions>>,\n {\n written,\n everyRejected = false,\n presumed = false,\n racing = false,\n }: Settling = {}\n ) {\n // Without the lock, a call that presumes this key never wrote its number\n // may race another call of this key that just wrote it. Its answer stands,\n // but a conflict it found is not kept: a later call checks the number again.\n const uncoordinated = !store.withLock;\n const outcome = await recordConflict(\n store,\n settled,\n await running,\n !(presumed && uncoordinated)\n );\n const marks =\n outcome.kind === \"rejected\" &&\n everyRejected &&\n !(\n uncoordinated &&\n racing &&\n mayHoldNumber(outcome.issues, record.service)\n );\n if (marks) {\n const rejected = { ...record, rejectedAt: new Date().toISOString() };\n await storeCall(() => store.set(key, JSON.stringify(rejected)));\n }\n // A rejection left unmarked may follow a send that still lands, so the\n // marker stays open and the barrier consults this key before the number\n // moves on.\n if (\n !store.withLock ||\n outcome.kind === \"indeterminate\" ||\n (outcome.kind === \"rejected\" && !marks)\n ) {\n return outcome;\n }\n const { marker } = sequenceOf(environment, taxId, record);\n const json = written ? null : await storeCall(() => store.get(marker));\n const claimed =\n written ?? (json === null ? null : readSequenceRecord(json));\n if (\n claimed !== null &&\n isOwnClaim(claimed) &&\n claimed.number === record.number &&\n claimed.resolvedAt === undefined\n ) {\n const resolved = { ...claimed, resolvedAt: new Date().toISOString() };\n await storeCall(() => store.set(marker, JSON.stringify(resolved)));\n }\n return outcome;\n }\n\n /**\n * Readies a rejected key to resend its number. ARCA rejected its last\n * write, so a voucher at the number is a stranger's. Only an empty number\n * is resent, as a claim of its own: the marker names this key and the mark\n * is cleared before the write leaves, since it may land. Returns the answer\n * when the number must not be resent.\n */\n async function clearRejection(\n record: ArcaAttemptRecord\n ): Promise<IssueOutcome<IssueOptions> | undefined> {\n const checked = await settle(\n record,\n consultReservation(select ?? (() => wsfe), record, options, taxId, true),\n { presumed: true }\n );\n if (\n checked.kind !== \"indeterminate\" ||\n checked.lookup.kind !== \"not_found\"\n ) {\n return checked;\n }\n const holder = await reclaim(record);\n if (holder !== undefined) {\n return withheld(\n record,\n { kind: \"blocked\", by: holder.key, byTaxId: holder.issuerTaxId },\n options\n );\n }\n const { rejectedAt: _, ...pending } = record;\n await storeCall(() => store.set(key, JSON.stringify(pending)));\n }\n\n /**\n * Takes the sequence marker back before a rejected key resends its number,\n * so a resend that gets no answer is one the barrier consults. Another\n * claim's unresolved write may still land on that number, even under the\n * same key from another issuer: that holder comes back and nothing is sent.\n */\n async function reclaim(record: ArcaAttemptRecord) {\n if (!store.withLock) {\n return;\n }\n const { marker } = sequenceOf(environment, taxId, record);\n const json = await storeCall(() => store.get(marker));\n const claimed = json === null ? null : readSequenceRecord(json);\n if (\n claimed !== null &&\n !isOwnClaim(claimed) &&\n claimed.resolvedAt === undefined\n ) {\n return { key: claimed.key, issuerTaxId: claimed.issuerTaxId ?? taxId };\n }\n const reopened: ArcaSequenceRecord = {\n v: 1,\n key: idempotencyKey,\n issuerTaxId: taxId,\n number: record.number,\n claimedAt: new Date().toISOString(),\n };\n await storeCall(() => store.set(marker, JSON.stringify(reopened)));\n }\n\n /** A marker names this claim only under this key and this issuer's CUIT. */\n function isOwnClaim(claimed: ArcaSequenceRecord) {\n return (\n claimed.key === idempotencyKey && (claimed.issuerTaxId ?? taxId) === taxId\n );\n }\n}\n\n/** The store keys of one issuer's idempotency key. */\ntype KeyScope = {\n store: ArcaStore;\n environment: ArcaEnvironment;\n taxId: string;\n idempotencyKey: string;\n};\n\n/**\n * The taxpayer whose numbering a reservation advances, with its sequence\n * marker and lock. Every key of the sequence comes from here.\n */\nfunction sequenceOf(\n environment: ArcaEnvironment,\n taxId: string,\n {\n representedTaxId,\n salesPoint,\n voucherType,\n }: Pick<ArcaAttemptRecord, \"representedTaxId\" | \"salesPoint\" | \"voucherType\">\n) {\n const owner = representedTaxId ?? taxId;\n return {\n taxId: owner,\n marker: sequenceKey(environment, owner, salesPoint, voucherType),\n lock: sequenceLockKey(environment, owner, salesPoint, voucherType),\n };\n}\n\n/**\n * Answers a stored reservation under its sequence lock, since a retry may\n * resend the reserved number and a barrier may supersede it. A reservation\n * read before the lock is read again inside it: another call with this key\n * may have cleared or rewritten the rejection meanwhile. A recorded outcome\n * answers first; `unrecorded` answers otherwise.\n */\nasync function consultKey(\n { store, environment, taxId, idempotencyKey }: KeyScope,\n stored: ArcaAttemptRecord,\n locked: boolean,\n select: SelectService,\n options: RecoveryOptions,\n unrecorded: (\n current: ArcaAttemptRecord\n ) => Promise<IssueOutcome<IssueOptions>>\n): Promise<IssueOutcome<IssueOptions>> {\n const consult = async (current: ArcaAttemptRecord) => {\n const recorded = await storeCall(() =>\n store.get(settledKey(environment, taxId, idempotencyKey))\n );\n if (recorded === null) {\n return await unrecorded(current);\n }\n return await settledOutcome(\n select,\n current,\n readSettledRecord(recorded),\n options,\n taxId,\n (owner, other) =>\n storeCall(() => store.get(settledKey(environment, owner, other)))\n );\n };\n if (locked || !store.withLock) {\n return await consult(stored);\n }\n return await store.withLock(\n sequenceOf(environment, taxId, stored).lock,\n async () => {\n const json = await storeCall(() =>\n store.get(attemptKey(environment, taxId, idempotencyKey))\n );\n return await consult(json === null ? stored : readRecord(json));\n },\n { signal: options.abortSignal }\n );\n}\n\n/**\n * Records a conflict once, so a retry answers from the store instead of\n * consulting a number a stranger already holds. Losing the atomic creation\n * means another call recorded the same conflict first.\n */\nasync function recordConflict(\n store: ArcaStore,\n key: string,\n outcome: IssueOutcome<IssueOptions>,\n durable = true\n): Promise<IssueOutcome<IssueOptions>> {\n if (outcome.kind !== \"conflict\" || !durable) {\n return outcome;\n }\n const record: ArcaSettledRecord = {\n v: 2,\n kind: \"conflict\",\n number: outcome.attempted.number,\n found: Object.fromEntries(\n Object.entries(outcome.found).filter(([field]) => field !== \"rawResponse\")\n ) as VoucherSummary,\n settledAt: new Date().toISOString(),\n };\n await storeCall(() => store.add(key, JSON.stringify(record)));\n return outcome;\n}\n\nfunction readSettledRecord(json: string): ArcaSettledRecord {\n try {\n const record = JSON.parse(json) as ArcaSettledRecord;\n if (\n (record?.v !== 1 && record?.v !== 2) ||\n !Number.isSafeInteger(record.number) ||\n (record.kind === \"conflict\"\n ? !record.found || typeof record.found !== \"object\"\n : record.kind !== \"superseded\" ||\n typeof record.by !== \"string\" ||\n (record.byTaxId !== undefined && typeof record.byTaxId !== \"string\"))\n ) {\n throw new Error(\"Invalid settled structure\");\n }\n if (record.kind === \"conflict\" && record.v === 1) {\n // Version 1 kept ARCA's units. The summary is normalized on read.\n return { ...record, v: 2, found: normalizeLegacySummary(record.found) };\n }\n return record;\n } catch (cause) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA settled record; preserve it for reconciliation.\",\n { cause }\n );\n }\n}\n\n/**\n * Answers a key whose outcome is already recorded. A conflict repeats with no\n * provider call. A superseded key consults its number once and never resends:\n * an empty number means this key will never write, and a voucher there\n * belongs to the key that took the sequence, unless that key, or one that took\n * it from it in turn, met a stranger at the number. Only then does the voucher\n * stay a conflict for a person to attribute.\n */\nasync function settledOutcome(\n select: SelectService,\n reservation: ArcaAttemptRecord,\n settled: ArcaSettledRecord,\n options: RecoveryOptions,\n taxId: string,\n settledFor: (taxId: string, key: string) => Promise<string | null>\n): Promise<IssueOutcome<IssueOptions>> {\n if (settled.kind === \"conflict\") {\n return settledConflict(settled, reservation, options);\n }\n const outcome = await consultReservation(\n select,\n reservation,\n options,\n taxId,\n true\n );\n const empty =\n outcome.kind === \"indeterminate\" && outcome.lookup.kind === \"not_found\";\n if (\n !empty &&\n (outcome.kind !== \"conflict\" ||\n (await successionDisputed(settled, taxId, settledFor)))\n ) {\n return outcome;\n }\n return withheld(\n reservation,\n { kind: \"superseded\", by: settled.by, byTaxId: settled.byTaxId ?? taxId },\n options,\n settled.number\n );\n}\n\n/**\n * The answer for a reservation this call must not write: another claim holds\n * its sequence, or its number went to another key.\n */\nfunction withheld(\n reservation: ArcaAttemptRecord,\n lookup: { kind: \"blocked\" | \"superseded\"; by: string; byTaxId: string },\n options: RecoveryOptions,\n number = reservation.number\n): IssueOutcome<IssueOptions> {\n return {\n kind: \"indeterminate\",\n attempted: {\n salesPoint: reservation.salesPoint,\n voucherType: reservation.voucherType,\n number,\n },\n attempt: replayEvidence(reservation.service),\n lookup,\n ...reservationEvidence(reservation, options),\n };\n}\n\n/** The request a stored reservation sent, when the caller asked for it. */\nfunction reservationEvidence(\n reservation: ArcaAttemptRecord,\n options: RecoveryOptions\n) {\n return requestEvidence(\n preparedFromRecord(reservation).data,\n reservation.number,\n { ...options, service: reservation.service ?? \"wsfe\" }\n );\n}\n\n/**\n * Follows the keys that took one number from each other. A recorded conflict\n * anywhere along that chain means a stranger reached the number; an\n * unrecorded end means the last key wrote it or still owns the question. Each\n * key is read under the issuer that claimed it. A chain too long to walk counts\n * as disputed.\n */\nasync function successionDisputed(\n superseded: Extract<ArcaSettledRecord, { kind: \"superseded\" }>,\n taxId: string,\n settledFor: (taxId: string, key: string) => Promise<string | null>\n): Promise<boolean> {\n let owner = superseded.byTaxId ?? taxId;\n let next = superseded.by;\n for (let hop = 0; hop < 16; hop += 1) {\n const json = await settledFor(owner, next);\n if (json === null) {\n return false;\n }\n const record = readSettledRecord(json);\n if (record.kind === \"conflict\") {\n return true;\n }\n owner = record.byTaxId ?? owner;\n next = record.by;\n }\n return true;\n}\n\nfunction settledConflict(\n settled: Extract<ArcaSettledRecord, { kind: \"conflict\" }>,\n reservation: ArcaAttemptRecord,\n options: RecoveryOptions\n): IssueOutcome<IssueOptions> {\n return {\n kind: \"conflict\",\n attempted: {\n salesPoint: reservation.salesPoint,\n voucherType: reservation.voucherType,\n number: settled.number,\n },\n attempt: replayEvidence(reservation.service),\n found: settled.found,\n reason:\n \"This key already recorded another voucher at the reserved number. Reconcile before issuing under a new key.\",\n ...reservationEvidence(reservation, options),\n };\n}\n\nfunction validateKeyStore(options: IssueOptions, context?: StoreContext) {\n if (options.idempotencyKey === undefined) {\n return;\n }\n if (\n typeof options.idempotencyKey !== \"string\" ||\n options.idempotencyKey.length < 1 ||\n options.idempotencyKey.length > 255\n ) {\n throw new ArcaInputError(\n \"idempotencyKey must contain 1 to 255 characters.\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"options.idempotencyKey\" }\n );\n }\n if (!context?.store) {\n throw new ArcaConfigurationError(\n 'idempotencyKey requires a store. Add import { createPostgresStore } from \"facturas\"; and store: createPostgresStore({ query }) to createArcaClient().'\n );\n }\n}\n\nfunction readRecord(json: string): ArcaAttemptRecord {\n if (isExportRecord(json)) {\n throw new ArcaInputError(\n \"The idempotency key was already used for an export voucher.\",\n {\n code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\",\n field: \"options.idempotencyKey\",\n }\n );\n }\n try {\n const record = JSON.parse(json) as ArcaAttemptRecord;\n if (\n !record ||\n (record.v !== 1 && record.v !== 2) ||\n (record.v === 2 && record.service === undefined) ||\n ![\"issue\", \"creditNote\", \"debitNote\"].includes(record.operation) ||\n typeof record.inputHash !== \"string\" ||\n !record.sent ||\n (record.rejectedAt !== undefined &&\n typeof record.rejectedAt !== \"string\") ||\n !Number.isSafeInteger(record.number) ||\n record.number < 1 ||\n record.number > 99_999_999 ||\n record.sent.salesPoint !== record.salesPoint ||\n record.sent.voucherType !== record.voucherType\n ) {\n throw new Error(\"Invalid reservation structure\");\n }\n normalizeWsfeVoucherInput(record.sent);\n if (\n record.service !== undefined &&\n record.service !== \"wsfe\" &&\n record.service !== \"wsmtxca\"\n ) {\n throw new Error(\"Invalid provider\");\n }\n if (record.service === \"wsmtxca\") {\n wsmtxcaRequest(record.sent, record.number);\n }\n return record;\n } catch (cause) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA reservation record; preserve it for reconciliation.\",\n { cause }\n );\n }\n}\n\n/** Export reservations live under the same key space; only WSFEX reads them. */\nfunction isExportRecord(json: string): boolean {\n try {\n return (JSON.parse(json) as { service?: unknown })?.service === \"wsfex\";\n } catch {\n return false;\n }\n}\n\nfunction preparedFromRecord(record: ArcaAttemptRecord): Prepared {\n const sentTotal = Number(\n normalizeArcaAmountToMinorUnits(record.sent.totalAmount, \"totalAmount\")\n );\n return {\n data: record.sent,\n voucherClass: voucherFamily(record.voucherType).voucherClass,\n amounts: { computedTotal: sentTotal, sentTotal, vatAdjustment: 0 },\n };\n}\n\nasync function nextNumber(\n wsfe: IssueWsfeService,\n data: WsfeVoucherInput,\n options: IssueOptions\n): Promise<number> {\n if (options.number !== undefined) {\n return options.number;\n }\n const number = await wsfe.getNextVoucherNumber({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n salesPoint: data.salesPoint,\n voucherType: data.voucherType,\n });\n if (!Number.isSafeInteger(number) || number < 1 || number > 99_999_999) {\n throw new ArcaServiceError(\n \"ARCA returned an invalid next voucher number.\",\n {\n service: options.service ?? \"wsfe\",\n operation:\n options.service === \"wsmtxca\"\n ? \"consultarUltimoComprobanteAutorizado\"\n : \"FECompUltimoAutorizado\",\n }\n );\n }\n return number;\n}\n\n/** How a write of a reserved number treats what it may find there. */\ntype Submission = {\n /** An earlier send of this key may have landed: consult before writing. */\n lookupFirst?: boolean;\n /**\n * This key never wrote the number: no send came before, or ARCA rejected\n * every one. A voucher found there after a rejection is a stranger's.\n */\n strangerAtNumber?: boolean;\n};\n\nasync function runAuthorization(\n wsfe: IssueWsfeService,\n { data, voucherClass, amounts }: Prepared,\n options: IssueOptions,\n taxId: string | undefined,\n reservedNumber?: number,\n { lookupFirst = false, strangerAtNumber = false }: Submission = {}\n): Promise<IssueOutcome<IssueOptions>> {\n const auth = {\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n };\n const includeRawResponse = options.include?.rawResponse === true;\n const number = reservedNumber ?? (await nextNumber(wsfe, data, options));\n const attempted = {\n salesPoint: data.salesPoint,\n voucherType: data.voucherType,\n number,\n };\n const includedRequest = requestEvidence(data, number, options);\n const voucher = (\n cae: string,\n caeExpiry: string,\n lookup?: VoucherSummary\n ): IssuedVoucher =>\n issuedVoucher(\n { attempted, voucherClass, data, amounts, taxId },\n cae,\n caeExpiry,\n lookup\n );\n const recovery = {\n wsfe,\n auth,\n data,\n attempted,\n includeRawResponse,\n includedRequest,\n voucher,\n service: options.service,\n };\n if (lookupFirst) {\n const attempt = replayEvidence(options.service);\n let lookup: Awaited<ReturnType<IssueWsfeService[\"lookupVoucher\"]>>;\n try {\n lookup = await wsfe.lookupVoucher({ ...auth, ...attempted });\n } catch (error) {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: options.abortSignal?.aborted\n ? { kind: \"aborted\" }\n : { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n ...includedRequest,\n };\n }\n if (lookup.kind === \"found\") {\n return recoverInvoice({ ...recovery, attempt, lookup });\n }\n }\n // The only authorization call, across every transport and recovery branch;\n // the one resubmission below is the sole exception and only follows a\n // rejected ticket, never an uncertain write.\n let authorization = await wsfe.issue({\n ...auth,\n data,\n voucherNumber: number,\n });\n if (\n authorization.kind === \"indeterminate\" &&\n authorization.reason === \"authentication_rejected\" &&\n auth.forceRefresh !== true\n ) {\n // The provider classifies a rejected ticket only when it returned no CAE,\n // no result and no number: the write never reached the fiscal logic, so\n // one resubmission with a fresh ticket cannot authorize twice.\n authorization = await wsfe.issue({\n ...auth,\n forceRefresh: true,\n data,\n voucherNumber: number,\n });\n }\n if (\n authorization.kind === \"authorized\" &&\n authorization.caeExpiry &&\n authorization.voucherNumber === number\n ) {\n return {\n kind: \"authorized\",\n recoveredByMatch: false,\n voucher: voucher(authorization.cae, authorization.caeExpiry),\n authorization: projectEvidence(authorization, includeRawResponse),\n ...includedRequest,\n };\n }\n if (authorization.kind === \"rejected\") {\n return await resolveRejection(\n authorization,\n recovery,\n options,\n includeRawResponse,\n strangerAtNumber\n );\n }\n // The provider outcome type permits an absent expiry. Keep that visible.\n const uncertain =\n authorization.kind === \"indeterminate\"\n ? authorization\n : {\n ...authorization,\n kind: \"indeterminate\" as const,\n reason:\n authorization.voucherNumber === number\n ? (\"incomplete_response\" as const)\n : (\"contradictory_response\" as const),\n };\n const attempt = projectEvidence(uncertain, includeRawResponse);\n return recoverInvoice({\n wsfe,\n service: options.service,\n auth,\n data,\n attempted,\n attempt,\n includeRawResponse,\n includedRequest,\n voucher,\n });\n}\n\n/**\n * A rejection with a key checks the reserved number once. On a reservation\n * this call created, or one whose last write ARCA rejected, any voucher there\n * is a stranger and the answer is a conflict; identity matching is left to a\n * true retry. A failed or empty lookup keeps the provider rejection as the\n * answer.\n */\nasync function resolveRejection(\n authorization: Extract<ArcaAuthorizationOutcome, { kind: \"rejected\" }>,\n recovery: Omit<RecoveryInput, \"attempt\">,\n options: IssueOptions,\n includeRawResponse: boolean,\n strangerAtNumber: boolean\n): Promise<IssueOutcome<IssueOptions>> {\n const issues = [...authorization.errors, ...authorization.observations];\n const consult =\n options.idempotencyKey !== undefined &&\n mayHoldNumber(issues, options.service);\n if (consult) {\n const recovered = await recoverInvoice({\n ...recovery,\n attempt: projectEvidence(\n {\n ...authorization,\n kind: \"indeterminate\",\n reason: \"contradictory_response\",\n },\n includeRawResponse\n ),\n strangerAtNumber,\n });\n if (recovered.kind === \"authorized\" || recovered.kind === \"conflict\") {\n return recovered;\n }\n }\n return {\n kind: \"rejected\",\n attempted: recovery.attempted,\n issues: issues.map(projectIssue),\n authorization: projectEvidence(authorization, includeRawResponse),\n ...recovery.includedRequest,\n };\n}\n\n/** A rejection that may mean the number is taken, so it is worth consulting. */\nfunction mayHoldNumber(\n issues: readonly { code?: string }[],\n service: IssuanceService = \"wsfe\"\n): boolean {\n return (\n service === \"wsmtxca\" || issues.some((issue) => issue.code === \"10016\")\n );\n}\n\ntype RecoveryInput = {\n wsfe: IssueWsfeService;\n lookup?: Awaited<ReturnType<IssueWsfeService[\"lookupVoucher\"]>>;\n auth: Pick<IssueOptions, \"representedTaxId\" | \"forceRefresh\" | \"abortSignal\">;\n data: IssuanceHeader;\n service?: \"wsfe\" | \"wsmtxca\";\n attempted: VoucherCoordinates;\n attempt: Omit<\n Extract<ArcaAuthorizationOutcome, { kind: \"indeterminate\" }>,\n \"raw\"\n > & { rawResponse?: Record<string, unknown> };\n includeRawResponse: boolean;\n includedRequest: { request?: IssueRequest<IssuanceService> };\n voucher: (\n cae: string,\n caeExpiry: string,\n lookup?: VoucherSummary\n ) => IssuedVoucher;\n /** This key never wrote the reserved number: any voucher on it is foreign. */\n strangerAtNumber?: boolean;\n};\nasync function recoverInvoice({\n wsfe,\n auth,\n data,\n attempted,\n attempt,\n includeRawResponse,\n includedRequest,\n voucher,\n lookup: suppliedLookup,\n service,\n strangerAtNumber = false,\n}: RecoveryInput): Promise<IssueOutcome<IssueOptions>> {\n if (suppliedLookup === undefined && auth.abortSignal?.aborted) {\n // The write may have landed; the reservation stays and recover() settles it.\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"aborted\" },\n ...includedRequest,\n };\n }\n let lookup: Awaited<ReturnType<IssueWsfeService[\"lookupVoucher\"]>>;\n try {\n lookup =\n suppliedLookup ?? (await wsfe.lookupVoucher({ ...auth, ...attempted }));\n } catch (error) {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: auth.abortSignal?.aborted\n ? { kind: \"aborted\" }\n : { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n ...includedRequest,\n };\n }\n const rawResponse = includeRawResponse ? { rawResponse: lookup.raw } : {};\n if (lookup.kind === \"not_found\") {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"not_found\", ...rawResponse },\n ...includedRequest,\n };\n }\n if (strangerAtNumber) {\n return {\n kind: \"conflict\",\n attempted,\n attempt,\n found: { ...toVoucherSummary(lookup.voucher), ...rawResponse },\n reason:\n \"This key never wrote the number it reserved, and another voucher occupies it\",\n ...includedRequest,\n };\n }\n const detailsMatch =\n service === \"wsmtxca\"\n ? matchWsmtxcaDetails(data, attempted.number, lookup.voucher.raw)\n : undefined;\n const matched =\n detailsMatch === undefined\n ? matchWsfeVoucherIdentity(data, attempted.number, lookup.voucher)\n : detailsMatch === \"match\" &&\n lookup.voucher.cae &&\n lookup.voucher.caeExpiry\n ? { matches: true as const }\n : {\n matches: false as const,\n evidence:\n detailsMatch === \"conflict\"\n ? (\"conflict\" as const)\n : (\"incomplete\" as const),\n reason:\n \"WSMTXCA consultation does not match the complete reserved request\",\n };\n if (!matched.matches) {\n if (matched.evidence === \"conflict\") {\n return {\n kind: \"conflict\",\n attempted,\n attempt,\n found: { ...toVoucherSummary(lookup.voucher), ...rawResponse },\n reason: `${matched.reason}. Configure a store and pass idempotencyKey for retries.`,\n ...includedRequest,\n };\n }\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: {\n kind: \"incomplete\",\n reason: matched.reason,\n ...rawResponse,\n },\n ...includedRequest,\n };\n }\n // The matcher requires both fields before declaring a complete match.\n const lookupSummary = toVoucherSummary(lookup.voucher);\n return {\n kind: \"authorized\",\n recoveredByMatch: true,\n voucher: voucher(\n lookup.voucher.cae as string,\n lookup.voucher.caeExpiry as string,\n lookupSummary\n ),\n attempt,\n lookup: { ...lookupSummary, ...rawResponse },\n ...includedRequest,\n };\n}\n\nfunction projectIssue(issue: ArcaAuthorizationOutcome[\"errors\"][number]) {\n return {\n service: issue.service,\n operation: issue.operation,\n source: issue.source,\n category: issue.category,\n message: issue.message,\n ...(issue.code === undefined ? {} : { code: issue.code }),\n ...(issue.resultLevel === undefined\n ? {}\n : { resultLevel: issue.resultLevel }),\n };\n}\nfunction projectEvidence<T extends ArcaAuthorizationOutcome>(\n evidence: T,\n includeRawResponse: boolean\n): Omit<T, \"raw\"> & { rawResponse?: Record<string, unknown> } {\n const base = {\n kind: evidence.kind,\n service: evidence.service,\n operation: evidence.operation,\n results: {\n ...(evidence.results.header === undefined\n ? {}\n : { header: evidence.results.header }),\n ...(evidence.results.detail === undefined\n ? {}\n : { detail: evidence.results.detail }),\n ...(evidence.results.operation === undefined\n ? {}\n : { operation: evidence.results.operation }),\n },\n errors: evidence.errors.map(projectIssue),\n observations: evidence.observations.map(projectIssue),\n ...(includeRawResponse && evidence.raw !== undefined\n ? { rawResponse: evidence.raw }\n : {}),\n };\n const projected: Record<string, unknown> = { ...base };\n for (const field of [\n \"result\",\n \"resultLevel\",\n \"cae\",\n \"caeExpiry\",\n \"voucherNumber\",\n \"reason\",\n ] as const) {\n if (field in evidence && evidence[field as keyof T] !== undefined) {\n projected[field] = evidence[field as keyof T];\n }\n }\n if (evidence.kind === \"indeterminate\" && evidence.authentication) {\n const { code, reason, providerCode } = evidence.authentication;\n projected.authentication = {\n code,\n reason,\n ...(providerCode === undefined ? {} : { providerCode }),\n };\n }\n return projected as Omit<T, \"raw\"> & {\n rawResponse?: Record<string, unknown>;\n };\n}\n\n/** An AbortSignal cannot be cloned, so the caller's deadline is carried over. */\nfunction cloneOptions<T extends IssueOptions>(options: T): T {\n assertIssueObject(options, \"options\");\n const { abortSignal, ...rest } = options;\n return {\n ...(structuredClone(rest) as T),\n ...(abortSignal === undefined ? {} : { abortSignal }),\n };\n}\n\nfunction validateOptions(options: IssueOptions) {\n assertIssueObject(options, \"options\");\n assertIssueKeys(\n options,\n [\n \"representedTaxId\",\n \"forceRefresh\",\n \"include\",\n \"idempotencyKey\",\n \"service\",\n \"number\",\n \"abortSignal\",\n ],\n \"options\"\n );\n if (\n options.abortSignal !== undefined &&\n (typeof options.abortSignal !== \"object\" ||\n options.abortSignal === null ||\n typeof options.abortSignal.aborted !== \"boolean\" ||\n typeof options.abortSignal.addEventListener !== \"function\")\n ) {\n throw new ArcaInputError(\"options.abortSignal must be an AbortSignal.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.abortSignal\",\n });\n }\n if (\n options.service !== undefined &&\n options.service !== \"wsfe\" &&\n options.service !== \"wsmtxca\"\n ) {\n throw new ArcaInputError(\"Unknown fiscal service\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.service\",\n });\n }\n if (\n options.number !== undefined &&\n (!Number.isSafeInteger(options.number) ||\n options.number < 1 ||\n options.number > 99_999_999)\n ) {\n throw new ArcaInputError(\"Invalid reserved number\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.number\",\n });\n }\n if (options.representedTaxId !== undefined) {\n issueDocumentNumber(\n options.representedTaxId,\n \"options.representedTaxId\",\n 11,\n 11\n );\n }\n if (\n options.forceRefresh !== undefined &&\n typeof options.forceRefresh !== \"boolean\"\n ) {\n throw new ArcaInputError(\"options.forceRefresh must be a boolean.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.forceRefresh\",\n });\n }\n if (options.include !== undefined) {\n assertIssueObject(options.include, \"options.include\");\n assertIssueKeys(\n options.include,\n [\"request\", \"rawResponse\"],\n \"options.include\"\n );\n for (const field of [\"request\", \"rawResponse\"] as const) {\n if (\n options.include[field] !== undefined &&\n typeof options.include[field] !== \"boolean\"\n ) {\n throw new ArcaInputError(\n `options.include.${field} must be a boolean.`,\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: `options.include.${field}`,\n }\n );\n }\n }\n }\n}\n\nfunction replayEvidence(\n service: \"wsfe\" | \"wsmtxca\" = \"wsfe\"\n): RecoveryInput[\"attempt\"] {\n return {\n kind: \"indeterminate\",\n service,\n operation: service === \"wsfe\" ? \"FECAESolicitar\" : \"autorizarComprobante\",\n reason: \"incomplete_response\",\n results: {},\n errors: [],\n observations: [],\n };\n}\n\nasync function issueCreditNote(\n wsfe: IssueWsfeService,\n input: CreditNoteInput | PeriodNoteInput,\n inputOptions: IssueOptions,\n context?: StoreContext,\n kind: \"creditNote\" | \"debitNote\" = \"creditNote\",\n select?: SelectService\n): Promise<IssueOutcome<IssueOptions>> {\n const options = cloneOptions(inputOptions);\n validateOptions(options);\n validateKeyStore(options, context);\n // Copy before the first await: caller mutation must not change the reservation.\n assertIssueObject(input, \"input\");\n const note =\n \"associatedPeriod\" in input && !(\"for\" in input)\n ? structuredClone(input)\n : assertCreditNoteInput(input as CreditNoteInput);\n if (kind === \"debitNote\" && \"all\" in note && note.all) {\n throw new ArcaInputError(\"Debit notes require explicit items\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"items\",\n });\n }\n return await runOperation(\n wsfe,\n kind,\n note,\n () => prepareNote(wsfe, note, options, context, kind),\n options,\n context,\n select\n );\n}\nasync function previewNote(\n wsfe: IssueWsfeService,\n input: CreditNoteInput | PeriodNoteInput,\n inputOptions: PreviewOptions,\n context: StoreContext | undefined,\n kind: \"creditNote\" | \"debitNote\"\n): Promise<NotePreview<IssuanceService>> {\n const options = cloneOptions(inputOptions);\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"service\", \"forceRefresh\", \"abortSignal\"],\n \"options\"\n );\n const prepared = withinDateWindow(\n await prepareNote(wsfe, input, options, context, kind),\n options\n );\n return {\n ...toPreview(prepared, options),\n ...(prepared.originals === undefined\n ? {}\n : { originals: prepared.originals }),\n };\n}\n\nasync function prepareNote(\n wsfe: IssueWsfeService,\n input: CreditNoteInput | PeriodNoteInput,\n options: IssueOptions,\n context: StoreContext | undefined,\n kind: \"creditNote\" | \"debitNote\"\n): Promise<Prepared & { originals?: readonly VoucherSummary[] }> {\n validateOptions(options);\n assertIssueObject(input, \"input\");\n if (\"associatedPeriod\" in input && !(\"for\" in input)) {\n return preparePeriodNote(input, options, kind);\n }\n const note = assertCreditNoteInput(input as CreditNoteInput);\n if (kind === \"debitNote\" && note.all) {\n throw new ArcaInputError(\"Debit notes require explicit items\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n });\n }\n const targets = creditNoteTargets(note);\n validateFceAssociations(note, targets, options.service ?? \"wsfe\");\n validateNoteService(targets, options);\n const originals: WsfeVoucherInfo[] = [];\n for (const target of targets) {\n originals.push(await lookupOriginal(wsfe, target, options));\n }\n const [firstOriginal] = originals;\n const prepared: Prepared =\n note.all === true\n ? deriveWsfeFullCreditNote(firstOriginal as WsfeVoucherInfo, note)\n : deriveWsfePartialCreditNote(originals, note, new Date(), kind);\n if (note.all === true) {\n // A full note mirrors the original, lines included, as ARCA returned them.\n const mirrored = (firstOriginal as { lines?: IssuanceHeader[\"lines\"] })\n .lines;\n if (mirrored !== undefined) {\n prepared.data.authorizedLines = structuredClone(mirrored);\n }\n } else {\n attachLines(prepared, options);\n }\n if (voucherFamily(prepared.data.voucherType).family === \"fce\") {\n const taxId = options.representedTaxId ?? context?.taxId;\n if (!taxId) {\n throw new ArcaInputError(\"FCE association requires the issuer tax ID\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"representedTaxId\",\n });\n }\n for (const associated of prepared.data.associatedVouchers ?? []) {\n associated.taxId = String(taxId);\n }\n }\n validatePrepared(prepared, options);\n return { ...prepared, originals: originals.map(toVoucherSummary) };\n}\n\n/** A note has its original's class, so refuse class C before any lookup. */\nfunction validateNoteService(\n targets: readonly VoucherCoordinates[],\n options: IssueOptions\n): void {\n if (options.service !== \"wsmtxca\") {\n return;\n }\n for (const target of targets) {\n assertWsmtxcaVoucherType(target.voucherType);\n }\n}\n\n/** Provider rules differ for FCE notes; ordinary multi-original notes remain valid. */\nfunction validateFceAssociations(\n note: CreditNoteInput,\n targets: readonly VoucherCoordinates[],\n service: IssuanceService\n): void {\n const fceTargets = targets.filter(\n (target) => voucherFamily(target.voucherType).family === \"fce\"\n );\n if (fceTargets.length === 0) {\n return;\n }\n const nonAnnulment = normalizedFceAnnulment(note) === false;\n if ((service === \"wsmtxca\" || nonAnnulment) && targets.length !== 1) {\n throw new ArcaInputError(\n service === \"wsmtxca\"\n ? \"WSMTXCA FCE notes require exactly one associated original.\"\n : \"Non-annulment FCE notes require exactly one associated invoice.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.for\",\n expected: \"one FCE original\",\n }\n );\n }\n const [target] = targets;\n if (\n nonAnnulment &&\n target !== undefined &&\n voucherFamily(target.voucherType).types[0] !== target.voucherType\n ) {\n throw new ArcaInputError(\n \"Non-annulment FCE notes must be associated to an FCE invoice.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.for.voucherType\",\n expected: \"an FCE invoice type\",\n }\n );\n }\n}\n\nconst SEQUENCE_BOUNDS = [\n [\"salesPoint\", 99_999],\n [\"voucherType\", 999],\n] as const;\nconst LOOKUP_BOUNDS = [...SEQUENCE_BOUNDS, [\"number\", 99_999_999]] as const;\n\nfunction assertBounds<K extends string>(\n value: Record<K, number>,\n bounds: readonly (readonly [K, number])[],\n field: string,\n method: string\n): void {\n for (const [key, max] of bounds) {\n if (\n !Number.isSafeInteger(value[key]) ||\n value[key] < 1 ||\n value[key] > max\n ) {\n throw new ArcaInputError(\n `${method} requires ${field}.${key} to be an integer from 1 through ${max}.`,\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: `${field}.${key}` }\n );\n }\n }\n}\n\nfunction assertLookup(voucher: VoucherCoordinates, options: PreviewOptions) {\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"service\", \"forceRefresh\", \"abortSignal\"],\n \"options\",\n \"lookup()\"\n );\n assertIssueObject(voucher, \"voucher\");\n assertIssueKeys(\n voucher,\n [\"salesPoint\", \"voucherType\", \"number\"],\n \"voucher\",\n \"lookup()\"\n );\n assertBounds(voucher, LOOKUP_BOUNDS, \"voucher\", \"lookup()\");\n}\n\nfunction assertSequence(\n sequence: Omit<VoucherCoordinates, \"number\">,\n options: PreviewOptions\n) {\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"service\", \"forceRefresh\", \"abortSignal\"],\n \"options\",\n \"lastAuthorized()\"\n );\n assertIssueObject(sequence, \"sequence\");\n assertIssueKeys(\n sequence,\n [\"salesPoint\", \"voucherType\"],\n \"sequence\",\n \"lastAuthorized()\"\n );\n assertBounds(sequence, SEQUENCE_BOUNDS, \"sequence\", \"lastAuthorized()\");\n}\n\nasync function lookupVoucher(\n wsfe: IssueWsfeService,\n voucher: VoucherCoordinates,\n inputOptions: PreviewOptions\n): Promise<VoucherSummary | null> {\n const options = cloneOptions(inputOptions);\n assertLookup(voucher, options);\n const found = await wsfe.lookupVoucher({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n salesPoint: voucher.salesPoint,\n voucherType: voucher.voucherType,\n number: voucher.number,\n });\n if (found.kind === \"not_found\") {\n return null;\n }\n if (\n found.voucher.salesPoint !== voucher.salesPoint ||\n found.voucher.voucherType !== voucher.voucherType ||\n found.voucher.voucherNumber !== voucher.number\n ) {\n throw new ArcaServiceError(\n \"ARCA returned a voucher with other coordinates than the one requested\",\n { service: found.service, operation: found.operation }\n );\n }\n return toVoucherSummary(found.voucher);\n}\n\nasync function lastAuthorizedNumber(\n wsfe: IssueWsfeService,\n sequence: Omit<VoucherCoordinates, \"number\">,\n inputOptions: PreviewOptions\n): Promise<number> {\n const options = cloneOptions(inputOptions);\n assertSequence(sequence, options);\n // WSMTXCA's adapter answers \"next\" from its \"last\", so one subtraction serves both.\n const next = await wsfe.getNextVoucherNumber({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n salesPoint: sequence.salesPoint,\n voucherType: sequence.voucherType,\n });\n return next - 1;\n}\n\n/** One read of one original, checked against the coordinates that asked for it. */\nasync function lookupOriginal(\n wsfe: IssueWsfeService,\n target: VoucherCoordinates,\n options: IssueOptions\n): Promise<WsfeVoucherInfo> {\n const original = await wsfe.lookupVoucher({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n ...target,\n });\n if (original.kind !== \"found\") {\n throw new ArcaInputError(\n \"issueCreditNote failed: original voucher not found\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"input.for\" }\n );\n }\n if (\n original.voucher.salesPoint !== target.salesPoint ||\n original.voucher.voucherType !== target.voucherType ||\n original.voucher.voucherNumber !== target.number\n ) {\n throw new ArcaInputError(\n \"Original lookup coordinates do not match input.for\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"input.for\" }\n );\n }\n return original.voucher;\n}\n\nfunction preparePeriodNote(\n input: PeriodNoteInput,\n options: IssueOptions,\n kind: \"creditNote\" | \"debitNote\"\n): Prepared {\n const { associatedPeriod, ...invoice } = input;\n assertIssueObject(associatedPeriod, \"associatedPeriod\");\n assertIssueKeys(associatedPeriod, [\"from\", \"to\"], \"associatedPeriod\");\n if (\n normalizeWsfeDateInput(associatedPeriod.from, \"associatedPeriod.from\") >\n normalizeWsfeDateInput(associatedPeriod.to, \"associatedPeriod.to\")\n ) {\n throw new ArcaInputError(\"Associated period starts after its end\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"associatedPeriod\",\n });\n }\n const prepared = prepareInvoice(invoice, options);\n const family = voucherFamily(prepared.data.voucherType);\n if (family.family === \"fce\") {\n throw new ArcaInputError(\"FCE notes require an associated invoice\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"associatedPeriod\",\n });\n }\n prepared.data.voucherType = family.types[\n kind === \"creditNote\" ? 2 : 1\n ] as number;\n prepared.data.associatedPeriod = {\n startDate: associatedPeriod.from,\n endDate: associatedPeriod.to,\n };\n normalizeWsfeVoucherInput(prepared.data);\n validatePrepared(prepared, options);\n return prepared;\n}\n\nfunction requestEvidence(\n data: IssuanceHeader,\n number: number | undefined,\n options: IssueOptions\n): { request?: IssueRequest<IssuanceService> } {\n return options.include?.request === true\n ? {\n request:\n options.service === \"wsmtxca\" ? wsmtxcaRequest(data, number) : data,\n }\n : {};\n}\n\nasync function recoverOperation(\n select: (options: IssueOptions) => IssueWsfeService,\n key: string,\n inputOptions: RecoveryOptions,\n context?: StoreContext,\n /** The reservation recover() already read; `undefined` reads it here. */\n read?: string | null\n): Promise<IssueOutcome<IssueOptions>> {\n const options = cloneOptions(inputOptions);\n assertIssueObject(options, \"options\");\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"forceRefresh\", \"include\", \"abortSignal\"],\n \"options\"\n );\n validateOptions(options);\n validateKeyStore({ ...options, idempotencyKey: key }, context);\n const scope = keyScope(context, key);\n const { store, environment, taxId } = scope;\n const json =\n read === undefined\n ? await storeCall(() => store.get(attemptKey(environment, taxId, key)))\n : read;\n if (json === null) {\n throw new ArcaInputError(\"No reservation exists for this idempotency key\", {\n code: \"ARCA_INPUT_RESERVATION_NOT_FOUND\",\n field: \"idempotencyKey\",\n });\n }\n const record = readRecord(json);\n if (\n options.representedTaxId !== undefined &&\n String(options.representedTaxId) !== (record.representedTaxId ?? taxId)\n ) {\n throw new ArcaInputError(\n \"Reservation belongs to another represented taxpayer\",\n { code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\" }\n );\n }\n // A retry of this key resends under the sequence lock. Holding it keeps the\n // rejection this call reads true until its lookup answers.\n return await consultKey(\n scope,\n record,\n false,\n select,\n options,\n async (current) => {\n // A rejected key never wrote its number. Without the lock, a retry may\n // have written it since, so that presumption is answered, never kept.\n const rejected = current.rejectedAt !== undefined;\n return await recordConflict(\n store,\n settledKey(environment, taxId, key),\n await consultReservation(select, current, options, taxId, rejected),\n !rejected || store.withLock !== undefined\n );\n }\n );\n}\n\n/** The store a keyed call needs, once validateKeyStore has required it. */\nfunction keyScope(\n context: StoreContext | undefined,\n idempotencyKey: string\n): KeyScope {\n if (!context?.store) {\n throw new ArcaConfigurationError(\"idempotencyKey requires a store.\");\n }\n return {\n store: context.store,\n environment: context.environment,\n taxId: context.taxId,\n idempotencyKey,\n };\n}\n\n/**\n * Consults one reservation without ever writing to ARCA: the read-only path\n * `recover()` uses, and the one the sequence barrier runs for a claim whose\n * fate nobody recorded.\n */\nfunction consultReservation(\n select: SelectService,\n record: ArcaAttemptRecord,\n options: RecoveryOptions,\n taxId: string,\n strangerAtNumber = false\n): Promise<IssueOutcome<IssueOptions>> {\n const storedOptions = {\n ...options,\n service: record.service ?? (\"wsfe\" as const),\n representedTaxId: record.representedTaxId,\n };\n const prepared = preparedFromRecord(record);\n const attempted = {\n salesPoint: record.salesPoint,\n voucherType: record.voucherType,\n number: record.number,\n };\n return recoverInvoice({\n wsfe: select(storedOptions),\n service: storedOptions.service,\n auth: storedOptions,\n data: prepared.data,\n strangerAtNumber,\n attempted,\n attempt: replayEvidence(storedOptions.service),\n includeRawResponse: options.include?.rawResponse === true,\n includedRequest: requestEvidence(\n prepared.data,\n record.number,\n storedOptions\n ),\n voucher: (cae, caeExpiry, lookup) =>\n issuedVoucher(\n {\n attempted,\n voucherClass: prepared.voucherClass,\n data: prepared.data,\n amounts: prepared.amounts,\n taxId: record.representedTaxId ?? taxId,\n },\n cae,\n caeExpiry,\n lookup\n ),\n });\n}\n\n/** The issuer's CUIT for this call: the represented one, else the client's. */\nfunction issuerTaxId(\n options: IssueOptions,\n context: StoreContext | undefined\n): string | undefined {\n return options.representedTaxId === undefined\n ? context?.taxId\n : String(options.representedTaxId);\n}\n\n/**\n * What the caller keeps: ISO dates, minor-unit money and the QR every printed\n * voucher must carry. The request keeps ARCA's own shape.\n */\nfunction issuedVoucher(\n {\n attempted,\n voucherClass,\n data,\n amounts,\n taxId,\n }: {\n attempted: VoucherCoordinates;\n voucherClass: VoucherClass;\n data: IssuanceHeader;\n amounts: IssueAmounts;\n taxId: string | undefined;\n },\n cae: string,\n caeExpiry: string,\n lookup?: VoucherSummary\n): IssuedVoucher {\n const date = toIsoDate(data.voucherDate) ?? data.voucherDate;\n const qr = voucherQr({ attempted, data, taxId, date, cae });\n return {\n ...attempted,\n voucherClass,\n date,\n header: fiscalHeader(data, lookup),\n cae,\n caeExpiry: toIsoDate(caeExpiry) ?? caeExpiry,\n amounts,\n ...qr,\n };\n}\n\n/**\n * Project the already-derived request into the stable public header. On a\n * matching recovery, valid normalized provider values win; the durable sent\n * request fills fields ARCA omitted. This performs no I/O and no derivation.\n */\nfunction fiscalHeader(\n data: IssuanceHeader,\n lookup?: VoucherSummary\n): FiscalHeader {\n const sent = normalizeWsfeVoucherInput(data);\n const header: FiscalHeader = {\n concept: (lookup?.concept ?? sent.concept) as FiscalHeader[\"concept\"],\n documentType: lookup?.documentType ?? sent.documentType,\n documentNumber: String(lookup?.documentNumber ?? sent.documentNumber),\n receiverVatConditionId:\n lookup?.receiverVatConditionId ?? sent.receiverVatConditionId,\n currencyId: lookup?.currencyId ?? sent.currencyId,\n };\n const exchangeRate = lookup?.exchangeRate ?? sent.exchangeRate;\n if (exchangeRate !== undefined) {\n header.exchangeRate = serializeArcaExchangeRate(\n exchangeRate,\n \"exchangeRate\"\n );\n }\n for (const field of [\n \"serviceStartDate\",\n \"serviceEndDate\",\n \"paymentDueDate\",\n ] as const) {\n const date = toIsoDate(lookup?.[field]) ?? toIsoDate(sent[field]);\n if (date !== undefined) {\n header[field] = date;\n }\n }\n return header;\n}\n\n/**\n * Runs after the fiscal write, so it never throws: the request was validated\n * before the write and only the CAE comes from the provider.\n */\nfunction voucherQr({\n attempted,\n data,\n taxId,\n date,\n cae,\n}: {\n attempted: VoucherCoordinates;\n data: IssuanceHeader;\n taxId: string | undefined;\n date: string;\n cae: string;\n}): Pick<IssuedVoucher, \"qr\" | \"qrPayload\"> {\n if (taxId === undefined) {\n return {};\n }\n try {\n const qrPayload = arcaQrPayload({\n taxId,\n ...attempted,\n date,\n total: Number(\n normalizeArcaAmountToMinorUnits(data.totalAmount, \"totalAmount\")\n ),\n currency: data.currencyId,\n ...(data.exchangeRate === undefined\n ? {}\n : { exchangeRate: data.exchangeRate }),\n cae,\n document: { type: data.documentType, number: data.documentNumber },\n });\n return { qr: qrUrlForPayload(qrPayload), qrPayload };\n } catch {\n return {};\n }\n}\n\ntype SequenceBarrier = {\n store: ArcaStore;\n environment: ArcaEnvironment;\n taxId: string;\n sequence: string;\n /** The taxpayer whose numbering the sequence follows. */\n sequenceTaxId: string;\n select: SelectService;\n options: IssueOptions;\n supersededBy: string;\n readNext: () => Promise<number>;\n};\n/** Either the sequence is free, with the number already read, or it is held. */\ntype BarrierResult =\n | { blocked: IssueOutcome<IssueOptions> }\n | { reserved?: number };\n\n/**\n * Holds the sequence while the last claim on it is unresolved. A claim ARCA\n * already reported, a rejected reservation and a recorded conflict clear it.\n * An empty number clears it only for a claim that would write that same\n * number, once the sequence proves it never moved: then the old key is\n * recorded as superseded, so its own retry can never take the number this\n * call is about to write. A lookup that cannot answer writes nothing at all.\n */\nasync function runSequenceBarrier({\n store,\n environment,\n taxId,\n sequence,\n sequenceTaxId,\n select,\n options,\n supersededBy,\n readNext,\n}: SequenceBarrier): Promise<BarrierResult> {\n const json = await storeCall(() => store.get(sequence));\n if (json === null) {\n return {};\n }\n const claimed = readSequenceRecord(json);\n if (claimed.resolvedAt !== undefined) {\n return {};\n }\n // The claim may belong to another issuer representing the same taxpayer: its\n // reservation and settled record live under that issuer's CUIT.\n const owner = claimed.issuerTaxId ?? taxId;\n const settled = settledKey(environment, owner, claimed.key);\n if ((await storeCall(() => store.get(settled))) !== null) {\n return {};\n }\n const reservation = await storeCall(() =>\n store.get(attemptKey(environment, owner, claimed.key))\n );\n if (reservation === null) {\n // The marker is written before the reservation: a key without one never\n // put its number in a record, let alone submitted it.\n return {};\n }\n // The reservation, not the marker, is the evidence: it names the number the\n // consultation checks and a superseded record repeats.\n const record = readRecord(reservation);\n if (record.rejectedAt !== undefined) {\n // The claim stopped before resolving its marker, but ARCA's rejection is\n // recorded: that key's retry treats any voucher at its number as foreign.\n return {};\n }\n const blocked: BarrierResult = {\n blocked: withheld(\n record,\n { kind: \"blocked\", by: claimed.key, byTaxId: owner },\n options\n ),\n };\n const outcome = await recordConflict(\n store,\n settled,\n await consultReservation(\n select,\n // This call's certificate may not be the one that claimed. Without a\n // represented CUIT, it would read its own numbering instead of the one\n // the claim advanced.\n {\n ...record,\n representedTaxId: record.representedTaxId ?? sequenceTaxId,\n },\n {\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n },\n owner\n )\n );\n if (outcome.kind === \"authorized\" || outcome.kind === \"conflict\") {\n return {};\n }\n if (outcome.kind !== \"indeterminate\" || outcome.lookup.kind !== \"not_found\") {\n return blocked;\n }\n // The consultation saw nothing. Only a claim that would write this same\n // number may take it over, and only the sequence itself proves it free: if\n // ARCA already moved past it, a write this lookup could not see is out there\n // and nothing may be superseded.\n if (options.number !== undefined && options.number !== record.number) {\n return blocked;\n }\n const next = await readNext();\n if (next !== record.number) {\n return blocked;\n }\n await storeCall(() =>\n store.add(\n settled,\n JSON.stringify({\n v: 1,\n kind: \"superseded\",\n number: record.number,\n by: supersededBy,\n byTaxId: taxId,\n settledAt: new Date().toISOString(),\n } satisfies ArcaSettledRecord)\n )\n );\n return { reserved: next };\n}\n\nfunction readSequenceRecord(json: string): ArcaSequenceRecord {\n try {\n const record = JSON.parse(json) as ArcaSequenceRecord;\n if (\n record?.v !== 1 ||\n typeof record.key !== \"string\" ||\n (record.issuerTaxId !== undefined &&\n typeof record.issuerTaxId !== \"string\") ||\n !Number.isSafeInteger(record.number)\n ) {\n throw new Error(\"Invalid sequence structure\");\n }\n return record;\n } catch (cause) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA sequence record; delete the sequence key to resume.\",\n { cause }\n );\n }\n}\n","import { getArcaServiceConfig } from \"../config\";\nimport { ArcaInvalidSoapResponseError, ArcaSoapFaultError } from \"../errors\";\nimport { postXmlWithMetadata } from \"../internal/http\";\nimport type { ArcaLogger } from \"../internal/logger\";\nimport { createSafeErrorDiagnostic } from \"../internal/redaction\";\nimport type {\n ArcaClientConfig,\n ArcaSoapExecutionOptions,\n ArcaSoapResponse,\n} from \"../internal/types\";\nimport {\n buildSoapEnvelope,\n getSingleBodyEntry,\n parseSoapBody,\n} from \"../internal/xml\";\n\nexport type SoapTransport = {\n execute<TBody, TResult>(\n request: ArcaSoapExecutionOptions<TBody>\n ): Promise<ArcaSoapResponse<TResult>>;\n};\n\nexport type CreateSoapTransportOptions = {\n config: ArcaClientConfig;\n logger?: ArcaLogger;\n};\n\nexport function createSoapTransport(\n options: CreateSoapTransportOptions\n): SoapTransport {\n return {\n async execute<TBody, TResult>(request: ArcaSoapExecutionOptions<TBody>) {\n const serviceConfig = getArcaServiceConfig(request.service);\n const url = serviceConfig.endpoint[options.config.environment];\n const soapActionOperation = request.operation;\n const bodyElementName = request.bodyElementName ?? request.operation;\n const soapAction = serviceConfig.usesEmptySoapAction\n ? \"\"\n : `${serviceConfig.soapActionBase}${soapActionOperation}`;\n const contentType =\n serviceConfig.soapVersion === \"1.2\"\n ? `application/soap+xml; charset=utf-8; action=\"${soapAction}\"`\n : 'text/xml; charset=\"utf-8\"';\n const xml = buildSoapEnvelope(\n serviceConfig.soapVersion,\n bodyElementName,\n serviceConfig.namespace,\n request.body as Record<string, unknown>,\n {\n namespaceMode: request.bodyElementNamespaceMode,\n }\n );\n const startedAt = Date.now();\n\n options.logger?.debug(\"Sending ARCA SOAP request\", {\n service: request.service,\n operation: request.operation,\n url,\n });\n\n try {\n const response = await postXmlWithMetadata({\n url,\n body: xml,\n contentType,\n soapAction:\n serviceConfig.soapVersion === \"1.1\" ? soapAction : undefined,\n useLegacyTlsSecurityLevel0:\n options.config.environment === \"production\" &&\n serviceConfig.useLegacyTlsSecurityLevel0 === true,\n timeout: options.config.timeout,\n retries: request.retries ?? options.config.retries,\n retryDelay: options.config.retryDelay,\n logger: options.logger,\n service: request.service,\n operation: request.operation,\n signal: request.signal,\n });\n\n options.logger?.debug(\"Received ARCA SOAP response\", {\n service: request.service,\n operation: request.operation,\n durationMs: Date.now() - startedAt,\n });\n\n const parseContext = {\n service: request.service,\n operation: request.operation,\n endpointUrl: url,\n statusCode: response.statusCode,\n contentType: response.contentType,\n responseBody: response.body,\n };\n const soapBody = parseSoapBody(response.body, parseContext);\n const [, result] = getSingleBodyEntry<Record<string, unknown>>(\n soapBody,\n parseContext\n );\n\n return {\n service: request.service,\n operation: request.operation,\n raw: response.body,\n result: result as TResult,\n };\n } catch (error) {\n if (error instanceof ArcaSoapFaultError) {\n options.logger?.error(\"ARCA SOAP fault response\", {\n service: request.service,\n operation: request.operation,\n url,\n ...createSafeErrorDiagnostic(error),\n });\n }\n\n if (error instanceof ArcaInvalidSoapResponseError) {\n options.logger?.error(\"ARCA invalid SOAP response\", {\n service: request.service,\n operation: request.operation,\n url,\n ...createSafeErrorDiagnostic(error),\n });\n }\n\n throw error;\n }\n },\n };\n}\n","import {\n createCipheriv,\n createDecipheriv,\n hkdfSync,\n randomBytes,\n} from \"node:crypto\";\nimport type {\n ArcaAuthCredentials,\n ArcaWsaaSessionKey,\n ArcaWsaaSessionStore,\n} from \"../internal/types\";\nimport { type ArcaStore, storeCall } from \"../store/types\";\nimport {\n isWsaaCredentialValid,\n serializeWsaaSessionKey,\n} from \"./session-store\";\n\n/**\n * A WSAA ticket authorizes fiscal work for twelve hours, so it never reaches\n * the store in clear. The key is derived from the private key the client\n * already holds: whoever has that PEM can log in on their own, so wrapping the\n * ticket with it adds no exposure and asks for no second secret.\n */\nexport type WsaaStoreAdapterSecret = { privateKeyPem: string };\n\nconst KEY_PREFIX = \"arca:v2:wsaa:\";\n/**\n * Where releases before 0.15 kept the ticket in clear. A valid one is resealed\n * under the v2 key on first read instead of logging in again, which ARCA\n * refuses for a few minutes after the previous login\n * (`coe.alreadyAuthenticated`). It is left in place until it expires so\n * the pre-0.15 processes of a mixed rollout keep finding it, and the lock stays\n * on this key so both versions serialize their logins.\n */\nconst LEGACY_KEY_PREFIX = \"arca:v1:wsaa:\";\nconst HKDF_SALT = \"facturas:wsaa:v2\";\nconst RECORD_VERSION = 2;\n\ntype SealedRecord = {\n v: typeof RECORD_VERSION;\n iv: string;\n data: string;\n tag: string;\n};\n\nexport function createWsaaStoreAdapter(\n store: ArcaStore,\n secret: WsaaStoreAdapterSecret\n): ArcaWsaaSessionStore {\n const key = (value: ArcaWsaaSessionKey) =>\n `${KEY_PREFIX}${serializeWsaaSessionKey(value)}`;\n const legacyKey = (value: ArcaWsaaSessionKey) =>\n `${LEGACY_KEY_PREFIX}${serializeWsaaSessionKey(value)}`;\n const remove = store.delete?.bind(store);\n const lock = store.withLock?.bind(store);\n const write = (value: ArcaWsaaSessionKey, credentials: ArcaAuthCredentials) =>\n store.set(\n key(value),\n seal(JSON.stringify(credentials), cipherKey(secret, value))\n );\n return {\n get: (value) =>\n storeCall(async () => {\n const json = await store.get(key(value));\n const sealed =\n json === null ? null : usable(open(json, cipherKey(secret, value)));\n if (sealed) {\n return sealed;\n }\n // No usable sealed ticket. A pre-0.15 process of a mixed rollout may\n // have refreshed the clear one since, so it is checked as well.\n const legacy = usable(parseClear(await store.get(legacyKey(value))));\n if (legacy) {\n await write(value, legacy);\n }\n return legacy;\n }),\n set: (value, credentials) => storeCall(() => write(value, credentials)),\n ...(remove\n ? {\n delete: (value: ArcaWsaaSessionKey) =>\n storeCall(() => remove(key(value))),\n }\n : {}),\n ...(lock\n ? {\n withLock: <T>(value: ArcaWsaaSessionKey, fn: () => Promise<T>) =>\n lock(legacyKey(value), fn),\n }\n : {}),\n };\n}\n\nfunction usable(\n credentials: ArcaAuthCredentials | null\n): ArcaAuthCredentials | null {\n return credentials &&\n typeof credentials.token === \"string\" &&\n typeof credentials.sign === \"string\" &&\n isWsaaCredentialValid(credentials)\n ? credentials\n : null;\n}\n\nfunction parseClear(json: string | null): ArcaAuthCredentials | null {\n if (json === null) {\n return null;\n }\n try {\n return JSON.parse(json) as ArcaAuthCredentials;\n } catch {\n return null;\n }\n}\n\n/** One key per session key, so a ticket sealed for one certificate opens for no other. */\nfunction cipherKey(\n secret: WsaaStoreAdapterSecret,\n value: ArcaWsaaSessionKey\n): Buffer {\n return Buffer.from(\n hkdfSync(\n \"sha256\",\n secret.privateKeyPem,\n HKDF_SALT,\n serializeWsaaSessionKey(value),\n 32\n )\n );\n}\n\nfunction seal(plaintext: string, cipherKey: Buffer): string {\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", cipherKey, iv);\n const data = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ]);\n const record: SealedRecord = {\n v: RECORD_VERSION,\n iv: iv.toString(\"base64url\"),\n data: data.toString(\"base64url\"),\n tag: cipher.getAuthTag().toString(\"base64url\"),\n };\n return JSON.stringify(record);\n}\n\n/** Anything that does not open cleanly is a cache miss, never a throw. */\nfunction open(json: string, cipherKey: Buffer): ArcaAuthCredentials | null {\n try {\n const record = JSON.parse(json) as Partial<SealedRecord> | null;\n if (\n !record ||\n record.v !== RECORD_VERSION ||\n typeof record.iv !== \"string\" ||\n typeof record.data !== \"string\" ||\n typeof record.tag !== \"string\"\n ) {\n return null;\n }\n const decipher = createDecipheriv(\n \"aes-256-gcm\",\n cipherKey,\n Buffer.from(record.iv, \"base64url\")\n );\n decipher.setAuthTag(Buffer.from(record.tag, \"base64url\"));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(record.data, \"base64url\")),\n decipher.final(),\n ]).toString(\"utf8\");\n return JSON.parse(plaintext) as ArcaAuthCredentials;\n } catch {\n return null;\n }\n}\n","import {\n assertArcaClientConfig,\n discoverArcaClientConfig,\n normalizeArcaClientConfig,\n} from \"./config\";\nimport { createArcaLogger } from \"./internal/logger\";\nimport type { ArcaClientOptions, ArcaEnvironment } from \"./internal/types\";\nimport { createPadronService, type PadronService } from \"./services/padron\";\nimport {\n createVouchersService,\n type VouchersService,\n} from \"./services/vouchers\";\nimport { createWsfeService, type WsfeService } from \"./services/wsfe\";\nimport { createWsfexService, type WsfexService } from \"./services/wsfex\";\nimport { createWsmtxcaService, type WsmtxcaService } from \"./services/wsmtxca\";\nimport { createSoapTransport } from \"./soap\";\nimport { createWsaaAuthModule } from \"./wsaa\";\nimport { createWsaaStoreAdapter } from \"./wsaa/store-adapter\";\n\n/** Immutable, credential-free operational view of an ARCA client configuration. */\nexport type ArcaClientConfigView = Readonly<{\n taxId: string;\n environment: ArcaEnvironment;\n timeout?: number;\n retries?: number;\n retryDelay?: number;\n}>;\n\n/** Fully wired ARCA client with access to all service modules. */\nexport type ArcaClient = {\n readonly config: ArcaClientConfigView;\n /** Issues an invoice from business input. Idempotent with a store and key. */\n issue: VouchersService[\"issue\"];\n /** Derives what issue() would send for the same input, with no I/O. */\n preview: VouchersService[\"preview\"];\n /** Issues a credit note against an authorized original or a period. */\n issueCreditNote: VouchersService[\"issueCreditNote\"];\n /** Consults a durable reservation. Never allocates or authorizes a voucher. */\n recover: VouchersService[\"recover\"];\n /** Issues a debit note against an authorized original or a period. */\n issueDebitNote: VouchersService[\"issueDebitNote\"];\n /** Derives a credit note; reads the original but reserves no number. */\n previewCreditNote: VouchersService[\"previewCreditNote\"];\n /** Derives a debit note; reads the original but reserves no number. */\n previewDebitNote: VouchersService[\"previewDebitNote\"];\n /** Consults one authorized voucher; `null` when ARCA has no such voucher. */\n lookup: VouchersService[\"lookup\"];\n /** The last number ARCA authorized for a sales point and type; `0` when none. */\n lastAuthorized: VouchersService[\"lastAuthorized\"];\n wsfe: WsfeService;\n /** WSFEX, ARCA's export service: its reference tables and exchange rates. */\n wsfex: WsfexService;\n wsmtxca: WsmtxcaService;\n padron: PadronService;\n};\n\n/**\n * Creates an ARCA client from the given configuration.\n * Validates the config, wires WSAA authentication and SOAP transport,\n * and returns an object with `issue()`, `preview()`, `issueCreditNote()`,\n * `issueDebitNote()`, `previewCreditNote()`, `previewDebitNote()`, `recover()`,\n * `lookup()`, `lastAuthorized()` and the `.wsfe`, `.wsfex`, `.wsmtxca`, and\n * `.padron` service modules.\n *\n * @throws {ArcaConfigurationError} When the config is missing or invalid.\n */\nexport function createArcaClient(config: ArcaClientOptions = {}): ArcaClient {\n const discovered = discoverArcaClientConfig(config);\n assertArcaClientConfig(discovered);\n const normalizedConfig = normalizeArcaClientConfig(discovered);\n if (normalizedConfig.store && !normalizedConfig.wsaaSessionStore) {\n normalizedConfig.wsaaSessionStore = createWsaaStoreAdapter(\n normalizedConfig.store,\n normalizedConfig\n );\n }\n const logger = createArcaLogger(normalizedConfig.logger);\n\n const auth = createWsaaAuthModule({ config: normalizedConfig, logger });\n const soap = createSoapTransport({ config: normalizedConfig, logger });\n const publicConfig = Object.freeze({\n taxId: normalizedConfig.taxId,\n environment: normalizedConfig.environment,\n timeout: normalizedConfig.timeout,\n retries: normalizedConfig.retries,\n retryDelay: normalizedConfig.retryDelay,\n });\n\n const wsfe = createWsfeService({ config: normalizedConfig, auth, soap });\n const wsmtxca = createWsmtxcaService({\n config: normalizedConfig,\n auth,\n soap,\n });\n const wsfex = createWsfexService({ config: normalizedConfig, auth, soap });\n const vouchers = createVouchersService(\n wsfe,\n normalizedConfig,\n wsmtxca,\n wsfex\n );\n return {\n config: publicConfig,\n issue: vouchers.issue,\n preview: vouchers.preview,\n issueCreditNote: vouchers.issueCreditNote,\n recover: vouchers.recover,\n issueDebitNote: vouchers.issueDebitNote,\n previewCreditNote: vouchers.previewCreditNote,\n previewDebitNote: vouchers.previewDebitNote,\n lookup: vouchers.lookup,\n lastAuthorized: vouchers.lastAuthorized,\n wsfe,\n wsfex,\n wsmtxca,\n padron: createPadronService({ config: normalizedConfig, auth, soap }),\n };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n type FileHandle,\n link,\n mkdir,\n open,\n readFile,\n rename,\n rmdir,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ARCA_LEASE_MS, type ArcaLeaseDriver, withLease } from \"./lock\";\nimport { type ArcaStore, storeCall } from \"./types\";\n\ntype Holder = { owner: string; expiresAt: string };\ntype HolderFile = { raw: string; value: Holder | null };\n\n/** Persistent store for a single server with a private durable volume. */\nexport function createFileStore(directory: string): ArcaStore {\n const path = (key: string) =>\n join(directory, createHash(\"sha256\").update(key).digest(\"hex\"));\n const ensure = () => mkdir(directory, { recursive: true, mode: 0o700 });\n return {\n get: (key) =>\n storeCall(async () => {\n try {\n return await readFile(path(key), \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }),\n set: (key, value) =>\n storeCall(async () => {\n await ensure();\n const temporary = `${path(key)}.${randomUUID()}.tmp`;\n try {\n await writeFile(temporary, value, { mode: 0o600, flag: \"wx\" });\n await rename(temporary, path(key));\n } finally {\n await unlink(temporary).catch(() => undefined);\n }\n }),\n add: (key, value) =>\n storeCall(async () => {\n await ensure();\n try {\n await writeFile(path(key), value, { flag: \"wx\", mode: 0o600 });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw error;\n }\n }),\n delete: (key) =>\n storeCall(async () => {\n try {\n await unlink(path(key));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n }),\n withLock: (key, fn, options) =>\n // A lock directory: mkdir is the atomic claim on every POSIX filesystem\n // and on Windows, and the holder file inside carries the lease.\n withLease(fileLease(`${path(key)}.lock`, ensure), fn, options),\n };\n}\n\nfunction fileLease(\n directory: string,\n ensure: () => Promise<unknown>\n): ArcaLeaseDriver {\n const holder = join(directory, \"holder\");\n const claim = (owner: string) =>\n JSON.stringify({\n owner,\n expiresAt: new Date(Date.now() + ARCA_LEASE_MS).toISOString(),\n } satisfies Holder);\n return {\n acquire: (owner) =>\n storeCall(async () => {\n await ensure();\n if (!(await createDirectory(directory))) {\n const current = await readHolder(holder);\n if (await stillHeld(directory, current?.value ?? null)) {\n return false;\n }\n if (current) {\n await retireHolder(directory, holder, current.raw);\n } else {\n await removeEmptyDirectory(directory);\n }\n // Do not recreate the directory in the same attempt. Another\n // contender may still be removing the stale path it also observed.\n // The lease retry makes every contender claim it again with mkdir.\n return false;\n }\n return await writeHolder(holder, claim(owner));\n }),\n renew: (owner) => storeCall(() => renewHolder(holder, owner, claim(owner))),\n release: (owner) =>\n storeCall(async () => {\n const current = await readHolder(holder);\n if (current?.value?.owner === owner) {\n await retireHolder(directory, holder, current.raw);\n }\n }),\n };\n}\n\nasync function createDirectory(directory: string): Promise<boolean> {\n try {\n await mkdir(directory);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw error;\n }\n}\n\nasync function writeHolder(holder: string, value: string): Promise<boolean> {\n try {\n await writeFile(holder, value, { mode: 0o600, flag: \"wx\" });\n return true;\n } catch (error) {\n if (\n (error as NodeJS.ErrnoException).code === \"EEXIST\" ||\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return false;\n }\n throw error;\n }\n}\n\nasync function readHolder(holder: string): Promise<HolderFile | null> {\n let raw: string;\n try {\n raw = await readFile(holder, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n try {\n return { raw, value: JSON.parse(raw) as Holder };\n } catch {\n return { raw, value: null };\n }\n}\n\nasync function renewHolder(\n holder: string,\n owner: string,\n value: string\n): Promise<void> {\n let file: FileHandle;\n try {\n file = await open(holder, \"r+\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n try {\n let current: Holder | null = null;\n try {\n current = JSON.parse(await file.readFile(\"utf8\")) as Holder;\n } catch {\n // An invalid claim is not ours to renew.\n }\n if (current?.owner === owner) {\n await file.truncate(0);\n await file.write(value, 0, \"utf8\");\n }\n } finally {\n await file.close();\n }\n}\n\nasync function retireHolder(\n directory: string,\n holder: string,\n expected: string\n): Promise<void> {\n const retired = `${directory}.${randomUUID()}.stale`;\n try {\n await rename(holder, retired);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n let removed = false;\n try {\n if ((await readFile(retired, \"utf8\")) !== expected) {\n return;\n }\n try {\n await rmdir(directory);\n removed = true;\n } catch (error) {\n if (!isDirectoryContention(error)) {\n throw error;\n }\n }\n } finally {\n if (!removed) {\n await restoreHolder(retired, holder);\n }\n await unlink(retired).catch(() => undefined);\n }\n}\n\nasync function restoreHolder(retired: string, holder: string): Promise<void> {\n try {\n await link(retired, holder);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== \"EEXIST\" && code !== \"ENOENT\") {\n throw error;\n }\n }\n}\n\nasync function removeEmptyDirectory(directory: string): Promise<void> {\n try {\n await rmdir(directory);\n } catch (error) {\n if (!isDirectoryContention(error)) {\n throw error;\n }\n }\n}\n\nfunction isDirectoryContention(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"ENOENT\" || code === \"ENOTEMPTY\" || code === \"EEXIST\";\n}\n\n/** A directory with no readable holder is still fresh for one lease. */\nasync function stillHeld(\n directory: string,\n holder: Holder | null\n): Promise<boolean> {\n if (holder) {\n return Date.parse(holder.expiresAt) > Date.now();\n }\n try {\n return (await stat(directory)).mtimeMs + ARCA_LEASE_MS > Date.now();\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,oBAAoB,CAAC,cAAc,MAAM;AAG/C,IAAM,qBAAqB;AAAA,EAChC,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,aAAa;AACf;AAUA,IAAM,2BAA2B;AAAA,EAC/B;AAAA,EACA;AACF;AACA,IAAM,mCACJ;AACF,IAAM,2CACJ;AACF,IAAM,wBAAwB,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAC/D,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAC7B,IAAM,8BAA8B;AAQ7B,SAAS,8BACd,UAAgD,CAAC,GAC/B;AAClB,QAAM,MAAM,QAAQ,OAAO,QAAQ;AACnC,QAAM,gBAAgB;AAAA,IACpB,GAAG;AAAA,IACH,GAAG,QAAQ;AAAA,EACb;AACA,QAAM,mBAAmB,QAAQ,KAAK,cAAc,WAAW;AAC/D,QAAM,mBAAmB,0BAA0B,gBAAgB;AAEnE,QAAM,SAA2B;AAAA,IAC/B,OAAO,QAAQ,KAAK,cAAc,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I;AACF,YAAQ,MAAM,KAAK,SAAS,GAAG,UAAU,gBAAgB,KAAK,IAAI;AAAA,EACpE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["iso","text","invalid","reviewedTotal","text","exchangeRate","from","to","auth","rows","lookupVoucher","issue","text","issuerTaxId","text","minor","iso","createHash","settled","runningForced","runningOrdinary","createHash","delay","assertSalesPoint","deriveReceiver","invalid","deriveCurrency","exchangeRate","prepared","store","outcome","issued","invalid","invalid","originalTotal","settled","settle","consultReservation","auth","issuedVoucher","attempt","target","exchangeRate","cipherKey","auth","createHash","randomUUID","open","createHash","randomUUID","open"]}