Intelligence, Advanced Charting & Trading Platform

1 import {marketCatalogSummary} from '../packages/market-domain/src/market-catalog-summary.mjs';
2
3 /**
4 * Fail-closed integration into the original Cloudflare ChartNova Worker v26.
5 * INPUT: clean module JS of the ACTIVE v26 version; never last-uploaded v27.
6 * Does not itself access Cloudflare APIs, publish versions, or deploy.
7 */
8 function replaceOnce(text,oldPart,newPart,label){
9 const count=text.split(oldPart).length-1;
10 if(count!==1)throw new Error(label+': expected one anchor, found '+count);
11 return text.replace(oldPart,newPart);
12 }
13 const routeAnchor='if(url.pathname==="/api/markets"&&request.method==="GET"){';
14 const summaryRoute=[
15 'if(url.pathname==="/api/markets/summary"&&request.method==="GET"){',
16 ' const catalog=await stored(env,"markets:gheymat:v1");',
17 ' const result=marketCatalogSummary(catalog,Date.now());',
18 ' return Response.json(result,{status:result.ok?200:503,headers:{"cache-control":"no-store","x-content-type-options":"nosniff"}});',
19 '}',
20 ''
21 ].join('\n');
22
23 const oldMarketRendering=' renderMarkets();renderTechnical();renderSelected();';
24 const lazyMarketRendering=[
25 ' if(!el("markets").hidden)renderMarkets();',
26 ' if(!el("technical").hidden)renderTechnical();',
27 ' if(!el("dashboard").hidden)renderSelected();',
28 ' if(!el("widget").hidden)renderWidget();'
29 ].join('\n');
30 const oldRefreshRendering=' renderSelected();renderMarkets();renderTechnical();';
31 const lazyRefreshRendering=[
32 ' if(!el("dashboard").hidden)renderSelected();',
33 ' if(!el("markets").hidden)renderMarkets();',
34 ' if(!el("technical").hidden)renderTechnical();',
35 ' if(!el("widget").hidden)renderWidget();'
36 ].join('\n');
37 const chartnovaSeriesHelper="\nconst chartnovaSeriesCache=new Map();\nconst chartnovaSeriesInFlight=new Map();\nconst chartnovaSeriesRetryAfter=new Map();\nasync function requestChartnovaSeries(symbol){\n const active=instrument(symbol);\n if(!active||active.historyCount<2||Array.isArray(active.history)||\n chartnovaSeriesInFlight.has(symbol)||\n Date.now()<(chartnovaSeriesRetryAfter.get(symbol)||0))return;\n if(!/^[A-Z0-9]{1,20}-[A-Z0-9]{2,10}$/.test(symbol))return;\n const job=(async()=>{\n const response=await fetch(\"/api/markets?symbol=\"+encodeURIComponent(symbol),{cache:\"no-store\"});\n if(!response.ok)throw Error(\"series_fetch_status\");\n const payload=await response.json(),row=payload.markets?.[0];\n if(payload.ok!==true||payload.source!==marketState.source||\n !Array.isArray(payload.markets)||payload.markets.length!==1||\n row?.symbol!==symbol||payload.fetchedAt!==marketState.receivedAt||\n row?.updatedAt!==active.updatedAt||row?.sellPrice!==active.sellPrice)\n throw Error(\"series_snapshot_mismatch\");\n const points=row.history;\n if(!Array.isArray(points)||points.length!==active.historyCount||\n points.length>168||!points.every(v=>Number.isFinite(v)&&v>0))\n throw Error(\"series_quality_gate\");\n if(instrument(symbol)!==active)return;\n active.history=points.slice();\n chartnovaSeriesCache.set(symbol,{updatedAt:active.updatedAt,history:points.slice()});\n if(chartnovaSeriesCache.size>12)chartnovaSeriesCache.delete(chartnovaSeriesCache.keys().next().value);\n if(!el(\"technical\").hidden&&marketState.selected===symbol)renderTechnical();\n const asset=chosen===\"usd\"?\"USD-IRT\":chosen===\"gold18\"?\"GOLD18-IRT\":\"GOLDO-USD\";\n if(!el(\"dashboard\").hidden&&asset===symbol)renderSelected();\n })().catch(()=>{chartnovaSeriesRetryAfter.set(symbol,Date.now()+30000)}).\n finally(()=>{chartnovaSeriesInFlight.delete(symbol)});\n chartnovaSeriesInFlight.set(symbol,job);\n await job;\n}\n";
38 const preloadCachedSeries="marketState.items=payload.markets;\n for(const m of marketState.items){\n const cached=chartnovaSeriesCache.get(m.symbol);\n if(cached&&cached.updatedAt===m.updatedAt&&\n cached.history.length===m.historyCount)m.history=cached.history.slice();\n }";
39 export function patchChartNovaV26(source){
40 if(typeof source!=='string'||!source.startsWith('export default {')||source.length<40000)
41 throw new Error('Expected clean v26 Worker source, not Cloudflare multipart wrapper');
42 if(source.includes('chartnovaRefreshInFlight')||source.includes('/api/markets/summary'))
43 throw new Error('Version mismatch: refuses uploaded v27 or already-patched script');
44 if(!source.includes('async scheduled(event,env)'))throw new Error('Scheduled handler absent');
45 const before=source;
46 source=replaceOnce(source,routeAnchor,summaryRoute+routeAnchor,'new read-only route');
47 source+='\n'+marketCatalogSummary.toString()+'\n';
48 const start=source.indexOf('return new Response("<!doctype html>');
49 const end=source.indexOf('",{headers:{"content-type":"text/html; charset=utf-8"',start);
50 if(start<0||end<0)throw new Error('Original HTML response not found');
51 const litStart=start+'return new Response('.length;
52 let html;
53 try{html=JSON.parse(source.slice(litStart,end+1))}catch{throw new Error('HTML literal decode failed')}
54 const first=html.indexOf('<script>'),last=html.indexOf('</script>',first);
55 if(first<0||last<0||html.indexOf('<script>',first+1)!==-1)
56 throw new Error('Expected one original inline UI script');
57 const oldJS=html.slice(first+8,last);
58 let js=oldJS;
59 js=replaceOnce(js,'function renderSelected(){',chartnovaSeriesHelper+'\nfunction renderSelected(){','history fetch helper');
60 js=replaceOnce(js,'const response=await fetch("/api/markets",{cache:"no-store"});','const response=await fetch("/api/markets/summary",{cache:"no-store"});','small snapshot fetch');
61 js=replaceOnce(js,'marketState.items=payload.markets;',preloadCachedSeries,'cached series retention');
62 js=replaceOnce(js,oldMarketRendering,lazyMarketRendering,'lazy loaded markets');
63 js=replaceOnce(js,oldRefreshRendering,lazyRefreshRendering,'lazy refresh');
64 js=replaceOnce(js,'if(m?.history?.length>1){',
65 'if(m?.historyCount>1&&!Array.isArray(m.history))void requestChartnovaSeries(code);\n if(m?.history?.length>1){',
66 'on-demand dashboard history');
67 js=replaceOnce(js,' const history=m.history||[];',
68 ' if(m.historyCount>1&&!Array.isArray(m.history))void requestChartnovaSeries(m.symbol);\n const history=m.history||[];',
69 'on-demand technical history');
70 js=replaceOnce(js,'m.history?.length+" نمونه ساعتی"',
71 '(m.historyCount??m.history?.length??0)+" نمونه ساعتی"','show true available count');
72 const updatedHTML=html.slice(0,first+8)+js+html.slice(last);
73 if(updatedHTML.replace(js,oldJS)!==html)throw new Error('HTML unexpectedly modified');
74 source=source.slice(0,litStart)+JSON.stringify(updatedHTML)+source.slice(end+1);
75 if(!source.includes('async scheduled(event,env)')||source.length<before.length)
76 throw new Error('Output truncated or lost backend handlers');
77 return {source,originalBytes:before.length,oldHTML:html,newHTML:updatedHTML,oldJS,newJS:js};
78 }