@stacksjs/stx 0.2.532 → 0.2.534
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/dist/{chunk-y4qks0bd.js → chunk-01343ehq.js} +2 -2
- package/dist/chunk-0e5nasyf.js +2 -0
- package/dist/chunk-13zbt9py.js +2 -0
- package/dist/{chunk-9w2vmfha.js → chunk-1c4t7ncb.js} +2 -2
- package/dist/{chunk-gxfnmjzp.js → chunk-1xgs9gd5.js} +2 -2
- package/dist/{chunk-4gt0r98p.js → chunk-2bvk0qyd.js} +2 -2
- package/dist/{chunk-y7ds4qyb.js → chunk-2h4f37kx.js} +2 -2
- package/dist/{chunk-q6e45gnw.js → chunk-2kvbg3t5.js} +3 -3
- package/dist/{chunk-xdtz2v5r.js → chunk-2n4je46m.js} +2 -2
- package/dist/{chunk-xcfhy5bj.js → chunk-33bzhsyw.js} +2 -2
- package/dist/{chunk-7ybgfk0m.js → chunk-3nk8cnrm.js} +2 -2
- package/dist/{chunk-gsxb0ry9.js → chunk-3r1m3tyr.js} +1 -1
- package/dist/chunk-3zs8yxy0.js +2 -0
- package/dist/{chunk-khwj964t.js → chunk-40hbpz2b.js} +3 -3
- package/dist/chunk-4a7v51vh.js +2 -0
- package/dist/{chunk-xtknewf7.js → chunk-4hyhr5r7.js} +1 -1
- package/dist/{chunk-hp1tnxzb.js → chunk-4pxc3r1p.js} +4 -4
- package/dist/chunk-4qts8zk7.js +2 -0
- package/dist/{chunk-587ehsxn.js → chunk-4r7s3862.js} +2 -2
- package/dist/chunk-4y2av4ev.js +2 -0
- package/dist/chunk-5g498pdp.js +2 -0
- package/dist/chunk-5gq8m2m7.js +2 -0
- package/dist/chunk-5wx323bm.js +2 -0
- package/dist/{chunk-d2r8t40y.js → chunk-66s4nhp7.js} +2 -2
- package/dist/{chunk-d7x6n702.js → chunk-6dtmants.js} +3 -3
- package/dist/chunk-6rcxtdh3.js +2 -0
- package/dist/{chunk-st79dqpz.js → chunk-6sd4zdtg.js} +1 -1
- package/dist/{chunk-zpdq0kx1.js → chunk-6tnh3cyq.js} +1 -1
- package/dist/chunk-6va8wt88.js +2 -0
- package/dist/chunk-7v2j9bmc.js +2 -0
- package/dist/chunk-7zgtdap7.js +2 -0
- package/dist/{chunk-0pebjkzx.js → chunk-843y0pfg.js} +4 -4
- package/dist/{chunk-4xxhprts.js → chunk-8chxczpj.js} +3 -3
- package/dist/{chunk-b7xdk1g4.js → chunk-8m1y1kyr.js} +5 -5
- package/dist/chunk-90kzf313.js +2 -0
- package/dist/{chunk-t6769zcy.js → chunk-93n6yv5x.js} +12 -12
- package/dist/chunk-94rg5s6c.js +2 -0
- package/dist/chunk-9674w2gm.js +2 -0
- package/dist/{chunk-gvw8wh29.js → chunk-9p6bt089.js} +3 -3
- package/dist/{chunk-kg77xs08.js → chunk-bczcm7jk.js} +2 -2
- package/dist/{chunk-rs46hksk.js → chunk-bxsehntq.js} +1 -1
- package/dist/{chunk-vg8thz41.js → chunk-c56qtne1.js} +1 -1
- package/dist/chunk-d1jxmhph.js +2 -0
- package/dist/{chunk-5tj6expd.js → chunk-d7zterbp.js} +2 -2
- package/dist/{chunk-664503e6.js → chunk-d871008z.js} +4 -4
- package/dist/chunk-dekpf1ry.js +2 -0
- package/dist/chunk-epa1c4q4.js +2 -0
- package/dist/{chunk-xb0785wp.js → chunk-f3q84h7b.js} +2 -2
- package/dist/{chunk-g060jncp.js → chunk-fqfqyn48.js} +4 -4
- package/dist/{chunk-g5t10z04.js → chunk-gnx0fzne.js} +60 -60
- package/dist/chunk-gsc5t942.js +2 -0
- package/dist/chunk-gsm1y1kb.js +2 -0
- package/dist/chunk-gxedmh17.js +2 -0
- package/dist/{chunk-9xq5yer8.js → chunk-h4crv0by.js} +1 -1
- package/dist/{chunk-pr5q4wev.js → chunk-hp8g2q2n.js} +1 -1
- package/dist/{chunk-38w14qs7.js → chunk-hvpzy98g.js} +1 -1
- package/dist/chunk-j9c0yam7.js +2 -0
- package/dist/{chunk-12e4a0ab.js → chunk-jbfad9cc.js} +2 -2
- package/dist/chunk-jv3jj612.js +2 -0
- package/dist/chunk-jvqas8y2.js +2 -0
- package/dist/{chunk-rwn3b21z.js → chunk-k3v13vfr.js} +2 -2
- package/dist/chunk-kcs7hyep.js +2 -0
- package/dist/chunk-kvp0at16.js +2 -0
- package/dist/{chunk-31c1g3rt.js → chunk-m011s2ha.js} +3 -3
- package/dist/{chunk-2jk0vceh.js → chunk-m56m95gk.js} +2 -2
- package/dist/{chunk-7s14bthq.js → chunk-m5fw8jq1.js} +2 -2
- package/dist/chunk-m7jmpech.js +2 -0
- package/dist/chunk-m8n9wxba.js +2 -0
- package/dist/{chunk-fyxydww2.js → chunk-mjdyyekx.js} +2 -2
- package/dist/{chunk-ennxrn5g.js → chunk-nd8v4xgb.js} +5 -5
- package/dist/chunk-ngma9vzc.js +2 -0
- package/dist/{chunk-rtk6n3vh.js → chunk-ngxqydsg.js} +3 -3
- package/dist/{chunk-ee4wwr89.js → chunk-nmy4x6dx.js} +4 -4
- package/dist/chunk-pz1mjgsp.js +2 -0
- package/dist/{chunk-er031j13.js → chunk-qfc912e5.js} +2 -2
- package/dist/chunk-qk3ptn6h.js +2 -0
- package/dist/{chunk-03wggzg8.js → chunk-qmza4327.js} +2 -2
- package/dist/{chunk-j8pacd7m.js → chunk-qqr4rn9p.js} +4 -4
- package/dist/chunk-rx4hz615.js +2 -0
- package/dist/chunk-shf0hd05.js +2 -0
- package/dist/{chunk-3vvppnws.js → chunk-sqb6gkzf.js} +8374 -8374
- package/dist/chunk-t1g1sp2z.js +2 -0
- package/dist/{chunk-m2v04c6v.js → chunk-tgc645pa.js} +45 -45
- package/dist/{chunk-2dzd2h15.js → chunk-tkvp3rz0.js} +1 -1
- package/dist/{chunk-458etq5a.js → chunk-tqnh98j7.js} +3 -3
- package/dist/chunk-tr9bjtqx.js +2 -0
- package/dist/{chunk-2y6tzn6d.js → chunk-ty1v368m.js} +2 -2
- package/dist/{chunk-grb3kfya.js → chunk-v4r8nzf3.js} +1 -1
- package/dist/{chunk-p8yh7mgr.js → chunk-v9vvzdag.js} +2 -2
- package/dist/{chunk-0wvsfs4s.js → chunk-vb4xxpa6.js} +2 -2
- package/dist/chunk-vfnerp7h.js +2 -0
- package/dist/{chunk-tkeabv04.js → chunk-vhfwnvmc.js} +5 -5
- package/dist/{chunk-15r72kw7.js → chunk-vjdj0ex3.js} +1 -1
- package/dist/{chunk-9pztpvvk.js → chunk-wh7xn313.js} +1 -1
- package/dist/chunk-wjt46tdp.js +2 -0
- package/dist/chunk-wxy9re1a.js +2 -0
- package/dist/{chunk-kwvexxey.js → chunk-x607yxrc.js} +3 -3
- package/dist/{chunk-3zyvhf4p.js → chunk-xey01yna.js} +1 -1
- package/dist/{chunk-stbsqy7e.js → chunk-xwrbrg1q.js} +1 -1
- package/dist/{chunk-9sqjmd9a.js → chunk-y18yvcjb.js} +5 -5
- package/dist/chunk-ydtnskdv.js +2 -0
- package/dist/{chunk-ky25egh1.js → chunk-yw3cqy43.js} +1 -1
- package/dist/{chunk-1945hk44.js → chunk-z9r3tqyr.js} +1 -1
- package/dist/chunk-zeve89kw.js +2 -0
- package/dist/cli.js +12 -12
- package/dist/client/signals-appearance-runtime.d.ts +2 -0
- package/dist/client/signals-appearance-runtime.js +283 -0
- package/dist/client/signals-authoring-runtime.d.ts +2 -0
- package/dist/client/signals-authoring-runtime.js +187 -0
- package/dist/client/signals-binding-utils-runtime.d.ts +2 -0
- package/dist/client/signals-binding-utils-runtime.js +130 -0
- package/dist/client/signals-bootstrap-runtime.d.ts +4 -0
- package/dist/client/signals-bootstrap-runtime.js +24 -0
- package/dist/client/signals-class-runtime.d.ts +2 -0
- package/dist/client/signals-class-runtime.js +69 -0
- package/dist/client/signals-component-api-runtime.d.ts +1 -0
- package/dist/client/signals-component-api-runtime.js +57 -0
- package/dist/client/signals-component-hydration-runtime.d.ts +2 -0
- package/dist/client/signals-component-hydration-runtime.js +147 -0
- package/dist/client/signals-component-props-runtime.d.ts +2 -0
- package/dist/client/signals-component-props-runtime.js +90 -0
- package/dist/client/signals-conditional-chain-runtime.d.ts +2 -0
- package/dist/client/signals-conditional-chain-runtime.js +39 -0
- package/dist/client/signals-conditional-component-runtime.d.ts +2 -0
- package/dist/client/signals-conditional-component-runtime.js +82 -0
- package/dist/client/signals-container-cleanup-runtime.d.ts +2 -0
- package/dist/client/signals-container-cleanup-runtime.js +42 -0
- package/dist/client/signals-context-runtime.d.ts +2 -0
- package/dist/client/signals-context-runtime.js +48 -0
- package/dist/client/signals-cookie-runtime.d.ts +2 -0
- package/dist/client/signals-cookie-runtime.js +56 -0
- package/dist/client/signals-devtools-runtime.d.ts +2 -0
- package/dist/client/signals-devtools-runtime.js +136 -0
- package/dist/client/signals-dialog-runtime.d.ts +2 -0
- package/dist/client/signals-dialog-runtime.js +195 -0
- package/dist/client/signals-dom-ready-runtime.d.ts +2 -0
- package/dist/client/signals-dom-ready-runtime.js +306 -0
- package/dist/client/signals-drawer-runtime.d.ts +2 -0
- package/dist/client/signals-drawer-runtime.js +39 -0
- package/dist/client/signals-effect-runtime.d.ts +2 -0
- package/dist/client/signals-effect-runtime.js +157 -0
- package/dist/client/signals-event-shorthand-runtime.d.ts +2 -0
- package/dist/client/signals-event-shorthand-runtime.js +88 -0
- package/dist/client/signals-expression-compiler-runtime.d.ts +2 -0
- package/dist/client/signals-expression-compiler-runtime.js +59 -0
- package/dist/client/signals-expression-runtime.d.ts +2 -0
- package/dist/client/signals-expression-runtime.js +67 -0
- package/dist/client/signals-fetch-runtime.d.ts +2 -0
- package/dist/client/signals-fetch-runtime.js +144 -0
- package/dist/client/signals-fetch-transport-runtime.d.ts +2 -0
- package/dist/client/signals-fetch-transport-runtime.js +216 -0
- package/dist/client/signals-for-runtime.d.ts +2 -0
- package/dist/client/signals-for-runtime.js +647 -0
- package/dist/client/signals-globals-runtime.d.ts +2 -0
- package/dist/client/signals-globals-runtime.js +66 -0
- package/dist/client/signals-handler-runtime.d.ts +2 -0
- package/dist/client/signals-handler-runtime.js +80 -0
- package/dist/client/signals-head-runtime.d.ts +2 -0
- package/dist/client/signals-head-runtime.js +92 -0
- package/dist/client/signals-helpers-runtime.d.ts +2 -0
- package/dist/client/signals-helpers-runtime.js +137 -0
- package/dist/client/signals-host-runtime.d.ts +9 -0
- package/dist/client/signals-host-runtime.js +132 -0
- package/dist/client/signals-hydration-audit-runtime.d.ts +2 -0
- package/dist/client/signals-hydration-audit-runtime.js +209 -0
- package/dist/client/signals-hydration-runtime.d.ts +2 -0
- package/dist/client/signals-hydration-runtime.js +52 -0
- package/dist/client/signals-if-chain-runtime.d.ts +2 -0
- package/dist/client/signals-if-chain-runtime.js +283 -0
- package/dist/client/signals-if-runtime.d.ts +2 -0
- package/dist/client/signals-if-runtime.js +346 -0
- package/dist/client/signals-kept-runtime.d.ts +2 -0
- package/dist/client/signals-kept-runtime.js +62 -0
- package/dist/client/signals-lazy-hydration-runtime.d.ts +2 -0
- package/dist/client/signals-lazy-hydration-runtime.js +133 -0
- package/dist/client/signals-lifecycle-runtime.d.ts +2 -0
- package/dist/client/signals-lifecycle-runtime.js +114 -0
- package/dist/client/signals-loop-component-remap-runtime.d.ts +2 -0
- package/dist/client/signals-loop-component-remap-runtime.js +66 -0
- package/dist/client/signals-loop-conditional-runtime.d.ts +2 -0
- package/dist/client/signals-loop-conditional-runtime.js +48 -0
- package/dist/client/signals-loop-row-runtime.d.ts +2 -0
- package/dist/client/signals-loop-row-runtime.js +41 -0
- package/dist/client/signals-manifest-hydration-runtime.d.ts +2 -0
- package/dist/client/signals-manifest-hydration-runtime.js +82 -0
- package/dist/client/signals-model-runtime.d.ts +2 -0
- package/dist/client/signals-model-runtime.js +156 -0
- package/dist/client/signals-mount-runtime.d.ts +1 -0
- package/dist/client/signals-mount-runtime.js +231 -0
- package/dist/client/signals-navigation-runtime.d.ts +2 -0
- package/dist/client/signals-navigation-runtime.js +198 -0
- package/dist/client/signals-optimistic-runtime.d.ts +2 -0
- package/dist/client/signals-optimistic-runtime.js +34 -0
- package/dist/client/signals-overlay-runtime.d.ts +2 -0
- package/dist/client/signals-overlay-runtime.js +352 -0
- package/dist/client/signals-pipe-runtime.d.ts +2 -0
- package/dist/client/signals-pipe-runtime.js +177 -0
- package/dist/client/signals-process-element-runtime.d.ts +1 -0
- package/dist/client/signals-process-element-runtime.js +696 -0
- package/dist/client/signals-proxy-runtime.d.ts +2 -0
- package/dist/client/signals-proxy-runtime.js +78 -0
- package/dist/client/signals-public-api-runtime.d.ts +1 -0
- package/dist/client/signals-public-api-runtime.js +120 -0
- package/dist/client/signals-query-runtime.d.ts +2 -0
- package/dist/client/signals-query-runtime.js +351 -0
- package/dist/client/signals-reactive-core-bootstrap-runtime.d.ts +1 -0
- package/dist/client/signals-reactive-core-bootstrap-runtime.js +30 -0
- package/dist/client/signals-reactive-runtime.d.ts +2 -0
- package/dist/client/signals-reactive-runtime.js +67 -0
- package/dist/client/signals-ref-runtime.d.ts +2 -0
- package/dist/client/signals-ref-runtime.js +33 -0
- package/dist/client/signals-scope-disposal-runtime.d.ts +2 -0
- package/dist/client/signals-scope-disposal-runtime.js +195 -0
- package/dist/client/signals-scope-traversal-runtime.d.ts +2 -0
- package/dist/client/signals-scope-traversal-runtime.js +42 -0
- package/dist/client/signals-show-runtime.d.ts +2 -0
- package/dist/client/signals-show-runtime.js +54 -0
- package/dist/client/signals-spa-load-control-runtime.d.ts +2 -0
- package/dist/client/signals-spa-load-control-runtime.js +42 -0
- package/dist/client/signals-spa-load-runtime.d.ts +2 -0
- package/dist/client/signals-spa-load-runtime.js +187 -0
- package/dist/client/signals-state-runtime.d.ts +2 -0
- package/dist/client/signals-state-runtime.js +125 -0
- package/dist/client/signals-storage-runtime.d.ts +2 -0
- package/dist/client/signals-storage-runtime.js +79 -0
- package/dist/client/signals-store-registry-runtime.d.ts +1 -0
- package/dist/client/signals-store-registry-runtime.js +461 -0
- package/dist/client/signals-style-runtime.d.ts +2 -0
- package/dist/client/signals-style-runtime.js +35 -0
- package/dist/client/signals-suspense-runtime.d.ts +2 -0
- package/dist/client/signals-suspense-runtime.js +59 -0
- package/dist/client/signals-timer-runtime.d.ts +2 -0
- package/dist/client/signals-timer-runtime.js +378 -0
- package/dist/client/signals-toast-runtime.d.ts +2 -0
- package/dist/client/signals-toast-runtime.js +206 -0
- package/dist/client/signals-tooltip-runtime.d.ts +2 -0
- package/dist/client/signals-tooltip-runtime.js +40 -0
- package/dist/client/signals-transition-group-runtime.d.ts +2 -0
- package/dist/client/signals-transition-group-runtime.js +92 -0
- package/dist/client/signals-websocket-runtime.d.ts +2 -0
- package/dist/client/signals-websocket-runtime.js +138 -0
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/pwa.js +3 -3
- package/dist/signals-context-runtime.d.ts +2 -0
- package/dist/signals-drawer-runtime.d.ts +2 -0
- package/dist/signals-host-runtime.d.ts +9 -0
- package/dist/signals-loop-conditional-runtime.d.ts +2 -0
- package/dist/signals-manifest-hydration-runtime.d.ts +2 -0
- package/dist/signals-optimistic-runtime.d.ts +2 -0
- package/dist/signals-overlay-runtime.d.ts +2 -0
- package/dist/signals-scope-disposal-runtime.d.ts +2 -0
- package/dist/signals-spa-load-control-runtime.d.ts +2 -0
- package/dist/signals-storage-runtime.d.ts +2 -0
- package/dist/signals.js +141 -9900
- package/dist/ssg.js +3 -3
- package/package.json +5 -5
- package/dist/chunk-0p9pwd61.js +0 -2
- package/dist/chunk-0zmv31nc.js +0 -2
- package/dist/chunk-28xtazwz.js +0 -2
- package/dist/chunk-2936t942.js +0 -2
- package/dist/chunk-29qwmthc.js +0 -2
- package/dist/chunk-323cxa69.js +0 -2
- package/dist/chunk-375zp0vr.js +0 -2
- package/dist/chunk-3w49r16x.js +0 -2
- package/dist/chunk-8bcvb86w.js +0 -2
- package/dist/chunk-8gmb3k1p.js +0 -2
- package/dist/chunk-a15yzfc6.js +0 -2
- package/dist/chunk-d4155ec5.js +0 -2
- package/dist/chunk-dd31q423.js +0 -2
- package/dist/chunk-f2q5bckn.js +0 -2
- package/dist/chunk-fhx35529.js +0 -2
- package/dist/chunk-h1y5q942.js +0 -2
- package/dist/chunk-h791c7sb.js +0 -2
- package/dist/chunk-h88jcr3k.js +0 -2
- package/dist/chunk-heq5c0gd.js +0 -2
- package/dist/chunk-j3b24e77.js +0 -2
- package/dist/chunk-jpck8nm5.js +0 -2
- package/dist/chunk-m4d99a9r.js +0 -2
- package/dist/chunk-ng2sdph7.js +0 -2
- package/dist/chunk-qs3p7sc6.js +0 -2
- package/dist/chunk-rchwwcxy.js +0 -2
- package/dist/chunk-rk4mttds.js +0 -2
- package/dist/chunk-rma3bv36.js +0 -2
- package/dist/chunk-rp5a91ak.js +0 -2
- package/dist/chunk-sp5x96rn.js +0 -2
- package/dist/chunk-t2mjeezd.js +0 -2
- package/dist/chunk-t61j834x.js +0 -2
- package/dist/chunk-v2vg5jqq.js +0 -2
- package/dist/chunk-vmfw4svt.js +0 -2
- package/dist/chunk-w6ecbk3y.js +0 -2
- package/dist/chunk-wbv6vjhm.js +0 -2
- package/dist/chunk-wfbr3txe.js +0 -2
- package/dist/chunk-wpnv0naj.js +0 -2
- package/dist/chunk-wwny5dk9.js +0 -2
- package/dist/chunk-x55avrcf.js +0 -2
- package/dist/chunk-yts2745t.js +0 -2
- package/dist/chunk-zah67v44.js +0 -2
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export const SIGNALS_EXPRESSION_COMPILER_RUNTIME = ` // Compiled expression functions, by parameter list and body. A binding was
|
|
2
|
+
// compiled with new Function on every evaluation: a page with a few hundred
|
|
3
|
+
// names in scope rebuilt a function of a few hundred parameters for every
|
|
4
|
+
// binding of every row, every time a row re-rendered. Opening a 386-message
|
|
5
|
+
// conversation took seven seconds in WebKit, the window frozen meanwhile.
|
|
6
|
+
// A Function built this way closes over nothing, so one can be reused.
|
|
7
|
+
const __stxCompiled = new Map();
|
|
8
|
+
function __stxCompile(params, body) {
|
|
9
|
+
const key = params.join(',') + '\\x01' + body;
|
|
10
|
+
let fn = __stxCompiled.get(key);
|
|
11
|
+
if (!fn) {
|
|
12
|
+
fn = new Function(...params, body);
|
|
13
|
+
// Bounded: expressions are finite per page, but SPA navigation adds more.
|
|
14
|
+
if (__stxCompiled.size >= 5000) __stxCompiled.clear();
|
|
15
|
+
__stxCompiled.set(key, fn);
|
|
16
|
+
}
|
|
17
|
+
return fn;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The names an expression mentions, by its text.
|
|
21
|
+
const __stxIdentifiers = new Map();
|
|
22
|
+
function __stxNamesIn(body) {
|
|
23
|
+
let names = __stxIdentifiers.get(body);
|
|
24
|
+
if (!names) {
|
|
25
|
+
names = Array.from(new Set(body.match(/[A-Za-z_$][\\w$]*/g) || []));
|
|
26
|
+
if (__stxIdentifiers.size >= 5000) __stxIdentifiers.clear();
|
|
27
|
+
__stxIdentifiers.set(body, names);
|
|
28
|
+
}
|
|
29
|
+
return names;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Compile an expression over just the names in scope it mentions.
|
|
33
|
+
//
|
|
34
|
+
// It was compiled over every name in scope and called with every value,
|
|
35
|
+
// read through the auto-unwrap proxy. Reading a signal subscribes the
|
|
36
|
+
// running effect, so every binding depended on every signal on the page:
|
|
37
|
+
// changing one unrelated value re-ran every binding of every row. The proxy
|
|
38
|
+
// also tested each signal against the expression with fresh regexes. Now an
|
|
39
|
+
// expression sees, reads and subscribes to what it names; a mention inside
|
|
40
|
+
// a string only widens that, never narrows it.
|
|
41
|
+
function __stxCompileScoped(scope, extraParams, body) {
|
|
42
|
+
const keys = [];
|
|
43
|
+
const names = __stxNamesIn(body);
|
|
44
|
+
for (let i = 0; i < names.length; i++) {
|
|
45
|
+
if (Object.prototype.propertyIsEnumerable.call(scope, names[i])) keys.push(names[i]);
|
|
46
|
+
}
|
|
47
|
+
const fn = __stxCompile(extraParams.length ? keys.concat(extraParams) : keys, body);
|
|
48
|
+
// The cache keys on the parameter list, so a function always has these keys.
|
|
49
|
+
fn.__stxKeys = keys;
|
|
50
|
+
return fn;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function __stxArgs(fn, scope) {
|
|
54
|
+
const keys = fn.__stxKeys;
|
|
55
|
+
const args = new Array(keys.length);
|
|
56
|
+
for (let i = 0; i < keys.length; i++) args[i] = scope[keys[i]];
|
|
57
|
+
return args;
|
|
58
|
+
}
|
|
59
|
+
`;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Scope lookup and expression evaluation for the generated client runtime. */
|
|
2
|
+
export declare const SIGNALS_EXPRESSION_RUNTIME = " let componentScope = { $refs: {} };\n\n // Current element being processed (for scope lookup)\n let currentElement = null;\n\n function findElementScope(el) {\n let current = el;\n while (current && current !== document) {\n // Check element-local scope first (from stx.mount())\n if (current.__stx_scope) {\n return current.__stx_scope;\n }\n if (current.hasAttribute && current.hasAttribute('data-stx-scope')) {\n const scopeId = current.getAttribute('data-stx-scope');\n if (window.stx._scopes && window.stx._scopes[scopeId]) {\n return window.stx._scopes[scopeId];\n }\n }\n current = current.parentElement || current.parentNode;\n }\n return null;\n }\n\n function toValue(expr, el, enableAutoUnwrap = true, extraScope = {}) {\n try {\n // Skip placeholder expressions like __TITLE__ (build-time placeholders)\n if (/^__[A-Z_]+__$/.test(expr.trim())) {\n return expr;\n }\n // First try component-level scope\n const elementScope = findElementScope(el || currentElement);\n const baseScope = { ...globalHelpers, ...componentScope, ...(elementScope || {}), ...extraScope };\n\n // Check for pipe syntax (Feature #2)\n const pipeResult = parsePipeExpression(expr, baseScope);\n if (pipeResult) {\n // Use auto-unwrap proxy for pipe expressions\n const unwrapScope = enableAutoUnwrap\n ? createAutoUnwrapProxy(baseScope, function(prop) {\n if (typeof prop !== 'string') return false;\n return expressionCallsSignal(expr, prop)\n || expressionUsesSignalApi(expr, prop);\n })\n : baseScope;\n const piped = executePipeExpression(pipeResult.valueExpr, pipeResult.pipes, unwrapScope);\n return (piped && typeof piped === 'function' && (piped._isSignal || piped._isDerived)) ? piped() : piped;\n }\n\n // Use auto-unwrap proxy if enabled (Feature #1)\n const scope = enableAutoUnwrap\n ? createAutoUnwrapProxy(baseScope, function(prop) {\n if (typeof prop !== 'string') return false;\n return expressionCallsSignal(expr, prop)\n || expressionUsesSignalApi(expr, prop);\n })\n : baseScope;\n const fn = __stxCompileScoped(baseScope, [], 'return ' + expr);\n const result = fn(...__stxArgs(fn, scope));\n // Post-eval unwrap \u2014 see evalAttrExpr note for the reason.\n return (result && typeof result === 'function' && (result._isSignal || result._isDerived)) ? result() : result;\n }\ncatch (e) {\n if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Expression error:', expr, e);\n return '';\n }\n }\n";
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export const SIGNALS_EXPRESSION_RUNTIME = ` let componentScope = { $refs: {} };
|
|
2
|
+
|
|
3
|
+
// Current element being processed (for scope lookup)
|
|
4
|
+
let currentElement = null;
|
|
5
|
+
|
|
6
|
+
function findElementScope(el) {
|
|
7
|
+
let current = el;
|
|
8
|
+
while (current && current !== document) {
|
|
9
|
+
// Check element-local scope first (from stx.mount())
|
|
10
|
+
if (current.__stx_scope) {
|
|
11
|
+
return current.__stx_scope;
|
|
12
|
+
}
|
|
13
|
+
if (current.hasAttribute && current.hasAttribute('data-stx-scope')) {
|
|
14
|
+
const scopeId = current.getAttribute('data-stx-scope');
|
|
15
|
+
if (window.stx._scopes && window.stx._scopes[scopeId]) {
|
|
16
|
+
return window.stx._scopes[scopeId];
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
current = current.parentElement || current.parentNode;
|
|
20
|
+
}
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function toValue(expr, el, enableAutoUnwrap = true, extraScope = {}) {
|
|
25
|
+
try {
|
|
26
|
+
// Skip placeholder expressions like __TITLE__ (build-time placeholders)
|
|
27
|
+
if (/^__[A-Z_]+__$/.test(expr.trim())) {
|
|
28
|
+
return expr;
|
|
29
|
+
}
|
|
30
|
+
// First try component-level scope
|
|
31
|
+
const elementScope = findElementScope(el || currentElement);
|
|
32
|
+
const baseScope = { ...globalHelpers, ...componentScope, ...(elementScope || {}), ...extraScope };
|
|
33
|
+
|
|
34
|
+
// Check for pipe syntax (Feature #2)
|
|
35
|
+
const pipeResult = parsePipeExpression(expr, baseScope);
|
|
36
|
+
if (pipeResult) {
|
|
37
|
+
// Use auto-unwrap proxy for pipe expressions
|
|
38
|
+
const unwrapScope = enableAutoUnwrap
|
|
39
|
+
? createAutoUnwrapProxy(baseScope, function(prop) {
|
|
40
|
+
if (typeof prop !== 'string') return false;
|
|
41
|
+
return expressionCallsSignal(expr, prop)
|
|
42
|
+
|| expressionUsesSignalApi(expr, prop);
|
|
43
|
+
})
|
|
44
|
+
: baseScope;
|
|
45
|
+
const piped = executePipeExpression(pipeResult.valueExpr, pipeResult.pipes, unwrapScope);
|
|
46
|
+
return (piped && typeof piped === 'function' && (piped._isSignal || piped._isDerived)) ? piped() : piped;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Use auto-unwrap proxy if enabled (Feature #1)
|
|
50
|
+
const scope = enableAutoUnwrap
|
|
51
|
+
? createAutoUnwrapProxy(baseScope, function(prop) {
|
|
52
|
+
if (typeof prop !== 'string') return false;
|
|
53
|
+
return expressionCallsSignal(expr, prop)
|
|
54
|
+
|| expressionUsesSignalApi(expr, prop);
|
|
55
|
+
})
|
|
56
|
+
: baseScope;
|
|
57
|
+
const fn = __stxCompileScoped(baseScope, [], 'return ' + expr);
|
|
58
|
+
const result = fn(...__stxArgs(fn, scope));
|
|
59
|
+
// Post-eval unwrap \u2014 see evalAttrExpr note for the reason.
|
|
60
|
+
return (result && typeof result === 'function' && (result._isSignal || result._isDerived)) ? result() : result;
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Expression error:', expr, e);
|
|
64
|
+
return '';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
`;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
export function signalsFetchRuntime(readHydratedDataSource, clearServerDataSource) {
|
|
2
|
+
return ` // ==========================================================================
|
|
3
|
+
// Declarative Data Fetching (Feature #6 - useFetch)
|
|
4
|
+
// ==========================================================================
|
|
5
|
+
|
|
6
|
+
var readHydratedData = ${readHydratedDataSource};
|
|
7
|
+
var clearServerData = ${clearServerDataSource};
|
|
8
|
+
|
|
9
|
+
function useFetch(urlOrFn, options = {}) {
|
|
10
|
+
const hydrated = readHydratedData(options.key, options.hydrate !== false, options.transform);
|
|
11
|
+
const initial = hydrated ? hydrated.data : (options.initialData ?? null);
|
|
12
|
+
const data = state(initial);
|
|
13
|
+
// Starts false when nothing will be requested. It used to start true
|
|
14
|
+
// unconditionally while the only thing clearing it was the fetch that
|
|
15
|
+
// immediate:false suppresses \u2014 so the documented way to declare a deferred
|
|
16
|
+
// request produced a composable stuck loading forever, which is exactly the
|
|
17
|
+
// case where a template is most likely driving a spinner off it (#1818).
|
|
18
|
+
const immediate = options.immediate !== false && !hydrated;
|
|
19
|
+
const loading = state(immediate);
|
|
20
|
+
// Any request in flight, background ones included. loading answers "is
|
|
21
|
+
// there nothing to show yet"; isFetching answers "is a request open" \u2014 and
|
|
22
|
+
// a background refresh is the case where those two stop agreeing (#1929).
|
|
23
|
+
const isFetching = state(immediate);
|
|
24
|
+
const error = state(hydrated ? (hydrated.error || null) : null);
|
|
25
|
+
if (options.suspense) registerSuspense(loading, error);
|
|
26
|
+
|
|
27
|
+
// A superseded or unmounted request must not resolve into a torn-down
|
|
28
|
+
// scope. Each run gets its own AbortController; a newer run (refetch or a
|
|
29
|
+
// reactive URL change) aborts the one before it, and onDestroy aborts the
|
|
30
|
+
// last in-flight one. State writes are guarded on signal.aborted (#1871).
|
|
31
|
+
let __stxAbort = null;
|
|
32
|
+
|
|
33
|
+
// runOptions: { background: true } refreshes data WITHOUT touching loading
|
|
34
|
+
// or clearing the current error, so a poll cannot flash a spinner or blank
|
|
35
|
+
// an error message that is still true. Everything already on screen stays
|
|
36
|
+
// there until the new response actually lands (#1929).
|
|
37
|
+
const fetchData = async (runOptions) => {
|
|
38
|
+
const background = !!(runOptions && runOptions.background);
|
|
39
|
+
if (__stxAbort) __stxAbort.abort();
|
|
40
|
+
__stxAbort = (typeof AbortController !== 'undefined') ? new AbortController() : null;
|
|
41
|
+
const __signal = __stxAbort ? __stxAbort.signal : undefined;
|
|
42
|
+
if (!background) loading.set(true);
|
|
43
|
+
isFetching.set(true);
|
|
44
|
+
if (!background) error.set(null);
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
const url = typeof urlOrFn === 'function' ? urlOrFn() : urlOrFn;
|
|
48
|
+
if (!url) {
|
|
49
|
+
if (!background) loading.set(false);
|
|
50
|
+
isFetching.set(false);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const fetchOptions = {
|
|
55
|
+
method: options.method || 'GET',
|
|
56
|
+
headers: {
|
|
57
|
+
'Content-Type': 'application/json',
|
|
58
|
+
...__stxHeaders(options.headers)
|
|
59
|
+
},
|
|
60
|
+
signal: __signal
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
if (options.body) {
|
|
64
|
+
fetchOptions.body = typeof options.body === 'string'
|
|
65
|
+
? options.body
|
|
66
|
+
: JSON.stringify(options.body);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const response = await __stxFetch('useFetch', url, fetchOptions);
|
|
70
|
+
if (__signal && __signal.aborted) return;
|
|
71
|
+
|
|
72
|
+
if (!response.ok) throw await __stxHttpError(response);
|
|
73
|
+
|
|
74
|
+
const result = await response.json();
|
|
75
|
+
if (__signal && __signal.aborted) return;
|
|
76
|
+
|
|
77
|
+
// Apply transform if provided
|
|
78
|
+
const transformed = options.transform ? options.transform(result) : result;
|
|
79
|
+
data.set(transformed);
|
|
80
|
+
// A background run did not clear the error up front, so a recovery has
|
|
81
|
+
// to clear it here \u2014 otherwise the first failed poll would leave the
|
|
82
|
+
// message on screen for the life of the page.
|
|
83
|
+
if (background) error.set(null);
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
// A superseded/unmounted request rejects with AbortError \u2014 expected,
|
|
87
|
+
// not a failure to surface. The run that superseded it owns the state.
|
|
88
|
+
if (e && e.name === 'AbortError') return;
|
|
89
|
+
console.error('[STX] useFetch error:', e);
|
|
90
|
+
// Store Error objects (not just messages) so consumers can use
|
|
91
|
+
// .message, .stack, instanceof Error. Matches the composable's
|
|
92
|
+
// shape; pinned by use-fetch-parity.test.ts (#1726).
|
|
93
|
+
error.set(e instanceof Error ? e : new Error(String(e)));
|
|
94
|
+
if (options.onError) options.onError(e);
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
// If a newer run (or onDestroy) aborted this one, that run owns loading.
|
|
98
|
+
if (!__signal || !__signal.aborted) {
|
|
99
|
+
if (!background) loading.set(false);
|
|
100
|
+
isFetching.set(false);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// A reactive URL drives its own fetching: effect() runs eagerly on creation,
|
|
106
|
+
// so the first run IS the mount fetch. Registering onMount as well issued
|
|
107
|
+
// two requests for every function URL (#1818).
|
|
108
|
+
if (typeof urlOrFn === 'function') {
|
|
109
|
+
var firstUrlRun = true;
|
|
110
|
+
effect(() => {
|
|
111
|
+
const url = urlOrFn();
|
|
112
|
+
if (!url) return;
|
|
113
|
+
// Honour immediate:false for the FIRST evaluation only. A later change
|
|
114
|
+
// to the URL is a new request the caller asked for by changing it, not
|
|
115
|
+
// the initial one they deferred.
|
|
116
|
+
if (firstUrlRun) {
|
|
117
|
+
firstUrlRun = false;
|
|
118
|
+
if (!immediate) return;
|
|
119
|
+
}
|
|
120
|
+
fetchData();
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
else if (immediate) {
|
|
124
|
+
onMount(fetchData);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Abort an in-flight request when the owning scope is destroyed, so its
|
|
128
|
+
// resolution can't write into a torn-down component (#1871).
|
|
129
|
+
if (typeof onDestroy === 'function') onDestroy(function() { if (__stxAbort) __stxAbort.abort(); });
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
data,
|
|
133
|
+
loading,
|
|
134
|
+
isFetching,
|
|
135
|
+
error,
|
|
136
|
+
refetch: fetchData,
|
|
137
|
+
// Convenience getters
|
|
138
|
+
get isLoading() { return loading(); },
|
|
139
|
+
get hasError() { return !!error(); },
|
|
140
|
+
get isEmpty() { return !loading() && !data(); }
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
`;
|
|
144
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Shared HTTP transport, hooks, errors, and CSRF support for the generated client runtime. */
|
|
2
|
+
export declare const SIGNALS_FETCH_TRANSPORT_RUNTIME = " // Short, ref-free repr of a value for the mutation log (so the buffer holds no\n // live references and big objects don't bloat it).\n function __stxShort(v) {\n try {\n if (typeof v === 'string') return v.length > 40 ? (v.slice(0, 40) + '\u2026') : v;\n if (v === null || typeof v !== 'object') return v;\n var s = JSON.stringify(v);\n return s.length > 60 ? (s.slice(0, 60) + '\u2026') : s;\n } catch (e) { return '[unserializable]'; }\n }\n // Wraps fetch with timing + a timeline record (the data layer's queries).\n // Turn a non-ok Response into an Error, reading the body FIRST.\n //\n // Every data primitive threw a synthesized 'HTTP nnn: statusText' before\n // touching the body, so whatever the server actually said \u2014 a validation\n // map, a rate-limit reason, an auth message \u2014 was unreachable from any stx\n // primitive, with no escape hatch (stacksjs/stx#1848). That is the single\n // most cited reason an app keeps writing raw fetch() calls.\n //\n // The body is attached rather than only interpolated: err.data is what a\n // caller needs to render field errors, and err.status is what it needs to\n // tell 401 from 500 without parsing the message.\n function __stxRawBody(body) {\n return (typeof FormData !== 'undefined' && body instanceof FormData)\n || (typeof Blob !== 'undefined' && body instanceof Blob)\n || (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams)\n || (typeof ArrayBuffer !== 'undefined' && (body instanceof ArrayBuffer || ArrayBuffer.isView(body)));\n }\n\n async function __stxHttpError(response) {\n var body = null;\n var text = '';\n try { text = await response.text(); } catch (e) { text = ''; }\n if (text) {\n try { body = JSON.parse(text); } catch (e) { body = text; }\n }\n var detail = '';\n if (body && typeof body === 'object') detail = body.message || body.error || '';\n else if (typeof body === 'string') detail = body.slice(0, 200);\n var message = 'HTTP ' + response.status;\n if (response.statusText) message += ': ' + response.statusText;\n if (detail) message += ' - ' + detail;\n var err = new Error(message);\n err.status = response.status;\n err.statusText = response.statusText;\n err.data = body;\n err.response = response;\n return err;\n }\n\n // One place an app can reach the data layer. Every stx data primitive goes\n // through __stxFetch, the only fetch call in this runtime, so a single pair\n // of hooks covers useFetch, useQuery and useMutation (#1855).\n //\n // Without it there is no way to attach an Authorization header or notice a\n // 401 in one place, which is the reason an app keeps hand-written fetch\n // calls sitting next to the primitives that were meant to replace them.\n //\n // Hooks mutate the context they are handed and their return value is\n // ignored \u2014 the ofetch shape most people will already know. Throwing from a\n // hook fails the request, which is what a token-refresh flow wants.\n var __stxFetchHooks = { onRequest: null, onResponse: null, onResponseError: null };\n\n // Double-submit CSRF, echoed for every same-origin unsafe request. A server\n // using the pattern (Stacks does, by default, on every POST/PUT/PATCH/DELETE)\n // plants a readable cookie and rejects any unsafe request whose header does\n // not repeat it. Nothing here repeated it, so a form posting through\n // useMutation - or the framework's own CMS form block - got 403 \"CSRF token\n // mismatch\" on a stock install. The same thing axios does for XSRF-TOKEN.\n // Only same-origin: the token must never leave for another host.\n var __stxCsrf = { cookie: 'X-CSRF-Token', header: 'X-CSRF-Token' };\n\n function __stxCookie(name) {\n if (typeof document === 'undefined' || !document.cookie) return null;\n var parts = document.cookie.split(';');\n for (var i = 0; i < parts.length; i++) {\n var at = parts[i].indexOf('=');\n if (at === -1) continue;\n if (parts[i].slice(0, at).trim() !== name) continue;\n var value = parts[i].slice(at + 1).trim();\n try { return value ? decodeURIComponent(value) : null; } catch (e) { return value || null; }\n }\n return null;\n }\n\n // Whether this request should carry the token: unsafe, and same-origin.\n function __stxWantsCsrf(url, opts) {\n if (!__stxCsrf) return false;\n var method = String((opts && opts.method) || 'GET').toUpperCase();\n if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return false;\n // A path is same-origin by definition; only an absolute URL needs its\n // origin compared, and one that cannot be parsed is not trusted.\n var target = String(url);\n if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.slice(0, 2) === '//') {\n if (typeof location === 'undefined') return false;\n try {\n if (new URL(target).origin !== location.origin) return false;\n } catch (e) { return false; }\n }\n return true;\n }\n\n // Fetch the cookie before the first unsafe request, when the page did not\n // bring one. A page served from a CDN cache cannot: the edge strips\n // Set-Cookie from a cached response, or it would hand one visitor's token to\n // everyone. So the only pages that could post a form were the ones nobody\n // cached. `csrf.prime` names a same-origin GET that sets the cookie (any\n // safe Stacks route does); one request, shared by concurrent callers, and\n // only when the cookie is missing.\n var __stxCsrfPriming = null;\n async function __stxPrimeCsrf(url, opts) {\n if (!__stxCsrf || !__stxCsrf.prime || !__stxWantsCsrf(url, opts)) return;\n if (__stxCookie(__stxCsrf.cookie)) return;\n if (!__stxCsrfPriming) {\n __stxCsrfPriming = fetch(__stxCsrf.prime, { credentials: 'same-origin', headers: { Accept: 'application/json' } })\n .then(function () {}, function () {})\n .then(function () { __stxCsrfPriming = null; });\n }\n await __stxCsrfPriming;\n }\n\n function __stxApplyCsrf(url, opts) {\n if (!__stxWantsCsrf(url, opts)) return;\n var token = __stxCookie(__stxCsrf.cookie);\n if (!token) return;\n var headers = __stxHeaders(opts.headers);\n var wanted = __stxCsrf.header.toLowerCase();\n for (var key in headers) {\n // A token the caller set on purpose wins.\n if (key.toLowerCase() === wanted) return;\n }\n headers[__stxCsrf.header] = token;\n opts.headers = headers;\n }\n\n function configureFetch(cfg) {\n cfg = cfg || {};\n // Unlike the hooks below, CSRF settings persist unless named: an app that\n // installs an Authorization hook has not asked to stop sending the token.\n // `csrf: false` turns it off; `{ cookie, header }` renames either side.\n if (Object.prototype.hasOwnProperty.call(cfg, 'csrf')) {\n __stxCsrf = cfg.csrf === false || cfg.csrf === null\n ? null\n : { cookie: (cfg.csrf && cfg.csrf.cookie) || 'X-CSRF-Token', header: (cfg.csrf && (cfg.csrf.header || cfg.csrf.cookie)) || 'X-CSRF-Token', prime: (cfg.csrf && typeof cfg.csrf.prime === 'string' && cfg.csrf.prime) || null };\n }\n // Replace rather than stack: a module re-evaluated by hot reload or by a\n // SPA script re-run must not end up with the same interceptor installed\n // twice, sending two Authorization headers or counting a 401 twice.\n __stxFetchHooks.onRequest = typeof cfg.onRequest === 'function' ? cfg.onRequest : null;\n __stxFetchHooks.onResponse = typeof cfg.onResponse === 'function' ? cfg.onResponse : null;\n // Fires for a non-ok response and for a thrown fetch (network error). If it\n // returns a Response, that Response replaces the original \u2014 this is how a\n // 401 -> refresh -> retry is expressed once instead of per call site. The\n // retry itself belongs to the hook: it should refresh the token and re-issue\n // the request with a plain fetch() (not this data layer) so it does not\n // re-enter the hook and loop. Returning nothing lets the error stand.\n __stxFetchHooks.onResponseError = typeof cfg.onResponseError === 'function' ? cfg.onResponseError : null;\n }\n\n // headers may be a function, so it can be evaluated per request rather than\n // captured once \u2014 a token that changes between calls. Object spread over a\n // function copies no own enumerable properties, so passing one used to\n // contribute nothing at all, in silence.\n function __stxHeaders(h) {\n return (typeof h === 'function' ? h() : h) || {};\n }\n\n async function __stxFetch(source, url, opts) {\n var t0 = __stxDevtoolsNow();\n opts = opts || {};\n // Before the hooks, so an onRequest hook sees (and may override) it.\n await __stxPrimeCsrf(url, opts);\n __stxApplyCsrf(url, opts);\n if (__stxFetchHooks.onRequest) {\n // Normalised first so a hook can write ctx.options.headers.Authorization\n // without having to create the bag itself.\n opts.headers = __stxHeaders(opts.headers);\n var reqCtx = { source: source, url: String(url), options: opts };\n await __stxFetchHooks.onRequest(reqCtx);\n // Reassignable, so a hook can prefix a baseURL or swap the options\n // wholesale instead of only mutating them.\n if (reqCtx.url) url = reqCtx.url;\n opts = reqCtx.options || opts;\n }\n var method = (opts && opts.method) || 'GET';\n // A hook may hand back a Response to use in place of the original. Anything\n // else (a truthy non-Response, undefined) leaves the outcome unchanged.\n function __stxIsResponse(v) { return !!v && typeof v.ok === 'boolean'; }\n try {\n var r = await fetch(url, opts);\n __stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: r.status, ok: r.ok, ms: __stxDevtoolsNow() - t0 });\n if (__stxFetchHooks.onResponse) {\n await __stxFetchHooks.onResponse({ source: source, url: String(url), options: opts, response: r });\n }\n if (!r.ok && __stxFetchHooks.onResponseError) {\n var recovered = await __stxFetchHooks.onResponseError({ source: source, url: String(url), options: opts, response: r, error: null });\n if (__stxIsResponse(recovered)) {\n __stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: recovered.status, ok: recovered.ok, retried: true, ms: __stxDevtoolsNow() - t0 });\n return recovered;\n }\n }\n return r;\n } catch (e) {\n __stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: 0, ok: false, error: String((e && e.message) || e), ms: __stxDevtoolsNow() - t0 });\n // A network-level failure (no Response) also reaches the hook, so a retry\n // can cover a dropped connection, not only an auth status.\n if (__stxFetchHooks.onResponseError) {\n var recoveredErr = await __stxFetchHooks.onResponseError({ source: source, url: String(url), options: opts, response: null, error: e });\n if (__stxIsResponse(recoveredErr)) {\n __stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: recoveredErr.status, ok: recoveredErr.ok, retried: true, ms: __stxDevtoolsNow() - t0 });\n return recoveredErr;\n }\n }\n throw e;\n }\n }";
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
export const SIGNALS_FETCH_TRANSPORT_RUNTIME = ` // Short, ref-free repr of a value for the mutation log (so the buffer holds no
|
|
2
|
+
// live references and big objects don't bloat it).
|
|
3
|
+
function __stxShort(v) {
|
|
4
|
+
try {
|
|
5
|
+
if (typeof v === 'string') return v.length > 40 ? (v.slice(0, 40) + '\u2026') : v;
|
|
6
|
+
if (v === null || typeof v !== 'object') return v;
|
|
7
|
+
var s = JSON.stringify(v);
|
|
8
|
+
return s.length > 60 ? (s.slice(0, 60) + '\u2026') : s;
|
|
9
|
+
} catch (e) { return '[unserializable]'; }
|
|
10
|
+
}
|
|
11
|
+
// Wraps fetch with timing + a timeline record (the data layer's queries).
|
|
12
|
+
// Turn a non-ok Response into an Error, reading the body FIRST.
|
|
13
|
+
//
|
|
14
|
+
// Every data primitive threw a synthesized 'HTTP nnn: statusText' before
|
|
15
|
+
// touching the body, so whatever the server actually said \u2014 a validation
|
|
16
|
+
// map, a rate-limit reason, an auth message \u2014 was unreachable from any stx
|
|
17
|
+
// primitive, with no escape hatch (stacksjs/stx#1848). That is the single
|
|
18
|
+
// most cited reason an app keeps writing raw fetch() calls.
|
|
19
|
+
//
|
|
20
|
+
// The body is attached rather than only interpolated: err.data is what a
|
|
21
|
+
// caller needs to render field errors, and err.status is what it needs to
|
|
22
|
+
// tell 401 from 500 without parsing the message.
|
|
23
|
+
function __stxRawBody(body) {
|
|
24
|
+
return (typeof FormData !== 'undefined' && body instanceof FormData)
|
|
25
|
+
|| (typeof Blob !== 'undefined' && body instanceof Blob)
|
|
26
|
+
|| (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams)
|
|
27
|
+
|| (typeof ArrayBuffer !== 'undefined' && (body instanceof ArrayBuffer || ArrayBuffer.isView(body)));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function __stxHttpError(response) {
|
|
31
|
+
var body = null;
|
|
32
|
+
var text = '';
|
|
33
|
+
try { text = await response.text(); } catch (e) { text = ''; }
|
|
34
|
+
if (text) {
|
|
35
|
+
try { body = JSON.parse(text); } catch (e) { body = text; }
|
|
36
|
+
}
|
|
37
|
+
var detail = '';
|
|
38
|
+
if (body && typeof body === 'object') detail = body.message || body.error || '';
|
|
39
|
+
else if (typeof body === 'string') detail = body.slice(0, 200);
|
|
40
|
+
var message = 'HTTP ' + response.status;
|
|
41
|
+
if (response.statusText) message += ': ' + response.statusText;
|
|
42
|
+
if (detail) message += ' - ' + detail;
|
|
43
|
+
var err = new Error(message);
|
|
44
|
+
err.status = response.status;
|
|
45
|
+
err.statusText = response.statusText;
|
|
46
|
+
err.data = body;
|
|
47
|
+
err.response = response;
|
|
48
|
+
return err;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// One place an app can reach the data layer. Every stx data primitive goes
|
|
52
|
+
// through __stxFetch, the only fetch call in this runtime, so a single pair
|
|
53
|
+
// of hooks covers useFetch, useQuery and useMutation (#1855).
|
|
54
|
+
//
|
|
55
|
+
// Without it there is no way to attach an Authorization header or notice a
|
|
56
|
+
// 401 in one place, which is the reason an app keeps hand-written fetch
|
|
57
|
+
// calls sitting next to the primitives that were meant to replace them.
|
|
58
|
+
//
|
|
59
|
+
// Hooks mutate the context they are handed and their return value is
|
|
60
|
+
// ignored \u2014 the ofetch shape most people will already know. Throwing from a
|
|
61
|
+
// hook fails the request, which is what a token-refresh flow wants.
|
|
62
|
+
var __stxFetchHooks = { onRequest: null, onResponse: null, onResponseError: null };
|
|
63
|
+
|
|
64
|
+
// Double-submit CSRF, echoed for every same-origin unsafe request. A server
|
|
65
|
+
// using the pattern (Stacks does, by default, on every POST/PUT/PATCH/DELETE)
|
|
66
|
+
// plants a readable cookie and rejects any unsafe request whose header does
|
|
67
|
+
// not repeat it. Nothing here repeated it, so a form posting through
|
|
68
|
+
// useMutation - or the framework's own CMS form block - got 403 "CSRF token
|
|
69
|
+
// mismatch" on a stock install. The same thing axios does for XSRF-TOKEN.
|
|
70
|
+
// Only same-origin: the token must never leave for another host.
|
|
71
|
+
var __stxCsrf = { cookie: 'X-CSRF-Token', header: 'X-CSRF-Token' };
|
|
72
|
+
|
|
73
|
+
function __stxCookie(name) {
|
|
74
|
+
if (typeof document === 'undefined' || !document.cookie) return null;
|
|
75
|
+
var parts = document.cookie.split(';');
|
|
76
|
+
for (var i = 0; i < parts.length; i++) {
|
|
77
|
+
var at = parts[i].indexOf('=');
|
|
78
|
+
if (at === -1) continue;
|
|
79
|
+
if (parts[i].slice(0, at).trim() !== name) continue;
|
|
80
|
+
var value = parts[i].slice(at + 1).trim();
|
|
81
|
+
try { return value ? decodeURIComponent(value) : null; } catch (e) { return value || null; }
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Whether this request should carry the token: unsafe, and same-origin.
|
|
87
|
+
function __stxWantsCsrf(url, opts) {
|
|
88
|
+
if (!__stxCsrf) return false;
|
|
89
|
+
var method = String((opts && opts.method) || 'GET').toUpperCase();
|
|
90
|
+
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return false;
|
|
91
|
+
// A path is same-origin by definition; only an absolute URL needs its
|
|
92
|
+
// origin compared, and one that cannot be parsed is not trusted.
|
|
93
|
+
var target = String(url);
|
|
94
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.slice(0, 2) === '//') {
|
|
95
|
+
if (typeof location === 'undefined') return false;
|
|
96
|
+
try {
|
|
97
|
+
if (new URL(target).origin !== location.origin) return false;
|
|
98
|
+
} catch (e) { return false; }
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Fetch the cookie before the first unsafe request, when the page did not
|
|
104
|
+
// bring one. A page served from a CDN cache cannot: the edge strips
|
|
105
|
+
// Set-Cookie from a cached response, or it would hand one visitor's token to
|
|
106
|
+
// everyone. So the only pages that could post a form were the ones nobody
|
|
107
|
+
// cached. \`csrf.prime\` names a same-origin GET that sets the cookie (any
|
|
108
|
+
// safe Stacks route does); one request, shared by concurrent callers, and
|
|
109
|
+
// only when the cookie is missing.
|
|
110
|
+
var __stxCsrfPriming = null;
|
|
111
|
+
async function __stxPrimeCsrf(url, opts) {
|
|
112
|
+
if (!__stxCsrf || !__stxCsrf.prime || !__stxWantsCsrf(url, opts)) return;
|
|
113
|
+
if (__stxCookie(__stxCsrf.cookie)) return;
|
|
114
|
+
if (!__stxCsrfPriming) {
|
|
115
|
+
__stxCsrfPriming = fetch(__stxCsrf.prime, { credentials: 'same-origin', headers: { Accept: 'application/json' } })
|
|
116
|
+
.then(function () {}, function () {})
|
|
117
|
+
.then(function () { __stxCsrfPriming = null; });
|
|
118
|
+
}
|
|
119
|
+
await __stxCsrfPriming;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function __stxApplyCsrf(url, opts) {
|
|
123
|
+
if (!__stxWantsCsrf(url, opts)) return;
|
|
124
|
+
var token = __stxCookie(__stxCsrf.cookie);
|
|
125
|
+
if (!token) return;
|
|
126
|
+
var headers = __stxHeaders(opts.headers);
|
|
127
|
+
var wanted = __stxCsrf.header.toLowerCase();
|
|
128
|
+
for (var key in headers) {
|
|
129
|
+
// A token the caller set on purpose wins.
|
|
130
|
+
if (key.toLowerCase() === wanted) return;
|
|
131
|
+
}
|
|
132
|
+
headers[__stxCsrf.header] = token;
|
|
133
|
+
opts.headers = headers;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function configureFetch(cfg) {
|
|
137
|
+
cfg = cfg || {};
|
|
138
|
+
// Unlike the hooks below, CSRF settings persist unless named: an app that
|
|
139
|
+
// installs an Authorization hook has not asked to stop sending the token.
|
|
140
|
+
// \`csrf: false\` turns it off; \`{ cookie, header }\` renames either side.
|
|
141
|
+
if (Object.prototype.hasOwnProperty.call(cfg, 'csrf')) {
|
|
142
|
+
__stxCsrf = cfg.csrf === false || cfg.csrf === null
|
|
143
|
+
? null
|
|
144
|
+
: { cookie: (cfg.csrf && cfg.csrf.cookie) || 'X-CSRF-Token', header: (cfg.csrf && (cfg.csrf.header || cfg.csrf.cookie)) || 'X-CSRF-Token', prime: (cfg.csrf && typeof cfg.csrf.prime === 'string' && cfg.csrf.prime) || null };
|
|
145
|
+
}
|
|
146
|
+
// Replace rather than stack: a module re-evaluated by hot reload or by a
|
|
147
|
+
// SPA script re-run must not end up with the same interceptor installed
|
|
148
|
+
// twice, sending two Authorization headers or counting a 401 twice.
|
|
149
|
+
__stxFetchHooks.onRequest = typeof cfg.onRequest === 'function' ? cfg.onRequest : null;
|
|
150
|
+
__stxFetchHooks.onResponse = typeof cfg.onResponse === 'function' ? cfg.onResponse : null;
|
|
151
|
+
// Fires for a non-ok response and for a thrown fetch (network error). If it
|
|
152
|
+
// returns a Response, that Response replaces the original \u2014 this is how a
|
|
153
|
+
// 401 -> refresh -> retry is expressed once instead of per call site. The
|
|
154
|
+
// retry itself belongs to the hook: it should refresh the token and re-issue
|
|
155
|
+
// the request with a plain fetch() (not this data layer) so it does not
|
|
156
|
+
// re-enter the hook and loop. Returning nothing lets the error stand.
|
|
157
|
+
__stxFetchHooks.onResponseError = typeof cfg.onResponseError === 'function' ? cfg.onResponseError : null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// headers may be a function, so it can be evaluated per request rather than
|
|
161
|
+
// captured once \u2014 a token that changes between calls. Object spread over a
|
|
162
|
+
// function copies no own enumerable properties, so passing one used to
|
|
163
|
+
// contribute nothing at all, in silence.
|
|
164
|
+
function __stxHeaders(h) {
|
|
165
|
+
return (typeof h === 'function' ? h() : h) || {};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function __stxFetch(source, url, opts) {
|
|
169
|
+
var t0 = __stxDevtoolsNow();
|
|
170
|
+
opts = opts || {};
|
|
171
|
+
// Before the hooks, so an onRequest hook sees (and may override) it.
|
|
172
|
+
await __stxPrimeCsrf(url, opts);
|
|
173
|
+
__stxApplyCsrf(url, opts);
|
|
174
|
+
if (__stxFetchHooks.onRequest) {
|
|
175
|
+
// Normalised first so a hook can write ctx.options.headers.Authorization
|
|
176
|
+
// without having to create the bag itself.
|
|
177
|
+
opts.headers = __stxHeaders(opts.headers);
|
|
178
|
+
var reqCtx = { source: source, url: String(url), options: opts };
|
|
179
|
+
await __stxFetchHooks.onRequest(reqCtx);
|
|
180
|
+
// Reassignable, so a hook can prefix a baseURL or swap the options
|
|
181
|
+
// wholesale instead of only mutating them.
|
|
182
|
+
if (reqCtx.url) url = reqCtx.url;
|
|
183
|
+
opts = reqCtx.options || opts;
|
|
184
|
+
}
|
|
185
|
+
var method = (opts && opts.method) || 'GET';
|
|
186
|
+
// A hook may hand back a Response to use in place of the original. Anything
|
|
187
|
+
// else (a truthy non-Response, undefined) leaves the outcome unchanged.
|
|
188
|
+
function __stxIsResponse(v) { return !!v && typeof v.ok === 'boolean'; }
|
|
189
|
+
try {
|
|
190
|
+
var r = await fetch(url, opts);
|
|
191
|
+
__stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: r.status, ok: r.ok, ms: __stxDevtoolsNow() - t0 });
|
|
192
|
+
if (__stxFetchHooks.onResponse) {
|
|
193
|
+
await __stxFetchHooks.onResponse({ source: source, url: String(url), options: opts, response: r });
|
|
194
|
+
}
|
|
195
|
+
if (!r.ok && __stxFetchHooks.onResponseError) {
|
|
196
|
+
var recovered = await __stxFetchHooks.onResponseError({ source: source, url: String(url), options: opts, response: r, error: null });
|
|
197
|
+
if (__stxIsResponse(recovered)) {
|
|
198
|
+
__stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: recovered.status, ok: recovered.ok, retried: true, ms: __stxDevtoolsNow() - t0 });
|
|
199
|
+
return recovered;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return r;
|
|
203
|
+
} catch (e) {
|
|
204
|
+
__stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: 0, ok: false, error: String((e && e.message) || e), ms: __stxDevtoolsNow() - t0 });
|
|
205
|
+
// A network-level failure (no Response) also reaches the hook, so a retry
|
|
206
|
+
// can cover a dropped connection, not only an auth status.
|
|
207
|
+
if (__stxFetchHooks.onResponseError) {
|
|
208
|
+
var recoveredErr = await __stxFetchHooks.onResponseError({ source: source, url: String(url), options: opts, response: null, error: e });
|
|
209
|
+
if (__stxIsResponse(recoveredErr)) {
|
|
210
|
+
__stxDevtoolsRecordQuery({ source: source, url: String(url), method: method, status: recoveredErr.status, ok: recoveredErr.ok, retried: true, ms: __stxDevtoolsNow() - t0 });
|
|
211
|
+
return recoveredErr;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
throw e;
|
|
215
|
+
}
|
|
216
|
+
}`;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Reactive list binding for the generated client runtime. */
|
|
2
|
+
export declare const SIGNALS_FOR_RUNTIME = " function bindFor(el, passedScope = componentScope, attrName = '@for') {\n if (el.__stx_for_bound) return;\n el.__stx_for_bound = true;\n const expr = el.getAttribute(attrName);\n // Support: \"item in list\", \"item, index in list\", \"(item, index) in list\"\n const match = expr.match(/^\\s*\\(?\\s*(\\w+)(?:\\s*,\\s*(\\w+))?\\s*\\)?\\s+(?:in|of)\\s+(.+)\\s*$/);\n\n if (!match) {\n console.warn('[STX] Invalid ' + attrName + ':', expr);\n return;\n }\n\n const [, itemName, indexName, listExpr] = match;\n let parent = el.parentNode;\n\n // Guard: if element has no parent, it's detached - skip processing\n if (!parent) {\n console.warn('[STX] bindFor: element has no parent, skipping');\n return;\n }\n\n const placeholder = stxHost.anchor('stx-for');\n const isTemplate = el.tagName === 'TEMPLATE';\n const componentSetupTemplates = [];\n if (!isTemplate && el.hasAttribute('data-stx-scope')) {\n const componentScopeId = el.getAttribute('data-stx-scope');\n const componentTemplateScopeId = el.getAttribute('data-stx-template-scope') || componentScopeId;\n let setupSibling = el.nextSibling;\n while (setupSibling) {\n const nextSetupSibling = setupSibling.nextSibling;\n if (setupSibling.nodeType === Node.TEXT_NODE && !(setupSibling.textContent || '').trim()) {\n setupSibling = nextSetupSibling;\n continue;\n }\n if (setupSibling.nodeType === Node.COMMENT_NODE) {\n setupSibling = nextSetupSibling;\n continue;\n }\n if (setupSibling.nodeType === Node.ELEMENT_NODE\n && setupSibling.tagName === 'SCRIPT'\n && setupSibling.hasAttribute('data-stx-scoped')\n && ((setupSibling.textContent || '').indexOf(componentScopeId) !== -1\n || (componentTemplateScopeId && (setupSibling.textContent || '').indexOf(componentTemplateScopeId) !== -1))) {\n componentSetupTemplates.push(stxHost.clone(setupSibling));\n stxHost.remove(setupSibling);\n setupSibling = nextSetupSibling;\n continue;\n }\n break;\n }\n }\n\n // Check if element also has @if / :if - need to handle together\n const ifExpr = el.getAttribute('@if') || el.getAttribute(':if');\n\n // Feature #3: Check for @loading and @empty siblings/content\n const loadingExpr = el.getAttribute('@loading');\n const emptyExpr = el.getAttribute('@empty');\n\n // Look for sibling elements with @for-loading or @for-empty\n let loadingTemplate = null;\n let emptyTemplate = null;\n\n // Check next siblings for @for-loading and @for-empty\n let sibling = el.nextElementSibling;\n while (sibling) {\n if (sibling.hasAttribute('@for-loading')) {\n loadingTemplate = stxHost.clone(sibling);\n loadingTemplate.removeAttribute('@for-loading');\n stxHost.remove(sibling);\n sibling = el.nextElementSibling;\n continue;\n }\n if (sibling.hasAttribute('@for-empty')) {\n emptyTemplate = stxHost.clone(sibling);\n emptyTemplate.removeAttribute('@for-empty');\n stxHost.remove(sibling);\n sibling = el.nextElementSibling;\n continue;\n }\n break;\n }\n\n // Capture the scope NOW before element is removed from DOM\n const capturedScope = findElementScope(el) || findElementScope(parent);\n\n stxHost.insert(parent, placeholder, el);\n // Component setup scripts execute while the server-rendered loop source is\n // still in the document. That source becomes a template, not a live\n // instance, so reclaim all registered scopes before removing it. Every\n // rendered iteration receives remapped setup scripts and fresh scopes.\n disposeSubtreeScopes(el);\n stxHost.remove(el);\n\n // Capture :key expression BEFORE removing the attribute\n const keyExpr = el.getAttribute(':key') || el.getAttribute('x-bind:key');\n\n // For <template> elements, use the content; otherwise clone the element\n let templateContent;\n if (isTemplate) {\n templateContent = el.content;\n deferRowConditionals(templateContent);\n }\nelse {\n // Before the source is cloned into the row template, so that clone does\n // not build the conditional elements either.\n deferRowConditionals(el);\n const wrapper = stxHost.clone(el);\n wrapper.removeAttribute('@for');\n wrapper.removeAttribute(':for');\n wrapper.removeAttribute('x-for');\n wrapper.removeAttribute('@loading');\n wrapper.removeAttribute('@empty');\n wrapper.removeAttribute(':key');\n wrapper.removeAttribute('x-bind:key');\n // Also remove @if / :if / x-if - we'll handle it inline\n if (ifExpr) { wrapper.removeAttribute('@if'); wrapper.removeAttribute(':if'); wrapper.removeAttribute('x-if'); }\n templateContent = wrapper;\n }\n\n let currentElements = [];\n // One entry per list item, each holding EVERY node that item rendered.\n // currentElements stays flat for transition snapshots, but the keyed\n // diff below must pair a key with all of its nodes: a template row\n // routinely yields several (an element plus its surrounding text nodes),\n // and indexing a flat list by key position then paired the wrong node\n // with each key, leaving the list rotated after an update.\n let currentGroups = [];\n let currentKeys = [];\n let loadingElement = null;\n let emptyElement = null;\n\n // A <template :for> can contain another structural directive. That\n // nested directive replaces its source node with a placeholder and owns\n // additional live siblings around that placeholder. Track an explicit\n // boundary for every template iteration so keyed reuse moves the complete\n // live range, including nodes created by nested :for / :if bindings.\n // Moving only the original cloned nodes pulled static siblings past the\n // nested range on the next outer update (header, then rows became rows,\n // then header).\n const liveGroupNodes = (group) => {\n if (!isTemplate || !group || group.length < 2) return group || [];\n const start = group[0];\n const end = group[group.length - 1];\n if (!start || !end || start.parentNode !== parent || end.parentNode !== parent)\n return group.filter(groupNode => groupNode && groupNode.parentNode === parent);\n\n const nodes = [];\n let currentNode = start;\n while (currentNode) {\n nodes.push(currentNode);\n if (currentNode === end) break;\n currentNode = currentNode.nextSibling;\n }\n return nodes;\n };\n\n const removeGroup = (group) => {\n const liveNodes = liveGroupNodes(group);\n const liveSet = new Set(liveNodes);\n liveNodes.forEach(e => { disposeSubtreeEffects(e); disposeSubtreeScopes(e); stxHost.remove(e); });\n group.forEach(groupNode => {\n if (liveSet.has(groupNode)) return;\n disposeSubtreeEffects(groupNode);\n disposeSubtreeScopes(groupNode);\n stxHost.remove(groupNode);\n });\n };\n\n const clearRenderedItems = () => {\n currentGroups.forEach(removeGroup);\n currentElements = [];\n currentGroups = [];\n currentKeys = [];\n };\n\n // Helper to evaluate with captured scope (auto-unwraps signals)\n // NOTE: This eagerly reads ALL signals in scope \u2014 use evalLazy inside effects\n // to avoid over-broad dependency tracking.\n const evalExpr = (expression, extraScope = {}) => {\n try {\n // Skip placeholder expressions like __TITLE__ (build-time placeholders)\n if (/^__[A-Z_]+__$/.test(expression.trim())) {\n return expression;\n }\n // Use passedScope instead of componentScope to preserve context through nested processing\n const scope = { ...globalHelpers, ...passedScope, ...(capturedScope || {}), ...extraScope };\n const unwrapScope = createAutoUnwrapProxy(scope, function(prop) {\n if (typeof prop !== 'string') return false;\n return expressionCallsSignal(expression, prop)\n || expressionUsesSignalApi(expression, prop);\n });\n const fn = __stxCompileScoped(scope, [], 'return ' + expression);\n return fn(...__stxArgs(fn, unwrapScope));\n }\ncatch (e) {\n if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Expression error:', expression, e);\n return '';\n }\n };\n\n // Lazy eval: uses with() so only variables ACTUALLY ACCESSED by the expression\n // trigger signal reads. This prevents unrelated signals (like modalOpen) from\n // being tracked as dependencies when we only care about the list signal.\n const evalLazy = (expression, extraScope = {}) => {\n try {\n if (/^__[A-Z_]+__$/.test(expression.trim())) return expression;\n const scope = { ...globalHelpers, ...passedScope, ...(capturedScope || {}), ...extraScope };\n const unwrapScope = createAutoUnwrapProxy(scope, function(prop) {\n if (typeof prop !== 'string') return false;\n return expressionCallsSignal(expression, prop)\n || expressionUsesSignalApi(expression, prop);\n });\n // Compiled over the names the expression mentions (__stxCompileScoped),\n // so only those are read and register as dependencies. It used with()\n // over the proxy, which JavaScriptCore resolves through proxy traps on\n // every identifier - 36x slower than V8 for a list of message rows.\n const fn = __stxCompileScoped(unwrapScope, [], 'return ' + expression + '');\n return fn(...__stxArgs(fn, unwrapScope));\n } catch (e) {\n if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Expression error:', expression, e);\n return '';\n }\n };\n\n // Helper to show loading state\n const showLoading = () => {\n hideLoading();\n hideEmpty();\n if (loadingTemplate) {\n loadingElement = stxHost.clone(loadingTemplate);\n stxHost.insert(parent, loadingElement, placeholder);\n }\n };\n\n // Helper to hide loading state\n const hideLoading = () => {\n if (loadingElement) {\n stxHost.remove(loadingElement);\n loadingElement = null;\n }\n };\n\n // Helper to show empty state\n const showEmpty = () => {\n hideLoading();\n hideEmpty();\n if (emptyTemplate) {\n emptyElement = stxHost.clone(emptyTemplate);\n stxHost.insert(parent, emptyElement, placeholder);\n const shownEmpty = emptyElement;\n shownEmpty.__stx_effect_disposers = trackEffects(function() { processElement(shownEmpty); });\n }\n };\n\n // Helper to hide empty state\n const hideEmpty = () => {\n if (emptyElement) {\n // A string @empty renders a text node, which has no subtree to dispose.\n if (emptyElement.nodeType === 1) disposeSubtreeEffects(emptyElement);\n stxHost.remove(emptyElement);\n emptyElement = null;\n }\n };\n\n // Helper: create DOM element(s) for a single list item.\n // The item is wrapped in a signal so bindings track it reactively. The pair\n // rides on the returned group, so reuse always reaches the signals the\n // bindings of THAT row actually read. A Map from key to signals could not:\n // two rows sharing a key overwrote each other in it, and the row that\n // reused the surviving entry was then bound to a signal nothing updated.\n const createItemElements = (item, index, key) => {\n const itemSignal = state(item);\n itemSignal._isStxLoopItem = true;\n const indexSignal = state(index);\n\n const itemScope = { ...globalHelpers, ...passedScope, ...(capturedScope || {}) };\n itemScope[itemName] = itemSignal;\n if (indexName) itemScope[indexName] = indexSignal;\n\n const elements = [];\n if (isTemplate) {\n elements.push(stxHost.anchor('stx-for-item-start'));\n Array.from(templateContent.childNodes).forEach(node => {\n const clone = stxHost.clone(node);\n if (clone.nodeType === 1) {\n // Structural directives need a live parent. Keep the iteration\n // scope on the clone until the keyed diff inserts it, then bind.\n clone.__stx_for_scope = itemScope;\n markLoopRow(clone, itemName, itemSignal);\n }\n elements.push(clone);\n });\n elements.push(stxHost.anchor('stx-for-item-end'));\n } else {\n const clone = stxHost.clone(templateContent);\n clone.__stx_for_scope = itemScope;\n markLoopRow(clone, itemName, itemSignal);\n elements.push(clone);\n componentSetupTemplates.forEach(function(setupTemplate) {\n elements.push(stxHost.clone(setupTemplate));\n });\n }\n remapForComponentScopes(elements);\n elements.__stx_signals = { item: itemSignal, index: indexSignal };\n return elements;\n };\n\n // Helper: compute key for an item\n const getItemKey = (item, index) => {\n if (!keyExpr) return String(index);\n try {\n const scope = { [itemName]: item };\n if (indexName) scope[indexName] = index;\n const fn = __stxCompile([itemName, indexName || '_idx'], 'return ' + keyExpr);\n return String(fn(item, index));\n } catch (e) {\n return String(index);\n }\n };\n\n effect(() => {\n parent = followPlaceholder(placeholder, parent);\n // Use evalLazy for the list expression \u2014 only tracks the list signal,\n // not every signal in the component scope. This prevents unrelated\n // signals (modalOpen, menuOpen, etc.) from triggering a full rebuild.\n // Check loading state if @loading attribute provided (Feature #3)\n if (loadingExpr) {\n const isLoading = evalLazy(loadingExpr);\n if (isLoading) {\n // Dispose scopes registered by items before they leave the DOM (#1727).\n clearRenderedItems();\n showLoading();\n return;\n }\n }\n\n hideLoading();\n\n // Evaluate list with LAZY tracking \u2014 only the list signal is tracked\n let list = evalLazy(listExpr);\n\n // Tolerate parens-on-signal in the list expression.\n // :for=\"x in store.signal\" --> works (bare-ref, auto-unwrapped)\n // :for=\"x in store.signal()\" --> silently iterated zero, because\n // the proxy unwraps the signal to\n // the array on access, then the\n // trailing call throws TypeError\n // which evalLazy's catch swallows.\n // Retry without the trailing parens so both forms succeed.\n //\n // This runtime is emitted as a TEMPLATE LITERAL, so every backslash here\n // must be DOUBLED to survive into the shipped string. A regex literal\n // crosses only that one layer (doubled escapes ship intact). A\n // new RegExp('...') string crosses a SECOND layer too \u2014 the browser's\n // string-literal parse strips the escapes again \u2014 collapsing the pattern\n // to a bare-letter match that never fires (stacksjs/stx#1748). So use a\n // regex literal, not new RegExp(string), for patterns with backslashes.\n var trailingParens = /\\(\\s*\\)\\s*$/;\n if (!Array.isArray(list) && trailingParens.test(listExpr)) {\n list = evalLazy(listExpr.replace(trailingParens, ''));\n }\n // Second-chance fallback: if the retry returned a signal /\n // derived function (the proxy failed to auto-unwrap, which\n // can happen when the resolved owning object lacks the\n // _isStxStore marker \u2014 e.g. ad-hoc objects, locally-imported\n // shapes), call it manually. Defensive: cheap when it would\n // already be an array, useful when the proxy missed.\n if (!Array.isArray(list) && typeof list === 'function' && (list._isSignal || list._isDerived)) {\n try { list = list(); } catch { /* swallow - the warning below surfaces it */ }\n }\n\n // If there's an @if condition, check it\n if (ifExpr) {\n const ifValue = evalLazy(ifExpr);\n if (!ifValue) {\n // Dispose scopes registered by items before they leave the DOM (#1727).\n clearRenderedItems();\n hideEmpty();\n return;\n }\n }\n\n if (!Array.isArray(list)) {\n // Silent return here used to mask a class of real misuse:\n // most often a signal call that threw mid-expression, or a\n // :for over undefined from a typo. One warn line saves a lot\n // of \"list rendered no rows despite the data being there\"\n // debugging cycles.\n //\n // Diagnostic: dump the scope identifiers so the caller can see\n // whether the expression's root identifier was in scope at all\n // (and if so, what type it was and whether it carried the\n // _isStxStore marker). Only fires on the warn path, which is\n // rare, so the extra Object.keys / spread cost is negligible.\n var diagScope;\n var rootName = '?';\n var rootInScope = true;\n var rootVal;\n try {\n var diagMerged = { ...globalHelpers, ...passedScope, ...(capturedScope || {}) };\n var firstIdent = listExpr.match(/^[A-Za-z_$][\\w$]*/);\n rootName = firstIdent ? firstIdent[0] : '?';\n rootInScope = Object.prototype.hasOwnProperty.call(diagMerged, rootName);\n rootVal = rootInScope ? diagMerged[rootName] : '<NOT-IN-SCOPE>';\n var rootKeys = (rootVal && typeof rootVal === 'object')\n ? Object.keys(rootVal).slice(0, 8).join(',')\n : '-';\n diagScope = '[root=' + rootName + ' inScope=' + rootInScope + ' type=' + (typeof rootVal) + ' isStxStore=' + !!(rootVal && rootVal._isStxStore) + ' keys=' + rootKeys + ']';\n }\n catch (_e) { diagScope = '[diag-error]'; rootInScope = true; }\n\n /*\n * Name the cause rather than guessing at it (stacksjs/stx#2051).\n *\n * This used to end with \"If this is a signal call, try the bare\n * reference\" every single time. In the most common failure the\n * identifier is not a signal at all -- it is a bare name the client\n * scope has never heard of, usually a declaration from a\n * script-server block, which :for cannot see because it is expanded\n * on the client. The hint sent people to the wrong layer: one app\n * read it, concluded the signals-and-:for pattern was unreliable, and\n * was rebuilt on hand-written getElementById wiring.\n *\n * The scope dump already answered the question -- inScope=false was\n * right there, ahead of the guess -- so lead with it, and keep the\n * signal advice for when the value really is a signal, which is the\n * one case where it applies.\n */\n var advice;\n if (!rootInScope) {\n advice = 'Nothing named ' + rootName + ' is in the client scope. A script-server declaration is not available here: :for is expanded on the client. '\n + 'Either wrap it in state() inside a script-client block, or iterate it with the server-side @foreach(' + rootName + ' as item).';\n }\n else if (typeof rootVal === 'function' && (rootVal._isSignal || rootVal._isDerived)) {\n advice = rootName + ' is a signal, so try the bare reference: ' + rootName + ' instead of ' + rootName + '().';\n }\n else {\n advice = rootName + ' resolved to a ' + (typeof rootVal) + ', not an array.';\n }\n console.warn('[STX] :for expected an array; got ' + (list === '' ? 'empty/error' : typeof list) + ' for expression \"' + listExpr + '\". ' + diagScope + ' ' + advice);\n return;\n }\n\n // Check empty state (Feature #3)\n if (list.length === 0) {\n // Dispose scopes registered by items before they leave the DOM (#1727).\n clearRenderedItems();\n if (emptyExpr) {\n const emptyContent = evalLazy(emptyExpr);\n // Held in the same slot the @for-empty template uses, so hideEmpty\n // takes it away when the list fills and a second empty render\n // replaces it instead of stacking another one. It used to go into\n // currentElements, which teardown does not walk -- it walks\n // currentGroups -- so the text stayed in the document forever: an\n // empty list that filled read \"Nothing herea\".\n hideEmpty();\n if (emptyContent && typeof emptyContent === 'string') {\n emptyElement = document.createTextNode(emptyContent);\n stxHost.insert(parent, emptyElement, placeholder);\n }\n } else if (emptyTemplate) {\n showEmpty();\n }\n return;\n }\n\n hideEmpty();\n\n // \u2500\u2500 <TransitionGroup> detection (#1742) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Active only when the list's parent is a [data-stx-transition-group]\n // AND it has already rendered once (no enter animation on first mount).\n // tgReady gates ALL animation work, so plain :for lists are untouched.\n var tgIsGroup = !!(parent && parent.hasAttribute && parent.hasAttribute('data-stx-transition-group'));\n var tgName = tgIsGroup ? (parent.getAttribute('data-stx-transition-group') || 'v') : null;\n var tgReady = tgIsGroup && !!parent.__stx_tg_init;\n var tgFirst = tgReady ? tgSnapshot(currentElements) : null;\n\n // \u2500\u2500 Key-based diffing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Build new key list\n const newKeys = list.map((item, i) => getItemKey(item, i));\n\n // Build old key \u2192 element(s) map\n const oldKeyMap = new Map();\n for (let i = 0; i < currentKeys.length; i++) {\n const k = currentKeys[i];\n if (!oldKeyMap.has(k)) oldKeyMap.set(k, []);\n oldKeyMap.get(k).push(currentGroups[i] || []);\n }\n\n // Build new element list, reusing existing DOM nodes by key\n const newElements = [];\n const newGroups = [];\n // Keys seen in THIS pass, for the duplicate warning only. Reuse is decided\n // by whether a group under the key is still unconsumed, not by whether the\n // key has been seen: gating it on the key made every duplicate occurrence\n // build a NEW group, while the removal pass below skipped the key as used\n // and left the old ones in the document. The list grew by one row on every\n // update, without bound, and the first duplicate stayed bound to a signal\n // the reconciliation never wrote to.\n const seenKeys = new Set();\n let warnedDuplicateKey = false;\n\n // Minimal-move reconciliation.\n //\n // Every reused row used to be round-tripped through a DocumentFragment,\n // and appendChild into a fragment DETACHES the node from the document\n // first. Removing a focused node blurs it and resets activeElement, so a\n // list could not contain a field the user was typing in: any write to the\n // backing array kicked them out of it, losing caret, selection and undo\n // history. It happened for every row unconditionally, including rows that\n // had not moved, and unkeyed loops took the same path because getItemKey\n // falls back to the index (#1882).\n //\n // The cursor walks the existing rendering in order. A node already at the\n // cursor is left ENTIRELY alone \u2014 an unchanged list now performs zero DOM\n // operations \u2014 and a node that genuinely has to move is moved with\n // insertBefore, which relocates it without a detach/reattach cycle.\n let cursor = null;\n for (let ci = 0; ci < currentGroups.length && !cursor; ci++) {\n const seed = liveGroupNodes(currentGroups[ci] || []);\n if (seed.length) cursor = seed[0];\n }\n\n for (let i = 0; i < list.length; i++) {\n const key = newKeys[i];\n const existing = oldKeyMap.get(key);\n\n if (seenKeys.has(key) && !warnedDuplicateKey) {\n warnedDuplicateKey = true;\n console.warn('[STX] :for has more than one item with the key ' + key + '. Rows are matched in order, so give each item a key of its own.');\n }\n seenKeys.add(key);\n\n if (existing && existing.length > 0) {\n // Reuse this item's nodes \u2014 move the whole group into position, in\n // order, so a multi-node row stays contiguous and correctly ordered.\n // A structural directive may intentionally have detached one of the\n // group's nodes. Its own placeholder owns reinsertion, so keyed reuse\n // must not resurrect that hidden node.\n const group = existing.shift();\n const liveNodes = liveGroupNodes(group);\n for (let li = 0; li < liveNodes.length; li++) {\n const groupNode = liveNodes[li];\n if (groupNode === cursor) {\n // Already exactly where it belongs. Touching it here is what\n // used to blur it, so the correct action is to do nothing.\n cursor = cursor.nextSibling;\n }\n else {\n // Moves without detaching. The cursor does not advance: this node\n // is now behind it, and the cursor still marks the next position\n // to fill.\n stxHost.insert(parent, groupNode, cursor || placeholder);\n }\n }\n newElements.push(...group);\n newGroups.push(group);\n // Update the item signal so bindings re-evaluate with new data.\n // This is the fix for #1669 \u2014 without this, reused elements show\n // stale data because the old bindings captured the old item via closure.\n const signals = group.__stx_signals;\n if (signals) {\n signals.item.set(list[i]);\n signals.index.set(i);\n }\n } else {\n // New item \u2014 create DOM elements with a fresh item signal\n const elements = createItemElements(list[i], i, key);\n elements.forEach(el => {\n // Before the cursor, not before the placeholder: a new row inserted\n // in the MIDDLE of the list must land at its own position, without\n // forcing every row after it to be moved to get back in order.\n stxHost.insert(parent, el, cursor || placeholder);\n if (tgReady && el.isConnected) tgEnter(el, tgName);\n });\n hydrateComponentScopes(elements, elements.find(function(node) {\n return node && node.__stx_for_scope;\n })?.__stx_for_scope || passedScope);\n elements.forEach(el => {\n if (el.nodeType === 1) {\n var itemScope = el.__stx_for_scope || passedScope;\n delete el.__stx_for_scope;\n // Tracked so removeGroup can dispose the row's effects (#1954). Kept\n // off __stx_disposers, which marks a hydrated component root here\n // and in the deferred :if pass.\n if (!el.__stx_disposers && el.tagName !== 'SCRIPT')\n el.__stx_effect_disposers = trackEffects(function() { processElement(el, itemScope); });\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(c => c.removeAttribute('x-cloak'));\n }\n });\n newElements.push(...elements);\n newGroups.push(elements);\n }\n }\n\n // Remove old elements whose keys are no longer in the list.\n // Dispose any scopes registered inside removed items before the\n // remove() call (#1727).\n // Whatever is still in here was not consumed above -- either the key left\n // the list, or the list now has fewer rows under that key than it did.\n // The test used to be \"this key was never used\", which could not see the\n // second case, so a duplicate key's leftover rows stayed on screen.\n for (const groups of oldKeyMap.values()) {\n if (groups.length > 0) {\n // In a transition group, run the leave animation and let it remove the\n // node; otherwise remove immediately. Scopes are disposed up-front\n // either way (their destroy hooks shouldn't wait on a CSS transition).\n groups.forEach((group) => {\n if (tgReady) {\n const liveNodes = liveGroupNodes(group);\n const transitioned = new Set();\n liveNodes.forEach((el) => {\n disposeSubtreeEffects(el);\n disposeSubtreeScopes(el);\n if (tgLeave(el, tgName)) transitioned.add(el);\n else stxHost.remove(el);\n });\n group.forEach((el) => {\n if (transitioned.has(el) || liveNodes.includes(el)) return;\n disposeSubtreeEffects(el);\n disposeSubtreeScopes(el);\n stxHost.remove(el);\n });\n }\n else {\n removeGroup(group);\n }\n });\n // The row's signals went with its group, so there is no key-indexed\n // map left to prune here.\n }\n }\n\n currentElements = newElements;\n currentGroups = newGroups;\n currentKeys = newKeys;\n\n // \u2500\u2500 <TransitionGroup> play (#1742) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // FLIP the surviving elements from their snapshotted positions, then mark\n // the group rendered so the next update animates.\n if (tgReady && tgFirst) tgFlip(newElements, tgFirst, tgName);\n if (tgIsGroup) parent.__stx_tg_init = true;\n });\n }\n";
|