@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 192c04a
Fork 0

سامانه صدور فاکتور و حسابداری

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 18:15 UTC

fix(phase0): bundle 38 parser-blocking Pages assets into three ordered bundles (#118)

* docs(state): record repeat owner BOOT_APP_ASSETS and 38 parser-blocking scripts before bounded fix * build(pages): group 38 parser-blocking scripts into 3 ordered same-origin bundles * build(pages): emit bundled baseline, business and accounting scripts on production artifact * fix(startup): reject workspace if any parser-blocking production bundle fails * test(pages): enforce three core bundles, keep early login responsive and fail closed on core asset error * fix(cache): pin updated CSP-safe bundle failure guard on browser clients * fix(cache): pin updated CSP-safe bundle failure guard on browser clients * test(pages): compare bundle filenames independent of _site URL prefix

davoodmehraban89 committed Oct 13, 2026 at 01:37 UTC 192c04a7e4c6324131f5c1b50a45bfa091c46a7a
7 files changed +107 -5
PROJECT_STATE.md
+6
@@ -121,6 +121,12 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
121 - PR-head Quality run `38311574244` SUCCESS **105/105 Chromium** (bundled production + blocked-bundle negative), Golden and 3 PostgreSQL PASS; Security `38311574218` SUCCESS. Exact merged main Quality `38311972925` SUCCESS, Security `38311972939` SUCCESS, Release Gate `38312280586` SUCCESS and Pages `38312349416` SUCCESS. Cancelled/skipped duplicate checks excluded.
122 - No Auth/RLS/schema/users/financial data/posting, no SMS/provider or remote desktop modifications. Remote Desktop Commander previously exhausted monthly quota; no bypass. **Owner affected-ISP full sign-in and performance not yet verified**; issue #106, F0-01, Phase 0 OPEN. Next: affected Chrome hard refresh and one actual sign-in, report result, elapsed and any BOOT code; if still failing compare an independent Internet connection. Rollback: revert #116 and gated deploy.
123
124 +### 2026-10-13 F0-01 owner photo STILL BOOT_APP_ASSETS after #116 — bounded critical-pages optimization
125 +- Actual owner photograph shows password login reverting to `BOOT_APP_ASSETS` rather than later `BOOT_APP_ASSETS_FAILED`; therefore user success after #116 NOT VERIFIED. This does not distinguish stale HTML from slow parser-blocking scripts or an unchanged owner network. No credentials or personal email copied from photo. Browser's first JS/manifest tests previously timed out, while public Auth health worked; PostgREST root 401 is not proof of database outage.
126 +- Source review at runtime `main=9b8d4cd7fa3bcb3b8175019525eaca0ffa97fb59`: production bundle optimization #116 only consolidated 14 **dynamically loaded extension modules**; `index.html` still has **38 other, parser-blocking, same-origin local JS tags** (12 before bootstrap and 26 after it). `DOMContentLoaded` waits for these, and `js/bootstrap.js` only starts its 18s deadline at DOMContentLoaded, so the account's 25s deadline can fire first, yielding `BOOT_APP_ASSETS` despite newer #116 code.
127 +- Safe implementation scope: build three content-hashed source-order-preserving **Pages-only blocking script bundles** corresponding to exact contiguous script ranges (admin..words, patches..accounting, accounting-foundation..ux-hardening). Preserve standalone `vendor/supabase.js`, `js/login-connectivity.js`, `js/core.js`, `js/bootstrap.js`, generated CSP event listeners and extension bundle. Preserve original source/dev `index.html`; only rewrite built `_site/index.html` in `scripts/build-pages.mjs`. Static dependency and VM parse checks, real Chromium Pages runtime DOM/CSP test, withheld-late-bundle responsive login test and exactly three bundle-request assertion required. No production tenant/auth/finance changes.
128 +- Genuine remedy acceptance: full Quality Chromium, Golden accounting, three disposable PostgreSQL, Security, exact SHA protected-main Release/Pages and owner actual affected-ISP login. Do not claim owner network repaired on CI pass. Existing issue #106 / F0-01 / Phase 0 OPEN. No remote-desktop quota circumvention.
129 +
130 ## Current change ledger
131 | 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
132
index.html
+2 -2
@@ -13,7 +13,7 @@
13 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net data:; img-src 'self' data: blob:; connect-src 'self' https://hcsixhqbyuhpshfwqpjx.supabase.co; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" />
14 <meta name="apple-mobile-web-app-capable" content="yes" />
15 <meta name="theme-color" content="#071a48" />
16 -<link rel="preload" as="script" href="js/core.js?v=20261013-asset-failclosed-v1" />
16 +<link rel="preload" as="script" href="js/core.js?v=20261013-static-pages-guard-v2" />
17 <link rel="preload" as="script" href="js/login-connectivity.js?v=20261012-data-probe-v3" />
18 <script src="vendor/supabase.js"></script>
19 <script async src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
@@ -893,7 +893,7 @@ body{background:#f6f9fc}
893 <!-- The credential-free connectivity action must be loaded before core declares
894 login actions interactive. Hardened Pages binds static handlers just before core. -->
895 <script src="js/login-connectivity.js?v=20261012-data-probe-v3"></script>
896 -<script src="js/core.js?v=20261013-asset-failclosed-v1"></script>
896 +<script src="js/core.js?v=20261013-static-pages-guard-v2"></script>
897 <script src="js/admin.js?v=20261012-provision-error-v1"></script>
898 <script src="js/sync.js?v=20261012-login-read-cancel-v1"></script>
899 <script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
js/core.js
+10
@@ -64,6 +64,16 @@ window.FinoraAppAssetsReady=new Promise((resolve,reject)=>{finoraAppAssetsResolv
64 window.FinoraAppAssetsReady.catch(()=>{});
65 window.finoraMarkAppAssetsReady=()=>finoraAppAssetsResolve();
66 window.finoraMarkAppAssetsFailed=()=>finoraAppAssetsReject(new Error('FINORA_APP_ASSETS_UNAVAILABLE'));
67 +
68 +window.addEventListener('error',event=>{
69 + const target=event.target;
70 + if(target?.tagName!=='SCRIPT')return;
71 + const source=String(target.src||'');
72 + if(!/\/finora-pages-(?:foundation|business|accounting)\.js(?:\?|$)/.test(source))return;
73 + window.FinoraStartupStatus.blockingPagesAssetFailed=true;
74 + window.finoraMarkAppAssetsFailed();
75 +},true);
76 +
77 window.FinoraStartupStatus={authFormReady:false,authSessionChecked:false,authChecked:false,extensionsReady:false};
78 function setAuthLoginStatus(message,state){
79 const el=document.getElementById('auth-login-status');
scripts/build-pages.mjs
+2
@@ -1,5 +1,6 @@
1 import fs from 'node:fs';
2 import path from 'node:path';
3 +import {bundleFinoraPagesBlockingScripts} from './pages-blocking-bundles.mjs';
4 import {createHash} from 'node:crypto';
5 import vm from 'node:vm';
6
@@ -96,6 +97,7 @@ if(!originalBootstrap.includes(marker))throw new Error('Missing bundle loader fe
97 fs.writeFileSync(bootstrapPath,originalBootstrap.replace(marker,
98 'const FINORA_EXTENSION_BUNDLE_URL="js/finora-extension-bundle.js?v='+bundleHash+'";'));
99
100 +html=bundleFinoraPagesBlockingScripts(html,out);
101 fs.writeFileSync(path.join(out,'index.html'),html);
102 fs.writeFileSync(path.join(out,'js','generated-event-handlers.js'),generated);
103 fs.writeFileSync(path.join(out,'js','generated-dynamic-handlers.js'),dynamic);
scripts/login-connectivity-check.mjs
+2 -2
@@ -7,8 +7,8 @@ assert(html.includes('id="auth-connectivity-check"'),'Missing diagnostic action'
7 assert(html.includes('id="auth-connectivity-result"'),'Missing accessible result');
8 assert(html.includes('id="auth-connectivity-result" aria-live="polite"'),'Diagnostic must announce updates without adding a conflicting global role=status');
9 assert(html.includes('js/login-connectivity.js?v=20261012-data-probe-v3'),'Missing versioned script');
10 -assert(html.includes('js/core.js?v=20261013-asset-failclosed-v1'),'Production login controls must use new cache version');
11 -assert(html.indexOf('<script src="js/login-connectivity.js?v=20261012-data-probe-v3"')<html.indexOf('<script src="js/core.js?v=20261013-asset-failclosed-v1"'),'Connectivity handler script must execute before core (not just preload)');
10 +assert(html.includes('js/core.js?v=20261013-static-pages-guard-v2'),'Production login controls must use new cache version');
11 +assert(html.indexOf('<script src="js/login-connectivity.js?v=20261012-data-probe-v3"')<html.indexOf('<script src="js/core.js?v=20261013-static-pages-guard-v2"'),'Connectivity handler script must execute before core (not just preload)');
12 assert(html.includes('js/bootstrap.js?v=20261013-ordered-bundle-v1'),'Parallel bootstrap must also be cache-busted');
13 assert(html.includes('id="auth-login-button"')&&html.includes('id="auth-login-status"'),'Login control requires real readiness/progress feedback');
14 assert(core.includes('window.FinoraAppAssetsReady'),'Authenticated workspace must remain gated until all module scripts settle');
scripts/pages-artifact.spec.js
+44 -1
@@ -29,7 +29,7 @@ test('hardened Pages artifact loads without script/CSP console errors',async({pa
29
30 test('Production CSP login and connectivity actions work while later ERP JS is still downloading',async({page})=>{
31 let delayedModuleFinished=false;
32 - await page.route('**/js/phase6-reporting.js*',async route=>{
32 + await page.route('**/js/finora-pages-accounting.js*',async route=>{
33 await new Promise(resolve=>setTimeout(resolve,5000));
34 delayedModuleFinished=true;
35 await route.continue();
@@ -99,3 +99,46 @@ test('A blocked production bundle fails closed and never exposes a partial finan
99 expect(output.loginVisible).toBe(true);
100 expect(output.currentUser).toBe(null);
101 });
102 +
103 +test('Built Pages loads exactly three ordered core groups instead of 38 blocking requests',async({page})=>{
104 + const names=['foundation','business','accounting'];
105 + const requests=[];
106 + page.on('request',r=>{if(new URL(r.url()).pathname.includes('/js/finora-pages-'))requests.push(new URL(r.url()).pathname);});
107 + await page.goto(base,{waitUntil:'domcontentloaded'});
108 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.extensionsReady),{timeout:15000}).toBe(true);
109 + const info=await page.evaluate(()=>({
110 + scripts:[...document.querySelectorAll('script[src*="finora-pages-"]')].map(el=>new URL(el.src).pathname.split('/').at(-1)),
111 + blockingFailed:window.FinoraStartupStatus.blockingPagesAssetFailed===true,
112 + loadedCore:typeof handleLogin,
113 + loadedAccounting:typeof window.finoraParseMoney==='function'||typeof window.parseFormattedNumber==='function'
114 + }));
115 + expect(info.scripts).toEqual(names.map(x=>'finora-pages-'+x+'.js'));
116 + expect(info.blockingFailed).toBe(false);
117 + expect(info.loadedCore).toBe('function');
118 + expect(info.loadedAccounting).toBe(true);
119 + expect(requests.map(x=>x.split('/').at(-1))).toEqual(names.map(x=>'finora-pages-'+x+'.js'));
120 + const html=await page.content();
121 + for(const legacy of ['js/admin.js','js/patches.js','js/accounting-foundation.js']){
122 + expect(html).not.toContain('<script src="'+legacy);
123 + }
124 +});
125 +
126 +test('A blocked required core Pages group prevents opening partial financial workspace',async({page})=>{
127 + await page.route('**/js/finora-pages-accounting.js*',route=>route.abort('failed'));
128 + await page.goto(base,{waitUntil:'domcontentloaded'});
129 + const output=await page.evaluate(async()=>{
130 + window.fetchCurrentUser=async()=>({id:'fixture-person'});
131 + await enterApp({id:'fixture-person'},{timeoutMs:300});
132 + return {
133 + status:document.getElementById('auth-login-status').textContent,
134 + visible:getComputedStyle(document.getElementById('auth-screen')).display,
135 + user:currentUser,
136 + missing:window.FinoraStartupStatus.blockingPagesAssetFailed
137 + };
138 + });
139 + expect(output.missing).toBe(true);
140 + expect(output.status).toContain('BOOT_APP_ASSETS_FAILED');
141 + expect(output.status).not.toContain('fixture-person');
142 + expect(output.visible).toBe('flex');
143 + expect(output.user).toBe(null);
144 +});
scripts/pages-blocking-bundles.mjs new
+41
@@ -0,0 +1,41 @@
1 +import fs from 'node:fs';
2 +import path from 'node:path';
3 +import vm from 'node:vm';
4 +import {createHash} from 'node:crypto';
5 +
6 +// These are original contiguous, parser-blocking <script> runs in index.html.
7 +// Preserve all CSS boundaries and early CSP/auth binding scripts unchanged.
8 +const groups=[
9 + {name:'foundation',files:['admin','sync','ui','invoices','print','products','contacts','cheques','expenses','companies','backup','words']},
10 + {name:'business',files:['patches','idle-and-reports','money-format','projects','invoice-excel-import','purchases','commercial-rnd','operations','payments','accounting']},
11 + {name:'accounting',files:['accounting-foundation','journal-engine','context-help','accounting-foundation-ui','accounting-foundation-render','journal-ui','document-management','drilldown','phase4-contracting','phase5-domain','phase5-enterprise','phase6-reporting','enterprise-iran','enterprise-iran-v2','selfcheck','ux-hardening-r2']}
12 +];
13 +const localScript=/<script src="(js\/([a-z0-9-]+)\.js(?:\?v=[a-z0-9-]+)?)"><\/script>/gi;
14 +
15 +export function bundleFinoraPagesBlockingScripts(originalHtml,outDir){
16 + let html=originalHtml;
17 + for(const {name,files} of groups){
18 + const tags=[...html.matchAll(localScript)];
19 + const from=tags.find(t=>t[2]===files[0]);
20 + const last=tags.find(t=>t[2]===files.at(-1));
21 + if(!from||!last||last.index<from.index)throw new Error('Missing Pages group '+name);
22 + const segment=html.slice(from.index,last.index+last[0].length);
23 + const found=[...segment.matchAll(localScript)].map(t=>t[2]);
24 + if(JSON.stringify(found)!==JSON.stringify(files)||segment.replace(localScript,'').trim())
25 + throw new Error('Non-contiguous or reordered Pages scripts in '+name);
26 + const sources=files.map(file=>{
27 + const filename=path.join(outDir,'js',file+'.js');
28 + if(!fs.existsSync(filename))throw new Error('Missing Pages JS '+file);
29 + return fs.readFileSync(filename,'utf8');
30 + });
31 + // A classic-script concatenation preserves global declarations and
32 + // executes each source in its original document order, exactly once.
33 + const content='// Finora '+name+' Pages-only bundle. Original order.\n'+sources.join('\n;\n');
34 + new vm.Script(content,{filename:'finora-'+name+'-pages.js'});
35 + const hash=createHash('sha256').update(content).digest('hex').slice(0,16);
36 + const file='finora-pages-'+name+'.js';
37 + fs.writeFileSync(path.join(outDir,'js',file),content);
38 + html=html.slice(0,from.index)+'<script src="js/'+file+'?v='+hash+'"></script>'+html.slice(last.index+last[0].length);
39 + }
40 + return html;
41 +}