mppx 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/Currency.d.ts +59 -0
  3. package/dist/Currency.js +60 -0
  4. package/dist/Errors.d.ts +24 -4
  5. package/dist/Errors.js +28 -10
  6. package/dist/cli/cli.js +135 -135
  7. package/dist/cli/plugins/index.js +12 -12
  8. package/dist/cli/plugins/tempo.js +13 -1
  9. package/dist/client/internal/Fetch.d.ts +5 -0
  10. package/dist/client/internal/Fetch.js +7 -0
  11. package/dist/cloudflare/ChannelStore.d.ts +1 -2
  12. package/dist/cloudflare/ChannelStore.js +14 -20
  13. package/dist/cloudflare/Channels.d.ts +20 -2
  14. package/dist/cloudflare/Channels.js +47 -4
  15. package/dist/cloudflare/index.d.ts +1 -1
  16. package/dist/cloudflare/index.js +1 -1
  17. package/dist/discovery/Discovery.d.ts +116 -9
  18. package/dist/discovery/Discovery.js +169 -0
  19. package/dist/evm/server/Charge.js +2 -3
  20. package/dist/evm/server/Methods.d.ts +1 -1
  21. package/dist/evm/server/Methods.js +3 -2
  22. package/dist/extensions/identity/Types.d.ts +26 -0
  23. package/dist/extensions/identity/attestation/Token.d.ts +6 -4
  24. package/dist/extensions/identity/attestation/Token.js +11 -5
  25. package/dist/extensions/identity/email-otp/client/index.js +4 -4
  26. package/dist/extensions/identity/index.d.ts +6 -0
  27. package/dist/extensions/identity/index.js +6 -0
  28. package/dist/extensions/identity/internal/HttpMessageSignature.d.ts +2 -2
  29. package/dist/extensions/identity/internal/HttpMessageSignature.js +13 -10
  30. package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.js +1 -1
  31. package/dist/extensions/identity/internal/Signer.d.ts +20 -0
  32. package/dist/extensions/identity/internal/Signer.js +94 -0
  33. package/dist/extensions/identity/link/Constants.d.ts +102 -0
  34. package/dist/extensions/identity/link/Constants.js +16 -0
  35. package/dist/extensions/identity/link/client/index.d.ts +80 -0
  36. package/dist/extensions/identity/link/client/index.js +211 -0
  37. package/dist/extensions/identity/link/index.d.ts +12 -0
  38. package/dist/extensions/identity/link/index.js +12 -0
  39. package/dist/extensions/identity/link/server/index.d.ts +124 -0
  40. package/dist/extensions/identity/link/server/index.js +518 -0
  41. package/dist/extensions/identity/persona/Constants.d.ts +24 -0
  42. package/dist/extensions/identity/persona/Constants.js +24 -0
  43. package/dist/extensions/identity/persona/Did.d.ts +24 -0
  44. package/dist/extensions/identity/persona/Did.js +24 -0
  45. package/dist/extensions/identity/persona/Types.d.ts +21 -0
  46. package/dist/extensions/identity/persona/Types.js +2 -0
  47. package/dist/extensions/identity/persona/index.d.ts +10 -0
  48. package/dist/extensions/identity/persona/index.js +9 -0
  49. package/dist/extensions/identity/persona/server/index.d.ts +152 -0
  50. package/dist/extensions/identity/persona/server/index.js +263 -0
  51. package/dist/extensions/identity/tap/client/index.d.ts +6 -2
  52. package/dist/extensions/identity/tap/client/index.js +2 -0
  53. package/dist/extensions/identity/tempo/Constants.d.ts +14 -0
  54. package/dist/extensions/identity/tempo/Constants.js +14 -0
  55. package/dist/extensions/identity/tempo/Types.d.ts +31 -0
  56. package/dist/extensions/identity/tempo/Types.js +2 -0
  57. package/dist/extensions/identity/tempo/client/index.d.ts +34 -0
  58. package/dist/extensions/identity/tempo/client/index.js +60 -0
  59. package/dist/extensions/identity/tempo/index.d.ts +5 -0
  60. package/dist/extensions/identity/tempo/index.js +4 -0
  61. package/dist/extensions/identity/tempo/internal/Jwt.d.ts +36 -0
  62. package/dist/extensions/identity/tempo/internal/Jwt.js +114 -0
  63. package/dist/extensions/identity/tempo/server/index.d.ts +65 -0
  64. package/dist/extensions/identity/tempo/server/index.js +247 -0
  65. package/dist/extensions/identity/web-bot-auth/client/index.d.ts +6 -4
  66. package/dist/extensions/identity/web-bot-auth/client/index.js +7 -5
  67. package/dist/extensions/identity/web-bot-auth/server/index.js +1 -1
  68. package/dist/extensions/identity/world/Constants.d.ts +50 -0
  69. package/dist/extensions/identity/world/Constants.js +50 -0
  70. package/dist/extensions/identity/world/Types.d.ts +52 -0
  71. package/dist/extensions/identity/world/Types.js +2 -0
  72. package/dist/extensions/identity/world/client/index.d.ts +103 -0
  73. package/dist/extensions/identity/world/client/index.js +208 -0
  74. package/dist/extensions/identity/world/index.d.ts +6 -0
  75. package/dist/extensions/identity/world/index.js +5 -0
  76. package/dist/extensions/identity/world/internal/Idp.d.ts +50 -0
  77. package/dist/extensions/identity/world/internal/Idp.js +265 -0
  78. package/dist/extensions/identity/world/issuer/index.d.ts +120 -0
  79. package/dist/extensions/identity/world/issuer/index.js +520 -0
  80. package/dist/extensions/identity/world/server/index.d.ts +49 -0
  81. package/dist/extensions/identity/world/server/index.js +63 -0
  82. package/dist/identity/Headers.d.ts +6 -1
  83. package/dist/identity/Headers.js +11 -1
  84. package/dist/identity/Server.js +2 -0
  85. package/dist/identity/Types.d.ts +10 -0
  86. package/dist/index.d.ts +1 -0
  87. package/dist/index.js +1 -0
  88. package/dist/internal/version.d.ts +2 -2
  89. package/dist/internal/version.js +1 -1
  90. package/dist/proxy/internal/Headers.js +4 -4
  91. package/dist/server/Mppx.js +6 -2
  92. package/dist/stripe/server/internal/html.gen.js +1 -1
  93. package/dist/tempo/client/Charge.d.ts +11 -8
  94. package/dist/tempo/client/Charge.js +85 -18
  95. package/dist/tempo/index.d.ts +4 -0
  96. package/dist/tempo/index.js +4 -0
  97. package/dist/tempo/internal/auto-swap.d.ts +6 -5
  98. package/dist/tempo/internal/auto-swap.js +17 -2
  99. package/dist/tempo/internal/currencies.d.ts +5 -4
  100. package/dist/tempo/internal/currencies.js +13 -9
  101. package/dist/tempo/internal/defaults.d.ts +7 -0
  102. package/dist/tempo/internal/defaults.js +7 -0
  103. package/dist/tempo/internal/fee-payer.js +8 -2
  104. package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
  105. package/dist/tempo/internal/machine-token-charge.js +82 -1
  106. package/dist/tempo/internal/zone.d.ts +27 -0
  107. package/dist/tempo/internal/zone.js +54 -7
  108. package/dist/tempo/server/Charge.js +59 -2
  109. package/dist/tempo/server/Methods.d.ts +1 -1
  110. package/dist/tempo/server/internal/html.gen.js +1 -1
  111. package/dist/tempo/server/internal/transport.d.ts +1 -1
  112. package/dist/tempo/server/internal/transport.js +9 -16
  113. package/dist/tempo/session/client/CredentialState.js +31 -0
  114. package/dist/tempo/session/client/Session.d.ts +12 -6
  115. package/dist/tempo/session/client/Session.js +64 -18
  116. package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
  117. package/dist/tempo/session/server/ChannelStore.js +58 -8
  118. package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
  119. package/dist/tempo/session/server/CloseSupervisor.js +110 -12
  120. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  121. package/dist/tempo/session/server/CredentialVerification.js +6 -32
  122. package/dist/tempo/session/server/Session.js +6 -3
  123. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  124. package/dist/tempo/session/server/Settlement.js +36 -6
  125. package/dist/tempo/session/server/Sse.d.ts +2 -0
  126. package/dist/tempo/session/server/Sse.js +12 -12
  127. package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
  128. package/dist/tempo/subscription/KeyAuthorization.js +1 -1
  129. package/dist/x402/Assets.d.ts +14 -5
  130. package/dist/x402/Assets.js +11 -16
  131. package/package.json +23 -3
  132. /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
@@ -11,6 +11,7 @@ import { normalizeHeaders } from '../../client/internal/Fetch.js';
11
11
  import * as Constants from '../../Constants.js';
12
12
  import * as Credential from '../../Credential.js';
13
13
  import { tempo as tempoMethods } from '../../tempo/client/index.js';
14
+ import * as MachineTokenCharge from '../../tempo/internal/machine-token-charge.js';
14
15
  import { tip20ChannelEscrow } from '../../tempo/session/precompile/Protocol.js';
15
16
  import { signCloseAuthorization, signVoucher } from '../../tempo/session/precompile/Voucher.js';
16
17
  import { createDefaultStore, createKeychain, resolveAccountName } from '../account.js';
@@ -706,7 +707,8 @@ async function scoreTempoChargeChallenge(challenge, probe) {
706
707
  const amount = request.amount;
707
708
  if (typeof currency !== 'string' || typeof amount !== 'string')
708
709
  return 'unsupported';
709
- const requiredChainId = request.methodDetails?.chainId;
710
+ const methodDetails = request.methodDetails;
711
+ const requiredChainId = methodDetails?.chainId;
710
712
  if (requiredChainId && probe.client.chain?.id && requiredChainId !== probe.client.chain.id) {
711
713
  return 'unsupported';
712
714
  }
@@ -724,6 +726,16 @@ async function scoreTempoChargeChallenge(challenge, probe) {
724
726
  return 'unknownBalance';
725
727
  if (balance >= amountRaw)
726
728
  return 'payable';
729
+ // A MACH-enabled charge is also payable from a MACH balance, but only without splits:
730
+ // the MACH route takes a single transfer, so a split charge pays in its currency.
731
+ if (methodDetails?.machineTokenEnabled === true && !methodDetails.splits?.length) {
732
+ const machineTokenBalance = await MachineTokenCharge.getBalance(probe.client, {
733
+ account: probe.account,
734
+ chainId: requiredChainId ?? probe.client.chain?.id,
735
+ });
736
+ if (machineTokenBalance !== undefined && machineTokenBalance >= amountRaw)
737
+ return 'payable';
738
+ }
727
739
  return 'insufficientBalance';
728
740
  }
729
741
  function parseOptions(schema, rawOptions, allowedKeys) {
@@ -8,6 +8,11 @@ import * as Transport from '../Transport.js';
8
8
  import * as ProofRealm from './ProofRealm.js';
9
9
  /** Per-request payment opt-out preserved by forwarding fetch layers. @internal */
10
10
  export declare const skipPayment: unique symbol;
11
+ /**
12
+ * Disables automatic payments for a request, including through identity wrappers.
13
+ * Custom forwarding layers must preserve the returned init's symbol properties.
14
+ */
15
+ export declare function withoutPayment(init?: RequestInit): RequestInit;
11
16
  export type ClientEventMap<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[], response = Response> = {
12
17
  'challenge.received': ChallengeReceivedPayload<methods, response>;
13
18
  'credential.created': CredentialCreatedPayload<methods, response>;
@@ -17,6 +17,13 @@ const MPPX_FETCH_WRAPPER = Symbol.for('mppx.fetch.wrapper');
17
17
  const MPPX_FETCH_IDENTITY = Symbol.for('mppx.fetch.identity');
18
18
  /** Per-request payment opt-out preserved by forwarding fetch layers. @internal */
19
19
  export const skipPayment = Symbol.for('mppx.fetch.skipPayment');
20
+ /**
21
+ * Disables automatic payments for a request, including through identity wrappers.
22
+ * Custom forwarding layers must preserve the returned init's symbol properties.
23
+ */
24
+ export function withoutPayment(init = {}) {
25
+ return { ...init, [skipPayment]: true };
26
+ }
20
27
  const defaultMaxPaymentRetries = 3;
21
28
  const maxErrorBodyBytes = 64 * 1024;
22
29
  const errorBodyTimeoutMs = 2_000;
@@ -78,8 +78,7 @@ export declare namespace ChannelStore {
78
78
  /** Whether a stored value is a precompile-backed session channel state. */
79
79
  export declare function isChannelState(value: unknown): value is State;
80
80
  /**
81
- * The raw amount a settlement of the channel would capture now: the largest accepted voucher
82
- * within `spent` (as mppx's `settle` picks it) above `settledOnChain`.
81
+ * The unpaid spend recoverable by settlement or a bounded payee close.
83
82
  */
84
83
  export declare function unsettledAmount(state: State): bigint;
85
84
  /**
@@ -1,6 +1,6 @@
1
1
  import { Json } from 'ox';
2
2
  import * as Store from '../Store.js';
3
- import { pendingCloseClockSkewSeconds, pendingCloseValiditySeconds, resolveSettleableVoucher, } from '../tempo/session/server/ChannelStore.js';
3
+ import { pendingCloseClockSkewSeconds, pendingCloseValiditySeconds, hasPendingClose, } from '../tempo/session/server/ChannelStore.js';
4
4
  /** Storage key of a channel object's settlement bookkeeping, beside the channel state. */
5
5
  const settlementKey = 'mppx:channel-store:settlement';
6
6
  /**
@@ -218,31 +218,31 @@ export function isChannelState(value) {
218
218
  typeof state.spent === 'bigint');
219
219
  }
220
220
  /**
221
- * The raw amount a settlement of the channel would capture now: the largest accepted voucher
222
- * within `spent` (as mppx's `settle` picks it) above `settledOnChain`.
221
+ * The unpaid spend recoverable by settlement or a bounded payee close.
223
222
  */
224
223
  export function unsettledAmount(state) {
225
224
  return settleableAmount(state) - state.settledOnChain;
226
225
  }
227
- /** The cumulative amount a settlement of the channel would bring it to: its settleable voucher's, or `settledOnChain`. */
226
+ /** Collectible spend, including partial capture of an oversized voucher through a payee close. */
228
227
  function settleableAmount(state) {
229
- return resolveSettleableVoucher(state)?.cumulativeAmount ?? state.settledOnChain;
228
+ const voucher = state.highestVoucher?.cumulativeAmount ?? state.settledOnChain;
229
+ const capture = [state.spent, voucher, state.deposit].reduce((a, b) => (a < b ? a : b));
230
+ return capture > state.settledOnChain ? capture : state.settledOnChain;
230
231
  }
231
232
  /** Whether the payer requested a close, after which the escrow's grace period runs. */
232
233
  function closing(state) {
233
234
  return closeRequest(state) !== 0n;
234
235
  }
235
- /**
236
- * The payer's close request: `closeRequestedAt`, or `0n` without one. The server's own
237
- * cooperative-close marker ({@link State.pendingCloseAt}) is not one while that close may still
238
- * land ({@link pendingClose}): it captures the vouchers itself. An on-chain close request merged
239
- * into the marker keeps its timestamp when the payer's is not later, so once the marker can no
240
- * longer land, it counts as one.
241
- */
236
+ /** The payer's observed close request, never an expired server-owned marker. */
242
237
  function closeRequest(state) {
243
238
  if (pendingClose(state))
244
239
  return 0n;
245
- return BigInt(state.closeRequestedAt ?? 0n);
240
+ if (state.onChainCloseRequestedAt !== undefined)
241
+ return BigInt(state.onChainCloseRequestedAt);
242
+ const requested = BigInt(state.closeRequestedAt ?? 0n);
243
+ return state.pendingCloseAt !== undefined && requested === BigInt(state.pendingCloseAt)
244
+ ? 0n
245
+ : requested;
246
246
  }
247
247
  /**
248
248
  * Unix milliseconds at which the server's close marker stops counting as {@link pendingClose},
@@ -271,13 +271,7 @@ async function wakeBy(storage, at) {
271
271
  * settlement could, so settling meanwhile only spends gas.
272
272
  */
273
273
  export function pendingClose(state, now = Date.now()) {
274
- if (state.pendingCloseAt === undefined || state.finalized)
275
- return false;
276
- const requestedAt = BigInt(state.closeRequestedAt ?? 0n);
277
- if (requestedAt === 0n || requestedAt !== BigInt(state.pendingCloseAt))
278
- return false;
279
- const expiresAt = Number(requestedAt) + pendingCloseValiditySeconds + pendingCloseClockSkewSeconds;
280
- return Math.floor(now / 1000) <= expiresAt;
274
+ return hasPendingClose(state, now);
281
275
  }
282
276
  /** The unsettled amount that sends a channel at once: `max(10% of deposit, minUnsettledAmount)`. */
283
277
  function threshold(state, settlement) {
@@ -1,9 +1,10 @@
1
- import { type Address } from 'viem';
1
+ import { type Address, type Hex } from 'viem';
2
2
  import type { MaybePromise } from '../internal/types.js';
3
3
  import * as Store from '../Store.js';
4
4
  import type { TransactionClient } from '../tempo/session/precompile/Chain.js';
5
5
  import type { ResolveSessionChannelId } from '../tempo/session/server/RequestState.js';
6
6
  import { settle as settleChannel, type SettlementTransactionOptions } from '../tempo/session/server/Settlement.js';
7
+ import { type ChannelStore } from './ChannelStore.js';
7
8
  /**
8
9
  * Tempo session channel storage on a {@link ChannelStore} Durable Object namespace, to spread
9
10
  * into `tempo.session()`: `store` keeps each channel in its own object, which schedules its
@@ -44,9 +45,24 @@ export declare namespace channels {
44
45
  store: Store.AtomicStore;
45
46
  };
46
47
  }
48
+ /**
49
+ * Queues unpaid channels dropped by older settlement schedulers. Run once after upgrading,
50
+ * using every channel ID from the application's channel registry or escrow opening events;
51
+ * dormant Durable Objects cannot enumerate or wake themselves. Safe to rerun after a send failure.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * await backfillSettlement(channelIds, { store: channels(env.MPPX_CHANNELS).store, queue: env.MPPX_SETTLEMENT_QUEUE })
56
+ * ```
57
+ */
58
+ export declare function backfillSettlement(channelIds: Iterable<Hex> | AsyncIterable<Hex>, parameters: {
59
+ store: Store.AtomicStore;
60
+ queue: ChannelStore.Queue;
61
+ }): Promise<number>;
47
62
  /**
48
63
  * Settles the channels of a settlement queue batch on-chain, from the Worker's `queue()`
49
- * handler. Each message is acknowledged once its channel settled or has nothing left to
64
+ * handler. A voucher above recorded spend uses a payee close that captures only that spend
65
+ * and refunds the remaining deposit. Each message is acknowledged once its channel settled or has nothing left to
50
66
  * settle, and when settlement cannot succeed (the channel is gone or has no voucher); any
51
67
  * other failure, such as a fee over the fee payer's cap, retries it after 30 s, doubling up
52
68
  * to 10 minutes. The {@link ChannelStore} watchdog sends a channel again if its job never settles it.
@@ -66,6 +82,8 @@ export declare function settle(batch: settle.Batch, parameters: settle.Parameter
66
82
  export declare namespace settle {
67
83
  /** Parameters of {@link settle}: the channel store, a client, and the settlement transaction's options. */
68
84
  type Parameters = SettlementTransactionOptions & {
85
+ /** Earliest escrow block for channels without a supervision checkpoint; must precede every channel opening. @default 0n */
86
+ closeSearchFromBlock?: bigint | undefined;
69
87
  /** Returns an account-bearing client for the channel's chain. */
70
88
  getClient: (parameters: {
71
89
  chainId: number;
@@ -3,7 +3,8 @@ import { ChannelNotFoundError, VerificationFailedError } from '../Errors.js';
3
3
  import * as Store from '../Store.js';
4
4
  import { parsePkhSource } from '../tempo/internal/proof.js';
5
5
  import { tip20ChannelEscrow } from '../tempo/session/precompile/Protocol.js';
6
- import { isPrecompileState } from '../tempo/session/server/ChannelStore.js';
6
+ import { isPrecompileState, normalizeChannelId, resolveSettleableVoucher, } from '../tempo/session/server/ChannelStore.js';
7
+ import * as CloseSupervisor from '../tempo/session/server/CloseSupervisor.js';
7
8
  import { settle as settleChannel, SettlementCheckpointError, } from '../tempo/session/server/Settlement.js';
8
9
  import { isChannelState, pendingClose, unsettledAmount } from './ChannelStore.js';
9
10
  /**
@@ -155,9 +156,32 @@ export function channels(namespace, options) {
155
156
  };
156
157
  return { resolveChannelId, store };
157
158
  }
159
+ /**
160
+ * Queues unpaid channels dropped by older settlement schedulers. Run once after upgrading,
161
+ * using every channel ID from the application's channel registry or escrow opening events;
162
+ * dormant Durable Objects cannot enumerate or wake themselves. Safe to rerun after a send failure.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * await backfillSettlement(channelIds, { store: channels(env.MPPX_CHANNELS).store, queue: env.MPPX_SETTLEMENT_QUEUE })
167
+ * ```
168
+ */
169
+ export async function backfillSettlement(channelIds, parameters) {
170
+ let queued = 0;
171
+ for await (const id of channelIds) {
172
+ const channelId = normalizeChannelId(id);
173
+ const state = await parameters.store.get(channelId);
174
+ if (!isChannelState(state) || state.finalized || unsettledAmount(state) <= 0n)
175
+ continue;
176
+ await parameters.queue.send({ channelId });
177
+ queued++;
178
+ }
179
+ return queued;
180
+ }
158
181
  /**
159
182
  * Settles the channels of a settlement queue batch on-chain, from the Worker's `queue()`
160
- * handler. Each message is acknowledged once its channel settled or has nothing left to
183
+ * handler. A voucher above recorded spend uses a payee close that captures only that spend
184
+ * and refunds the remaining deposit. Each message is acknowledged once its channel settled or has nothing left to
161
185
  * settle, and when settlement cannot succeed (the channel is gone or has no voucher); any
162
186
  * other failure, such as a fee over the fee payer's cap, retries it after 30 s, doubling up
163
187
  * to 10 minutes. The {@link ChannelStore} watchdog sends a channel again if its job never settles it.
@@ -174,7 +198,7 @@ export function channels(namespace, options) {
174
198
  * ```
175
199
  */
176
200
  export async function settle(batch, parameters) {
177
- const { getClient, settle: settle_ = settleChannel, store, ...options } = parameters;
201
+ const { getClient, settle: settle_ = settleChannel, store, closeSearchFromBlock = 0n, ...options } = parameters;
178
202
  for (const message of batch.messages) {
179
203
  try {
180
204
  const channelId = message.body
@@ -207,7 +231,26 @@ export async function settle(batch, parameters) {
207
231
  void renew(store, channelId, leaseOwner).catch(() => undefined);
208
232
  }, settlementLeaseMs / 2);
209
233
  try {
210
- await settle_(store, await getClient({ chainId: state.chainId }), channelId, options);
234
+ const client = await getClient({ chainId: state.chainId });
235
+ if (isPrecompileState(state) && !resolveSettleableVoucher(state)) {
236
+ const result = await CloseSupervisor.superviseCloses({
237
+ ...options,
238
+ channelIds: [channelId],
239
+ client,
240
+ closeUnsettled: true,
241
+ settlementLeaseOwner: leaseOwner,
242
+ previousBlock: closeSearchFromBlock,
243
+ closeSearchMarginBlocks: 0n,
244
+ store,
245
+ });
246
+ if (!['closed', 'settled', 'unrecovered', 'finalized', 'missing'].includes(result.channels[0]?.outcome ?? 'failed')) {
247
+ message.retry({ delaySeconds: 60 });
248
+ continue;
249
+ }
250
+ }
251
+ else {
252
+ await settle_(store, client, channelId, options);
253
+ }
211
254
  }
212
255
  finally {
213
256
  clearInterval(renewal);
@@ -1,5 +1,5 @@
1
1
  /** Durable Object class that stores Tempo session channels and schedules their settlement. */
2
2
  export { ChannelStore } from './ChannelStore.js';
3
3
  /** Channel store and lookup for `tempo.session()`, and the settlement queue consumer. */
4
- export { channels, settle } from './Channels.js';
4
+ export { backfillSettlement, channels, settle } from './Channels.js';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,5 @@
1
1
  /** Durable Object class that stores Tempo session channels and schedules their settlement. */
2
2
  export { ChannelStore } from './ChannelStore.js';
3
3
  /** Channel store and lookup for `tempo.session()`, and the settlement queue consumer. */
4
- export { channels, settle } from './Channels.js';
4
+ export { backfillSettlement, channels, settle } from './Channels.js';
5
5
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,11 @@
1
1
  import * as z from '../zod.js';
2
+ declare const PaymentOffer: z.ZodMiniObject<{
3
+ amount: z.ZodMiniOptional<z.ZodMiniUnion<readonly [z.ZodMiniNull, z.ZodMiniString<string>]>>;
4
+ currency: z.ZodMiniOptional<z.ZodMiniString<string>>;
5
+ description: z.ZodMiniOptional<z.ZodMiniString<string>>;
6
+ intent: z.ZodMiniOptional<z.ZodMiniString<string>>;
7
+ method: z.ZodMiniOptional<z.ZodMiniString<string>>;
8
+ }, z.core.$loose>;
2
9
  /**
3
10
  * Schema for the `x-payment-info` OpenAPI extension on an operation.
4
11
  *
@@ -19,7 +26,14 @@ export declare const PaymentInfo: z.ZodMiniPipe<z.ZodMiniObject<{
19
26
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
20
27
  }, z.core.$loose>>>;
21
28
  }, z.core.$loose>, z.ZodMiniTransform<{
22
- offers: Record<string, unknown>[];
29
+ offers: {
30
+ [x: string]: unknown;
31
+ amount?: string | null | undefined;
32
+ currency?: string | undefined;
33
+ description?: string | undefined;
34
+ intent?: string | undefined;
35
+ method?: string | undefined;
36
+ }[];
23
37
  }, {
24
38
  [x: string]: unknown;
25
39
  amount?: string | null | undefined;
@@ -83,7 +97,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
83
97
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
84
98
  }, z.core.$loose>>>;
85
99
  }, z.core.$loose>, z.ZodMiniTransform<{
86
- offers: Record<string, unknown>[];
100
+ offers: {
101
+ [x: string]: unknown;
102
+ amount?: string | null | undefined;
103
+ currency?: string | undefined;
104
+ description?: string | undefined;
105
+ intent?: string | undefined;
106
+ method?: string | undefined;
107
+ }[];
87
108
  }, {
88
109
  [x: string]: unknown;
89
110
  amount?: string | null | undefined;
@@ -119,7 +140,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
119
140
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
120
141
  }, z.core.$loose>>>;
121
142
  }, z.core.$loose>, z.ZodMiniTransform<{
122
- offers: Record<string, unknown>[];
143
+ offers: {
144
+ [x: string]: unknown;
145
+ amount?: string | null | undefined;
146
+ currency?: string | undefined;
147
+ description?: string | undefined;
148
+ intent?: string | undefined;
149
+ method?: string | undefined;
150
+ }[];
123
151
  }, {
124
152
  [x: string]: unknown;
125
153
  amount?: string | null | undefined;
@@ -155,7 +183,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
155
183
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
156
184
  }, z.core.$loose>>>;
157
185
  }, z.core.$loose>, z.ZodMiniTransform<{
158
- offers: Record<string, unknown>[];
186
+ offers: {
187
+ [x: string]: unknown;
188
+ amount?: string | null | undefined;
189
+ currency?: string | undefined;
190
+ description?: string | undefined;
191
+ intent?: string | undefined;
192
+ method?: string | undefined;
193
+ }[];
159
194
  }, {
160
195
  [x: string]: unknown;
161
196
  amount?: string | null | undefined;
@@ -191,7 +226,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
191
226
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
192
227
  }, z.core.$loose>>>;
193
228
  }, z.core.$loose>, z.ZodMiniTransform<{
194
- offers: Record<string, unknown>[];
229
+ offers: {
230
+ [x: string]: unknown;
231
+ amount?: string | null | undefined;
232
+ currency?: string | undefined;
233
+ description?: string | undefined;
234
+ intent?: string | undefined;
235
+ method?: string | undefined;
236
+ }[];
195
237
  }, {
196
238
  [x: string]: unknown;
197
239
  amount?: string | null | undefined;
@@ -227,7 +269,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
227
269
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
228
270
  }, z.core.$loose>>>;
229
271
  }, z.core.$loose>, z.ZodMiniTransform<{
230
- offers: Record<string, unknown>[];
272
+ offers: {
273
+ [x: string]: unknown;
274
+ amount?: string | null | undefined;
275
+ currency?: string | undefined;
276
+ description?: string | undefined;
277
+ intent?: string | undefined;
278
+ method?: string | undefined;
279
+ }[];
231
280
  }, {
232
281
  [x: string]: unknown;
233
282
  amount?: string | null | undefined;
@@ -263,7 +312,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
263
312
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
264
313
  }, z.core.$loose>>>;
265
314
  }, z.core.$loose>, z.ZodMiniTransform<{
266
- offers: Record<string, unknown>[];
315
+ offers: {
316
+ [x: string]: unknown;
317
+ amount?: string | null | undefined;
318
+ currency?: string | undefined;
319
+ description?: string | undefined;
320
+ intent?: string | undefined;
321
+ method?: string | undefined;
322
+ }[];
267
323
  }, {
268
324
  [x: string]: unknown;
269
325
  amount?: string | null | undefined;
@@ -299,7 +355,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
299
355
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
300
356
  }, z.core.$loose>>>;
301
357
  }, z.core.$loose>, z.ZodMiniTransform<{
302
- offers: Record<string, unknown>[];
358
+ offers: {
359
+ [x: string]: unknown;
360
+ amount?: string | null | undefined;
361
+ currency?: string | undefined;
362
+ description?: string | undefined;
363
+ intent?: string | undefined;
364
+ method?: string | undefined;
365
+ }[];
303
366
  }, {
304
367
  [x: string]: unknown;
305
368
  amount?: string | null | undefined;
@@ -335,7 +398,14 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
335
398
  method: z.ZodMiniOptional<z.ZodMiniString<string>>;
336
399
  }, z.core.$loose>>>;
337
400
  }, z.core.$loose>, z.ZodMiniTransform<{
338
- offers: Record<string, unknown>[];
401
+ offers: {
402
+ [x: string]: unknown;
403
+ amount?: string | null | undefined;
404
+ currency?: string | undefined;
405
+ description?: string | undefined;
406
+ intent?: string | undefined;
407
+ method?: string | undefined;
408
+ }[];
339
409
  }, {
340
410
  [x: string]: unknown;
341
411
  amount?: string | null | undefined;
@@ -359,4 +429,41 @@ export declare const DiscoveryDocument: z.ZodMiniObject<{
359
429
  }, z.core.$loose>>>;
360
430
  }, z.core.$loose>;
361
431
  export type DiscoveryDocument = z.infer<typeof DiscoveryDocument>;
432
+ /** One offer from an operation's `x-payment-info`. Every field is optional; discovery is advisory. */
433
+ export type PaymentOffer = z.infer<typeof PaymentOffer>;
434
+ /** The HTTP methods an OpenAPI path item can describe. */
435
+ export type OperationMethod = 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace';
436
+ /** One operation of a discovery document, flattened for clients. */
437
+ export type Operation = {
438
+ /** The operation's HTTP method, lowercase as in OpenAPI. */
439
+ method: OperationMethod;
440
+ /** The operation's path, relative to the document's server. */
441
+ path: string;
442
+ /** What the operation costs. Empty when it has no `x-payment-info`. */
443
+ offers: PaymentOffer[];
444
+ /**
445
+ * The JSON Schema of an `application/json` request body (an object or a boolean schema), when it
446
+ * has one. Local `$ref`s to the body or schema are followed; nested ones point into the document.
447
+ */
448
+ requestSchema: Record<string, unknown> | boolean | undefined;
449
+ /** The operation's summary, when it has one. */
450
+ summary: string | undefined;
451
+ };
452
+ /**
453
+ * Lists every operation in a discovery document with its offers and JSON request schema.
454
+ *
455
+ * Accepts a raw `openapi.json` body or an already parsed {@link DiscoveryDocument}, and throws
456
+ * when the document is invalid. Prices are advisory: the 402 Challenge stays authoritative.
457
+ *
458
+ * @example
459
+ * ```ts
460
+ * import { listOperations } from 'mppx/discovery'
461
+ *
462
+ * const doc = await fetch('https://api.example.com/openapi.json').then((r) => r.json())
463
+ * for (const { method, path, offers } of listOperations(doc))
464
+ * console.log(method, path, offers[0]?.amount)
465
+ * ```
466
+ */
467
+ export declare function listOperations(document: unknown): Operation[];
468
+ export {};
362
469
  //# sourceMappingURL=Discovery.d.ts.map
@@ -80,4 +80,173 @@ export const DiscoveryDocument = z.looseObject({
80
80
  'x-service-info': z.optional(ServiceInfo),
81
81
  paths: z.optional(z.record(z.string(), PathItem)),
82
82
  });
83
+ const operationMethods = [
84
+ 'get',
85
+ 'post',
86
+ 'put',
87
+ 'patch',
88
+ 'delete',
89
+ 'head',
90
+ 'options',
91
+ 'trace',
92
+ ];
93
+ /**
94
+ * Lists every operation in a discovery document with its offers and JSON request schema.
95
+ *
96
+ * Accepts a raw `openapi.json` body or an already parsed {@link DiscoveryDocument}, and throws
97
+ * when the document is invalid. Prices are advisory: the 402 Challenge stays authoritative.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import { listOperations } from 'mppx/discovery'
102
+ *
103
+ * const doc = await fetch('https://api.example.com/openapi.json').then((r) => r.json())
104
+ * for (const { method, path, offers } of listOperations(doc))
105
+ * console.log(method, path, offers[0]?.amount)
106
+ * ```
107
+ */
108
+ export function listOperations(document) {
109
+ const doc = DiscoveryDocument.parse(document);
110
+ const resolve = resolver(doc);
111
+ const merged = new WeakMap();
112
+ const operations = [];
113
+ for (const [path, entry] of Object.entries(doc.paths ?? {})) {
114
+ // OpenAPI paths start with `/` and are relative to the server; skip anything else, such as an
115
+ // absolute URL, rather than hand a client a path that points somewhere unexpected.
116
+ if (!path.startsWith('/') || path.startsWith('//'))
117
+ continue;
118
+ // A Path Item can itself be a `$ref`, such as to `#/components/pathItems/...`.
119
+ // A Path Item `$ref` merges with fields declared next to it (OpenAPI 3.1 leaves conflicts
120
+ // undefined; inline fields win). An invalid target throws, as an invalid inline Path Item does;
121
+ // an unresolvable one contributes nothing.
122
+ let item = entry;
123
+ if (entry.$ref !== undefined) {
124
+ const { $ref: _, ...inline } = entry;
125
+ const target = resolve(entry);
126
+ item = { ...(target === undefined ? {} : PathItem.parse(target)), ...inline };
127
+ }
128
+ for (const method of operationMethods) {
129
+ const operation = item[method];
130
+ if (!operation)
131
+ continue;
132
+ operations.push({
133
+ method,
134
+ path,
135
+ offers: operation['x-payment-info']?.offers ?? [],
136
+ requestSchema: jsonSchema(resolve, merged, operation.requestBody),
137
+ summary: operation.summary,
138
+ });
139
+ }
140
+ }
141
+ return operations;
142
+ }
143
+ /** The `application/json` schema of an OpenAPI request body, if any, following local `$ref`s. */
144
+ function jsonSchema(resolve, merged, requestBody) {
145
+ const body = resolve(requestBody);
146
+ const raw = jsonContent(body?.content)?.schema;
147
+ const schema = resolve(raw);
148
+ if (typeof raw === 'boolean')
149
+ return raw;
150
+ if (typeof schema !== 'boolean' && !isObject(schema))
151
+ return undefined;
152
+ if (!isObject(raw))
153
+ return undefined;
154
+ // JSON Schema 2020-12 applies keywords next to `$ref`: keep them alongside the target.
155
+ const object = raw;
156
+ if (object === schema)
157
+ return schema;
158
+ // `false` rejects everything whatever its siblings say; a `true` target adds nothing to them.
159
+ if (schema === false)
160
+ return false;
161
+ // Operations that share a schema object share one merged result, copied once.
162
+ const cached = merged.get(object);
163
+ if (cached)
164
+ return cached;
165
+ const { $ref: _, ...siblings } = object;
166
+ const allOf = Array.isArray(siblings.allOf) ? siblings.allOf : [];
167
+ const result = Object.keys(siblings).length === 0
168
+ ? schema
169
+ : schema === true
170
+ ? siblings
171
+ : { ...siblings, allOf: [schema, ...allOf] };
172
+ merged.set(object, result);
173
+ return result;
174
+ }
175
+ /**
176
+ * Returns a function that follows Reference Objects to local JSON Pointers (`#/components/...`)
177
+ * in the document. Nested references inside a result stay as they are, and a reference that is
178
+ * remote, missing or circular resolves to `undefined`. Results are cached per reference, so
179
+ * operations that share a reference chain walk it once.
180
+ */
181
+ function resolver(doc) {
182
+ const cache = new Map();
183
+ function resolveValue(value) {
184
+ // A loop rather than recursion, so a long chain can't overflow the stack.
185
+ const chain = new Set();
186
+ let current = value;
187
+ let result;
188
+ for (;;) {
189
+ const ref = current?.$ref;
190
+ if (typeof ref !== 'string') {
191
+ result = current;
192
+ break;
193
+ }
194
+ if (cache.has(ref)) {
195
+ result = cache.get(ref);
196
+ break;
197
+ }
198
+ if (!ref.startsWith('#') || chain.has(ref)) {
199
+ result = undefined;
200
+ break;
201
+ }
202
+ chain.add(ref);
203
+ current = pointer(ref);
204
+ }
205
+ for (const ref of chain)
206
+ cache.set(ref, result);
207
+ return result;
208
+ }
209
+ function pointer(ref) {
210
+ // RFC 6901: percent-decode the URI fragment first, then split it into reference tokens.
211
+ const fragment = decodeFragment(ref.slice(1));
212
+ if (fragment === undefined || !fragment.startsWith('/'))
213
+ return undefined;
214
+ let target = doc;
215
+ for (const part of fragment.slice(1).split('/')) {
216
+ const key = part.replaceAll('~1', '/').replaceAll('~0', '~');
217
+ if (!target || typeof target !== 'object' || !Object.hasOwn(target, key))
218
+ return undefined;
219
+ target = target[key];
220
+ }
221
+ return target;
222
+ }
223
+ return resolveValue;
224
+ }
225
+ /** Percent-decodes a URI fragment, or `undefined` when its encoding is malformed. */
226
+ function decodeFragment(fragment) {
227
+ try {
228
+ return decodeURIComponent(fragment);
229
+ }
230
+ catch {
231
+ return undefined;
232
+ }
233
+ }
234
+ /** Whether a value is a plain JSON object, not an array or `null`. */
235
+ function isObject(value) {
236
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
237
+ }
238
+ /**
239
+ * The `application/json` entry of an OpenAPI `content` map. Media type keys match
240
+ * case-insensitively and may carry parameters, such as `application/json; charset=utf-8`.
241
+ */
242
+ function jsonContent(content) {
243
+ if (!isObject(content))
244
+ return undefined;
245
+ if (Object.hasOwn(content, 'application/json'))
246
+ return content['application/json'];
247
+ for (const [type, entry] of Object.entries(content))
248
+ if (type.split(';')[0].trim().toLowerCase() === 'application/json')
249
+ return entry;
250
+ return undefined;
251
+ }
83
252
  //# sourceMappingURL=Discovery.js.map