import { buildShopSearchQuery, matchesShopSearchQuery, parseStructuredPriceToCny } from '../upstream/src/shop-search-query'; import { matchesShopCategory } from '../upstream/src/shop-filter-state'; import { matchesListKinds } from '../upstream/src/list-kind-filter'; import { pinSiteRows } from '../upstream/src/site-list-pinning'; // The live frontend uses a paginated response contract newer than the public repository. // Unpack the real captured catalog, reuse original search/pinning rules, return that contract locally. let datasetPromise: Promise | undefined; const storage=(key:string,fallback:any)=>{try{return JSON.parse(localStorage.getItem(key)||'null')||fallback;}catch{return fallback;}}; const iso=(value:number|null)=>value?new Date(value).toISOString():null; const beijingFormatter=new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'}); const time=(value:number|null)=>value?beijingFormatter.format(new Date(value)):''; async function dataset(){ return datasetPromise ||= fetch('/data/catalog-index.json').then(r=>{if(!r.ok)throw new Error('Catalog index unavailable');return r.json();}).then(async metadata=>{ const parts:any[][]=new Array(metadata.chunks.length); let cursor=0; await Promise.all(Array.from({length:4},async()=>{ while(cursor(); const products=raw.p.map((p:any[],index:number)=>{ const s=raw.s[p[0]]; const unit=p[4]===null?'¥':p[4]===-1?'':raw.u[p[4]]||'¥'; const category=raw.c[p[1]]||''; siteCounts.set(s[0],(siteCounts.get(s[0])||0)+1); const priceNumber=p[3]; return { id:p[10],categoryName:category,autoCategory:p[11]||'other',name:p[2],price:priceNumber===null?'—':unit+priceNumber,priceNumber,priceUnit:unit, productUrl:p[5],stock:p[6],inStock:Boolean(p[7]),score:p[9],refreshedAt:iso(p[8]),refreshTime:time(p[8]), siteId:s[0],siteSlug:s[9]||'',siteName:s[1],siteUrl:s[2],sitePlatformName:s[8]||'',siteScore:s[4],siteSponsor:Boolean(s[5]), siteSupportPoints:s[7]||0,siteSupportTotalCents:s[6]||0,siteProductRefreshSuccessAt:iso(s[3]),siteProductRefreshSuccessTime:time(s[3]), productFavoriteKey:`${s[1]}#${category}-${p[2]}`,siteFavoriteKey:s[0],sponsor:Boolean(s[5]),supportPoints:s[7]||0,supportTotalCents:s[6]||0, _index:index,_search:{productName:p[2],categoryName:category,siteText:s[1],siteUrl:s[2],autoCategory:p[11]||'other',priceNumber,priceUnit:unit} }; }); const sites=raw.s.map((s:any[])=>({ id:s[0],name:s[1],url:s[2],lastProductRefreshSuccessAt:iso(s[3]),lastProductRefreshSuccessTime:time(s[3]),score:s[4],sponsor:Boolean(s[5]), supportTotalCents:s[6]||0,supportPoints:s[7]||0,platformName:s[8]||'',slug:s[9]||'',productCount:siteCounts.get(s[0])||0, })); return {raw,products,sites}; }).catch(error=>{datasetPromise=undefined;throw error;}); } const number=(params:URLSearchParams,key:string)=>params.has(key)&¶ms.get(key)!==''?Number(params.get(key)):null; function sortValue(row:any,key:string){ if(key==='priceValue')return parseStructuredPriceToCny(row.priceNumber,row.priceUnit)??Infinity; if(key==='stockValue')return row.stock??Infinity; if(key==='productName')return row.name; if(key==='productScore')return row.score; if(key==='categoryName')return row.categoryName; if(key==='siteName')return row.siteName; if(key==='refreshMs')return Date.parse(row.refreshedAt||'')||0; if(key==='sequence'||key==='rank')return row._index; return row[key]??row._index; } export async function respond(pathname:string,params:URLSearchParams,body:any={}){ const data=await dataset(); if(pathname==='/api/shop-merchants.json')return {sites:data.sites,products:[],totalSiteCount:data.sites.length,latestRefreshTime:'',isPartial:false}; if(body.query)params=new URLSearchParams(body.query); const q=params.get('q')||'',category=params.get('category')||'',siteId=params.get('siteId')||body.siteId||''; const query=buildShopSearchQuery(q); const favorites=body.favorites||{}; const siteFavorites=new Set(favorites.siteIds||storage('cardnav.favoriteSites',[])); const productFavorites=new Set(favorites.productKeys||storage('cardnav.favoriteProducts',[])); const productIds=new Set(favorites.productIds||Object.values(storage('cardnav.favoriteProductIds',{}))); const min=number(params,'priceMin'),max=number(params,'priceMax'); const platforms=params.getAll('platform'),originalCategories=params.getAll('originalCategory'),kinds=params.getAll('kind'); const matchCategory=params.get('matchCategory')==='1',matchMerchant=params.get('matchMerchant')==='1'; let rows=data.products.filter((row:any)=>{ if(siteId&&row.siteId!==siteId)return false; if(!matchesShopCategory(row.autoCategory,category))return false; if(params.get('inStockOnly')==='1'&&!row.inStock)return false; if(params.get('platformOnly')==='1'&&!row.sitePlatformName)return false; if(platforms.length&&!platforms.includes(row.sitePlatformName||'self-hosted'))return false; if(originalCategories.length&&!originalCategories.includes(row.categoryName))return false; const value=parseStructuredPriceToCny(row.priceNumber,row.priceUnit); if(min!==null&&(value===null||valuemax))return false; const favorite=productFavorites.has(row.productFavoriteKey)||productIds.has(row.id)||siteFavorites.has(row.siteId); if(!matchesListKinds(kinds,{sponsor:row.sponsor,supportPoints:row.supportPoints,favorite}))return false; return matchesShopSearchQuery(row._search,query,{matchCategory,matchMerchant}); }); const sort=params.get('productSort')||''; const [sortKey,direction]=sort.split(':'); if(sortKey)rows.sort((a:any,b:any)=>{ const x=sortValue(a,sortKey),y=sortValue(b,sortKey); const delta=typeof x==='number'&&typeof y==='number'?x-y:String(x).localeCompare(String(y),'zh-Hans-CN',{numeric:true}); return (Number.isNaN(delta)?0:delta)*(direction==='desc'?-1:1)||a._index-b._index; }); const pinned=pinSiteRows(rows.map((row:any,index:number)=>({row,defaultIndex:index,sponsor:row.sponsor,supportPoints:row.supportPoints,supportTotalCents:row.supportTotalCents,favorite:productFavorites.has(row.productFavoriteKey)||productIds.has(row.id)||siteFavorites.has(row.siteId)})),(entry:any,kind:string)=>{entry.row={...entry.row,pinKind:kind};},Boolean(sortKey)); rows=pinned.map((entry:any)=>entry.row); const totalCount=rows.length,pageSize=100,pageCount=Math.max(1,Math.ceil(totalCount/pageSize)); const page=Math.min(pageCount,Math.max(1,Number(params.get('page'))||1)); const pageRows=rows.slice((page-1)*pageSize,page*pageSize).map((row:any)=>{ const {_index,_search,...plain}=row; return {...plain,merchantMatch:false}; }); return { catalogSummary:{totalSiteCount:data.raw.sc,totalProductCount:data.raw.pc,totalInStockProductCount:data.raw.ipc,latestRefreshAt:iso(data.raw.l)}, query:q,sort,inStock:params.get('inStockOnly')==='1',platformOnly:params.get('platformOnly')==='1',category,page,pageSize,pageCount, queryInvalid:query.mode==='invalid',totalCount,totalSiteCount:new Set(rows.map((row:any)=>row.siteId)).size,rows:pageRows,groups:[], originalCategoryOptions:data.raw.c,platformOptions:[...new Set(data.sites.map((site:any)=>site.platformName||'self-hosted'))], generatedAt:iso(data.raw.l)||'2026-11-15T04:20:43Z',resultVersion:'cardnav-static-snapshot-v1' }; }