@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
@@ -2,7 +2,7 @@ import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
2
  import type { IngestSettings } from "./ingest";
3
3
  import type { DeliveryOutcome } from "./pipeline";
4
4
  import type { EngineContext } from "./ports";
5
- import { readStatusRows, noteMarketplaceStep, statusTable } from "./status-store";
5
+ import { readStatusRows, noteMarketplaceStep, statusTable, type StatusRowStep } from "./status-store";
6
6
  import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } from "./types";
7
7
 
8
8
  /**
@@ -20,7 +20,7 @@ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } fr
20
20
  * 3. a cancellation request standing (PENDING or REQUESTED) is the store's
21
21
  * last word and nothing here contradicts it;
22
22
  * 4. an event that answers a step WE informed (a STORE row for DISPATCHED, or
23
- * for HANDED_OVER when the event is CONCLUDED) is an echo: the failure case
23
+ * for HANDED_OVER when the event is COLLECTED or CONCLUDED) is an echo: the failure case
24
24
  * of forward-only alone is the store's undo, where the echo would
25
25
  * dispatch a card again with no courier.
26
26
  *
@@ -36,9 +36,23 @@ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } fr
36
36
  /** The step of the table an event's echo is looked for under. */
37
37
  const ECHO_OF: Record<MarketplaceLifecycle, "DISPATCHED" | "HANDED_OVER"> = {
38
38
  DISPATCHED: "DISPATCHED",
39
+ // The courier holding the bag answers the store's hand-over (FUT-5665).
40
+ COLLECTED: "HANDED_OVER",
39
41
  CONCLUDED: "HANDED_OVER",
40
42
  };
41
43
 
44
+ /**
45
+ * The step the marketplace's word is NOTED under. `COLLECTED` is the
46
+ * hand-over seen from the marketplace's side, so it is noted as HANDED_OVER:
47
+ * the table's vocabulary (its CHECK) is unchanged, and our own job never
48
+ * informs a hand-over the marketplace already announced.
49
+ */
50
+ const NOTED_AS: Record<MarketplaceLifecycle, StatusRowStep> = {
51
+ DISPATCHED: "DISPATCHED",
52
+ COLLECTED: "HANDED_OVER",
53
+ CONCLUDED: "CONCLUDED",
54
+ };
55
+
42
56
  interface HeldAcceptance {
43
57
  orderId: string;
44
58
  status: string;
@@ -62,6 +76,15 @@ function refusal(held: HeldAcceptance): string | null {
62
76
  return null;
63
77
  }
64
78
 
79
+ /**
80
+ * A COLLECTED is the marketplace's courier taking the bag (FUT-5665): for a
81
+ * bag the store carries it moves nothing and is never noted, so it cannot
82
+ * stand in for the store's own HANDED_OVER (a merchant bag's "delivered").
83
+ */
84
+ function notTheFleets(lifecycle: MarketplaceLifecycle, held: HeldAcceptance): string | null {
85
+ return lifecycle === "COLLECTED" && held.deliveredBy !== "MARKETPLACE" ? "COLLECTED of a bag the marketplace does not carry" : null;
86
+ }
87
+
65
88
  function deliveredByOf(held: HeldAcceptance): MarketplaceDeliveredBy | null {
66
89
  return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
67
90
  }
@@ -108,7 +131,7 @@ export async function followLifecycle(
108
131
  await deferInboxEvent(ctx, inboxId, reason);
109
132
  return { kind: "ignored", reason };
110
133
  }
111
- const stopped = refusal(held);
134
+ const stopped = refusal(held) ?? notTheFleets(lifecycle, held);
112
135
  if (stopped) return ignored(ctx, inboxId, stopped);
113
136
 
114
137
  const echo = ECHO_OF[lifecycle];
@@ -121,7 +144,7 @@ export async function followLifecycle(
121
144
  // FAILED and logged): the marketplace's state and ours already agree, and a stricter ordering
122
145
  // would put a write before the host's answer on every event.
123
146
  const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
124
- await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
147
+ await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: NOTED_AS[lifecycle] });
125
148
  if (answer === "moved") {
126
149
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
127
150
  ctx.ports.publishChanged(clientId);
@@ -0,0 +1,170 @@
1
+ import type { AdapterGrant, AdapterTokenCache, MarketplaceCredentials, OutboundResult } from "./adapter";
2
+ import type { LinkGrant } from "./linking-port";
3
+ import type { EngineContext } from "./ports";
4
+ import type { MarketplaceProvider } from "./types";
5
+
6
+ /**
7
+ * A LINKED connection's secrets and tokens (FUT-5613).
8
+ *
9
+ * The sealed `credentials` blob of a linked connection holds the store's
10
+ * refresh token and nothing of the app: the app's client id and secret are
11
+ * the host's configuration (`appCredentials`), read at each use so a rotation
12
+ * there reaches every store at once. The access token lives in the engine's
13
+ * per-process token cache only, like every other marketplace token.
14
+ */
15
+
16
+ /** How a connection authenticates. */
17
+ export type MarketplaceAuthMode = "CREDENTIALS" | "LINKED";
18
+
19
+ /** A token is renewed this long before the marketplace says it expires. */
20
+ const TOKEN_MARGIN_MS = 60_000;
21
+
22
+ /** The blob a linked connection stores, sealed. The empty app fields keep 1.x readers' shape. */
23
+ export function sealLink(ctx: EngineContext, refreshToken: string): string {
24
+ return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
25
+ }
26
+
27
+ /** The refresh token a linked connection's blob holds. Throws when it holds none, or will not open. */
28
+ export function openLinkRefreshToken(ctx: EngineContext, sealed: string): string {
29
+ const parsed: unknown = JSON.parse(ctx.ports.secrets.open(sealed));
30
+ const token = typeof parsed === "object" && parsed !== null ? (parsed as { refreshToken?: unknown }).refreshToken : null;
31
+ if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
32
+ return token;
33
+ }
34
+
35
+ /** The software's own app on this marketplace, or null when the host configured none. */
36
+ export async function appCredentialsOf(
37
+ ctx: EngineContext,
38
+ provider: MarketplaceProvider,
39
+ environment: "SANDBOX" | "PRODUCTION",
40
+ ): Promise<MarketplaceCredentials | null> {
41
+ const port = ctx.ports.appCredentials;
42
+ if (!port) return null;
43
+ const credentials = await port(provider, environment);
44
+ return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
45
+ }
46
+
47
+ /** Where a linked connection's access token sits in the cache: per store, never per app. */
48
+ export const linkTokenKey = (provider: string, environment: string, clientId: string): string =>
49
+ `LINK:${provider}:${environment}:${clientId}`;
50
+
51
+ /** The row a token belongs to, and the sealed blob it was read with: the compare-and-set's version. */
52
+ interface LinkVersion {
53
+ clientId: string;
54
+ provider: string;
55
+ sealed: string;
56
+ }
57
+
58
+ /**
59
+ * Put a fresh access token in the cache, only while the connection still
60
+ * holds the blob it was bought with: a grant a re-link replaced caches nothing.
61
+ */
62
+ export async function cacheLinkToken(ctx: EngineContext, link: LinkVersion, key: string, grant: LinkGrant): Promise<boolean> {
63
+ const db = await ctx.ports.db();
64
+ const row = (await db.marketplaceIntegration.findUnique({
65
+ where: { clientId_provider: { clientId: link.clientId, provider: link.provider } },
66
+ select: { credentials: true },
67
+ })) as { credentials: string } | null;
68
+ if (row?.credentials !== link.sealed) return false;
69
+ setToken(ctx, key, grant);
70
+ return true;
71
+ }
72
+
73
+ function setToken(ctx: EngineContext, key: string, grant: LinkGrant): void {
74
+ const expiresAt = ctx.ports.clock.now().getTime() + Math.max(grant.expiresInSeconds, 1) * 1000;
75
+ ctx.tokens.set(key, { token: grant.accessToken, expiresAt });
76
+ }
77
+
78
+ /** One refresh per connection at a time, per token cache (that is, per engine). */
79
+ const inflight = new WeakMap<AdapterTokenCache, Map<string, Promise<{ token: string } | OutboundResult>>>();
80
+
81
+ /** Who a grant is for. */
82
+ interface LinkedConnection extends LinkVersion {
83
+ clientId: string;
84
+ provider: MarketplaceProvider;
85
+ environment: "SANDBOX" | "PRODUCTION";
86
+ refreshToken: string;
87
+ app: MarketplaceCredentials;
88
+ }
89
+
90
+ /** Store a rotated refresh token back on the live connection, unless a re-link replaced the blob it was read with. */
91
+ async function storeRotated(ctx: EngineContext, link: LinkedConnection, refreshToken: string): Promise<boolean> {
92
+ const db = await ctx.ports.db();
93
+ const { count } = await db.marketplaceIntegration.updateMany({
94
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", archivedAt: null, credentials: link.sealed },
95
+ data: { credentials: sealLink(ctx, refreshToken) },
96
+ });
97
+ return count > 0;
98
+ }
99
+
100
+ /**
101
+ * The marketplace no longer honours the refresh token: the store must link
102
+ * again. The connection reads FAILED, which is what the screen shows; a
103
+ * connection linked again since the token was read is left alone.
104
+ */
105
+ async function markLinkFailed(ctx: EngineContext, link: LinkedConnection): Promise<boolean> {
106
+ const db = await ctx.ports.db();
107
+ const { count } = await db.marketplaceIntegration.updateMany({
108
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", credentials: link.sealed },
109
+ data: { status: "FAILED" },
110
+ });
111
+ if (count > 0) ctx.ports.publishChanged(link.clientId);
112
+ return count > 0;
113
+ }
114
+
115
+ /** What a refresh that lost the race to a re-link answers: the caller reads the new link and tries again. */
116
+ const RELINKED: OutboundResult = { kind: "retry", reason: "the connection was linked again during the refresh" };
117
+
118
+ async function refreshOnce(ctx: EngineContext, link: LinkedConnection, key: string): Promise<{ token: string } | OutboundResult> {
119
+ const linking = ctx.registry.get(link.provider)?.linking;
120
+ if (!linking) return { kind: "refused", status: 0, message: "this marketplace links no store", own: true };
121
+ const answer = await linking.refresh(
122
+ { http: ctx.ports.http, credentials: link.app, environment: link.environment, now: ctx.ports.clock.now() },
123
+ { refreshToken: link.refreshToken },
124
+ );
125
+ if (answer.kind === "retry") return answer;
126
+ if (answer.kind === "refused") return (await markLinkFailed(ctx, link)) ? { ...answer, own: true } : RELINKED;
127
+ const rotated = answer.value.refreshToken;
128
+ if (rotated === null || rotated === link.refreshToken) {
129
+ return (await cacheLinkToken(ctx, link, key, answer.value)) ? { token: answer.value.accessToken } : RELINKED;
130
+ }
131
+ // The new token is already in hand; a failed write costs a re-link only if
132
+ // the marketplace also revoked the old one, so it is logged, never thrown.
133
+ const stored = await storeRotated(ctx, link, rotated).catch((error: unknown) => {
134
+ ctx.ports.logger.error(
135
+ `marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` +
136
+ (error instanceof Error ? error.message : String(error)),
137
+ );
138
+ return null;
139
+ });
140
+ if (stored === false) return RELINKED;
141
+ setToken(ctx, key, answer.value);
142
+ return { token: answer.value.accessToken };
143
+ }
144
+
145
+ /** The grant an outbound call of a linked connection is handed. */
146
+ export function linkGrant(ctx: EngineContext, link: LinkedConnection): AdapterGrant {
147
+ const key = linkTokenKey(link.provider, link.environment, link.clientId);
148
+ return {
149
+ key,
150
+ accessToken: async () => {
151
+ const cached = ctx.tokens.get(key);
152
+ if (cached && cached.expiresAt > ctx.ports.clock.now().getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
153
+ let running = inflight.get(ctx.tokens);
154
+ if (!running) {
155
+ running = new Map();
156
+ inflight.set(ctx.tokens, running);
157
+ }
158
+ const pending = running.get(key);
159
+ if (pending) return pending;
160
+ const call = refreshOnce(ctx, link, key)
161
+ .catch((error: unknown): OutboundResult => ({
162
+ kind: "retry",
163
+ reason: error instanceof Error ? error.message : String(error),
164
+ }))
165
+ .finally(() => running.delete(key));
166
+ running.set(key, call);
167
+ return call;
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,100 @@
1
+ import type { MarketplaceCredentials, MarketplaceHttp, OutboundResult } from "./adapter";
2
+
3
+ /**
4
+ * LINKING a store through the software's OWN marketplace app (FUT-5613): the
5
+ * store authorizes the software's app on the marketplace's portal, and never
6
+ * types a client id, a secret, a webhook key or a webhook address.
7
+ *
8
+ * The flow, as an adapter states it (iFood's "distributed app"):
9
+ *
10
+ * 1. `requestCode`: the app asks for a short code the store types (or a link
11
+ * that already carries it) on the marketplace's portal, plus a VERIFIER the
12
+ * engine keeps server-side for that store and never hands the browser.
13
+ * 2. The store authorizes the app on the portal and is shown an
14
+ * AUTHORIZATION CODE, which it pastes back.
15
+ * 3. `exchange`: the code plus the verifier buy an access token and a refresh
16
+ * token, stored sealed on the store's connection.
17
+ * 4. `merchants`: which of the marketplace's stores the grant covers; one is
18
+ * selected at once.
19
+ * 5. `refresh`: a new access token from the refresh token, whenever the
20
+ * cached one is gone. A rotated refresh token is stored back.
21
+ *
22
+ * The app's own credentials are the HOST's configuration, one pair per
23
+ * marketplace and environment ({@link MarketplaceAppCredentialsPort}), never a
24
+ * store's.
25
+ */
26
+
27
+ /** What a linking call is handed: the APP's credentials, never a store's. */
28
+ export interface LinkCallContext {
29
+ http: MarketplaceHttp;
30
+ credentials: MarketplaceCredentials;
31
+ environment: "SANDBOX" | "PRODUCTION";
32
+ now: Date;
33
+ }
34
+
35
+ /** The code a store types on the marketplace's portal, and the verifier kept for it. */
36
+ export interface LinkCode {
37
+ /** Shown to the person: they type it on the portal. */
38
+ userCode: string;
39
+ /** The portal page the code is typed on. */
40
+ verificationUrl: string;
41
+ /** The same page with the code already in it: the link the screen opens. */
42
+ verificationUrlComplete: string;
43
+ /** How long the code lives, in seconds. */
44
+ expiresInSeconds: number;
45
+ /** Kept server-side for this store until the exchange. NEVER sent to a browser. */
46
+ verifier: string;
47
+ }
48
+
49
+ /** What an exchange or a refresh buys. */
50
+ export interface LinkGrant {
51
+ accessToken: string;
52
+ /** How long the access token lives, in seconds. */
53
+ expiresInSeconds: number;
54
+ /**
55
+ * The refresh token. An exchange always answers one; a refresh answers one
56
+ * when the marketplace rotates it, and null when the old one stays valid.
57
+ */
58
+ refreshToken: string | null;
59
+ }
60
+
61
+ /** One marketplace store the grant covers. */
62
+ export interface LinkedMerchant {
63
+ id: string;
64
+ name: string | null;
65
+ corporateName: string | null;
66
+ }
67
+
68
+ /**
69
+ * A linking call's answer: the value, or why there is none. `refused` is
70
+ * final (the marketplace judged the request: a wrong or used code, a refresh
71
+ * token it no longer honours); `retry` is the network, a 5xx, a rate limit.
72
+ */
73
+ export type LinkResult<T> = { kind: "ok"; value: T } | Exclude<OutboundResult, { kind: "accepted" }>;
74
+
75
+ /** The adapter's half: the marketplace's wire format for each step, and nothing else. */
76
+ export interface MarketplaceLinking {
77
+ requestCode(ctx: LinkCallContext): Promise<LinkResult<LinkCode>>;
78
+ exchange(ctx: LinkCallContext, input: { authorizationCode: string; verifier: string }): Promise<LinkResult<LinkGrant>>;
79
+ refresh(ctx: LinkCallContext, input: { refreshToken: string }): Promise<LinkResult<LinkGrant>>;
80
+ merchants(ctx: LinkCallContext, input: { accessToken: string }): Promise<LinkResult<LinkedMerchant[]>>;
81
+ }
82
+
83
+ /**
84
+ * The host's configuration of its OWN app on a marketplace: client id, client
85
+ * secret, and the key the marketplace signs the app's webhook deliveries with.
86
+ * Null (or the port not bound) means the software has no app there, and the
87
+ * linking flow reports itself unavailable; a store's own credentials keep
88
+ * working unchanged either way.
89
+ */
90
+ export type MarketplaceAppCredentialsPort = (
91
+ provider: string,
92
+ environment: "SANDBOX" | "PRODUCTION",
93
+ ) => MarketplaceCredentials | null | Promise<MarketplaceCredentials | null>;
94
+
95
+ /** The link-attempt delegate the engine reads and writes (the `MarketplaceLinkAttempt` model). */
96
+ export interface MarketplaceLinkAttemptDelegate {
97
+ findUnique(args: unknown): Promise<unknown>;
98
+ upsert(args: unknown): Promise<unknown>;
99
+ deleteMany(args: unknown): Promise<{ count: number }>;
100
+ }