@adminide-stack/yantra-mobile 12.0.197-alpha.0 → 12.0.197
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.
- package/lib/components/NavigationHeader/NavigationHeader.js +10 -2
- package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -1
- package/lib/compute.js +5 -3
- package/lib/compute.js.map +1 -1
- package/lib/config/env-config.js +1 -1
- package/lib/config/env-config.js.map +1 -1
- package/lib/features/shopping/DealRails.js +1 -1
- package/lib/features/shopping/DealRails.js.map +1 -1
- package/lib/features/shopping/TrendingSections.js +6 -3
- package/lib/features/shopping/TrendingSections.js.map +1 -1
- package/lib/features/shopping/deals/registry.js +14 -1
- package/lib/features/shopping/deals/registry.js.map +1 -1
- package/lib/features/shopping/services/blackFridayBrowserSites.js +6 -3
- package/lib/features/shopping/services/blackFridayBrowserSites.js.map +1 -1
- package/lib/features/shopping/services/dealProviders.js +11 -2
- package/lib/features/shopping/services/dealProviders.js.map +1 -1
- package/lib/features/shopping/services/holidayDeals.js +7 -5
- package/lib/features/shopping/services/holidayDeals.js.map +1 -1
- package/lib/features/shopping/services/liveDealLanes.js +66 -24
- package/lib/features/shopping/services/liveDealLanes.js.map +1 -1
- package/lib/features/shopping/shoppingExec.js +60 -11
- package/lib/features/shopping/shoppingExec.js.map +1 -1
- package/lib/features/team-chat/TeamChatExperience.js +30 -15
- package/lib/features/team-chat/TeamChatExperience.js.map +1 -1
- package/lib/features/team-chat/api/client.js +19 -6
- package/lib/features/team-chat/api/client.js.map +1 -1
- package/lib/features/team-chat/app.js.map +1 -1
- package/lib/features/team-chat/components/Avatar.js +3 -2
- package/lib/features/team-chat/components/Avatar.js.map +1 -1
- package/lib/features/team-chat/components/Composer.js +8 -8
- package/lib/features/team-chat/components/Composer.js.map +1 -1
- package/lib/features/team-chat/components/Dialogs.js +7 -61
- package/lib/features/team-chat/components/Dialogs.js.map +1 -1
- package/lib/features/team-chat/components/EmojiPicker.js +2 -2
- package/lib/features/team-chat/components/EmojiPicker.js.map +1 -1
- package/lib/features/team-chat/components/MessageItem.js +23 -16
- package/lib/features/team-chat/components/MessageItem.js.map +1 -1
- package/lib/features/team-chat/components/MessageList.js +2 -2
- package/lib/features/team-chat/components/MessageList.js.map +1 -1
- package/lib/features/team-chat/components/QuickSwitcher.js +2 -2
- package/lib/features/team-chat/components/QuickSwitcher.js.map +1 -1
- package/lib/features/team-chat/components/TabBar.js +138 -0
- package/lib/features/team-chat/components/TabBar.js.map +1 -0
- package/lib/features/team-chat/components/YouButton.js +69 -0
- package/lib/features/team-chat/components/YouButton.js.map +1 -0
- package/lib/features/team-chat/components/ui.js +40 -12
- package/lib/features/team-chat/components/ui.js.map +1 -1
- package/lib/features/team-chat/theme.js +81 -29
- package/lib/features/team-chat/theme.js.map +1 -1
- package/lib/features/team-chat/views/ActivityView.js +8 -6
- package/lib/features/team-chat/views/ActivityView.js.map +1 -1
- package/lib/features/team-chat/views/BrowseView.js +2 -2
- package/lib/features/team-chat/views/BrowseView.js.map +1 -1
- package/lib/features/team-chat/views/ChannelView.js +2 -2
- package/lib/features/team-chat/views/ChannelView.js.map +1 -1
- package/lib/features/team-chat/views/DetailsPane.js +5 -5
- package/lib/features/team-chat/views/DetailsPane.js.map +1 -1
- package/lib/features/team-chat/views/DmsTab.js +154 -0
- package/lib/features/team-chat/views/DmsTab.js.map +1 -0
- package/lib/features/team-chat/views/DraftsView.js +2 -2
- package/lib/features/team-chat/views/DraftsView.js.map +1 -1
- package/lib/features/team-chat/views/FilesView.js +2 -2
- package/lib/features/team-chat/views/FilesView.js.map +1 -1
- package/lib/features/team-chat/views/NewMessageView.js +4 -4
- package/lib/features/team-chat/views/NewMessageView.js.map +1 -1
- package/lib/features/team-chat/views/PeopleView.js +2 -2
- package/lib/features/team-chat/views/PeopleView.js.map +1 -1
- package/lib/features/team-chat/views/ProfilePane.js +2 -2
- package/lib/features/team-chat/views/ProfilePane.js.map +1 -1
- package/lib/features/team-chat/views/SearchView.js +2 -2
- package/lib/features/team-chat/views/SearchView.js.map +1 -1
- package/lib/features/team-chat/views/Sidebar.js +247 -176
- package/lib/features/team-chat/views/Sidebar.js.map +1 -1
- package/lib/features/team-chat/views/ThreadPane.js +3 -3
- package/lib/features/team-chat/views/ThreadPane.js.map +1 -1
- package/lib/features/team-chat/views/ThreadsView.js +2 -2
- package/lib/features/team-chat/views/ThreadsView.js.map +1 -1
- package/lib/features/team-chat/views/YouTab.js +133 -0
- package/lib/features/team-chat/views/YouTab.js.map +1 -0
- package/lib/features/webbuilder/components/AppPhoneSheet.js +2 -2
- package/lib/features/webbuilder/components/AppPhoneSheet.js.map +1 -1
- package/lib/features/webbuilder/components/Credits.js +2 -2
- package/lib/features/webbuilder/components/Credits.js.map +1 -1
- package/lib/features/webbuilder/components/GithubConnectSheet.js +3 -3
- package/lib/features/webbuilder/components/GithubConnectSheet.js.map +1 -1
- package/lib/features/webbuilder/components/NotesSheet.js +2 -2
- package/lib/features/webbuilder/components/NotesSheet.js.map +1 -1
- package/lib/features/webbuilder/components/SiteScoreSheet.js +2 -2
- package/lib/features/webbuilder/components/SiteScoreSheet.js.map +1 -1
- package/lib/features/webbuilder/components/TemplatePreviewSheet.js +2 -2
- package/lib/features/webbuilder/components/TemplatePreviewSheet.js.map +1 -1
- package/lib/features/webbuilder/components/ui.js +12 -2
- package/lib/features/webbuilder/components/ui.js.map +1 -1
- package/lib/routes.json +2 -1
- package/lib/screens/TeamChat/index.js +9 -8
- package/lib/screens/TeamChat/index.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dealProviders.js","sources":["../../../../src/features/shopping/services/dealProviders.ts"],"sourcesContent":["/**\n * The shopping surface's sources, plugged into the shared universal board.\n *\n * Native port of web `services/dealProviders.ts` (0.37.0). Web's fifth lane,\n * the paired desktop browser (`browserDealsProvider`), is left out: a phone has\n * no Yantra extension to read retailer sale pages in.\n *\n * `dealsSearch` answers \"what product is marked down\" and is deliberately\n * product-shaped. This file is the adapter layer that lets the same lanes stand\n * next to sources that are NOT product-shaped — coupon feeds here, fare and\n * stay deals from the travel surface, local vouchers when a feed for them is\n * wired — on one board, ranked together.\n *\n * Registration happens once per bundle, on first use, rather than at import\n * time: a module-level side effect would register the providers into whichever\n * host loaded the remote first, including hosts that never open the deals view.\n */\nimport {\n registerDealProvider,\n searchUniversalDeals,\n type DealProvider,\n type UniversalDeal,\n type UniversalDealsRequest,\n type UniversalDealsResult,\n} from '../deals';\nimport type { Product } from '../catalog';\nimport { getShoppingRuntime } from '../shoppingRuntime';\nimport { isCatalogConfigured } from './catalogProductSearch';\nimport { COUPON_PROVIDER_ID, searchCouponDeals } from './couponDeals';\nimport { searchCatalogDealsLane, searchDeals, type DealsRequest, type DealsResult } from './dealsSearch';\nimport { searchLiveRetailerDeals } from './liveDealLanes';\nimport { isOffersConfigured } from './productOffers';\nimport { resolveShoppingSearchConnectorCredentials } from './shoppingSearchConnectorClient';\n\n/** The offers lane — Google Shopping's live markdowns. Keeps its historical id. */\nexport const PRODUCT_DEALS_PROVIDER_ID = 'shopping-products';\nexport const CATALOG_DEALS_PROVIDER_ID = 'shopping-catalog';\nexport const LIVE_RETAILER_DEALS_PROVIDER_ID = 'shopping-live-retailers';\n\n/**\n * A storefront row as a universal deal.\n *\n * The `Product` is carried through on `raw` rather than flattened away, so the\n * board can render the existing product card for these rows — a product deal\n * loses its image, its rating and its cart button if it is downgraded to the\n * common shape on the way to the screen.\n */\nexport function productToUniversalDeal(product: Product, providerId = PRODUCT_DEALS_PROVIDER_ID): UniversalDeal {\n return {\n id: product.id,\n kind: 'product',\n title: product.name,\n providerId,\n price: product.price,\n ...(product.originalPrice != null ? { originalPrice: product.originalPrice } : {}),\n ...(product.discountPercent != null ? { discountPercent: product.discountPercent } : {}),\n ...(product.currency ? { currency: product.currency } : {}),\n ...(product.imageUrl ? { imageUrl: product.imageUrl } : {}),\n ...(product.url ? { url: product.url } : {}),\n ...(product.retailerId ? { merchant: product.retailerId } : {}),\n ...(product.rating ? { rating: product.rating } : {}),\n ...(typeof product.inStock === 'boolean' ? { inStock: product.inStock } : {}),\n ...(product.reviews ? { reviews: product.reviews } : {}),\n raw: product,\n };\n}\n\n/**\n * Any route to a coupon feed at all.\n *\n * Three keys, not one, because the lane merges three feeds and a host commonly\n * holds exactly one of them — reporting the source unconfigured because the\n * OTHER vendor's key is missing would hide a working feed behind a setup\n * message.\n */\nfunction hasCouponFeed(): boolean {\n // The host may hold no key at all and still have a working lane, because the\n // connector resolves feed credentials backend-side — `couponsEnabled` is how\n // a deployment says so, exactly as `catalogEnabled` does for the catalog.\n if (getShoppingRuntime().config.shoppingSearch?.couponsEnabled) return true;\n const credentials = resolveShoppingSearchConnectorCredentials();\n return !!(credentials.linkmydealsApiKey || credentials.couponApiKey || credentials.rapidApiKey);\n}\n\n/** The shared shape of a product lane's `fetch`: the chips, mapped once. */\nfunction toDealsRequest(request: UniversalDealsRequest): DealsRequest {\n return {\n ...(request.query ? { query: request.query } : {}),\n ...(request.departmentId ? { departmentId: request.departmentId } : {}),\n ...(request.minDiscount != null ? { minDiscount: request.minDiscount } : {}),\n ...(request.maxPrice != null ? { maxPrice: request.maxPrice } : {}),\n ...(request.minRating != null ? { minRating: request.minRating } : {}),\n ...(request.inStock ? { inStock: true } : {}),\n sort: request.sort === 'price' ? 'price' : 'discount',\n // Fetch the provider's own depth, not the board's: the board's limit\n // is a budget shared across every source, and asking each source for\n // only that many would leave the interleave nothing to choose from.\n limit: request.maxPerProvider ?? request.limit ?? 24,\n };\n}\n\nfunction toProviderResult(result: DealsResult, providerId: string) {\n return {\n deals: result.products.map((product) => productToUniversalDeal(product, providerId)),\n ...(result.hint ? { hint: result.hint } : {}),\n ...(result.error ? { error: result.error } : {}),\n };\n}\n\n/**\n * Google Shopping's live markdowns — the lane with a real list price on every\n * row and no index behind it. First to paint of the product lanes.\n *\n * Long budget, because this lane is legitimately slow and the arithmetic says\n * so: a browse board with no term sweeps `DEALS_SEED_LIMIT` seed queries\n * SEQUENTIALLY (the upstream is quota-metered and a burst trips its rate\n * limit) and the connector gives each request 20s of its own. Anything tighter\n * reports a working lane as timed out. The board does not WAIT this long to\n * render — `onPartial` paints the other sources as they land.\n */\nexport const productDealsProvider: DealProvider = {\n id: PRODUCT_DEALS_PROVIDER_ID,\n label: 'Google Shopping',\n kinds: ['product'],\n // `offersEnabled` is how a deployment says \"the connector holds the key\" —\n // the browser-held key is only a proxy for \"the lane is usable\", and a\n // wrong one on the standalone build (see catalogEnabled / couponsEnabled).\n isConfigured: isOffersConfigured,\n timeoutMs: 95_000,\n fetch: async (request) => toProviderResult(await searchDeals(toDealsRequest(request)), PRODUCT_DEALS_PROVIDER_ID),\n};\n\n/**\n * The indexed catalog — one contributor, no longer a gate. Its rows are typed\n * (real list price, stock, identifiers) so they win the cross-provider dedupe\n * when the same product also arrives from a live lane.\n */\nexport const catalogDealsProvider: DealProvider = {\n id: CATALOG_DEALS_PROVIDER_ID,\n label: 'Indexed catalog',\n kinds: ['product'],\n isConfigured: () => isCatalogConfigured(),\n // The indexed store answers in ms when warm, but LemmeBuyIt's DEALS query\n // over a cold index has been seen to take well past 20s; that ceiling\n // reported a working lane as timed out. Still far under the sweep lanes.\n timeoutMs: 60_000,\n fetch: async (request) =>\n toProviderResult(await searchCatalogDealsLane(toDealsRequest(request)), CATALOG_DEALS_PROVIDER_ID),\n};\n\n/**\n * Live retailer listings + Yantra research, every discount read off the\n * product page. Slowest lane: a search fan-out per seed, then up to\n * `VERIFY_LIMIT` page reads. Configured when either search backend can run.\n */\nexport const liveRetailerDealsProvider: DealProvider = {\n id: LIVE_RETAILER_DEALS_PROVIDER_ID,\n label: 'Live retailers',\n kinds: ['product'],\n // Always on: this is the SAME search the Shop tab runs (Amazon + retailer\n // LISTs + Yantra research through the connector), and that tab has never\n // gated on a browser-held key. If the connector cannot search, the lane\n // reports \"down\" with the connector's own message rather than \"off\".\n isConfigured: () => true,\n timeoutMs: 120_000,\n fetch: async (request) =>\n toProviderResult(await searchLiveRetailerDeals(toDealsRequest(request)), LIVE_RETAILER_DEALS_PROVIDER_ID),\n};\n\n/**\n * Coupons and vouchers — the lane with no product behind it.\n *\n * Declares `local` alongside `coupon` because the same feed carries both: a\n * place-bound voucher is a coupon row that came with a location. Declaring only\n * `coupon` would make a \"local deals\" board skip this provider and show nothing\n * on the very ask it can answer.\n */\nexport const couponDealsProvider: DealProvider = {\n id: COUPON_PROVIDER_ID,\n label: 'Coupons & vouchers',\n kinds: ['coupon', 'local'],\n isConfigured: hasCouponFeed,\n // One request per feed, fanned out inside the connector (20s each there), so\n // a single connector round-trip plus headroom — not the sweep's arithmetic.\n timeoutMs: 30_000,\n fetch: async (request: UniversalDealsRequest) => {\n const result = await searchCouponDeals({\n ...(request.query ? { query: request.query } : {}),\n ...(request.minDiscount != null ? { minDiscount: request.minDiscount } : {}),\n maxResults: request.maxPerProvider ?? request.limit ?? 24,\n });\n return {\n deals: result.deals,\n ...(result.source ? { hint: `Coupon feed: ${result.source}.` } : {}),\n ...(result.error ? { error: result.error } : {}),\n };\n },\n};\n\n/**\n * Register this surface's sources. Safe to call from every mount.\n *\n * Idempotent through the REGISTRY (`registerDealProvider` replaces by id)\n * rather than through a module-level \"already done\" flag. The flag version\n * looked equivalent and was not: anything that clears the registry — a host\n * tearing a surface down, a test isolating a board — left the flag set, so the\n * next call registered nothing and the board came back permanently empty with\n * no error anywhere.\n *\n * Other surfaces call their own equivalent; the board is whatever has been\n * registered by the time it runs, which is how a standalone shopping build\n * shows two sources and a host with travel mounted shows more, with no\n * conditional imports in either.\n */\nexport function registerShoppingDealProviders(): void {\n registerDealProvider(productDealsProvider);\n registerDealProvider(catalogDealsProvider);\n registerDealProvider(liveRetailerDealsProvider);\n registerDealProvider(couponDealsProvider);\n}\n\n/**\n * The deals board's one entry point: every registered source, merged.\n *\n * Registers on the way in so a caller cannot get a half-built board by\n * forgetting the setup call — the failure mode that would look exactly like a\n * provider being down.\n */\nexport async function searchAllDeals(\n request: UniversalDealsRequest = {},\n options: { onPartial?: (result: UniversalDealsResult) => void } = {},\n) {\n registerShoppingDealProviders();\n return searchUniversalDeals(request, options);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA4BO,MAAM,yBAA4B,GAAA;AAClC,MAAM,yBAA4B,GAAA;AAClC,MAAM,+BAAkC,GAAA;AAU/B,SAAA,sBAAA,CAAuB,OAAkB,EAAA,UAAA,GAAa,yBAA0C,EAAA;AAC9G,EAAO,OAAA,aAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA;AAAA,IACL,IAAI,OAAQ,CAAA,EAAA;AAAA,IACZ,IAAM,EAAA,SAAA;AAAA,IACN,OAAO,OAAQ,CAAA,IAAA;AAAA,IACf,UAAA;AAAA,IACA,OAAO,OAAQ,CAAA;AAAA,GACX,EAAA,OAAA,CAAQ,iBAAiB,IAAO,GAAA;AAAA,IAClC,eAAe,OAAQ,CAAA;AAAA,GACrB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,mBAAmB,IAAO,GAAA;AAAA,IACpC,iBAAiB,OAAQ,CAAA;AAAA,GACvB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,QAAW,GAAA;AAAA,IACrB,UAAU,OAAQ,CAAA;AAAA,GAChB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,QAAW,GAAA;AAAA,IACrB,UAAU,OAAQ,CAAA;AAAA,GAChB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,GAAM,GAAA;AAAA,IAChB,KAAK,OAAQ,CAAA;AAAA,GACX,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,UAAa,GAAA;AAAA,IACvB,UAAU,OAAQ,CAAA;AAAA,GAChB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,MAAS,GAAA;AAAA,IACnB,QAAQ,OAAQ,CAAA;AAAA,MAC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AAAA,KACxD,CAAA,CAAA;AACD,IAAO,OAAA,cAAA,CAAA,cAAA,CAAA;AAAA,MACL,OAAO,MAAO,CAAA;AAAA,KAAA,EACV,OAAO,MAAS,GAAA;AAAA,MAClB,IAAA,EAAM,CAAgB,aAAA,EAAA,MAAA,CAAO,MAAM,CAAA,CAAA;AAAA,KACjC,GAAA,EACA,CAAA,EAAA,MAAA,CAAO,KAAQ,GAAA;AAAA,MACjB,OAAO,MAAO,CAAA;AAAA,QACZ,EAAC,CAAA;AAAA;AAGX;AAiBO,SAAS,6BAAsC,GAAA;AACpD,EAAA,oBAAA,CAAqB,oBAAoB,CAAA;AACzC,EAAA,oBAAA,CAAqB,oBAAoB,CAAA;AACzC,EAAA,oBAAA,CAAqB,yBAAyB,CAAA;AAC9C,EAAA,oBAAA,CAAqB,mBAAmB,CAAA;AAC1C;AASA,eAAsB,eAAe,OAAiC,GAAA,EAAI,EAAA,OAAA,GAEtE,EAAI,EAAA;AACN,EAA8B,6BAAA,EAAA;AAC9B,EAAO,OAAA,oBAAA,CAAqB,SAAS,OAAO,CAAA;AAC9C"}
|
|
1
|
+
{"version":3,"file":"dealProviders.js","sources":["../../../../src/features/shopping/services/dealProviders.ts"],"sourcesContent":["/**\n * The shopping surface's sources, plugged into the shared universal board.\n *\n * Native port of web `services/dealProviders.ts` (0.37.0). Web's fifth lane,\n * the paired desktop browser (`browserDealsProvider`), is left out: a phone has\n * no Yantra extension to read retailer sale pages in.\n *\n * `dealsSearch` answers \"what product is marked down\" and is deliberately\n * product-shaped. This file is the adapter layer that lets the same lanes stand\n * next to sources that are NOT product-shaped — coupon feeds here, fare and\n * stay deals from the travel surface, local vouchers when a feed for them is\n * wired — on one board, ranked together.\n *\n * Registration happens once per bundle, on first use, rather than at import\n * time: a module-level side effect would register the providers into whichever\n * host loaded the remote first, including hosts that never open the deals view.\n */\nimport {\n registerDealProvider,\n searchUniversalDeals,\n type DealProvider,\n type UniversalDeal,\n type UniversalDealsRequest,\n type UniversalDealsResult,\n} from '../deals';\nimport type { Product } from '../catalog';\nimport { getShoppingRuntime } from '../shoppingRuntime';\nimport { isCatalogConfigured } from './catalogProductSearch';\nimport { COUPON_PROVIDER_ID, searchCouponDeals } from './couponDeals';\nimport { searchCatalogDealsLane, searchDeals, type DealsRequest, type DealsResult } from './dealsSearch';\nimport { searchLiveRetailerDeals } from './liveDealLanes';\nimport { isOffersConfigured } from './productOffers';\nimport { resolveShoppingSearchConnectorCredentials } from './shoppingSearchConnectorClient';\n\n/** The offers lane — Google Shopping's live markdowns. Keeps its historical id. */\nexport const PRODUCT_DEALS_PROVIDER_ID = 'shopping-products';\nexport const CATALOG_DEALS_PROVIDER_ID = 'shopping-catalog';\nexport const LIVE_RETAILER_DEALS_PROVIDER_ID = 'shopping-live-retailers';\n\n/**\n * A storefront row as a universal deal.\n *\n * The `Product` is carried through on `raw` rather than flattened away, so the\n * board can render the existing product card for these rows — a product deal\n * loses its image, its rating and its cart button if it is downgraded to the\n * common shape on the way to the screen.\n */\nexport function productToUniversalDeal(product: Product, providerId = PRODUCT_DEALS_PROVIDER_ID): UniversalDeal {\n return {\n id: product.id,\n kind: 'product',\n title: product.name,\n providerId,\n price: product.price,\n ...(product.originalPrice != null ? { originalPrice: product.originalPrice } : {}),\n ...(product.discountPercent != null ? { discountPercent: product.discountPercent } : {}),\n ...(product.currency ? { currency: product.currency } : {}),\n ...(product.imageUrl ? { imageUrl: product.imageUrl } : {}),\n ...(product.url ? { url: product.url } : {}),\n ...(product.retailerId ? { merchant: product.retailerId } : {}),\n ...(product.rating ? { rating: product.rating } : {}),\n ...(typeof product.inStock === 'boolean' ? { inStock: product.inStock } : {}),\n ...(product.reviews ? { reviews: product.reviews } : {}),\n raw: product,\n };\n}\n\n/**\n * Any route to a coupon feed at all.\n *\n * Three keys, not one, because the lane merges three feeds and a host commonly\n * holds exactly one of them — reporting the source unconfigured because the\n * OTHER vendor's key is missing would hide a working feed behind a setup\n * message.\n */\nfunction hasCouponFeed(): boolean {\n // The host may hold no key at all and still have a working lane, because the\n // connector resolves feed credentials backend-side — `couponsEnabled` is how\n // a deployment says so, exactly as `catalogEnabled` does for the catalog.\n if (getShoppingRuntime().config.shoppingSearch?.couponsEnabled) return true;\n const credentials = resolveShoppingSearchConnectorCredentials();\n return !!(credentials.linkmydealsApiKey || credentials.couponApiKey || credentials.rapidApiKey);\n}\n\n/** The shared shape of a product lane's `fetch`: the chips, mapped once. */\nfunction toDealsRequest(request: UniversalDealsRequest): DealsRequest {\n return {\n ...(request.query ? { query: request.query } : {}),\n ...(request.departmentId ? { departmentId: request.departmentId } : {}),\n ...(request.minDiscount != null ? { minDiscount: request.minDiscount } : {}),\n ...(request.maxPrice != null ? { maxPrice: request.maxPrice } : {}),\n ...(request.minRating != null ? { minRating: request.minRating } : {}),\n ...(request.inStock ? { inStock: true } : {}),\n sort: request.sort === 'price' ? 'price' : 'discount',\n // Fetch the provider's own depth, not the board's: the board's limit\n // is a budget shared across every source, and asking each source for\n // only that many would leave the interleave nothing to choose from.\n limit: request.maxPerProvider ?? request.limit ?? 24,\n };\n}\n\nfunction toProviderResult(result: DealsResult, providerId: string) {\n return {\n deals: result.products.map((product) => productToUniversalDeal(product, providerId)),\n ...(result.hint ? { hint: result.hint } : {}),\n ...(result.error ? { error: result.error } : {}),\n };\n}\n\n/**\n * Google Shopping's live markdowns — the lane with a real list price on every\n * row and no index behind it. First to paint of the product lanes.\n *\n * Long budget, because this lane is legitimately slow and the arithmetic says\n * so: a browse board with no term sweeps `DEALS_SEED_LIMIT` seed queries\n * SEQUENTIALLY (the upstream is quota-metered and a burst trips its rate\n * limit) and the connector gives each request 20s of its own. Anything tighter\n * reports a working lane as timed out. The board does not WAIT this long to\n * render — `onPartial` paints the other sources as they land.\n */\nexport const productDealsProvider: DealProvider = {\n id: PRODUCT_DEALS_PROVIDER_ID,\n label: 'Google Shopping',\n kinds: ['product'],\n // `offersEnabled` is how a deployment says \"the connector holds the key\" —\n // the browser-held key is only a proxy for \"the lane is usable\", and a\n // wrong one on the standalone build (see catalogEnabled / couponsEnabled).\n isConfigured: isOffersConfigured,\n timeoutMs: 95_000,\n fetch: async (request) => toProviderResult(await searchDeals(toDealsRequest(request)), PRODUCT_DEALS_PROVIDER_ID),\n};\n\n/**\n * The indexed catalog — one contributor, no longer a gate. Its rows are typed\n * (real list price, stock, identifiers) so they win the cross-provider dedupe\n * when the same product also arrives from a live lane.\n */\nexport const catalogDealsProvider: DealProvider = {\n id: CATALOG_DEALS_PROVIDER_ID,\n label: 'Indexed catalog',\n kinds: ['product'],\n isConfigured: () => isCatalogConfigured(),\n // The indexed store answers in ms when warm, but LemmeBuyIt's DEALS query\n // over a cold index has been seen to take well past 20s; that ceiling\n // reported a working lane as timed out. Still far under the sweep lanes.\n timeoutMs: 60_000,\n fetch: async (request) =>\n toProviderResult(await searchCatalogDealsLane(toDealsRequest(request)), CATALOG_DEALS_PROVIDER_ID),\n};\n\n/**\n * Live retailer listings + Yantra research, every discount read off the\n * product page. Slowest lane: a search fan-out per seed, then up to\n * `VERIFY_LIMIT` page reads. Configured when either search backend can run.\n */\n/** When the live sweep stops waiting for slow stores (native; under the 120 s budget). */\nexport const LIVE_DEALS_DEADLINE_MS = 95_000;\n\nexport const liveRetailerDealsProvider: DealProvider = {\n id: LIVE_RETAILER_DEALS_PROVIDER_ID,\n label: 'Live retailers',\n kinds: ['product'],\n // Always on: this is the SAME search the Shop tab runs (Amazon + retailer\n // LISTs + Yantra research through the connector), and that tab has never\n // gated on a browser-held key. If the connector cannot search, the lane\n // reports \"down\" with the connector's own message rather than \"off\".\n isConfigured: () => true,\n timeoutMs: 120_000,\n // Native: the stores that answered are kept - the sweep stops waiting at 95 s and checks what\n // landed (verification fits in the rest of the budget), and each store's deals paint as they land.\n fetch: async (request, progress) =>\n toProviderResult(\n await searchLiveRetailerDeals(toDealsRequest(request), {\n deadlineMs: LIVE_DEALS_DEADLINE_MS,\n onPartial: (partial) =>\n progress?.onPartial?.(toProviderResult(partial, LIVE_RETAILER_DEALS_PROVIDER_ID)),\n }),\n LIVE_RETAILER_DEALS_PROVIDER_ID,\n ),\n};\n\n/**\n * Coupons and vouchers — the lane with no product behind it.\n *\n * Declares `local` alongside `coupon` because the same feed carries both: a\n * place-bound voucher is a coupon row that came with a location. Declaring only\n * `coupon` would make a \"local deals\" board skip this provider and show nothing\n * on the very ask it can answer.\n */\nexport const couponDealsProvider: DealProvider = {\n id: COUPON_PROVIDER_ID,\n label: 'Coupons & vouchers',\n kinds: ['coupon', 'local'],\n isConfigured: hasCouponFeed,\n // One request per feed, fanned out inside the connector (20s each there), so\n // a single connector round-trip plus headroom — not the sweep's arithmetic.\n timeoutMs: 30_000,\n fetch: async (request: UniversalDealsRequest) => {\n const result = await searchCouponDeals({\n ...(request.query ? { query: request.query } : {}),\n ...(request.minDiscount != null ? { minDiscount: request.minDiscount } : {}),\n maxResults: request.maxPerProvider ?? request.limit ?? 24,\n });\n return {\n deals: result.deals,\n ...(result.source ? { hint: `Coupon feed: ${result.source}.` } : {}),\n ...(result.error ? { error: result.error } : {}),\n };\n },\n};\n\n/**\n * Register this surface's sources. Safe to call from every mount.\n *\n * Idempotent through the REGISTRY (`registerDealProvider` replaces by id)\n * rather than through a module-level \"already done\" flag. The flag version\n * looked equivalent and was not: anything that clears the registry — a host\n * tearing a surface down, a test isolating a board — left the flag set, so the\n * next call registered nothing and the board came back permanently empty with\n * no error anywhere.\n *\n * Other surfaces call their own equivalent; the board is whatever has been\n * registered by the time it runs, which is how a standalone shopping build\n * shows two sources and a host with travel mounted shows more, with no\n * conditional imports in either.\n */\nexport function registerShoppingDealProviders(): void {\n registerDealProvider(productDealsProvider);\n registerDealProvider(catalogDealsProvider);\n registerDealProvider(liveRetailerDealsProvider);\n registerDealProvider(couponDealsProvider);\n}\n\n/**\n * The deals board's one entry point: every registered source, merged.\n *\n * Registers on the way in so a caller cannot get a half-built board by\n * forgetting the setup call — the failure mode that would look exactly like a\n * provider being down.\n */\nexport async function searchAllDeals(\n request: UniversalDealsRequest = {},\n options: { onPartial?: (result: UniversalDealsResult) => void } = {},\n) {\n registerShoppingDealProviders();\n return searchUniversalDeals(request, options);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA4BO,MAAM,yBAA4B,GAAA;AAClC,MAAM,yBAA4B,GAAA;AAClC,MAAM,+BAAkC,GAAA;AAU/B,SAAA,sBAAA,CAAuB,OAAkB,EAAA,UAAA,GAAa,yBAA0C,EAAA;AAC9G,EAAO,OAAA,aAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA,cAAA,CAAA;AAAA,IACL,IAAI,OAAQ,CAAA,EAAA;AAAA,IACZ,IAAM,EAAA,SAAA;AAAA,IACN,OAAO,OAAQ,CAAA,IAAA;AAAA,IACf,UAAA;AAAA,IACA,OAAO,OAAQ,CAAA;AAAA,GACX,EAAA,OAAA,CAAQ,iBAAiB,IAAO,GAAA;AAAA,IAClC,eAAe,OAAQ,CAAA;AAAA,GACrB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,mBAAmB,IAAO,GAAA;AAAA,IACpC,iBAAiB,OAAQ,CAAA;AAAA,GACvB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,QAAW,GAAA;AAAA,IACrB,UAAU,OAAQ,CAAA;AAAA,GAChB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,QAAW,GAAA;AAAA,IACrB,UAAU,OAAQ,CAAA;AAAA,GAChB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,GAAM,GAAA;AAAA,IAChB,KAAK,OAAQ,CAAA;AAAA,GACX,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,UAAa,GAAA;AAAA,IACvB,UAAU,OAAQ,CAAA;AAAA,GAChB,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,MAAS,GAAA;AAAA,IACnB,QAAQ,OAAQ,CAAA;AAAA,MACd,EAAC,CAAA,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AAA,cAAA,CAAA,EAAA,EACjC,QAAQ,KAAQ,GAAA;AAAA,MAClB,OAAO,OAAQ,CAAA;AAAA,KACb,GAAA,EACA,CAAA,EAAA,OAAA,CAAQ,eAAe,IAAO,GAAA;AAAA,MAChC,aAAa,OAAQ,CAAA;AAAA,KACvB,GAAI,EANiC,CAAA,EAAA;AAAA,MAOrC,aAAY,EAAQ,GAAA,CAAA,EAAA,GAAA,OAAA,CAAA,cAAA,KAAR,IAA0B,GAAA,EAAA,GAAA,OAAA,CAAQ,UAAlC,IAA2C,GAAA,EAAA,GAAA;AAAA,KACxD,CAAA,CAAA;AACD,IAAO,OAAA,cAAA,CAAA,cAAA,CAAA;AAAA,MACL,OAAO,MAAO,CAAA;AAAA,KAAA,EACV,OAAO,MAAS,GAAA;AAAA,MAClB,IAAA,EAAM,CAAgB,aAAA,EAAA,MAAA,CAAO,MAAM,CAAA,CAAA;AAAA,KACjC,GAAA,EACA,CAAA,EAAA,MAAA,CAAO,KAAQ,GAAA;AAAA,MACjB,OAAO,MAAO,CAAA;AAAA,QACZ,EAAC,CAAA;AAAA;AAGX;AAiBO,SAAS,6BAAsC,GAAA;AACpD,EAAA,oBAAA,CAAqB,oBAAoB,CAAA;AACzC,EAAA,oBAAA,CAAqB,oBAAoB,CAAA;AACzC,EAAA,oBAAA,CAAqB,yBAAyB,CAAA;AAC9C,EAAA,oBAAA,CAAqB,mBAAmB,CAAA;AAC1C;AASA,eAAsB,eAAe,OAAiC,GAAA,EAAI,EAAA,OAAA,GAEtE,EAAI,EAAA;AACN,EAA8B,6BAAA,EAAA;AAC9B,EAAO,OAAA,oBAAA,CAAqB,SAAS,OAAO,CAAA;AAC9C"}
|
|
@@ -17,13 +17,15 @@ var __spreadValues = (a, b) => {
|
|
|
17
17
|
function blackFridaySitePage(site, query) {
|
|
18
18
|
return site.url(query.trim() || BLACK_FRIDAY_SEASON_QUERY);
|
|
19
19
|
}
|
|
20
|
-
function
|
|
21
|
-
if (!answer) return false;
|
|
20
|
+
function sourceReport(site, answer) {
|
|
22
21
|
const label = site.label.toLowerCase();
|
|
23
|
-
|
|
22
|
+
return answer == null ? void 0 : answer.sources.find((source) => {
|
|
24
23
|
var _a;
|
|
25
24
|
return source.source === site.id || ((_a = source.label) != null ? _a : "").toLowerCase() === label;
|
|
26
25
|
});
|
|
26
|
+
}
|
|
27
|
+
function serverReported(site, answer) {
|
|
28
|
+
const report = sourceReport(site, answer);
|
|
27
29
|
return !!report && (report.status === "ok" || report.status === "empty" || report.status === "reading");
|
|
28
30
|
}
|
|
29
31
|
const READING_REFETCH_MS = 3e4;
|
|
@@ -101,7 +103,7 @@ function holidaySiteStates(answer) {
|
|
|
101
103
|
var _a2;
|
|
102
104
|
return source.source === site.id || ((_a2 = source.label) != null ? _a2 : "").toLowerCase() === label;
|
|
103
105
|
}) : void 0;
|
|
104
|
-
if (
|
|
106
|
+
if (serverReported(site, answer)) {
|
|
105
107
|
out[site.id] = __spreadValues({
|
|
106
108
|
kind: "server",
|
|
107
109
|
count: (_a = report == null ? void 0 : report.count) != null ? _a : 0
|
|
@@ -140,4 +142,4 @@ function serversReadingCount(states) {
|
|
|
140
142
|
const state = states[site.id];
|
|
141
143
|
return (state == null ? void 0 : state.kind) === "server" && state.reading === true;
|
|
142
144
|
}).length;
|
|
143
|
-
}export{HOLIDAY_SITE_GROUPS,HOLIDAY_STORE_COUNT,READING_REFETCHES,READING_REFETCH_MS,blackFridaySitePage,holidaySiteStates,holidaySiteStatus,mergeHolidayDeals,readingRefetch,
|
|
145
|
+
}export{HOLIDAY_SITE_GROUPS,HOLIDAY_STORE_COUNT,READING_REFETCHES,READING_REFETCH_MS,blackFridaySitePage,holidaySiteStates,holidaySiteStatus,mergeHolidayDeals,readingRefetch,serversReadingCount};//# sourceMappingURL=holidayDeals.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"holidayDeals.js","sources":["../../../../src/features/shopping/services/holidayDeals.ts"],"sourcesContent":["/**\n * The holiday deals section's merging, ordering and site directory - the pure\n * half of the web surface's `services/blackFridayBrowser.ts` (0.49.0).\n *\n * On the web a paired desktop browser also reads the deal sites and stores a\n * server cannot (`readBlackFridaySite`, the deal-reader script, the\n * own-browser queue). A phone has no shopper's browser to read them in, so\n * that half is not ported: the browser's deal list is always empty here, and\n * every site the servers did not read opens on its own search page instead.\n * What is kept is verbatim: how the connector's deals are merged and ordered\n * (`mergeHolidayDeals`, `VERDICT_RANK`, accessories after the product), which\n * sites the servers answered for (`serverAnswered`), the \"still reading\"\n * re-ask (`readingRefetch`), each site's own page (`blackFridaySitePage`) and\n * the query match (`rowMatchesQuery`).\n */\nimport type { BlackFridayAnswer, BlackFridayDeal, BlackFridaySort } from './blackFriday';\nimport {\n BLACK_FRIDAY_BROWSER_SITES,\n BLACK_FRIDAY_SEASON_QUERY,\n BLACK_FRIDAY_STORE_GROUPS,\n type BlackFridaySite,\n} from './blackFridayBrowserSites';\nimport { MODEL_LINE_WORDS as MODEL_LINE } from './modelWords';\nimport { accessoryTest } from './searchRelevance';\n\n/** The page a site is read on, and the query the reader searches for (the season's deals when none was typed). */\nexport function blackFridaySitePage(site: BlackFridaySite, query: string): string {\n return site.url(query.trim() || BLACK_FRIDAY_SEASON_QUERY);\n}\n\nconst tokens = (text: string): string[] =>\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((token) => token.length > 1);\n\n/** A word without its plural s (\"tvs\" → \"tv\", \"laptops\" → \"laptop\"); \"glass\" keeps its own. */\nconst singular = (word: string): string =>\n word.length > 2 && word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word;\n\n/**\n * Whether a row answers what the shopper typed. A page that searched for the\n * query needs half its words in the title; a page that lists deals without\n * searching (or a search that fell back to the latest deals) needs all of them.\n *\n * A model-line word counts only right after the word it names, and a title that\n * names that word without it is another line: a store's search for \"macbook pro\"\n * also lists \"Win11 Pro\" laptops, \"Beats Studio Pro\" and the \"MacBook Neo\".\n */\nexport function rowMatchesQuery(title: string, query: string, searched: boolean): boolean {\n const words = tokens(query).map(singular);\n if (words.length === 0) return true;\n // Whole words: \"art\" is not in \"Smart TV\".\n const said = tokens(title).map(singular);\n const inTitle = new Set(said);\n const follows = (head: string, word: string) => said.some((token, at) => token === head && said[at + 1] === word);\n let hits = 0;\n let named = false;\n for (const [at, word] of words.entries()) {\n const head = at > 0 ? words[at - 1] : undefined;\n if (head && MODEL_LINE.has(word) && !MODEL_LINE.has(head)) {\n if (inTitle.has(head) && !follows(head, word)) return false;\n if (follows(head, word)) hits++;\n } else if (head && MODEL_LINE.has(word)) {\n // \"pro max\": the second line word follows the first\n if (follows(head, word)) hits++;\n else if (inTitle.has(head)) return false;\n } else if (inTitle.has(word)) {\n hits++;\n named = true;\n }\n }\n // A product the shopper named must be in the title, not only its line (\"pro\")\n if (!named && words.some((word, at) => !(at > 0 && MODEL_LINE.has(word)))) return false;\n return searched ? hits >= Math.ceil(words.length / 2) : hits === words.length;\n}\n\n/**\n * Whether the connector already read `site` for this search: any site it\n * reports (found deals, found none, or is still reading it - its next answer\n * brings those), not only the sites it read before the deal recipes.\n */\nexport function serverAnswered(site: BlackFridaySite, answer: BlackFridayAnswer | undefined): boolean {\n if (!answer) return false;\n const label = site.label.toLowerCase();\n const report = answer.sources.find(\n (source) => source.source === site.id || (source.label ?? '').toLowerCase() === label,\n );\n return !!report && (report.status === 'ok' || report.status === 'empty' || report.status === 'reading');\n}\n\n/** Ask the connector again this often while it says it is still reading a site, at most READING_REFETCHES times. */\nexport const READING_REFETCH_MS = 30_000;\nexport const READING_REFETCHES = 12;\n\n/** The panel's refetch interval: READING_REFETCH_MS while the server is still reading a site, a few times; else none. */\nexport function readingRefetch(answer: BlackFridayAnswer | undefined, updates: number): number | false {\n return answer?.sources.some((source) => source.status === 'reading') && updates <= READING_REFETCHES\n ? READING_REFETCH_MS\n : false;\n}\n\nconst dealKey = (deal: BlackFridayDeal): string =>\n `${deal.title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, ' ')\n .trim()}|${deal.price}`;\n\n/** One per link and per product at a store, the first group's first: the order given is kept. */\nfunction dedupeDeals(...groups: BlackFridayDeal[][]): BlackFridayDeal[] {\n const byUrl = new Set<string>();\n const byKey = new Set<string>();\n const merged: BlackFridayDeal[] = [];\n for (const deal of groups.flat()) {\n const key = dealKey(deal);\n if (byUrl.has(deal.url) || byKey.has(key)) continue;\n byUrl.add(deal.url);\n byKey.add(key);\n merged.push(deal);\n }\n return merged;\n}\n\n/** The connector's deals and the browser's, one card per deal, biggest discount first. */\nexport function mergeBlackFridayDeals(...groups: BlackFridayDeal[][]): BlackFridayDeal[] {\n // A stable sort: equal discounts keep the connector's order, which lists its best first.\n return dedupeDeals(...groups).sort((a, b) => b.discountPercent - a.discountPercent);\n}\n\n/** Real lows first, then deals with no history, then ordinary prices (the connector's dealLedger ranks). */\nconst VERDICT_RANK: Record<string, number> = {\n lowest: 0,\n good: 1,\n new: 2,\n 'cheaper-elsewhere': 3,\n usual: 3,\n higher: 4,\n};\n\n/**\n * The connector's deals in the order the shopper picked, with the deals a\n * browser read placed by the same rule (on a phone there are none: pass []).\n * \"Real deals first\" keeps the connector's order and slots the extra deals in\n * by verdict - they have none yet, so among the deals with no history, biggest\n * discount first. Every other order is one sort over all of them. In every\n * order, what was searched for comes first and its accessories after (as the\n * connector orders its own): a store's search for \"macbook pro\" lists laptop\n * bags, hubs and cables too.\n */\nexport function mergeHolidayDeals(\n server: BlackFridayDeal[],\n browser: BlackFridayDeal[],\n sort: BlackFridaySort,\n query = '',\n): BlackFridayDeal[] {\n const byDiscount = (a: BlackFridayDeal, b: BlackFridayDeal) =>\n b.discountPercent - a.discountPercent || (b.votes ?? 0) - (a.votes ?? 0);\n const isAccessory = accessoryTest(query);\n const tiers = new Map<BlackFridayDeal, number>();\n const tier = (deal: BlackFridayDeal): number => {\n if (!tiers.has(deal)) tiers.set(deal, isAccessory(deal.title) ? 1 : 0);\n return tiers.get(deal)!;\n };\n const extras = dedupeDeals(browser).sort(byDiscount);\n const all = dedupeDeals(server, extras);\n if (sort === 'best') {\n // The connector's order stays as it is; each browser deal goes in among the deals of its verdict, by discount\n const rank = (deal: BlackFridayDeal) => VERDICT_RANK[deal.verdict?.kind ?? 'new'] ?? 2;\n const fromServer = new Set(server);\n const placed = all.filter((deal) => fromServer.has(deal)).sort((a, b) => tier(a) - tier(b));\n for (const extra of all.filter((deal) => !fromServer.has(deal))) {\n const at = placed.findIndex(\n (deal) =>\n tier(deal) > tier(extra) ||\n (tier(deal) === tier(extra) &&\n (rank(deal) > rank(extra) ||\n (rank(deal) === rank(extra) && deal.discountPercent < extra.discountPercent))),\n );\n placed.splice(at < 0 ? placed.length : at, 0, extra);\n }\n return placed;\n }\n const order =\n sort === 'votes'\n ? (a: BlackFridayDeal, b: BlackFridayDeal) => (b.votes ?? -1) - (a.votes ?? -1) || byDiscount(a, b)\n : sort === 'price'\n ? (a: BlackFridayDeal, b: BlackFridayDeal) => a.price - b.price || byDiscount(a, b)\n : byDiscount;\n return all.sort((a, b) => tier(a) - tier(b) || order(a, b));\n}\n\n// ─── the site directory ──────────────────────────────────────────────────────\n\n/**\n * What one site did for this search, as the directory says it. The web\n * section's `BlackFridaySiteState` without the shopper's-browser states\n * (`idle`, `queued`, `reading`, `done`): on a phone a site is either one our\n * servers read, one they could not, closed, or one only its own page shows.\n */\nexport type HolidaySiteState =\n | { kind: 'closed'; note: string }\n /** The connector read it; `count` is what it found. `reading`: our servers are still reading it. */\n | { kind: 'server'; count: number; reading?: boolean }\n /** Our servers tried it and could not read it: it opens on its own page. */\n | { kind: 'failed' }\n /** Not read for this search (web: `unpaired`): it opens on its own page. */\n | { kind: 'unpaired' };\n\n/** Each site's state for `answer` (undefined: no answer yet), by site id - the web `useBlackFridayBrowser` states, unpaired. */\nexport function holidaySiteStates(answer: BlackFridayAnswer | undefined): Record<string, HolidaySiteState> {\n const out: Record<string, HolidaySiteState> = {};\n for (const site of BLACK_FRIDAY_BROWSER_SITES) {\n if (site.closed) {\n out[site.id] = { kind: 'closed', note: site.closed };\n continue;\n }\n const label = site.label.toLowerCase();\n const report = site.server\n ? answer?.sources.find(\n (source) => source.source === site.id || (source.label ?? '').toLowerCase() === label,\n )\n : undefined;\n if (serverAnswered(site, answer)) {\n out[site.id] = {\n kind: 'server',\n count: report?.count ?? 0,\n ...(report?.status === 'reading' ? { reading: true } : {}),\n };\n continue;\n }\n // The connector could not reach it, and there is no browser to try.\n out[site.id] = report?.status === 'failed' ? { kind: 'failed' } : { kind: 'unpaired' };\n }\n return out;\n}\n\n/** What a site chip says beside the site's name (web `SiteChip`); null says nothing. */\nexport function holidaySiteStatus(state: HolidaySiteState): string | null {\n if (state.kind === 'closed') return 'closed';\n if (state.kind === 'server' && state.reading) return 'reading on Yantra…';\n if (state.kind === 'server') return state.count > 0 ? `${state.count} via Yantra` : 'checked';\n if (state.kind === 'failed') return 'could not read';\n return null;\n}\n\nexport interface HolidaySiteGroup {\n id: string;\n label: string;\n sites: BlackFridaySite[];\n}\n\n/** Every Black Friday site, grouped as the issue lists them: the deal sites, then the stores by kind. */\nexport const HOLIDAY_SITE_GROUPS: HolidaySiteGroup[] = [\n { id: 'deals', label: 'Deal sites', sites: BLACK_FRIDAY_BROWSER_SITES.filter((site) => site.kind === 'deals') },\n ...BLACK_FRIDAY_STORE_GROUPS.map((group) => ({\n id: group.id,\n label: group.label,\n sites: BLACK_FRIDAY_BROWSER_SITES.filter((site) => site.group === group.id),\n })),\n];\n\n/** How many stores the section covers (\"44 stores in all\"). */\nexport const HOLIDAY_STORE_COUNT = BLACK_FRIDAY_BROWSER_SITES.filter((site) => site.kind === 'store').length;\n\n/** How many stores our servers are still reading for this answer (\"Yantra is reading 3 stores\"). */\nexport function serversReadingCount(states: Record<string, HolidaySiteState>): number {\n return BLACK_FRIDAY_BROWSER_SITES.filter((site) => {\n const state = states[site.id];\n return state?.kind === 'server' && state.reading === true;\n }).length;\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;AAqBgB,SAAA,mBAA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GAAA,KAAA,CAAA,IAAA,MAAS,QAAY,IAAA,KAAA,CAAM,OAAY,KAAA,IAAA;AAAA,GACtD,CAAE,CAAA,MAAA;AACL"}
|
|
1
|
+
{"version":3,"file":"holidayDeals.js","sources":["../../../../src/features/shopping/services/holidayDeals.ts"],"sourcesContent":["/**\n * The holiday deals section's merging, ordering and site directory - the pure\n * half of the web surface's `services/blackFridayBrowser.ts` (0.49.0).\n *\n * On the web a paired desktop browser also reads the deal sites and stores a\n * server cannot (`readBlackFridaySite`, the deal-reader script, the\n * own-browser queue). A phone has no shopper's browser to read them in, so\n * that half is not ported: the browser's deal list is always empty here, and\n * every site the servers did not read opens on its own search page instead.\n * What is kept is verbatim: how the connector's deals are merged and ordered\n * (`mergeHolidayDeals`, `VERDICT_RANK`, accessories after the product), which\n * sites the servers answered for (`serverAnswered`), the \"still reading\"\n * re-ask (`readingRefetch`), each site's own page (`blackFridaySitePage`) and\n * the query match (`rowMatchesQuery`).\n */\nimport type { BlackFridayAnswer, BlackFridayDeal, BlackFridaySort } from './blackFriday';\nimport {\n BLACK_FRIDAY_BROWSER_SITES,\n BLACK_FRIDAY_SEASON_QUERY,\n BLACK_FRIDAY_STORE_GROUPS,\n type BlackFridaySite,\n} from './blackFridayBrowserSites';\nimport { MODEL_LINE_WORDS as MODEL_LINE } from './modelWords';\nimport { accessoryTest } from './searchRelevance';\n\n/** The page a site is read on, and the query the reader searches for (the season's deals when none was typed). */\nexport function blackFridaySitePage(site: BlackFridaySite, query: string): string {\n return site.url(query.trim() || BLACK_FRIDAY_SEASON_QUERY);\n}\n\nconst tokens = (text: string): string[] =>\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((token) => token.length > 1);\n\n/** A word without its plural s (\"tvs\" → \"tv\", \"laptops\" → \"laptop\"); \"glass\" keeps its own. */\nconst singular = (word: string): string =>\n word.length > 2 && word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word;\n\n/**\n * Whether a row answers what the shopper typed. A page that searched for the\n * query needs half its words in the title; a page that lists deals without\n * searching (or a search that fell back to the latest deals) needs all of them.\n *\n * A model-line word counts only right after the word it names, and a title that\n * names that word without it is another line: a store's search for \"macbook pro\"\n * also lists \"Win11 Pro\" laptops, \"Beats Studio Pro\" and the \"MacBook Neo\".\n */\nexport function rowMatchesQuery(title: string, query: string, searched: boolean): boolean {\n const words = tokens(query).map(singular);\n if (words.length === 0) return true;\n // Whole words: \"art\" is not in \"Smart TV\".\n const said = tokens(title).map(singular);\n const inTitle = new Set(said);\n const follows = (head: string, word: string) => said.some((token, at) => token === head && said[at + 1] === word);\n let hits = 0;\n let named = false;\n for (const [at, word] of words.entries()) {\n const head = at > 0 ? words[at - 1] : undefined;\n if (head && MODEL_LINE.has(word) && !MODEL_LINE.has(head)) {\n if (inTitle.has(head) && !follows(head, word)) return false;\n if (follows(head, word)) hits++;\n } else if (head && MODEL_LINE.has(word)) {\n // \"pro max\": the second line word follows the first\n if (follows(head, word)) hits++;\n else if (inTitle.has(head)) return false;\n } else if (inTitle.has(word)) {\n hits++;\n named = true;\n }\n }\n // A product the shopper named must be in the title, not only its line (\"pro\")\n if (!named && words.some((word, at) => !(at > 0 && MODEL_LINE.has(word)))) return false;\n return searched ? hits >= Math.ceil(words.length / 2) : hits === words.length;\n}\n\n/** Fewer deals than this from a store's season read on the servers is a thin read (web 0.49.2). */\nexport const THIN_SEASON_STORE_READ = 3;\n\n/** The connector's report on `site` in this answer, by its id or its label. */\nfunction sourceReport(site: BlackFridaySite, answer: BlackFridayAnswer | undefined) {\n const label = site.label.toLowerCase();\n return answer?.sources.find((source) => source.source === site.id || (source.label ?? '').toLowerCase() === label);\n}\n\n/**\n * Whether the connector already read `site` for this search: any site it\n * reports (found deals, found none, or is still reading it - its next answer\n * brings those), not only the sites it read before the deal recipes. A store's\n * season read that came back thin (the servers read a page its recipe was not\n * made for - Macy's: 1 deal on the servers, 30 on its own page) does not count:\n * on a phone that store is offered on its own deals page instead (web 0.49.2).\n */\n/**\n * Whether the connector reported reading `site` at all (found deals, none, or\n * still reading), thin or not. The phone's site directory says this - it has no\n * browser to read a thin store again, so \"2 via Yantra\" is the honest line.\n */\nfunction serverReported(site: BlackFridaySite, answer: BlackFridayAnswer | undefined): boolean {\n const report = sourceReport(site, answer);\n return !!report && (report.status === 'ok' || report.status === 'empty' || report.status === 'reading');\n}\n\nexport function serverAnswered(site: BlackFridaySite, answer: BlackFridayAnswer | undefined): boolean {\n const report = sourceReport(site, answer);\n if (!answer || !report) return false;\n if (\n report.status === 'ok' &&\n site.kind === 'store' &&\n !(answer.query ?? '').trim() &&\n (report.count ?? 0) < THIN_SEASON_STORE_READ\n ) {\n return false;\n }\n return report.status === 'ok' || report.status === 'empty' || report.status === 'reading';\n}\n\n/** Ask the connector again this often while it says it is still reading a site, at most READING_REFETCHES times. */\nexport const READING_REFETCH_MS = 30_000;\nexport const READING_REFETCHES = 12;\n\n/** The panel's refetch interval: READING_REFETCH_MS while the server is still reading a site, a few times; else none. */\nexport function readingRefetch(answer: BlackFridayAnswer | undefined, updates: number): number | false {\n return answer?.sources.some((source) => source.status === 'reading') && updates <= READING_REFETCHES\n ? READING_REFETCH_MS\n : false;\n}\n\nconst dealKey = (deal: BlackFridayDeal): string =>\n `${deal.title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, ' ')\n .trim()}|${deal.price}`;\n\n/** One per link and per product at a store, the first group's first: the order given is kept. */\nfunction dedupeDeals(...groups: BlackFridayDeal[][]): BlackFridayDeal[] {\n const byUrl = new Set<string>();\n const byKey = new Set<string>();\n const merged: BlackFridayDeal[] = [];\n for (const deal of groups.flat()) {\n const key = dealKey(deal);\n if (byUrl.has(deal.url) || byKey.has(key)) continue;\n byUrl.add(deal.url);\n byKey.add(key);\n merged.push(deal);\n }\n return merged;\n}\n\n/** The connector's deals and the browser's, one card per deal, biggest discount first. */\nexport function mergeBlackFridayDeals(...groups: BlackFridayDeal[][]): BlackFridayDeal[] {\n // A stable sort: equal discounts keep the connector's order, which lists its best first.\n return dedupeDeals(...groups).sort((a, b) => b.discountPercent - a.discountPercent);\n}\n\n/** Real lows first, then deals with no history, then ordinary prices (the connector's dealLedger ranks). */\nconst VERDICT_RANK: Record<string, number> = {\n lowest: 0,\n good: 1,\n new: 2,\n 'cheaper-elsewhere': 3,\n usual: 3,\n higher: 4,\n};\n\n/**\n * The connector's deals in the order the shopper picked, with the deals a\n * browser read placed by the same rule (on a phone there are none: pass []).\n * \"Real deals first\" keeps the connector's order and slots the extra deals in\n * by verdict - they have none yet, so among the deals with no history, biggest\n * discount first. Every other order is one sort over all of them. In every\n * order, what was searched for comes first and its accessories after (as the\n * connector orders its own): a store's search for \"macbook pro\" lists laptop\n * bags, hubs and cables too.\n */\nexport function mergeHolidayDeals(\n server: BlackFridayDeal[],\n browser: BlackFridayDeal[],\n sort: BlackFridaySort,\n query = '',\n): BlackFridayDeal[] {\n const byDiscount = (a: BlackFridayDeal, b: BlackFridayDeal) =>\n b.discountPercent - a.discountPercent || (b.votes ?? 0) - (a.votes ?? 0);\n const isAccessory = accessoryTest(query);\n const tiers = new Map<BlackFridayDeal, number>();\n const tier = (deal: BlackFridayDeal): number => {\n if (!tiers.has(deal)) tiers.set(deal, isAccessory(deal.title) ? 1 : 0);\n return tiers.get(deal)!;\n };\n const extras = dedupeDeals(browser).sort(byDiscount);\n const all = dedupeDeals(server, extras);\n if (sort === 'best') {\n // The connector's order stays as it is; each browser deal goes in among the deals of its verdict, by discount\n const rank = (deal: BlackFridayDeal) => VERDICT_RANK[deal.verdict?.kind ?? 'new'] ?? 2;\n const fromServer = new Set(server);\n const placed = all.filter((deal) => fromServer.has(deal)).sort((a, b) => tier(a) - tier(b));\n for (const extra of all.filter((deal) => !fromServer.has(deal))) {\n const at = placed.findIndex(\n (deal) =>\n tier(deal) > tier(extra) ||\n (tier(deal) === tier(extra) &&\n (rank(deal) > rank(extra) ||\n (rank(deal) === rank(extra) && deal.discountPercent < extra.discountPercent))),\n );\n placed.splice(at < 0 ? placed.length : at, 0, extra);\n }\n return placed;\n }\n const order =\n sort === 'votes'\n ? (a: BlackFridayDeal, b: BlackFridayDeal) => (b.votes ?? -1) - (a.votes ?? -1) || byDiscount(a, b)\n : sort === 'price'\n ? (a: BlackFridayDeal, b: BlackFridayDeal) => a.price - b.price || byDiscount(a, b)\n : byDiscount;\n return all.sort((a, b) => tier(a) - tier(b) || order(a, b));\n}\n\n// ─── the site directory ──────────────────────────────────────────────────────\n\n/**\n * What one site did for this search, as the directory says it. The web\n * section's `BlackFridaySiteState` without the shopper's-browser states\n * (`idle`, `queued`, `reading`, `done`): on a phone a site is either one our\n * servers read, one they could not, closed, or one only its own page shows.\n */\nexport type HolidaySiteState =\n | { kind: 'closed'; note: string }\n /** The connector read it; `count` is what it found. `reading`: our servers are still reading it. */\n | { kind: 'server'; count: number; reading?: boolean }\n /** Our servers tried it and could not read it: it opens on its own page. */\n | { kind: 'failed' }\n /** Not read for this search (web: `unpaired`): it opens on its own page. */\n | { kind: 'unpaired' };\n\n/** Each site's state for `answer` (undefined: no answer yet), by site id - the web `useBlackFridayBrowser` states, unpaired. */\nexport function holidaySiteStates(answer: BlackFridayAnswer | undefined): Record<string, HolidaySiteState> {\n const out: Record<string, HolidaySiteState> = {};\n for (const site of BLACK_FRIDAY_BROWSER_SITES) {\n if (site.closed) {\n out[site.id] = { kind: 'closed', note: site.closed };\n continue;\n }\n const label = site.label.toLowerCase();\n const report = site.server\n ? answer?.sources.find(\n (source) => source.source === site.id || (source.label ?? '').toLowerCase() === label,\n )\n : undefined;\n if (serverReported(site, answer)) {\n out[site.id] = {\n kind: 'server',\n count: report?.count ?? 0,\n ...(report?.status === 'reading' ? { reading: true } : {}),\n };\n continue;\n }\n // The connector could not reach it, and there is no browser to try.\n out[site.id] = report?.status === 'failed' ? { kind: 'failed' } : { kind: 'unpaired' };\n }\n return out;\n}\n\n/** What a site chip says beside the site's name (web `SiteChip`); null says nothing. */\nexport function holidaySiteStatus(state: HolidaySiteState): string | null {\n if (state.kind === 'closed') return 'closed';\n if (state.kind === 'server' && state.reading) return 'reading on Yantra…';\n if (state.kind === 'server') return state.count > 0 ? `${state.count} via Yantra` : 'checked';\n if (state.kind === 'failed') return 'could not read';\n return null;\n}\n\nexport interface HolidaySiteGroup {\n id: string;\n label: string;\n sites: BlackFridaySite[];\n}\n\n/** Every Black Friday site, grouped as the issue lists them: the deal sites, then the stores by kind. */\nexport const HOLIDAY_SITE_GROUPS: HolidaySiteGroup[] = [\n { id: 'deals', label: 'Deal sites', sites: BLACK_FRIDAY_BROWSER_SITES.filter((site) => site.kind === 'deals') },\n ...BLACK_FRIDAY_STORE_GROUPS.map((group) => ({\n id: group.id,\n label: group.label,\n sites: BLACK_FRIDAY_BROWSER_SITES.filter((site) => site.group === group.id),\n })),\n];\n\n/** How many stores the section covers (\"44 stores in all\"). */\nexport const HOLIDAY_STORE_COUNT = BLACK_FRIDAY_BROWSER_SITES.filter((site) => site.kind === 'store').length;\n\n/** How many stores our servers are still reading for this answer (\"Yantra is reading 3 stores\"). */\nexport function serversReadingCount(states: Record<string, HolidaySiteState>): number {\n return BLACK_FRIDAY_BROWSER_SITES.filter((site) => {\n const state = states[site.id];\n return state?.kind === 'server' && state.reading === true;\n }).length;\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;AAqBgB,SAAA,mBAAA,CAAoB,MAAuB,KAAuB,EAAA;AAChF,EAAA,OAAO,IAAK,CAAA,GAAA,CAAI,KAAM,CAAA,IAAA,MAAU,yBAAyB,CAAA;AAC3D;AA8CA,SAAS,YAAA,CAAa,MAAuB,MAAuC,EAAA;AAClF,EAAM,MAAA,KAAA,GAAQ,IAAK,CAAA,KAAA,CAAM,WAAY,EAAA;AACrC,EAAO,OAAA,MAAA,IAAA,IAAA,GAAA,MAAA,GAAA,MAAA,CAAQ,OAAQ,CAAA,IAAA,CAAK,CAAO,MAAA,KAAA;AAvErC,IAAA,IAAA,EAAA;AAuEwC,IAAO,OAAA,MAAA,CAAA,MAAA,KAAW,KAAK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AAQ,CAAI,GAAA,CAAA,EAAG,KAAM,CAAA,KAAK,CAAgB,WAAA,CAAA,GAAA,SAAA;AACpF,EAAI,IAAA,KAAA,CAAM,IAAS,KAAA,QAAA,EAAiB,OAAA,gBAAA;AACpC,EAAO,OAAA,IAAA;AACT;AAQO,MAAM,sBAA0C,CAAC;AAAA,EACtD,EAAI,EAAA,OAAA;AAAA,EACJ,KAAO,EAAA,YAAA;AAAA,EACP,OAAO,0BAA2B,CAAA,MAAA,CAAO,CAAQ,IAAA,KAAA,IAAA,CAAK,SAAS,OAAO;AACxE,CAAG,EAAA,GAAG,yBAA0B,CAAA,GAAA,CAAI,CAAU,KAAA,MAAA;AAAA,EAC5C,IAAI,KAAM,CAAA,EAAA;AAAA,EACV,OAAO,KAAM,CAAA,KAAA;AAAA,EACb,OAAO,0BAA2B,CAAA,MAAA,CAAO,UAAQ,IAAK,CAAA,KAAA,KAAU,MAAM,EAAE;AAC1E,CAAA,CAAE,CAAC;AAGI,MAAM,sBAAsB,0BAA2B,CAAA,MAAA,CAAO,UAAQ,IAAK,CAAA,IAAA,KAAS,OAAO,CAAE,CAAA;AAG7F,SAAS,oBAAoB,MAAkD,EAAA;AACpF,EAAO,OAAA,0BAAA,CAA2B,OAAO,CAAQ,IAAA,KAAA;AAC/C,IAAM,MAAA,KAAA,GAAQ,MAAO,CAAA,IAAA,CAAK,EAAE,CAAA;AAC5B,IAAA,OAAA,CAAO,KAAO,IAAA,IAAA,GAAA,MAAA,GAAA,KAAA,CAAA,IAAA,MAAS,QAAY,IAAA,KAAA,CAAM,OAAY,KAAA,IAAA;AAAA,GACtD,CAAE,CAAA,MAAA;AACL"}
|
|
@@ -64,7 +64,7 @@ async function verifyDiscounts(candidates, limit = VERIFY_LIMIT) {
|
|
|
64
64
|
});
|
|
65
65
|
return [...proven, ...checked.filter((p) => p !== null)];
|
|
66
66
|
}
|
|
67
|
-
async function searchLiveRetailerDeals(request) {
|
|
67
|
+
async function searchLiveRetailerDeals(request, options = {}) {
|
|
68
68
|
var _a, _b;
|
|
69
69
|
const term = (_a = request.query) == null ? void 0 : _a.trim();
|
|
70
70
|
const seeds = term ? [term] : seedQueries(request.departmentId, LIVE_SEED_LIMIT);
|
|
@@ -72,30 +72,72 @@ async function searchLiveRetailerDeals(request) {
|
|
|
72
72
|
const preset = departmentId ? DEPARTMENT_SEARCH_PRESETS[departmentId] : void 0;
|
|
73
73
|
const groups = [];
|
|
74
74
|
const errors = [];
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
75
|
+
let stopped = false;
|
|
76
|
+
const proven = [];
|
|
77
|
+
let reports = Promise.resolve();
|
|
78
|
+
const reportLane = (rows) => {
|
|
79
|
+
if (!options.onPartial || rows.length === 0) return;
|
|
80
|
+
reports = reports.then(async () => {
|
|
81
|
+
var _a2;
|
|
82
|
+
if (stopped) return;
|
|
83
|
+
proven.push(...await verifyDiscounts(rows));
|
|
84
|
+
if (stopped) return;
|
|
85
|
+
const products2 = applyDealsQuery(mergeShoppingProductSources([proven]), request);
|
|
86
|
+
if (products2.length > 0) (_a2 = options.onPartial) == null ? void 0 : _a2.call(options, {
|
|
87
|
+
products: products2,
|
|
88
|
+
source: "offers"
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
const sweep = (async () => {
|
|
93
|
+
for (const seed of seeds) {
|
|
94
|
+
if (stopped) return;
|
|
95
|
+
const query = saleQuery(seed);
|
|
96
|
+
const [amazon, rest] = await Promise.allSettled([searchAmazonProducts(__spreadValues({
|
|
97
|
+
query,
|
|
98
|
+
departmentId,
|
|
99
|
+
maxResults: 24
|
|
100
|
+
}, preset ? {
|
|
101
|
+
category: preset.category
|
|
102
|
+
} : {})).then((result) => {
|
|
103
|
+
const rows = result.products.map((p) => __spreadProps(__spreadValues({}, p), {
|
|
104
|
+
source: "amazon"
|
|
105
|
+
}));
|
|
106
|
+
if (!stopped) {
|
|
107
|
+
groups.push(rows);
|
|
108
|
+
reportLane(rows);
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}), searchShoppingProductsRest(__spreadValues({
|
|
112
|
+
query,
|
|
113
|
+
departmentId,
|
|
114
|
+
maxResults: 24
|
|
115
|
+
}, preset ? {
|
|
116
|
+
category: preset.category
|
|
117
|
+
} : {}), {
|
|
118
|
+
// Each store's list the moment it lands, not after the ~85 s research.
|
|
119
|
+
onLane: (rows) => {
|
|
120
|
+
if (stopped) return;
|
|
121
|
+
groups.push(rows);
|
|
122
|
+
reportLane(rows);
|
|
123
|
+
}
|
|
124
|
+
})]);
|
|
125
|
+
if (stopped) return;
|
|
126
|
+
if (amazon.status === "rejected") errors.push(amazon.reason instanceof Error ? amazon.reason.message : "Amazon lane failed");
|
|
127
|
+
if (rest.status === "fulfilled") {
|
|
128
|
+
groups.push(rest.value.products);
|
|
129
|
+
if (rest.value.error) errors.push(rest.value.error);
|
|
130
|
+
} else errors.push(rest.reason instanceof Error ? rest.reason.message : "Retailer lane failed");
|
|
131
|
+
}
|
|
132
|
+
})();
|
|
133
|
+
if (options.deadlineMs && options.deadlineMs > 0) {
|
|
134
|
+
let timer;
|
|
135
|
+
await Promise.race([sweep, new Promise((resolve) => timer = setTimeout(resolve, options.deadlineMs))]);
|
|
136
|
+
if (timer) clearTimeout(timer);
|
|
137
|
+
} else {
|
|
138
|
+
await sweep;
|
|
98
139
|
}
|
|
140
|
+
stopped = true;
|
|
99
141
|
const candidates = mergeShoppingProductSources(groups);
|
|
100
142
|
const deals = await verifyDiscounts(candidates);
|
|
101
143
|
const products = applyDealsQuery(deals, request);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"liveDealLanes.js","sources":["../../../../src/features/shopping/services/liveDealLanes.ts"],"sourcesContent":["/**\n * The LIVE product-deal lanes — deals found by searching, with the discount\n * proven rather than asserted.\n *\n * A SERP row is a name and a price. It cannot be a deal on its own: \"deal\"\n * is a claim about TWO prices, and a search excerpt carries one. So these lanes\n * gather candidates from the live search (Amazon, Walmart, eBay, Target,\n * Shopify, Google Shopping, Yantra research) and then READ THE PRODUCT PAGE for\n * the rows they want to show: the page-check lane (`checkProductLink`) returns\n * the struck-through list price the page itself states, and only a row whose\n * page says \"was $X, now $Y\" with X > Y stays. The percent is recomputed from\n * those two numbers (`reconcilePricing`), never trusted from upstream.\n *\n * Native port of web `services/liveDealLanes.ts` (0.37.0) without web's\n * paired-browser lane (`searchBrowserDeals`): it reads sale pages in the\n * shopper's desktop Chrome through the Yantra extension, which a phone has not.\n *\n * Deliberately budgeted: the retailer lane sweeps at most two seeds on the\n * unscoped board and verifies at most `VERIFY_LIMIT` pages. The rest of the board (offers,\n * catalog, coupons) has already painted by the time these land — they add\n * breadth, they do not gate the first paint.\n */\nimport type { Product } from '../catalog';\nimport { searchAmazonProducts } from './amazonProductSearch';\nimport { applyDealsQuery, seedQueries, type DealsRequest, type DealsResult } from './dealsSearch';\nimport {\n DEPARTMENT_SEARCH_PRESETS,\n mergeShoppingProductSources,\n searchShoppingProductsRest,\n} from './shoppingProductSearch';\nimport { reconcilePricing } from './pricing';\nimport { applyPageCheck, checkProductLink } from './verifyProducts';\n\n/** Seeds the retailer lane sweeps on the unscoped board. Two: each is a full fan-out. */\nexport const LIVE_SEED_LIMIT = 2;\n/** Product pages read per load to prove a discount. */\nexport const VERIFY_LIMIT = 16;\nconst VERIFY_CONCURRENCY = 6;\n\n/**\n * The words that pull a retailer's search toward its marked-down rows.\n *\n * A search-term tactic, not a vocabulary table: every retailer's own search\n * box ranks sale/clearance listings up for these, and the page check below is\n * what decides whether a row is a deal — this only improves the candidate pool.\n */\nfunction saleQuery(seed: string): string {\n return `${seed} sale`;\n}\n\n/** A row already carries a proven markdown (list price above sale price). */\nfunction hasDiscount(product: Product): boolean {\n return product.price > 0 && typeof product.originalPrice === 'number' && product.originalPrice > product.price;\n}\n\nasync function mapPaced<T, R>(items: T[], limit: number, work: (item: T) => Promise<R>): Promise<R[]> {\n const out: R[] = new Array(items.length);\n let next = 0;\n const worker = async () => {\n for (;;) {\n const i = next++;\n if (i >= items.length) return;\n out[i] = await work(items[i]);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return out;\n}\n\n/**\n * Prove or drop: read each candidate's product page and keep only the rows\n * whose page states a list price above the current one. Rows that already\n * carry a proven discount (a retailer lane that returned a list price) do not\n * need the page to prove the discount, but they are still opened: a delisted\n * or sold-out item is never shown, whatever discount its listing claimed. An\n * unreadable page keeps a proven row and drops an unproven one. Never throws.\n */\nexport async function verifyDiscounts(candidates: Product[], limit = VERIFY_LIMIT): Promise<Product[]> {\n const provenChecked = await Promise.all(\n candidates.filter(hasDiscount).map(async (product) => {\n if (!product.url) return reconcilePricing(product);\n try {\n const next = applyPageCheck(product, await checkProductLink(product.url));\n return next && next.inStock !== false && hasDiscount(next) ? reconcilePricing(next) : null;\n } catch {\n return reconcilePricing(product);\n }\n }),\n );\n const proven = provenChecked.filter((p): p is Product => p !== null);\n const toCheck = candidates.filter((p) => !hasDiscount(p) && p.url).slice(0, limit);\n const checked = await mapPaced(toCheck, VERIFY_CONCURRENCY, async (product) => {\n try {\n const check = await checkProductLink(product.url as string);\n const next = applyPageCheck(product, check);\n return next && next.inStock !== false && hasDiscount(next) ? reconcilePricing(next) : null;\n } catch {\n return null;\n }\n });\n return [...proven, ...checked.filter((p): p is Product => p !== null)];\n}\n\n/**\n * Live retailer + Yantra-research deals for the board.\n *\n * Each seed runs the Amazon lane and the cross-retailer/research lane together,\n * seeds sequentially (the research lane is Parallel-backed and contends with\n * itself). Candidates are merged, verified off their pages, then ranked under\n * the chips exactly as the other product lanes are.\n */\nexport async function searchLiveRetailerDeals(request: DealsRequest): Promise<DealsResult> {\n const term = request.query?.trim();\n const seeds = term ? [term] : seedQueries(request.departmentId, LIVE_SEED_LIMIT);\n const departmentId = request.departmentId ?? undefined;\n const preset = departmentId ? DEPARTMENT_SEARCH_PRESETS[departmentId] : undefined;\n\n const groups: Product[][] = [];\n const errors: string[] = [];\n for (const seed of seeds) {\n const query = saleQuery(seed);\n const [amazon, rest] = await Promise.allSettled([\n searchAmazonProducts({\n query,\n departmentId,\n maxResults: 24,\n ...(preset ? { category: preset.category } : {}),\n }),\n searchShoppingProductsRest({\n query,\n departmentId,\n maxResults: 24,\n ...(preset ? { category: preset.category } : {}),\n }),\n ]);\n if (amazon.status === 'fulfilled')\n groups.push(amazon.value.products.map((p) => ({ ...p, source: 'amazon' as const })));\n else errors.push(amazon.reason instanceof Error ? amazon.reason.message : 'Amazon lane failed');\n if (rest.status === 'fulfilled') {\n groups.push(rest.value.products);\n if (rest.value.error) errors.push(rest.value.error);\n } else errors.push(rest.reason instanceof Error ? rest.reason.message : 'Retailer lane failed');\n }\n\n const candidates = mergeShoppingProductSources(groups);\n const deals = await verifyDiscounts(candidates);\n const products = applyDealsQuery(deals, request);\n const allFailed = groups.length === 0 && errors.length > 0;\n return {\n products,\n source: 'offers',\n ...(allFailed ? { error: errors[0] } : {}),\n ...(products.length > 0\n ? {\n hint: `Live retailer listings — every discount read off the product page (${candidates.length} candidates checked).`,\n }\n : {}),\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA8BO,MAAM,eAAkB,GAAA;AAExB,MAAM,YAAe,GAAA;AAC5B,MAAM,kBAAqB,GAAA,CAAA;AAS3B,SAAS,UAAU,IAAsB,EAAA;AACvC,EAAA,OAAO,GAAG,IAAI,CAAA,KAAA,CAAA;AAChB;AAGA,SAAS,YAAY,OAA2B,EAAA;AAC9C,EAAO,OAAA,OAAA,CAAQ,QAAQ,CAAK,IAAA,OAAO,QAAQ,aAAkB,KAAA,QAAA,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CAAA;AAC/B,MAAA,IAAI,KAAK,KAAM,CAAA,KAAA,SAAc,IAAK,CAAA,IAAA,CAAK,MAAM,KAAK,CAAA;AAAA,KACpD,aAAc,IAAK,CAAA,IAAA,CAAK,kBAAkB,KAAQ,GAAA,IAAA,CAAK,MAAO,CAAA,OAAA,GAAU,sBAAsB,CAAA;AAAA;AAEhG,EAAM,MAAA,UAAA,GAAa,4BAA4B,MAAM,CAAA;AACrD,EAAM,MAAA,KAAA,GAAQ,MAAM,eAAA,CAAgB,UAAU,CAAA;AAC9C,EAAM,MAAA,QAAA,GAAW,eAAgB,CAAA,KAAA,EAAO,OAAO,CAAA;AAC/C,EAAA,MAAM,SAAY,GAAA,MAAA,CAAO,MAAW,KAAA,CAAA,IAAK,OAAO,MAAS,GAAA,CAAA;AACzD,EAAO,OAAA,cAAA,CAAA,cAAA,CAAA;AAAA,IACL,QAAA;AAAA,IACA,MAAQ,EAAA;AAAA,GAAA,EACJ,SAAY,GAAA;AAAA,IACd,KAAA,EAAO,OAAO,CAAC;AAAA,GACb,GAAA,EACA,CAAA,EAAA,QAAA,CAAS,SAAS,CAAI,GAAA;AAAA,IACxB,IAAA,EAAM,CAAsE,wEAAA,EAAA,UAAA,CAAW,MAAM,CAAA,qBAAA;AAAA,MAC3F,EAAC,CAAA;AAET"}
|
|
1
|
+
{"version":3,"file":"liveDealLanes.js","sources":["../../../../src/features/shopping/services/liveDealLanes.ts"],"sourcesContent":["/**\n * The LIVE product-deal lanes — deals found by searching, with the discount\n * proven rather than asserted.\n *\n * A SERP row is a name and a price. It cannot be a deal on its own: \"deal\"\n * is a claim about TWO prices, and a search excerpt carries one. So these lanes\n * gather candidates from the live search (Amazon, Walmart, eBay, Target,\n * Shopify, Google Shopping, Yantra research) and then READ THE PRODUCT PAGE for\n * the rows they want to show: the page-check lane (`checkProductLink`) returns\n * the struck-through list price the page itself states, and only a row whose\n * page says \"was $X, now $Y\" with X > Y stays. The percent is recomputed from\n * those two numbers (`reconcilePricing`), never trusted from upstream.\n *\n * Native port of web `services/liveDealLanes.ts` (0.37.0) without web's\n * paired-browser lane (`searchBrowserDeals`): it reads sale pages in the\n * shopper's desktop Chrome through the Yantra extension, which a phone has not.\n *\n * Deliberately budgeted: the retailer lane sweeps at most two seeds on the\n * unscoped board and verifies at most `VERIFY_LIMIT` pages. The rest of the board (offers,\n * catalog, coupons) has already painted by the time these land — they add\n * breadth, they do not gate the first paint.\n */\nimport type { Product } from '../catalog';\nimport { searchAmazonProducts } from './amazonProductSearch';\nimport { applyDealsQuery, seedQueries, type DealsRequest, type DealsResult } from './dealsSearch';\nimport {\n DEPARTMENT_SEARCH_PRESETS,\n mergeShoppingProductSources,\n searchShoppingProductsRest,\n} from './shoppingProductSearch';\nimport { reconcilePricing } from './pricing';\nimport { applyPageCheck, checkProductLink } from './verifyProducts';\n\n/** Seeds the retailer lane sweeps on the unscoped board. Two: each is a full fan-out. */\nexport const LIVE_SEED_LIMIT = 2;\n/** Product pages read per load to prove a discount. */\nexport const VERIFY_LIMIT = 16;\nconst VERIFY_CONCURRENCY = 6;\n\n/**\n * The words that pull a retailer's search toward its marked-down rows.\n *\n * A search-term tactic, not a vocabulary table: every retailer's own search\n * box ranks sale/clearance listings up for these, and the page check below is\n * what decides whether a row is a deal — this only improves the candidate pool.\n */\nfunction saleQuery(seed: string): string {\n return `${seed} sale`;\n}\n\n/** A row already carries a proven markdown (list price above sale price). */\nfunction hasDiscount(product: Product): boolean {\n return product.price > 0 && typeof product.originalPrice === 'number' && product.originalPrice > product.price;\n}\n\nasync function mapPaced<T, R>(items: T[], limit: number, work: (item: T) => Promise<R>): Promise<R[]> {\n const out: R[] = new Array(items.length);\n let next = 0;\n const worker = async () => {\n for (;;) {\n const i = next++;\n if (i >= items.length) return;\n out[i] = await work(items[i]);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return out;\n}\n\n/**\n * Prove or drop: read each candidate's product page and keep only the rows\n * whose page states a list price above the current one. Rows that already\n * carry a proven discount (a retailer lane that returned a list price) do not\n * need the page to prove the discount, but they are still opened: a delisted\n * or sold-out item is never shown, whatever discount its listing claimed. An\n * unreadable page keeps a proven row and drops an unproven one. Never throws.\n */\nexport async function verifyDiscounts(candidates: Product[], limit = VERIFY_LIMIT): Promise<Product[]> {\n const provenChecked = await Promise.all(\n candidates.filter(hasDiscount).map(async (product) => {\n if (!product.url) return reconcilePricing(product);\n try {\n const next = applyPageCheck(product, await checkProductLink(product.url));\n return next && next.inStock !== false && hasDiscount(next) ? reconcilePricing(next) : null;\n } catch {\n return reconcilePricing(product);\n }\n }),\n );\n const proven = provenChecked.filter((p): p is Product => p !== null);\n const toCheck = candidates.filter((p) => !hasDiscount(p) && p.url).slice(0, limit);\n const checked = await mapPaced(toCheck, VERIFY_CONCURRENCY, async (product) => {\n try {\n const check = await checkProductLink(product.url as string);\n const next = applyPageCheck(product, check);\n return next && next.inStock !== false && hasDiscount(next) ? reconcilePricing(next) : null;\n } catch {\n return null;\n }\n });\n return [...proven, ...checked.filter((p): p is Product => p !== null)];\n}\n\n/**\n * Live retailer + Yantra-research deals for the board.\n *\n * Each seed runs the Amazon lane and the cross-retailer/research lane together,\n * seeds sequentially (the research lane is Parallel-backed and contends with\n * itself). Candidates are merged, verified off their pages, then ranked under\n * the chips exactly as the other product lanes are.\n */\nexport interface LiveDealsOptions {\n /**\n * Native: stop waiting for slow stores this long after the start and check the\n * deals that already landed. The lane asks every store one seed at a time and\n * rarely finishes inside the board's budget; without a deadline, the stores\n * that DID answer (Amazon in seconds) were thrown away with the slow ones.\n */\n deadlineMs?: number;\n /** Native: the deals proven so far, each time another store's list is checked. */\n onPartial?: (result: DealsResult) => void;\n}\n\nexport async function searchLiveRetailerDeals(\n request: DealsRequest,\n options: LiveDealsOptions = {},\n): Promise<DealsResult> {\n const term = request.query?.trim();\n const seeds = term ? [term] : seedQueries(request.departmentId, LIVE_SEED_LIMIT);\n const departmentId = request.departmentId ?? undefined;\n const preset = departmentId ? DEPARTMENT_SEARCH_PRESETS[departmentId] : undefined;\n\n const groups: Product[][] = [];\n const errors: string[] = [];\n let stopped = false;\n\n // Proven deals so far, reported as each store's list is checked (native).\n const proven: Product[] = [];\n let reports = Promise.resolve();\n const reportLane = (rows: Product[]) => {\n if (!options.onPartial || rows.length === 0) return;\n reports = reports.then(async () => {\n if (stopped) return;\n proven.push(...(await verifyDiscounts(rows)));\n if (stopped) return;\n const products = applyDealsQuery(mergeShoppingProductSources([proven]), request);\n if (products.length > 0) options.onPartial?.({ products, source: 'offers' });\n });\n };\n\n const sweep = (async () => {\n for (const seed of seeds) {\n if (stopped) return;\n const query = saleQuery(seed);\n const [amazon, rest] = await Promise.allSettled([\n searchAmazonProducts({\n query,\n departmentId,\n maxResults: 24,\n ...(preset ? { category: preset.category } : {}),\n }).then((result) => {\n const rows = result.products.map((p) => ({ ...p, source: 'amazon' as const }));\n if (!stopped) {\n groups.push(rows);\n reportLane(rows);\n }\n return result;\n }),\n searchShoppingProductsRest(\n {\n query,\n departmentId,\n maxResults: 24,\n ...(preset ? { category: preset.category } : {}),\n },\n {\n // Each store's list the moment it lands, not after the ~85 s research.\n onLane: (rows) => {\n if (stopped) return;\n groups.push(rows);\n reportLane(rows);\n },\n },\n ),\n ]);\n if (stopped) return;\n if (amazon.status === 'rejected')\n errors.push(amazon.reason instanceof Error ? amazon.reason.message : 'Amazon lane failed');\n if (rest.status === 'fulfilled') {\n // The final list adds the research rows; the stores already landed through onLane.\n groups.push(rest.value.products);\n if (rest.value.error) errors.push(rest.value.error);\n } else errors.push(rest.reason instanceof Error ? rest.reason.message : 'Retailer lane failed');\n }\n })();\n\n if (options.deadlineMs && options.deadlineMs > 0) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([sweep, new Promise<void>((resolve) => (timer = setTimeout(resolve, options.deadlineMs)))]);\n if (timer) clearTimeout(timer);\n } else {\n await sweep;\n }\n stopped = true;\n\n const candidates = mergeShoppingProductSources(groups);\n const deals = await verifyDiscounts(candidates);\n const products = applyDealsQuery(deals, request);\n const allFailed = groups.length === 0 && errors.length > 0;\n return {\n products,\n source: 'offers',\n ...(allFailed ? { error: errors[0] } : {}),\n ...(products.length > 0\n ? {\n hint: `Live retailer listings — every discount read off the product page (${candidates.length} candidates checked).`,\n }\n : {}),\n };\n}\n"],"names":["_a","products"],"mappings":";;;;;;;;;;;;;;;;;;;AA8BO,MAAM,eAAkB,GAAA;AAExB,MAAM,YAAe,GAAA;AAC5B,MAAM,kBAAqB,GAAA,CAAA;AAS3B,SAAS,UAAU,IAAsB,EAAA;AACvC,EAAA,OAAO,GAAG,IAAI,CAAA,KAAA,CAAA;AAChB;AAGA,SAAS,YAAY,OAA2B,EAAA;AAC9C,EAAO,OAAA,OAAA,CAAQ,QAAQ,CAAK,IAAA,OAAO,QAAQ,aAAkB,KAAA,QAAA,IAAY,OAAQ,CAAA,aAAA,GAAgB,OAAQ,CAAA,KAAA;AAC3G;AACA,eAAe,QAAA,CAAe,KAAY,EAAA,KAAA,EAAe,IAA6C,EAAA;AACpG,EAAA,MAAM,GAAW,GAAA,IAAI,KAAM,CAAA,KAAA,CAAM,MAAM,CAAA;AACvC,EAAA,IAAI,IAAO,GAAA,CAAA;AACX,EAAA,MAAM,SAAS,YAAY;AACzB,IAAS,WAAA;AACP,MAAA,MAAM,CAAI,GAAA,IAAA,EAAA;AACV,MAAI,IAAA,CAAA,IAAK,MAAM,MAAQ,EAAA;AACvB,MAAA,GAAA,CAAI,CAAC,CAAI,GAAA,MAAM,IAAK,CAAA,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA;AAC9B,GACF;AACA,EAAM,MAAA,OAAA,CAAQ,GAAI,CAAA,KAAA,CAAM,IAAK,CAAA;AAAA,IAC3B,MAAQ,EAAA,IAAA,CAAK,GAAI,CAAA,KAAA,EAAO,MAAM,MAAM;AAAA,GACtC,EAAG,MAAM,CAAC,CAAA;AACV,EAAO,OAAA,GAAA;AACT;AAUsB,eAAA,eAAA,CAAgB,UAAuB,EAAA,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rD,EAAM,MAAA,KAAA,GAAQ,MAAM,eAAA,CAAgB,UAAU,CAAA;AAC9C,EAAM,MAAA,QAAA,GAAW,eAAgB,CAAA,KAAA,EAAO,OAAO,CAAA;AAC/C,EAAA,MAAM,SAAY,GAAA,MAAA,CAAO,MAAW,KAAA,CAAA,IAAK,OAAO,MAAS,GAAA,CAAA;AACzD,EAAO,OAAA,cAAA,CAAA,cAAA,CAAA;AAAA,IACL,QAAA;AAAA,IACA,MAAQ,EAAA;AAAA,GAAA,EACJ,SAAY,GAAA;AAAA,IACd,KAAA,EAAO,OAAO,CAAC;AAAA,GACb,GAAA,EACA,CAAA,EAAA,QAAA,CAAS,SAAS,CAAI,GAAA;AAAA,IACxB,IAAA,EAAM,CAAsE,wEAAA,EAAA,UAAA,CAAW,MAAM,CAAA,qBAAA;AAAA,MAC3F,EAAC,CAAA;AAET"}
|
|
@@ -1,14 +1,63 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import {createRemoteConnectorExec}from'../canvas/videoEditor/remoteMediaClient.js';import {unwrapConnectorEnvelope}from'./shoppingRuntime.js';const SHOPPING_EXEC_TIMEOUT_MS = 18e4;
|
|
2
|
+
const MAX_CONCURRENT_EXECS = 8;
|
|
3
|
+
const CAPACITY_RETRY_DELAYS_MS = [1500, 3500, 7e3];
|
|
4
|
+
const BUSY_MESSAGE = "Yantra is busy with other searches right now. Try again in a moment.";
|
|
5
|
+
const CAPACITY_REFUSAL = /execution capacity exhausted|too many concurrent executions|queue full|\bHTTP 429\b|"code"\s*:\s*429/i;
|
|
6
|
+
function isCapacityRefusal(message) {
|
|
7
|
+
return !!message && CAPACITY_REFUSAL.test(message);
|
|
8
|
+
}
|
|
9
|
+
let active = 0;
|
|
10
|
+
const waiting = [];
|
|
11
|
+
function acquire() {
|
|
12
|
+
if (active < MAX_CONCURRENT_EXECS) {
|
|
13
|
+
active += 1;
|
|
14
|
+
return Promise.resolve();
|
|
15
|
+
}
|
|
16
|
+
return new Promise((resolve) => waiting.push(() => {
|
|
17
|
+
active += 1;
|
|
18
|
+
resolve();
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
function release() {
|
|
22
|
+
var _a;
|
|
23
|
+
active -= 1;
|
|
24
|
+
(_a = waiting.shift()) == null ? void 0 : _a();
|
|
25
|
+
}
|
|
26
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
27
|
+
function pacedShoppingExec(run, delays = CAPACITY_RETRY_DELAYS_MS) {
|
|
3
28
|
return async (connector, action, params) => {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
success
|
|
10
|
-
|
|
11
|
-
|
|
29
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
30
|
+
await acquire();
|
|
31
|
+
let refused = false;
|
|
32
|
+
try {
|
|
33
|
+
const result = unwrapConnectorEnvelope(await run(connector, action, params));
|
|
34
|
+
if (result.success || !isCapacityRefusal(result.error)) return result;
|
|
35
|
+
refused = true;
|
|
36
|
+
if (attempt >= delays.length) return {
|
|
37
|
+
success: false,
|
|
38
|
+
error: BUSY_MESSAGE
|
|
39
|
+
};
|
|
40
|
+
} catch (err) {
|
|
41
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
42
|
+
if (!isCapacityRefusal(message)) return {
|
|
43
|
+
success: false,
|
|
44
|
+
error: message
|
|
45
|
+
};
|
|
46
|
+
refused = true;
|
|
47
|
+
if (attempt >= delays.length) return {
|
|
48
|
+
success: false,
|
|
49
|
+
error: BUSY_MESSAGE
|
|
50
|
+
};
|
|
51
|
+
} finally {
|
|
52
|
+
release();
|
|
53
|
+
}
|
|
54
|
+
if (refused) await sleep(delays[attempt] + Math.floor(Math.random() * 400));
|
|
12
55
|
}
|
|
13
56
|
};
|
|
14
|
-
}
|
|
57
|
+
}
|
|
58
|
+
function createShoppingExec(token, indexUrl) {
|
|
59
|
+
const run = createRemoteConnectorExec(token, indexUrl);
|
|
60
|
+
return pacedShoppingExec((connector, action, params) => run(connector, action, params, {
|
|
61
|
+
timeoutMs: SHOPPING_EXEC_TIMEOUT_MS
|
|
62
|
+
}));
|
|
63
|
+
}export{BUSY_MESSAGE,CAPACITY_RETRY_DELAYS_MS,MAX_CONCURRENT_EXECS,SHOPPING_EXEC_TIMEOUT_MS,createShoppingExec,isCapacityRefusal,pacedShoppingExec};//# sourceMappingURL=shoppingExec.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shoppingExec.js","sources":["../../../src/features/shopping/shoppingExec.ts"],"sourcesContent":["/**\n * Connector transport for native shopping: the same cdecli `exec/stream`\n * lane canvas editors use. Token + index URL come from the host session;\n * nothing host-specific (Apollo, env) ships in the remote.\n */\n\nimport {
|
|
1
|
+
{"version":3,"file":"shoppingExec.js","sources":["../../../src/features/shopping/shoppingExec.ts"],"sourcesContent":["/**\n * Connector transport for native shopping: the same cdecli `exec/stream`\n * lane canvas editors use. Token + index URL come from the host session;\n * nothing host-specific (Apollo, env) ships in the remote.\n *\n * Native-only pacing. The account's executor runs a few connector executions\n * at a time and refuses the rest with HTTP 429 (\"execution capacity exhausted:\n * too many concurrent executions; queue full\"). A phone opening Deals fans out\n * every deal lane, the coupon feeds and the department rails at once, so the\n * refusals reached the screen as raw JSON. Every shopping call now:\n * - waits for one of {@link MAX_CONCURRENT_EXECS} slots, shared by all callers;\n * - is retried after a short back-off when the executor refused it (a refused\n * call never ran, so a retry cannot double anything);\n * - fails with words a shopper can read when it is still refused.\n */\n\nimport { createRemoteConnectorExec } from '../canvas/videoEditor/remoteMediaClient';\nimport type { ConnectorExec } from './shoppingRuntime';\nimport { unwrapConnectorEnvelope } from './shoppingRuntime';\n\n/**\n * One shopping action's time limit - web standalone's EXEC_TIMEOUT_MS. The shared\n * transport's default is the video editor's 15 minutes; with that, one stalled\n * store call held a slot (and the one-at-a-time catalog lane behind it) for a\n * quarter of an hour and every rail, deal board and the Watchlist spun on.\n */\nexport const SHOPPING_EXEC_TIMEOUT_MS = 180_000;\n\n/**\n * Shopping connector executions in flight at once, across the whole app. Not a\n * tight cap: the deal board's sources keep their time budgets from the moment\n * they ask, so a call left waiting here spends its budget in the queue (at 4,\n * a coupon call that runs in seconds timed out at 30 s behind the store sweeps\n * and every rail came back empty). The executor queues what it can take and\n * refuses the rest with 429, which is retried below.\n */\nexport const MAX_CONCURRENT_EXECS = 8;\n/** Waits before each retry of a refused call. */\nexport const CAPACITY_RETRY_DELAYS_MS = [1500, 3500, 7000];\n/** What a shopper reads when the executor is still refusing after the retries. */\nexport const BUSY_MESSAGE = 'Yantra is busy with other searches right now. Try again in a moment.';\n\nconst CAPACITY_REFUSAL =\n /execution capacity exhausted|too many concurrent executions|queue full|\\bHTTP 429\\b|\"code\"\\s*:\\s*429/i;\n\n/** True when the executor refused the call for capacity (it never ran). */\nexport function isCapacityRefusal(message: string | undefined): boolean {\n return !!message && CAPACITY_REFUSAL.test(message);\n}\n\nlet active = 0;\nconst waiting: Array<() => void> = [];\n\nfunction acquire(): Promise<void> {\n if (active < MAX_CONCURRENT_EXECS) {\n active += 1;\n return Promise.resolve();\n }\n return new Promise((resolve) =>\n waiting.push(() => {\n active += 1;\n resolve();\n }),\n );\n}\n\nfunction release(): void {\n active -= 1;\n waiting.shift()?.();\n}\n\n/** Tests: drop the slot bookkeeping. */\nexport function resetShoppingExecForTests(): void {\n active = 0;\n waiting.length = 0;\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\ntype RunAction = (connector: string, action: string, params: Record<string, unknown>) => Promise<unknown>;\n\n/** The paced exec over any raw `run` - exported so tests drive it without a network. */\nexport function pacedShoppingExec(run: RunAction, delays: readonly number[] = CAPACITY_RETRY_DELAYS_MS): ConnectorExec {\n return async <T = unknown>(connector: string, action: string, params: Record<string, unknown>) => {\n for (let attempt = 0; ; attempt += 1) {\n await acquire();\n let refused = false;\n try {\n const result = unwrapConnectorEnvelope<T>(await run(connector, action, params));\n if (result.success || !isCapacityRefusal(result.error)) return result;\n refused = true;\n if (attempt >= delays.length) return { success: false, error: BUSY_MESSAGE };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (!isCapacityRefusal(message)) return { success: false, error: message };\n refused = true;\n if (attempt >= delays.length) return { success: false, error: BUSY_MESSAGE };\n } finally {\n release();\n }\n // Back off outside the slot, with a little jitter so refused calls do not return together.\n if (refused) await sleep(delays[attempt] + Math.floor(Math.random() * 400));\n }\n };\n}\n\nexport function createShoppingExec(token: string, indexUrl: string): ConnectorExec {\n const run = createRemoteConnectorExec(token, indexUrl);\n return pacedShoppingExec((connector, action, params) =>\n run(connector, action, params, { timeoutMs: SHOPPING_EXEC_TIMEOUT_MS }),\n );\n}\n"],"names":[],"mappings":"8IA0BO,MAAM,wBAA2B,GAAA;AAUjC,MAAM,oBAAuB,GAAA;AAE7B,MAAM,wBAA2B,GAAA,CAAC,IAAM,EAAA,IAAA,EAAM,GAAI;AAElD,MAAM,YAAe,GAAA;AAC5B,MAAM,gBAAmB,GAAA,uGAAA;AAGlB,SAAS,kBAAkB,OAAsC,EAAA;AACtE,EAAA,OAAO,CAAC,CAAC,OAAW,IAAA,gBAAA,CAAiB,KAAK,OAAO,CAAA;AACnD;AACA,IAAI,MAAS,GAAA,CAAA;AACb,MAAM,UAA6B,EAAC;AACpC,SAAS,OAAyB,GAAA;AAChC,EAAA,IAAI,SAAS,oBAAsB,EAAA;AACjC,IAAU,MAAA,IAAA,CAAA;AACV,IAAA,OAAO,QAAQ,OAAQ,EAAA;AAAA;AAEzB,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAW,OAAA,KAAA,OAAA,CAAQ,KAAK,MAAM;AAC/C,IAAU,MAAA,IAAA,CAAA;AACV,IAAQ,OAAA,EAAA;AAAA,GACT,CAAC,CAAA;AACJ;AACA,SAAS,OAAgB,GAAA;AA3DzB,EAAA,IAAA,EAAA;AA4DE,EAAU,MAAA,IAAA,CAAA;AACV,EAAA,CAAA,EAAA,GAAA,OAAA,C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