@12-apps/marketplace 1.11.0 → 1.13.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 (55) hide show
  1. package/ADOPTING.md +134 -1
  2. package/README.md +49 -3
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CD0SfdVS.d.ts → adapter-CQ4QiZPi.d.ts} +327 -174
  6. package/dist/{chunk-TVZU4HNT.js → chunk-4J2KJ3ZW.js} +1 -1
  7. package/dist/{chunk-TVZU4HNT.js.map → chunk-4J2KJ3ZW.js.map} +1 -1
  8. package/dist/{chunk-YWMEIMO3.js → chunk-CEWTV2TC.js} +176 -40
  9. package/dist/chunk-CEWTV2TC.js.map +1 -0
  10. package/dist/{chunk-DCWOQ5PN.js → chunk-NFJQQWG4.js} +2 -2
  11. package/dist/{chunk-OS4TSIFU.js → chunk-W57TITU4.js} +2 -2
  12. package/dist/{client-11sncog4.d.ts → client-CCSnylou.d.ts} +1 -1
  13. package/dist/{engine-C_3RK8wC.d.ts → engine-1KlJ_8jK.d.ts} +34 -5
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +20 -2
  17. package/dist/ifood/index.js +349 -125
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +162 -65
  21. package/dist/index.js.map +1 -1
  22. package/dist/keeta/index.d.ts +2 -18
  23. package/dist/keeta/index.js +12 -3
  24. package/dist/keeta/index.js.map +1 -1
  25. package/dist/manifest/server.d.ts +2 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +2 -2
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/src/core/adapter.ts +8 -1
  33. package/src/core/connection-stamp.ts +61 -0
  34. package/src/core/courier-port.ts +100 -0
  35. package/src/core/courier.ts +153 -0
  36. package/src/core/engine.ts +4 -1
  37. package/src/core/fetch-order.ts +54 -12
  38. package/src/core/integration.ts +19 -4
  39. package/src/core/lifecycle.ts +27 -4
  40. package/src/core/outbound-queue.ts +24 -11
  41. package/src/core/outbound.ts +8 -6
  42. package/src/core/pickup-code.ts +136 -0
  43. package/src/core/pipeline.ts +15 -6
  44. package/src/core/ports.ts +23 -1
  45. package/src/core/status-store.ts +2 -3
  46. package/src/core/types.ts +56 -4
  47. package/src/ifood/courier.ts +210 -0
  48. package/src/ifood/fetch-order.ts +103 -0
  49. package/src/ifood/index.ts +9 -1
  50. package/src/ifood/normalize.ts +30 -3
  51. package/src/index.ts +16 -0
  52. package/src/keeta/normalize.ts +21 -6
  53. package/dist/chunk-YWMEIMO3.js.map +0 -1
  54. /package/dist/{chunk-DCWOQ5PN.js.map → chunk-NFJQQWG4.js.map} +0 -0
  55. /package/dist/{chunk-OS4TSIFU.js.map → chunk-W57TITU4.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { A as AcceptanceDecision, a as AcceptanceStatus, b as AvailabilityJobPayload, c as AvailabilityOutcome, d as AvailabilityRetryError, e as AvailabilitySweepResult, B as BulkProblem, f as BulkProblemCode, g as BulkResult, C as CancellationFailureReason, h as CancellationStatus, i as CatalogueAction, j as CatalogueActionResult, k as CatalogueDocumentResult, l as CatalogueFailedAction, m as CatalogueFailureCode, n as CatalogueJobPayload, o as CatalogueOutcome, p as CataloguePublicationView, q as CataloguePublishInput, r as CatalogueRefusalCode, s as CatalogueRetryError, t as CatalogueStatus, u as CatalogueTarget, D as DecideManyResult, v as DecidedRow, w as DecisionInput, x as DecisionProblem, y as DecisionProblemCode, z as DecisionResult, E as DeliveryOutcome, F as ExpirySweepResult, G as FetchOrderJobPayload, H as FetchOrderOutcome, I as FetchOrderRetryError, J as InformStatusInput, K as IngestResult, L as IngestSettings, M as IngestionTarget, N as IntegrationRowInput, O as LinkFailure, P as LinkFinished, Q as LinkPendingView, R as LinkRefusalCode, S as MARKETPLACE_AVAILABILITY_JOB, T as MARKETPLACE_CATALOGUE_JOB, U as MARKETPLACE_FETCH_ORDER_JOB, V as MARKETPLACE_OUTBOUND_JOB, W as MarketplaceAdmission, X as MarketplaceAdmissionRequest, Y as MarketplaceAdmissionResult, Z as MarketplaceAuditEntry, _ as MarketplaceAuditPort, $ as MarketplaceAuthMode, a0 as MarketplaceCataloguePort, a1 as MarketplaceClockPort, a2 as MarketplaceDb, a3 as MarketplaceEngine, a4 as MarketplaceEngineConfig, a5 as MarketplaceEnqueuePort, a6 as MarketplaceIntegrationView, a7 as MarketplaceLifecycleAnswer, a8 as MarketplaceLifecycleFacts, a9 as MarketplaceLogger, aa as MarketplaceMenuLinkView, ab as MarketplaceOrderPort, ac as MarketplaceOrderState, ad as MarketplaceOrderSummary, ae as MarketplacePorts, af as MarketplaceRefusal, ag as MarketplaceSecretsPort, ah as MenuLinkRowInput, ai as OUTBOUND_GIVE_UP_MS, aj as OUTBOUND_STALE_MS, ak as OutboundAction, al as OutboundAttempt, am as OutboundJobPayload, an as OutboundOutcome, ao as OutboundRetryError, ap as OutboundSweepResult, aq as PauseOutcome, ar as PauseStoreInput, as as PauseStoreResult, at as PendingAcceptance, au as PendingInboxEvent, av as ResolvedOrderLine, aw as ResumeOutcome, ax as STORE_PAUSE_LEASE_MS, ay as SaveMarketplaceIntegrationInput, az as StoreAvailabilityView, aA as StorePauseFailureCode, aB as StorePauseState, aC as StorePauseWanted, aD as availabilityDedupeKey, aE as catalogueDedupeKey, aF as createMarketplaceEngine, aG as outboundDedupeKey } from './engine-C_3RK8wC.js';
2
- import { c as MarketplaceAdapter, j as MarketplaceProvider, k as CancellationReason } from './adapter-CD0SfdVS.js';
3
- export { A as AdapterCallContext, l as AdapterGrant, m as AdapterTokenCache, n as CancellationOutcome, o as CancellationRequestInput, p as CatalogueCallContext, q as CatalogueFailure, r as CatalogueImage, s as CatalogueItem, e as CatalogueItemOut, t as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, u as CataloguePublishResult, v as CatalogueReadContext, w as CatalogueReadNotice, x as CatalogueReadRefusalCode, y as CatalogueReadResult, z as CatalogueReadWarning, B as CatalogueReadWarningCode, f as CatalogueReader, D as CatalogueSnapshot, E as CatalogueSnapshotCategory, F as CatalogueSnapshotItem, G as CatalogueSnapshotOption, H as CatalogueSnapshotOptionGroup, I as CatalogueStoredImage, J as CatalogueWarningCode, K as FetchOrderResult, L as LinkCallContext, Q as LinkCode, R as LinkGrant, T as LinkResult, U as LinkedMerchant, V as MarketplaceAppCredentialsPort, M as MarketplaceAvailability, W as MarketplaceCapabilities, X as MarketplaceCatalogue, Y as MarketplaceCredentials, Z as MarketplaceDeliveredBy, _ as MarketplaceDiscountSponsor, $ as MarketplaceHttp, a0 as MarketplaceHttpRequest, a1 as MarketplaceHttpResponse, a2 as MarketplaceLifecycle, a3 as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, a4 as MarketplaceOrderType, a5 as NormalizedAddress, a6 as NormalizedBuyer, N as NormalizedEvent, a as NormalizedMarketplaceOrder, a7 as NormalizedOrderDiscount, a8 as NormalizedOrderLine, a9 as OutboundOrderRef, O as OutboundResult, aa as PROVIDER_ID_PATTERN, P as PullCatalogue, d as PushCatalogue, ab as StatusFacts, ac as StatusStep, i as StorePauseRef, S as StorePauseRequest, h as StorePauseResult, ad as answered, ae as centsFromMajor, af as outboundResultOf, ag as tokenGrantResultOf } from './adapter-CD0SfdVS.js';
1
+ export { A as AcceptanceDecision, a as AcceptanceStatus, b as AvailabilityJobPayload, c as AvailabilityOutcome, d as AvailabilityRetryError, e as AvailabilitySweepResult, B as BulkProblem, f as BulkProblemCode, g as BulkResult, C as CancellationFailureReason, h as CancellationStatus, i as CatalogueAction, j as CatalogueActionResult, k as CatalogueDocumentResult, l as CatalogueFailedAction, m as CatalogueFailureCode, n as CatalogueJobPayload, o as CatalogueOutcome, p as CataloguePublicationView, q as CataloguePublishInput, r as CatalogueRefusalCode, s as CatalogueRetryError, t as CatalogueStatus, u as CatalogueTarget, D as DecideManyResult, v as DecidedRow, w as DecisionInput, x as DecisionProblem, y as DecisionProblemCode, z as DecisionResult, E as DeliveryOutcome, F as ExpirySweepResult, G as FetchOrderJobPayload, H as FetchOrderOutcome, I as FetchOrderRetryError, J as InformStatusInput, K as IngestResult, L as IngestSettings, M as IngestionTarget, N as IntegrationRowInput, O as LinkFailure, P as LinkFinished, Q as LinkPendingView, R as LinkRefusalCode, S as MARKETPLACE_AVAILABILITY_JOB, T as MARKETPLACE_CATALOGUE_JOB, U as MARKETPLACE_FETCH_ORDER_JOB, V as MARKETPLACE_OUTBOUND_JOB, W as MarketplaceAdmission, X as MarketplaceAdmissionRequest, Y as MarketplaceAdmissionResult, Z as MarketplaceAuditEntry, _ as MarketplaceAuditPort, $ as MarketplaceAuthMode, a0 as MarketplaceCataloguePort, a1 as MarketplaceClockPort, a2 as MarketplaceDb, a3 as MarketplaceEngine, a4 as MarketplaceEngineConfig, a5 as MarketplaceEnqueuePort, a6 as MarketplaceIntegrationView, a7 as MarketplaceLifecycleAnswer, a8 as MarketplaceLifecycleFacts, a9 as MarketplaceLogger, aa as MarketplaceMenuLinkView, ab as MarketplaceOrderPort, ac as MarketplaceOrderState, ad as MarketplaceOrderSummary, ae as MarketplacePorts, af as MarketplaceRefusal, ag as MarketplaceSecretsPort, ah as MenuLinkRowInput, ai as OUTBOUND_GIVE_UP_MS, aj as OUTBOUND_STALE_MS, ak as OutboundAction, al as OutboundAttempt, am as OutboundJobPayload, an as OutboundOutcome, ao as OutboundRetryError, ap as OutboundSweepResult, aq as PauseOutcome, ar as PauseStoreInput, as as PauseStoreResult, at as PendingAcceptance, au as PendingInboxEvent, av as ResolvedOrderLine, aw as ResumeOutcome, ax as STORE_PAUSE_LEASE_MS, ay as SaveMarketplaceIntegrationInput, az as StoreAvailabilityView, aA as StorePauseFailureCode, aB as StorePauseState, aC as StorePauseWanted, aD as availabilityDedupeKey, aE as catalogueDedupeKey, aF as createMarketplaceEngine, aG as outboundDedupeKey } from './engine-1KlJ_8jK.js';
2
+ import { c as MarketplaceAdapter, l as MarketplaceProvider, m as CancellationReason } from './adapter-CQ4QiZPi.js';
3
+ export { A as AdapterCallContext, n as AdapterGrant, o as AdapterTokenCache, p as CancellationOutcome, q as CancellationRequestInput, r as CatalogueCallContext, s as CatalogueFailure, t as CatalogueImage, u as CatalogueItem, e as CatalogueItemOut, v as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, w as CataloguePublishResult, x as CatalogueReadContext, y as CatalogueReadNotice, z as CatalogueReadRefusalCode, B as CatalogueReadResult, D as CatalogueReadWarning, E as CatalogueReadWarningCode, f as CatalogueReader, G as CatalogueSnapshot, H as CatalogueSnapshotCategory, I as CatalogueSnapshotItem, J as CatalogueSnapshotOption, K as CatalogueSnapshotOptionGroup, L as CatalogueStoredImage, Q as CatalogueWarningCode, R as CourierTrackingCallResult, T as CourierTrackingResult, F as FetchOrderResult, U as LinkCallContext, V as LinkCode, W as LinkGrant, X as LinkResult, Y as LinkedMerchant, Z as MarketplaceAppCredentialsPort, M as MarketplaceAvailability, _ as MarketplaceCapabilities, $ as MarketplaceCatalogue, a0 as MarketplaceCourier, a1 as MarketplaceCourierAnswer, h as MarketplaceCourierApi, a2 as MarketplaceCourierEngine, a3 as MarketplaceCourierFacts, a4 as MarketplaceCourierStep, a5 as MarketplaceCourierTracking, a6 as MarketplaceCourierVehicle, a7 as MarketplaceCredentials, a8 as MarketplaceDeliveredBy, a9 as MarketplaceDiscountSponsor, aa as MarketplaceHttp, ab as MarketplaceHttpRequest, ac as MarketplaceHttpResponse, ad as MarketplaceLifecycle, ae as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, af as MarketplaceOrderType, ag as NormalizedAddress, ah as NormalizedBuyer, i as NormalizedCourierEvent, N as NormalizedEvent, a as NormalizedMarketplaceOrder, ai as NormalizedOrderDiscount, aj as NormalizedOrderLine, ak as OutboundOrderRef, O as OutboundResult, al as PROVIDER_ID_PATTERN, am as PickupCodeCallResult, an as PickupCodeValidation, P as PullCatalogue, d as PushCatalogue, ao as StatusFacts, ap as StatusStep, k as StorePauseRef, S as StorePauseRequest, j as StorePauseResult, aq as ValidatePickupCodeInput, ar as answered, as as centsFromMajor, at as outboundResultOf, au as tokenGrantResultOf } from './adapter-CQ4QiZPi.js';
4
4
 
5
5
  /**
6
6
  * The adapter registry: the ONE place a provider id becomes a marketplace.
package/dist/index.js CHANGED
@@ -79,8 +79,9 @@ import {
79
79
  sweepOutbound,
80
80
  tellCancellationFailed,
81
81
  upsertLink,
82
+ validatePickupCode,
82
83
  viewOf
83
- } from "./chunk-YWMEIMO3.js";
84
+ } from "./chunk-CEWTV2TC.js";
84
85
  import {
85
86
  centsFromMajor
86
87
  } from "./chunk-WN2EK4KX.js";
@@ -91,7 +92,7 @@ import {
91
92
  answered,
92
93
  outboundResultOf,
93
94
  tokenGrantResultOf
94
- } from "./chunk-TVZU4HNT.js";
95
+ } from "./chunk-4J2KJ3ZW.js";
95
96
  import {
96
97
  __name
97
98
  } from "./chunk-7QVYU63E.js";
@@ -595,6 +596,163 @@ var engineRefusal = /* @__PURE__ */ __name((code) => ({
595
596
  message: null
596
597
  }), "engineRefusal");
597
598
 
599
+ // src/core/lifecycle.ts
600
+ var ECHO_OF = {
601
+ DISPATCHED: "DISPATCHED",
602
+ // The courier holding the bag answers the store's hand-over (FUT-5665).
603
+ COLLECTED: "HANDED_OVER",
604
+ CONCLUDED: "HANDED_OVER"
605
+ };
606
+ var NOTED_AS = {
607
+ DISPATCHED: "DISPATCHED",
608
+ COLLECTED: "HANDED_OVER",
609
+ CONCLUDED: "CONCLUDED"
610
+ };
611
+ async function ignored(ctx, inboxId, reason) {
612
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
613
+ return { kind: "ignored", reason };
614
+ }
615
+ __name(ignored, "ignored");
616
+ function refusal(held) {
617
+ if (held.status !== "ACCEPTED") return `the order is ${held.status}, not ACCEPTED`;
618
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") {
619
+ return `a cancellation request is ${held.cancellationStatus}`;
620
+ }
621
+ return null;
622
+ }
623
+ __name(refusal, "refusal");
624
+ function notTheFleets(lifecycle, held) {
625
+ return lifecycle === "COLLECTED" && held.deliveredBy !== "MARKETPLACE" ? "COLLECTED of a bag the marketplace does not carry" : null;
626
+ }
627
+ __name(notTheFleets, "notTheFleets");
628
+ function deliveredByOf(held) {
629
+ return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
630
+ }
631
+ __name(deliveredByOf, "deliveredByOf");
632
+ function following(ctx, event, settings) {
633
+ const hook = ctx.ports.order.onLifecycle;
634
+ if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;
635
+ return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };
636
+ }
637
+ __name(following, "following");
638
+ async function followLifecycle(ctx, inboxId, clientId, event, settings) {
639
+ const follow = following(ctx, event, settings);
640
+ if (!follow) return null;
641
+ const { lifecycle, hook } = follow;
642
+ const db = await ctx.ports.db();
643
+ const table = statusTable(db);
644
+ if (!table) return null;
645
+ const held = await db.marketplaceAcceptance.findFirst({
646
+ where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },
647
+ select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true }
648
+ });
649
+ if (!held) {
650
+ const reason2 = "lifecycle before its order";
651
+ await deferInboxEvent(ctx, inboxId, reason2);
652
+ return { kind: "ignored", reason: reason2 };
653
+ }
654
+ const stopped = refusal(held) ?? notTheFleets(lifecycle, held);
655
+ if (stopped) return ignored(ctx, inboxId, stopped);
656
+ const echo = ECHO_OF[lifecycle];
657
+ const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === "STORE");
658
+ if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);
659
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
660
+ await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: NOTED_AS[lifecycle] });
661
+ if (answer === "moved") {
662
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
663
+ ctx.ports.publishChanged(clientId);
664
+ return { kind: "moved", orderId: held.orderId, lifecycle };
665
+ }
666
+ const reason = answer === "unchanged" ? `already at or past ${lifecycle}` : answer.reason;
667
+ if (answer !== "unchanged") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);
668
+ return ignored(ctx, inboxId, reason);
669
+ }
670
+ __name(followLifecycle, "followLifecycle");
671
+
672
+ // src/core/courier.ts
673
+ function deliveredByOf2(value) {
674
+ return value === "MERCHANT" || value === "MARKETPLACE" ? value : null;
675
+ }
676
+ __name(deliveredByOf2, "deliveredByOf");
677
+ function reasonOf(answer, step) {
678
+ if (answer === "unchanged") return `nothing to record for ${step}`;
679
+ return answer === "recorded" ? "" : answer.reason;
680
+ }
681
+ __name(reasonOf, "reasonOf");
682
+ async function followCourier(ctx, clientId, event) {
683
+ const hook = ctx.ports.order.onCourier;
684
+ const courier = event.courier;
685
+ if (!hook || !courier || !event.externalOrderId) return null;
686
+ const db = await ctx.ports.db();
687
+ const held = await db.marketplaceAcceptance.findFirst({
688
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
689
+ select: { orderId: true, status: true, deliveredBy: true }
690
+ });
691
+ if (!held) return { kind: "deferred" };
692
+ if (held.status !== "ACCEPTED") return { kind: "stopped", reason: `the order is ${held.status}, not ACCEPTED` };
693
+ const facts = { deliveredBy: deliveredByOf2(held.deliveredBy), at: courier.at ?? ctx.ports.clock.now() };
694
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, courier, facts);
695
+ if (answer === "recorded") return { kind: "recorded", orderId: held.orderId, step: courier.step };
696
+ return { kind: "stopped", reason: reasonOf(answer, courier.step) };
697
+ }
698
+ __name(followCourier, "followCourier");
699
+ async function settleCourier(ctx, inboxId, clientId, outcome) {
700
+ if (outcome.kind === "recorded") {
701
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
702
+ ctx.ports.publishChanged(clientId);
703
+ return { kind: "courier", orderId: outcome.orderId, step: outcome.step };
704
+ }
705
+ if (outcome.kind === "deferred") {
706
+ const reason = "courier event before its order";
707
+ await deferInboxEvent(ctx, inboxId, reason);
708
+ return { kind: "ignored", reason };
709
+ }
710
+ await settleInboxEvent(ctx, inboxId, "IGNORED", outcome.reason);
711
+ return { kind: "ignored", reason: outcome.reason };
712
+ }
713
+ __name(settleCourier, "settleCourier");
714
+ async function followCourierAndLifecycle(ctx, inboxId, clientId, event, settings) {
715
+ const courier = await followCourier(ctx, clientId, event);
716
+ const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
717
+ const recorded = courier?.kind === "recorded";
718
+ if (followed && !(recorded && followed.kind === "ignored")) return followed;
719
+ return courier ? settleCourier(ctx, inboxId, clientId, courier) : null;
720
+ }
721
+ __name(followCourierAndLifecycle, "followCourierAndLifecycle");
722
+ async function readCourierTracking(ctx, input) {
723
+ const db = await ctx.ports.db();
724
+ const row = await db.marketplaceAcceptance.findFirst({
725
+ where: { clientId: input.clientId, orderId: input.orderId },
726
+ select: { orderId: true, provider: true, externalOrderId: true, externalDisplayId: true, deliveredBy: true, createdAt: true }
727
+ });
728
+ if (!row) return { kind: "unsupported", reason: "no marketplace order with this id" };
729
+ const api = ctx.registry.get(row.provider)?.courier;
730
+ if (!api) return { kind: "unsupported", reason: `${row.provider} has no courier tracking` };
731
+ if (row.deliveredBy !== "MARKETPLACE") return { kind: "unsupported", reason: "the order is not carried by the marketplace's courier" };
732
+ let connection;
733
+ try {
734
+ connection = await readOutboundConnection(ctx, input.clientId, row.provider);
735
+ } catch (error) {
736
+ return { kind: "refused", status: 0, message: `credentials do not open: ${error instanceof Error ? error.message : String(error)}`, own: true };
737
+ }
738
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
739
+ const ref = {
740
+ externalOrderId: row.externalOrderId,
741
+ externalDisplayId: row.externalDisplayId,
742
+ hostOrderCode: row.orderId,
743
+ placedAt: row.createdAt
744
+ };
745
+ return api.tracking({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, ref);
746
+ }
747
+ __name(readCourierTracking, "readCourierTracking");
748
+ function courierEngine(ctx) {
749
+ return {
750
+ validatePickupCode: /* @__PURE__ */ __name((input) => validatePickupCode(ctx, input), "validatePickupCode"),
751
+ courierTracking: /* @__PURE__ */ __name((input) => readCourierTracking(ctx, input), "courierTracking")
752
+ };
753
+ }
754
+ __name(courierEngine, "courierEngine");
755
+
598
756
  // src/core/linking.ts
599
757
  var refused2 = /* @__PURE__ */ __name((code, status = null, message = null) => ({
600
758
  kind: "refused",
@@ -1101,68 +1259,6 @@ async function sweepAvailability(ctx, now) {
1101
1259
  }
1102
1260
  __name(sweepAvailability, "sweepAvailability");
1103
1261
 
1104
- // src/core/lifecycle.ts
1105
- var ECHO_OF = {
1106
- DISPATCHED: "DISPATCHED",
1107
- CONCLUDED: "HANDED_OVER"
1108
- };
1109
- async function ignored(ctx, inboxId, reason) {
1110
- await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
1111
- return { kind: "ignored", reason };
1112
- }
1113
- __name(ignored, "ignored");
1114
- function refusal(held) {
1115
- if (held.status !== "ACCEPTED") return `the order is ${held.status}, not ACCEPTED`;
1116
- if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") {
1117
- return `a cancellation request is ${held.cancellationStatus}`;
1118
- }
1119
- return null;
1120
- }
1121
- __name(refusal, "refusal");
1122
- function deliveredByOf(held) {
1123
- return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
1124
- }
1125
- __name(deliveredByOf, "deliveredByOf");
1126
- function following(ctx, event, settings) {
1127
- const hook = ctx.ports.order.onLifecycle;
1128
- if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;
1129
- return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };
1130
- }
1131
- __name(following, "following");
1132
- async function followLifecycle(ctx, inboxId, clientId, event, settings) {
1133
- const follow = following(ctx, event, settings);
1134
- if (!follow) return null;
1135
- const { lifecycle, hook } = follow;
1136
- const db = await ctx.ports.db();
1137
- const table = statusTable(db);
1138
- if (!table) return null;
1139
- const held = await db.marketplaceAcceptance.findFirst({
1140
- where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },
1141
- select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true }
1142
- });
1143
- if (!held) {
1144
- const reason2 = "lifecycle before its order";
1145
- await deferInboxEvent(ctx, inboxId, reason2);
1146
- return { kind: "ignored", reason: reason2 };
1147
- }
1148
- const stopped = refusal(held);
1149
- if (stopped) return ignored(ctx, inboxId, stopped);
1150
- const echo = ECHO_OF[lifecycle];
1151
- const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === "STORE");
1152
- if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);
1153
- const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
1154
- await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
1155
- if (answer === "moved") {
1156
- await settleInboxEvent(ctx, inboxId, "PROCESSED");
1157
- ctx.ports.publishChanged(clientId);
1158
- return { kind: "moved", orderId: held.orderId, lifecycle };
1159
- }
1160
- const reason = answer === "unchanged" ? `already at or past ${lifecycle}` : answer.reason;
1161
- if (answer !== "unchanged") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);
1162
- return ignored(ctx, inboxId, reason);
1163
- }
1164
- __name(followLifecycle, "followLifecycle");
1165
-
1166
1262
  // src/core/pipeline.ts
1167
1263
  function normalizeEvent(ctx, provider, payload) {
1168
1264
  return ctx.registry.get(provider)?.normalize(payload) ?? null;
@@ -1217,7 +1313,7 @@ async function applyEvent(ctx, inboxId, clientId, event, settings, now) {
1217
1313
  await awaitOrderBody(ctx, clientId, inboxId);
1218
1314
  return { kind: "awaitingOrder" };
1219
1315
  }
1220
- const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
1316
+ const followed = await followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
1221
1317
  if (followed) return followed;
1222
1318
  return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
1223
1319
  }
@@ -1377,6 +1473,7 @@ function createMarketplaceEngine(config) {
1377
1473
  runOutbound: /* @__PURE__ */ __name((payload, attempt) => runOutbound(ctx, payload, attempt), "runOutbound"),
1378
1474
  runFetchOrder: /* @__PURE__ */ __name((payload, attempt) => runFetchOrder(ctx, payload, attempt), "runFetchOrder"),
1379
1475
  informStatus: /* @__PURE__ */ __name((input) => informStatus(ctx, input), "informStatus"),
1476
+ ...courierEngine(ctx),
1380
1477
  // Null too when the host bound no catalogue port: nothing could be published.
1381
1478
  catalogueMode: /* @__PURE__ */ __name((provider) => ports.catalogue ? registry.get(provider)?.catalogue?.mode ?? null : null, "catalogueMode"),
1382
1479
  publish: /* @__PURE__ */ __name((input) => publishToCatalogue(ctx, input), "publish"),