@12-apps/marketplace 0.0.0-stage → 1.1.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 (87) hide show
  1. package/ADOPTING.md +199 -0
  2. package/README.md +68 -2
  3. package/dist/adapter-BggtVFf9.d.ts +285 -0
  4. package/dist/chunk-7BYVGNU5.js +28 -0
  5. package/dist/chunk-7BYVGNU5.js.map +1 -0
  6. package/dist/chunk-7QVYU63E.js +7 -0
  7. package/dist/chunk-7QVYU63E.js.map +1 -0
  8. package/dist/chunk-DVIRN42O.js +707 -0
  9. package/dist/chunk-DVIRN42O.js.map +1 -0
  10. package/dist/chunk-NGNEL4HS.js +388 -0
  11. package/dist/chunk-NGNEL4HS.js.map +1 -0
  12. package/dist/chunk-UYFYGGCS.js +250 -0
  13. package/dist/chunk-UYFYGGCS.js.map +1 -0
  14. package/dist/engine-KrgZ4pA4.d.ts +850 -0
  15. package/dist/hono/index.d.ts +38 -0
  16. package/dist/hono/index.js +64 -0
  17. package/dist/hono/index.js.map +1 -0
  18. package/dist/ifood/en-US.d.ts +20 -0
  19. package/dist/ifood/en-US.js +24 -0
  20. package/dist/ifood/en-US.js.map +1 -0
  21. package/dist/ifood/index.d.ts +75 -0
  22. package/dist/ifood/index.js +313 -0
  23. package/dist/ifood/index.js.map +1 -0
  24. package/dist/ifood/pt-BR.d.ts +25 -0
  25. package/dist/ifood/pt-BR.js +24 -0
  26. package/dist/ifood/pt-BR.js.map +1 -0
  27. package/dist/index.d.ts +45 -0
  28. package/dist/index.js +883 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/manifest/index.d.ts +339 -0
  31. package/dist/manifest/index.js +20 -0
  32. package/dist/manifest/index.js.map +1 -0
  33. package/dist/manifest/server.d.ts +23 -0
  34. package/dist/manifest/server.js +18 -0
  35. package/dist/manifest/server.js.map +1 -0
  36. package/dist/server/en-US.d.ts +22 -0
  37. package/dist/server/en-US.js +26 -0
  38. package/dist/server/en-US.js.map +1 -0
  39. package/dist/server/index.d.ts +529 -0
  40. package/dist/server/index.js +41 -0
  41. package/dist/server/index.js.map +1 -0
  42. package/dist/server/pt-BR.d.ts +22 -0
  43. package/dist/server/pt-BR.js +26 -0
  44. package/dist/server/pt-BR.js.map +1 -0
  45. package/package.json +118 -4
  46. package/prisma/marketplace.prisma +248 -0
  47. package/prisma/migrations/20261111200000_marketplace_engine/migration.sql +272 -0
  48. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  49. package/src/core/acceptance.ts +213 -0
  50. package/src/core/adapter.ts +190 -0
  51. package/src/core/bulk.ts +203 -0
  52. package/src/core/cancellation-outcome.ts +92 -0
  53. package/src/core/cancellation.ts +206 -0
  54. package/src/core/decisions.ts +367 -0
  55. package/src/core/engine.ts +229 -0
  56. package/src/core/inbox.ts +172 -0
  57. package/src/core/ingest.ts +168 -0
  58. package/src/core/integration.ts +300 -0
  59. package/src/core/menu-links.ts +166 -0
  60. package/src/core/outbound-queue.ts +63 -0
  61. package/src/core/outbound-sweep.ts +169 -0
  62. package/src/core/outbound.ts +359 -0
  63. package/src/core/pipeline.ts +193 -0
  64. package/src/core/ports.ts +292 -0
  65. package/src/core/registry.ts +107 -0
  66. package/src/core/state.ts +81 -0
  67. package/src/core/types.ts +131 -0
  68. package/src/hono/index.ts +95 -0
  69. package/src/ifood/copy.ts +36 -0
  70. package/src/ifood/en-US.ts +20 -0
  71. package/src/ifood/index.ts +74 -0
  72. package/src/ifood/normalize.ts +281 -0
  73. package/src/ifood/outbound.ts +112 -0
  74. package/src/ifood/pt-BR.ts +25 -0
  75. package/src/index.ts +123 -0
  76. package/src/manifest/index.ts +42 -0
  77. package/src/manifest/server.ts +20 -0
  78. package/src/server/contribution.ts +34 -0
  79. package/src/server/copy.ts +25 -0
  80. package/src/server/en-US.ts +22 -0
  81. package/src/server/http.ts +66 -0
  82. package/src/server/index.ts +55 -0
  83. package/src/server/jobs.ts +132 -0
  84. package/src/server/mcp.ts +306 -0
  85. package/src/server/pt-BR.ts +22 -0
  86. package/src/server/routes.ts +215 -0
  87. package/src/server/webhook.ts +118 -0
package/ADOPTING.md ADDED
@@ -0,0 +1,199 @@
1
+ # Adopting @12-apps/marketplace
2
+
3
+ The engine is a library with required ports and no defaults: a host answers
4
+ every question only it can answer, and the engine supplies the mechanism.
5
+ Everything below is what a host binds, in the order it binds it.
6
+
7
+ ## 1. The host ports (`MarketplacePorts`)
8
+
9
+ Every field is REQUIRED unless marked OPTIONAL. A missing required one is a type
10
+ error at mount, never a default that quietly adopts another host's policy.
11
+
12
+ | port | type | what the host answers |
13
+ |---|---|---|
14
+ | `db` | `() => Promise<MarketplaceDb>` | The Prisma client generated from a schema that includes `prisma/marketplace.prisma`. Structural: the four delegates `marketplaceIntegration`, `marketplaceMenuLink`, `marketplaceInboxEvent`, `marketplaceAcceptance`. |
15
+ | `transaction` | `<T>(fn: (db: MarketplaceDb) => Promise<T>) => Promise<T>` | Prisma's interactive `$transaction`: run `fn` with the transaction's client; a throw rolls back. Every bulk write and every decision (admission + claim) is one transaction. |
16
+ | `order.admit` | `(request: { clientId; orderId; decision: "ACCEPT" \| "REJECT"; admission: MarketplaceAdmission; db: MarketplaceDb }) => Promise<{ admitted: true } \| { admitted: false; code: string; message: string; details?: unknown }>` | Judge each decision BEFORE its claim commits, inside the claim's transaction (`request.db` is the transaction's client: draw the stock there, and a refusal anywhere in the call rolls the draw back). `admission` is `{ admitStockPastZero?: boolean }` as the person stated it. Refuse with your own code: the route answers 409 with it (`MARKETPLACE_STOCK_ASK` and the short lines in `details`). Never called for an ingest or `recordStoreCancellation`. |
17
+ | `order.create` | `(clientId, order: NormalizedMarketplaceOrder, lines: readonly ResolvedOrderLine[], db: MarketplaceDb) => Promise<string>` | Create the host's own order from a normalized one; return its id. `lines[i].subjectRef` is the mapped catalog id or null (never refuse the order for a null). `db` is the ingest's transaction client: write the order through it, so the order and the acceptance row commit together (a lost race rolls the host's order back instead of leaving an orphan a redelivery would duplicate). |
18
+ | `order.catalogHas` | `(clientId, subjectRef) => Promise<boolean>` | Does this catalog id exist and belong to this tenant? Asked before a SKU is mapped. |
19
+ | `order.onAccepted` | `(clientId, orderId) => Promise<void>` | The store accepted, or the connection auto-accepts. Start whatever accepting means here (the ticket, the board). Runs after the commit and AFTER the confirm is queued; a throw is logged and cannot un-accept or lose the confirm. Atomic work (the stock draw) belongs in `admit`. |
20
+ | `order.onRefused` | `(clientId, orderId, reason: "REJECTED" \| "EXPIRED" \| "CANCELLED") => Promise<void>` | Refuse/cancel the host order: the store refused on the clock, the clock lapsed, or the marketplace cancelled. After the commit and after the cancellation request is queued; a throw on a decision is logged. NOT called for `recordStoreCancellation`. A host that binds `onCancellationConfirmed` (request first) does not get `"REJECTED"` from `decide` either, nor `"CANCELLED"` for a cancellation the store asked for: `onCancellationConfirmed` replaces both. |
21
+ | `order.onCancellationConfirmed` | OPTIONAL — binding it OPTS IN to request first. `(clientId, orderId) => Promise<void>` | The marketplace CONFIRMED the store's own cancellation request (its event, or the job's answer for a marketplace that answers in the response); the row is REJECTED/CONFIRMED by then. Run the host's cancel here. Bound: the store's refusals and cancels (`decide` REJECT, `recordStoreCancellation`) only REQUEST the cancellation and keep the order as it was until this is called, once (a redelivered confirmation calls nothing), INSTEAD of `onRefused`. Not bound (a 1.0.0 host): everything as 1.0.0 — REJECTED at request time, `onRefused(…, "REJECTED")` from `decide`, and `onRefused(…, "CANCELLED")` on the confirmation. A throw is logged. |
22
+ | `order.onCancellationFailed` | OPTIONAL. `(clientId, orderId, reason: "REFUSED" \| "TIMEOUT") => Promise<void>` | The store's request FAILED: REFUSED (the marketplace's refusal event, the job's 4xx, its last attempt dying, or — request first — a marketplace whose API cannot take it, at once) or TIMEOUT (the outbound sweep, past the marketplace's answer window, or the 24-hour give-up). Called once, by the path that moved the row. Request first: the order stays as it was (AWAITING or ACCEPTED) and may be accepted again; show the adapter's app link and tell the person. A throw is logged. |
23
+ | `order.summarize` | `(clientId, orderIds: readonly string[]) => Promise<Map<string, MarketplaceOrderSummary>>` | The queue's host facts in one read: `{ buyerName, totalCents, unmappedLines, createdAt }`. |
24
+ | `secrets` | `{ seal(plaintext): string; open(sealed): string }` | Seal and open the credential blob with the host's key. `open` THROWS on a blob that will not open. |
25
+ | `http` | `(req: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>` | The only way the engine reaches a marketplace. Answer any status; throw only when no answer arrived (timeout, network). The host owns the timeout, proxy and CA. |
26
+ | `audit` | `{ record(entry: { clientId; actorId: string \| null; action: "marketplace.integration.archive" \| "marketplace.integration.unarchive"; provider; reason: string \| null; at: Date }, db: MarketplaceDb): Promise<void> }` | Every archive and unarchive of a connection, INSIDE the same transaction: write the line through `db`, so an archive never lands without its line and a failing audit rolls the archive back. `actorId` is `MarketplaceActor.userId`. |
27
+ | `enqueue` | `{ enqueue(name, payload, { dedupeKey? }) => Promise<{ enqueued: boolean; reason?: string }> }` | The wiring `JobsEnqueuePort`. The engine queues only `marketplace.outbound` with `{ clientId, orderId, action }` and dedupe key `marketplace.outbound:<action>:<orderId>`. Never throws. |
28
+ | `clock` | `{ now(): Date }` | What time it is. |
29
+ | `logger` | `{ info, warn, error }` | The wiring `LoggerPort`; bind `assembled.loggers["@12-apps/marketplace"]`. |
30
+ | `publishChanged` | `(clientId) => void` | Tell the staff surfaces something moved. Fire-and-forget. |
31
+ | `defaultAckSlaSeconds` | `number` | The acceptance window a new connection gets (the origin host: 300). |
32
+ | `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
33
+ | `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
34
+ | `cancellationWindowMs` | OPTIONAL. `number` | For a host that requests first (binds `onCancellationConfirmed`): how long a store's cancellation request may wait (PENDING: not yet delivered, or REQUESTED: delivered and unanswered) before the outbound sweep fails it as TIMEOUT, for every adapter; a PENDING request's retries stop with it. A 1.0.0 host has no window: its requests are re-queued and given up after 24 hours, as before. Absent: each adapter's `capabilities.cancellationAnswerWindowMs` (iFood: 5 minutes, estimated); an adapter with none is given up on only after 24 hours. |
35
+
36
+ Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
37
+ sells through. The list is validated at mount (ids, duplicates, reason lists).
38
+
39
+ ```ts
40
+ import { createMarketplaceEngine } from "@12-apps/marketplace";
41
+ import { createIfoodAdapter } from "@12-apps/marketplace/ifood";
42
+ import { IFOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/ifood/pt-BR";
43
+
44
+ export const engine = createMarketplaceEngine({
45
+ db: async () => getPrismaClient(),
46
+ transaction: async (fn) => (await getPrismaClient()).$transaction((tx) => fn(tx)),
47
+ order: { admit, create, catalogHas, onAccepted, onRefused, summarize },
48
+ audit: { record: writeAuditLine },
49
+ secrets: { seal: encryptSecret, open: decryptSecret },
50
+ http: marketplaceHttp,
51
+ enqueue: jobs,
52
+ clock: { now: () => new Date() },
53
+ logger: assembled.loggers["@12-apps/marketplace"],
54
+ publishChanged,
55
+ defaultAckSlaSeconds: 300,
56
+ reconcileBatchSize: 50,
57
+ maxInboxAttempts: 5,
58
+ adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })],
59
+ });
60
+ ```
61
+
62
+ ## 2. What the host calls on the engine
63
+
64
+ | call | when |
65
+ |---|---|
66
+ | `decideMany({ clientId, decisions, validateOnly? })` / `decide({ clientId, ...decision })` | Every accept or refusal of an order on the clock, from every surface (the board, the admin route, the MCP tool). One decide path, all-or-nothing. A decision is `{ orderId, decision: "ACCEPT", admission?, preparationMinutes? }` or `{ orderId, decision: "REJECT", reasonCode?, offendingSkus? }`. `decide` answers `decided`, `stale` with `reason` (`ALREADY_DECIDED` with the `status` — answer an ACCEPTED one as done, I4 — `EXPIRED`, `NOT_FOUND`, `CONFLICT`), `invalidReason` (`INVALID_REASON`, `ITEMS_REQUIRED`, `UNKNOWN_ITEM`), or `refusedByHost` (your `admit`'s code). |
67
+ | `recordStoreCancellation({ clientId, orderId, reasonCode?, offendingSkus? })` | The store cancels a marketplace order (before or after accepting it). Stamps the request and queues it. A host that binds no `onCancellationConfirmed` cancelled first and gets 1.0.0's stamps (REJECTED at once). A host that binds it (request first) gets the REQUEST only: the status stays AWAITING or ACCEPTED (and `decided.status` says so) until the marketplace confirms; a FAILED request may be asked again. `stale` when the marketplace already cancelled it or a request is already waiting. |
68
+ | `suggestReason(provider, { itemUnavailable })` | To preselect a reason in the refusal dialog. The host judges the shortage. |
69
+ | `orderStates(clientId, orderIds)` | The order reads: `{ status, confirmedAt, confirmFailedAt, cancellation, cancellationReasonCode, cancellationFailure, appUrl }` per marketplace order, one query. `cancellation` PENDING or REQUESTED is a request still waiting: draw it as such. `cancellationFailure` is REFUSED or TIMEOUT when `cancellation` is FAILED. |
70
+ | `adapter(provider)`, `reasons(provider)`, `appLink(provider, ref)` | The marketplace's capabilities, reasons and link, without naming it. |
71
+ | `ingest(...)`, `deliver(...)` | A producer that hands over an order directly; the webhook does `deliver` for you. |
72
+
73
+ A host never writes `provider === "IFOOD"`. A capability is asked of
74
+ `engine.adapter(provider).capabilities`.
75
+
76
+ ## 3. The wiring capabilities
77
+
78
+ Adopt through `@12-apps/wiring/consumer`:
79
+
80
+ ```ts
81
+ host.adoptServer({
82
+ manifest: marketplaceManifest, // @12-apps/marketplace/manifest
83
+ server: marketplaceServerManifest, // @12-apps/marketplace/manifest/server
84
+ bindings: {
85
+ http: { mountPath: "/api", config: { engine, copy: MARKETPLACE_SERVER_COPY_PT_BR, tenantBySlug, logger } },
86
+ jobs: { deps: { engine } },
87
+ },
88
+ });
89
+ ```
90
+
91
+ | capability | what it is |
92
+ |---|---|
93
+ | `http` | `POST /webhooks/marketplace/:tenantSlug/:provider` (`kind: "webhook"`, needs the raw `request`), and per entity one read and one bulk write under `/admin/:tenantSlug/marketplace`: `GET`/`PUT` (connections), `GET`/`PUT /menu-links`, `GET`/`POST /acceptances` (decisions). `@12-apps/marketplace/hono`'s `marketplaceRouter({ ...config, resolveActor })` mounts them in one line. |
94
+ | `jobs` | `marketplace.expire-acceptances` (every minute, lease 5 min), `marketplace.reconcile-inbox` (every 5 min, lease 5 min), `marketplace.outbound` (3 attempts, exponential backoff 30 s), `marketplace.outbound-sweep` (every 5 min, lease 5 min: re-queues every call still owed after 10 min, gives a PENDING request up as FAILED after 24 h). Bind `{ engine }`. |
95
+ | `mcp` | Six tools, the bulk-upsert protocol: `listMarketplaceIntegrations` / `upsertMarketplaceIntegrations` (operations `upsert`, `archive`, `unarchive`), `listMarketplaceMenuLinks` / `upsertMarketplaceMenuLinks`, `listMarketplaceAcceptances` / `decideMarketplaceOrders`. Every write takes a list, is all-or-nothing in one transaction, supports `validateOnly`, answers every problem with its path; reads take `ids`. Descriptions are English. |
96
+ | `permissions` | `marketplace:manage` (connect, map) and `marketplace:decide` (read and answer the queue). The host decides which roles hold them; each route declares its own. |
97
+ | `db` | `prisma/marketplace.prisma` + `prisma/migrations` (composed). |
98
+ | `observability` | namespace `marketplace`. |
99
+
100
+ The route copy (`MarketplaceServerCopy`) and the iFood adapter's copy
101
+ (`IfoodAdapterCopy`) are required config; pt-BR and en-US packs ship beside
102
+ each.
103
+
104
+ ## 4. What the origin host changes when it adopts this package
105
+
106
+ 1. **Bind the new ports:** `transaction` (`prisma.$transaction`), `order.admit` (move the
107
+ stock ask and the draw of an accept here, from the Quadro's own path, so the board, the
108
+ admin route and the MCP share it), `audit`, `http` (`marketplaceHttp`), `enqueue`,
109
+ `clock`, `logger`. Move any atomic work out of `onAccepted`.
110
+ 2. **`normalizeIfoodEvent(payload, options)`** now takes `{ missingStreetNumber }` (the pack's
111
+ `IFOOD_ADAPTER_COPY_PT_BR.missingStreetNumber` is "s/n"); the host's tests that call it with
112
+ one argument change. Better: call `engine.normalize("IFOOD", payload)`.
113
+ 3. **The webhook's refusals are JSON:** `401 {error:"unauthorized"}`, `404
114
+ {error:"unknown_provider"}`, `400 {error:"invalid_json"}`; an unreadable payload answers
115
+ `{received:true, ignored:"unrecognized_payload"}` (was "unrecognized payload").
116
+ 4. **`GET …/menu-links?unmapped=`** is true only for `"true"` (the host's `z.coerce.boolean`
117
+ read `"false"` as true).
118
+ 5. **The tools and routes are bulk:** `saveMarketplaceIntegration`, `deleteMarketplaceIntegration`,
119
+ `setMarketplaceMenuLink` and `decideMarketplaceOrder` (and `POST …/acceptances/:orderId`)
120
+ become `upsertMarketplaceIntegrations` (delete is now `operation: "archive"`),
121
+ `upsertMarketplaceMenuLinks` and `decideMarketplaceOrders` (`POST …/acceptances` with a
122
+ `decisions` list). Update the admin SPA's calls, the MCP tool groups and the policy table.
123
+ 6. **The guards move to permissions:** connections and SKU links take `marketplace:manage`
124
+ (was `requireTenantAdminBySlug` / `products:*`), the queue and the decision
125
+ `marketplace:decide` (was `orders:read:all` / `requireTenantAdminBySlug`). Grant BOTH to the
126
+ roles that hold store administration today (OWNER, ADMIN) to keep today's access, and
127
+ `marketplace:decide` to whoever reads the queue today.
128
+ 7. **`decide` returns a union** (`decided`, `stale` with a reason, `invalidReason`,
129
+ `refusedByHost`), not `AcceptanceOutcome | null`; `recordStoreCancellation` replaces calling
130
+ `onRefused` after the PATCH cancel.
131
+ 8. **The provider is a string** checked by `engine.knows(provider)`;
132
+ `MARKETPLACE_PROVIDERS`/`isMarketplaceProvider` are gone.
133
+ 9. **Drop the origin host's unmerged `20261111190000_marketplace_outbound`** migration: this
134
+ package's `20261111200000_marketplace_engine` adds the same columns (and more), and
135
+ deployed in the other order the plain `ADD COLUMN` of 190000 would fail.
136
+ 10. **Stop syncing the predecessor's own migration copies over this package's**: keep the
137
+ host's applied `20260814140000`/`20261105120000` files as they are.
138
+ 11. **Orders accepted before adoption are stamped confirmed, never re-sent.** The migration's
139
+ first run over the predecessor's table sets `confirmed_at = acknowledged_at` on every row
140
+ already `ACCEPTED`, because nothing confirmed through an API before this engine; the outbound
141
+ sweep then owes none of them. Fresh databases and replays stamp nothing.
142
+ 12. **`order.create` and `audit.record` receive a transaction client** (last argument): write
143
+ the host's order and the audit line through it, so they commit with the engine's own rows.
144
+ Everything `create` writes goes through that client, the buyer record and the order
145
+ number included, never the host's global client inside the callback: on PGlite, which
146
+ runs one transaction at a time, a write on the global client hangs the ingest, and on
147
+ Postgres a rolled-back ingest would leave an orphan order and a burnt order number.
148
+ 13. **Request first, cancel on confirm (1.1, FUT-4758) — opt in by binding
149
+ `order.onCancellationConfirmed`.** Without it, 1.0.0's behaviour holds, with two
150
+ differences, both harmless to a host whose cancel is idempotent: a marketplace that
151
+ confirms in its response now also moves the row to REJECTED and calls
152
+ `onRefused(…, "CANCELLED")` (1.0.0 called nothing there), and the event path keeps an
153
+ accepted order's `acknowledged_at` instead of overwriting it with the cancel time. With it, the
154
+ store's refusals and cancels (`decide` REJECT and `recordStoreCancellation`) only request
155
+ the cancellation; the order keeps its status until the marketplace confirms, and the
156
+ acceptance clock leaves an order with a waiting request alone (the request's window ends
157
+ it first). To opt in:
158
+ - bind `order.onCancellationConfirmed` (run the ordinary cancel there);
159
+ - call `recordStoreCancellation` from every cancel entry point, without cancelling;
160
+ - draw `orderStates(…).cancellation` PENDING/REQUESTED as "waiting for the marketplace";
161
+ - keep the store's own reason (its loss record, who asked) for that cancel: the engine
162
+ carries only the marketplace's code;
163
+ - bind `order.onCancellationFailed` (REFUSED or TIMEOUT: the order stays, show the app link);
164
+ - expect the answer window: a request still waiting past it (delivered or not) ends TIMEOUT;
165
+ - run migration `20261112120000_marketplace_cancellation_failure` (one nullable column,
166
+ its CHECK and an index), through the host's plugin-migration sync like the first.
167
+
168
+ ## 5. The database
169
+
170
+ The partial names no host table: `client_id`, `order_id` and `menu_item_id`
171
+ are by-value scalars. A host that wants referential integrity adds, in its own
172
+ migration:
173
+
174
+ - `marketplace_*.client_id → <tenants>(id) ON DELETE CASCADE`
175
+ - `marketplace_acceptances.order_id → <orders>(id) ON DELETE CASCADE`
176
+ - `marketplace_menu_links.menu_item_id → <catalog>(id) ON DELETE SET NULL`
177
+
178
+ The migrations are replay-safe. `20261112120000_marketplace_cancellation_failure`
179
+ (1.1) adds `marketplace_acceptances.cancellation_failure_reason` (REFUSED or
180
+ TIMEOUT, CHECKed), and a PARTIAL index the expiry of waiting requests reads
181
+ (`marketplace_acceptances_cancellation_waiting_idx`, `WHERE cancellation_status IN
182
+ ('PENDING','REQUESTED')`). Prisma cannot express a partial index, so it is SQL-only and
183
+ the partial declares none: a host that diffs its schema against its database ignores it,
184
+ as it already does for the first migration's partial indexes.
185
+
186
+ The migration `20261111200000_marketplace_engine` is replay-safe. On a host
187
+ that already has the predecessor's tables it adds the outbound columns
188
+ (including `cancellation_offending_skus`, `cancellation_requested_at`,
189
+ `preparation_minutes`), the order's `line_skus`, `delivered_by` and the
190
+ connection's `archived_at`, keeps the host's foreign keys, and replaces the
191
+ closed provider lists (`*_provider_valid`) with a shape check, so a new
192
+ adapter is never a migration.
193
+
194
+ ## 6. What stays the host's
195
+
196
+ The stock draw at the acceptance, the settlement effects, the board's and the
197
+ order screen's UI, the cancel route itself, the HTTP client's timeout and CA,
198
+ the jobs runtime and its leases, which roles hold the two permissions, and
199
+ every sentence a person reads.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # @12-apps/marketplace
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One integration engine for every marketplace a store sells through. Each
4
+ marketplace is an **adapter** on that engine, shipped inside this package at
5
+ its own subpath (`@12-apps/marketplace/ifood` today).
6
+
7
+ ```ts
8
+ import { createMarketplaceEngine } from "@12-apps/marketplace";
9
+ import { createIfoodAdapter } from "@12-apps/marketplace/ifood";
10
+ import { IFOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/ifood/pt-BR";
11
+
12
+ const engine = createMarketplaceEngine({
13
+ ...hostPorts, // db, order, secrets, http, enqueue, clock, logger, publishChanged, the three numbers
14
+ adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })],
15
+ });
16
+ ```
17
+
18
+ Adoption contract, every host port and the wiring: **[ADOPTING.md](./ADOPTING.md)**.
19
+ Why it is shaped this way: the decision record
20
+ [`docs/marketplace/decisions/0001-one-engine-an-adapter-per-marketplace.md`](../../docs/marketplace/decisions/0001-one-engine-an-adapter-per-marketplace.md).
21
+
22
+ ## The owner's two rules
23
+
24
+ 1. "The integration engine must be the same for all integrations: iFood, Rappi,
25
+ 99. Only an adapter is made for each one, to connect to the base engine."
26
+ 2. "This base engine must be a separate lib that implements the wiring package."
27
+
28
+ Engine and adapters share one version. No provider-specific branch exists
29
+ anywhere outside an adapter and its registration: the engine dispatches every
30
+ provider decision through the adapter registry, and a suite registers a fake
31
+ second marketplace and drives ingest, confirm and cancel without touching
32
+ engine code (`src/__tests__/second-adapter.test.ts`).
33
+
34
+ ## What the engine holds
35
+
36
+ | part | what it does |
37
+ |---|---|
38
+ | **Canonical types** | `NormalizedEvent`, `NormalizedMarketplaceOrder`: what every adapter normalizes into. Poorer than any marketplace's payload on purpose; the raw payload stays in the inbox row. |
39
+ | **Inbox** | Every delivery recorded before it is processed, deduped on `(provider, eventId)`. A redelivery is a DB-level no-op; a crash mid-ingest leaves a PENDING row the sweep retries. |
40
+ | **Pipeline** | normalize → inbox → ingest / cancel / cancellation-refused / ignore. Never throws. |
41
+ | **Ingest** | Idempotent on `(provider, externalOrderId)`. Unmapped SKUs are rows on the attention list, never a rejection. The deadline is stamped at ingest; auto-accept is born accepted in one write and queues the confirm. |
42
+ | **Acceptance clock** | `AWAITING → ACCEPTED | REJECTED | EXPIRED`, every transition predicated on the current state. The sweep never touches an accepted order. |
43
+ | **Decisions** | Many at once, all-or-nothing: accept (with the person's admission and a preparation time), or refuse with a reason code validated against the adapter's own list and, for a reason that needs them, the order's offending SKUs. The host admits each decision inside the claim's transaction (`order.admit`: the stock ask, the draw). For a host that binds `onCancellationConfirmed`, the store's refusal or cancel is a REQUEST: only the request moves, the order stays as it was until the marketplace answers, and the host hears the answer through the optional `onCancellationConfirmed` / `onCancellationFailed` (REFUSED or TIMEOUT). `suggestReason` preselects the item-unavailable reason when the host says stock is short. |
44
+ | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. |
45
+ | **Integration settings** | Enabled, environment, merchant id, auto-accept, acknowledgement window; credentials sealed as one blob by the host's secrets port, never returned. A connection is archived (reversible, audited), never deleted. |
46
+ | **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. The same sweep fails a request still waiting (never delivered, or delivered and unanswered) as TIMEOUT once past its answer window, and its retries stop (the adapter's `cancellationAnswerWindowMs`, or the engine's `cancellationWindowMs`), so no request waits forever. |
47
+ | **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
48
+ | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, and `capabilities`. |
49
+
50
+ ## Subpaths
51
+
52
+ | export | what |
53
+ |---|---|
54
+ | `@12-apps/marketplace` | the engine, the adapter port and registry, every type |
55
+ | `@12-apps/marketplace/ifood` | `createIfoodAdapter({ copy })` |
56
+ | `@12-apps/marketplace/ifood/pt-BR`, `/en-US` | the iFood adapter's copy packs (reason labels, "no street number") |
57
+ | `@12-apps/marketplace/server` | `createApiMarketplace` (route descriptors), `MARKETPLACE_JOBS`, `MARKETPLACE_MCP_TOOLS` (six: a read and a bulk write per entity), `MARKETPLACE_PERMISSIONS`, the strict Zod inputs |
58
+ | `@12-apps/marketplace/server/pt-BR`, `/en-US` | the routes' copy packs |
59
+ | `@12-apps/marketplace/hono` | `marketplaceRouter(config)` — the routes as one Hono router (`hono` is an optional peer) |
60
+ | `@12-apps/marketplace/manifest`, `/manifest/server` | the wiring manifests |
61
+ | `prisma/marketplace.prisma`, `prisma/migrations/*` | the partial (no host table named) and its replay-safe migration |
62
+
63
+ ## iFood is unverified
64
+
65
+ iFood's developer portal refused our reader, so the iFood adapter's URLs, body
66
+ fields and reason codes come from the portal's search snippets (2026-11-11).
67
+ They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
68
+ headers say so, so the homologation run corrects two files. Tests never reach
69
+ iFood: the HTTP client is the host's port.
@@ -0,0 +1,285 @@
1
+ /**
2
+ * The canonical shape every marketplace adapter normalizes INTO.
3
+ *
4
+ * This type is the seam. The engine below it knows no marketplace by name: a
5
+ * marketplace is an adapter registered with the engine (`./adapter`), and the
6
+ * provider id is whatever that adapter says it is. A second marketplace is a
7
+ * second adapter, never a second pipeline, a second acceptance clock or a
8
+ * second idea of what an order is.
9
+ *
10
+ * Deliberately POORER than any marketplace's own payload. Everything a store
11
+ * operates on is here; everything else stays in the inbox row's raw `payload`,
12
+ * which is where a normalization bug is reconstructed from.
13
+ */
14
+ /**
15
+ * A marketplace's id, as its adapter declares it (`"IFOOD"`). Uppercase
16
+ * letters, digits and underscores; the migration's CHECK holds the same shape.
17
+ * A string rather than a closed union, because the set of marketplaces is the
18
+ * set of registered adapters, and a union would make a new one a code change
19
+ * in the engine.
20
+ */
21
+ type MarketplaceProvider = string;
22
+ /** The shape a provider id must have. Shared by the registry and the CHECK. */
23
+ declare const PROVIDER_ID_PATTERN: RegExp;
24
+ /** One line of an incoming order, before it is resolved against the catalog. */
25
+ interface NormalizedOrderLine {
26
+ /** The marketplace's own SKU — the key the SKU map is matched on. */
27
+ externalSku: string;
28
+ /** What the marketplace called it. Snapshotted, and the fallback line text. */
29
+ name: string;
30
+ quantity: number;
31
+ /**
32
+ * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A
33
+ * marketplace's menu carries its own prices, and the buyer's receipt is the
34
+ * marketplace's one: re-pricing from the host's catalog would produce a
35
+ * total nobody was charged.
36
+ */
37
+ unitPriceCents: number;
38
+ /** The buyer's note on this line, when they left one. */
39
+ note: string | null;
40
+ }
41
+ /** The buyer, as much of them as the marketplace discloses. */
42
+ interface NormalizedBuyer {
43
+ /** The marketplace's own stable id for this customer, when it gives one. */
44
+ externalId: string | null;
45
+ name: string | null;
46
+ phone: string | null;
47
+ }
48
+ /** Where a delivery goes, as much of it as the marketplace states. */
49
+ interface NormalizedAddress {
50
+ street: string;
51
+ number: string;
52
+ neighborhood: string;
53
+ complement: string | null;
54
+ /** The sentence that finds the door. */
55
+ reference: string | null;
56
+ postalCode: string | null;
57
+ city: string | null;
58
+ state: string | null;
59
+ }
60
+ /** How the order reaches the buyer: brought to the door, or collected. */
61
+ type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
62
+ /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
63
+ type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
64
+ /** An incoming marketplace order, normalized. */
65
+ interface NormalizedMarketplaceOrder {
66
+ provider: MarketplaceProvider;
67
+ /** The marketplace's order id — THE idempotency key for the whole pipeline. */
68
+ externalOrderId: string;
69
+ /** The short code the courier and the buyer say out loud. */
70
+ externalDisplayId: string | null;
71
+ buyer: NormalizedBuyer;
72
+ lines: NormalizedOrderLine[];
73
+ /**
74
+ * What the buyer paid, gross. NOT derived from the lines when the
75
+ * marketplace states it: its total carries fees, promotions and rounding the
76
+ * line sum does not, and the number that must match the receipt is this one.
77
+ */
78
+ totalCents: number;
79
+ /** The marketplace's cut, when it states one. NULL is "did not say", not 0. */
80
+ commissionCents: number | null;
81
+ /** The marketplace's own promise to the buyer. */
82
+ deliveryDueAt: Date | null;
83
+ /** When the marketplace says the order was placed. */
84
+ placedAt: Date;
85
+ /** Null when the payload does not say. */
86
+ orderType?: MarketplaceOrderType | null;
87
+ /** Null on a take-out and when unstated. */
88
+ deliveredBy?: MarketplaceDeliveredBy | null;
89
+ /** Null on a take-out and when unstated. */
90
+ deliveryAddress?: NormalizedAddress | null;
91
+ }
92
+ /**
93
+ * What an event says about the STORE's own cancellation request: `CONFIRMED`
94
+ * when the marketplace cancelled the order (a pending request is answered),
95
+ * `FAILED` when it refused the request.
96
+ */
97
+ type CancellationOutcome = "CONFIRMED" | "FAILED";
98
+ /** What an adapter makes of one inbound delivery. */
99
+ interface NormalizedEvent {
100
+ provider: MarketplaceProvider;
101
+ /** The delivery's own id — the inbox dedup key, paired with the provider. */
102
+ eventId: string;
103
+ /** The provider's event type verbatim, kept for the inbox row and the log. */
104
+ eventType: string;
105
+ /** The merchant this event names, used to attribute it to a tenant. */
106
+ externalMerchantId: string | null;
107
+ externalOrderId: string | null;
108
+ /**
109
+ * The order this event carries, or null when the event is one the engine
110
+ * understands and does not ingest. A null here is an IGNORED inbox row (or a
111
+ * cancellation, below), never a failure.
112
+ */
113
+ order: NormalizedMarketplaceOrder | null;
114
+ /** The marketplace has CANCELLED the order. */
115
+ cancelled: boolean;
116
+ /**
117
+ * The answer to the store's own cancellation request, when this event is
118
+ * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
119
+ */
120
+ cancellationOutcome?: CancellationOutcome | null;
121
+ }
122
+
123
+ /**
124
+ * The adapter port: everything one marketplace is, behind one shape.
125
+ *
126
+ * The owner's rule, which this file exists to make true: "the integration
127
+ * engine must be the same for all integrations: iFood, Rappi, 99. Only an
128
+ * adapter is made for each one, to connect to the base engine."
129
+ *
130
+ * A marketplace differs from the next in five ways that matter to a store:
131
+ * how its deliveries look and are signed (`normalize`, `readSignature`,
132
+ * `verifySignature`), what it lets a store answer through its API (`confirm`,
133
+ * `requestCancellation`), which reasons a refusal may carry
134
+ * (`cancellationReasons`), and where a person goes when the API cannot do it
135
+ * (`appLink`). Everything else — the inbox, the clock, the SKU map, the
136
+ * outbound bookkeeping and its retries — is the engine's and does not change
137
+ * with the marketplace.
138
+ *
139
+ * What a marketplace CAN do is stated by its adapter as
140
+ * {@link MarketplaceCapabilities} and read by the engine and the host. It is
141
+ * never inferred from the provider's id: a branch on the id outside an adapter
142
+ * would make the next marketplace a code change instead of an adapter.
143
+ *
144
+ * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every
145
+ * outbound call. An adapter never reaches the network on its own, so tests
146
+ * answer the seam and nothing else, and the host owns the timeout, the proxy
147
+ * and the CA.
148
+ */
149
+ /** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */
150
+ interface MarketplaceCredentials {
151
+ clientId: string;
152
+ clientSecret: string;
153
+ /**
154
+ * The shared secret a delivery's signature is verified against. Separate
155
+ * from the OAuth pair: a merchant rotating their webhook secret has not
156
+ * re-onboarded.
157
+ */
158
+ webhookSecret: string | null;
159
+ }
160
+ /** What the host's HTTP client takes. */
161
+ interface MarketplaceHttpRequest {
162
+ method: "GET" | "POST" | "PUT";
163
+ url: string;
164
+ headers: Record<string, string>;
165
+ body?: string;
166
+ }
167
+ /** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */
168
+ interface MarketplaceHttpResponse {
169
+ status: number;
170
+ body: string;
171
+ }
172
+ /** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */
173
+ type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;
174
+ /** What a marketplace can do, stated by its adapter. */
175
+ interface MarketplaceCapabilities {
176
+ /** Accepting is answered through the API. */
177
+ apiConfirm: boolean;
178
+ /** A cancellation can be requested through the API at all. */
179
+ apiCancel: boolean;
180
+ /** …and still once the order was accepted. */
181
+ cancelAfterAccept: boolean;
182
+ /** The cancellation's outcome arrives later as an event rather than in the answer. */
183
+ asyncCancellationOutcome: boolean;
184
+ /** `appLink` names this order, rather than only the marketplace's portal. */
185
+ perOrderAppLink: boolean;
186
+ /** Confirming states a preparation time. */
187
+ confirmTakesPreparationTime: boolean;
188
+ /**
189
+ * OPTIONAL. How long the marketplace takes, at most, to answer a store's
190
+ * cancellation request, in milliseconds: past it the outbound sweep fails
191
+ * the request as TIMEOUT. Absent: only the 24-hour give-up applies.
192
+ */
193
+ cancellationAnswerWindowMs?: number;
194
+ }
195
+ /** One reason a store may give for refusing or cancelling an order. */
196
+ interface CancellationReason {
197
+ /** The marketplace's own code, sent verbatim. */
198
+ code: string;
199
+ /** The label the host was configured with for this code (a named pack). */
200
+ label: string;
201
+ /** This reason means "an item is unavailable": the host preselects it when stock is short. */
202
+ itemUnavailable: boolean;
203
+ /** The marketplace requires the offending SKUs with this reason. */
204
+ needsItems: boolean;
205
+ }
206
+ /** The order an outbound call is about, as the engine knows it. */
207
+ interface OutboundOrderRef {
208
+ externalOrderId: string;
209
+ externalDisplayId: string | null;
210
+ /** The host's own id for the order. */
211
+ hostOrderCode: string;
212
+ /** When the engine recorded the order. */
213
+ placedAt: Date;
214
+ }
215
+ /** A per-engine token cache an adapter reads and fills. Never persisted. */
216
+ type AdapterTokenCache = Map<string, {
217
+ token: string;
218
+ expiresAt: number;
219
+ }>;
220
+ /** What one outbound call is handed. */
221
+ interface AdapterCallContext {
222
+ http: MarketplaceHttp;
223
+ credentials: MarketplaceCredentials;
224
+ environment: "SANDBOX" | "PRODUCTION";
225
+ /** Written to no row, log or audit entry: memory only, per process. */
226
+ tokens: AdapterTokenCache;
227
+ now: Date;
228
+ }
229
+ /** One outbound call's answer, in the three shapes the engine acts on. */
230
+ type OutboundResult =
231
+ /** 2xx. For a marketplace whose outcome is asynchronous, "the request was taken". */
232
+ {
233
+ kind: "accepted";
234
+ }
235
+ /** A final 4xx (not 408/425/429): never retried. */
236
+ | {
237
+ kind: "refused";
238
+ status: number;
239
+ message: string;
240
+ }
241
+ /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */
242
+ | {
243
+ kind: "retry";
244
+ reason: string;
245
+ };
246
+ /** What a cancellation request carries. */
247
+ interface CancellationRequestInput {
248
+ reason: CancellationReason;
249
+ /** Free text from the store; empty means "the reason's own label". */
250
+ text: string;
251
+ mode: "MANUAL" | "AUTO";
252
+ offendingSkus: readonly string[];
253
+ }
254
+ /** One marketplace, in and out. */
255
+ interface MarketplaceAdapter {
256
+ readonly provider: MarketplaceProvider;
257
+ readonly capabilities: MarketplaceCapabilities;
258
+ /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */
259
+ normalize(payload: unknown): NormalizedEvent | null;
260
+ /** Which header carries this marketplace's signature, read off the request. */
261
+ readSignature(header: (name: string) => string | null): string | null;
262
+ /** Is this delivery's signature the one this store's secret would produce? */
263
+ verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;
264
+ /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */
265
+ cancellationReasons(): readonly CancellationReason[];
266
+ /** Tell the marketplace the store accepted the order. */
267
+ confirm(ctx: AdapterCallContext, order: OutboundOrderRef, input: {
268
+ preparationMinutes: number | null;
269
+ }): Promise<OutboundResult>;
270
+ /** Ask the marketplace to cancel the order, with one of its own reasons. */
271
+ requestCancellation(ctx: AdapterCallContext, order: OutboundOrderRef, input: CancellationRequestInput): Promise<OutboundResult>;
272
+ /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
273
+ appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
274
+ }
275
+ /**
276
+ * Read one HTTP answer the way the engine acts on it. Shared by every adapter
277
+ * whose API speaks plain status codes, so the rule is one rule rather than one
278
+ * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and
279
+ * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.
280
+ */
281
+ declare function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult;
282
+ /** A call that never got an answer is a retry, with the reason a log can read. */
283
+ declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
284
+
285
+ export { type AdapterCallContext as A, type CancellationReason as C, type MarketplaceAdapter as M, type NormalizedEvent as N, type OutboundOrderRef as O, PROVIDER_ID_PATTERN as P, type MarketplaceProvider as a, type AdapterTokenCache as b, type CancellationOutcome as c, type CancellationRequestInput as d, type MarketplaceCapabilities as e, type MarketplaceCredentials as f, type MarketplaceDeliveredBy as g, type MarketplaceHttp as h, type MarketplaceHttpRequest as i, type MarketplaceHttpResponse as j, type MarketplaceOrderType as k, type NormalizedAddress as l, type NormalizedBuyer as m, type NormalizedMarketplaceOrder as n, type NormalizedOrderLine as o, type OutboundResult as p, answered as q, outboundResultOf as r };
@@ -0,0 +1,28 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/core/adapter.ts
6
+ var TRANSIENT_CLIENT_STATUSES = /* @__PURE__ */ new Set([408, 425, 429]);
7
+ function outboundResultOf(response) {
8
+ if (response.status >= 200 && response.status < 300) return { kind: "accepted" };
9
+ const message = response.body.slice(0, 300);
10
+ const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);
11
+ if (refusal) return { kind: "refused", status: response.status, message };
12
+ return { kind: "retry", reason: `status ${response.status}: ${message}` };
13
+ }
14
+ __name(outboundResultOf, "outboundResultOf");
15
+ async function answered(call) {
16
+ try {
17
+ return await call();
18
+ } catch (error) {
19
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
20
+ }
21
+ }
22
+ __name(answered, "answered");
23
+
24
+ export {
25
+ outboundResultOf,
26
+ answered
27
+ };
28
+ //# sourceMappingURL=chunk-7BYVGNU5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceProvider, NormalizedEvent } from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n method: \"GET\" | \"POST\" | \"PUT\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /** A final 4xx (not 408/425/429): never retried. */\n | { kind: \"refused\"; status: number; message: string }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAsKA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAShB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
@@ -0,0 +1,7 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ export {
5
+ __name
6
+ };
7
+ //# sourceMappingURL=chunk-7QVYU63E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}