@andco/protocol 0.0.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.
Files changed (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +44 -0
  3. package/dist/authorization-preparation.d.ts +754 -0
  4. package/dist/authorization-preparation.d.ts.map +1 -0
  5. package/dist/authorization-preparation.js +187 -0
  6. package/dist/authorization.d.ts +99 -0
  7. package/dist/authorization.d.ts.map +1 -0
  8. package/dist/authorization.js +227 -0
  9. package/dist/automatic-charge.d.ts +314 -0
  10. package/dist/automatic-charge.d.ts.map +1 -0
  11. package/dist/automatic-charge.js +126 -0
  12. package/dist/bank-account-authorization.d.ts +6 -0
  13. package/dist/bank-account-authorization.d.ts.map +1 -0
  14. package/dist/bank-account-authorization.js +13 -0
  15. package/dist/callback-state.d.ts +10 -0
  16. package/dist/callback-state.d.ts.map +1 -0
  17. package/dist/callback-state.js +28 -0
  18. package/dist/consent.d.ts +48 -0
  19. package/dist/consent.d.ts.map +1 -0
  20. package/dist/consent.js +110 -0
  21. package/dist/constants.d.ts +17 -0
  22. package/dist/constants.d.ts.map +1 -0
  23. package/dist/constants.js +20 -0
  24. package/dist/errors.d.ts +70 -0
  25. package/dist/errors.d.ts.map +1 -0
  26. package/dist/errors.js +80 -0
  27. package/dist/index.d.ts +33 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +32 -0
  30. package/dist/intent-input.d.ts +637 -0
  31. package/dist/intent-input.d.ts.map +1 -0
  32. package/dist/intent-input.js +101 -0
  33. package/dist/messages/authorization-response.d.ts +12 -0
  34. package/dist/messages/authorization-response.d.ts.map +1 -0
  35. package/dist/messages/authorization-response.js +9 -0
  36. package/dist/messages/base.d.ts +31 -0
  37. package/dist/messages/base.d.ts.map +1 -0
  38. package/dist/messages/base.js +30 -0
  39. package/dist/messages/click.d.ts +11 -0
  40. package/dist/messages/click.d.ts.map +1 -0
  41. package/dist/messages/click.js +8 -0
  42. package/dist/messages/error.d.ts +13 -0
  43. package/dist/messages/error.d.ts.map +1 -0
  44. package/dist/messages/error.js +9 -0
  45. package/dist/messages/index.d.ts +75 -0
  46. package/dist/messages/index.d.ts.map +1 -0
  47. package/dist/messages/index.js +27 -0
  48. package/dist/messages/init.d.ts +9 -0
  49. package/dist/messages/init.d.ts.map +1 -0
  50. package/dist/messages/init.js +6 -0
  51. package/dist/messages/popup.d.ts +108 -0
  52. package/dist/messages/popup.d.ts.map +1 -0
  53. package/dist/messages/popup.js +62 -0
  54. package/dist/messages/ready.d.ts +9 -0
  55. package/dist/messages/ready.d.ts.map +1 -0
  56. package/dist/messages/ready.js +6 -0
  57. package/dist/messages/set-preferences.d.ts +16 -0
  58. package/dist/messages/set-preferences.d.ts.map +1 -0
  59. package/dist/messages/set-preferences.js +20 -0
  60. package/dist/miniapp-icon.d.ts +4 -0
  61. package/dist/miniapp-icon.d.ts.map +1 -0
  62. package/dist/miniapp-icon.js +68 -0
  63. package/dist/miniapp-manifest.d.ts +71 -0
  64. package/dist/miniapp-manifest.d.ts.map +1 -0
  65. package/dist/miniapp-manifest.js +46 -0
  66. package/dist/native-copy.d.ts +7 -0
  67. package/dist/native-copy.d.ts.map +1 -0
  68. package/dist/native-copy.js +436 -0
  69. package/dist/native-intent.d.ts +402 -0
  70. package/dist/native-intent.d.ts.map +1 -0
  71. package/dist/native-intent.js +410 -0
  72. package/dist/native.d.ts +55 -0
  73. package/dist/native.d.ts.map +1 -0
  74. package/dist/native.js +53 -0
  75. package/dist/oauth.d.ts +4 -0
  76. package/dist/oauth.d.ts.map +1 -0
  77. package/dist/oauth.js +3 -0
  78. package/dist/release.d.ts +3 -0
  79. package/dist/release.d.ts.map +1 -0
  80. package/dist/release.js +2 -0
  81. package/dist/scopes.d.ts +35 -0
  82. package/dist/scopes.d.ts.map +1 -0
  83. package/dist/scopes.js +15 -0
  84. package/dist/server.d.ts +9 -0
  85. package/dist/server.d.ts.map +1 -0
  86. package/dist/server.js +14 -0
  87. package/dist/transport/financial-events.d.ts +134 -0
  88. package/dist/transport/financial-events.d.ts.map +1 -0
  89. package/dist/transport/financial-events.js +120 -0
  90. package/dist/transport/generated/oauth-api.d.ts +1685 -0
  91. package/dist/transport/generated/oauth-api.d.ts.map +1 -0
  92. package/dist/transport/generated/oauth-api.js +5 -0
  93. package/dist/transport/index.d.ts +6 -0
  94. package/dist/transport/index.d.ts.map +1 -0
  95. package/dist/transport/index.js +5 -0
  96. package/dist/transport/intents.d.ts +81 -0
  97. package/dist/transport/intents.d.ts.map +1 -0
  98. package/dist/transport/intents.js +286 -0
  99. package/dist/transport/rest.d.ts +76 -0
  100. package/dist/transport/rest.d.ts.map +1 -0
  101. package/dist/transport/rest.js +48 -0
  102. package/dist/transport/runtime.d.ts +8 -0
  103. package/dist/transport/runtime.d.ts.map +1 -0
  104. package/dist/transport/runtime.js +16 -0
  105. package/dist/transport/webhooks.d.ts +27 -0
  106. package/dist/transport/webhooks.d.ts.map +1 -0
  107. package/dist/transport/webhooks.js +68 -0
  108. package/dist/urls.d.ts +71 -0
  109. package/dist/urls.d.ts.map +1 -0
  110. package/dist/urls.js +132 -0
  111. package/dist/userinfo.d.ts +11 -0
  112. package/dist/userinfo.d.ts.map +1 -0
  113. package/dist/userinfo.js +9 -0
  114. package/dist/utils.d.ts +20 -0
  115. package/dist/utils.d.ts.map +1 -0
  116. package/dist/utils.js +45 -0
  117. package/dist/webhook-input.d.ts +22 -0
  118. package/dist/webhook-input.d.ts.map +1 -0
  119. package/dist/webhook-input.js +11 -0
  120. package/dist/webhook-signature.d.ts +54 -0
  121. package/dist/webhook-signature.d.ts.map +1 -0
  122. package/dist/webhook-signature.js +74 -0
  123. package/dist/window-features.d.ts +28 -0
  124. package/dist/window-features.d.ts.map +1 -0
  125. package/dist/window-features.js +55 -0
  126. package/package.json +63 -0
@@ -0,0 +1,410 @@
1
+ import * as v from "valibot";
2
+ import { WithdrawalConfirmationSchema } from "./intent-input.js";
3
+ import { ANDCO_NATIVE_TEXT as t } from "./native-copy.js";
4
+ import { SafeURL } from "./urls.js";
5
+ const text = /* @__PURE__ */ v.string();
6
+ const money = /* @__PURE__ */ v.pipe(text, v.regex(/^[0-9]+$/));
7
+ const uuid = /* @__PURE__ */ v.pipe(text, v.uuid());
8
+ const account = /* @__PURE__ */ v.object({
9
+ account_holder_id: text,
10
+ account_holder_name: text,
11
+ account_kind: v.picklist(["checking", "debit", "savings"]),
12
+ account_number: text,
13
+ bank_id: text,
14
+ country: v.literal("CL"),
15
+ });
16
+ const base = {
17
+ id: uuid,
18
+ status: v.picklist([
19
+ "requires_action",
20
+ "processing.confirmed",
21
+ "processing.settling",
22
+ "processing.reversing",
23
+ "processing.reconciling",
24
+ "succeeded",
25
+ "completed",
26
+ "closed",
27
+ "failed",
28
+ "failed.insufficient_funds",
29
+ "cancelled",
30
+ "expired",
31
+ ]),
32
+ amount: v.object({ currency: v.literal("CLP"), suggested: money, editable: v.boolean() }),
33
+ fee: v.object({ currency: v.literal("CLP"), amount: money }),
34
+ note: v.optional(v.object({ suggested: text, editable: v.boolean() })),
35
+ expires_at: v.nullable(text),
36
+ server_time: text,
37
+ can_confirm: v.boolean(),
38
+ project: v.object({ id: uuid, name: text }),
39
+ };
40
+ /** Authenticated Host presentation; bank commands and account ownership remain on Platform. */
41
+ export const AndCoNativeIntentPreparationSchema = /* @__PURE__ */ v.object({
42
+ intent: v.variant("type", [
43
+ v.object({
44
+ ...base,
45
+ type: v.literal("deposit"),
46
+ amount: v.nullable(v.object({ ...base.amount.entries, confirmed: v.nullable(money), frozen_at: v.nullable(text) })),
47
+ destination: v.object({ ...account.entries, bank_account_id: uuid }),
48
+ progress: v.object({ credited: money, remaining: v.nullable(money) }),
49
+ closure: v.nullable(v.object({ closed_at: text, total: money })),
50
+ completion: v.nullable(v.object({ completed_at: text, total: money })),
51
+ transactions: v.array(v.object({
52
+ id: uuid,
53
+ received_at: text,
54
+ note: v.nullable(text),
55
+ outcome: v.picklist(["credited", "reversed"]),
56
+ receipt_time_source: v.picklist(["bank_timestamp", "unknown"]),
57
+ account_holder_name_masked: text,
58
+ account_number_masked: text,
59
+ bank_id: text,
60
+ amount: money,
61
+ currency: v.literal("CLP"),
62
+ })),
63
+ }),
64
+ v.object({
65
+ ...base,
66
+ type: v.literal("withdrawal"),
67
+ beneficiary: v.object({ ...account.entries, editable: v.boolean() }),
68
+ source: v.optional(v.union([v.object({ bank_account_id: uuid }), account])),
69
+ }),
70
+ ]),
71
+ sources: v.array(v.object({ id: uuid, number: text, name: v.nullable(text) })),
72
+ checklist: v.nullable(v.object({
73
+ accountId: uuid,
74
+ version: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)),
75
+ credits: v.array(v.object({
76
+ movementId: uuid,
77
+ transactionId: text,
78
+ amount: money,
79
+ receivedAt: text,
80
+ note: v.nullable(text),
81
+ assignedIntentId: v.nullable(uuid),
82
+ assignedProjectName: v.nullable(text),
83
+ unavailableReason: v.nullable(text),
84
+ })),
85
+ otherRequests: v.array(v.object({ id: uuid, projectName: text, target: v.nullable(money) })),
86
+ })),
87
+ funding: v.optional(v.object({
88
+ commandId: uuid,
89
+ pendingSourceId: v.nullable(uuid),
90
+ pendingAmount: v.nullable(money),
91
+ pendingNote: v.nullable(text),
92
+ completed: v.boolean(),
93
+ })),
94
+ confirmedNote: v.nullable(text),
95
+ sourceEditable: v.boolean(),
96
+ banks: v.array(v.object({ id: text, name: text })),
97
+ retryable: v.boolean(),
98
+ developmentDeposit: v.boolean(),
99
+ });
100
+ /** Explicit commands supported by the current web presentation. */
101
+ export const AndCoNativeIntentCommandSchema = /* @__PURE__ */ v.variant("action", [
102
+ v.strictObject({
103
+ action: v.literal("fund_deposit"),
104
+ commandId: v.optional(uuid),
105
+ sourceAccountId: uuid,
106
+ amount: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(Number.MAX_SAFE_INTEGER)),
107
+ note: v.optional(v.pipe(text, v.maxLength(140))),
108
+ }),
109
+ v.strictObject({
110
+ action: v.literal("confirm_withdrawal"),
111
+ sourceAccountId: WithdrawalConfirmationSchema.entries.source_account_id,
112
+ amount: WithdrawalConfirmationSchema.entries.amount,
113
+ beneficiary: WithdrawalConfirmationSchema.entries.beneficiary,
114
+ note: WithdrawalConfirmationSchema.entries.note,
115
+ }),
116
+ v.strictObject({ action: v.literal("fund_development_deposit") }),
117
+ v.strictObject({ action: v.literal("close_deposit") }),
118
+ v.strictObject({
119
+ action: v.literal("confirm_deposit_target"),
120
+ amount: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(Number.MAX_SAFE_INTEGER)),
121
+ expectedTarget: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(Number.MAX_SAFE_INTEGER)),
122
+ }),
123
+ v.strictObject({
124
+ action: v.literal("assign_deposit_credits"),
125
+ expectedVersion: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)),
126
+ selectedMovements: v.pipe(v.array(uuid), v.check((ids) => new Set(ids).size === ids.length)),
127
+ }),
128
+ ]);
129
+ class NativeIntentRequestError extends Error {
130
+ status;
131
+ constructor(message, status) {
132
+ super(message);
133
+ this.status = status;
134
+ }
135
+ }
136
+ /** Recognizes only the canonical Intent path, never a generic trusted-origin URL. */
137
+ export function ANDCO_NATIVE_INTENT_ID(value, bankOrigin) {
138
+ try {
139
+ const url = new SafeURL(value);
140
+ const match = /^\/oauth\/intents\/([0-9a-f-]{36})$/i.exec(url.pathname);
141
+ return url.origin === new SafeURL(bankOrigin).origin && match && v.safeParse(uuid, match[1]).success
142
+ ? match[1]
143
+ : null;
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ }
149
+ /** Validates a presentation's callbacks against the active Miniapp, independently of the Intent's authority. */
150
+ export function ANDCO_NATIVE_INTENT_PRESENTATION(value, bankOrigin, miniappOrigin) {
151
+ const id = ANDCO_NATIVE_INTENT_ID(value, bankOrigin);
152
+ if (!id)
153
+ throw new Error("La URL no corresponde a una operación de Andco.");
154
+ const url = new URL(value);
155
+ const returnUri = new SafeURL(url.searchParams.get("return_uri") ?? "");
156
+ const errorReturnUri = new SafeURL(url.searchParams.get("error_return_uri") ?? "");
157
+ const state = url.searchParams.get("state");
158
+ const presentation = url.searchParams.get("presentation");
159
+ if (returnUri.origin !== new URL(miniappOrigin).origin ||
160
+ errorReturnUri.origin !== returnUri.origin ||
161
+ returnUri.username ||
162
+ returnUri.password ||
163
+ errorReturnUri.username ||
164
+ errorReturnUri.password ||
165
+ !state ||
166
+ !/^[A-Za-z0-9._~-]{16,2048}$/.test(state) ||
167
+ (presentation !== "popup" && presentation !== "redirect")) {
168
+ throw new Error("La operación no tiene un retorno válido para esta Miniapp. Iníciala nuevamente desde la aplicación.");
169
+ }
170
+ return { id, returnUri: returnUri.href, errorReturnUri: errorReturnUri.href, state, presentation };
171
+ }
172
+ /** Returns to the original document without changing the financial operation. */
173
+ export function ANDCO_NATIVE_INTENT_CALLBACK(presentation, result) {
174
+ const url = new URL(result === "complete" ? presentation.returnUri : presentation.errorReturnUri);
175
+ url.searchParams.set("andco_intent_result", result);
176
+ url.searchParams.set("intent_id", presentation.id);
177
+ url.searchParams.set("state", presentation.state);
178
+ return url.href;
179
+ }
180
+ /** Reads the current state or submits one explicit command; commands are never retried automatically. */
181
+ export async function requestAndCoNativeIntent(options) {
182
+ const url = new URL(`/api/host/intents/${options.presentation.id}`, options.bankOrigin);
183
+ url.searchParams.set("return_uri", options.presentation.returnUri);
184
+ url.searchParams.set("error_return_uri", options.presentation.errorReturnUri);
185
+ const response = await (options.fetcher ?? fetch)(url, {
186
+ method: options.command ? "POST" : "GET",
187
+ headers: {
188
+ Accept: "application/json",
189
+ "Content-Type": "application/json",
190
+ Authorization: `Bearer ${options.accessToken}`,
191
+ },
192
+ body: options.command ? JSON.stringify(v.parse(AndCoNativeIntentCommandSchema, options.command)) : undefined,
193
+ });
194
+ const body = await response.json();
195
+ if (!response.ok) {
196
+ const parsed = v.safeParse(v.object({ error: v.object({ message: text }) }), body);
197
+ throw new NativeIntentRequestError(parsed.success
198
+ ? parsed.output.error.message
199
+ : "No fue posible consultar la operación. Actualiza e inténtalo nuevamente.", response.status);
200
+ }
201
+ return v.parse(AndCoNativeIntentPreparationSchema, body);
202
+ }
203
+ /** A mounted native presentation; disposing it never changes or retries the financial operation. */
204
+ export class AndCoNativeIntentSession {
205
+ load;
206
+ snapshot = {
207
+ data: null,
208
+ pending: false,
209
+ error: null,
210
+ };
211
+ listeners = new Set();
212
+ disposed = false;
213
+ reading;
214
+ timer;
215
+ constructor(load) {
216
+ this.load = load;
217
+ }
218
+ subscribe(listener) {
219
+ this.listeners.add(listener);
220
+ return () => {
221
+ this.listeners.delete(listener);
222
+ };
223
+ }
224
+ publish(value) {
225
+ if (this.disposed)
226
+ return;
227
+ this.snapshot = value;
228
+ for (const listener of this.listeners)
229
+ listener();
230
+ }
231
+ async refresh() {
232
+ if (this.disposed || this.snapshot.pending)
233
+ return;
234
+ if (this.reading)
235
+ return this.reading;
236
+ clearTimeout(this.timer);
237
+ this.reading = (async () => {
238
+ try {
239
+ this.publish({ ...this.snapshot, data: await this.load(), error: null });
240
+ }
241
+ catch (error) {
242
+ this.publish({
243
+ ...this.snapshot,
244
+ error: error instanceof Error ? error.message : "No fue posible consultar la operación.",
245
+ });
246
+ }
247
+ finally {
248
+ if (!this.disposed)
249
+ this.timer = setTimeout(() => void this.refresh(), 2000);
250
+ }
251
+ })();
252
+ try {
253
+ await this.reading;
254
+ }
255
+ finally {
256
+ this.reading = undefined;
257
+ }
258
+ }
259
+ async submit(command) {
260
+ if (this.disposed || this.snapshot.pending)
261
+ return;
262
+ await this.reading;
263
+ if (this.disposed || this.snapshot.pending)
264
+ return;
265
+ if (this.snapshot.retryCommand && this.snapshot.retryCommand.action !== command.action) {
266
+ this.publish({ ...this.snapshot, error: t("Revisa la operación pendiente antes de iniciar otra acción.") });
267
+ return;
268
+ }
269
+ clearTimeout(this.timer);
270
+ const submitted = this.snapshot.retryCommand ??
271
+ (command.action === "fund_deposit"
272
+ ? { ...command, commandId: command.commandId ?? this.snapshot.data?.funding?.commandId }
273
+ : command);
274
+ this.publish({ ...this.snapshot, pending: true, error: null });
275
+ try {
276
+ this.publish({ data: await this.load(submitted), pending: false, error: null, retryCommand: undefined });
277
+ }
278
+ catch (error) {
279
+ this.publish({
280
+ ...this.snapshot,
281
+ pending: false,
282
+ retryCommand: this.snapshot.retryCommand ??
283
+ ((submitted.action === "fund_deposit" || submitted.action === "confirm_withdrawal") &&
284
+ !(error instanceof NativeIntentRequestError && error.status < 500)
285
+ ? submitted
286
+ : undefined),
287
+ error: error instanceof Error ? error.message : "Actualiza para consultar el resultado.",
288
+ });
289
+ }
290
+ // After an uncertain command, keep its error visible until the user explicitly refreshes.
291
+ if (!this.disposed && !this.snapshot.error)
292
+ this.timer = setTimeout(() => void this.refresh(), 2000);
293
+ }
294
+ dispose() {
295
+ this.disposed = true;
296
+ clearTimeout(this.timer);
297
+ this.listeners.clear();
298
+ }
299
+ }
300
+ /** Server-authoritative lifecycle and display values used by both native renderers. */
301
+ export function ANDCO_NATIVE_INTENT_VIEW(data, now = Date.now(), observedAt = now) {
302
+ const intent = data.intent;
303
+ const remaining = intent.expires_at === null
304
+ ? null
305
+ : Math.max(0, Date.parse(intent.expires_at) - Date.parse(intent.server_time) - (now - observedAt));
306
+ const terminal = ["succeeded", "completed", "closed", "cancelled", "expired"].includes(intent.status) ||
307
+ intent.status.startsWith("failed");
308
+ const expired = intent.status === "expired" || (intent.status === "requires_action" && remaining === 0);
309
+ const processing = intent.status.startsWith("processing.");
310
+ const pendingFunding = Boolean(data.funding?.pendingSourceId);
311
+ const frozen = processing || pendingFunding;
312
+ return {
313
+ terminal,
314
+ expired,
315
+ processing,
316
+ frozen,
317
+ remaining,
318
+ canSubmit: (!terminal || pendingFunding) &&
319
+ (!expired || pendingFunding) &&
320
+ (intent.type === "deposit" ||
321
+ (!processing && intent.can_confirm) ||
322
+ (intent.status === "processing.confirmed" && data.retryable)),
323
+ title: intent.type === "deposit" ? t("Realizar un depósito") : t("Confirmar retiro"),
324
+ status: ["succeeded", "completed"].includes(intent.status)
325
+ ? t("Operación completada")
326
+ : expired
327
+ ? t("La solicitud venció")
328
+ : processing
329
+ ? t("Procesando la operación")
330
+ : terminal
331
+ ? t("La operación finalizó")
332
+ : t("Revisa los datos antes de continuar"),
333
+ };
334
+ }
335
+ /** Restores accepted command values; otherwise defaults only an unambiguous source. */
336
+ export function ANDCO_NATIVE_INTENT_FORM(data, retry) {
337
+ const intent = data.intent;
338
+ if (retry?.action === "fund_deposit")
339
+ return { source: retry.sourceAccountId, amount: String(retry.amount), note: retry.note ?? "", beneficiary: null };
340
+ const withdrawalRetry = retry?.action === "confirm_withdrawal" ? retry : undefined;
341
+ return {
342
+ source: withdrawalRetry?.sourceAccountId ??
343
+ data.funding?.pendingSourceId ??
344
+ (intent.type === "withdrawal" && intent.source && "bank_account_id" in intent.source
345
+ ? intent.source.bank_account_id
346
+ : data.sources.length === 1
347
+ ? data.sources[0]?.id
348
+ : undefined) ??
349
+ "",
350
+ amount: withdrawalRetry?.amount ??
351
+ data.funding?.pendingAmount ??
352
+ (intent.type === "deposit" ? (intent.progress.remaining ?? "") : intent.amount.suggested),
353
+ note: withdrawalRetry?.note ?? data.funding?.pendingNote ?? data.confirmedNote ?? intent.note?.suggested ?? "",
354
+ beneficiary: intent.type === "withdrawal" ? { ...intent.beneficiary, ...withdrawalRetry?.beneficiary } : null,
355
+ };
356
+ }
357
+ /** Builds an explicit command without resending editable values on a frozen withdrawal. */
358
+ export function ANDCO_NATIVE_INTENT_COMMAND(data, form) {
359
+ const intent = data.intent;
360
+ const frozen = intent.status.startsWith("processing.");
361
+ const beneficiary = form.beneficiary;
362
+ return v.parse(AndCoNativeIntentCommandSchema, intent.type === "deposit"
363
+ ? {
364
+ action: "fund_deposit",
365
+ sourceAccountId: form.source,
366
+ amount: Number(data.funding?.pendingAmount ?? intent.progress.remaining ?? form.amount),
367
+ note: form.note,
368
+ }
369
+ : {
370
+ action: "confirm_withdrawal",
371
+ sourceAccountId: form.source || undefined,
372
+ note: frozen ? undefined : form.note,
373
+ amount: !frozen && intent.amount.editable ? form.amount : undefined,
374
+ beneficiary: !frozen && intent.beneficiary.editable && beneficiary
375
+ ? {
376
+ country: beneficiary.country,
377
+ bank_id: beneficiary.bank_id,
378
+ account_kind: beneficiary.account_kind,
379
+ account_number: beneficiary.account_number,
380
+ account_holder_id: beneficiary.account_holder_id,
381
+ account_holder_name: beneficiary.account_holder_name,
382
+ }
383
+ : undefined,
384
+ });
385
+ }
386
+ /** Validates the proposed command while preserving an already accepted deposit's frozen amount. */
387
+ export function ANDCO_NATIVE_INTENT_FORM_VALID(data, form) {
388
+ if (data.intent.type === "withdrawal" && data.sourceEditable && !form.source)
389
+ return false;
390
+ try {
391
+ const command = ANDCO_NATIVE_INTENT_COMMAND(data, form);
392
+ return (command.action !== "fund_deposit" ||
393
+ Boolean(data.funding?.pendingSourceId) ||
394
+ (data.intent.type === "deposit" && data.intent.progress.remaining === null) ||
395
+ BigInt(command.amount) <= BigInt(data.intent.type === "deposit" ? (data.intent.progress.remaining ?? "0") : "0"));
396
+ }
397
+ catch {
398
+ return false;
399
+ }
400
+ }
401
+ /** Preserves the User's selection while a changed account version requires explicit review. */
402
+ export function ANDCO_NATIVE_DEPOSIT_CHECKLIST(intentId, checklist, draft) {
403
+ const selected = new Set(draft?.selected ??
404
+ checklist.credits.filter((credit) => credit.assignedIntentId === intentId).map((credit) => credit.movementId));
405
+ return {
406
+ selected,
407
+ conflict: draft !== null && draft.version !== checklist.version,
408
+ moving: checklist.credits.some((credit) => selected.has(credit.movementId) && credit.assignedIntentId !== null && credit.assignedIntentId !== intentId),
409
+ };
410
+ }
@@ -0,0 +1,55 @@
1
+ import * as v from "valibot";
2
+ /** Event emitted by the browser SDK when its authorization must be presented by a native Host. */
3
+ export declare const AndCoNativeAuthorizationRequestSchema: v.StrictObjectSchema<{
4
+ readonly type: v.LiteralSchema<"native-authorization-request", undefined>;
5
+ readonly transactionId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 128, undefined>, v.RegexAction<string, undefined>]>;
6
+ readonly authorizationUrl: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 8192, undefined>]>;
7
+ readonly protocol: v.LiteralSchema<"andco:sdk", undefined>;
8
+ readonly version: v.LiteralSchema<2, undefined>;
9
+ }, undefined>;
10
+ /** Event emitted when a native Host must present an OAuth popup without navigating the active WebView. */
11
+ export declare const AndCoNativeOpenPopupRequestSchema: v.StrictObjectSchema<{
12
+ readonly type: v.LiteralSchema<"open-popup", undefined>;
13
+ readonly transactionId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 128, undefined>, v.RegexAction<string, undefined>]>;
14
+ readonly url: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 8192, undefined>]>;
15
+ readonly protocol: v.LiteralSchema<"andco:sdk", undefined>;
16
+ readonly version: v.LiteralSchema<2, undefined>;
17
+ }, undefined>;
18
+ /** Result returned to the mounted SDK after a native Host finishes presenting authorization. */
19
+ export declare const AndCoNativeAuthorizationResultSchema: v.VariantSchema<"status", [v.StrictObjectSchema<{
20
+ readonly status: v.LiteralSchema<"complete", undefined>;
21
+ readonly callbackUrl: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 8192, undefined>]>;
22
+ readonly type: v.LiteralSchema<"native-authorization-result", undefined>;
23
+ readonly transactionId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 128, undefined>, v.RegexAction<string, undefined>]>;
24
+ readonly protocol: v.LiteralSchema<"andco:sdk", undefined>;
25
+ readonly version: v.LiteralSchema<2, undefined>;
26
+ }, undefined>, v.StrictObjectSchema<{
27
+ readonly status: v.LiteralSchema<"dismiss", undefined>;
28
+ readonly type: v.LiteralSchema<"native-authorization-result", undefined>;
29
+ readonly transactionId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 128, undefined>, v.RegexAction<string, undefined>]>;
30
+ readonly protocol: v.LiteralSchema<"andco:sdk", undefined>;
31
+ readonly version: v.LiteralSchema<2, undefined>;
32
+ }, undefined>, v.StrictObjectSchema<{
33
+ readonly status: v.LiteralSchema<"error", undefined>;
34
+ readonly error: v.StrictObjectSchema<{
35
+ readonly code: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 128, undefined>]>;
36
+ readonly message: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 2048, undefined>]>, undefined>;
37
+ }, undefined>;
38
+ readonly type: v.LiteralSchema<"native-authorization-result", undefined>;
39
+ readonly transactionId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 128, undefined>, v.RegexAction<string, undefined>]>;
40
+ readonly protocol: v.LiteralSchema<"andco:sdk", undefined>;
41
+ readonly version: v.LiteralSchema<2, undefined>;
42
+ }, undefined>], undefined>;
43
+ /** Authorization request relayed from a Miniapp main frame to an Andco native Host. */
44
+ export type AndCoNativeAuthorizationRequest = v.InferOutput<typeof AndCoNativeAuthorizationRequestSchema>;
45
+ /** Popup authorization request relayed from a mounted Miniapp to its native Host. */
46
+ export type AndCoNativeOpenPopupRequest = v.InferOutput<typeof AndCoNativeOpenPopupRequestSchema>;
47
+ /** Correlated outcome returned by the native Host to a mounted Miniapp SDK. */
48
+ export type AndCoNativeAuthorizationResult = v.InferOutput<typeof AndCoNativeAuthorizationResultSchema>;
49
+ /** Checks whether an unknown WebView message is a supported native Host request. */
50
+ export declare function isAndCoNativeAuthorizationRequest(input: unknown): input is AndCoNativeAuthorizationRequest;
51
+ /** Checks whether an unknown WebView message requests native popup presentation. */
52
+ export declare function isAndCoNativeOpenPopupRequest(input: unknown): input is AndCoNativeOpenPopupRequest;
53
+ /** Checks whether an unknown message is a correlated native authorization result. */
54
+ export declare function isAndCoNativeAuthorizationResult(input: unknown): input is AndCoNativeAuthorizationResult;
55
+ //# sourceMappingURL=native.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native.d.ts","sourceRoot":"","sources":["../src/native.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAG7B,kGAAkG;AAClG,eAAO,MAAM,qCAAqC;;;;;;aAKhD,CAAC;AAEH,0GAA0G;AAC1G,eAAO,MAAM,iCAAiC;;;;;;aAK5C,CAAC;AAQH,gGAAgG;AAChG,eAAO,MAAM,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;0BAkB/C,CAAC;AAEH,uFAAuF;AACvF,MAAM,MAAM,+BAA+B,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,qCAAqC,CAAC,CAAC;AAC1G,qFAAqF;AACrF,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,iCAAiC,CAAC,CAAC;AAClG,+EAA+E;AAC/E,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,oCAAoC,CAAC,CAAC;AAExG,oFAAoF;AACpF,wBAAgB,iCAAiC,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,+BAA+B,CAE1G;AAED,oFAAoF;AACpF,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,2BAA2B,CAElG;AAED,qFAAqF;AACrF,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,8BAA8B,CAExG"}
package/dist/native.js ADDED
@@ -0,0 +1,53 @@
1
+ import * as v from "valibot";
2
+ import { AndCoMessageBaseEntries, AndCoTransactionIdSchema } from "./messages/base.js";
3
+ /** Event emitted by the browser SDK when its authorization must be presented by a native Host. */
4
+ export const AndCoNativeAuthorizationRequestSchema = /* @__PURE__ */ v.strictObject({
5
+ ...AndCoMessageBaseEntries,
6
+ type: v.literal("native-authorization-request"),
7
+ transactionId: AndCoTransactionIdSchema,
8
+ authorizationUrl: v.pipe(v.string(), v.minLength(1), v.maxLength(8192)),
9
+ });
10
+ /** Event emitted when a native Host must present an OAuth popup without navigating the active WebView. */
11
+ export const AndCoNativeOpenPopupRequestSchema = /* @__PURE__ */ v.strictObject({
12
+ ...AndCoMessageBaseEntries,
13
+ type: v.literal("open-popup"),
14
+ transactionId: AndCoTransactionIdSchema,
15
+ url: v.pipe(v.string(), v.minLength(1), v.maxLength(8192)),
16
+ });
17
+ const AndCoNativeAuthorizationResultBaseEntries = {
18
+ ...AndCoMessageBaseEntries,
19
+ type: v.literal("native-authorization-result"),
20
+ transactionId: AndCoTransactionIdSchema,
21
+ };
22
+ /** Result returned to the mounted SDK after a native Host finishes presenting authorization. */
23
+ export const AndCoNativeAuthorizationResultSchema = /* @__PURE__ */ v.variant("status", [
24
+ v.strictObject({
25
+ ...AndCoNativeAuthorizationResultBaseEntries,
26
+ status: v.literal("complete"),
27
+ callbackUrl: v.pipe(v.string(), v.minLength(1), v.maxLength(8192)),
28
+ }),
29
+ v.strictObject({
30
+ ...AndCoNativeAuthorizationResultBaseEntries,
31
+ status: v.literal("dismiss"),
32
+ }),
33
+ v.strictObject({
34
+ ...AndCoNativeAuthorizationResultBaseEntries,
35
+ status: v.literal("error"),
36
+ error: v.strictObject({
37
+ code: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
38
+ message: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(2048))),
39
+ }),
40
+ }),
41
+ ]);
42
+ /** Checks whether an unknown WebView message is a supported native Host request. */
43
+ export function isAndCoNativeAuthorizationRequest(input) {
44
+ return v.safeParse(AndCoNativeAuthorizationRequestSchema, input).success;
45
+ }
46
+ /** Checks whether an unknown WebView message requests native popup presentation. */
47
+ export function isAndCoNativeOpenPopupRequest(input) {
48
+ return v.safeParse(AndCoNativeOpenPopupRequestSchema, input).success;
49
+ }
50
+ /** Checks whether an unknown message is a correlated native authorization result. */
51
+ export function isAndCoNativeAuthorizationResult(input) {
52
+ return v.safeParse(AndCoNativeAuthorizationResultSchema, input).success;
53
+ }
@@ -0,0 +1,4 @@
1
+ import * as v from "valibot";
2
+ /** Validates an RFC 7636 PKCE code verifier. */
3
+ export declare const AndCoCodeVerifierSchema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 43, undefined>, v.MaxLengthAction<string, 128, undefined>, v.RegexAction<string, undefined>]>;
4
+ //# sourceMappingURL=oauth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../src/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,gDAAgD;AAChD,eAAO,MAAM,uBAAuB,+KAKnC,CAAC"}
package/dist/oauth.js ADDED
@@ -0,0 +1,3 @@
1
+ import * as v from "valibot";
2
+ /** Validates an RFC 7636 PKCE code verifier. */
3
+ export const AndCoCodeVerifierSchema = /* @__PURE__ */ v.pipe(v.string(), v.minLength(43), v.maxLength(128), v.regex(/^[A-Za-z0-9._~-]+$/));
@@ -0,0 +1,3 @@
1
+ /** Generated from package.json at build time. */
2
+ export declare const ANDCO_RELEASE: 1780358400;
3
+ //# sourceMappingURL=release.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"release.d.ts","sourceRoot":"","sources":["../src/release.ts"],"names":[],"mappings":"AAAA,iDAAiD;AACjD,eAAO,MAAM,aAAa,EAAG,UAAmB,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** Generated from package.json at build time. */
2
+ export const ANDCO_RELEASE = 1780358400;
@@ -0,0 +1,35 @@
1
+ /** OAuth scopes currently supported by AndCo and suggested by TypeScript editors. */
2
+ export type AndCoKnownScope = "openid" | "email" | "profile" | "profile:write" | "phone" | "offline_access" | "identities:read" | "addresses:read" | "addresses:write" | "organizations:list" | "bank_accounts:read" | "bank_accounts.movements:read";
3
+ /** OAuth scope forwarded to AndCo without transformations. Known scopes are suggested, while custom future scopes remain valid. */
4
+ export type AndCoScope = AndCoKnownScope | (string & {});
5
+ /** Valid OAuth scope token: printable ASCII except space, double quote, and backslash. */
6
+ export declare const ANDCO_SCOPE_REGEX: RegExp;
7
+ /** Available modes for starting the authorization flow. */
8
+ export declare enum ANDCO_AUTH_MODES {
9
+ AUTO = "auto",
10
+ SIGNUP = "signup",
11
+ LOGIN = "login"
12
+ }
13
+ /** Union of supported authorization modes. */
14
+ export type AndCoAuthMode = ANDCO_AUTH_MODES;
15
+ /** Available presentations for the authorization flow. */
16
+ export declare enum ANDCO_PRESENTATIONS {
17
+ REDIRECT = "redirect",
18
+ POPUP = "popup"
19
+ }
20
+ /** Union of supported authorization presentations. */
21
+ export type AndCoPresentation = ANDCO_PRESENTATIONS;
22
+ /** Options that control the AndCo authorization flow. */
23
+ export type AndCoAuthorizationOptions = {
24
+ /** Opens OAuth in the current page by default, or in a user-initiated popup. */
25
+ presentation?: AndCoPresentation;
26
+ /** Public OAuth client that is requesting access. */
27
+ clientId?: string;
28
+ /** Scopes requested for this authorization. Required project scopes are added by the server. */
29
+ scopes?: AndCoScope[];
30
+ /** Selects automatic discovery, signup-only or login-only behavior. */
31
+ authMode?: AndCoAuthMode;
32
+ /** Registered OAuth `redirect_uri` that receives `code` and `state` in a public PKCE flow. */
33
+ redirectTo?: string;
34
+ };
35
+ //# sourceMappingURL=scopes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,MAAM,MAAM,eAAe,GACvB,QAAQ,GACR,OAAO,GACP,SAAS,GACT,eAAe,GACf,OAAO,GACP,gBAAgB,GAChB,iBAAiB,GACjB,gBAAgB,GAChB,iBAAiB,GACjB,oBAAoB,GACpB,oBAAoB,GACpB,8BAA8B,CAAC;AAEnC,mIAAmI;AACnI,MAAM,MAAM,UAAU,GAAG,eAAe,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAEzD,0FAA0F;AAC1F,eAAO,MAAM,iBAAiB,QAAsC,CAAC;AAErE,2DAA2D;AAC3D,oBAAY,gBAAgB;IAC1B,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,KAAK,UAAU;CAChB;AAED,8CAA8C;AAC9C,MAAM,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAE7C,0DAA0D;AAC1D,oBAAY,mBAAmB;IAC7B,QAAQ,aAAa;IACrB,KAAK,UAAU;CAChB;AAED,sDAAsD;AACtD,MAAM,MAAM,iBAAiB,GAAG,mBAAmB,CAAC;AAEpD,yDAAyD;AACzD,MAAM,MAAM,yBAAyB,GAAG;IACtC,gFAAgF;IAChF,YAAY,CAAC,EAAE,iBAAiB,CAAC;IACjC,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gGAAgG;IAChG,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC;IACtB,uEAAuE;IACvE,QAAQ,CAAC,EAAE,aAAa,CAAC;IACzB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC"}
package/dist/scopes.js ADDED
@@ -0,0 +1,15 @@
1
+ /** Valid OAuth scope token: printable ASCII except space, double quote, and backslash. */
2
+ export const ANDCO_SCOPE_REGEX = /^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/;
3
+ /** Available modes for starting the authorization flow. */
4
+ export var ANDCO_AUTH_MODES;
5
+ (function (ANDCO_AUTH_MODES) {
6
+ ANDCO_AUTH_MODES["AUTO"] = "auto";
7
+ ANDCO_AUTH_MODES["SIGNUP"] = "signup";
8
+ ANDCO_AUTH_MODES["LOGIN"] = "login";
9
+ })(ANDCO_AUTH_MODES || (ANDCO_AUTH_MODES = {}));
10
+ /** Available presentations for the authorization flow. */
11
+ export var ANDCO_PRESENTATIONS;
12
+ (function (ANDCO_PRESENTATIONS) {
13
+ ANDCO_PRESENTATIONS["REDIRECT"] = "redirect";
14
+ ANDCO_PRESENTATIONS["POPUP"] = "popup";
15
+ })(ANDCO_PRESENTATIONS || (ANDCO_PRESENTATIONS = {}));
@@ -0,0 +1,9 @@
1
+ import { type AndCoResolveAuthorizationOptions } from "./authorization.js";
2
+ /** Creates the RFC 6749 client_secret_basic Authorization header value. */
3
+ export declare function andCoClientSecretBasic(clientId: string, clientSecret: string): string;
4
+ /** Resolves GET/PAR for a confidential client authenticated with client_secret_basic. */
5
+ export declare function resolveAndCoConfidentialAuthorization(options: Omit<AndCoResolveAuthorizationOptions, "parHeaders"> & {
6
+ clientId: string;
7
+ clientSecret: string;
8
+ }): Promise<import("./authorization.js").AndCoResolvedAuthorization>;
9
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,gCAAgC,EAA6B,MAAM,oBAAoB,CAAC;AAEtG,2EAA2E;AAC3E,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAGrF;AAED,yFAAyF;AACzF,wBAAgB,qCAAqC,CACnD,OAAO,EAAE,IAAI,CAAC,gCAAgC,EAAE,YAAY,CAAC,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,oEAM3G"}
package/dist/server.js ADDED
@@ -0,0 +1,14 @@
1
+ import { resolveAndCoAuthorization } from "./authorization.js";
2
+ /** Creates the RFC 6749 client_secret_basic Authorization header value. */
3
+ export function andCoClientSecretBasic(clientId, clientSecret) {
4
+ if (!clientId || !clientSecret)
5
+ throw new TypeError("clientId and clientSecret are required");
6
+ return `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`;
7
+ }
8
+ /** Resolves GET/PAR for a confidential client authenticated with client_secret_basic. */
9
+ export function resolveAndCoConfidentialAuthorization(options) {
10
+ return resolveAndCoAuthorization({
11
+ ...options,
12
+ parHeaders: { Authorization: andCoClientSecretBasic(options.clientId, options.clientSecret) },
13
+ });
14
+ }