@12-apps/marketplace 1.10.0 → 1.12.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 (84) hide show
  1. package/ADOPTING.md +126 -1
  2. package/README.md +100 -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-nUyZpLzz.d.ts} +448 -173
  6. package/dist/{chunk-2BA2EHNF.js → chunk-45ZVN5XI.js} +316 -42
  7. package/dist/chunk-45ZVN5XI.js.map +1 -0
  8. package/dist/{chunk-PYHNM47K.js → chunk-L6FG6T4S.js} +2 -2
  9. package/dist/{chunk-HEXLCTOG.js → chunk-LACBT6NC.js} +1 -1
  10. package/dist/chunk-LACBT6NC.js.map +1 -0
  11. package/dist/{chunk-WVZ2IXFH.js → chunk-MIPNQ7X5.js} +190 -12
  12. package/dist/chunk-MIPNQ7X5.js.map +1 -0
  13. package/dist/chunk-SGOTN5PX.js +345 -0
  14. package/dist/chunk-SGOTN5PX.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-Ctas7WCS.d.ts} +1 -1
  16. package/dist/{engine-DK3iV_Kk.d.ts → engine-CIy9P7Cq.d.ts} +149 -8
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +10 -2
  20. package/dist/ifood/index.js +297 -25
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +424 -84
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -18
  26. package/dist/keeta/index.js +12 -3
  27. package/dist/keeta/index.js.map +1 -1
  28. package/dist/manifest/index.d.ts +219 -1
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +2 -2
  31. package/dist/manifest/server.js +3 -3
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/en-US.d.ts +13 -0
  35. package/dist/server/en-US.js +13 -0
  36. package/dist/server/en-US.js.map +1 -1
  37. package/dist/server/index.d.ts +241 -7
  38. package/dist/server/index.js +3 -3
  39. package/dist/server/pt-BR.d.ts +13 -0
  40. package/dist/server/pt-BR.js +13 -0
  41. package/dist/server/pt-BR.js.map +1 -1
  42. package/package.json +1 -1
  43. package/prisma/marketplace.prisma +41 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +27 -0
  46. package/src/core/bulk.ts +43 -8
  47. package/src/core/courier-port.ts +100 -0
  48. package/src/core/courier.ts +153 -0
  49. package/src/core/engine.ts +63 -4
  50. package/src/core/integration.ts +60 -32
  51. package/src/core/lifecycle.ts +27 -4
  52. package/src/core/link-store.ts +170 -0
  53. package/src/core/linking-port.ts +100 -0
  54. package/src/core/linking.ts +363 -0
  55. package/src/core/merchant-claim.ts +106 -0
  56. package/src/core/outbound-queue.ts +24 -11
  57. package/src/core/outbound.ts +8 -6
  58. package/src/core/pickup-code.ts +136 -0
  59. package/src/core/pipeline.ts +15 -6
  60. package/src/core/ports.ts +26 -1
  61. package/src/core/status-store.ts +2 -3
  62. package/src/core/types.ts +56 -4
  63. package/src/ifood/courier.ts +210 -0
  64. package/src/ifood/index.ts +8 -0
  65. package/src/ifood/linking.ts +170 -0
  66. package/src/ifood/normalize.ts +7 -0
  67. package/src/ifood/outbound.ts +10 -3
  68. package/src/index.ts +30 -0
  69. package/src/keeta/normalize.ts +21 -6
  70. package/src/server/copy.ts +20 -2
  71. package/src/server/en-US.ts +13 -0
  72. package/src/server/index.ts +1 -1
  73. package/src/server/link-routes.ts +140 -0
  74. package/src/server/mcp-link.ts +103 -0
  75. package/src/server/mcp.ts +6 -2
  76. package/src/server/pt-BR.ts +13 -0
  77. package/src/server/routes.ts +5 -2
  78. package/src/server/webhook.ts +86 -0
  79. package/dist/chunk-2BA2EHNF.js.map +0 -1
  80. package/dist/chunk-HEXLCTOG.js.map +0 -1
  81. package/dist/chunk-WVZ2IXFH.js.map +0 -1
  82. package/dist/chunk-ZO4S3LF4.js +0 -254
  83. package/dist/chunk-ZO4S3LF4.js.map +0 -1
  84. /package/dist/{chunk-PYHNM47K.js.map → chunk-L6FG6T4S.js.map} +0 -0
@@ -0,0 +1,170 @@
1
+ import { outboundResultOf, type MarketplaceHttpRequest } from "../core/adapter";
2
+ import type { LinkCallContext, LinkCode, LinkGrant, LinkResult, LinkedMerchant, MarketplaceLinking } from "../core/linking-port";
3
+ import { asString, pick } from "../core/payload-read";
4
+ import { IFOOD_API } from "./outbound";
5
+
6
+ /**
7
+ * iFood's DISTRIBUTED-APP authentication, the wire format only (FUT-5613).
8
+ * Read 2026-11-26 off iFood's own pages, served as Markdown at
9
+ * https://developer.ifood.com.br/pt-BR/docs/guides/modules/authentication/distributed.md
10
+ * and .../merchant/endpoints.md:
11
+ *
12
+ * - `POST /authentication/v1.0/oauth/userCode`, form `clientId` → 200
13
+ * `{ userCode, authorizationCodeVerifier, verificationUrl,
14
+ * verificationUrlComplete, expiresIn }` ("valid for 10 minutes", 600).
15
+ * - `POST /authentication/v1.0/oauth/token`, form `grantType=authorization_code`,
16
+ * `clientId`, `clientSecret`, `authorizationCode`, `authorizationCodeVerifier`
17
+ * → 200 `{ accessToken, type: "bearer", expiresIn }` (6 hours by default)
18
+ * and a refresh token ("returns an access token and a refresh token").
19
+ * - The same URL, `grantType=refresh_token`, `clientId`, `clientSecret`,
20
+ * `refreshToken`.
21
+ * - `GET /merchant/v1.0/merchants?page=&size=` (size default 100) → 200
22
+ * `[{ id, name, corporateName }]`: every store the token covers.
23
+ *
24
+ * ESTIMATED, not settled by those pages:
25
+ * - the refresh token's FIELD name in the token answer: the page's table
26
+ * lists only `accessToken`, `type`, `expiresIn`; `refreshToken` (the name
27
+ * the request takes) is read, and the snake-case twin as a fallback;
28
+ * - whether a refresh ROTATES the refresh token: a new one is stored when
29
+ * answered, the old one kept when not;
30
+ * - the refresh token's own lifetime (unstated: "if the refreshToken
31
+ * expires, the user must authorize again"): a refused refresh marks the
32
+ * connection FAILED for the store to link again;
33
+ * - the status of a wrong or used authorization code: any final 4xx is
34
+ * `refused`.
35
+ */
36
+
37
+ const USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
38
+ const TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
39
+ const MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
40
+
41
+ /** iFood's documented lifetime of a user code, used when the answer states none. */
42
+ const USER_CODE_SECONDS = 600;
43
+ /** iFood's documented default lifetime of an access token: 6 hours. */
44
+ const ACCESS_TOKEN_SECONDS = 21_600;
45
+ /** One page of the merchant list; iFood's documented default. */
46
+ const MERCHANT_PAGE_SIZE = 100;
47
+ /** A ceiling on pages read, so a misbehaving answer cannot loop. */
48
+ const MAX_MERCHANT_PAGES = 20;
49
+
50
+ const FORM = { "Content-Type": "application/x-www-form-urlencoded" };
51
+
52
+ function json(body: string): unknown {
53
+ try {
54
+ return body === "" ? null : (JSON.parse(body) as unknown);
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /** One call whose 2xx body `read` turns into the value; anything else ends it. */
61
+ async function call<T>(
62
+ ctx: LinkCallContext,
63
+ request: MarketplaceHttpRequest,
64
+ read: (body: unknown) => T | null,
65
+ ): Promise<LinkResult<T>> {
66
+ try {
67
+ const response = await ctx.http(request);
68
+ const result = outboundResultOf(response);
69
+ if (result.kind !== "accepted") return result;
70
+ const value = read(json(response.body));
71
+ return value === null
72
+ ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" }
73
+ : { kind: "ok", value };
74
+ } catch (error) {
75
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
76
+ }
77
+ }
78
+
79
+ const positive = (value: unknown, fallback: number): number =>
80
+ typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
81
+
82
+ function codeOf(body: unknown): LinkCode | null {
83
+ const userCode = asString(pick(body, "userCode"));
84
+ const verifier = asString(pick(body, "authorizationCodeVerifier"));
85
+ const verificationUrl = asString(pick(body, "verificationUrl"));
86
+ if (!userCode || !verifier || !verificationUrl) return null;
87
+ return {
88
+ userCode,
89
+ verifier,
90
+ verificationUrl,
91
+ verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
92
+ expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS),
93
+ };
94
+ }
95
+
96
+ function grantOf(body: unknown, requireRefresh: boolean): LinkGrant | null {
97
+ const accessToken = asString(pick(body, "accessToken"));
98
+ const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
99
+ if (!accessToken || (requireRefresh && !refreshToken)) return null;
100
+ return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
101
+ }
102
+
103
+ function merchantsOf(body: unknown): LinkedMerchant[] | null {
104
+ if (!Array.isArray(body)) return null;
105
+ return body.flatMap((raw: unknown) => {
106
+ const id = asString(pick(raw, "id"));
107
+ return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
108
+ });
109
+ }
110
+
111
+ const tokenRequest = (fields: Record<string, string>): MarketplaceHttpRequest => ({
112
+ method: "POST",
113
+ url: TOKEN_URL,
114
+ headers: FORM,
115
+ body: new URLSearchParams(fields).toString(),
116
+ });
117
+
118
+ /** Every merchant the token covers, page by page until a short page. */
119
+ async function listMerchants(ctx: LinkCallContext, accessToken: string): Promise<LinkResult<LinkedMerchant[]>> {
120
+ const all: LinkedMerchant[] = [];
121
+ for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
122
+ const answer = await call(
123
+ ctx,
124
+ {
125
+ method: "GET",
126
+ url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
127
+ headers: { Authorization: `Bearer ${accessToken}` },
128
+ },
129
+ merchantsOf,
130
+ );
131
+ if (answer.kind !== "ok") return answer;
132
+ all.push(...answer.value);
133
+ if (answer.value.length < MERCHANT_PAGE_SIZE) break;
134
+ }
135
+ return { kind: "ok", value: all };
136
+ }
137
+
138
+ /** The iFood adapter's linking half. */
139
+ export const IFOOD_LINKING: MarketplaceLinking = {
140
+ requestCode: (ctx) =>
141
+ call(
142
+ ctx,
143
+ { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
144
+ codeOf,
145
+ ),
146
+ exchange: (ctx, input) =>
147
+ call(
148
+ ctx,
149
+ tokenRequest({
150
+ grantType: "authorization_code",
151
+ clientId: ctx.credentials.clientId,
152
+ clientSecret: ctx.credentials.clientSecret,
153
+ authorizationCode: input.authorizationCode,
154
+ authorizationCodeVerifier: input.verifier,
155
+ }),
156
+ (body) => grantOf(body, true),
157
+ ),
158
+ refresh: (ctx, input) =>
159
+ call(
160
+ ctx,
161
+ tokenRequest({
162
+ grantType: "refresh_token",
163
+ clientId: ctx.credentials.clientId,
164
+ clientSecret: ctx.credentials.clientSecret,
165
+ refreshToken: input.refreshToken,
166
+ }),
167
+ (body) => grantOf(body, false),
168
+ ),
169
+ merchants: (ctx, input) => listMerchants(ctx, input.accessToken),
170
+ };
@@ -19,6 +19,7 @@ import {
19
19
  toCents,
20
20
  verifyHmacSha256Hex,
21
21
  } from "../core/payload-read";
22
+ import { readIfoodCourierEvent } from "./courier";
22
23
 
23
24
  /**
24
25
  * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.
@@ -53,6 +54,9 @@ const LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = {
53
54
  DISPATCHED: "DISPATCHED",
54
55
  CON: "CONCLUDED",
55
56
  CONCLUDED: "CONCLUDED",
57
+ // iFood's courier has the bag (FUT-5665): for a fleet bag, the same hand-over as DSP.
58
+ CLT: "COLLECTED",
59
+ COLLECTED: "COLLECTED",
56
60
  };
57
61
 
58
62
  /**
@@ -237,6 +241,8 @@ function readOrder(
237
241
  deliveryFeeCents: firstCents(order, [["total", "deliveryFee"]]),
238
242
  subtotalCents: firstCents(order, [["total", "subTotal"]]),
239
243
  ...optional("discounts", readDiscounts(order)),
244
+ // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.
245
+ pickupCode: firstString(order, [["delivery", "pickupCode"]]),
240
246
  };
241
247
  }
242
248
 
@@ -274,5 +280,6 @@ export function normalizeIfoodEvent(
274
280
  cancelled,
275
281
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
276
282
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
283
+ ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
277
284
  };
278
285
  }
@@ -38,8 +38,13 @@ export const IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
38
38
  /** A token is renewed this long before iFood says it expires. */
39
39
  const TOKEN_MARGIN_MS = 60_000;
40
40
 
41
- /** The token cache key: per environment and merchant app. */
42
- export const ifoodTokenKey = (ctx: AdapterCallContext): string => `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
41
+ /**
42
+ * The token cache key: per environment and merchant app, or, for a store
43
+ * linked through the software's app (FUT-5613), the store's own grant key, so
44
+ * deleting it after a 401 forgets that store's token and nobody else's.
45
+ */
46
+ export const ifoodTokenKey = (ctx: AdapterCallContext): string =>
47
+ ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
43
48
 
44
49
  /** iFood's OAuth answer, read defensively: a missing field is "no token". */
45
50
  function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
@@ -55,10 +60,12 @@ function tokenOf(body: string): { token: string; expiresInSeconds: number } | nu
55
60
 
56
61
  /**
57
62
  * A bearer token for this merchant app, from the per-process cache or a fresh
58
- * client-credentials grant. Keyed by the app's client id, so two stores with
63
+ * client-credentials grant (or, linked, the store's grant). Keyed by the app's client id, so two stores with
59
64
  * two apps never share one. The token lives in memory only.
60
65
  */
61
66
  export async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {
67
+ // A linked store: its refresh token buys the token, never a client-credentials grant.
68
+ if (ctx.grant) return ctx.grant.accessToken();
62
69
  const key = ifoodTokenKey(ctx);
63
70
  const cached = ctx.tokens.get(key);
64
71
  if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
package/src/index.ts CHANGED
@@ -28,6 +28,7 @@ export {
28
28
  outboundResultOf,
29
29
  tokenGrantResultOf,
30
30
  type AdapterCallContext,
31
+ type AdapterGrant,
31
32
  type AdapterTokenCache,
32
33
  type CancellationReason,
33
34
  type CancellationRequestInput,
@@ -82,6 +83,10 @@ export {
82
83
  type NormalizedAddress,
83
84
  type NormalizedBuyer,
84
85
  type MarketplaceLifecycle,
86
+ type MarketplaceCourier,
87
+ type MarketplaceCourierStep,
88
+ type MarketplaceCourierVehicle,
89
+ type NormalizedCourierEvent,
85
90
  type NormalizedEvent,
86
91
  type NormalizedMarketplaceOrder,
87
92
  type NormalizedOrderDiscount,
@@ -120,6 +125,7 @@ export type {
120
125
  MarketplaceIntegrationView,
121
126
  SaveMarketplaceIntegrationInput,
122
127
  } from "./core/integration";
128
+ export { MarketplaceMerchantTakenError } from "./core/merchant-claim";
123
129
  export type { MarketplaceMenuLinkView } from "./core/menu-links";
124
130
  export {
125
131
  OutboundRetryError,
@@ -134,6 +140,18 @@ export {
134
140
  } from "./core/outbound-queue";
135
141
  export type { DeliveryOutcome } from "./core/pipeline";
136
142
  export type { InformStatusInput } from "./core/status-inform";
143
+ export type {
144
+ CourierTrackingCallResult,
145
+ CourierTrackingResult,
146
+ MarketplaceCourierAnswer,
147
+ MarketplaceCourierApi,
148
+ MarketplaceCourierEngine,
149
+ MarketplaceCourierFacts,
150
+ MarketplaceCourierTracking,
151
+ PickupCodeCallResult,
152
+ PickupCodeValidation,
153
+ ValidatePickupCodeInput,
154
+ } from "./core/courier-port";
137
155
  export {
138
156
  FetchOrderRetryError,
139
157
  MARKETPLACE_FETCH_ORDER_JOB,
@@ -218,3 +236,15 @@ export {
218
236
  type StorePauseWanted,
219
237
  } from "./core/pause-store";
220
238
  export type { AvailabilitySweepResult } from "./core/pause-sweep";
239
+ export type {
240
+ LinkCallContext,
241
+ LinkCode,
242
+ LinkGrant,
243
+ LinkResult,
244
+ LinkedMerchant,
245
+ MarketplaceAppCredentialsPort,
246
+ MarketplaceLinkAttemptDelegate,
247
+ MarketplaceLinking,
248
+ } from "./core/linking-port";
249
+ export type { LinkFailure, LinkFinished, LinkPendingView, LinkRefusalCode } from "./core/linking";
250
+ export type { MarketplaceAuthMode } from "./core/link-store";
@@ -1,6 +1,6 @@
1
1
  import { outboundResultOf, type AdapterCallContext } from "../core/adapter";
2
- import { pick } from "../core/payload-read";
3
- import type { NormalizedEvent, NormalizedMarketplaceOrder } from "../core/types";
2
+ import { firstDate, pick } from "../core/payload-read";
3
+ import type { MarketplaceCourierStep, NormalizedEvent, NormalizedMarketplaceOrder } from "../core/types";
4
4
  import { isStop, openDeliveryCall, type OpenDeliveryDialect } from "../open-delivery/client";
5
5
  import { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from "../open-delivery/normalize";
6
6
 
@@ -12,15 +12,26 @@ import { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from "../o
12
12
  *
13
13
  * Events (Keeta's order guide, read 2026-11-26): `CREATED` → fetch;
14
14
  * `CANCELLED` (with a JSON-string `metadata` carrying `reason` and `code`) →
15
- * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle. Keeta has NO
15
+ * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle; `RIDER_ARRIVED_AT_STORE`,
16
+ * `ORDER_COLLECTED` → courier steps (the second a lifecycle too). Keeta has NO
16
17
  * `CANCELLATION_REQUEST_DENIED`: a store's request that Keeta does not grant
17
18
  * produces no event, so it ends TIMEOUT at the adapter's answer window. The
18
- * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`,
19
- * `RIDER_ARRIVED_AT_STORE`, `ORDER_COLLECTED`, `DELIVERED`,
19
+ * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`, `DELIVERED`,
20
20
  * `CANCELLATION_REQUESTED`, `USER_REFUND_REQUEST`, `REFUNDED`,
21
21
  * `REFUND_FAILED`, `RECOMMENDED_PREPARATION_START`) are recorded and IGNORED.
22
22
  */
23
23
 
24
+ /**
25
+ * Keeta's rider events as courier steps (FUT-5665). ESTIMATED: the event names
26
+ * are Keeta's order guide's (read 2026-11-26), their meaning is read off the
27
+ * names; they carry no rider's name, photo or vehicle. `PICKUP_ONGOING` is left
28
+ * IGNORED: whether it means "on the way" or "at the counter" is not stated.
29
+ */
30
+ const KEETA_COURIER_STEP_OF: Readonly<Record<string, MarketplaceCourierStep>> = {
31
+ RIDER_ARRIVED_AT_STORE: "ARRIVED_AT_ORIGIN",
32
+ ORDER_COLLECTED: "COLLECTED",
33
+ };
34
+
24
35
  /** The provider id Keeta is registered under. Uppercase: the column's CHECK holds that shape. */
25
36
  export const KEETA_PROVIDER = "KEETA";
26
37
 
@@ -31,7 +42,11 @@ const DECRYPT_BATCH = 50;
31
42
 
32
43
  /** Normalize one webhook `Event`. Null only when it names no order. */
33
44
  export function normalizeKeetaEvent(payload: unknown): NormalizedEvent | null {
34
- return normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);
45
+ const event = normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);
46
+ const step = event ? KEETA_COURIER_STEP_OF[event.eventType] : undefined;
47
+ if (!event || !step) return event;
48
+ const courier = { step, at: firstDate(payload, [["createdAt"]]), courier: null, returning: null };
49
+ return { ...event, courier, ...(step === "COLLECTED" ? { lifecycle: "COLLECTED" as const } : {}) };
35
50
  }
36
51
 
37
52
  /** Normalize one `Order`, after {@link revealKeetaOrder}. Null when it carries no id or no line. */
@@ -1,8 +1,13 @@
1
1
  import type { BulkProblemCode } from "../core/bulk";
2
2
  import type { DecisionProblemCode } from "../core/cancellation";
3
+ import type { LinkRefusalCode } from "../core/linking";
3
4
 
4
- /** Every problem code a route can answer, decisions and bulk writes alike. */
5
- export type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
5
+ /**
6
+ * Every problem code a route words from `problems`, decisions and bulk writes
7
+ * alike. MERCHANT_TAKEN is worded by `link.problems` instead (FUT-5613), so a
8
+ * host's own pack written against 1.x still compiles.
9
+ */
10
+ export type MarketplaceProblemCode = DecisionProblemCode | Exclude<BulkProblemCode, "MERCHANT_TAKEN">;
6
11
 
7
12
  /**
8
13
  * Every sentence the marketplace routes answer with. Required, no defaults
@@ -22,4 +27,17 @@ export interface MarketplaceServerCopy {
22
27
  orderNoLongerPending: string;
23
28
  /** One sentence per problem code, for each `problems[].message`. */
24
29
  problems: Readonly<Record<MarketplaceProblemCode, string>>;
30
+ /**
31
+ * OPTIONAL in the type, so a host's own pack written against 1.x still
32
+ * compiles: the sentences of the linking routes (FUT-5613). Absent, those
33
+ * routes answer the machine code as `error`. Both shipped packs carry it.
34
+ */
35
+ link?: MarketplaceLinkCopy;
36
+ }
37
+
38
+ /** What the linking routes say: one sentence per refusal, and one for "try again". */
39
+ export interface MarketplaceLinkCopy {
40
+ problems: Readonly<Record<LinkRefusalCode, string>>;
41
+ /** The marketplace did not answer (a timeout, a 5xx, a rate limit). */
42
+ tryAgain: string;
25
43
  }
@@ -19,4 +19,17 @@ export const MARKETPLACE_SERVER_COPY_EN_US = {
19
19
  NOTHING_TO_UPDATE: "Nothing to update.",
20
20
  CATALOG_ITEM_NOT_FOUND: "Product not found.",
21
21
  },
22
+ link: {
23
+ problems: {
24
+ UNAVAILABLE: "Connecting through the app is not available for this marketplace.",
25
+ NO_LINK_IN_PROGRESS: "No connection is in progress. Start again from the first step.",
26
+ LINK_EXPIRED: "The code has expired. Get a new code and repeat the steps.",
27
+ CODE_REFUSED: "The marketplace refused the authorization code. Check the code and paste it again.",
28
+ MARKETPLACE_REFUSED: "The marketplace refused the connection request.",
29
+ NOT_LINKED: "This store is not connected through the app. Connect it again.",
30
+ UNKNOWN_MERCHANT: "This store is not among the ones authorized on the marketplace.",
31
+ MERCHANT_TAKEN: "This marketplace store is already connected to another account.",
32
+ },
33
+ tryAgain: "The marketplace did not answer. Try again in a moment.",
34
+ },
22
35
  } as const satisfies MarketplaceServerCopy;
@@ -29,7 +29,7 @@ export function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketpla
29
29
 
30
30
  export type { MarketplaceActor, MarketplaceApiConfig } from "./http";
31
31
  export type { MarketplaceRoute } from "./routes";
32
- export type { MarketplaceServerCopy } from "./copy";
32
+ export type { MarketplaceLinkCopy, MarketplaceServerCopy } from "./copy";
33
33
  export {
34
34
  MARKETPLACE_DECIDE,
35
35
  MARKETPLACE_MANAGE,
@@ -0,0 +1,140 @@
1
+ import type { WireResponse, WireRoute } from "@12-apps/wiring";
2
+
3
+ import type { MarketplaceIntegrationView } from "../core/integration";
4
+ import type { LinkFailure, LinkPendingView, LinkRefusalCode } from "../core/linking";
5
+ import { MARKETPLACE_MANAGE } from "./contribution";
6
+ import { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from "./http";
7
+ import { finishLinkBody, linkMerchantsQuery, linkStateQuery, selectLinkMerchantBody, startLinkBody } from "./mcp-link";
8
+
9
+ /**
10
+ * Linking a store through the software's own marketplace app (FUT-5613), as
11
+ * HTTP, beside the connection routes and behind the same permission:
12
+ *
13
+ * - `GET …/marketplace/link?provider=` — whether linking is available, and the code in progress;
14
+ * - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);
15
+ * - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;
16
+ * - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;
17
+ * - `PUT …/marketplace/link/merchant` — which of them this store is.
18
+ *
19
+ * No answer ever carries a token, a verifier or the app's credentials.
20
+ */
21
+
22
+ const BASE = "/admin/:tenantSlug/marketplace/link";
23
+
24
+ /** The HTTP status each refusal answers. */
25
+ const STATUS: Readonly<Record<LinkRefusalCode, number>> = {
26
+ UNAVAILABLE: 409,
27
+ NO_LINK_IN_PROGRESS: 409,
28
+ LINK_EXPIRED: 409,
29
+ CODE_REFUSED: 422,
30
+ MARKETPLACE_REFUSED: 502,
31
+ NOT_LINKED: 409,
32
+ UNKNOWN_MERCHANT: 422,
33
+ MERCHANT_TAKEN: 409,
34
+ };
35
+
36
+ /** A failure as the routes answer it: the host's sentence, the code, and the marketplace's own words. */
37
+ function failed(config: MarketplaceApiConfig, failure: LinkFailure): WireResponse {
38
+ const words = config.copy.link;
39
+ if (failure.kind === "retry") {
40
+ return refuse(503, words?.tryAgain ?? "MARKETPLACE_UNREACHABLE", { code: "MARKETPLACE_UNREACHABLE" });
41
+ }
42
+ return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {
43
+ code: failure.code,
44
+ ...(failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }),
45
+ });
46
+ }
47
+
48
+ const pendingOut = (pending: LinkPendingView | null) => (pending ? { ...pending, expiresAt: pending.expiresAt.toISOString() } : null);
49
+
50
+ function connectionOut(row: MarketplaceIntegrationView) {
51
+ return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };
52
+ }
53
+
54
+ /** An unknown provider, before anything is asked of the engine. */
55
+ function unknown(config: MarketplaceApiConfig, id: string): WireResponse | null {
56
+ return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: "UNKNOWN_PROVIDER" });
57
+ }
58
+
59
+ function readRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
60
+ const { engine, copy } = config;
61
+ return [
62
+ {
63
+ method: "GET",
64
+ path: BASE,
65
+ permission: MARKETPLACE_MANAGE,
66
+ handle: async ({ actor, query }) => {
67
+ const parsed = parse(linkStateQuery, query, copy);
68
+ if (!parsed.ok) return parsed.response;
69
+ const refusal = unknown(config, parsed.value.provider);
70
+ if (refusal) return refusal;
71
+ const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });
72
+ return ok({ available: state.available, pending: pendingOut(state.pending) });
73
+ },
74
+ },
75
+ {
76
+ method: "GET",
77
+ path: `${BASE}/merchants`,
78
+ permission: MARKETPLACE_MANAGE,
79
+ handle: async ({ actor, query }) => {
80
+ const parsed = parse(linkMerchantsQuery, query, copy);
81
+ if (!parsed.ok) return parsed.response;
82
+ const refusal = unknown(config, parsed.value.provider);
83
+ if (refusal) return refusal;
84
+ const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });
85
+ return result.kind === "listed" ? ok(result.merchants) : failed(config, result);
86
+ },
87
+ },
88
+ ];
89
+ }
90
+
91
+ function writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
92
+ const { engine, copy } = config;
93
+ return [
94
+ {
95
+ method: "POST",
96
+ path: `${BASE}/start`,
97
+ permission: MARKETPLACE_MANAGE,
98
+ handle: async ({ actor, body }) => {
99
+ const parsed = parse(startLinkBody, body, copy);
100
+ if (!parsed.ok) return parsed.response;
101
+ const refusal = unknown(config, parsed.value.provider);
102
+ if (refusal) return refusal;
103
+ const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });
104
+ return result.kind === "started" ? ok(pendingOut(result.pending)) : failed(config, result);
105
+ },
106
+ },
107
+ {
108
+ method: "POST",
109
+ path: `${BASE}/finish`,
110
+ permission: MARKETPLACE_MANAGE,
111
+ handle: async ({ actor, body }) => {
112
+ const parsed = parse(finishLinkBody, body, copy);
113
+ if (!parsed.ok) return parsed.response;
114
+ const refusal = unknown(config, parsed.value.provider);
115
+ if (refusal) return refusal;
116
+ const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });
117
+ if (result.kind !== "linked") return failed(config, result);
118
+ return ok({ integration: connectionOut(result.integration), merchants: result.merchants });
119
+ },
120
+ },
121
+ {
122
+ method: "PUT",
123
+ path: `${BASE}/merchant`,
124
+ permission: MARKETPLACE_MANAGE,
125
+ handle: async ({ actor, body }) => {
126
+ const parsed = parse(selectLinkMerchantBody, body, copy);
127
+ if (!parsed.ok) return parsed.response;
128
+ const refusal = unknown(config, parsed.value.provider);
129
+ if (refusal) return refusal;
130
+ const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, ...parsed.value });
131
+ return result.kind === "selected" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);
132
+ },
133
+ },
134
+ ];
135
+ }
136
+
137
+ /** The linking routes, in mount order. */
138
+ export function linkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
139
+ return [...readRoutes(config), ...writeRoutes(config)];
140
+ }
@@ -0,0 +1,103 @@
1
+ import { z } from "zod";
2
+
3
+ import type { WireMcpTool } from "@12-apps/wiring";
4
+
5
+ /**
6
+ * The linking tools (FUT-5613), one per linking route, authored once and
7
+ * reused as the routes' validators. Every input is STRICT. No answer carries a
8
+ * token, a verifier or the app's credentials.
9
+ */
10
+
11
+ const provider = z.string().regex(/^[A-Z][A-Z0-9_]*$/u);
12
+ const environment = z.enum(["SANDBOX", "PRODUCTION"]);
13
+
14
+ /** Whether linking is available, and the code in progress. */
15
+ export const linkStateQuery = z.strictObject({ provider, environment: environment.optional() });
16
+ /** Start a linking: a new portal code. */
17
+ export const startLinkBody = z.strictObject({ provider, environment: environment.optional() });
18
+ /** Finish it with the authorization code the person pasted. */
19
+ export const finishLinkBody = z.strictObject({
20
+ provider,
21
+ authorizationCode: z.string().trim().min(1).max(512),
22
+ enabled: z.boolean().optional(),
23
+ });
24
+ /** The marketplace stores a linked connection's grant covers. */
25
+ export const linkMerchantsQuery = z.strictObject({ provider });
26
+ /** Which of them this store is. */
27
+ export const selectLinkMerchantBody = z.strictObject({ provider, merchantId: z.string().trim().min(1).max(200) });
28
+
29
+ const pendingSchema = z.object({
30
+ userCode: z.string(),
31
+ verificationUrl: z.string(),
32
+ verificationUrlComplete: z.string(),
33
+ expiresAt: z.string(),
34
+ });
35
+
36
+ const merchantSchema = z.object({ id: z.string(), name: z.string().nullable(), corporateName: z.string().nullable() });
37
+
38
+ const BASE = "/admin/{tenantSlug}/marketplace/link";
39
+
40
+ /** The five linking tools, over the connection schema the connection tools answer. */
41
+ export function marketplaceLinkTools<P extends z.ZodType, I extends z.ZodType>(params: P, integration: I) {
42
+ return [
43
+ {
44
+ operationId: "getMarketplaceLink",
45
+ method: "GET",
46
+ path: BASE,
47
+ summary:
48
+ "Read in one call whether a store can connect a marketplace through the software's own app (no credentials typed), and the portal code still in progress, if any: `userCode`, the portal link that already carries it, and when it expires.",
49
+ tags: ["marketplace"],
50
+ params,
51
+ query: linkStateQuery,
52
+ response: z.object({ data: z.object({ available: z.boolean(), pending: pendingSchema.nullable() }) }),
53
+ annotations: { readOnly: true },
54
+ },
55
+ {
56
+ operationId: "listMarketplaceLinkMerchants",
57
+ method: "GET",
58
+ path: `${BASE}/merchants`,
59
+ summary: "List the marketplace stores a linked connection's authorization covers, to choose which one this store is.",
60
+ tags: ["marketplace"],
61
+ params,
62
+ query: linkMerchantsQuery,
63
+ response: z.object({ data: z.array(merchantSchema) }),
64
+ annotations: { readOnly: true, openWorld: true },
65
+ },
66
+ {
67
+ operationId: "startMarketplaceLink",
68
+ method: "POST",
69
+ path: `${BASE}/start`,
70
+ summary:
71
+ "Start connecting a marketplace through the software's own app in one call: answers the code the person types on the marketplace's portal and the portal link that already carries it (valid ten minutes on iFood). Replaces a code in progress. 409 UNAVAILABLE when the software has no app on that marketplace.",
72
+ tags: ["marketplace"],
73
+ params,
74
+ body: startLinkBody,
75
+ response: z.object({ data: pendingSchema }),
76
+ annotations: { readOnly: false, destructive: false, openWorld: true },
77
+ },
78
+ {
79
+ operationId: "finishMarketplaceLink",
80
+ method: "POST",
81
+ path: `${BASE}/finish`,
82
+ summary:
83
+ "Finish connecting, in one call, with the authorization code the marketplace's portal showed the person. Stores the connection as LINKED and selects the marketplace store when the authorization covers only one; `merchants` lists them (null when they could not be listed). 422 CODE_REFUSED for a wrong code (the code in progress stays, paste again); 409 LINK_EXPIRED past its ten minutes.",
84
+ tags: ["marketplace"],
85
+ params,
86
+ body: finishLinkBody,
87
+ response: z.object({ data: z.object({ integration, merchants: z.array(merchantSchema).nullable() }) }),
88
+ annotations: { readOnly: false, destructive: false, openWorld: true },
89
+ },
90
+ {
91
+ operationId: "selectMarketplaceLinkMerchant",
92
+ method: "PUT",
93
+ path: `${BASE}/merchant`,
94
+ summary:
95
+ "Choose in one call which marketplace store a linked connection is, among those its authorization covers. 422 UNKNOWN_MERCHANT for one it does not cover; 409 MERCHANT_TAKEN when another store's connection holds it.",
96
+ tags: ["marketplace"],
97
+ params,
98
+ body: selectLinkMerchantBody,
99
+ response: z.object({ data: z.object({ integration }) }),
100
+ annotations: { readOnly: false, destructive: false, openWorld: true },
101
+ },
102
+ ] as const satisfies readonly WireMcpTool<z.ZodType>[];
103
+ }