@12-apps/marketplace 1.9.0 → 1.11.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 (75) hide show
  1. package/ADOPTING.md +63 -1
  2. package/README.md +64 -1
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CYJzu1c9.d.ts → adapter-CD0SfdVS.d.ts} +124 -1
  6. package/dist/{chunk-PYHNM47K.js → chunk-DCWOQ5PN.js} +2 -2
  7. package/dist/{chunk-6N2HEV3U.js → chunk-OS4TSIFU.js} +190 -12
  8. package/dist/chunk-OS4TSIFU.js.map +1 -0
  9. package/dist/chunk-SGOTN5PX.js +345 -0
  10. package/dist/chunk-SGOTN5PX.js.map +1 -0
  11. package/dist/{chunk-HEXLCTOG.js → chunk-TVZU4HNT.js} +1 -1
  12. package/dist/chunk-TVZU4HNT.js.map +1 -0
  13. package/dist/{chunk-BMCERPQX.js → chunk-YWMEIMO3.js} +221 -27
  14. package/dist/chunk-YWMEIMO3.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-11sncog4.d.ts} +1 -1
  16. package/dist/{engine-wmW-VuBL.d.ts → engine-C_3RK8wC.d.ts} +207 -64
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +5 -2
  20. package/dist/ifood/index.js +125 -7
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +280 -26
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -2
  26. package/dist/keeta/index.js +2 -2
  27. package/dist/manifest/index.d.ts +223 -2
  28. package/dist/manifest/index.js +1 -1
  29. package/dist/manifest/server.d.ts +2 -2
  30. package/dist/manifest/server.js +3 -3
  31. package/dist/rappi/index.d.ts +1 -1
  32. package/dist/rappi/index.js +1 -1
  33. package/dist/server/en-US.d.ts +13 -0
  34. package/dist/server/en-US.js +13 -0
  35. package/dist/server/en-US.js.map +1 -1
  36. package/dist/server/index.d.ts +246 -8
  37. package/dist/server/index.js +3 -3
  38. package/dist/server/pt-BR.d.ts +13 -0
  39. package/dist/server/pt-BR.js +13 -0
  40. package/dist/server/pt-BR.js.map +1 -1
  41. package/package.json +1 -1
  42. package/prisma/marketplace.prisma +47 -0
  43. package/prisma/migrations/20261126230000_marketplace_menu_link_variation/migration.sql +11 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +21 -0
  46. package/src/core/bulk.ts +77 -15
  47. package/src/core/engine.ts +59 -3
  48. package/src/core/ingest.ts +2 -1
  49. package/src/core/integration.ts +60 -32
  50. package/src/core/link-store.ts +170 -0
  51. package/src/core/linking-port.ts +100 -0
  52. package/src/core/linking.ts +363 -0
  53. package/src/core/menu-links.ts +36 -6
  54. package/src/core/merchant-claim.ts +106 -0
  55. package/src/core/order-types.ts +74 -0
  56. package/src/core/ports.ts +26 -65
  57. package/src/ifood/index.ts +4 -0
  58. package/src/ifood/linking.ts +170 -0
  59. package/src/ifood/outbound.ts +10 -3
  60. package/src/index.ts +14 -0
  61. package/src/server/copy.ts +20 -2
  62. package/src/server/en-US.ts +13 -0
  63. package/src/server/index.ts +1 -1
  64. package/src/server/link-routes.ts +140 -0
  65. package/src/server/mcp-link.ts +103 -0
  66. package/src/server/mcp.ts +13 -4
  67. package/src/server/pt-BR.ts +13 -0
  68. package/src/server/routes.ts +5 -2
  69. package/src/server/webhook.ts +86 -0
  70. package/dist/chunk-6N2HEV3U.js.map +0 -1
  71. package/dist/chunk-BMCERPQX.js.map +0 -1
  72. package/dist/chunk-HEXLCTOG.js.map +0 -1
  73. package/dist/chunk-NP4EYKPO.js +0 -252
  74. package/dist/chunk-NP4EYKPO.js.map +0 -1
  75. /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
package/ADOPTING.md CHANGED
@@ -14,8 +14,9 @@ error at mount, never a default that quietly adopts another host's policy.
14
14
  | `db` | `() => Promise<MarketplaceDb>` | The Prisma client generated from a schema that includes `prisma/marketplace.prisma`. Structural: the four delegates `marketplaceIntegration`, `marketplaceMenuLink`, `marketplaceInboxEvent`, `marketplaceAcceptance`, and the catalogue's `marketplaceCataloguePublication` (optional in the type; the catalogue calls need it). |
15
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
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). |
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); `lines[i].variationRef` is the variation of it the SKU was mapped to, or null for the item alone. `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
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.catalogHasVariation` (optional) | `(clientId, subjectRef, variationRef) => Promise<boolean>` | Is `variationRef` a variation of this tenant's catalog id `subjectRef`? Asked before a SKU is mapped to a variation, after `catalogHas`. Absent: a mapping that names a variation is refused (`CATALOG_ITEM_NOT_FOUND` at `variationId`). |
19
20
  | `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
21
  | `order.mayAutoAccept` | OPTIONAL. `(clientId) => Promise<boolean>` | May a NEW order of this tenant be accepted automatically? Asked once per order, before the ingest's transaction, and only when the connection auto-accepts (never for a redelivery). `false` declines the automatic acceptance: the order lands exactly as with auto-accept off (AWAITING on the clock, no confirm queued, no `onAccepted`) and a person decides it; the order is never refused for it. A throw is logged and declines too. Not bound: every auto-accept proceeds, as before. It sits on every order's ingest, so answer it from something already in hand rather than a fresh query. |
21
22
  | `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. |
@@ -33,6 +34,7 @@ error at mount, never a default that quietly adopts another host's policy.
33
34
  | `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
34
35
  | `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
35
36
  | `catalogue` | OPTIONAL. `{ items(clientId, productIds) => Promise<Map<string, CatalogueItem>>; image(url) => Promise<{ contentType; base64 } \| null> }` | Catalogue publishing (1.2, FUT-4768). `items` maps the host's products into `{ name, description, imageUrl, categoryName, priceCents }` (the store's price, smallest unit; the photo an absolute https URL that CHANGES when the photo changes, such as a content hash or upload id in it: a marketplace's uploaded copy is reused while the URL is the same), keyed by product id; a missing id is a product that no longer exists. Called at publish (to check it exists) and by the job when it sends, so what goes out is the product as it is then. `image` reads a photo's bytes for a marketplace that takes an upload (iFood); null publishes without a photo. Absent: every catalogue call answers `UNSUPPORTED`. |
37
+ | `appCredentials` | OPTIONAL. `(provider, environment) => { clientId; clientSecret; webhookSecret } \| null` (sync or async) | The software's OWN app on each marketplace, for linking a store without its own credentials (FUT-5613, section 9). Absent or null: linking is unavailable there and the per-store credentials work as before. |
36
38
  | `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. |
37
39
 
38
40
  Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
@@ -239,6 +241,15 @@ not composed the model still compiles, and the two paths then do nothing.
239
241
  switches over either exhaustively adds the case; allow `"status"` in any
240
242
  action allow-list in front of the outbound job.
241
243
 
244
+ `20261127090000_marketplace_app_link` (FUT-5613) adds
245
+ `marketplace_integrations.auth_mode` (NOT NULL DEFAULT 'CREDENTIALS', CHECKed
246
+ CREDENTIALS | LINKED: every existing connection stays the store's own app) and
247
+ `marketplace_link_attempts`, one linking in progress per (store, marketplace)
248
+ with its sealed verifier, environment CHECKed and provider shape-checked.
249
+ Additive. Compose it with the schema in the same change as the engine bump:
250
+ the engine selects `auth_mode`. `MarketplaceDb.marketplaceLinkAttempt` is
251
+ optional in the type; without it linking reports itself unavailable.
252
+
242
253
  ## 6. What stays the host's
243
254
 
244
255
  The stock draw at the acceptance, the settlement effects, the board's and the
@@ -292,3 +303,54 @@ if you want one). The `MarketplaceDb.marketplaceStorePause` delegate is
292
303
  OPTIONAL in the type, so a 1.x host compiles before it migrates; `pauseStore`
293
304
  and `resumeStore` throw naming the migration until it does, and
294
305
  `availabilityState` reads every marketplace OPEN.
306
+
307
+ ## 8. Mapping a SKU to a variation (FUT-4927)
308
+
309
+ A marketplace SKU usually names one flavour or size of an item. A link can now
310
+ carry that variation beside the catalog id: `variationId` on
311
+ `upsertMenuLinks` / `setMenuLink` rows, on `PUT …/menu-links` and its MCP
312
+ tool, and on every link view. Absent or null maps the item alone, exactly as
313
+ before; a write always sets both halves, so re-mapping to the item clears a
314
+ variation and an unmap clears both. A variation on an unmap is refused.
315
+
316
+ **The port.** Bind `order.catalogHasVariation(clientId, subjectRef,
317
+ variationRef)` to answer whether the variation is one of that item's and the
318
+ tenant's. Without it every mapping that names a variation is refused, and
319
+ mapping to the item works as it did.
320
+
321
+ **The line.** `ResolvedOrderLine.variationRef` is the mapped variation, or
322
+ null. Write it on the order line with `subjectRef`; a host that ignores it
323
+ keeps selling the item alone.
324
+
325
+ **The database.** Migration `20261126230000_marketplace_menu_link_variation`
326
+ adds the nullable `marketplace_menu_links.variation_id`: additive, no foreign
327
+ key, every existing link stays the item alone. The engine selects the column,
328
+ so a Prisma client generated before the migration throws on the unknown
329
+ `variationId`: on the bump, sync the partial, run `prisma generate` and apply
330
+ the migration together.
331
+
332
+ ## 9. Linking a store through the software's own app
333
+
334
+ The flow and its routes are in the README ("Linking a store through the
335
+ software's own app"). What the host binds and decides:
336
+
337
+ - **`appCredentials`** (OPTIONAL port): `(provider, environment) =>
338
+ { clientId, clientSecret, webhookSecret } | null`, sync or async, read at
339
+ each use (a rotation reaches every linked store at once). Answer it from the
340
+ host's secret store; never from a store's row. Null or unbound: the screen
341
+ shows the per-store form, as before.
342
+ - **The app's webhook**: register `…/webhooks/marketplace/IFOOD` (under the
343
+ host's mount) as the app's one webhook address on iFood's developer portal,
344
+ iFood signs it with the app's client secret, so `webhookSecret` may be left
345
+ null; pass it only to verify with another key.
346
+ - **The screen** is the host's: `GET …/link` says whether to offer it and
347
+ restores a code in progress after a reload; `start`, `finish` and, when the
348
+ grant covers several iFood stores, `merchants` and `merchant`. Each refusal
349
+ answers a `code` (`UNAVAILABLE`, `NO_LINK_IN_PROGRESS`, `LINK_EXPIRED`,
350
+ `CODE_REFUSED`, `MARKETPLACE_REFUSED`, `NOT_LINKED`, `UNKNOWN_MERCHANT`,
351
+ `MERCHANT_TAKEN`; 503 `MARKETPLACE_UNREACHABLE`) and the pack's sentence
352
+ (`copy.link`, optional in the type, carried by both shipped packs).
353
+ - **Disconnect** is the existing archive (`PUT …/marketplace`, operation
354
+ `archive`): the row is kept; linking again unarchives it with its audit line.
355
+ - **A view** gains `authMode`; a host that switches on it treats an absent
356
+ value as `CREDENTIALS`.
package/README.md CHANGED
@@ -42,7 +42,7 @@ engine code (`src/__tests__/second-adapter.test.ts`).
42
42
  | **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, unless the host's optional `order.mayAutoAccept` declines it, and then the order lands AWAITING as if auto-accept were off. |
43
43
  | **Acceptance clock** | `AWAITING → ACCEPTED | REJECTED | EXPIRED`, every transition predicated on the current state. The sweep never touches an accepted order. |
44
44
  | **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. |
45
- | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. |
45
+ | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. A link may name ONE variation of that id (`variationId`): the host's optional `order.catalogHasVariation` checks it belongs, and ingest hands it on the line as `variationRef` beside `subjectRef`. Without a variation the SKU maps to the item alone, as before. |
46
46
  | **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. |
47
47
  | **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. |
48
48
  | **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. |
@@ -226,6 +226,69 @@ They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
226
226
  headers say so, so the homologation run corrects two files. Tests never reach
227
227
  iFood: the HTTP client is the host's port.
228
228
 
229
+ ## Linking a store through the software's own app (FUT-5613)
230
+
231
+ A store connects iFood WITHOUT typing a client id, a secret, a webhook key or a
232
+ webhook address: it authorizes the software's own iFood app (iFood's
233
+ "distributed app") on iFood's portal. The host's screen is three steps; the
234
+ engine supplies each one:
235
+
236
+ | step | engine | route (`marketplace:manage`) |
237
+ |---|---|---|
238
+ | the code to copy, and the portal link that already carries it | `startLink({ clientId, provider, environment? })` → `{ userCode, verificationUrl, verificationUrlComplete, expiresAt }` | `POST …/marketplace/link/start` |
239
+ | the screen after a reload | `linkState(...)` → `{ available, pending }` | `GET …/marketplace/link?provider=` |
240
+ | the authorization code pasted back | `finishLink({ clientId, provider, authorizationCode, actorId, enabled? })` → `{ integration, merchants }` | `POST …/marketplace/link/finish` |
241
+ | a grant covering several iFood stores | `linkedMerchants(...)`, `selectLinkedMerchant({ …, merchantId })` | `GET …/link/merchants`, `PUT …/link/merchant` |
242
+
243
+ - **The verifier never leaves the server.** `startLink` seals iFood's
244
+ `authorizationCodeVerifier` with the host's secrets port into
245
+ `marketplace_link_attempts` (one per store and marketplace; starting again
246
+ replaces it; the exchange removes it). No answer carries a token, the
247
+ verifier or the app's credentials.
248
+ - **The tokens.** `finishLink` stores the refresh token sealed in the
249
+ connection's `credentials` and marks it `authMode: "LINKED"`, `VERIFIED`,
250
+ unarchived (a disconnected store reconnecting gets its `unarchive` audit
251
+ line). The merchant is selected when the grant covers exactly one, and
252
+ never when another store's live connection holds it. The access token lives
253
+ in the per-process cache, per STORE (never per app); a missing or expiring
254
+ one is refreshed once however many calls ask at once, and a rotated refresh
255
+ token is stored back. A refused refresh marks the connection `FAILED`: the
256
+ store links again.
257
+ - **The app's credentials** are the host's, through the optional
258
+ `appCredentials(provider, environment)` port (client id, secret, and
259
+ optionally a separate key the app's deliveries are signed with; absent or
260
+ empty, the client secret, which is what iFood signs with). Unbound, or null for a marketplace:
261
+ `available: false`, and a store's own credentials keep working exactly as
262
+ before. Typing credentials into a linked connection makes it `CREDENTIALS`
263
+ again.
264
+ - **One webhook address for every linked store:** `POST
265
+ /webhooks/marketplace/:provider`. The store is found by the merchant the
266
+ delivery names, and the delivery must carry a valid signature by the app's
267
+ key (unsigned is refused here, whatever the store's own setting). The
268
+ per-store address keeps working, and a linked store's never accepts an
269
+ unsigned delivery either. A merchant is held by one live connection of a
270
+ marketplace at a time: every write refuses `MERCHANT_TAKEN` at
271
+ `externalMerchantId`, and a partial unique index backs it. A linked
272
+ connection with no merchant chosen yet (the list failed, or the grant covers
273
+ several) has every delivery to this address refused, and iFood redelivers,
274
+ until the store chooses one.
275
+
276
+ What iFood's pages settle, read 2026-11-26 as Markdown
277
+ (`developer.ifood.com.br/pt-BR/docs/guides/modules/authentication/distributed.md`,
278
+ `…/merchant/endpoints.md`), and what they do not:
279
+
280
+ | fact | status |
281
+ |---|---|
282
+ | `POST /authentication/v1.0/oauth/userCode`, form `clientId` → `userCode`, `authorizationCodeVerifier`, `verificationUrl`, `verificationUrlComplete`, `expiresIn` (600: ten minutes) | CONFIRMED |
283
+ | `POST /authentication/v1.0/oauth/token`, form `grantType=authorization_code`, `clientId`, `clientSecret`, `authorizationCode`, `authorizationCodeVerifier`; and `grantType=refresh_token` with `refreshToken` | CONFIRMED |
284
+ | The token answer: `accessToken`, `type`, `expiresIn` (21600: six hours) | CONFIRMED |
285
+ | The refresh token's FIELD in that answer (`refreshToken`, `refresh_token` as a fallback) | ESTIMATED: the page says one is returned, its table lists none |
286
+ | Whether a refresh rotates the refresh token | ESTIMATED: stored when answered, kept when not |
287
+ | The refresh token's lifetime | ESTIMATED: unstated; a refused refresh marks the connection FAILED |
288
+ | `GET /merchant/v1.0/merchants?page=&size=` (size 100) → `[{ id, name, corporateName }]` | CONFIRMED |
289
+ | The status of a wrong or used authorization code | ESTIMATED: any final 4xx is `CODE_REFUSED` |
290
+ | The key iFood signs an app's webhook deliveries with | CONFIRMED (`webhook-signature.md`): the app's `client_secret`, the default when `webhookSecret` is absent |
291
+
229
292
  ## 99Food, on Open Delivery
230
293
 
231
294
  99Food completed Open Delivery (Abrasel) adherence, so its adapter speaks
@@ -1,5 +1,5 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CYJzu1c9.js';
2
- import { O as OpenDeliveryApiBaseUrls } from '../client-B4EQCRD_.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CD0SfdVS.js';
2
+ import { O as OpenDeliveryApiBaseUrls } from '../client-11sncog4.js';
3
3
 
4
4
  /**
5
5
  * The words the 99Food adapter needs from its host, and nothing else.
@@ -12,10 +12,10 @@ import {
12
12
  openDeliveryStatus,
13
13
  openDeliverySwitchAvailability,
14
14
  verifyOpenDeliverySignature
15
- } from "../chunk-PYHNM47K.js";
15
+ } from "../chunk-DCWOQ5PN.js";
16
16
  import "../chunk-M2V4RFMA.js";
17
17
  import "../chunk-BD7DS3XM.js";
18
- import "../chunk-HEXLCTOG.js";
18
+ import "../chunk-TVZU4HNT.js";
19
19
  import {
20
20
  __name
21
21
  } from "../chunk-7QVYU63E.js";
@@ -303,6 +303,108 @@ interface CatalogueReader {
303
303
  */
304
304
  declare function centsFromMajor(value: unknown): number | null;
305
305
 
306
+ /**
307
+ * LINKING a store through the software's OWN marketplace app (FUT-5613): the
308
+ * store authorizes the software's app on the marketplace's portal, and never
309
+ * types a client id, a secret, a webhook key or a webhook address.
310
+ *
311
+ * The flow, as an adapter states it (iFood's "distributed app"):
312
+ *
313
+ * 1. `requestCode`: the app asks for a short code the store types (or a link
314
+ * that already carries it) on the marketplace's portal, plus a VERIFIER the
315
+ * engine keeps server-side for that store and never hands the browser.
316
+ * 2. The store authorizes the app on the portal and is shown an
317
+ * AUTHORIZATION CODE, which it pastes back.
318
+ * 3. `exchange`: the code plus the verifier buy an access token and a refresh
319
+ * token, stored sealed on the store's connection.
320
+ * 4. `merchants`: which of the marketplace's stores the grant covers; one is
321
+ * selected at once.
322
+ * 5. `refresh`: a new access token from the refresh token, whenever the
323
+ * cached one is gone. A rotated refresh token is stored back.
324
+ *
325
+ * The app's own credentials are the HOST's configuration, one pair per
326
+ * marketplace and environment ({@link MarketplaceAppCredentialsPort}), never a
327
+ * store's.
328
+ */
329
+ /** What a linking call is handed: the APP's credentials, never a store's. */
330
+ interface LinkCallContext {
331
+ http: MarketplaceHttp;
332
+ credentials: MarketplaceCredentials;
333
+ environment: "SANDBOX" | "PRODUCTION";
334
+ now: Date;
335
+ }
336
+ /** The code a store types on the marketplace's portal, and the verifier kept for it. */
337
+ interface LinkCode {
338
+ /** Shown to the person: they type it on the portal. */
339
+ userCode: string;
340
+ /** The portal page the code is typed on. */
341
+ verificationUrl: string;
342
+ /** The same page with the code already in it: the link the screen opens. */
343
+ verificationUrlComplete: string;
344
+ /** How long the code lives, in seconds. */
345
+ expiresInSeconds: number;
346
+ /** Kept server-side for this store until the exchange. NEVER sent to a browser. */
347
+ verifier: string;
348
+ }
349
+ /** What an exchange or a refresh buys. */
350
+ interface LinkGrant {
351
+ accessToken: string;
352
+ /** How long the access token lives, in seconds. */
353
+ expiresInSeconds: number;
354
+ /**
355
+ * The refresh token. An exchange always answers one; a refresh answers one
356
+ * when the marketplace rotates it, and null when the old one stays valid.
357
+ */
358
+ refreshToken: string | null;
359
+ }
360
+ /** One marketplace store the grant covers. */
361
+ interface LinkedMerchant {
362
+ id: string;
363
+ name: string | null;
364
+ corporateName: string | null;
365
+ }
366
+ /**
367
+ * A linking call's answer: the value, or why there is none. `refused` is
368
+ * final (the marketplace judged the request: a wrong or used code, a refresh
369
+ * token it no longer honours); `retry` is the network, a 5xx, a rate limit.
370
+ */
371
+ type LinkResult<T> = {
372
+ kind: "ok";
373
+ value: T;
374
+ } | Exclude<OutboundResult, {
375
+ kind: "accepted";
376
+ }>;
377
+ /** The adapter's half: the marketplace's wire format for each step, and nothing else. */
378
+ interface MarketplaceLinking {
379
+ requestCode(ctx: LinkCallContext): Promise<LinkResult<LinkCode>>;
380
+ exchange(ctx: LinkCallContext, input: {
381
+ authorizationCode: string;
382
+ verifier: string;
383
+ }): Promise<LinkResult<LinkGrant>>;
384
+ refresh(ctx: LinkCallContext, input: {
385
+ refreshToken: string;
386
+ }): Promise<LinkResult<LinkGrant>>;
387
+ merchants(ctx: LinkCallContext, input: {
388
+ accessToken: string;
389
+ }): Promise<LinkResult<LinkedMerchant[]>>;
390
+ }
391
+ /**
392
+ * The host's configuration of its OWN app on a marketplace: client id, client
393
+ * secret, and the key the marketplace signs the app's webhook deliveries with.
394
+ * Null (or the port not bound) means the software has no app there, and the
395
+ * linking flow reports itself unavailable; a store's own credentials keep
396
+ * working unchanged either way.
397
+ */
398
+ type MarketplaceAppCredentialsPort = (provider: string, environment: "SANDBOX" | "PRODUCTION") => MarketplaceCredentials | null | Promise<MarketplaceCredentials | null>;
399
+ /** The link-attempt delegate the engine reads and writes (the `MarketplaceLinkAttempt` model). */
400
+ interface MarketplaceLinkAttemptDelegate {
401
+ findUnique(args: unknown): Promise<unknown>;
402
+ upsert(args: unknown): Promise<unknown>;
403
+ deleteMany(args: unknown): Promise<{
404
+ count: number;
405
+ }>;
406
+ }
407
+
306
408
  /**
307
409
  * The adapter port's OPTIONAL availability capability: closing a store on a
308
410
  * marketplace for a while, and opening it again (FUT-4851).
@@ -705,14 +807,30 @@ type AdapterTokenCache = Map<string, {
705
807
  token: string;
706
808
  expiresAt: number;
707
809
  }>;
810
+ /**
811
+ * A connection LINKED through the software's own app (FUT-5613): the store's
812
+ * access token comes from its refresh token, not from a client-credentials
813
+ * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it
814
+ * to forget a token the marketplace refused); `accessToken` answers the cached
815
+ * one or refreshes, once per connection however many calls ask at once.
816
+ */
817
+ interface AdapterGrant {
818
+ key: string;
819
+ accessToken(): Promise<{
820
+ token: string;
821
+ } | OutboundResult>;
822
+ }
708
823
  /** What one outbound call is handed. */
709
824
  interface AdapterCallContext {
710
825
  http: MarketplaceHttp;
826
+ /** The store's own credentials, or, for a linked connection, the software's app. */
711
827
  credentials: MarketplaceCredentials;
712
828
  environment: "SANDBOX" | "PRODUCTION";
713
829
  /** Written to no row, log or audit entry: memory only, per process. */
714
830
  tokens: AdapterTokenCache;
715
831
  now: Date;
832
+ /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */
833
+ grant?: AdapterGrant;
716
834
  }
717
835
  /** One outbound call's answer, in the three shapes the engine acts on. */
718
836
  type OutboundResult =
@@ -818,6 +936,11 @@ interface MarketplaceAdapter {
818
936
  * API, and the host says so.
819
937
  */
820
938
  readonly availability?: MarketplaceAvailability;
939
+ /**
940
+ * OPTIONAL. Linking a store through the software's own app on this
941
+ * marketplace (FUT-5613). Absent: a store connects with its own credentials only.
942
+ */
943
+ readonly linking?: MarketplaceLinking;
821
944
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
822
945
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
823
946
  }
@@ -837,4 +960,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
837
960
  /** A call that never got an answer is a retry, with the reason a log can read. */
838
961
  declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
839
962
 
840
- export { type NormalizedOrderLine as $, type AdapterCallContext as A, type CatalogueSnapshotCategory as B, type CatalogueMenuEntry as C, type CatalogueSnapshotItem as D, type CatalogueSnapshotOption as E, type CatalogueSnapshotOptionGroup as F, type CatalogueStoredImage as G, type CatalogueWarningCode as H, type FetchOrderResult as I, type MarketplaceCapabilities as J, type MarketplaceCatalogue as K, type MarketplaceCredentials as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type MarketplaceDeliveredBy as Q, type MarketplaceDiscountSponsor as R, type StorePauseRequest as S, type MarketplaceHttp as T, type MarketplaceHttpRequest as U, type MarketplaceHttpResponse as V, type MarketplaceLifecycle as W, type MarketplaceOrderType as X, type NormalizedAddress as Y, type NormalizedBuyer as Z, type NormalizedOrderDiscount as _, type NormalizedMarketplaceOrder as a, type OutboundOrderRef as a0, PROVIDER_ID_PATTERN as a1, type StatusFacts as a2, type StatusStep as a3, answered as a4, centsFromMajor as a5, outboundResultOf as a6, tokenGrantResultOf as a7, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type StorePauseResult as g, type StorePauseRef as h, type MarketplaceProvider as i, type CancellationReason as j, type AdapterTokenCache as k, type CancellationOutcome as l, type CancellationRequestInput as m, type CatalogueCallContext as n, type CatalogueFailure as o, type CatalogueImage as p, type CatalogueItem as q, type CatalogueItemRef as r, type CataloguePublishResult as s, type CatalogueReadContext as t, type CatalogueReadNotice as u, type CatalogueReadRefusalCode as v, type CatalogueReadResult as w, type CatalogueReadWarning as x, type CatalogueReadWarningCode as y, type CatalogueSnapshot as z };
963
+ export { type MarketplaceHttp as $, type AdapterCallContext as A, type CatalogueReadWarningCode as B, type CatalogueMenuEntry as C, type CatalogueSnapshot as D, type CatalogueSnapshotCategory as E, type CatalogueSnapshotItem as F, type CatalogueSnapshotOption as G, type CatalogueSnapshotOptionGroup as H, type CatalogueStoredImage as I, type CatalogueWarningCode as J, type FetchOrderResult as K, type LinkCallContext as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type LinkCode as Q, type LinkGrant as R, type StorePauseRequest as S, type LinkResult as T, type LinkedMerchant as U, type MarketplaceAppCredentialsPort as V, type MarketplaceCapabilities as W, type MarketplaceCatalogue as X, type MarketplaceCredentials as Y, type MarketplaceDeliveredBy as Z, type MarketplaceDiscountSponsor as _, type NormalizedMarketplaceOrder as a, type MarketplaceHttpRequest as a0, type MarketplaceHttpResponse as a1, type MarketplaceLifecycle as a2, type MarketplaceLinkAttemptDelegate as a3, type MarketplaceOrderType as a4, type NormalizedAddress as a5, type NormalizedBuyer as a6, type NormalizedOrderDiscount as a7, type NormalizedOrderLine as a8, type OutboundOrderRef as a9, PROVIDER_ID_PATTERN as aa, type StatusFacts as ab, type StatusStep as ac, answered as ad, centsFromMajor as ae, outboundResultOf as af, tokenGrantResultOf as ag, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type MarketplaceLinking as g, type StorePauseResult as h, type StorePauseRef as i, type MarketplaceProvider as j, type CancellationReason as k, type AdapterGrant as l, type AdapterTokenCache as m, type CancellationOutcome as n, type CancellationRequestInput as o, type CatalogueCallContext as p, type CatalogueFailure as q, type CatalogueImage as r, type CatalogueItem as s, type CatalogueItemRef as t, type CataloguePublishResult as u, type CatalogueReadContext as v, type CatalogueReadNotice as w, type CatalogueReadRefusalCode as x, type CatalogueReadResult as y, type CatalogueReadWarning as z };
@@ -14,7 +14,7 @@ import {
14
14
  answered,
15
15
  outboundResultOf,
16
16
  tokenGrantResultOf
17
- } from "./chunk-HEXLCTOG.js";
17
+ } from "./chunk-TVZU4HNT.js";
18
18
  import {
19
19
  __name
20
20
  } from "./chunk-7QVYU63E.js";
@@ -475,4 +475,4 @@ export {
475
475
  normalizeOpenDeliveryEventAs,
476
476
  normalizeOpenDeliveryOrderAs
477
477
  };
478
- //# sourceMappingURL=chunk-PYHNM47K.js.map
478
+ //# sourceMappingURL=chunk-DCWOQ5PN.js.map